From b007d141fbb383164169c779a9eca9a490a3c85d Mon Sep 17 00:00:00 2001 From: eas4ai Date: Fri, 16 Oct 2026 17:27:01 -0400 Subject: [PATCH 1/9] docs: design bounded notification sync --- ...-10-16-bounded-notification-sync-design.md | 163 ++++++++++++++++++ 1 file changed, 163 insertions(+) create mode 100644 docs/superpowers/specs/2026-10-16-bounded-notification-sync-design.md diff --git a/docs/superpowers/specs/2026-10-16-bounded-notification-sync-design.md b/docs/superpowers/specs/2026-10-16-bounded-notification-sync-design.md new file mode 100644 index 0000000000..4ffbd2e620 --- /dev/null +++ b/docs/superpowers/specs/2026-10-16-bounded-notification-sync-design.md @@ -0,0 +1,163 @@ +# Bounded Notification Inbox Synchronization Design + +## Status + +Approved approach: fixed notification head plus visible-row revalidation. + +This design replaces inbox polling whose request and response size grows with every loaded page. It is a separate change from unread-count query optimization, which is already covered by upstream pull request #264. + +## Problem + +The notification inbox polls every 30 seconds. The client sends the oldest loaded group timestamp as `through`, and the server expands the replacement page to every group at or above that timestamp. Loading more pages therefore makes each later poll perform more database work, serialize more rows, transfer a larger response, and reconcile a larger DOM-backed list. + +The current replacement does provide useful behavior: the loaded window is exact, newly active old groups move to the top, removed groups disappear, the scroll anchor is preserved, and the deepest cursor remains usable. The replacement must keep those properties where bounded data can prove them and fail safely where it cannot. + +## Goals + +- Keep every polling request and response bounded, independent of pagination depth. +- Keep the newest 20 groups exact. +- Revalidate up to 20 groups currently visible in the viewport. +- Preserve already loaded offscreen history and its existing pagination cursor. +- Prevent duplicate groups when old conversations receive new activity. +- Preserve filtering, read acknowledgement, arrival indicators, and scroll anchoring. +- Fall back to a full page-one refresh when a bounded response cannot prove continuity. + +## Non-goals + +- Do not persist notification groups or add a change-feed table. +- Do not make every offscreen historical row immediately consistent. +- Do not immediately discover an old notification that becomes relevant without a new notification event, such as a previously muted actor becoming visible again. It appears after a normal page-one refresh. +- Do not immediately discover a notification that becomes visible after a sync snapshot but sorts below that snapshot's proven boundary, such as an insert committed from a delayed transaction. It also appears after a normal page-one refresh. +- Do not rewrite the full-history grouping query. Pull request #264 addresses that cost separately. +- Do not change group identity, filter semantics, or expanded-group history. +- Do not solve the expanded-group state issue covered by upstream pull request #246. + +## HTTP Contract + +Add an authenticated, private, non-cacheable `GET /notifications/sync` endpoint. + +The request accepts: + +- `type`: the existing notification filter, defaulting to `all`. +- `visible[]`: an optional list of distinct notification group UUIDs, limited to 20. + +The JSON response is: + +```json +{ + "head": [], + "boundary": { "group_id": "uuid", "id": "uuid" }, + "visible": [], + "missing_visible_group_ids": [], + "unread_notifications_count": 0 +} +``` + +`head` contains the newest 20 current groups. The server queries 21 groups and returns the 21st representative's stable group ID and latest event ID as `boundary`. A null boundary means the head contains the complete current inbox for the selected filter. + +`visible` contains current representatives for requested visible groups that are not already present in `head`. `missing_visible_group_ids` contains requested IDs that no longer identify a current group. A changed group ID is treated as removal of the old visible row; its replacement can return through the head or a later full refresh. + +Rows in `head` and `visible` use the existing serialized `NotificationGroup` shape. That includes the representative actor and commit, up to three stacked actors, `actor.is_followed`, `event_count`, `actors_count`, and `unread_count`; existing hidden query columns remain hidden. + +The endpoint calls `UpdateNotificationsReadAt` before reading the result, matching current inbox-poll behavior. It then returns the real unread group count so activity created during the request is not incorrectly reported as read. + +## Server Design + +Add a dedicated sync controller and request object. The request validates the filter and UUID list before the query runs. Authentication comes from the existing notification route group, and every query is scoped to the current recipient. + +Extend `NotificationGroupsQuery` with bounded operations that: + +1. Read at most 21 ranked group representatives for the selected filter. +2. Load actors and commits for the 20 returned head rows. +3. Resolve at most 20 requested visible group IDs using the same grouping and filtering rules. +4. Load actors and commits for visible rows not already included in the head. +5. Compute missing requested IDs from the returned head and visible IDs. + +The grouping query still evaluates recipient history until the separate query optimization lands, but the number of selected models, related records, serialized rows, and response bytes no longer depends on loaded page count. + +The continuity proof applies to the ordered rows visible in one database snapshot. Application notification writes use the current time and a new UUIDv7, so an ordinarily committed new event sorts ahead of unchanged historical representatives. Database visibility still follows commit order rather than event timestamp order: a delayed transaction can become visible after a snapshot while sorting below its boundary. That case, and state changes that reveal an older existing event, are deliberately covered by the historical-staleness non-goals and require a page-one refresh. A stronger guarantee would require a persistent recipient mutation version or change feed, which is outside this design. + +Remove `through` from the normal list request and remove dynamic `perPage` expansion from `paginate()`. Normal page loads and infinite-scroll requests always use `NotificationGroupsQuery::PER_PAGE`. + +## Client Polling + +Replace the inbox's Inertia reload poll with the repository's existing bounded JSON polling pattern: + +- Run every 30 seconds. +- Pause while the document is hidden. +- Never overlap requests. +- Abort on unmount or filter navigation. +- Use a 10-second timeout and `cache: 'no-store'`. +- On failure, keep the last good state and retry at the next interval. + +Before each request, collect intersecting `[data-notification-group]` elements in DOM order and send at most 20 group IDs. The client records the current scroll anchor before applying a successful response. + +## Reconciliation + +Put reconciliation in a pure TypeScript function so ordering and fallback behavior can be tested without rendering the page. + +Given the loaded list and a sync response: + +1. Treat the response as complete when `boundary` is null. Use `head` as the whole list and set `next_cursor` to null. +2. Otherwise, continuity is proven when a loaded row matches both boundary fields: its stable `group_id` and latest representative event `id`. Matching only `group_id` is unsafe because new activity can bump a loaded group while retaining that ID. +3. An unchanged first page is also safe when the returned head representative pairs (`group_id` and latest event `id`) exactly match the loaded prefix. Comparing both IDs prevents a group with new activity from disguising an ambiguous burst merely because its stable `group_id` stayed in place. This avoids a false refresh when the 21st current group has never been loaded and nothing ahead of it changed. +4. If neither continuity condition holds, do not change notification data. Set a `refreshRequired` state instead. +5. For a safe response, start with the server head. +6. Append the existing loaded list after removing head duplicates and missing visible IDs. +7. Replace retained visible rows with their fresh server versions. +8. Deduplicate the final list by `group_id`, preserving the first occurrence. +9. Preserve the existing `next_cursor` unless the response is complete. + +This makes the head and visible rows exact while deliberately leaving other retained rows in their previous order. A group bumped from the retained tail into the head appears only once. + +Apply the reconciled paginator and unread count through Inertia's client-side prop replacement. The existing layout effect then restores the anchor and derives the arrival count from the anchor's new position. + +## Ambiguous Change Fallback + +When continuity cannot be proven, show a `New notifications` control without applying a partial result. Clicking it performs a normal page-one Inertia reload, resets the notification prop, clears retained history, and scrolls to the top. This prevents silent gaps after bursts or deletions that move the event boundary outside the loaded window. + +Normal bounded arrivals continue to use the existing numeric arrival control. + +## Deployment Compatibility + +The client and server ship together with a changed asset manifest. Existing Inertia version handling reloads an old page before it can continue issuing the removed `through` contract against the new application version. The new sync endpoint is additive and is used only by the new client bundle. + +No database migration or persistent backfill is required. + +## Testing + +Feature tests must prove: + +- The sync head is 20 rows and the response exposes only the 21st representative pair with at least 62 groups present. +- Payload row counts remain capped regardless of how many pages the client previously loaded. +- Requested visible groups are refreshed, head duplicates are omitted, and missing IDs return as tombstones. +- A new event moves an old group into the head without changing its `group_id`. +- Filters use the same global group identity and read acknowledgement semantics as the inbox. +- Other recipients, irrelevant notifications, invalid filters, duplicate UUIDs, and lists over 20 are rejected or excluded as appropriate. +- Unauthenticated requests are rejected, and successful responses carry `Cache-Control: private, no-store`. +- Head and visible rows preserve current serialization, actor-stack, follow-state, and hidden-field behavior. +- Activity inserted after read acknowledgement remains unread in the returned global count. +- An old Inertia asset version triggers the existing reload path instead of continuing the removed `through` contract. +- The normal paginator no longer expands from a `through` value. + +A directly discovered TypeScript unit suite must prove: + +- Safe head replacement with a retained multi-page tail. +- A bumped old group is deduplicated. +- Visible replacements and tombstones are applied. +- A null boundary clears stale tail data and the cursor. +- A known boundary preserves the existing cursor. +- An unchanged first-page representative prefix is accepted, while matching group IDs with changed representative IDs are not treated as proof of continuity. +- A mixed burst of new groups and a bumped loaded group cannot use the bumped group as a false continuity boundary. +- An unknown boundary leaves data untouched and requests a full refresh. + +Run the repository's focused tests, complete unit suite, lint, static analysis, type checks, production build, and structural change gates before submission. + +## Acceptance Criteria + +- Poll response size has a hard maximum of 20 head rows plus 20 non-head visible rows and one boundary representative pair. +- Loading additional pages does not change the sync request limit or response limit. +- The loaded list never contains duplicate `group_id` values after synchronization. +- The deepest pagination cursor remains unchanged during safe partial reconciliation. +- Within a sync snapshot, reconciliation never accepts a changed boundary representative or omits a group returned in the bounded head. +- No production behavior outside notification synchronization changes. From b5c9228a38f3b51658bcf25b86e47b5949fa752e Mon Sep 17 00:00:00 2001 From: eas4ai Date: Fri, 16 Oct 2026 18:06:04 -0400 Subject: [PATCH 2/9] docs: plan bounded notification sync --- .../2026-10-16-bounded-notification-sync.md | 1677 +++++++++++++++++ ...-10-16-bounded-notification-sync-design.md | 14 +- 2 files changed, 1687 insertions(+), 4 deletions(-) create mode 100644 docs/superpowers/plans/2026-10-16-bounded-notification-sync.md diff --git a/docs/superpowers/plans/2026-10-16-bounded-notification-sync.md b/docs/superpowers/plans/2026-10-16-bounded-notification-sync.md new file mode 100644 index 0000000000..f0d6117d6c --- /dev/null +++ b/docs/superpowers/plans/2026-10-16-bounded-notification-sync.md @@ -0,0 +1,1677 @@ +# Bounded Notification Sync Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Replace depth-dependent notification inbox polling with a fixed-size, authenticated sync response that safely reconciles the loaded list or requests a full refresh. + +**Architecture:** Laravel exposes a private JSON endpoint backed by one bounded representative query while the normal inbox paginator returns exactly 20 rows. A pure TypeScript reconciler proves continuity with `(group_id, id)` representative pairs; the React page polls the endpoint every 30 seconds and applies only safe responses. + +**Tech Stack:** PHP 8.5, Laravel 13, PostgreSQL/SQLite, Pest 5, React 19, Inertia 3, TypeScript 7, Node test runner, Bun, Wayfinder, Vite Plus. + +**Spec:** [`docs/superpowers/specs/2026-10-16-bounded-notification-sync-design.md`](../specs/2026-10-16-bounded-notification-sync-design.md) + +## Global Constraints + +- Keep `GET /notifications/sync` inside the existing `auth` route group and return `Cache-Control: private, no-store`. +- Accept the existing `type` filter and at most 20 distinct UUID values in `visible[]`. +- Query 21 representatives, return 20 in `head`, and expose only `{ group_id, id }` for the 21st `boundary`. +- Select head, boundary, and requested visible representative identities in one SQL statement so PostgreSQL `READ COMMITTED` cannot mix snapshots. +- Return at most 20 head rows plus 20 non-head visible rows; loaded pagination depth must never alter either bound. +- Preserve existing `NotificationGroup` serialization, filtering, global group identity, stacked actors, follow state, and read acknowledgement. +- Compare both `group_id` and representative `id`; stable group identity alone is not continuity proof. +- Keep the deepest cursor for safe partial reconciliation and clear it only when `boundary` is `null`. +- Reconcile inside one functional Inertia page-prop replacement so a page merged by `InfiniteScroll` after render but before application cannot be overwritten by stale React props. +- When a complete response meets an active Inertia next-page token, use a server-backed page-one reset; replacing the paginator prop alone does not clear InfiniteScroll's separate cursor state. +- Poll every 30 seconds, pause in hidden tabs, prohibit overlap, abort navigation/unmount requests, and time out after 10 seconds. +- Keep ambiguous, offscreen, relevance-only, and delayed-transaction changes behind the explicit page-one refresh fallback described by the spec. +- Do not add a migration, dependency, persistent group projection, or full-history query rewrite; upstream PR #264 owns the latter optimization. +- Do not change `package.json` or test discovery; PR #300 separately owns React/TSX test discovery. +- Generated Wayfinder files under `resources/js/actions`, `resources/js/routes`, and `resources/js/wayfinder` remain ignored and uncommitted. +- Before implementation checks, provision the locked dependencies and PHP 8.5. The current host default is PHP 8.4 and this worktree has no `vendor` or `node_modules`; local PHP results under 8.4 are supplemental, and the PHP 8.5 CI gate is authoritative. + +## Review Focus + +- A boundary or prefix row with a stable `group_id` but changed representative `id` must not prove continuity; Task 4 pins this with prefix and mixed-burst regression tests. +- A requested visible UUID belonging to another recipient or an irrelevant row must return no model data; Tasks 1 and 2 pin this as a tombstone/privacy case. +- Invalid, duplicate, associative, or over-limit `visible` input must fail before acknowledgement; Task 2 verifies `read_at` remains null. +- Activity inserted after acknowledgement must remain unread in the returned global count; Task 2 inserts it from a guarded query listener. +- A requested tail group changed after representative selection must not leak a newer representative into an older head snapshot; Task 1 pins the single-statement boundary. +- A complete response (`boundary: null`) must remove stale retained history and clear the cursor; Task 4 tests both effects. +- A complete response with an active next-page token must reset Inertia's server scroll metadata before the list is replaced; Tasks 4 and 5 pin this path. +- A page appended while a poll response waits in Inertia's client queue must remain present with its newer deepest cursor; Tasks 4 and 5 require reconciliation against the updater's current props. + +## File Map + +- Create `app/Http/Controllers/NotificationSyncController.php`: thin JSON adapter for acknowledgement, query results, unread count, and cache headers. +- Create `app/Http/Requests/ListNotificationSyncRequest.php`: validates `type` and the bounded visible UUID list. +- Modify `app/Queries/NotificationGroupsQuery.php`: adds bounded synchronization, shared representative ordering, and batched relation loading; removes dynamic page expansion. +- Modify `app/Http/Controllers/NotificationController.php`: removes the retired `through` argument. +- Modify `app/Http/Requests/ListNotificationsRequest.php`: removes `through` validation and parsing. +- Modify `routes/web.php`: registers the authenticated sync route. +- Modify `tests/Unit/Queries/NotificationGroupsQueryTest.php`: proves bounded query shape, tombstones, serialization relations, and group bumps. +- Create `tests/Feature/Controllers/NotificationSyncControllerTest.php`: proves the HTTP, security, validation, caching, filtering, and acknowledgement contract. +- Modify `tests/Feature/NotificationInboxTest.php`: replaces obsolete expanding-poll assertions with fixed pagination, scroll-reset metadata, and stale-client reload coverage. +- Modify `resources/js/types/notification.ts`: defines the sync response contract. +- Create `resources/js/lib/notification-sync.ts`: owns visibility selection and pure reconciliation. +- Create `tests/Unit/NotificationSync.test.ts`: exercises every continuity and merge branch through the current `*.test.ts` runner. +- Modify `resources/js/pages/notification/index.tsx`: replaces Inertia reload polling with bounded JSON polling and the fallback control. + +--- + +### Task 1: Build the bounded server query + +**Files:** +- Modify: `app/Queries/NotificationGroupsQuery.php:16-164` +- Modify: `tests/Unit/Queries/NotificationGroupsQueryTest.php:1-247` + +**Interfaces:** +- Consumes: existing `events(User $user, string $type): NotificationBuilder`, `PER_PAGE = 20`, and `loadStackedActors()` semantics. +- Produces: `sync(User $user, string $type = 'all', array $visibleGroupIds = []): array{head: list, boundary: array{group_id: string, id: string}|null, visible: list, missing_visible_group_ids: list}`. +- Produces: private `groupRepresentatives(User $user, string $type): NotificationBuilder` and `loadGroupRelations(User $user, string $type, array $groups): void` for Task 3 reuse. +- Guarantees: one representative SELECT returns positions 1–21 plus requested visible group IDs; relation queries may follow, but representative identity cannot cross statement snapshots. + +- [ ] **Step 1: Add the failing bounded-window query test** + +Add `CommitStatus` and `QueryExecuted` to the imports and append this test: + +```php +it('builds a bounded sync head with visible refreshes and ordered tombstones', function (): void { + $user = User::factory()->create(); + $groups = collect(range(1, 62))->map(fn (int $minutes): Notification => Notification::factory() + ->for($user, 'recipient') + ->replied() + ->create(['created_at' => now()->subMinutes($minutes)])); + $visible = $groups[30]; + $hidden = $groups[40]; + $hidden->commit->update(['status' => CommitStatus::Pending]); + $other = Notification::factory()->replied()->create(); + + DB::flushQueryLog(); + DB::enableQueryLog(); + + $sync = resolve(NotificationGroupsQuery::class)->sync($user, visibleGroupIds: [ + $groups[0]->id, + $groups[20]->id, + $visible->id, + $hidden->id, + $other->id, + ]); + + expect($sync['head'])->toHaveCount(NotificationGroupsQuery::PER_PAGE) + ->and(array_map(fn (Notification $group): string => $group->id, $sync['head'])) + ->toBe($groups->take(20)->pluck('id')->all()) + ->and($sync['boundary'])->toBe([ + 'group_id' => $groups[20]->id, + 'id' => $groups[20]->id, + ]) + ->and(array_map(fn (Notification $group): string => $group->group_id, $sync['visible'])) + ->toBe([$groups[20]->id, $visible->id]) + ->and($sync['missing_visible_group_ids'])->toBe([$hidden->id, $other->id]) + ->and($sync['head'][0]->relationLoaded('actor'))->toBeTrue() + ->and($sync['head'][0]->relationLoaded('commit'))->toBeTrue() + ->and($sync['head'][0]->relationLoaded('actors'))->toBeTrue() + ->and(DB::getQueryLog())->toHaveCount(3); +}); +``` + +- [ ] **Step 2: Add failing completion and stable-group bump tests** + +```php +it('uses a null sync boundary when the head contains the complete inbox', function (int $count): void { + $user = User::factory()->create(); + Notification::factory()->for($user, 'recipient')->count($count)->replied()->create(); + + $sync = resolve(NotificationGroupsQuery::class)->sync($user); + + expect($sync['head'])->toHaveCount($count) + ->and($sync['boundary'])->toBeNull() + ->and($sync['visible'])->toBe([]) + ->and($sync['missing_visible_group_ids'])->toBe([]); +})->with([0, 1, NotificationGroupsQuery::PER_PAGE]); + +it('moves an active old group into the sync head without changing its group id', function (): void { + $user = User::factory()->create(); + $root = Commit::factory()->for($user)->create(); + $oldReply = Commit::factory()->for($root, 'parent')->create(); + $old = Notification::factory()->for($user, 'recipient')->for($oldReply, 'commit')->create([ + 'type' => NotificationType::Replied, + 'created_at' => now()->subHour(), + ]); + Notification::factory()->for($user, 'recipient')->count(20)->replied()->create([ + 'created_at' => now()->subMinutes(30), + ]); + $latestReply = Commit::factory()->for($root, 'parent')->create(); + $latest = Notification::factory()->for($user, 'recipient')->for($latestReply, 'commit')->create([ + 'type' => NotificationType::Replied, + ]); + + $sync = resolve(NotificationGroupsQuery::class)->sync($user); + + expect($sync['head'][0]->id)->toBe($latest->id) + ->and($sync['head'][0]->group_id)->toBe($old->id) + ->and($sync['head'][0]->event_count)->toBe(2); +}); + +it('selects head boundary and visible representatives from one statement snapshot', function (): void { + $user = User::factory()->create(); + $root = Commit::factory()->for($user)->create(); + $oldReply = Commit::factory()->for($root, 'parent')->create(); + $old = Notification::factory()->for($user, 'recipient')->for($oldReply, 'commit')->create([ + 'type' => NotificationType::Replied, + 'created_at' => now()->subMinutes(50), + 'read_at' => now(), + ]); + Notification::factory()->for($user, 'recipient')->count(21)->replied()->read()->create([ + 'created_at' => now()->subMinutes(30), + ]); + $inserted = false; + /** @var Notification|null $late */ + $late = null; + + DB::listen(function (QueryExecuted $event) use ($user, $root, &$inserted, &$late): void { + if ($inserted || ! str_starts_with(strtolower(ltrim($event->sql)), 'select')) { + return; + } + + $inserted = true; + $reply = Commit::factory()->for($root, 'parent')->create(); + $late = Notification::factory()->for($user, 'recipient')->for($reply, 'commit')->create([ + 'type' => NotificationType::Replied, + ]); + }); + + $query = resolve(NotificationGroupsQuery::class); + $sync = $query->sync($user, visibleGroupIds: [$old->id]); + + expect($late)->toBeInstanceOf(Notification::class); + assert($late instanceof Notification); + expect($sync['visible'])->toHaveCount(1) + ->and($sync['visible'][0]->id)->toBe($old->id) + ->and(collect($sync['head'])->pluck('id'))->not->toContain($late->id) + ->and($query->unreadCount($user))->toBe(1); +}); +``` + +- [ ] **Step 3: Run the focused query tests and confirm the new contract is absent** + +Run: + +```bash +php -d memory_limit=-1 vendor/bin/pest tests/Unit/Queries/NotificationGroupsQueryTest.php +``` + +Expected: FAIL because `NotificationGroupsQuery::sync()` is undefined. + +- [ ] **Step 4: Add the representative and relation-loading seams** + +Refactor `paginate()` to use these private methods without changing its current behavior yet: + +```php +private function groupRepresentatives(User $user, string $type): NotificationBuilder +{ + return $this->events($user, $type) + ->where('group_rank', 1) + ->latest() + ->latest('id'); +} + +/** @param list $groups */ +private function loadGroupRelations(User $user, string $type, array $groups): void +{ + (new Collection($groups))->load([ + 'actor' => fn (BelongsTo $query): BelongsTo => $query + ->withExists(['followers as is_followed' => fn (Builder $query): Builder => $query->whereKey($user->id)]), + 'commit', + ]); + + $this->loadStackedActors($user, $type, $groups); +} +``` + +- [ ] **Step 5: Implement the bounded synchronization method** + +```php +/** + * @param list $visibleGroupIds + * @return array{ + * head: list, + * boundary: array{group_id: string, id: string}|null, + * visible: list, + * missing_visible_group_ids: list + * } + */ +public function sync(User $user, string $type = 'all', array $visibleGroupIds = []): array +{ + $visibleGroupIds = array_slice($visibleGroupIds, 0, self::PER_PAGE); + $ranked = $this->groupRepresentatives($user, $type) + ->reorder() + ->select('notifications.*') + ->selectRaw('ROW_NUMBER() OVER (ORDER BY created_at DESC, id DESC) AS sync_position'); + $groups = Notification::query() + ->fromSub($ranked, 'notifications') + ->where(fn (NotificationBuilder $query): NotificationBuilder => $query + ->where('sync_position', '<=', self::PER_PAGE + 1) + ->when( + $visibleGroupIds !== [], + fn (NotificationBuilder $query): NotificationBuilder => $query + ->orWhereIn('group_id', $visibleGroupIds), + )) + ->withCasts([ + 'event_count' => 'integer', + 'sync_position' => 'integer', + ]) + ->orderBy('sync_position') + ->get(); + $headWithBoundary = $groups->take(self::PER_PAGE + 1)->values(); + $boundary = $headWithBoundary->count() > self::PER_PAGE + ? $headWithBoundary->pop() + : null; + $head = $headWithBoundary->values()->all(); + $headIds = collect($head)->pluck('group_id'); + $requestedVisibleIds = collect($visibleGroupIds)->diff($headIds)->values(); + $visible = $groups->whereIn('group_id', $requestedVisibleIds)->values()->all(); + + $this->loadGroupRelations($user, $type, [...$head, ...$visible]); + + foreach ([...$head, ...$visible] as $group) { + $group->makeHidden('sync_position'); + } + + $foundIds = $headIds->merge(array_map( + fn (Notification $group): string => $group->group_id, + $visible, + )); + + return [ + 'head' => $head, + 'boundary' => $boundary instanceof Notification ? [ + 'group_id' => $boundary->group_id, + 'id' => $boundary->id, + ] : null, + 'visible' => $visible, + 'missing_visible_group_ids' => collect($visibleGroupIds) + ->diff($foundIds) + ->values() + ->all(), + ]; +} +``` + +- [ ] **Step 6: Run the query suite and structural check** + +Run: + +```bash +php -d memory_limit=-1 vendor/bin/pest tests/Unit/Queries/NotificationGroupsQueryTest.php +/home/shawn/.local/bin/ripwire . --edit-check=NotificationGroupsQuery +``` + +Expected: all query tests pass, including the existing constant-query-count cases; Ripwire reports no blocking regression. + +- [ ] **Step 7: Commit the bounded query** + +```bash +git add app/Queries/NotificationGroupsQuery.php tests/Unit/Queries/NotificationGroupsQueryTest.php +git commit -m "feat: add bounded notification sync query" +``` + +--- + +### Task 2: Expose the authenticated sync contract + +**Files:** +- Create: `app/Http/Requests/ListNotificationSyncRequest.php` +- Create: `app/Http/Controllers/NotificationSyncController.php` +- Create: `tests/Feature/Controllers/NotificationSyncControllerTest.php` +- Modify: `routes/web.php:5-55,215-217` + +**Interfaces:** +- Consumes: Task 1 `NotificationGroupsQuery::sync()` and existing `UpdateNotificationsReadAt::handle(User): CarbonImmutable`. +- Produces: Wayfinder action `NotificationSyncController.index()` and route name `notification-sync.index`. +- Produces JSON keys: `head`, `boundary`, `visible`, `missing_visible_group_ids`, and `unread_notifications_count`. + +- [ ] **Step 1: Add failing authentication, validation, and payload-bound tests** + +Create the controller test with these imports and cases: + +```php +getJson(route('notification-sync.index'))->assertUnauthorized(); +}); + +it('returns a private bounded sync payload with the existing group shape', function (): void { + $user = User::factory()->create(); + $groups = collect(range(1, 62))->map(fn (int $minutes): Notification => Notification::factory() + ->for($user, 'recipient') + ->replied() + ->create(['created_at' => now()->subMinutes($minutes)])); + $visibleIds = $groups->slice(21, 20)->pluck('id')->all(); + + $response = $this->actingAs($user)->getJson(route('notification-sync.index', [ + 'visible' => $visibleIds, + ]))->assertOk()->assertHeader('Cache-Control', 'no-store, private'); + + $response->assertJsonCount(20, 'head') + ->assertExactJsonPath('boundary', [ + 'group_id' => $groups[20]->id, + 'id' => $groups[20]->id, + ]) + ->assertJsonCount(20, 'visible') + ->assertExactJsonPath('missing_visible_group_ids', []) + ->assertJsonPath('unread_notifications_count', 0) + ->assertJsonPath('head.0.event_count', 1) + ->assertJsonPath('head.0.actors_count', 1) + ->assertJsonPath('head.0.unread_count', 0) + ->assertJsonStructure([ + 'head' => [['actor' => ['is_followed'], 'actors', 'commit']], + 'visible' => [['actor' => ['is_followed'], 'actors', 'commit']], + ]) + ->assertJsonMissingPath('head.0.key') + ->assertJsonMissingPath('head.0.group_rank') + ->assertJsonMissingPath('head.0.actor_position') + ->assertJsonMissingPath('head.0.sync_position') + ->assertJsonMissingPath('visible.0.key') + ->assertJsonMissingPath('visible.0.group_rank') + ->assertJsonMissingPath('visible.0.actor_position') + ->assertJsonMissingPath('visible.0.sync_position'); + + expect(array_keys($response->json()))->toBe([ + 'head', + 'boundary', + 'visible', + 'missing_visible_group_ids', + 'unread_notifications_count', + ]); +}); + +it('rejects invalid sync input before acknowledging notifications', function (array $query, string $field): void { + $user = User::factory()->create(); + $notification = Notification::factory()->for($user, 'recipient')->create(); + + $this->actingAs($user) + ->getJson(route('notification-sync.index', $query)) + ->assertUnprocessable() + ->assertJsonValidationErrors($field); + + expect($notification->refresh()->read_at)->toBeNull(); +})->with([ + 'invalid filter' => fn (): array => [['type' => 'secret'], 'type'], + 'scalar visible value' => fn (): array => [['visible' => (string) Str::uuid()], 'visible'], + 'associative visible value' => fn (): array => [['visible' => ['group' => (string) Str::uuid()]], 'visible'], + 'invalid visible uuid' => fn (): array => [['visible' => ['invalid']], 'visible.0'], + 'duplicate visible uuid' => function (): array { + $id = (string) Str::uuid(); + + return [['visible' => [$id, $id]], 'visible.1']; + }, + 'twenty one visible uuids' => fn (): array => [[ + 'visible' => collect(range(1, 21))->map(fn (): string => (string) Str::uuid())->all(), + ], 'visible'], +]); +``` + +- [ ] **Step 2: Add failing filter, privacy, acknowledgement, and race tests** + +Append: + +```php +it('keeps global group identity while acknowledging all relevant activity', function (): void { + $user = User::factory()->create(); + $root = Commit::factory()->for($user)->create(); + $oldReply = Commit::factory()->for($root, 'parent')->create(); + $old = Notification::factory()->for($user, 'recipient')->for($oldReply, 'commit')->create([ + 'type' => NotificationType::Replied, + 'created_at' => now()->subMinutes(40), + ]); + $latestReply = Commit::factory()->for($root, 'parent')->create(); + $latest = Notification::factory()->for($user, 'recipient')->for($latestReply, 'commit')->create([ + 'type' => NotificationType::Replied, + ]); + $follow = Notification::factory()->for($user, 'recipient')->create(); + $hidden = Notification::factory()->for($user, 'recipient')->replied()->create(); + $hidden->commit->update(['status' => CommitStatus::Pending]); + $other = Notification::factory()->create(); + + $this->actingAs($user)->getJson(route('notification-sync.index', [ + 'type' => 'replies', + 'visible' => [$old->id, $hidden->id, $other->id], + ]))->assertOk() + ->assertJsonPath('head.0.id', $latest->id) + ->assertJsonPath('head.0.group_id', $old->id) + ->assertJsonPath('head.0.event_count', 2) + ->assertExactJsonPath('visible', []) + ->assertExactJsonPath('missing_visible_group_ids', [$hidden->id, $other->id]); + + expect($latest->refresh()->read_at)->not->toBeNull() + ->and($follow->refresh()->read_at)->not->toBeNull() + ->and($hidden->refresh()->read_at)->toBeNull() + ->and($other->refresh()->read_at)->toBeNull(); +}); + +it('serializes a requested non-head group with its actor stack and follow state', function (): void { + $user = User::factory()->create(); + $commit = Commit::factory()->for($user)->create(); + $stargazers = User::factory()->count(4)->create(); + $stars = $stargazers->map(fn (User $stargazer, int $index): Notification => Notification::factory() + ->for($user, 'recipient') + ->for($stargazer, 'actor') + ->starred($commit) + ->create(['created_at' => now()->subMinutes(80 - $index)])); + $user->following()->attach($stargazers[3]); + Notification::factory()->for($user, 'recipient')->count(21)->replied()->create([ + 'created_at' => now()->subMinutes(30), + ]); + + $this->actingAs($user)->getJson(route('notification-sync.index', [ + 'visible' => [$stars[0]->id], + ]))->assertOk() + ->assertJsonCount(1, 'visible') + ->assertJsonPath('visible.0.id', $stars[3]->id) + ->assertJsonPath('visible.0.group_id', $stars[0]->id) + ->assertJsonPath('visible.0.actor.id', $stargazers[3]->id) + ->assertJsonPath('visible.0.actor.is_followed', true) + ->assertJsonPath('visible.0.commit.id', $commit->id) + ->assertJsonPath('visible.0.event_count', 4) + ->assertJsonPath('visible.0.actors_count', 4) + ->assertJsonPath('visible.0.unread_count', 0) + ->assertJsonCount(3, 'visible.0.actors') + ->assertJsonPath('visible.0.actors.0.id', $stargazers[3]->id) + ->assertJsonMissingPath('visible.0.actor.email') + ->assertJsonMissingPath('visible.0.actors.0.email') + ->assertJsonMissingPath('visible.0.sync_position'); +}); + +it('reports activity committed after acknowledgement as unread', function (): void { + $user = User::factory()->create(); + Notification::factory()->for($user, 'recipient')->create(); + $inserted = false; + /** @var Notification|null $late */ + $late = null; + + DB::listen(function (QueryExecuted $query) use ($user, &$inserted, &$late): void { + if ($inserted || ! Str::startsWith(Str::lower($query->sql), 'update') || ! Str::contains($query->sql, 'notifications')) { + return; + } + + $inserted = true; + $late = Notification::factory()->for($user, 'recipient')->create(); + }); + + $this->actingAs($user) + ->getJson(route('notification-sync.index')) + ->assertOk() + ->assertJsonPath('unread_notifications_count', 1); + + expect($late)->toBeInstanceOf(Notification::class); + assert($late instanceof Notification); + expect($late->refresh()->read_at)->toBeNull(); +}); +``` + +- [ ] **Step 3: Run the controller test and verify it fails at the missing route** + +Run: + +```bash +php -d memory_limit=-1 vendor/bin/pest tests/Feature/Controllers/NotificationSyncControllerTest.php +``` + +Expected: FAIL because `notification-sync.index` is undefined. + +- [ ] **Step 4: Implement the dedicated Form Request** + +```php +> */ + public function rules(): array + { + return [ + 'type' => ['nullable', 'in:all,replies,quotes,stars,mentions,follows,moderation'], + 'visible' => ['sometimes', 'array', 'list', 'max:20'], + 'visible.*' => ['required', 'uuid', 'distinct'], + ]; + } + + public function type(): string + { + return $this->filled('type') ? $this->string('type')->value() : 'all'; + } + + /** @return list */ + public function visible(): array + { + /** @var list $visible */ + $visible = $this->validated('visible', []); + + return $visible; + } +} +``` + +- [ ] **Step 5: Implement the thin controller and authenticated route** + +```php +handle($user); + + return response()->json([ + ...$query->sync($user, $request->type(), $request->visible()), + 'unread_notifications_count' => $query->unreadCount($user), + ])->header('Cache-Control', 'private, no-store'); + } +} +``` + +Add the controller import beside the existing notification controller imports: + +```php +use App\Http\Controllers\NotificationSyncController; +``` + +Then register the route inside the existing authenticated group, before the group-history route: + +```php +Route::get('notifications/sync', [NotificationSyncController::class, 'index']) + ->name('notification-sync.index'); +Route::get('notifications', [NotificationController::class, 'index']) + ->name('notification.index'); +Route::get('notifications/{notification}/group', [NotificationGroupController::class, 'show']) + ->name('notification-group.show'); +``` + +- [ ] **Step 6: Run endpoint tests, route inspection, and Wayfinder generation** + +Run: + +```bash +php -d memory_limit=-1 vendor/bin/pest tests/Feature/Controllers/NotificationSyncControllerTest.php +php artisan route:list --name=notification-sync +php artisan wayfinder:generate --with-form +git status --short +``` + +Expected: controller tests pass; route output contains authenticated `notifications/sync`; generated ignored files do not appear in Git status. + +- [ ] **Step 7: Commit the HTTP contract** + +```bash +git add app/Http/Controllers/NotificationSyncController.php app/Http/Requests/ListNotificationSyncRequest.php routes/web.php tests/Feature/Controllers/NotificationSyncControllerTest.php +git commit -m "feat: expose bounded notification sync" +``` + +--- + +### Task 3: Retire depth-dependent inbox pagination + +**Files:** +- Modify: `app/Http/Requests/ListNotificationsRequest.php:7-34` +- Modify: `app/Http/Controllers/NotificationController.php:18-25` +- Modify: `app/Queries/NotificationGroupsQuery.php:21-39` +- Modify: `tests/Feature/NotificationInboxTest.php:33-104` + +**Interfaces:** +- Consumes: Task 1 `groupRepresentatives()` and `loadGroupRelations()`. +- Produces: `paginate(User $user, string $type = 'all'): CursorPaginator`, always using `PER_PAGE` and preserving only the `type` query parameter. + +- [ ] **Step 1: Replace expanding-poll tests with fixed-page, scroll-reset, and stale-client tests** + +Delete the three obsolete polling tests at the top of `NotificationInboxTest.php` and add: + +```php +it('keeps a legacy inbox refresh query to one fixed page', function (): void { + $user = User::factory()->create(); + $notices = collect(range(1, 62))->map(fn (int $minutes): Notification => Notification::factory() + ->for($user, 'recipient') + ->replied() + ->create(['created_at' => now()->subMinutes($minutes)])); + + $this->actingAs($user) + ->get(route('notification.index', ['through' => $notices[39]->created_at->toJSON()])) + ->assertOk() + ->assertInertia(fn ($page) => $page + ->has('notifications.data', NotificationGroupsQuery::PER_PAGE) + ->where('notifications.data.0.id', $notices[0]->id) + ->where('notifications.next_page_url', fn (string $url): bool => ! str_contains($url, 'through'))); +}); + +it('marks an explicit page-one inbox visit as an infinite-scroll reset', function (): void { + $user = User::factory()->create(); + Notification::factory()->for($user, 'recipient')->count(21)->replied()->create(); + + $this->actingAs($user)->withHeaders([ + 'X-Inertia' => 'true', + 'X-Inertia-Version' => (string) new HandleInertiaRequests()->version(request()), + 'X-Inertia-Partial-Component' => 'notification/index', + 'X-Inertia-Partial-Data' => 'notifications,filters,readAt,auth', + 'X-Inertia-Reset' => 'notifications', + ])->get(route('notification.index'))->assertOk() + ->assertJsonCount(NotificationGroupsQuery::PER_PAGE, 'props.notifications.data') + ->assertJsonPath('scrollProps.notifications.reset', true); +}); + +it('forces a stale notification client to reload before it can reuse the retired poll contract', function (): void { + $user = User::factory()->create(); + $notification = Notification::factory()->for($user, 'recipient')->create(); + $url = route('notification.index', ['through' => $notification->created_at->toJSON()]); + + $this->actingAs($user)->withHeaders([ + 'X-Inertia' => 'true', + 'X-Inertia-Version' => 'stale-notification-client', + ])->get($url) + ->assertStatus(409) + ->assertHeader('X-Inertia-Location', $url); +}); +``` + +- [ ] **Step 2: Run the inbox test and confirm the fixed-page assertion fails** + +Run: + +```bash +php -d memory_limit=-1 vendor/bin/pest tests/Feature/NotificationInboxTest.php +``` + +Expected: FAIL because the current `through` branch expands the first response to 40 rows. + +- [ ] **Step 3: Remove `through` from request parsing and controller dispatch** + +Make `ListNotificationsRequest::rules()` return only the `type` rule, delete the `CarbonImmutable` import and `through()` method, and change the controller callback to: + +```php +'notifications' => Inertia::scroll( + fn (): CursorPaginator => $query->paginate($user, $request->type()), +)->matchOn('data.group_id'), +``` + +- [ ] **Step 4: Make pagination fixed and retain only the filter query parameter** + +Replace `paginate()` with: + +```php +/** @return CursorPaginator */ +public function paginate(User $user, string $type = 'all'): CursorPaginator +{ + $groups = $this->groupRepresentatives($user, $type) + ->cursorPaginate(self::PER_PAGE) + ->appends(request()->only('type')); + + $this->loadGroupRelations($user, $type, $groups->items()); + + return $groups; +} +``` + +- [ ] **Step 5: Run all server-focused tests and static checks** + +Run: + +```bash +php -d memory_limit=-1 vendor/bin/pest tests/Unit/Queries/NotificationGroupsQueryTest.php tests/Feature/Controllers/NotificationSyncControllerTest.php tests/Feature/NotificationInboxTest.php +composer test:types +composer test:type-coverage +``` + +Expected: all focused tests, PHPStan, and 100% type coverage pass. + +- [ ] **Step 6: Commit the retired poll contract** + +```bash +git add app/Http/Controllers/NotificationController.php app/Http/Requests/ListNotificationsRequest.php app/Queries/NotificationGroupsQuery.php tests/Feature/NotificationInboxTest.php +git commit -m "fix: keep notification pagination bounded" +``` + +--- + +### Task 4: Implement and test pure client reconciliation + +**Files:** +- Modify: `resources/js/types/notification.ts:4-42` +- Create: `resources/js/lib/notification-sync.ts` +- Create: `tests/Unit/NotificationSync.test.ts` + +**Interfaces:** +- Consumes: existing `CursorPaginated` and server keys from Task 2. +- Produces: `NotificationSyncResponse` and `NotificationSyncRepresentative` types. +- Produces: `reconcileNotificationSync(current, sync): { notifications, refreshRequired, paginationResetRequired }`. +- Produces: `visibleNotificationGroupIds(elements, headerBottom, viewport): string[]`, capped at 20 in DOM order. + +- [ ] **Step 1: Add the failing reconciliation suite** + +Create `tests/Unit/NotificationSync.test.ts`: + +```ts +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { + reconcileNotificationSync, + visibleNotificationGroupIds, +} from '../../resources/js/lib/notification-sync.ts'; +import type { + CursorPaginated, + NotificationGroup, + NotificationSyncResponse, +} from '../../resources/js/types/index.ts'; + +const group = (groupId: string, id = groupId): NotificationGroup => + ({ group_id: groupId, id }) as NotificationGroup; + +const sequence = (prefix: string, count: number): NotificationGroup[] => + Array.from({ length: count }, (_, index) => group(`${prefix}${index + 1}`)); + +const page = ( + data: NotificationGroup[], + nextCursor: string | null = 'deep-cursor', +): CursorPaginated => ({ + data, + next_cursor: nextCursor, + prev_cursor: null, +}); + +const response = ( + values: Partial, +): NotificationSyncResponse => ({ + head: [], + boundary: null, + visible: [], + missing_visible_group_ids: [], + unread_notifications_count: 0, + ...values, +}); + +void test('replaces a twenty-row head and retains the loaded tail and cursor', () => { + const loaded = sequence('A', 59); + const head = [group('X'), ...loaded.slice(0, 19)]; + const result = reconcileNotificationSync( + page(loaded), + response({ head, boundary: group('A20') }), + ); + + assert.equal(result.refreshRequired, false); + assert.deepEqual( + result.notifications.data.map(({ group_id }) => group_id), + ['X', ...loaded.map(({ group_id }) => group_id)], + ); + assert.equal(result.notifications.data.length, 60); + assert.equal(result.notifications.next_cursor, 'deep-cursor'); +}); + +void test('preserves a page merged after the poll request started', () => { + const atRequestStart = sequence('A', 20); + const currentAtApply = page( + [...atRequestStart, ...sequence('merged-', 20)], + 'new-deep-cursor', + ); + const head = [group('X'), ...atRequestStart.slice(0, 19)]; + const result = reconcileNotificationSync( + currentAtApply, + response({ head, boundary: group('A20') }), + ); + + assert.equal(result.refreshRequired, false); + assert.equal(result.paginationResetRequired, false); + assert.equal(result.notifications.data.length, 41); + assert.equal(result.notifications.data.at(-1)?.group_id, 'merged-20'); + assert.equal(result.notifications.next_cursor, 'new-deep-cursor'); +}); + +void test('deduplicates a bumped old group by stable group id', () => { + const loaded = sequence('A', 30); + const bumped = group('A30', 'A30:new'); + const result = reconcileNotificationSync( + page(loaded), + response({ + head: [bumped, ...loaded.slice(0, 19)], + boundary: group('A20'), + }), + ); + + assert.equal(result.refreshRequired, false); + assert.equal(result.notifications.data[0], bumped); + assert.equal( + result.notifications.data.filter(({ group_id }) => group_id === 'A30') + .length, + 1, + ); +}); + +void test('applies visible replacements and missing-row tombstones', () => { + const head = sequence('A', 20); + const current = page([...head, group('A21'), group('visible'), group('missing')]); + const replacement = group('visible', 'visible:new'); + const result = reconcileNotificationSync( + current, + response({ + head, + boundary: group('A21'), + visible: [replacement], + missing_visible_group_ids: ['missing'], + }), + ); + + assert.equal(result.refreshRequired, false); + assert.equal( + result.notifications.data.find(({ group_id }) => group_id === 'visible'), + replacement, + ); + assert.equal( + result.notifications.data.some(({ group_id }) => group_id === 'missing'), + false, + ); +}); + +void test('treats a null boundary as complete and clears retained history and cursor', () => { + const head = sequence('A', 4); + const result = reconcileNotificationSync( + page([...head, ...sequence('stale', 5)]), + response({ head }), + ); + + assert.equal(result.refreshRequired, false); + assert.equal(result.paginationResetRequired, true); + assert.deepEqual(result.notifications.data, head); + assert.equal(result.notifications.next_cursor, null); +}); + +void test('updates a complete paginator locally when its cursor is already exhausted', () => { + const head = sequence('A', 4); + const result = reconcileNotificationSync( + page([...head, ...sequence('stale', 5)], null), + response({ head }), + ); + + assert.equal(result.refreshRequired, false); + assert.equal(result.paginationResetRequired, false); + assert.deepEqual(result.notifications.data, head); + assert.equal(result.notifications.next_cursor, null); +}); + +void test('accepts an unchanged representative prefix with an unloaded boundary', () => { + const head = sequence('A', 20); + const result = reconcileNotificationSync( + page(head), + response({ head: [...head], boundary: group('A21') }), + ); + + assert.equal(result.refreshRequired, false); + assert.equal(result.notifications.next_cursor, 'deep-cursor'); +}); + +void test('rejects a matching group-id prefix when a representative id changed', () => { + const loaded = sequence('A', 20); + const changed = [group('A1', 'A1:new'), ...loaded.slice(1)]; + const result = reconcileNotificationSync( + page(loaded), + response({ head: changed, boundary: group('A21') }), + ); + + assert.equal(result.refreshRequired, true); + assert.equal(result.notifications.data, loaded); +}); + +void test('rejects a mixed burst whose stable boundary group has a new representative', () => { + const current = page(sequence('A', 40)); + const burst = Array.from({ length: 20 }, (_, index) => group(`X${21 - index}`)); + const result = reconcileNotificationSync( + current, + response({ + head: burst, + boundary: group('A30', 'A30:new'), + }), + ); + + assert.equal(result.refreshRequired, true); + assert.equal(result.notifications, current); +}); + +void test('returns the original paginator when no continuity proof exists', () => { + const current = page(sequence('A', 20)); + const result = reconcileNotificationSync( + current, + response({ head: sequence('X', 20), boundary: group('unknown') }), + ); + + assert.equal(result.refreshRequired, true); + assert.equal(result.notifications, current); +}); + +void test('collects distinct visible rows below the header and stops at twenty', () => { + const element = ( + id: string, + bounds: Partial = {}, + ): HTMLElement => + ({ + dataset: { notificationGroup: id }, + getBoundingClientRect: () => ({ + width: 10, + height: 10, + top: 30, + bottom: 40, + left: 0, + right: 10, + ...bounds, + }), + }) as unknown as HTMLElement; + const visible = Array.from({ length: 22 }, (_, index) => + element(`visible-${index + 1}`), + ); + + const ids = visibleNotificationGroupIds( + [ + element('zero-size', { width: 0 }), + element('under-header', { top: 0, bottom: 10 }), + element('offscreen', { top: 110, bottom: 120 }), + visible[0], + ...visible, + ], + 20, + { innerHeight: 100, innerWidth: 100 }, + ); + + assert.deepEqual( + ids, + Array.from({ length: 20 }, (_, index) => `visible-${index + 1}`), + ); +}); +``` + +- [ ] **Step 2: Run the direct unit test and confirm the module is missing** + +Run: + +```bash +node --experimental-strip-types --test tests/Unit/NotificationSync.test.ts +``` + +Expected: FAIL because `resources/js/lib/notification-sync.ts` does not exist. + +- [ ] **Step 3: Add the shared response types** + +Append to `resources/js/types/notification.ts`: + +```ts +export type NotificationSyncRepresentative = Pick< + NotificationGroup, + 'group_id' | 'id' +>; + +export type NotificationSyncResponse = { + head: NotificationGroup[]; + boundary: NotificationSyncRepresentative | null; + visible: NotificationGroup[]; + missing_visible_group_ids: string[]; + unread_notifications_count: number; +}; +``` + +- [ ] **Step 4: Implement visibility selection and reconciliation** + +Create `resources/js/lib/notification-sync.ts`: + +```ts +import type { + CursorPaginated, + NotificationGroup, + NotificationSyncRepresentative, + NotificationSyncResponse, +} from '@/types'; + +const maxVisibleGroups = 20; + +const sameRepresentative = ( + left: NotificationSyncRepresentative, + right: NotificationSyncRepresentative, +): boolean => left.group_id === right.group_id && left.id === right.id; + +const uniqueGroups = (groups: NotificationGroup[]): NotificationGroup[] => { + const seen = new Set(); + + return groups.filter(({ group_id }) => { + if (seen.has(group_id)) { + return false; + } + + seen.add(group_id); + + return true; + }); +}; + +export function visibleNotificationGroupIds( + elements: Iterable, + headerBottom: number, + viewport: Pick, +): string[] { + const ids: string[] = []; + const seen = new Set(); + + for (const element of elements) { + const id = element.dataset.notificationGroup ?? ''; + const bounds = element.getBoundingClientRect(); + const visible = + id !== '' && + bounds.width > 0 && + bounds.height > 0 && + bounds.bottom > headerBottom && + bounds.top < viewport.innerHeight && + bounds.right > 0 && + bounds.left < viewport.innerWidth; + + if (!visible || seen.has(id)) { + continue; + } + + seen.add(id); + ids.push(id); + + if (ids.length === maxVisibleGroups) { + break; + } + } + + return ids; +} + +export function reconcileNotificationSync( + current: CursorPaginated, + sync: NotificationSyncResponse, +): { + notifications: CursorPaginated; + refreshRequired: boolean; + paginationResetRequired: boolean; +} { + if (sync.boundary === null) { + return { + notifications: { + ...current, + data: uniqueGroups(sync.head), + next_cursor: null, + }, + refreshRequired: false, + paginationResetRequired: current.next_cursor !== null, + }; + } + + const knownBoundary = current.data.some((group) => + sameRepresentative(group, sync.boundary as NotificationSyncRepresentative), + ); + const unchangedPrefix = + sync.head.length > 0 && + sync.head.every((group, index) => { + const loaded = current.data[index]; + + return loaded !== undefined && sameRepresentative(group, loaded); + }); + + if (!knownBoundary && !unchangedPrefix) { + return { + notifications: current, + refreshRequired: true, + paginationResetRequired: false, + }; + } + + const headIds = new Set(sync.head.map(({ group_id }) => group_id)); + const missingIds = new Set(sync.missing_visible_group_ids); + const visible = new Map( + sync.visible.map((group) => [group.group_id, group]), + ); + const retained = current.data + .filter( + ({ group_id }) => + !headIds.has(group_id) && !missingIds.has(group_id), + ) + .map((group) => visible.get(group.group_id) ?? group); + + return { + notifications: { + ...current, + data: uniqueGroups([...sync.head, ...retained]), + }, + refreshRequired: false, + paginationResetRequired: false, + }; +} +``` + +`paginationResetRequired` is separate from `refreshRequired`: a null boundary proves the response is complete, but Inertia's `InfiniteScroll` data manager keeps its own next-page token. The page must perform a server-backed reset when that token was active instead of applying the otherwise-safe paginator locally. + +The `current` argument must be the paginator from Inertia's page at client-visit execution time, not the `notifications` prop captured when React last rendered. Task 5 supplies it from a functional `router.replace()` callback so an intervening infinite-scroll merge and its deeper cursor survive. + +- [ ] **Step 5: Run direct and complete client unit suites plus type checking** + +Run: + +```bash +node --experimental-strip-types --test tests/Unit/NotificationSync.test.ts +bun run test:unit +bun run test:types +``` + +Expected: the new suite, every directly discovered TypeScript test, application types, and test types pass. + +- [ ] **Step 6: Commit the pure client contract** + +```bash +git add resources/js/lib/notification-sync.ts resources/js/types/notification.ts tests/Unit/NotificationSync.test.ts +git commit -m "feat: reconcile bounded notification updates" +``` + +--- + +### Task 5: Wire bounded polling and the safe refresh fallback + +**Files:** +- Modify: `resources/js/pages/notification/index.tsx:1-325` + +**Interfaces:** +- Consumes: Task 2 Wayfinder action `NotificationSyncController.index`, Task 4 response type, visibility selector, and reconciler. +- Preserves: `firstVisibleGroup()`, the existing layout-effect scroll correction, numeric arrival calculation, filters, infinite scrolling, and `data-notification-group` markers. +- Produces: one functional `router.replace()` update that reconciles the paginator from current Inertia props and updates unread state atomically. +- Produces: sticky `refreshRequired` UI state and automatic complete-list recovery, both cleared only by successful page-one navigation. + +- [ ] **Step 1: Replace polling imports and state** + +Remove `CancelToken` and `usePoll`. Add `useEffectEvent`, alias the new Wayfinder action, and import the Task 4 contract: + +```ts +import { Head, InfiniteScroll, Link, router } from '@inertiajs/react'; +import { + Fragment, + useEffect, + useEffectEvent, + useId, + useLayoutEffect, + useRef, + useState, +} from 'react'; +import { index as sync } from '@/actions/App/Http/Controllers/NotificationSyncController'; +import { + reconcileNotificationSync, + visibleNotificationGroupIds, +} from '@/lib/notification-sync'; +import type { + Auth, + CursorPaginated, + Notification, + NotificationGroup, + NotificationSyncResponse, +} from '@/types'; +``` + +Add this page-prop shape next to `Filters` so the functional Inertia update is type-safe: + +```ts +type NotificationPageProps = { + auth: Auth; + notifications: CursorPaginated; + [key: string]: unknown; +}; +``` + +Replace the old cancel token and `usePoll` state with the following block, moving the existing `filterVisit` declaration here so it is defined exactly once: + +```ts +const pollRequest = useRef(null); +const pollPaused = useRef(false); +const syncGeneration = useRef(0); +const filterNav = useRef(null); +const header = useRef(null); +const pollAnchor = useRef(null); +const filterVisit = useRef(0); +const [arrivals, setArrivals] = useState(0); +const [refreshRequired, setRefreshRequired] = useState(false); +``` + +- [ ] **Step 2: Add page-one reset, latest-prop application, and bounded interval polling** + +Insert after the state declarations and before `filterLink`: + +```ts +const refreshInbox = () => { + const href = index({ + query: filters.type === 'all' ? {} : { type: filters.type }, + }); + const visit = ++filterVisit.current; + syncGeneration.current++; + pollPaused.current = true; + pollRequest.current?.abort(); + pollAnchor.current = null; + const finishRefresh = () => { + if (visit === filterVisit.current) { + setRefreshRequired(false); + setArrivals(0); + window.scrollTo({ top: 0 }); + } + }; + + router.visit(href, { + only: ['notifications', 'filters', 'readAt', 'auth'], + reset: ['notifications'], + preserveState: true, + onError: finishRefresh, + onSuccess: finishRefresh, + onFinish: () => { + if (visit === filterVisit.current) { + pollPaused.current = false; + } + }, + }); +}; + +const applySync = useEffectEvent( + (response: NotificationSyncResponse, generation: number) => { + let reconciliation: ReturnType< + typeof reconcileNotificationSync + > | null = null; + const finishReconciliation = () => { + const result = reconciliation; + + if (generation !== syncGeneration.current || result === null) { + return; + } + + if (result.refreshRequired) { + setRefreshRequired(true); + + return; + } + + if (result.paginationResetRequired) { + refreshInbox(); + } + }; + + router.replace({ + preserveScroll: true, + preserveState: true, + props: (currentProps) => { + if (generation !== syncGeneration.current) { + return currentProps; + } + + const auth = { + ...currentProps.auth, + unreadNotificationsCount: + response.unread_notifications_count, + }; + + if (refreshRequired) { + return { ...currentProps, auth }; + } + + const result = reconcileNotificationSync( + currentProps.notifications, + response, + ); + reconciliation = result; + + if ( + result.refreshRequired || + result.paginationResetRequired + ) { + return { ...currentProps, auth }; + } + + pollAnchor.current = firstVisibleGroup( + header.current, + currentProps.notifications.data, + ); + + return { + ...currentProps, + auth, + notifications: result.notifications, + }; + }, + onError: finishReconciliation, + onSuccess: finishReconciliation, + }); + }, +); + +useEffect(() => { + const lifecycle = new AbortController(); + let running = false; + + const poll = async () => { + if (document.hidden || running || pollPaused.current) { + return; + } + + const generation = syncGeneration.current; + const request = new AbortController(); + const visible = visibleNotificationGroupIds( + document.querySelectorAll( + '[data-notification-group]', + ), + header.current?.getBoundingClientRect().bottom ?? 0, + window, + ); + const query = { + visible, + ...(filters.type === 'all' ? {} : { type: filters.type }), + }; + running = true; + pollRequest.current = request; + + try { + const result = await fetch(sync.url({ query }), { + headers: { Accept: 'application/json' }, + cache: 'no-store', + signal: AbortSignal.any([ + lifecycle.signal, + request.signal, + AbortSignal.timeout(10_000), + ]), + }); + + if (!result.ok) { + return; + } + + const response = (await result.json()) as NotificationSyncResponse; + + if ( + !lifecycle.signal.aborted && + !request.signal.aborted && + !pollPaused.current && + generation === syncGeneration.current + ) { + applySync(response, generation); + } + } catch { + // Keep the last good inbox until the next interval. + } finally { + if (pollRequest.current === request) { + pollRequest.current = null; + } + + running = false; + } + }; + + const interval = window.setInterval(() => void poll(), 30_000); + + return () => { + syncGeneration.current++; + window.clearInterval(interval); + lifecycle.abort(); + pollRequest.current?.abort(); + }; +}, [filters.type]); +``` + +Keep each successful-swap completion handler on both `onError` and `onSuccess`, including `finishReconciliation`, `finishRefresh`, and `finishNavigation`. Inertia chooses `onError` instead of `onSuccess` when the resulting page has non-empty error props, even though the replacement or GET swap completed; either branch must still surface ambiguity, launch the required reset, or clear sticky fallback state. + +- [ ] **Step 3: Preserve cancellation across filter navigation** + +At the start of the existing unmodified-click path, invalidate queued sync applications, pause, and abort; clear fallback state only on successful navigation and resume the interval on finish: + +```ts +event.preventDefault(); +const visit = ++filterVisit.current; +syncGeneration.current++; +pollPaused.current = true; +pollRequest.current?.abort(); +pollAnchor.current = null; +setArrivals(0); +const finishNavigation = () => { + if (visit === filterVisit.current) { + setRefreshRequired(false); + } +}; +router.visit(href, { + only: ['notifications', 'filters', 'auth'], + reset: ['notifications'], + preserveState: true, + viewTransition: true, + onError: finishNavigation, + onSuccess: finishNavigation, + onFinish: () => { + if (visit === filterVisit.current) { + pollPaused.current = false; + } + }, +}); +``` + +- [ ] **Step 4: Add the page-one recovery control for ambiguous responses** + +Use the `refreshInbox` handler from Step 2 for ambiguous responses. Replace the arrival-control condition and click/text branches with: + +```tsx +{(refreshRequired || arrivals > 0) && ( +
+ +
+)} +``` + +- [ ] **Step 5: Generate the action and run client verification** + +Run: + +```bash +php artisan wayfinder:generate --with-form +node --experimental-strip-types --test tests/Unit/NotificationSync.test.ts +bun run test:unit +bun run test:types +bun run test:lint +bun run build +``` + +Expected: reconciliation tests, all discovered TypeScript tests, application and test types, lint, and the production build pass. + +- [ ] **Step 6: Inspect polling behavior and commit the page integration** + +Run: + +```bash +/home/shawn/.local/bin/ripwire . --edit-check=./resources/js/pages/notification/index.tsx:Index +git diff --check +git status --short +``` + +Verify from the diff that the old `through`, `CancelToken`, and `usePoll` client contract is gone; the existing anchor layout effect and `data-notification-group` attribute remain. + +Commit: + +```bash +git add resources/js/pages/notification/index.tsx +git commit -m "fix: bound notification inbox polling" +``` + +--- + +### Task 6: Verify, review, and submit the focused PR + +**Files:** +- Review: every file listed in the File Map +- Do not commit: ignored Wayfinder output, dependency directories, build output, credentials, or unrelated worktree changes. + +**Interfaces:** +- Consumes: all prior task commits. +- Produces: a reviewed branch and one upstream pull request for bounded notification synchronization, unless an equivalent open PR now exists. + +- [ ] **Step 1: Run formatting, regenerate Wayfinder, and inspect formatter changes** + +Run: + +```bash +composer lint +php artisan wayfinder:generate --with-form +git diff --check +git status --short +``` + +Expected: formatting succeeds; only files in the File Map are tracked as changed. If formatting changed a committed file, inspect it and commit that scoped correction before continuing. + +- [ ] **Step 2: Run the complete project gates** + +Run: + +```bash +composer test +bun run build +/home/shawn/.local/bin/ripwire . --quality-delta +/home/shawn/.local/bin/ripwire . --test-gate +``` + +Expected: lint, PHPStan, TypeScript, 100% PHP type coverage, 100% PHP test coverage, directly discovered JavaScript tests, production build, and both structural gates pass. + +- [ ] **Step 3: Run targeted cross-database-sensitive and contract checks once more** + +Run: + +```bash +php -d memory_limit=-1 vendor/bin/pest tests/Unit/Queries/NotificationGroupsQueryTest.php tests/Feature/Controllers/NotificationSyncControllerTest.php tests/Feature/NotificationInboxTest.php +node --experimental-strip-types --test tests/Unit/NotificationSync.test.ts +php artisan route:list --name=notification-sync +``` + +Expected: all focused tests pass and the only matching route is authenticated `GET notifications/sync` named `notification-sync.index`. + +- [ ] **Step 4: Request an independent whole-branch review and resolve every finding** + +Invoke `superpowers:requesting-code-review`. Give the reviewer the design, this plan, and the full diff from `upstream/production...HEAD`. Require explicit review of: + +```text +1. Recipient scoping, validation-before-acknowledgement, and cache privacy. +2. The 20 + 20 payload bound and absence of loaded-depth amplification. +3. One-statement representative identity and exact (group_id, id) continuity, including the mixed-burst counterexample. +4. Read acknowledgement races and stale Inertia deployment behavior. +5. Poll cancellation, overlap prevention, current-prop reconciliation, InfiniteScroll reset, sticky fallback, cursor preservation, and scroll anchoring. +``` + +After corrections, rerun the smallest affected test first, then repeat Steps 1 through 3. + +- [ ] **Step 5: Recheck open pull requests and stop if an equivalent fix appeared** + +Run: + +```bash +gh pr list --repo nunomaduro/dev-null.sh --state open --limit 500 --json number,title,body,headRefName,url +``` + +Inspect the full result, including bodies, for notification, inbox, polling, sync, or retired-`through` candidates; do not rely only on an exact search phrase. If any candidate materially implements this bounded sync contract, do not push or open another PR; report the existing PR URL and retain the local branch for reference. + +- [ ] **Step 6: Push to the fork and open a detailed plain-English PR** + +Push this branch explicitly to the authenticated fork; do not use bare `git push`, because the local branch currently tracks the read-only `upstream` remote: + +```bash +git push --set-upstream origin fix/bounded-notification-sync +``` + +Then create the PR explicitly from `eas4ai:fix/bounded-notification-sync` to `nunomaduro/dev-null.sh:production`: + +```bash +gh pr create \ + --repo nunomaduro/dev-null.sh \ + --base production \ + --head eas4ai:fix/bounded-notification-sync \ + --title "Bound notification inbox polling work" \ + --body-file - +``` + +Send the following body on standard input and then close it: + +```markdown +## Summary + +- add a private notification sync endpoint with a fixed 20-row head and at most 20 visible-row refreshes +- reconcile safe updates by stable group ID and representative event ID while preserving the deepest pagination cursor +- select head, boundary, and visible representatives from one database statement and reset Inertia's internal cursor when a complete list is returned +- replace depth-dependent Inertia reload polling with non-overlapping JSON polling and a safe full-refresh fallback +- keep normal inbox pages fixed at 20 rows and remove the retired `through` request contract + +## Why + +The old poll sent the oldest loaded timestamp back to the server. Every additional page made later polls query, serialize, transfer, and replace a larger window. This change keeps hydration and response work bounded regardless of how far a person has scrolled. + +## Safety + +The endpoint is authenticated, recipient-scoped, validated before read acknowledgement, and marked `private, no-store`. The client applies a response only when an exact `(group_id, id)` boundary or unchanged representative prefix proves continuity. It reconciles against Inertia's latest page state so a concurrent infinite-scroll merge is not overwritten, and a complete response performs a server-backed cursor reset when needed. Ambiguous bursts leave the loaded list untouched and show `New notifications`, which performs a normal page-one reload. + +Offscreen historical rows can remain stale until they become visible or the page is refreshed. Delayed transactions that become visible below a previously proven boundary have the same documented limitation. A persistent mutation version or change feed would be required for a stronger guarantee. + +## Verification + +- complete Composer test pipeline, including 100% PHP coverage and type coverage +- complete directly discovered TypeScript unit suite +- production frontend build +- focused query, controller, inbox, and reconciliation regression suites +- Ripwire quality-delta and test-gate checks +``` + +After creation, record the PR URL and monitor its checks. A fork-workflow `action_required` state means maintainer approval is pending; report it accurately rather than calling it a test failure. diff --git a/docs/superpowers/specs/2026-10-16-bounded-notification-sync-design.md b/docs/superpowers/specs/2026-10-16-bounded-notification-sync-design.md index 4ffbd2e620..5ee5a66d60 100644 --- a/docs/superpowers/specs/2026-10-16-bounded-notification-sync-design.md +++ b/docs/superpowers/specs/2026-10-16-bounded-notification-sync-design.md @@ -65,11 +65,11 @@ The endpoint calls `UpdateNotificationsReadAt` before reading the result, matchi Add a dedicated sync controller and request object. The request validates the filter and UUID list before the query runs. Authentication comes from the existing notification route group, and every query is scoped to the current recipient. -Extend `NotificationGroupsQuery` with bounded operations that: +Extend `NotificationGroupsQuery` with bounded operations that select representative identity in one database statement. Rank current representatives globally, then retain rows whose position is at most 21 or whose group ID was requested in `visible[]`. Split that result in application code so the head, boundary, and visible representatives always describe the same statement snapshot. The operation: 1. Read at most 21 ranked group representatives for the selected filter. 2. Load actors and commits for the 20 returned head rows. -3. Resolve at most 20 requested visible group IDs using the same grouping and filtering rules. +3. Resolve at most 20 requested visible group IDs using the same grouping and filtering rules and the same representative snapshot. 4. Load actors and commits for visible rows not already included in the head. 5. Compute missing requested IDs from the returned head and visible IDs. @@ -87,6 +87,7 @@ Replace the inbox's Inertia reload poll with the repository's existing bounded J - Pause while the document is hidden. - Never overlap requests. - Abort on unmount or filter navigation. +- Discard a response if filter or page-one navigation changes before its queued client update executes. - Use a 10-second timeout and `cache: 'no-store'`. - On failure, keep the last good state and retry at the next interval. @@ -98,7 +99,7 @@ Put reconciliation in a pure TypeScript function so ordering and fallback behavi Given the loaded list and a sync response: -1. Treat the response as complete when `boundary` is null. Use `head` as the whole list and set `next_cursor` to null. +1. Treat the response as complete when `boundary` is null. Use `head` as the whole list and set `next_cursor` to null. If Inertia's infinite-scroll manager still owns a non-null next-page token, perform an automatic page-one reset instead of only replacing the prop; this clears its separate internal cursor state. 2. Otherwise, continuity is proven when a loaded row matches both boundary fields: its stable `group_id` and latest representative event `id`. Matching only `group_id` is unsafe because new activity can bump a loaded group while retaining that ID. 3. An unchanged first page is also safe when the returned head representative pairs (`group_id` and latest event `id`) exactly match the loaded prefix. Comparing both IDs prevents a group with new activity from disguising an ambiguous burst merely because its stable `group_id` stayed in place. This avoids a false refresh when the 21st current group has never been loaded and nothing ahead of it changed. 4. If neither continuity condition holds, do not change notification data. Set a `refreshRequired` state instead. @@ -110,7 +111,7 @@ Given the loaded list and a sync response: This makes the head and visible rows exact while deliberately leaving other retained rows in their previous order. A group bumped from the retained tail into the head appears only once. -Apply the reconciled paginator and unread count through Inertia's client-side prop replacement. The existing layout effect then restores the anchor and derives the arrival count from the anchor's new position. +Apply the reconciled paginator and unread count together through one functional Inertia client-side prop replacement. The updater must reconcile against Inertia's current paginator when the queued replacement executes, not the React prop captured when the poll completed. This preserves a page and deeper cursor that `InfiniteScroll` may merge while the poll result is waiting in the client queue. Run post-swap decisions after either Inertia completion branch for client replacements, page-one resets, and filter visits, because non-empty resulting error props make Inertia use its error callback even when the swap succeeds. The existing layout effect then restores the anchor and derives the arrival count from the anchor's new position. ## Ambiguous Change Fallback @@ -137,6 +138,7 @@ Feature tests must prove: - Unauthenticated requests are rejected, and successful responses carry `Cache-Control: private, no-store`. - Head and visible rows preserve current serialization, actor-stack, follow-state, and hidden-field behavior. - Activity inserted after read acknowledgement remains unread in the returned global count. +- Head, boundary, and visible representatives remain from one statement snapshot when a requested tail group changes during synchronization. - An old Inertia asset version triggers the existing reload path instead of continuing the removed `through` contract. - The normal paginator no longer expands from a `through` value. @@ -146,6 +148,8 @@ A directly discovered TypeScript unit suite must prove: - A bumped old group is deduplicated. - Visible replacements and tombstones are applied. - A null boundary clears stale tail data and the cursor. +- A null boundary with an active infinite-scroll cursor requests a server-backed page-one reset; a list already known to be complete can update locally. +- A page merged by infinite scroll after a poll starts remains loaded with its deeper cursor when that poll is applied. - A known boundary preserves the existing cursor. - An unchanged first-page representative prefix is accepted, while matching group IDs with changed representative IDs are not treated as proof of continuity. - A mixed burst of new groups and a bumped loaded group cannot use the bumped group as a false continuity boundary. @@ -159,5 +163,7 @@ Run the repository's focused tests, complete unit suite, lint, static analysis, - Loading additional pages does not change the sync request limit or response limit. - The loaded list never contains duplicate `group_id` values after synchronization. - The deepest pagination cursor remains unchanged during safe partial reconciliation. +- A concurrent infinite-scroll merge cannot be overwritten by a poll response based on an older React render. - Within a sync snapshot, reconciliation never accepts a changed boundary representative or omits a group returned in the bounded head. +- A complete response cannot leave Inertia's infinite-scroll manager with a stale next-page token. - No production behavior outside notification synchronization changes. From a36bef4d05d5d231bbb6f30204e07b7981f1e3c8 Mon Sep 17 00:00:00 2001 From: eas4ai Date: Fri, 16 Oct 2026 18:25:13 -0400 Subject: [PATCH 3/9] feat: add bounded notification sync query --- app/Queries/NotificationGroupsQuery.php | 93 ++++++++++++-- .../Queries/NotificationGroupsQueryTest.php | 115 ++++++++++++++++++ 2 files changed, 199 insertions(+), 9 deletions(-) diff --git a/app/Queries/NotificationGroupsQuery.php b/app/Queries/NotificationGroupsQuery.php index ca5b292a0f..b74af6ee4b 100644 --- a/app/Queries/NotificationGroupsQuery.php +++ b/app/Queries/NotificationGroupsQuery.php @@ -22,25 +22,80 @@ /** @return CursorPaginator */ public function paginate(User $user, string $type = 'all', ?CarbonImmutable $through = null): CursorPaginator { - $query = $this->events($user, $type) - ->where('group_rank', 1) - ->with([ - 'actor' => fn (BelongsTo $query): BelongsTo => $query - ->withExists(['followers as is_followed' => fn (Builder $query): Builder => $query->whereKey($user->id)]), - 'commit', - ]) - ->latest()->latest('id'); + $query = $this->groupRepresentatives($user, $type); $perPage = $through instanceof CarbonImmutable ? max(self::PER_PAGE, (clone $query)->where('created_at', '>=', $through)->count()) : self::PER_PAGE; $groups = $query->cursorPaginate($perPage)->appends(request()->except('through')); - $this->loadStackedActors($user, $type, $groups->items()); + $this->loadGroupRelations($user, $type, array_values($groups->items())); return $groups; } + /** + * @param list $visibleGroupIds + * @return array{ + * head: list, + * boundary: array{group_id: string, id: string}|null, + * visible: list, + * missing_visible_group_ids: list + * } + */ + public function sync(User $user, string $type = 'all', array $visibleGroupIds = []): array + { + $visibleGroupIds = array_slice($visibleGroupIds, 0, self::PER_PAGE); + $ranked = $this->groupRepresentatives($user, $type) + ->reorder() + ->select('notifications.*') + ->selectRaw('ROW_NUMBER() OVER (ORDER BY created_at DESC, id DESC) AS sync_position'); + $groups = Notification::query() + ->fromSub($ranked, 'notifications') + ->where(fn (NotificationBuilder $query): NotificationBuilder => $query + ->where('sync_position', '<=', self::PER_PAGE + 1) + ->when( + $visibleGroupIds !== [], + fn (NotificationBuilder $query): NotificationBuilder => $query + ->orWhereIn('group_id', $visibleGroupIds), + )) + ->withCasts([ + 'event_count' => 'integer', + 'sync_position' => 'integer', + ]) + ->orderBy('sync_position') + ->get(); + $headWithBoundary = $groups->take(self::PER_PAGE + 1)->values(); + $boundary = $headWithBoundary->count() > self::PER_PAGE + ? $headWithBoundary->pop() + : null; + $head = array_values($headWithBoundary->all()); + $headIds = array_map(fn (Notification $group): string => $group->group_id, $head); + $requestedVisibleIds = collect($visibleGroupIds)->diff($headIds)->values(); + $visible = array_values($groups->whereIn('group_id', $requestedVisibleIds)->all()); + + $this->loadGroupRelations($user, $type, [...$head, ...$visible]); + + foreach ([...$head, ...$visible] as $group) { + $group->makeHidden('sync_position'); + } + + $foundIds = [...$headIds, ...array_map( + fn (Notification $group): string => $group->group_id, + $visible, + )]; + + return [ + 'head' => $head, + 'boundary' => $boundary instanceof Notification ? [ + 'group_id' => $boundary->group_id, + 'id' => $boundary->id, + ] : null, + 'visible' => $visible, + 'missing_visible_group_ids' => array_values(array_diff($visibleGroupIds, $foundIds)), + ]; + } + public function unreadCount(User $user): int { return $this->events($user)->where('group_rank', 1)->where('unread_count', '>', 0)->count(); @@ -137,6 +192,26 @@ public function events(User $user, string $type = 'all'): NotificationBuilder ->withCasts(['event_count' => 'integer']); } + private function groupRepresentatives(User $user, string $type): NotificationBuilder + { + return $this->events($user, $type) + ->where('group_rank', 1) + ->latest() + ->latest('id'); + } + + /** @param list $groups */ + private function loadGroupRelations(User $user, string $type, array $groups): void + { + new Collection($groups)->load([ + 'actor' => fn (BelongsTo $query): BelongsTo => $query + ->withExists(['followers as is_followed' => fn (Builder $query): Builder => $query->whereKey($user->id)]), + 'commit', + ]); + + $this->loadStackedActors($user, $type, $groups); + } + /** @param array $groups */ private function loadStackedActors(User $user, string $type, array $groups): void { diff --git a/tests/Unit/Queries/NotificationGroupsQueryTest.php b/tests/Unit/Queries/NotificationGroupsQueryTest.php index ba746cef4c..27a1048b20 100644 --- a/tests/Unit/Queries/NotificationGroupsQueryTest.php +++ b/tests/Unit/Queries/NotificationGroupsQueryTest.php @@ -7,11 +7,13 @@ use App\Actions\CreateUserFollow; use App\Actions\DeleteCommit; use App\Actions\DeleteUser; +use App\Enums\CommitStatus; use App\Enums\NotificationType; use App\Models\Commit; use App\Models\Notification; use App\Models\User; use App\Queries\NotificationGroupsQuery; +use Illuminate\Database\Events\QueryExecuted; use Illuminate\Support\Facades\DB; function starAt(User $user, Commit $commit, int $minutesAgo): void @@ -244,3 +246,116 @@ function followAt(User $follower, User $user, int $minutesAgo): void 'MariaDB' => ['mariadb', 'TIMESTAMPDIFF(SECOND, previous_match_at, created_at)'], 'PostgreSQL' => ['pgsql', 'EXTRACT(EPOCH FROM (created_at - previous_match_at))'], ]); + +it('builds a bounded sync head with visible refreshes and ordered tombstones', function (): void { + $user = User::factory()->create(); + $groups = collect(range(1, 62))->map(fn (int $minutes): Notification => Notification::factory() + ->for($user, 'recipient') + ->replied() + ->create(['created_at' => now()->subMinutes($minutes)])); + $visible = $groups[30]; + $hidden = $groups[40]; + $hidden->commit->update(['status' => CommitStatus::Pending]); + + $other = Notification::factory()->replied()->create(); + + DB::flushQueryLog(); + DB::enableQueryLog(); + + $sync = resolve(NotificationGroupsQuery::class)->sync($user, visibleGroupIds: [ + $groups[0]->id, + $groups[20]->id, + $visible->id, + $hidden->id, + $other->id, + ]); + + expect($sync['head'])->toHaveCount(NotificationGroupsQuery::PER_PAGE) + ->and(array_map(fn (Notification $group): string => $group->id, $sync['head'])) + ->toBe($groups->take(20)->pluck('id')->all()) + ->and($sync['boundary'])->toBe([ + 'group_id' => $groups[20]->id, + 'id' => $groups[20]->id, + ]) + ->and(array_map(fn (Notification $group): string => $group->group_id, $sync['visible'])) + ->toBe([$groups[20]->id, $visible->id]) + ->and($sync['missing_visible_group_ids'])->toBe([$hidden->id, $other->id]) + ->and($sync['head'][0]->relationLoaded('actor'))->toBeTrue() + ->and($sync['head'][0]->relationLoaded('commit'))->toBeTrue() + ->and($sync['head'][0]->relationLoaded('actors'))->toBeTrue() + ->and(DB::getQueryLog())->toHaveCount(3); +}); + +it('uses a null sync boundary when the head contains the complete inbox', function (int $count): void { + $user = User::factory()->create(); + Notification::factory()->for($user, 'recipient')->count($count)->replied()->create(); + + $sync = resolve(NotificationGroupsQuery::class)->sync($user); + + expect($sync['head'])->toHaveCount($count) + ->and($sync['boundary'])->toBeNull() + ->and($sync['visible'])->toBe([]) + ->and($sync['missing_visible_group_ids'])->toBe([]); +})->with([0, 1, NotificationGroupsQuery::PER_PAGE]); + +it('moves an active old group into the sync head without changing its group id', function (): void { + $user = User::factory()->create(); + $root = Commit::factory()->for($user)->create(); + $oldReply = Commit::factory()->for($root, 'parent')->create(); + $old = Notification::factory()->for($user, 'recipient')->for($oldReply, 'commit')->create([ + 'type' => NotificationType::Replied, + 'created_at' => now()->subHour(), + ]); + Notification::factory()->for($user, 'recipient')->count(20)->replied()->create([ + 'created_at' => now()->subMinutes(30), + ]); + $latestReply = Commit::factory()->for($root, 'parent')->create(); + $latest = Notification::factory()->for($user, 'recipient')->for($latestReply, 'commit')->create([ + 'type' => NotificationType::Replied, + ]); + + $sync = resolve(NotificationGroupsQuery::class)->sync($user); + + expect($sync['head'][0]->id)->toBe($latest->id) + ->and($sync['head'][0]->group_id)->toBe($old->id) + ->and($sync['head'][0]->event_count)->toBe(2); +}); + +it('selects head boundary and visible representatives from one statement snapshot', function (): void { + $user = User::factory()->create(); + $root = Commit::factory()->for($user)->create(); + $oldReply = Commit::factory()->for($root, 'parent')->create(); + $old = Notification::factory()->for($user, 'recipient')->for($oldReply, 'commit')->create([ + 'type' => NotificationType::Replied, + 'created_at' => now()->subMinutes(50), + 'read_at' => now(), + ]); + Notification::factory()->for($user, 'recipient')->count(21)->replied()->read()->create([ + 'created_at' => now()->subMinutes(30), + ]); + $inserted = false; + /** @var Notification|null $late */ + $late = null; + + DB::listen(function (QueryExecuted $event) use ($user, $root, &$inserted, &$late): void { + if ($inserted || ! str_starts_with(mb_strtolower(mb_ltrim($event->sql)), 'select')) { + return; + } + + $inserted = true; + $reply = Commit::factory()->for($root, 'parent')->create(); + $late = Notification::factory()->for($user, 'recipient')->for($reply, 'commit')->create([ + 'type' => NotificationType::Replied, + ]); + }); + + $query = resolve(NotificationGroupsQuery::class); + $sync = $query->sync($user, visibleGroupIds: [$old->id]); + + expect($late)->toBeInstanceOf(Notification::class); + assert($late instanceof Notification); + expect($sync['visible'])->toHaveCount(1) + ->and($sync['visible'][0]->id)->toBe($old->id) + ->and(collect($sync['head'])->pluck('id'))->not->toContain($late->id) + ->and($query->unreadCount($user))->toBe(1); +}); From 342208ae2e54c41720280b3ed71f917b112e1684 Mon Sep 17 00:00:00 2001 From: eas4ai Date: Fri, 16 Oct 2026 18:29:43 -0400 Subject: [PATCH 4/9] feat: expose bounded notification sync --- .../NotificationSyncController.php | 29 +++ .../Requests/ListNotificationSyncRequest.php | 39 ++++ routes/web.php | 2 + .../NotificationSyncControllerTest.php | 179 ++++++++++++++++++ 4 files changed, 249 insertions(+) create mode 100644 app/Http/Controllers/NotificationSyncController.php create mode 100644 app/Http/Requests/ListNotificationSyncRequest.php create mode 100644 tests/Feature/Controllers/NotificationSyncControllerTest.php diff --git a/app/Http/Controllers/NotificationSyncController.php b/app/Http/Controllers/NotificationSyncController.php new file mode 100644 index 0000000000..c25bb87a32 --- /dev/null +++ b/app/Http/Controllers/NotificationSyncController.php @@ -0,0 +1,29 @@ +handle($user); + + return response()->json([ + ...$query->sync($user, $request->type(), $request->visible()), + 'unread_notifications_count' => $query->unreadCount($user), + ])->header('Cache-Control', 'private, no-store'); + } +} diff --git a/app/Http/Requests/ListNotificationSyncRequest.php b/app/Http/Requests/ListNotificationSyncRequest.php new file mode 100644 index 0000000000..0e8c966872 --- /dev/null +++ b/app/Http/Requests/ListNotificationSyncRequest.php @@ -0,0 +1,39 @@ +> */ + public function rules(): array + { + return [ + 'type' => ['nullable', 'in:all,replies,quotes,stars,mentions,follows,moderation'], + 'visible' => ['sometimes', 'array', 'list', 'max:20'], + 'visible.*' => ['required', 'uuid', 'distinct'], + ]; + } + + public function type(): string + { + return $this->filled('type') ? $this->string('type')->value() : 'all'; + } + + /** @return list */ + public function visible(): array + { + /** @var list $visible */ + $visible = $this->validated('visible', []); + + return $visible; + } +} diff --git a/routes/web.php b/routes/web.php index 83b61e8601..f99044db0a 100644 --- a/routes/web.php +++ b/routes/web.php @@ -30,6 +30,7 @@ use App\Http\Controllers\ModerationController; use App\Http\Controllers\NotificationController; use App\Http\Controllers\NotificationGroupController; +use App\Http\Controllers\NotificationSyncController; use App\Http\Controllers\OnboardingController; use App\Http\Controllers\OperationsController; use App\Http\Controllers\ReportedCommitController; @@ -213,6 +214,7 @@ ->name('commit-poll-vote.store'); // Notifications... + Route::get('notifications/sync', [NotificationSyncController::class, 'index'])->name('notification-sync.index'); Route::get('notifications', [NotificationController::class, 'index'])->name('notification.index'); Route::get('notifications/{notification}/group', [NotificationGroupController::class, 'show'])->name('notification-group.show'); diff --git a/tests/Feature/Controllers/NotificationSyncControllerTest.php b/tests/Feature/Controllers/NotificationSyncControllerTest.php new file mode 100644 index 0000000000..d65be6fa23 --- /dev/null +++ b/tests/Feature/Controllers/NotificationSyncControllerTest.php @@ -0,0 +1,179 @@ +getJson(route('notification-sync.index'))->assertUnauthorized(); +}); + +it('returns a private bounded sync payload with the existing group shape', function (): void { + $user = User::factory()->create(); + $groups = collect(range(1, 62))->map(fn (int $minutes): Notification => Notification::factory() + ->for($user, 'recipient') + ->replied() + ->create(['created_at' => now()->subMinutes($minutes)])); + $visibleIds = $groups->slice(21, 20)->pluck('id')->all(); + + $response = $this->actingAs($user)->getJson(route('notification-sync.index', [ + 'visible' => $visibleIds, + ]))->assertOk()->assertHeader('Cache-Control', 'no-store, private'); + + $response->assertJsonCount(20, 'head') + ->assertJsonPath('boundary', [ + 'group_id' => $groups[20]->id, + 'id' => $groups[20]->id, + ]) + ->assertJsonCount(20, 'visible') + ->assertJsonPath('missing_visible_group_ids', []) + ->assertJsonPath('unread_notifications_count', 0) + ->assertJsonPath('head.0.event_count', 1) + ->assertJsonPath('head.0.actors_count', 1) + ->assertJsonPath('head.0.unread_count', 0) + ->assertJsonStructure([ + 'head' => [['actor' => ['is_followed'], 'actors', 'commit']], + 'visible' => [['actor' => ['is_followed'], 'actors', 'commit']], + ]) + ->assertJsonMissingPath('head.0.key') + ->assertJsonMissingPath('head.0.group_rank') + ->assertJsonMissingPath('head.0.actor_position') + ->assertJsonMissingPath('head.0.sync_position') + ->assertJsonMissingPath('visible.0.key') + ->assertJsonMissingPath('visible.0.group_rank') + ->assertJsonMissingPath('visible.0.actor_position') + ->assertJsonMissingPath('visible.0.sync_position'); + + expect(array_keys($response->json()))->toBe([ + 'head', + 'boundary', + 'visible', + 'missing_visible_group_ids', + 'unread_notifications_count', + ]); +}); + +it('rejects invalid sync input before acknowledging notifications', function (array $query, string $field): void { + $user = User::factory()->create(); + $notification = Notification::factory()->for($user, 'recipient')->create(); + + $this->actingAs($user) + ->getJson(route('notification-sync.index', $query)) + ->assertUnprocessable() + ->assertJsonValidationErrors($field); + + expect($notification->refresh()->read_at)->toBeNull(); +})->with([ + 'invalid filter' => fn (): array => [['type' => 'secret'], 'type'], + 'scalar visible value' => fn (): array => [['visible' => (string) Str::uuid()], 'visible'], + 'associative visible value' => fn (): array => [['visible' => ['group' => (string) Str::uuid()]], 'visible'], + 'invalid visible uuid' => fn (): array => [['visible' => ['invalid']], 'visible.0'], + 'duplicate visible uuid' => function (): array { + $id = (string) Str::uuid(); + + return [['visible' => [$id, $id]], 'visible.1']; + }, + 'twenty one visible uuids' => fn (): array => [[ + 'visible' => collect(range(1, 21))->map(fn (): string => (string) Str::uuid())->all(), + ], 'visible'], +]); + +it('keeps global group identity while acknowledging all relevant activity', function (): void { + $user = User::factory()->create(); + $root = Commit::factory()->for($user)->create(); + $oldReply = Commit::factory()->for($root, 'parent')->create(); + $old = Notification::factory()->for($user, 'recipient')->for($oldReply, 'commit')->create([ + 'type' => NotificationType::Replied, + 'created_at' => now()->subMinutes(40), + ]); + $latestReply = Commit::factory()->for($root, 'parent')->create(); + $latest = Notification::factory()->for($user, 'recipient')->for($latestReply, 'commit')->create([ + 'type' => NotificationType::Replied, + ]); + $follow = Notification::factory()->for($user, 'recipient')->create(); + $hidden = Notification::factory()->for($user, 'recipient')->replied()->create(); + $hidden->commit->update(['status' => CommitStatus::Pending]); + + $other = Notification::factory()->create(); + + $this->actingAs($user)->getJson(route('notification-sync.index', [ + 'type' => 'replies', + 'visible' => [$old->id, $hidden->id, $other->id], + ]))->assertOk() + ->assertJsonPath('head.0.id', $latest->id) + ->assertJsonPath('head.0.group_id', $old->id) + ->assertJsonPath('head.0.event_count', 2) + ->assertJsonPath('visible', []) + ->assertJsonPath('missing_visible_group_ids', [$hidden->id, $other->id]); + + expect($latest->refresh()->read_at)->not->toBeNull() + ->and($follow->refresh()->read_at)->not->toBeNull() + ->and($hidden->refresh()->read_at)->toBeNull() + ->and($other->refresh()->read_at)->toBeNull(); +}); + +it('serializes a requested non-head group with its actor stack and follow state', function (): void { + $user = User::factory()->create(); + $commit = Commit::factory()->for($user)->create(); + $stargazers = User::factory()->count(4)->create(); + $stars = $stargazers->map(fn (User $stargazer, int $index): Notification => Notification::factory() + ->for($user, 'recipient') + ->for($stargazer, 'actor') + ->starred($commit) + ->create(['created_at' => now()->subMinutes(80 - $index)])); + $user->following()->attach($stargazers[3]); + Notification::factory()->for($user, 'recipient')->count(21)->replied()->create([ + 'created_at' => now()->subMinutes(30), + ]); + + $this->actingAs($user)->getJson(route('notification-sync.index', [ + 'visible' => [$stars[0]->id], + ]))->assertOk() + ->assertJsonCount(1, 'visible') + ->assertJsonPath('visible.0.id', $stars[3]->id) + ->assertJsonPath('visible.0.group_id', $stars[0]->id) + ->assertJsonPath('visible.0.actor.id', $stargazers[3]->id) + ->assertJsonPath('visible.0.actor.is_followed', true) + ->assertJsonPath('visible.0.commit.id', $commit->id) + ->assertJsonPath('visible.0.event_count', 4) + ->assertJsonPath('visible.0.actors_count', 4) + ->assertJsonPath('visible.0.unread_count', 0) + ->assertJsonCount(3, 'visible.0.actors') + ->assertJsonPath('visible.0.actors.0.id', $stargazers[3]->id) + ->assertJsonMissingPath('visible.0.actor.email') + ->assertJsonMissingPath('visible.0.actors.0.email') + ->assertJsonMissingPath('visible.0.sync_position'); +}); + +it('reports activity committed after acknowledgement as unread', function (): void { + $user = User::factory()->create(); + Notification::factory()->for($user, 'recipient')->create(); + $inserted = false; + /** @var Notification|null $late */ + $late = null; + + DB::listen(function (QueryExecuted $query) use ($user, &$inserted, &$late): void { + if ($inserted || ! Str::startsWith(Str::lower($query->sql), 'update') || ! Str::contains($query->sql, 'notifications')) { + return; + } + + $inserted = true; + $late = Notification::factory()->for($user, 'recipient')->create(); + }); + + $this->actingAs($user) + ->getJson(route('notification-sync.index')) + ->assertOk() + ->assertJsonPath('unread_notifications_count', 1); + + expect($late)->toBeInstanceOf(Notification::class); + assert($late instanceof Notification); + expect($late->refresh()->read_at)->toBeNull(); +}); From 51efbd4885dab539325dcec2b114e4b23b17ebe6 Mon Sep 17 00:00:00 2001 From: eas4ai Date: Fri, 16 Oct 2026 18:33:18 -0400 Subject: [PATCH 5/9] fix: keep notification pagination bounded --- .../Controllers/NotificationController.php | 4 +- .../Requests/ListNotificationsRequest.php | 7 -- app/Queries/NotificationGroupsQuery.php | 12 +-- tests/Feature/NotificationInboxTest.php | 91 +++++++------------ 4 files changed, 38 insertions(+), 76 deletions(-) diff --git a/app/Http/Controllers/NotificationController.php b/app/Http/Controllers/NotificationController.php index dab08e1567..400f383bf6 100644 --- a/app/Http/Controllers/NotificationController.php +++ b/app/Http/Controllers/NotificationController.php @@ -20,7 +20,9 @@ public function index(ListNotificationsRequest $request, #[CurrentUser] User $us $readAt = $action->handle($user); return Inertia::render('notification/index', [ - 'notifications' => Inertia::scroll(fn (): CursorPaginator => $query->paginate($user, $request->type(), $request->through()))->matchOn('data.group_id'), + 'notifications' => Inertia::scroll( + fn (): CursorPaginator => $query->paginate($user, $request->type()), + )->matchOn('data.group_id'), 'filters' => ['type' => $request->type()], 'readAt' => $readAt->toJSON(), ]); diff --git a/app/Http/Requests/ListNotificationsRequest.php b/app/Http/Requests/ListNotificationsRequest.php index e44b287c22..95fd01b8bd 100644 --- a/app/Http/Requests/ListNotificationsRequest.php +++ b/app/Http/Requests/ListNotificationsRequest.php @@ -4,7 +4,6 @@ namespace App\Http\Requests; -use Carbon\CarbonImmutable; use Illuminate\Foundation\Http\FormRequest; final class ListNotificationsRequest extends FormRequest @@ -19,7 +18,6 @@ public function rules(): array { return [ 'type' => ['nullable', 'in:all,replies,quotes,stars,mentions,follows,moderation'], - 'through' => ['nullable', 'date'], ]; } @@ -27,9 +25,4 @@ public function type(): string { return $this->filled('type') ? $this->string('type')->value() : 'all'; } - - public function through(): ?CarbonImmutable - { - return $this->date('through')?->toImmutable(); - } } diff --git a/app/Queries/NotificationGroupsQuery.php b/app/Queries/NotificationGroupsQuery.php index b74af6ee4b..1a195b0946 100644 --- a/app/Queries/NotificationGroupsQuery.php +++ b/app/Queries/NotificationGroupsQuery.php @@ -6,7 +6,6 @@ use App\Models\Notification; use App\Models\User; -use Carbon\CarbonImmutable; use Illuminate\Contracts\Pagination\CursorPaginator; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Collection; @@ -20,14 +19,11 @@ private const int STACKED_ACTORS = 3; /** @return CursorPaginator */ - public function paginate(User $user, string $type = 'all', ?CarbonImmutable $through = null): CursorPaginator + public function paginate(User $user, string $type = 'all'): CursorPaginator { - $query = $this->groupRepresentatives($user, $type); - $perPage = $through instanceof CarbonImmutable - ? max(self::PER_PAGE, (clone $query)->where('created_at', '>=', $through)->count()) - : self::PER_PAGE; - - $groups = $query->cursorPaginate($perPage)->appends(request()->except('through')); + $groups = $this->groupRepresentatives($user, $type) + ->cursorPaginate(self::PER_PAGE) + ->appends(request()->only('type')); $this->loadGroupRelations($user, $type, array_values($groups->items())); diff --git a/tests/Feature/NotificationInboxTest.php b/tests/Feature/NotificationInboxTest.php index c0c18c91b6..3251f77835 100644 --- a/tests/Feature/NotificationInboxTest.php +++ b/tests/Feature/NotificationInboxTest.php @@ -30,77 +30,48 @@ expect($notice->refresh()->read_at)->toBeNull(); }); -it('refreshes the entire loaded inbox window without losing older pages', function (): void { +it('keeps a legacy inbox refresh query to one fixed page', function (): void { $user = User::factory()->create(); - $notices = collect(); - for ($index = 1; $index <= 62; $index++) { - $notices->push(Notification::factory()->for($user, 'recipient')->replied()->create([ - 'created_at' => now()->subMinutes($index), - ])); - } + $notices = collect(range(1, 62))->map(fn (int $minutes): Notification => Notification::factory() + ->for($user, 'recipient') + ->replied() + ->create(['created_at' => now()->subMinutes($minutes)])); + + $this->actingAs($user) + ->get(route('notification.index', ['through' => $notices[39]->created_at->toJSON()])) + ->assertOk() + ->assertInertia(fn ($page) => $page + ->has('notifications.data', NotificationGroupsQuery::PER_PAGE) + ->where('notifications.data.0.id', $notices[0]->id) + ->where('notifications.next_page_url', fn (string $url): bool => ! str_contains($url, 'through'))); +}); + +it('marks an explicit page-one inbox visit as an infinite-scroll reset', function (): void { + $user = User::factory()->create(); + Notification::factory()->for($user, 'recipient')->count(21)->replied()->create(); - $new = Notification::factory()->for($user, 'recipient')->create(); - $through = $notices[39]->created_at->toJSON(); - $response = $this->actingAs($user)->withHeaders([ + $this->actingAs($user)->withHeaders([ 'X-Inertia' => 'true', 'X-Inertia-Version' => (string) new HandleInertiaRequests()->version(request()), 'X-Inertia-Partial-Component' => 'notification/index', - 'X-Inertia-Partial-Data' => 'notifications,auth.unreadNotificationsCount', + 'X-Inertia-Partial-Data' => 'notifications,filters,readAt,auth', 'X-Inertia-Reset' => 'notifications', - ])->get(route('notification.index', ['through' => $through]))->assertOk() - ->assertJsonCount(41, 'props.notifications.data') - ->assertJsonPath('props.notifications.data.0.id', $new->id) - ->assertJsonPath('props.notifications.data.40.id', $notices[39]->id) - ->assertJsonPath('props.auth.unreadNotificationsCount', 0) - ->assertJsonMissingPath('props.auth.user'); - - expect($new->refresh()->read_at)->not->toBeNull(); - $this->get($response->json('props.notifications.next_page_url')) - ->assertJsonCount(20, 'props.notifications.data') - ->assertJsonPath('props.notifications.data.0.id', $notices[40]->id); -}); - -it('rejects an invalid inbox refresh boundary without reading notifications', function (): void { - $user = User::factory()->create(); - $notice = Notification::factory()->for($user, 'recipient')->create(); - - $this->actingAs($user)->getJson(route('notification.index', ['through' => 'invalid'])) - ->assertUnprocessable()->assertJsonValidationErrors('through'); - expect($notice->refresh()->read_at)->toBeNull(); + ])->get(route('notification.index'))->assertOk() + ->assertJsonCount(NotificationGroupsQuery::PER_PAGE, 'props.notifications.data') + ->assertJsonPath('scrollProps.notifications.reset', true); }); -it('polls fresh filtered groups and excludes activity that is no longer relevant', function (): void { +it('forces a stale notification client to reload before it can reuse the retired poll contract', function (): void { $user = User::factory()->create(); - $root = Commit::factory()->for($user)->create(); - $oldReply = Commit::factory()->for($root, 'parent')->create(); - $old = Notification::factory()->for($user, 'recipient')->for($oldReply, 'commit')->create([ - 'type' => NotificationType::Replied, 'created_at' => now()->subMinutes(40), - ]); - $otherGroup = Notification::factory()->for($user, 'recipient')->replied()->create(['created_at' => now()->subMinutes(10)]); - $this->actingAs($user)->get(route('notification.index', ['type' => 'replies']))->assertOk(); - - $latestReply = Commit::factory()->for($root, 'parent')->create(); - $latest = Notification::factory()->for($user, 'recipient')->for($latestReply, 'commit')->create(['type' => NotificationType::Replied]); - $follow = Notification::factory()->for($user, 'recipient')->create(); - $otherGroup->commit->update(['status' => CommitStatus::Pending]); - $other = Notification::factory()->create(); + $notification = Notification::factory()->for($user, 'recipient')->create(); + $url = route('notification.index', ['through' => $notification->created_at->toJSON()]); - $this->withHeaders([ + $this->actingAs($user)->withHeaders([ 'X-Inertia' => 'true', - 'X-Inertia-Version' => (string) new HandleInertiaRequests()->version(request()), - 'X-Inertia-Partial-Component' => 'notification/index', - 'X-Inertia-Partial-Data' => 'notifications,auth.unreadNotificationsCount', - 'X-Inertia-Reset' => 'notifications', - ])->get(route('notification.index', ['type' => 'replies', 'through' => $old->created_at->toJSON()])) - ->assertOk()->assertJsonCount(1, 'props.notifications.data') - ->assertJsonPath('props.notifications.data.0.id', $latest->id) - ->assertJsonPath('props.notifications.data.0.group_id', $old->id) - ->assertJsonPath('props.notifications.data.0.event_count', 2) - ->assertJsonPath('props.auth.unreadNotificationsCount', 0); - - expect($latest->refresh()->read_at)->not->toBeNull() - ->and($follow->refresh()->read_at)->not->toBeNull() - ->and($other->refresh()->read_at)->toBeNull(); + 'X-Inertia-Version' => 'stale-notification-client', + ])->get($url) + ->assertStatus(409) + ->assertHeader('X-Inertia-Location', $url); }); it('groups nested replies and mentions and bumps an old conversation using its latest event', function (): void { From cb3c532f9d21fee2cdc00fd9ef651ca60e1ba87f Mon Sep 17 00:00:00 2001 From: eas4ai Date: Fri, 16 Oct 2026 18:37:47 -0400 Subject: [PATCH 6/9] feat: reconcile bounded notification updates --- resources/js/lib/notification-sync.ts | 134 +++++++++++++ resources/js/types/notification.ts | 13 ++ tests/Unit/NotificationSync.test.ts | 259 ++++++++++++++++++++++++++ 3 files changed, 406 insertions(+) create mode 100644 resources/js/lib/notification-sync.ts create mode 100644 tests/Unit/NotificationSync.test.ts diff --git a/resources/js/lib/notification-sync.ts b/resources/js/lib/notification-sync.ts new file mode 100644 index 0000000000..062fdb0111 --- /dev/null +++ b/resources/js/lib/notification-sync.ts @@ -0,0 +1,134 @@ +import type { + CursorPaginated, + NotificationGroup, + NotificationSyncRepresentative, + NotificationSyncResponse, +} from '@/types'; + +const maxVisibleGroups = 20; + +const sameRepresentative = ( + left: NotificationSyncRepresentative, + right: NotificationSyncRepresentative, +): boolean => left.group_id === right.group_id && left.id === right.id; + +const uniqueGroups = (groups: NotificationGroup[]): NotificationGroup[] => { + const seen = new Set(); + + return groups.filter(({ group_id }) => { + if (seen.has(group_id)) { + return false; + } + + seen.add(group_id); + + return true; + }); +}; + +export function visibleNotificationGroupIds( + elements: Iterable, + headerBottom: number, + viewport: Pick, +): string[] { + const ids: string[] = []; + const seen = new Set(); + + for (const element of elements) { + const id = element.dataset.notificationGroup ?? ''; + const bounds = element.getBoundingClientRect(); + const visible = + id !== '' && + bounds.width > 0 && + bounds.height > 0 && + bounds.bottom > headerBottom && + bounds.top < viewport.innerHeight && + bounds.right > 0 && + bounds.left < viewport.innerWidth; + + if (!visible || seen.has(id)) { + continue; + } + + seen.add(id); + ids.push(id); + + if (ids.length === maxVisibleGroups) { + break; + } + } + + return ids; +} + +export function reconcileNotificationSync( + current: CursorPaginated, + sync: NotificationSyncResponse, + refreshRequired = false, +): { + notifications: CursorPaginated; + refreshRequired: boolean; + paginationResetRequired: boolean; +} { + if (refreshRequired) { + return { + notifications: current, + refreshRequired: true, + paginationResetRequired: false, + }; + } + + const boundary = sync.boundary; + + if (boundary === null) { + return { + notifications: { + ...current, + data: uniqueGroups(sync.head), + next_cursor: null, + }, + refreshRequired: false, + paginationResetRequired: current.next_cursor !== null, + }; + } + + const knownBoundary = current.data.some((group) => + sameRepresentative(group, boundary), + ); + const unchangedPrefix = + sync.head.length > 0 && + sync.head.every((group, index) => { + const loaded = current.data[index]; + + return loaded !== undefined && sameRepresentative(group, loaded); + }); + + if (!knownBoundary && !unchangedPrefix) { + return { + notifications: current, + refreshRequired: true, + paginationResetRequired: false, + }; + } + + const headIds = new Set(sync.head.map(({ group_id }) => group_id)); + const missingIds = new Set(sync.missing_visible_group_ids); + const visible = new Map( + sync.visible.map((group) => [group.group_id, group]), + ); + const retained = current.data + .filter( + ({ group_id }) => + !headIds.has(group_id) && !missingIds.has(group_id), + ) + .map((group) => visible.get(group.group_id) ?? group); + + return { + notifications: { + ...current, + data: uniqueGroups([...sync.head, ...retained]), + }, + refreshRequired: false, + paginationResetRequired: false, + }; +} diff --git a/resources/js/types/notification.ts b/resources/js/types/notification.ts index 60fe44839a..54eddd266b 100644 --- a/resources/js/types/notification.ts +++ b/resources/js/types/notification.ts @@ -39,3 +39,16 @@ export type Notification = subject_id: null; commit: Omit; }); + +export type NotificationSyncRepresentative = Pick< + NotificationGroup, + 'group_id' | 'id' +>; + +export type NotificationSyncResponse = { + head: NotificationGroup[]; + boundary: NotificationSyncRepresentative | null; + visible: NotificationGroup[]; + missing_visible_group_ids: string[]; + unread_notifications_count: number; +}; diff --git a/tests/Unit/NotificationSync.test.ts b/tests/Unit/NotificationSync.test.ts new file mode 100644 index 0000000000..fbbe1efb89 --- /dev/null +++ b/tests/Unit/NotificationSync.test.ts @@ -0,0 +1,259 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { + reconcileNotificationSync, + visibleNotificationGroupIds, +} from '../../resources/js/lib/notification-sync.ts'; +import type { + CursorPaginated, + NotificationGroup, + NotificationSyncResponse, +} from '../../resources/js/types/index.ts'; + +const group = (groupId: string, id = groupId): NotificationGroup => + ({ group_id: groupId, id }) as NotificationGroup; + +const sequence = (prefix: string, count: number): NotificationGroup[] => + Array.from({ length: count }, (_, index) => group(`${prefix}${index + 1}`)); + +const page = ( + data: NotificationGroup[], + nextCursor: string | null = 'deep-cursor', +): CursorPaginated => ({ + data, + next_cursor: nextCursor, + prev_cursor: null, +}); + +const response = ( + values: Partial, +): NotificationSyncResponse => ({ + head: [], + boundary: null, + visible: [], + missing_visible_group_ids: [], + unread_notifications_count: 0, + ...values, +}); + +void test('replaces a twenty-row head and retains the loaded tail and cursor', () => { + const loaded = sequence('A', 59); + const head = [group('X'), ...loaded.slice(0, 19)]; + const result = reconcileNotificationSync( + page(loaded), + response({ head, boundary: group('A20') }), + ); + + assert.equal(result.refreshRequired, false); + assert.deepEqual( + result.notifications.data.map(({ group_id }) => group_id), + ['X', ...loaded.map(({ group_id }) => group_id)], + ); + assert.equal(result.notifications.data.length, 60); + assert.equal(result.notifications.next_cursor, 'deep-cursor'); +}); + +void test('preserves a page merged after the poll request started', () => { + const atRequestStart = sequence('A', 20); + const currentAtApply = page( + [...atRequestStart, ...sequence('merged-', 20)], + 'new-deep-cursor', + ); + const head = [group('X'), ...atRequestStart.slice(0, 19)]; + const result = reconcileNotificationSync( + currentAtApply, + response({ head, boundary: group('A20') }), + ); + + assert.equal(result.refreshRequired, false); + assert.equal(result.paginationResetRequired, false); + assert.equal(result.notifications.data.length, 41); + assert.equal(result.notifications.data.at(-1)?.group_id, 'merged-20'); + assert.equal(result.notifications.next_cursor, 'new-deep-cursor'); +}); + +void test('deduplicates a bumped old group by stable group id', () => { + const loaded = sequence('A', 30); + const bumped = group('A30', 'A30:new'); + const result = reconcileNotificationSync( + page(loaded), + response({ + head: [bumped, ...loaded.slice(0, 19)], + boundary: group('A20'), + }), + ); + + assert.equal(result.refreshRequired, false); + assert.equal(result.notifications.data[0], bumped); + assert.equal( + result.notifications.data.filter(({ group_id }) => group_id === 'A30') + .length, + 1, + ); +}); + +void test('applies visible replacements and missing-row tombstones', () => { + const head = sequence('A', 20); + const current = page([...head, group('A21'), group('visible'), group('missing')]); + const replacement = group('visible', 'visible:new'); + const result = reconcileNotificationSync( + current, + response({ + head, + boundary: group('A21'), + visible: [replacement], + missing_visible_group_ids: ['missing'], + }), + ); + + assert.equal(result.refreshRequired, false); + assert.equal( + result.notifications.data.find(({ group_id }) => group_id === 'visible'), + replacement, + ); + assert.equal( + result.notifications.data.some(({ group_id }) => group_id === 'missing'), + false, + ); +}); + +void test('treats a null boundary as complete and clears retained history and cursor', () => { + const head = sequence('A', 4); + const result = reconcileNotificationSync( + page([...head, ...sequence('stale', 5)]), + response({ head }), + ); + + assert.equal(result.refreshRequired, false); + assert.equal(result.paginationResetRequired, true); + assert.deepEqual(result.notifications.data, head); + assert.equal(result.notifications.next_cursor, null); +}); + +void test('updates a complete paginator locally when its cursor is already exhausted', () => { + const head = sequence('A', 4); + const result = reconcileNotificationSync( + page([...head, ...sequence('stale', 5)], null), + response({ head }), + ); + + assert.equal(result.refreshRequired, false); + assert.equal(result.paginationResetRequired, false); + assert.deepEqual(result.notifications.data, head); + assert.equal(result.notifications.next_cursor, null); +}); + +void test('accepts an unchanged representative prefix with an unloaded boundary', () => { + const head = sequence('A', 20); + const result = reconcileNotificationSync( + page(head), + response({ head: [...head], boundary: group('A21') }), + ); + + assert.equal(result.refreshRequired, false); + assert.equal(result.notifications.next_cursor, 'deep-cursor'); +}); + +void test('rejects a matching group-id prefix when a representative id changed', () => { + const loaded = sequence('A', 20); + const changed = [group('A1', 'A1:new'), ...loaded.slice(1)]; + const result = reconcileNotificationSync( + page(loaded), + response({ head: changed, boundary: group('A21') }), + ); + + assert.equal(result.refreshRequired, true); + assert.equal(result.notifications.data, loaded); +}); + +void test('rejects a mixed burst whose stable boundary group has a new representative', () => { + const current = page(sequence('A', 40)); + const burst = Array.from({ length: 20 }, (_, index) => group(`X${21 - index}`)); + const result = reconcileNotificationSync( + current, + response({ + head: burst, + boundary: group('A30', 'A30:new'), + }), + ); + + assert.equal(result.refreshRequired, true); + assert.equal(result.notifications, current); +}); + +void test('returns the original paginator when no continuity proof exists', () => { + const current = page(sequence('A', 20)); + const result = reconcileNotificationSync( + current, + response({ head: sequence('X', 20), boundary: group('unknown') }), + ); + + assert.equal(result.refreshRequired, true); + assert.equal(result.notifications, current); +}); + +void test('keeps fallback sticky after ambiguous A even when queued B would be safe', () => { + const current = page(sequence('A', 20)); + const ambiguous = reconcileNotificationSync( + current, + response({ head: sequence('X', 20), boundary: group('unknown') }), + ); + const safe = response({ head: [group('replacement')] }); + + assert.equal(ambiguous.refreshRequired, true); + assert.notEqual( + reconcileNotificationSync(current, safe).notifications, + current, + ); + + const queued = reconcileNotificationSync( + ambiguous.notifications, + safe, + ambiguous.refreshRequired, + ); + + assert.equal(queued.notifications, current); + assert.equal(queued.notifications.data, current.data); + assert.equal(queued.notifications.next_cursor, 'deep-cursor'); + assert.equal(queued.refreshRequired, true); + assert.equal(queued.paginationResetRequired, false); +}); + +void test('collects distinct visible rows below the header and stops at twenty', () => { + const element = ( + id: string, + bounds: Partial = {}, + ): HTMLElement => + ({ + dataset: { notificationGroup: id }, + getBoundingClientRect: () => ({ + width: 10, + height: 10, + top: 30, + bottom: 40, + left: 0, + right: 10, + ...bounds, + }), + }) as unknown as HTMLElement; + const visible = Array.from({ length: 22 }, (_, index) => + element(`visible-${index + 1}`), + ); + + const ids = visibleNotificationGroupIds( + [ + element('zero-size', { width: 0 }), + element('under-header', { top: 0, bottom: 10 }), + element('offscreen', { top: 110, bottom: 120 }), + visible[0], + ...visible, + ], + 20, + { innerHeight: 100, innerWidth: 100 }, + ); + + assert.deepEqual( + ids, + Array.from({ length: 20 }, (_, index) => `visible-${index + 1}`), + ); +}); From 9cead241af1bd9896cfba0c14000633521ddefd2 Mon Sep 17 00:00:00 2001 From: eas4ai Date: Fri, 16 Oct 2026 18:43:28 -0400 Subject: [PATCH 7/9] fix: bound notification inbox polling --- resources/js/pages/notification/index.tsx | 276 ++++++++++++++++++---- 1 file changed, 235 insertions(+), 41 deletions(-) diff --git a/resources/js/pages/notification/index.tsx b/resources/js/pages/notification/index.tsx index a76a61f9df..5c478cb1df 100644 --- a/resources/js/pages/notification/index.tsx +++ b/resources/js/pages/notification/index.tsx @@ -1,5 +1,4 @@ -import type { CancelToken } from '@inertiajs/core'; -import { Head, InfiniteScroll, Link, router, usePoll } from '@inertiajs/react'; +import { Head, InfiniteScroll, Link, router } from '@inertiajs/react'; import { ArrowUp, AtSign, @@ -15,6 +14,7 @@ import type { MouseEvent, ReactNode } from 'react'; import { Fragment, useEffect, + useEffectEvent, useId, useLayoutEffect, useRef, @@ -23,6 +23,7 @@ import { import CommitController from '@/actions/App/Http/Controllers/CommitController'; import { index } from '@/actions/App/Http/Controllers/NotificationController'; import { show as groupShow } from '@/actions/App/Http/Controllers/NotificationGroupController'; +import { index as sync } from '@/actions/App/Http/Controllers/NotificationSyncController'; import { CommitBodyExcerpt } from '@/components/commit-body'; import { EmptyFeed } from '@/components/commit-feed'; import { FollowButton } from '@/components/follow-button'; @@ -32,6 +33,10 @@ import { UserAvatar } from '@/components/user-avatar'; import { useNow } from '@/hooks/use-now'; import { useUser } from '@/hooks/use-user'; import AppLayout from '@/layouts/app-layout'; +import { + reconcileNotificationSync, + visibleNotificationGroupIds, +} from '@/lib/notification-sync'; import { cn, formatDayLabel, @@ -40,7 +45,13 @@ import { localDayKey, } from '@/lib/utils'; import { show } from '@/routes/user'; -import type { CursorPaginated, Notification, NotificationGroup } from '@/types'; +import type { + Auth, + CursorPaginated, + Notification, + NotificationGroup, + NotificationSyncResponse, +} from '@/types'; type Filters = { type: @@ -53,6 +64,12 @@ type Filters = { | 'moderation'; }; +type NotificationPageProps = { + auth: Auth; + notifications: CursorPaginated; + [key: string]: unknown; +}; + const filterOptions: { type: Filters['type']; label: string; @@ -140,38 +157,193 @@ export default function Index({ readAt: string; }) { const now = useNow(); - const pollRequest = useRef(null); + const pollRequest = useRef(null); + const pollPaused = useRef(false); + const syncGeneration = useRef(0); const filterNav = useRef(null); const header = useRef(null); const pollAnchor = useRef(null); + const filterVisit = useRef(0); + const refreshRequiredRef = useRef(false); const [arrivals, setArrivals] = useState(0); - const { start, stop } = usePoll( - 30_000, - () => ({ - only: ['notifications', 'auth.unreadNotificationsCount'], + const [refreshRequired, setRefreshRequired] = useState(false); + + const refreshInbox = () => { + const href = index({ + query: filters.type === 'all' ? {} : { type: filters.type }, + }); + const visit = ++filterVisit.current; + syncGeneration.current++; + pollPaused.current = true; + pollRequest.current?.abort(); + pollAnchor.current = null; + const finishRefresh = () => { + if (visit === filterVisit.current) { + refreshRequiredRef.current = false; + setRefreshRequired(false); + setArrivals(0); + window.scrollTo({ top: 0 }); + } + }; + + router.visit(href, { + only: ['notifications', 'filters', 'readAt', 'auth'], reset: ['notifications'], - data: { - cursor: '', - through: notifications.data.at(-1)?.created_at, - }, - preserveUrl: true, - preserveErrors: true, - onStart: () => { - pollAnchor.current = firstVisibleGroup( - header.current, - notifications.data, - ); - }, - onCancelToken: (token) => { - pollRequest.current = token; - }, + preserveState: true, + onError: finishRefresh, + onSuccess: finishRefresh, onFinish: () => { - pollRequest.current = null; + if (visit === filterVisit.current) { + pollPaused.current = false; + } }, - }), - { mode: 'rest', background: 'pause' }, + }); + }; + + const applySync = useEffectEvent( + (response: NotificationSyncResponse, generation: number) => { + let reconciliation: ReturnType< + typeof reconcileNotificationSync + > | null = null; + const finishReconciliation = () => { + const result = reconciliation; + + if (generation !== syncGeneration.current || result === null) { + return; + } + + if (result.refreshRequired) { + setRefreshRequired(true); + + return; + } + + if (result.paginationResetRequired) { + refreshInbox(); + } + }; + + router.replace({ + preserveScroll: true, + preserveState: true, + props: (currentProps) => { + if (generation !== syncGeneration.current) { + return currentProps; + } + + const auth = { + ...currentProps.auth, + unreadNotificationsCount: + response.unread_notifications_count, + }; + const result = reconcileNotificationSync( + currentProps.notifications, + response, + refreshRequiredRef.current, + ); + reconciliation = result; + + if (result.refreshRequired) { + refreshRequiredRef.current = true; + } + + if ( + result.refreshRequired || + result.paginationResetRequired + ) { + return { ...currentProps, auth }; + } + + pollAnchor.current = firstVisibleGroup( + header.current, + currentProps.notifications.data, + ); + + return { + ...currentProps, + auth, + notifications: result.notifications, + }; + }, + onError: finishReconciliation, + onSuccess: finishReconciliation, + }); + }, ); - const filterVisit = useRef(0); + + useEffect(() => { + const lifecycle = new AbortController(); + const generationRef = syncGeneration; + let running = false; + + const poll = async () => { + if (document.hidden || running || pollPaused.current) { + return; + } + + const generation = syncGeneration.current; + const request = new AbortController(); + const visible = visibleNotificationGroupIds( + document.querySelectorAll( + '[data-notification-group]', + ), + header.current?.getBoundingClientRect().bottom ?? 0, + window, + ); + const query = { + visible, + ...(filters.type === 'all' ? {} : { type: filters.type }), + }; + running = true; + pollRequest.current = request; + + try { + const result = await fetch(sync.url({ query }), { + headers: { Accept: 'application/json' }, + cache: 'no-store', + signal: AbortSignal.any([ + lifecycle.signal, + request.signal, + AbortSignal.timeout(10_000), + ]), + }); + + if (!result.ok) { + return; + } + + const response = + (await result.json()) as NotificationSyncResponse; + + if ( + !lifecycle.signal.aborted && + !request.signal.aborted && + !pollPaused.current && + generation === syncGeneration.current + ) { + applySync(response, generation); + } + } catch { + // Keep the last good inbox until the next interval. + } finally { + if (pollRequest.current === request) { + pollRequest.current = null; + } + + running = false; + } + }; + + const interval = window.setInterval(() => void poll(), 30_000); + + return () => { + generationRef.current++; + window.clearInterval(interval); + lifecycle.abort(); + pollRequest.current?.abort(); + }; + }, [filters.type]); + const filterLink = (type: Filters['type']) => { const href = index({ query: type === 'all' ? {} : { type } }); @@ -190,18 +362,27 @@ export default function Index({ event.preventDefault(); const visit = ++filterVisit.current; - stop(); - pollRequest.current?.cancel(); + syncGeneration.current++; + pollPaused.current = true; + pollRequest.current?.abort(); pollAnchor.current = null; setArrivals(0); + const finishNavigation = () => { + if (visit === filterVisit.current) { + refreshRequiredRef.current = false; + setRefreshRequired(false); + } + }; router.visit(href, { only: ['notifications', 'filters', 'auth'], reset: ['notifications'], preserveState: true, viewTransition: true, + onError: finishNavigation, + onSuccess: finishNavigation, onFinish: () => { if (visit === filterVisit.current) { - start(); + pollPaused.current = false; } }, }); @@ -303,23 +484,36 @@ export default function Index({ ); })} - {arrivals > 0 && ( + {(refreshRequired || arrivals > 0) && (
)} From 3d6cf53c30b6915f5bc4294351aa5fbfaa13e33a Mon Sep 17 00:00:00 2001 From: eas4ai Date: Fri, 16 Oct 2026 18:51:55 -0400 Subject: [PATCH 8/9] fix: reset notification scroll after error-bearing swaps --- resources/js/pages/notification/index.tsx | 4 + tests/Unit/NotificationIndex.test.tsx | 314 +++++++++++++++++++++- 2 files changed, 315 insertions(+), 3 deletions(-) diff --git a/resources/js/pages/notification/index.tsx b/resources/js/pages/notification/index.tsx index 5c478cb1df..901d048cf1 100644 --- a/resources/js/pages/notification/index.tsx +++ b/resources/js/pages/notification/index.tsx @@ -167,6 +167,7 @@ export default function Index({ const refreshRequiredRef = useRef(false); const [arrivals, setArrivals] = useState(0); const [refreshRequired, setRefreshRequired] = useState(false); + const [scrollReset, setScrollReset] = useState(0); const refreshInbox = () => { const href = index({ @@ -179,6 +180,7 @@ export default function Index({ pollAnchor.current = null; const finishRefresh = () => { if (visit === filterVisit.current) { + setScrollReset((epoch) => epoch + 1); refreshRequiredRef.current = false; setRefreshRequired(false); setArrivals(0); @@ -369,6 +371,7 @@ export default function Index({ setArrivals(0); const finishNavigation = () => { if (visit === filterVisit.current) { + setScrollReset((epoch) => epoch + 1); refreshRequiredRef.current = false; setRefreshRequired(false); } @@ -541,6 +544,7 @@ export default function Index({ ) : ( <> import assert from 'node:assert/strict'; -import { test } from 'node:test'; -import { createInertiaApp } from '@inertiajs/react'; +import { mock, test } from 'node:test'; +import { createInertiaApp, InfiniteScroll, router } from '@inertiajs/react'; +import React, { type ReactElement, type ReactNode } from 'react'; import { renderToString } from 'react-dom/server'; import Index from '../../resources/js/pages/notification/index'; -import type { Commit, NotificationGroup, User } from '../../resources/js/types'; +import type { + Commit, + NotificationGroup, + NotificationSyncResponse, + User, +} from '../../resources/js/types'; const actor = { id: 'actor', @@ -118,3 +124,305 @@ for (const isFollowing of [false, true]) { assert.doesNotMatch(body, /```/); }); } + +type Element = ReactElement>; + +function elements(node: ReactNode): Element[] { + if (!React.isValidElement(node)) { + return []; + } + + const element = node as Element; + + return [ + element, + ...React.Children.toArray(element.props.children as ReactNode).flatMap( + elements, + ), + ]; +} + +// This seam executes Index and its completion callbacks with persistent hook +// state. It inspects React keys; it does not mount Inertia or simulate its DOM. +function inboxLifecycle() { + const slots: unknown[] = []; + let cursor = 0; + let applySync: ( + response: NotificationSyncResponse, + generation: number, + ) => void; + let props = { + auth: { unreadNotificationsCount: 0 }, + errors: {} as Record, + notifications: { + data: [notification], + next_cursor: 'old-deep-cursor' as string | null, + prev_cursor: null, + }, + }; + const visits: Parameters[1][] = []; + const visit = mock.method( + router, + 'visit', + (...[_href, options]: Parameters) => { + visits.push(options); + }, + ); + const replace = mock.method( + router, + 'replace', + (options: { + props: (current: typeof props) => typeof props; + onError?: (errors: Record) => void; + onSuccess?: () => void; + }) => { + props = options.props(props); + if (Object.keys(props.errors).length > 0) { + options.onError?.(props.errors); + } else { + options.onSuccess?.(); + } + }, + ); + const internals = ( + React as unknown as { + __CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE: { + H: unknown; + }; + } + ).__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE; + const dispatcher = { + useRef: (initial: unknown) => { + const index = cursor++; + slots[index] ??= { current: initial }; + + return slots[index]; + }, + useState: (initial: unknown) => { + const index = cursor++; + if (!(index in slots)) { + slots[index] = initial; + } + + return [ + slots[index], + (value: unknown) => { + slots[index] = + typeof value === 'function' + ? value(slots[index]) + : value; + }, + ]; + }, + useEffect: () => {}, + useLayoutEffect: () => {}, + useEffectEvent: (callback: typeof applySync) => { + applySync = callback; + + return callback; + }, + useSyncExternalStore: (_subscribe: unknown, snapshot: () => unknown) => + snapshot(), + }; + const render = () => { + const previous = internals.H; + internals.H = dispatcher; + cursor = 0; + + try { + return elements( + Index({ + notifications: props.notifications, + filters: { type: 'all' }, + readAt: '2026-10-16T12:00:00.000000Z', + }), + ); + } finally { + internals.H = previous; + } + }; + + return { + render, + visits, + sync: (response: NotificationSyncResponse) => applySync(response, 0), + swap: (errors: Record, nextCursor: string | null) => { + props = { + ...props, + errors, + notifications: { + data: [{ ...notification, id: 'refreshed-notification' }], + next_cursor: nextCursor, + prev_cursor: null, + }, + }; + }, + restore: () => { + visit.mock.restore(); + replace.mock.restore(); + }, + }; +} + +for (const navigation of ['refresh', 'filter'] as const) { + for (const completion of ['onError', 'onSuccess'] as const) { + void test(`${navigation} resets the rendered scroll instance after ${completion}`, () => { + const inbox = inboxLifecycle(); + const originalWindow = Object.getOwnPropertyDescriptor( + globalThis, + 'window', + ); + Object.defineProperty(globalThis, 'window', { + configurable: true, + value: { scrollTo: () => {} }, + }); + + try { + const before = inbox.render(); + const oldScroll = before.find( + (element) => element.type === InfiniteScroll, + ); + assert.ok(oldScroll); + + if (navigation === 'refresh') { + inbox.sync({ + head: [notification], + boundary: null, + visible: [], + missing_visible_group_ids: [], + unread_notifications_count: 0, + }); + } else { + const filter = before.find( + (element) => + element.type === 'a' && + element.props.href === + '/notifications?type=replies', + ); + assert.ok(filter); + (filter.props.onClick as (event: unknown) => void)({ + button: 0, + preventDefault: () => {}, + }); + } + + const visit = inbox.visits.at(-1); + assert.ok(visit); + assert.deepEqual(visit.reset, ['notifications']); + assert.equal(visit.preserveState, true); + assert.equal( + inbox + .render() + .find((element) => element.type === InfiniteScroll) + ?.key, + oldScroll.key, + ); + + const errors: Record = + completion === 'onError' + ? { notice: 'Earlier action failed' } + : {}; + inbox.swap(errors, 'refreshed-cursor'); + assert.equal( + inbox + .render() + .find((element) => element.type === InfiniteScroll) + ?.key, + oldScroll.key, + ); + const finish = visit[completion] as (result: unknown) => void; + assert.equal(typeof finish, 'function'); + finish( + completion === 'onError' ? errors : { props: { errors } }, + ); + + const nextScroll = inbox + .render() + .find((element) => element.type === InfiniteScroll); + assert.ok(nextScroll); + assert.notEqual( + nextScroll.key, + oldScroll.key, + 'a completed reset must replace the old scroll data manager', + ); + } finally { + inbox.restore(); + if (originalWindow) { + Object.defineProperty(globalThis, 'window', originalWindow); + } else { + Reflect.deleteProperty(globalThis, 'window'); + } + } + }); + } +} + +void test('a superseded filter completion does not reset the current scroll instance', () => { + const inbox = inboxLifecycle(); + + try { + const before = inbox.render(); + const oldScroll = before.find( + (element) => element.type === InfiniteScroll, + ); + assert.ok(oldScroll); + const filter = before.find( + (element) => + element.type === 'a' && + element.props.href === '/notifications?type=replies', + ); + assert.ok(filter); + const click = filter.props.onClick as (event: unknown) => void; + click({ button: 0, preventDefault: () => {} }); + const superseded = inbox.visits.at(-1); + click({ button: 0, preventDefault: () => {} }); + + superseded?.onError?.({ notice: 'Earlier action failed' }); + assert.equal( + inbox.render().find((element) => element.type === InfiniteScroll) + ?.key, + oldScroll.key, + ); + } finally { + inbox.restore(); + } +}); + +void test('safe poll reconciliation preserves the rendered scroll instance', () => { + const inbox = inboxLifecycle(); + const originalDocument = Object.getOwnPropertyDescriptor( + globalThis, + 'document', + ); + Object.defineProperty(globalThis, 'document', { + configurable: true, + value: { querySelectorAll: () => [] }, + }); + + try { + const oldScroll = inbox + .render() + .find((element) => element.type === InfiniteScroll); + assert.ok(oldScroll); + inbox.sync({ + head: [notification], + boundary: { id: notification.id, group_id: notification.group_id }, + visible: [], + missing_visible_group_ids: [], + unread_notifications_count: 1, + }); + assert.equal( + inbox.render().find((element) => element.type === InfiniteScroll) + ?.key, + oldScroll.key, + ); + assert.equal(inbox.visits.length, 0); + } finally { + inbox.restore(); + if (originalDocument) { + Object.defineProperty(globalThis, 'document', originalDocument); + } else { + Reflect.deleteProperty(globalThis, 'document'); + } + } +}); From b4145a62f4eb87332860f1bacdd1c6663970cfee Mon Sep 17 00:00:00 2001 From: eas4ai Date: Fri, 16 Oct 2026 19:07:36 -0400 Subject: [PATCH 9/9] fix: check live notification scroll cursor before sync --- resources/js/lib/notification-sync.ts | 4 +- resources/js/pages/notification/index.tsx | 4 + tests/Unit/NotificationIndex.test.tsx | 133 +++++++++++++++++++++- tests/Unit/NotificationSync.test.ts | 31 +++++ 4 files changed, 169 insertions(+), 3 deletions(-) diff --git a/resources/js/lib/notification-sync.ts b/resources/js/lib/notification-sync.ts index 062fdb0111..baab8ee8b0 100644 --- a/resources/js/lib/notification-sync.ts +++ b/resources/js/lib/notification-sync.ts @@ -65,6 +65,7 @@ export function reconcileNotificationSync( current: CursorPaginated, sync: NotificationSyncResponse, refreshRequired = false, + scrollHasNext = false, ): { notifications: CursorPaginated; refreshRequired: boolean; @@ -88,7 +89,8 @@ export function reconcileNotificationSync( next_cursor: null, }, refreshRequired: false, - paginationResetRequired: current.next_cursor !== null, + paginationResetRequired: + current.next_cursor !== null || scrollHasNext, }; } diff --git a/resources/js/pages/notification/index.tsx b/resources/js/pages/notification/index.tsx index 901d048cf1..5d6a90cfe3 100644 --- a/resources/js/pages/notification/index.tsx +++ b/resources/js/pages/notification/index.tsx @@ -1,3 +1,4 @@ +import type { InfiniteScrollRef } from '@inertiajs/core'; import { Head, InfiniteScroll, Link, router } from '@inertiajs/react'; import { ArrowUp, @@ -165,6 +166,7 @@ export default function Index({ const pollAnchor = useRef(null); const filterVisit = useRef(0); const refreshRequiredRef = useRef(false); + const notificationScroll = useRef(null); const [arrivals, setArrivals] = useState(0); const [refreshRequired, setRefreshRequired] = useState(false); const [scrollReset, setScrollReset] = useState(0); @@ -242,6 +244,7 @@ export default function Index({ currentProps.notifications, response, refreshRequiredRef.current, + notificationScroll.current?.hasNext() ?? false, ); reconciliation = result; @@ -545,6 +548,7 @@ export default function Index({ <> , notifications: { data: [notification], - next_cursor: 'old-deep-cursor' as string | null, + next_cursor: nextCursor, prev_cursor: null, }, }; @@ -246,6 +247,34 @@ function inboxLifecycle() { render, visits, sync: (response: NotificationSyncResponse) => applySync(response, 0), + attachScroll: (handle: InfiniteScrollRef) => { + const ref = render().find( + (element) => element.type === InfiniteScroll, + )?.props.ref as React.RefObject | undefined; + + if (ref) { + ref.current = handle; + } + }, + appendFinalPage: () => { + props = { + ...props, + errors: { notice: 'Earlier action failed' }, + notifications: { + ...props.notifications, + data: [ + ...props.notifications.data, + { + ...notification, + id: 'last-row', + group_id: 'last-row', + }, + ], + next_cursor: null, + }, + }; + }, + currentProps: () => props, swap: (errors: Record, nextCursor: string | null) => { props = { ...props, @@ -426,3 +455,103 @@ void test('safe poll reconciliation preserves the rendered scroll instance', () } } }); + +void test('complete sync resets a live manager after an error-bearing final-page append', () => { + const inbox = inboxLifecycle(); + const originalDocument = Object.getOwnPropertyDescriptor( + globalThis, + 'document', + ); + Object.defineProperty(globalThis, 'document', { + configurable: true, + value: { querySelectorAll: () => [] }, + }); + + try { + // Inertia advances this token only on success, so an error-bearing + // append updates the paginator while this handle still reports true. + inbox.attachScroll({ + hasNext: () => true, + hasPrevious: () => false, + fetchNext: () => {}, + fetchPrevious: () => {}, + }); + inbox.appendFinalPage(); + const appended = inbox.currentProps().notifications; + assert.equal(appended.next_cursor, null); + assert.equal(appended.data.length, 2); + assert.notDeepEqual(inbox.currentProps().errors, {}); + + inbox.sync({ + head: [notification], + boundary: null, + visible: [], + missing_visible_group_ids: [], + unread_notifications_count: 0, + }); + + assert.equal( + inbox.visits.length, + 1, + 'a live scroll token requires a server-backed reset', + ); + assert.deepEqual(inbox.visits[0]?.reset, ['notifications']); + assert.equal(inbox.currentProps().notifications, appended); + } finally { + inbox.restore(); + if (originalDocument) { + Object.defineProperty(globalThis, 'document', originalDocument); + } else { + Reflect.deleteProperty(globalThis, 'document'); + } + } +}); + +void test('repeated complete polls keep an exhausted first-page scroll instance', () => { + const inbox = inboxLifecycle(null); + const originalDocument = Object.getOwnPropertyDescriptor( + globalThis, + 'document', + ); + Object.defineProperty(globalThis, 'document', { + configurable: true, + value: { querySelectorAll: () => [] }, + }); + + try { + inbox.attachScroll({ + hasNext: () => false, + hasPrevious: () => false, + fetchNext: () => {}, + fetchPrevious: () => {}, + }); + const oldScroll = inbox + .render() + .find((element) => element.type === InfiniteScroll); + assert.ok(oldScroll); + + for (let poll = 0; poll < 2; poll++) { + inbox.sync({ + head: [notification], + boundary: null, + visible: [], + missing_visible_group_ids: [], + unread_notifications_count: 0, + }); + } + + assert.equal(inbox.visits.length, 0); + assert.equal( + inbox.render().find((element) => element.type === InfiniteScroll) + ?.key, + oldScroll.key, + ); + } finally { + inbox.restore(); + if (originalDocument) { + Object.defineProperty(globalThis, 'document', originalDocument); + } else { + Reflect.deleteProperty(globalThis, 'document'); + } + } +}); diff --git a/tests/Unit/NotificationSync.test.ts b/tests/Unit/NotificationSync.test.ts index fbbe1efb89..1da24bb51c 100644 --- a/tests/Unit/NotificationSync.test.ts +++ b/tests/Unit/NotificationSync.test.ts @@ -143,6 +143,37 @@ void test('updates a complete paginator locally when its cursor is already exhau assert.equal(result.notifications.next_cursor, null); }); +void test('resets a live scroll cursor after error-bearing final-page props look exhausted', () => { + const current = page(sequence('loaded', 40), null); + const result = reconcileNotificationSync( + current, + response({ head: sequence('remaining', 4) }), + false, + true, + ); + + assert.equal(result.refreshRequired, false); + assert.equal(result.paginationResetRequired, true); +}); + +void test('does not repeatedly reset a complete first page with an exhausted scroll manager', () => { + const complete = response({ head: sequence('A', 4) }); + let current = page(complete.head, null); + + for (let poll = 0; poll < 2; poll++) { + const result = reconcileNotificationSync( + current, + complete, + false, + false, + ); + + assert.equal(result.refreshRequired, false); + assert.equal(result.paginationResetRequired, false); + current = result.notifications; + } +}); + void test('accepts an unchanged representative prefix with an unloaded boundary', () => { const head = sequence('A', 20); const result = reconcileNotificationSync(