Introducing a new way to review your PRs.

Read the announcement

immich-app / immich

High performance self-hosted photo and video management solution.

View on GitHub

21 documents · Updated Oct 19, 2026

docs / mobile-library-synchronization

Mobile library synchronization

The mobile library model gives one client view of media that exists on the device, on the server, or in both places. It joins local device discovery with server change sync, exposes that data through domain services and Riverpod state, and drives browsing and management views such as the timeline, albums, archive, trash, people, places, and search. For the wider client structure, see Mobile application architecture; for upload and device-copy behavior, see Mobile capture and backup, Sync and client state, and Native media core.

Library data model

Asset representation

An asset is the shared media concept used by the mobile library. BaseAsset describes common media facts such as name, type, dates, dimensions, duration, favorite state, and edit state. LocalAsset identifies a device item, while RemoteAsset identifies a server item. Either form can point to its counterpart so the client can treat one item as local, remote, or merged. AssetState is the client’s high-level answer to where the media is available.

The client uses checksums and available local or remote IDs to decide whether two records refer to the same media. This lets device media gain server identity after upload without changing the way views describe the item. Remote visibility also gives the library common states for timeline, hidden, archive, and locked media.

References: mobile/…/base_asset.model.dart• L6-85 mobile/…/local_asset.model.dart• L3-49 mobile/…/remote_asset.model.dart• L3-74

Album representation

Albums have two roles in the mobile library. LocalAlbum represents a device album and carries backup choice, device metadata, and an optional link to a server album. RemoteAlbum represents a server album and carries its owner, sharing state, order, description, thumbnail, and asset count. The two models stay separate because a device album is a source for media while a server album is a shared collection.

The local album model also records whether an album is selected, not selected, or excluded for backup. This choice affects how local media is protected and how server changes are applied back to the device. The relationship is described in more detail in Asset organization and discovery.

References: mobile/…/local_album.model.dart• L6-25 mobile/…/album.model.dart• L6-35 mobile/…/local_album.repository.dart• L112-135

Data service boundary

Domain services

Domain services are the boundary between library behavior and data access. The presentation layer asks services for assets, albums, timelines, or changes. Services then coordinate repositories and remote APIs so a user action updates the server and the local view together.

The main services have distinct responsibilities:

  • AssetService reads and watches local or remote assets. It coordinates asset edits, visibility, favorites, stacking, trash, restoration, deletion, local cleanup, and upload version links.
  • LocalAlbumService exposes device albums and their thumbnails.
  • RemoteAlbumService exposes server albums. It manages album metadata, members, assets, and the transition from local-only media to uploaded album media.
  • TimelineFactory creates a timeline for the main library or a focused source such as a local album, remote album, favorite set, archive, trash, person, place, search, or map.

This boundary keeps screens focused on user intent. It also gives local and server actions one place to maintain the client’s cached view.

References: mobile/…/asset.service.dart• L18-43 mobile/…/asset.service.dart• L92-219 mobile/…/local_album.service.dart• L5-28 mobile/…/remote_album.service.dart• L25-64 mobile/…/timeline.service.dart• L41-95

Repository roles

Repositories provide the durable library view used by the services. Local repositories read device media and album links. Remote repositories read server media, albums, metadata, stacks, and sharing links from the client’s local data store. API repositories perform server actions, while media and native repositories access the device library.

The repositories join local and remote records by checksum when an item has both forms. A read can therefore return a LocalAsset with a remote ID or a RemoteAsset with a local ID. Album repositories use the same split: local album links describe device membership, while remote album links describe server membership.

References: mobile/…/local_asset.repository.dart• L22-59 mobile/…/remote_asset.repository.dart• L16-45 mobile/…/local_album.repository.dart• L17-56 mobile/…/remote_album.repository.dart• L19-84

Synchronization flows

Device library synchronization

Device synchronization keeps the client’s local asset and album view aligned with the phone’s media library. The native platform reports either a full library state or a change set. LocalSyncService applies album changes, asset additions, updates, deletions, and membership changes to the local store. It preserves the user’s backup selection while refreshing device facts.

The process also handles platform differences. Android checks album membership to find removed media. iOS refreshes cloud-backed albums and resolves cloud IDs. On supported Android setups, local trash handling can move device media to or from the system trash when server trash state changes.

This diagram shows how device media becomes the local library view.

flowchart LR
    A[Device media library] --> B[Native change report]
    B --> C{Full or delta sync}
    C -->|Full| D[Compare device albums with local albums]
    C -->|Delta| E[Apply asset and album changes]
    D --> F[Local asset and album store]
    E --> F
    F --> G[Local library views and backup selection]

References: mobile/…/local_sync.service.dart• L23-126 mobile/…/local_sync.service.dart• L128-214 mobile/…/local_sync.service.dart• L263-352

Server library synchronization

Server synchronization keeps remote assets, albums, users, sharing, metadata, memories, stacks, people, and search-related data available offline in the client’s local store. Before it starts, SyncStreamService checks the server version and applies any required sync migration checkpoints. SyncApiRepository then requests the event formats supported by that server, reads the JSON-lines stream in batches, and converts each event into a typed change.

SyncStreamService groups adjacent changes by entity type and passes each group to SyncStreamRepository. The repository writes the current remote view, after which the service acknowledges the last event in the group. Asset upload and edit notifications can use the same repository path to refresh an asset and its related metadata without waiting for a later full stream.

The stream can request a reset when the server and client no longer share a valid starting point. A reset clears remote-derived data while keeping local device media and removes local links to deleted remote albums. The next stream rebuilds the remote view, which lets the rest of the mobile library continue to read one consistent local cache.

This diagram shows how server changes reach browsing state.

sequenceDiagram
    participant Server
    participant API as Sync API repository
    participant Stream as Sync stream service
    participant Store as Remote data store
    participant Views as Library services and state
    Server->>API: Version-aware change stream
    API->>Stream: Typed change batches
    Stream->>Store: Apply entity updates
    Store-->>Stream: Batch applied
    Stream->>API: Acknowledge batch
    API->>Server: Checkpoint
    Store-->>Views: Updated queries and streams
    Server-->>Stream: Reset request when needed
    Stream->>Store: Clear remote-derived state

References: mobile/…/sync_stream.service.dart• L59-105 mobile/…/sync_stream.service.dart• L107-190 mobile/…/sync_stream.service.dart• L192-337 mobile/…/sync_stream.service.dart• L340-505 mobile/…/sync_api.repository.dart• L19-142 mobile/…/sync_stream.repository.dart• L47-89

Local and server convergence

Local and server synchronization meet through asset identity rather than through one shared record type. A local asset starts with device identity and may later gain a checksum, cloud ID, or remote ID. A remote asset can gain a local ID when the same media is present on the device. The merged state lets browsing show one media item while management actions use the correct local or server operation.

Album operations use the same rule. Remote assets can enter an album at once. Local-only assets must first upload, then the new remote asset is linked to the album. The album view can show upload progress while the server and local store catch up. When a manual upload replaces an earlier server version, AssetService also tries to preserve the version relationship and records the new checksum as the local base.

References: mobile/…/base_asset.model.dart• L59-75 mobile/…/local_asset.repository.dart• L28-49 mobile/…/remote_asset.repository.dart• L22-37 mobile/…/asset.service.dart• L206-219 mobile/…/remote_album.service.dart• L15-52

Browsing state

Timeline state

The timeline is the main browsing surface for ordered media. A TimelineService exposes date buckets and loads asset ranges on demand. It keeps a small moving buffer around the visible range so scrolling can move through large libraries without loading the full result at once.

Riverpod creates a timeline service for the current timeline users and settings. The timeline widget turns bucket updates into grid segments, restores the visible asset after layout changes, and reloads when library data changes. The same service shape supports the main timeline and focused views such as albums, favorites, archive, trash, people, places, search, and map results. When bucket data changes, the service reloads its buffer before it publishes the new total and reload event, so a view does not read a new range from an old buffer.

References: mobile/…/timeline.service.dart• L41-95 mobile/…/timeline.service.dart• L97-190 mobile/…/timeline.provider.dart• L9-43 mobile/…/timeline.state.dart• L68-90 mobile/…/timeline.widget.dart• L192-203

Image resolution

Image resolution chooses the best available source for each asset in a browsing view. The image layer uses a device copy when the asset has one and the copy is allowed by the image preference. It uses the server source when the asset is remote-only, edited, or configured to prefer the server. Thumbnails and full images follow the same local-versus-remote identity rules.

Image loading can first reuse a synchronously available cached image, then load the requested source. Loading is cancellable because timeline cells can leave the screen before their request finishes. Each provider resolution keeps its own request state, and cancellation stops active work and evicts unfinished cache entries. A final load error also evicts its cache entry so a later view can retry instead of reusing a failed result.

References: mobile/…/image_provider.dart• L15-156 mobile/…/image_provider.dart• L159-229

Album state

Local albums are exposed as a stream because device changes can alter album names, counts, thumbnails, and membership. The library page uses that stream to show albums stored on the device.

Remote albums use a Riverpod notifier with a list state. The notifier refreshes the list, filters and sorts it for the album screen, and updates the list after create, edit, delete, or asset-link actions. It also refreshes one album after membership changes so counts and thumbnails change without waiting for a full list refresh.

References: mobile/…/album.provider.dart• L13-37 mobile/…/remote_album.provider.dart• L22-73 mobile/…/remote_album.provider.dart• L181-213 mobile/…/remote_album.provider.dart• L273-283

Memory state

Memories are server-backed collections that the mobile library reads from its local remote store. MemoryRepository joins each memory to its remote assets, keeps only active memories owned by the requested user, and limits the normal view to assets that are not deleted and remain visible in the timeline. It can also return saved memories and a single memory for focused browsing.

This filtering makes memory views follow the same remote asset visibility rules as the rest of the library. A memory can therefore remain in the local store while its deleted or hidden assets stay out of the user-facing collection.

References: mobile/…/memory.repository.dart• L15-59 mobile/…/memory.repository.dart• L61-90 mobile/…/sync_stream.repository.dart• L643-715

Search state and workflow

Search turns one user query into a filtered asset collection that uses the same timeline browsing surface as the rest of the library. SearchFilter can combine text, metadata, people, tags, location, camera, date, rating, media type, and display rules. The page keeps the active filter and the paginated result state in Riverpod.

The search service sends context or asset-linked queries to the smart-search path. Other searches use the metadata path. The repository maps the client filter to the server contract and preserves the selected timeline or archive visibility. Server feature flags choose whether context and OCR search are offered. User preferences control optional tag and rating controls.

When a filter changes, the page clears the old result set before it starts a new request. The notifier prevents overlapping requests, appends later pages, and exposes the current asset count to a timeline service. Scrolling near the end loads the next page. With no active filter, the page shows quick library links instead of an empty search grid.

This diagram shows how search results become a normal browsable asset view.

flowchart LR
    A[Search input and filter controls] --> B[SearchFilter]
    B --> C[Search service]
    C --> D{Query kind}
    D -->|Context or asset| E[Smart search API]
    D -->|Metadata and filters| F[Metadata search API]
    E --> G[Paginated asset state]
    F --> G
    G --> H[Search timeline]

References: mobile/…/search_filter.model.dart• L46-86 mobile/…/search.service.dart• L8-29 mobile/…/search_api.repository.dart• L7-94 mobile/…/paginated_search.provider.dart• L26-76 mobile/…/search.page.dart• L39-127 mobile/…/search.page.dart• L494-499 mobile/…/search.page.dart• L715-814

Library workflows

Library entry points

The library page is a navigation hub rather than a second copy of the timeline. It exposes actions for favorites, archive, shared links, and trash. It also links to people, places, device albums, memories, folders, the locked folder, partners, and partner-shared media.

Each entry point selects a timeline source or collection service. This keeps the browsing model consistent while changing the source query and the allowed management actions.

References: mobile/…/library.page.dart• L24-41 mobile/…/library.page.dart• L43-91 mobile/…/library.page.dart• L127-147 mobile/…/library.page.dart• L420-487

Asset management

Asset management separates server actions from device actions. The delete action first classifies the selection by local copy, owned remote asset, ownership, and trash state. Local-only media is removed from the device without a server call. A remote asset moves to server trash when that is available and the asset is not already trashed or locked. A permanent server delete is confirmed before it runs and removes the local copy only after the server request succeeds.

The same action can handle a merged asset as one user choice. It removes the device copy when local cleanup is part of the request, sends the server operation for owned remote media, and offers undo only for reversible trash operations. Device cleanup applies platform-specific confirmation rules, including Android version and media-management permission behavior.

The service updates the local remote view after a server action. This gives the user immediate feedback while the next server sync remains the source of any later correction. Restore, stack, metadata, edit, and local-delete operations follow the same service boundary: the server or device operation completes first, then the matching local view is updated.

References: mobile/…/delete.action.dart• L19-99 mobile/…/delete.action.dart• L102-163 mobile/…/delete.action.dart• L166-272 mobile/…/asset.service.dart• L92-195 mobile/…/asset.provider.dart• L8-18

Album management

Album management supports server album creation, editing, deletion, sharing, activity settings, ordering, and asset membership. A selection can contain remote assets, local assets that already have a server identity, and local-only assets. The service handles these groups as one user action while keeping their required paths separate.

When a local-only item is added to a server album, the client queues it for upload and reports progress. After upload, it links the new server asset to the album and refreshes the album state. This allows the user to manage a mixed library without first sorting media into separate local and remote workflows.

References: mobile/…/remote_album.service.dart• L118-208 mobile/…/remote_album.service.dart• L211-285 mobile/…/remote_album.provider.dart• L216-270

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep local and remote asset identity rules aligned. Changes to checksum, local ID, remote ID, or cloud ID mapping can turn one media item into two visible items.
  • Keep local album backup selection separate from device album refresh. A full device refresh must not erase the user’s backup choice.
  • Keep sync entity handling aligned with the repository writes and the model fields used by timeline, album, people, memory, and search queries.
  • Keep server capability checks aligned across requested stream types, event parsers, and event handlers. A new server event version needs support at each boundary.
  • Keep sync migration checkpoints aligned with the acknowledgements that must be cleared before a changed payload is rebuilt.
  • Keep album membership updates consistent with upload completion. A newly uploaded asset needs a remote row before the album link can appear in local queries.
  • Keep timeline bucket changes and timeline reload events aligned. A store update without a matching reload can leave the visible grid stale. A new total must not become visible before its buffer is ready.
  • Keep image source choice aligned with asset identity and edit state. A merged or edited asset can require a remote image even when a device copy exists.
  • Keep image loader state separate for each provider resolution. A canceled cell must not cancel a later load that uses the same cache key.
  • Keep delete classification aligned with ownership, trash, locked-folder state, and local-copy cleanup. A mixed selection must not apply a server action to another user’s asset or remove a device copy before a required server delete succeeds.
  • Keep Android media permission and version rules aligned with the user prompt. A change can make device cleanup silent when confirmation is required or block cleanup that should proceed.
  • Keep asset and album enum orders stable when their values cross the native platform or generated API boundary.
  • Keep search query routing aligned with the filter model. Context and asset-linked searches use the smart-search contract, while other filters use the metadata contract.
  • Clear paginated search results whenever the active filter changes. Otherwise, results from different queries can appear in one timeline.
  • Keep search page feature and preference checks aligned with the filters sent to the server. A hidden control must not be the only way to prevent an unsupported search field from being used.

Important failure modes

TriggerConsequenceGuard
A local and remote copy cannot be matched by ID or checksumOne media item can appear as separate local and remote itemsPreserve the identity fields and matching rules in BaseAsset and both asset repositories
The requested sync event version does not match the server capabilityA supported change can be skipped or fail before it reaches the local storeSelect request types and parsers from the negotiated server version
A server change batch is written but not acknowledgedThe server can send the same batch again and the client can repeat workApply the batch before acknowledging its last checkpoint
A sync reset leaves old remote rows or local album linksBrowsing can show stale albums, assets, or dangling local-to-remote linksClear remote-derived data and null linked remote album IDs before rebuilding the stream
A device delta omits an old album link after an asset moveA later delete sweep can remove media that still exists in its new albumReplace changed asset-to-album links before applying per-album deletes
A local-only asset is linked to a remote album before upload completesThe album can contain a missing remote asset or fail its local database linkUpload first, create the remote placeholder when needed, then link the asset
A remote trash event arrives without device media permissionLocal media cannot be moved or restored to match server trashCheck platform permission before applying device trash changes
A delete action treats another user’s remote asset as ownedA mixed selection can show the wrong action or send an invalid server requestBuild remote IDs from assets owned by the current user
A permanent server delete fails after local cleanupThe server copy remains while the device copy is goneComplete the server delete before removing the local copy
A timeline count changes before its asset buffer is refreshedThe grid can request a range against stale offsets or show the wrong itemsReload the buffer under the service mutex before publishing the new count and reload event
A canceled or failed image request remains in the image cacheA timeline cell can show stale or failed media on a later requestKeep load state per resolution and evict unfinished or final failed providers
A memory keeps links to assets that no longer meet visibility rulesA memory can show deleted or hidden media, or an empty result can be misread as missing memory dataJoin memories through active timeline-visible remote assets
A search filter is sent through the wrong server search contractThe query can lose fields or return results that do not match the user’s intentRoute context and asset-linked filters to smart search and other filters to metadata search
A new search starts without clearing the prior pagesThe result grid can mix assets from two filtersReset the paginated notifier before loading the new filter
A search page starts overlapping page requestsResults can be duplicated or the loading state can move backwardAllow one request at a time and stop when the server returns no next page
An edited upload cannot stack with its previous server versionThe new upload loses its version relation even though the upload succeededRecord the uploaded checksum in the local base state even when the stack request fails

Key files

FileWhy to read it
mobile/lib/domain/models/asset/base_asset.model.dartDefines the shared asset view and local, remote, and merged storage states.
mobile/lib/domain/models/asset/local_asset.model.dartShows the identity and device metadata carried by local media.
mobile/lib/domain/models/asset/remote_asset.model.dartShows server visibility, ownership, stacks, trash, and local linkage.
mobile/lib/domain/models/album/local_album.model.dartDefines device album state and backup selection.
mobile/lib/domain/models/album/album.model.dartDefines server album state, sharing, order, and counts.
mobile/lib/domain/services/local_sync.service.dartExplains how device album and asset changes become local library state.
mobile/lib/domain/services/sync_stream.service.dartExplains server-version checks, sync migrations, event routing, reset behavior, and device trash effects from remote changes.
mobile/lib/infrastructure/repositories/sync_api.repository.dartExplains the version-aware server stream, JSON-lines parsing, batching, and acknowledgements.
mobile/lib/infrastructure/repositories/sync_stream.repository.dartShows the remote data updates and reset behavior that support the domain model.
mobile/lib/infrastructure/repositories/memory.repository.dartShows how synced memories become filtered collections of visible remote assets.
mobile/lib/domain/services/asset.service.dartExplains how server asset actions, device cleanup, and edited-upload version links update the local view.
mobile/lib/domain/services/remote_album.service.dartExplains album actions and mixed local/server asset handling.
mobile/lib/domain/services/timeline.service.dartExplains the common browsing source, range buffer, and reload behavior for the main library and focused views.
mobile/lib/presentation/actions/delete.action.dartShows how mixed local and remote selections become trash, permanent delete, or device cleanup actions.
mobile/lib/presentation/widgets/images/image_provider.dartShows how browsing selects local or remote image sources and isolates or cancels unused loads.
mobile/lib/presentation/pages/library.page.dartShows the user-facing library entry points and collection choices.
mobile/lib/presentation/widgets/timeline/timeline.widget.dartShows how timeline state becomes the browsable media grid.
mobile/lib/providers/infrastructure/remote_album.provider.dartShows how album actions update presentation state.
mobile/lib/models/search/search_filter.model.dartDefines the user-facing search dimensions and empty-filter behavior.
mobile/lib/domain/services/search.service.dartConnects search results from the API boundary to mobile asset state.
mobile/lib/infrastructure/repositories/search_api.repository.dartShows how filters select the smart-search or metadata-search server contract.
mobile/lib/presentation/pages/search/paginated_search.provider.dartHolds paginated search results and the count used by the search timeline.
mobile/lib/presentation/pages/search/search.page.dartShows search controls, feature-aware modes, result loading, and timeline presentation.