Skip to content

Add albums to tag albums and person albums - #4626

Open
ildyria wants to merge 3 commits into
masterfrom
smart-person-albums-listing
Open

Add albums to tag albums and person albums#4626
ildyria wants to merge 3 commits into
masterfrom
smart-person-albums-listing

Conversation

@ildyria

@ildyria ildyria commented Aug 16, 2026

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • New Features

    • Tag Albums and Person Albums can display matching real albums alongside photos.
    • Matching results support pagination, sorting, access controls, and AND/OR person criteria.
    • Added settings to enable or disable these album listings.
  • Bug Fixes

    • Album listings and related album information now refresh correctly after photo moves, deletions, merges, tag changes, and face updates.
    • Improved matching accuracy for visibility, sensitivity, and dismissed face data.
  • Documentation

    • Added translated settings descriptions across supported languages.
  • Tests

    • Added coverage for matching, pagination, access, configuration, caching, and empty results.

@ildyria
ildyria requested a review from a team as a code owner August 16, 2026 18:44
@coderabbitai

coderabbitai Bot commented Aug 16, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Changes

The pull request adds cached, paginated real-album listings for Tag Albums and Person Albums. It centralizes person matching, adds configuration and translations, loads matching albums in the client, batches photo events, and invalidates related caches after photo changes.

Matching album listings

Layer / File(s) Summary
Matching queries and album endpoint
app/Services/PersonAlbumMatcher.php, app/Repositories/AlbumRepository.php, app/Http/Requests/Album/GetAlbumChildrenRequest.php, app/Http/Controllers/Gallery/AlbumChildrenController.php, app/Http/Resources/Collections/PaginatedAlbumsResource.php, app/Relations/HasManyPhotosByPerson.php, app/Services/Cache/CacheKeyProvider.php, resources/js/stores/AlbumState.ts
Tag and person albums now return cached, paginated matching real albums. Person matching applies visibility, searchability, sensitivity, unlocked-album, dismissed-face, and AND/OR criteria.
Configuration, settings, and validation
database/migrations/2026_08_16_000005_add_matching_albums_listing_config.php, lang/*/all_settings.php, tests/Feature_v2/Album/AlbumMatchingAlbumsTest.php, tests/Unit/Repositories/AlbumRepositoryTest.php
Two settings control matching-album listings. Translations describe both settings. Tests cover matching, pagination, access rules, disabled settings, AND semantics, empty results, and cache behavior.

Album listing cache invalidation

Layer / File(s) Summary
Batched photo event contracts and dispatch
app/Events/PhotoPersonsChanged.php, app/Events/PhotoSaved.php, app/Events/PhotoMoved.php, app/Http/Controllers/AiVision/FaceController.php, app/Actions/Album/Merge.php, app/Actions/Photo/MoveOrDuplicate.php, app/Actions/Photo/Pipes/Shared/SetParent.php, app/Http/Controllers/Admin/Maintenance/GenSizeVariants.php, app/Http/Controllers/Admin/Maintenance/MissingFileSizes.php, app/DTO/Delete/PhotosToBeDeletedDTO.php
PhotoSaved and PhotoMoved now carry photo ID arrays. Photo person-change events carry affected person IDs. Photo mutations dispatch batched events after changes.
Cache invalidation and album updates
app/Listeners/ManagedCacheAlbumListingInvalidator.php, app/Listeners/RecomputeAlbumSizeOnPhotoMutation.php, app/Listeners/RecomputeAlbumStatsOnPhotoChange.php, app/Listeners/RecomputeAlbumUserThumbsOnPhotoChange.php, app/Listeners/WebhookListener.php, app/Providers/EventServiceProvider.php
Listeners invalidate person-album cache tags and process batched photo IDs for album size, statistics, thumbnails, and webhooks.
Batched event test updates
tests/Precomputing/CoverSelection/EventListenersTest.php, tests/Precomputing/CoverSelection/EventPropagationIntegrationTest.php, tests/Precomputing/SizeComputations/AlbumSizeEventListenerTest.php, tests/Unit/Listeners/WebhookListenerTest.php
Tests now construct PhotoSaved and PhotoMoved with batched photo ID payloads.

Estimated code review effort: 4 (Complex) | ~60 minutes

Merge Risk: 🟡 Moderate · up to ae9df

Album listings can remain stale after root moves, tag criteria changes, or maintenance failures, causing users to see removed or outdated matching albums. The PR should not merge until these cache-invalidation paths are corrected or explicitly accepted by the owner.

Poem

A rabbit checks each album page,
Tags and faces hop through every stage.
Batched events tell caches when to roam,
Fresh album results find their home.
Carrots celebrate the updated code.

🚥 Pre-merge checks | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 55.22% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (4)
app/Services/PersonAlbumMatcher.php (1)

114-132: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Drop the by-reference parameter and the unused sub-select list.

Builder is an object. PHP passes the handle by value, so &$query has no effect and the docblock @param Builder &$query is misleading. In the whereExists sub-query the selected columns are ignored by the database; COUNT(DISTINCT person_id) AS num is never read.

♻️ Proposed refactor
-	private function getPhotoIdsWithPersons(Builder &$query, array $person_ids, bool $is_and): void
+	private function getPhotoIdsWithPersons(Builder $query, array $person_ids, bool $is_and): void
 	{
@@
 			$query->whereExists(
-				fn (BaseBuilder $q) => $q->select(['photo_id', DB::raw('COUNT(DISTINCT person_id) AS num')])
+				fn (BaseBuilder $q) => $q->selectRaw('1')
 					->from('faces')
app/Repositories/AlbumRepository.php (2)

159-188: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Confirm the AND path scales with the number of criteria tags.

Each required tag adds one correlated whereHas('tags', ...) subquery. For a TagAlbum with many criteria tags this produces one EXISTS per tag on every page load. An alternative is a single whereHas('tags', fn ($q) => $q->whereIn('tags.id', $tag_ids), '=', count($tag_ids)) which uses one subquery with a count constraint. Verify which form your target databases plan better before changing it.


244-268: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Type the whereExists closure parameter.

fn ($q) => ... has no type hint, unlike the other closures in this file. Add \Illuminate\Database\Query\Builder $q so PHPStan level 6 keeps the inference and the code matches the surrounding style.

tests/Unit/Repositories/AlbumRepositoryTest.php (1)

356-384: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a cache-hit test for the person variant.

The tag variant has testGetMatchingAlbumsForTagPaginatedCacheHitPerformsNoAlbumsTableQueries. The person variant has no equivalent. The person path builds a different cache key and a different tag set, so it can regress independently.

💚 Proposed test
public function testGetMatchingAlbumsForPersonPaginatedCacheHitPerformsNoAlbumsTableQueries(): void
{
	$person = Person::factory()->create(['is_searchable' => true]);
	$photo = Photo::factory()->owned_by($this->user)->in($this->parentAlbum)->create();
	Face::factory()->for_photo($photo)->for_person($person)->create();

	$this->actingAs($this->user);
	$personAlbum = resolve(CreatePersonAlbum::class)->create('person_album', [$person->id], false);
	$this->repository->getMatchingAlbumsForPersonPaginated($personAlbum, 10);

	$second_call_count = $this->countAlbumTableQueries(
		fn () => $this->repository->getMatchingAlbumsForPersonPaginated($personAlbum, 10)
	);

	$this->assertSame(0, $second_call_count, 'A cache hit must not run any query against albums/base_albums.');
}

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f94644ef-4cd2-4517-8b50-eaefec178fb9

📥 Commits

Reviewing files that changed from the base of the PR and between 9f5efec and 108b7b4.

📒 Files selected for processing (41)
  • app/Actions/Album/Merge.php
  • app/Actions/Photo/MoveOrDuplicate.php
  • app/DTO/Delete/PhotosToBeDeletedDTO.php
  • app/Events/PhotoPersonsChanged.php
  • app/Http/Controllers/AiVision/FaceController.php
  • app/Http/Controllers/Gallery/AlbumChildrenController.php
  • app/Http/Requests/Album/GetAlbumChildrenRequest.php
  • app/Http/Resources/Collections/PaginatedAlbumsResource.php
  • app/Listeners/ManagedCacheAlbumListingInvalidator.php
  • app/Providers/EventServiceProvider.php
  • app/Relations/HasManyPhotosByPerson.php
  • app/Repositories/AlbumRepository.php
  • app/Services/Cache/CacheKeyProvider.php
  • app/Services/PersonAlbumMatcher.php
  • database/migrations/2026_08_16_000005_add_matching_albums_listing_config.php
  • lang/ar/all_settings.php
  • lang/bg/all_settings.php
  • lang/cz/all_settings.php
  • lang/de/all_settings.php
  • lang/el/all_settings.php
  • lang/en/all_settings.php
  • lang/es/all_settings.php
  • lang/fa/all_settings.php
  • lang/fr/all_settings.php
  • lang/hu/all_settings.php
  • lang/it/all_settings.php
  • lang/ja/all_settings.php
  • lang/nl/all_settings.php
  • lang/no/all_settings.php
  • lang/pl/all_settings.php
  • lang/pt/all_settings.php
  • lang/ru/all_settings.php
  • lang/sk/all_settings.php
  • lang/sv/all_settings.php
  • lang/tr/all_settings.php
  • lang/vi/all_settings.php
  • lang/zh_CN/all_settings.php
  • lang/zh_TW/all_settings.php
  • resources/js/stores/AlbumState.ts
  • tests/Feature_v2/Album/AlbumMatchingAlbumsTest.php
  • tests/Unit/Repositories/AlbumRepositoryTest.php

Included review availability: Your plan includes up to 8 reviews per rolling hour; 7 remain after this review.

Comment thread app/Actions/Photo/MoveOrDuplicate.php Outdated
Comment on lines +79 to +87
// Dispatch PhotoSaved for every photo that gained this album link
// (covers both cross-album move and the same-album "copy" case,
// i.e. CopyPhotosRequest, where $from_album === $to_album and
// PhotoMoved below never fires) so listeners depending on a
// photo's containing albums (e.g. the TagAlbum/PersonAlbum
// "matching albums" cache) are notified either way.
foreach ($photos_ids as $photo_id) {
PhotoSaved::dispatch($photo_id);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Invalidate person-album caches when a photo moves to the root.

If $from_album !== null and $to_album === null, the code removes the source pivot row but does not dispatch PhotoSaved. It also does not dispatch PhotoMoved. PhotoDeleted has no managed-cache invalidator registration in app/Providers/EventServiceProvider.php.

Cached matching albums can retain the source album for persons on the moved photo. Dispatch an invalidating event after any album-link mutation, including a move to the root. Add a regression test for this path.

Proposed fix
 		if ($to_album !== null) {
 			// Add the new links.
 			DB::table(PA::PHOTO_ALBUM)->insert(array_map(fn (string $id) => ['photo_id' => $id, 'album_id' => $to_album->id], $photos_ids));

 			// Dispatch event for destination album (photos added)
 			AlbumSaved::dispatch([$to_album->id], [$to_album->parent_id]);
-
-			foreach ($photos_ids as $photo_id) {
-				PhotoSaved::dispatch($photo_id);
-			}
 		}
 
+		if ($from_album !== null || $to_album !== null) {
+			foreach ($photos_ids as $photo_id) {
+				PhotoSaved::dispatch($photo_id);
+			}
+		}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Dispatch PhotoSaved for every photo that gained this album link
// (covers both cross-album move and the same-album "copy" case,
// i.e. CopyPhotosRequest, where $from_album === $to_album and
// PhotoMoved below never fires) so listeners depending on a
// photo's containing albums (e.g. the TagAlbum/PersonAlbum
// "matching albums" cache) are notified either way.
foreach ($photos_ids as $photo_id) {
PhotoSaved::dispatch($photo_id);
}
if ($to_album !== null) {
// Add the new links.
DB::table(PA::PHOTO_ALBUM)->insert(array_map(fn (string $id) => ['photo_id' => $id, 'album_id' => $to_album->id], $photos_ids));
// Dispatch event for destination album (photos added)
AlbumSaved::dispatch([$to_album->id], [$to_album->parent_id]);
}
if ($from_album !== null || $to_album !== null) {
// Dispatch PhotoSaved for every photo whose album links changed.
foreach ($photos_ids as $photo_id) {
PhotoSaved::dispatch($photo_id);
}
}

Comment on lines +133 to +137
$tags = [
...$this->cache_key_provider->albumTagTags($tag_ids),
$this->cache_key_provider->userTag($user_id),
$this->cache_key_provider->albumListingGlobalTag(),
];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Matching-albums cache entries omit the owning album's cache tag. Both new cached listings are tagged with criteria tags, the user tag, and the global listing tag, but not with albumTag() of the TagAlbum/PersonAlbum itself. ManagedCacheAlbumListingInvalidator::handleTagAlbumSaved() and handlePersonAlbumSaved() evict exactly that missing tag, so a criteria edit on the smart album leaves the stale page in the cache.

  • app/Repositories/AlbumRepository.php#L133-L137: add $this->cache_key_provider->albumTag($tag_album->id) to the $tags array.
  • app/Repositories/AlbumRepository.php#L219-L223: add $this->cache_key_provider->albumTag($person_album->id) to the $tags array.
📍 Affects 1 file
  • app/Repositories/AlbumRepository.php#L133-L137 (this comment)
  • app/Repositories/AlbumRepository.php#L219-L223

Comment on lines +83 to +102
if ($this->config_manager->getValueAsBool('PA_override_visibility')) {
$this->photo_query_policy
->applySensitivityFilter(
query: $ids_query,
user: $user,
origin: null,
include_nsfw: !$this->config_manager->getValueAsBool('hide_nsfw_in_person_albums')
)
->where(fn (Builder $q) => $this->getPhotoIdsWithPersons($q, $person_ids, $album->is_and));
} else {
$this->photo_query_policy
->applySearchabilityFilter(
query: $ids_query,
user: $user,
unlocked_album_ids: $unlocked_album_ids,
origin: null,
include_nsfw: !$this->config_manager->getValueAsBool('hide_nsfw_in_person_albums')
)
->where(fn (Builder $q) => $this->getPhotoIdsWithPersons($q, $person_ids, $album->is_and));
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Remove the duplicated predicate from both branches.

Both branches append the identical ->where(fn (Builder $q) => $this->getPhotoIdsWithPersons(...)) clause. The coding guidelines forbid duplicate code in both the if and else statements. Apply the person predicate once after the visibility filter.

As per coding guidelines: "Avoid code duplication in both if and else statements".

♻️ Proposed refactor
 		if ($this->config_manager->getValueAsBool('PA_override_visibility')) {
 			$this->photo_query_policy
 				->applySensitivityFilter(
 					query: $ids_query,
 					user: $user,
 					origin: null,
 					include_nsfw: !$this->config_manager->getValueAsBool('hide_nsfw_in_person_albums')
-				)
-				->where(fn (Builder $q) => $this->getPhotoIdsWithPersons($q, $person_ids, $album->is_and));
+				);
 		} else {
 			$this->photo_query_policy
 				->applySearchabilityFilter(
 					query: $ids_query,
 					user: $user,
 					unlocked_album_ids: $unlocked_album_ids,
 					origin: null,
 					include_nsfw: !$this->config_manager->getValueAsBool('hide_nsfw_in_person_albums')
-				)
-				->where(fn (Builder $q) => $this->getPhotoIdsWithPersons($q, $person_ids, $album->is_and));
+				);
 		}
+
+		$ids_query->where(fn (Builder $q) => $this->getPhotoIdsWithPersons($q, $person_ids, $album->is_and));
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if ($this->config_manager->getValueAsBool('PA_override_visibility')) {
$this->photo_query_policy
->applySensitivityFilter(
query: $ids_query,
user: $user,
origin: null,
include_nsfw: !$this->config_manager->getValueAsBool('hide_nsfw_in_person_albums')
)
->where(fn (Builder $q) => $this->getPhotoIdsWithPersons($q, $person_ids, $album->is_and));
} else {
$this->photo_query_policy
->applySearchabilityFilter(
query: $ids_query,
user: $user,
unlocked_album_ids: $unlocked_album_ids,
origin: null,
include_nsfw: !$this->config_manager->getValueAsBool('hide_nsfw_in_person_albums')
)
->where(fn (Builder $q) => $this->getPhotoIdsWithPersons($q, $person_ids, $album->is_and));
}
if ($this->config_manager->getValueAsBool('PA_override_visibility')) {
$this->photo_query_policy
->applySensitivityFilter(
query: $ids_query,
user: $user,
origin: null,
include_nsfw: !$this->config_manager->getValueAsBool('hide_nsfw_in_person_albums')
);
} else {
$this->photo_query_policy
->applySearchabilityFilter(
query: $ids_query,
user: $user,
unlocked_album_ids: $unlocked_album_ids,
origin: null,
include_nsfw: !$this->config_manager->getValueAsBool('hide_nsfw_in_person_albums')
);
}
$ids_query->where(fn (Builder $q) => $this->getPhotoIdsWithPersons($q, $person_ids, $album->is_and));

Source: Coding guidelines

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
app/Listeners/WebhookListener.php (1)

57-62: 🚀 Performance & Scalability | 🔵 Trivial | 🏗️ Heavy lift

Batch move-event handling and regression coverage should be tightened. handlePhotoMoved() currently reloads enabled webhooks and photo relations once per photo ID, creating repeated queries for large batches. Reuse the batch-level webhook collection and batch-load photos before constructing per-photo payloads. Add multi-ID regression coverage for overlapping memberships, empty batches, inactive webhooks, and one dispatch per photo ID.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: fc0f06c4-baad-483c-88e0-603cc5c30200

📥 Commits

Reviewing files that changed from the base of the PR and between 108b7b4 and ae9dfcf.

📒 Files selected for processing (16)
  • app/Actions/Album/Merge.php
  • app/Actions/Photo/MoveOrDuplicate.php
  • app/Actions/Photo/Pipes/Shared/SetParent.php
  • app/Events/PhotoMoved.php
  • app/Events/PhotoSaved.php
  • app/Http/Controllers/Admin/Maintenance/GenSizeVariants.php
  • app/Http/Controllers/Admin/Maintenance/MissingFileSizes.php
  • app/Listeners/ManagedCacheAlbumListingInvalidator.php
  • app/Listeners/RecomputeAlbumSizeOnPhotoMutation.php
  • app/Listeners/RecomputeAlbumStatsOnPhotoChange.php
  • app/Listeners/RecomputeAlbumUserThumbsOnPhotoChange.php
  • app/Listeners/WebhookListener.php
  • tests/Precomputing/CoverSelection/EventListenersTest.php
  • tests/Precomputing/CoverSelection/EventPropagationIntegrationTest.php
  • tests/Precomputing/SizeComputations/AlbumSizeEventListenerTest.php
  • tests/Unit/Listeners/WebhookListenerTest.php
🚧 Files skipped from review as they are similar to previous changes (2)
  • app/Actions/Album/Merge.php
  • app/Listeners/ManagedCacheAlbumListingInvalidator.php

Included review availability: Your plan includes up to 8 reviews per rolling hour; 6 remain after this review.

Comment thread app/Http/Controllers/Admin/Maintenance/GenSizeVariants.php
@codecov

codecov Bot commented Aug 16, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.07048% with 18 lines in your changes missing coverage. Please review.
✅ Project coverage is 91.13%. Comparing base (a203d75) to head (ae9dfcf).
⚠️ Report is 2 commits behind head on master.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant