Frontend
The frontend is a React 18 single-page app, written in TypeScript and built with Vite. Mantine provides the UI components, TanStack Router handles routing, and TanStack Query handles server state.
The full tech stack, the development commands (yarn start, yarn test, yarn build) and the code
style conventions are documented in
apps/frontend/README.md,
which lives next to the code. Please read that first — this page only covers what it does not:
debugging, and how the source tree is laid out.
✨ Code Standards
We use ESLint and Prettier to keep our code tidy. Before you commit, run yarn lint:error to check
your changes and yarn lint:error:fix to apply the automatic fixes — the ESLint config enforces
Prettier through the prettier/prettier rule, so linting also flags unformatted code. The
lint-frontend CI workflow runs the lint, test and build steps on every pull request that touches
apps/frontend and fails on anything unclean, so nothing un-linted gets merged.
yarn build does not type-check, so run yarn typecheck as well. It runs tsc --noEmit over the app
and vite.config.ts. The frontend has zero type errors and no baseline: any error fails it, and so
does the typecheck-frontend CI workflow. Fix the type rather than working around it.
The repository ships a husky pre-commit hook (apps/frontend/.husky/pre-commit, which runs
lint-staged), but it is currently inactive in the monorepo: yarn install runs the prepare
script — husky — with the working directory set to apps/frontend, which has no .git of
its own, so husky exits without registering the hook. Don't rely on it; lint before you commit.
🎨 Colours and surfaces
The web app has one accent colour and a small set of surfaces, and two lint rules keep it that way.
Colours name a role, not a hue. A colour prop (c, color, bg, iconColor, ...) takes no colour or brand for the
primary accent, gray, dark or dimmed for neutral, red for danger, orange for a warning and green for
success. CSS uses var(--mantine-primary-color-*) for the primary. The theme (src/theme/cssVariables.ts) keeps the roles readable in both
schemes: outline buttons in the dark scheme use shade 3 of their colour, and warning and gray text in the light scheme
use darker inks that pass WCAG AA on white and on their tints. Mantine's other palette names (blue, cyan,
grape, indigo, lime, pink, teal, violet, yellow) are decoration with no meaning, and stock blue is not
the app's accent. ban/palette-color fails on them in props, colour maps, returned colour names, union types and
--mantine-color-<hue>-* strings, and src/architecture/styles.test.ts counts them in CSS modules. A colour that
really is not a role, such as the histogram's red, green and blue channels or the favourite star, is a named
--app-* variable in src/theme/colors.css, the one place allowed to use the palette directly.
Surfaces come from components/common/surfaces. Only that folder imports Mantine's Card and Paper
(ban/raw-surface), so border, radius and shadow are decided once:
| Surface | Use it for | Look |
|---|---|---|
ContentCard | a block of a page (SettingsCard builds on it) | border, large radius, no shadow |
Panel | a box inside a card or dialog | border, medium radius, no shadow |
FloatingCard | a card over the page: the upload and What's new cards, map popups, the sign-in card | border, large radius, extra-large shadow, a raised background in the dark scheme so it sits above the page cards |
MediaCard | a card with a photo that runs to its edges (MediaCard.Section) | border, medium radius, no shadow |
Their props leave out radius, shadow and withBorder, so a page cannot restyle one. A new kind of surface is a
new component in that folder.
Settings page
Noch nicht erschienen (kommt nach 1.7.0) The user's settings (components/settings/Settings.tsx) are five areas, each a SettingsArea. An area shows
what an ordinary person changes. Everything else goes into its advanced part, which is closed at first and not rendered until it opens.
- A new option goes into the
advancedpart unless most people would look for it. Its label says in plain words what it does, and one sentence says what changes for the photos. - Deep links: give the card a
SettingsSectionwith an id fromsectionIds.tsand list the id in the area'ssections.useAdvancedPartopens the part when the address points at one of them. Ids are never renamed, people have saved links to them. - Search: add the card to
components/spotlight/settingsActions.ts, with the same section. - "Different from the standard": add the field to
UserSettingDefaultsSerializer(GET /api/user-setting-defaults/), toUserSettingDefaultsin the API client and tochangedSettings.ts. The server's model defaults are the only list of standards, so the line cannot disagree with them.
🧪 End-to-end tests
apps/frontend/e2e holds a Playwright smoke suite: log in, the timeline
shows photos, the lightbox opens, a favorite toggles and persists, log out. It has its own
package.json, separate from the app's. The e2e workflow runs it nightly, on demand, and on pull
requests labelled e2e, and uploads the Playwright report, traces and container logs when it fails.
Against the Docker e2e stack (what CI does). deploy/compose/docker-compose.e2e.yml builds the
proxy, frontend and backend from your checkout, creates admin/admin and scans the eight sample
photos in deploy/e2e/photos:
docker compose -f deploy/compose/docker-compose.e2e.yml up -d --build --wait
cd apps/frontend/e2e
yarn install
yarn playwright install chromium
yarn test # or `yarn test:ui` for the interactive runner
docker compose -f ../../../deploy/compose/docker-compose.e2e.yml down -v
Against a native stack (no Docker, see
Native Windows Setup). Use a fresh
data directory and an admin/admin account, copy deploy/e2e/photos to <DataDir>\data\e2e (it
has to be inside the backend's data root), then point the suite at the Vite dev server and that folder:
$env:E2E_BASE_URL = "http://localhost:3000"
$env:E2E_SCAN_DIR = "C:\librephotos-devdata\data\e2e"
yarn test
The setup step sets the admin's scan directory and starts a scan when the account has no photos yet.
A scan started this way first downloads the ML models (about 1.3 GB, once). The specs expect exactly
the sample library, so run them against an account with no other photos. E2E_USERNAME and
E2E_PASSWORD override the credentials.
The suite runs as an admin who already answered the one-time dialogs, so none of them covers the page under test: the e2e stack's entrypoint marks the thank-you dialog seen and the error reporting question answered before it scans, and the setup step does the same through the API on any other backend (on a server without the ML models, answering the question there starts their download). Every click and fill gives up after 15 seconds, so a selector that no longer matches fails at once with its locator instead of after the setup's 15-minute budget.
Docs screenshots
Neu in 1.5.0 The same package takes the screenshots of this site and of the release
posts. yarn screens takes every shot listed in e2e/screens/manifest.ts in the light and the dark
theme, at 1600 × 1000 and, for the shots marked phone, on a Pixel 7. It writes
<id>-<theme>.webp and <id>-phone-<theme>.webp into apps/docs/static/img/shots/ and
regenerates manifest.json there, which the <Screenshot id="..." /> component and the release
check read. It logs in like the smoke suite, so the same variables apply:
cd apps/frontend/e2e
E2E_BASE_URL=http://localhost:8080 yarn screens
SHOTS=timeline,lightbox yarn screens # only these shot ids
SHOTS_DIR=/tmp/shots yarn screens # somewhere else, to look before you replace the docs files
yarn screens:unit # the helpers, without a running LibrePhotos
- Each shot waits for its screen, for the pictures and map tiles in view, and for the page to stop changing. A new shot that looks like the file it would replace (at most 0.2 % of the pixels changed) keeps the old file, so a second run changes nothing. The run says per file whether it kept or wrote it, and how much changed.
- Shots are WebP at quality 80, or at 70 or 60 when that is what it takes to fit the budget: a desktop shot over 200 KB or a phone shot over 120 KB even at 60 fails its test.
- The browser clock and the Memories strip are fixed to
SHOTS_DAY(default2026-05-12), so the memories are the same in every run. - The e2e stack has the eight sample photos and no machine learning, so it has no faces, places or
events: take
timeline,lightbox,timeline-filterandcategory-badgethere. The committed landing page shots come from a bigger sample library. - Noch nicht erschienen (kommt nach 1.7.0) Every shot gets the same Storage card:
openShotinscreens.spec.tsanswers/api/storagestats/withSTORAGE(120 GB of 500 GB used), so no shot shows the disk of the machine that took it. Shots taken before 1.8.0 can still show the real disk; take them again to change that. - Noch nicht erschienen (kommt nach 1.7.0)
search-resultsandaccount-menuneed the Windows or Mac program, not the e2e stack:account-menuwaits for Quit LibrePhotos, which only the programs show, andsearch-resultsneeds search by what is in a photo, which needs the models. Run the program, orpython librephotos_standalone.py runinapps/backend, with a library of free sample photos and a user with a password, and pointE2E_BASE_URL,E2E_USERNAMEandE2E_PASSWORDat it.
Commit only shots made inside the Playwright Linux container (mcr.microsoft.com/playwright, the
version of @playwright/test in e2e/package.json): fonts and rendering differ between operating
systems, so shots from your machine would change every image. The screenshots workflow does that:
started by hand on a branch (default dev) with the shot ids to take, it builds and starts the e2e
stack with the sidebar showing the latest release, runs yarn screens in that container, uploads the
shots as an artifact, and opens a PR "docs: refresh screenshots" with the files that changed (none
changed, no PR). A PR opened by a workflow starts no checks: close and reopen it to run them.
🐛 Debugging
React Debug Tool
React provides a debug tool, which you can download here.
WDYR
WDYR explains to you why a component re-rendered, by logging the changed props and hooks to the browser console. It is wired up in src/wdyr.ts and only runs in development builds.
Set VITE_APP_WDYR to the literal string true — any other value (True, 1, unset) leaves it
off. Where you set it depends on how you run the frontend:
-
Local dev server (
yarn start) — addVITE_APP_WDYR=truetoapps/frontend/.env.development. -
Docker dev stack — add
VITE_APP_WDYR=truetodeploy/compose/.env, then recreate the container so it picks up the new environment:docker compose -f docker-compose.yml -f docker-compose.dev.yml up -d frontend
Either way the dev server has to be restarted. WDYR needs its own JSX transform, which
vite.config.ts only selects when the variable is set at startup, so flipping it mid-session has no
effect.
REST API
Our REST API is documented with Swagger and ReDoc. Once your development stack is up, both are served from the running instance — see Development Installation for the URLs.
🏙️ Structure
Everything below is relative to apps/frontend/src.
- routes holds the
pages. Routing is file-based: the path of a file determines its URL. Routes under
_protectedrequire a logged-in user, routes underpublicdo not, and__root.tsxis the shell they all render into.routeTree.gen.tsis generated from this folder by the TanStack Router plugin — never edit it by hand. - Pages should be split up into React components, which you can find in components, grouped by feature.
- api_client
is the web side of the API layer, and every request starts there. The requests themselves live in
packages/api-client,
which the mobile app uses too: one endpoint function per call in
src/endpoints, each parsing the answer with its zod schema fromsrc/schemasand returning the parsed type.api.tssets upapiClient, the shared client with the web's policy around it: it attaches the access token, refreshes it on a 401, logs out when that fails, rejects a failed request withApiError, and shows a "please report this" notification when an answer does not match its schema. Around it, one folder per domain (photos,albums,faces, …) holds the TanStack Query hooks the components actually call (useFetch…Query,use…Mutation): each wraps anendpoints.<name>(apiClient, …)call and adds the web's cache invalidation and notifications, with keys from the domain's key factory inpackages/api-client/src/hooks/queryKeys.ts, which the mobile app's hooks share. Files under/media/(thumbnails, originals, videos) get their URLs frommediaUrland are fetched withfetchMedia, both inapi_client/media/mediaUrl.ts. A component never callsapiClientorfetchitself: when it needs a request, add the endpoint and its schema (with a fixture test) topackages/api-client, then a hook to the domain's folder. Lint enforces this: no file inapi_clientcallsapiClientdirectly or defines its own zod schema (#2347). - hooks and service contain cross-cutting hooks and helpers, such as authentication and notifications.
- locales holds the
translations, set up in
i18n.ts. Translations are contributed through Weblate rather than edited directly: itslibrephotos-frontendcomponent translatesapps/frontend/src/locales/*/translation.jsonagainst the English file,apps/frontend/src/locales/en/translation.json.i18n.tsloads every directory underlocalesas its own chunk, English included, so a language Weblate adds loads without a code change. Neu in 1.7.0 The first render waits for the user's language and English, the fallback (index.tsxawaitsi18nReady), so no raw keys flash. A small script that the build adds toindex.html(localePreload.ts, a Vite plugin) preloads both chunks before the app's JavaScript runs, from thelngquery parameter, the savedi18nextLngor the browser's first language, so neither waits for the main bundle. Under vitest (MODE"test")i18n.tsstill passes English as a bundled resource, so component tests read it synchronously; the build drops that branch. To offer it in the Profile language picker, give it an entry incomponents/settings/languageOptions.ts;src/i18n.test.tsfails until it is there. Neu in 1.7.0 The UI language is detected byutil/languageDetector.ts, in the order the i18next-browser-languagedetector package used before it: thelngquery parameter, thei18nextcookie,i18nextLngin localStorage, then in sessionStorage, the browser's languages and<html lang>. The language a user picks is saved underi18nextLng, so a saved choice survives the change. - Neu in 1.7.0 Date and time fields are the browser's own inputs,
NativeDateInput,NativeTimeInput(withSecondsforstep=1) andNativeDateTimeInputincomponents/common/NativeDateInput.tsx, styled as Mantine inputs with an optional clear button. They read and write the input's wall-clock strings (yyyy-MM-dd,HH:mm:ss,yyyy-MM-ddTHH:mm:ss), whichutil/dateUtils.tsconverts with luxon:photoTimestampWallClockandwallClockToPhotoTimestampfor anexif_timestamp,toDateTimeInputValueandfromDateTimeInputValuefor an instant. No JSDatesits in between, so a picked day cannot turn into the day before (#630). The pickers follow the browser's language and calendar, not the UI language, and Firefox on desktop has no time picker. There is no Mantine dates package and no dayjs. - The names of things (the words the tagger finds,
apps/backend/service/tags/tags.txt) are their own namespace,locales/<lang>/tags.json, loaded only by the pages that show things (hooks/useThingLabel.ts).locales/en/tags.jsonnames every word as itself and is the source a Weblate component translates;src/i18n.tags.test.tsfails when it andtags.txtdiffer, so a word added totags.txtgoes intotags.jsonin the same change. Only the display is translated: links and search keep the English word. - In util you can find miscellaneous functions.
- Neu in 1.7.0 A package stylesheet that only a lazy feature uses is imported by the
component that renders it, not by
index.tsx:maplibre-gl/dist/maplibre-gl.cssincomponents/map/ThemedMap.tsx(every map renders through it). Vite loads a lazy chunk's CSS before the chunk runs, and after@mantine/core/styles.css, so the order Mantine asks for holds and nothing renders unstyled.index.tsxkeeps only the core styles and the app's colour variables. - Neu in 1.7.0 Touch, pen and mouse gestures go through
hooks/useViewerGestures.ts(trackViewerGesturesinhooks/viewerGestures.ts). It reads pointer events on one element and reports a drag (locked to the axis it started on, with the velocity of its last 100 ms), a pinch (scale and the fingers' midpoint), the wheel (in pixels; return true to keep the page from scrolling) and a double tap. A pointer that starts inside[data-own-gesture]is left to that element (the live text, the face drawing layer, the editor's crop overlay and split divider). The element needstouch-action: none. The lightbox (lightbox/LightboxStage.tsx,useLightboxGestures.ts,lightboxView.ts) lays the previous, current and next photo side by side and moves them with--lb-swipe-x. It zooms and pans the current one with--lb-x,--lb-yand--lb-scale, written to the element while a gesture runs and kept in React state (useLightboxZoom) only when it ends, so a gesture never re-renders per frame. The photo editor's canvas (editor/canvas/useStageGestures.ts) uses the same hook.
Token refresh and the end of a session
Noch nicht erschienen (kommt nach 1.7.0) The shared transport (packages/api-client/src/transport/client.ts) refreshes a token for the session that sent the request, and only for it. The web, the mobile app and the desktop app all use it, each with its own token supplier (cookies, expo-secure-store, the desktop's session with its Rust mirror and keychain).
- A request remembers the refresh token stored when it was sent, and its 401 is refreshed only while that token is still the stored one. When nothing is stored any more (a logout), the session has ended: no refresh starts, and the 401 stands. When another session's refresh token is stored (a sign-out followed by a sign-in), the request is neither refreshed nor retried, and it signs nobody out: it rejects with an
ApiError401. - Refreshes are single-flight per refresh token: requests of one session share one refresh, and a request of another session never waits on it or gets its answer.
- A refresh stores its new access token, and retries the requests waiting for it, only if the stored refresh token is still the one it sent. A supplier whose storage is asynchronous provides
setAccessTokenFor(refresh, token), which checks and writes as one step (the mobiletokenStorageruns every read and write of the tokens one at a time, so a sign-in or logout cannot land between the check and the write). After a logout (nothing stored) the requests fail as signed out; after a sign-in as someone else they fail without touching that session. - A 400 or 401 from the refresh endpoint ends the session (
clearTokensandonAuthError, or the platform'sonUnauthorized). Anything else keeps the tokens: a network error, a 5xx, the 429 throttle, an answer without a token, and a 403, which the backend never sends and so comes from a proxy or a firewall in front of it. The request rejects with a retryable error: the network error itself, or anApiErrorwith the refresh's status (a 5xx or 429; any other status is reported as 503). Once the refresh has failed without a break, measured on a monotonic clock, for longer than the refresh token had left at its first failure, the session ends too; one failure never ends it. This rule is in practice web-only: on mobileperformance.now()starts again at every launch and stands still while the phone sleeps, so a server that is never reachable leaves the app signed in, with its offline mirror, until a refresh is answered with a 400 or 401. - A request refreshes at most once: a 401 after a proactive refresh (the access token was about to expire) reuses that refresh's answer.
- Noch nicht erschienen (kommt nach 1.7.0) A 401 for an access token that is no longer the stored one is retried with the stored token instead of starting a refresh (
storedSinceinclient.ts). Two requests sent with one expired token used to refresh it twice when the second 401 came after the first refresh had finished, which spends the refresh throttle (60 a minute). After reading the stored access token it checks that the stored refresh token is still the request's session; when another session's tokens were stored in between, the request is not retried and ends as superseded (sessionEnded). Up to 1.7.0 every such 401 refreshed again. - Noch nicht erschienen (kommt nach 1.7.0)
onUnauthorized(endpoint, response, session)gets the refresh token the refused request was sent with (null when there was none). The web ends a session once (expireSessioninapi_client/session.ts): it remembers the refresh token of the session it ended, and later 401s of requests sent with that token, or with none, change nothing. A request of a session signed in later, in this tab or another, ends that session as usual. Up to 1.7.0 the tab kept one "ending" flag until the page load; when "Leave site?" kept the page (files uploading, an unsaved edit), a later session that ran out never went to the login page. - On the web, logging out clears the cookies, waits up to 10 seconds for this tab's refreshes to settle (
endpoints.logoutwaits forrefreshSettled(), which covers the error forwarder's client too), and only then tells the server, whose answer clears the HttpOnlyjwtcookie. A refresh that has not settled after those 10 seconds is cancelled first (cancelRefreshes()aborts its fetch, and the refresh settles at once even when a fetch ignores the abort): a cancelled refresh stores nothing and ends no session, and the requests waiting on it reject with a retryable error. So no refresh answer of this tab can set thejwtcookie after the logout answer cleared it. A refresh answer that lands later in another tab is not stored, so that tab ends its own session and its logout clears thejwtcookie again. - On the web, "signed in" means a
refreshcookie is there (hasLiveSessioninapi_client/authCookies.ts), so anaccesscookie alone never sends the login page back into the app. Whether the refresh token is still valid is left to the server, not to the computer's clock, so a stale refresh cookie shows the app once before the first request ends the session and loads/login?session=expired.
A tab open across an upgrade, and saved UI state
Noch nicht erschienen (kommt nach 1.7.0)- A code file of the running build that the server no longer has (
vite:preloadError, or a failedimport()thatreportBrowserErrorsees) reloads the page once a minute at most (service/newBuildReload.ts). While that reload is under way, errors are not reported. The hold now lasts the same minute: when "Leave site?" keeps the page (files uploading, an unsaved edit), errors are reported again after it, and the next missing file reloads again. Up to 1.7.0 the hold lasted until the page went, so such a tab never reported an error again. - The error reporter loads its Sentry client with the first error (
loadClientinservice/errorReporting/reportBrowserError.ts). A failed load is not kept: the next error loads it again. Up to 1.7.0 one failed load (offline for a moment) dropped every later report of the page. readStoredinutil/storage.tsfalls back to a value under its legacy key without moving it; the firstwriteStoredof the key moves it, since it writes the new key and removes the legacy one. Up to 1.7.0 the read moved it, and two tabs of a new build could write the old value over an edit the other tab had saved a moment before, because a tab reads its own copy of localStorage, which another tab's writes reach later.
The API client outside the browser
Neu in 1.7.0 packages/api-client has three entry points: @librephotos/api-client (everything, for the web and mobile apps), @librephotos/api-client/core (src/core.ts: the schemas, the transport, endpoints, the media URL helpers and ResponseParseError, without the TanStack Query hooks and the polling helpers, so it needs only zod), and the narrower schemas, transport and hooks. The desktop app imports core, through a Vite alias like the web app, and node scripts/check-shared-deps.mjs checks its zod (and React or React Query, if it ever declares them) against the package's peer ranges along with the web and mobile apps'. Noch nicht erschienen (kommt nach 1.7.0) endpoints uses the timer helper of src/polling.ts (the logout's bounded wait), so that module imports nothing from React Query: invalidateAfter takes any object with an invalidateQueries method. The desktop workflow's npm run typecheck fails when something under core reaches @tanstack/react-query.
ApiClientConfig.fetch takes any fetch. createNativeFetch(send) (src/transport/native.ts) builds one that sends every request through a host's own HTTP stack instead of the runtime's fetch, so CORS, the webview's cookie jar and its request limits never apply; the desktop sends everything from Rust this way:
import { createApiClient, createNativeFetch } from "@librephotos/api-client/core";
const client = createApiClient({ baseUrl, tokens, fetch: createNativeFetch(sendThroughRust) });
- The adapter encodes the request the way
fetchwould (aFormDatabody becomes multipart with its boundary incontent-type; an object body was already JSON-encoded by the client) and handssendplain data: aNativeRequestwith the URL, the upper-case method, lower-case header pairs, the body's bytes (or null), the caller'sAbortSignaland the body's file parts.sendanswers aNativeResponse(status, headers, bytes) for any HTTP status, and rejects only when there is no answer, preferably with aTypeErrorlikefetch. The adapter turns the answer into aResponse(no body for 204, 205 and 304), so the refresh interceptor,ApiErrorand the endpoint schemas run exactly as on the web and on mobile. Aborting the caller's signal rejects at once with anAbortError, whateversenddoes with its copy of the signal. nativeFilePart(ref, name)is aFormDatafile part whose bytes the native side already has, such as a byte range of a file on disk: append it without a file name (form.append("file", part), soFormDatakeeps that very object). The adapter sends a random marker in its place and lists it inNativeRequest.filePartswith itsref; the native side replaces the marker with the bytes before sending. It only works with afetchmade bycreateNativeFetch; any otherfetchwould send the marker itself. The desktop's backup engine uploads every chunk this way, so no file bytes pass through JavaScript.- Request bodies may also be bytes: a
Blob, anArrayBufferor a typed array goes out unchanged with theContent-Typegiven inheaders, like aFormDatabody. endpoints.refreshAccessToken(client, refresh)trades the refresh token for a new access token outside any request, for a platform whose media loader (a native image proxy, an image component with headers) needs a fresh token while no API request is due. The transport still refreshes on its own around requests; a refused refresh token answers 401, which signs the client out like any other unrecoverable 401.
src/__tests__/nativeFetch.test.ts drives the client through a fake native stack that only sees plain data, as a Rust command would.