Compare commits

...

63 Commits

Author SHA1 Message Date
Maurice 39d2196a14 feat(postgres): support PostgreSQL 19
PostgreSQL 19 was released on 19.11.2026, and TREK refused it at boot as
newer than the 14 to 18 it supported (discussion #3214). It now supports 14
to 19.

The image installs the version 19 client tools from PGDG's main component,
since the per-major component can trail a new release; a client handles
every server up to its own major, so pg_dump, pg_restore and psql 19 back up
and restore every supported server. The tools are looked for in the 19
directory first. Installs that pointed TREK_DB_PG_BIN_DIR at the old
/usr/lib/postgresql/18/bin keep working: the image keeps that path as a link
to the 19 tools. CI runs the Postgres lane on 14 and 19 instead of 14 and
18, so the job count stays the same, and the Docker job boots on 19. The
list of server functions and roles that reach the host was checked against
the release notes; PostgreSQL 19 adds none. The compose example stays on 18,
because an existing database stays on the major it was created with.
2026-11-26 23:48:52 +01:00
Maurice a9fd443b63 feat(db): present a Postgres client certificate from sslcert and sslkey in TREK_DB_URL
A Postgres server that authenticates clients by certificate could not be
used: TREK read only sslmode and sslrootcert from TREK_DB_URL, so neither
the connection pool nor pg_dump, pg_restore and psql ever offered a client
certificate (discussion #3215).

TREK_DB_URL now also takes libpq's sslcert and sslkey. Both must be given
together and only with a verifying sslmode, and each file must be readable,
or the boot refuses with the same kind of message as for sslrootcert. The
pool gets them as its TLS cert and key, the tools as PGSSLCERT and
PGSSLKEY. The Postgres wiki page shows the URL, how to mount the files with
Compose or the chart's extraVolumes, and libpq's rule for the key file's
permissions, which the backup tools enforce.
2026-11-26 23:35:18 +01:00
Maurice b8dffdbb13 fix(files): serve the stored offline copy when a live download stalls
Opening a document that was stored for offline use fetched it from the
server first and only fell back to the stored copy when the request
rejected. On a weak or stalled connection the request never rejects, so a
boarding pass already on the phone could spin indefinitely.

With a stored copy, the live download now gets five seconds, request and
body together; after that the stored copy is served and the download is
aborted. A connection that breaks while the body arrives serves the copy as
well. An HTTP error that comes back in time still surfaces over the copy,
and without a stored copy the download waits as long as it always did. The
test file is now formatted and leaves the format baseline.
2026-11-26 23:35:18 +01:00
Maurice 3b42ffa67b feat(helm): render extra Kubernetes objects from an extraObjects list
The chart had no way to ship objects of the operator's own next to TREK, so
a backup CronJob, a ConfigMap for it or any other helper had to live in a
second release or be applied by hand (discussion #3194). extraObjects takes
a list, empty by default so nothing renders, and renders each item through
tpl: a map as YAML, a string as written, so names such as
{{ .Release.Name }} resolve in both forms.

The values comment, the chart README and the Helm wiki page say that braces
are evaluated in both forms, that a backup job must mount the data volume
read only, and that it should copy TREK's own backup archives rather than
the live travel.db. Those archives carry the encryption key unless
ENCRYPTION_KEY comes from the environment, so their destination needs the
same protection as the volume. CI renders a variant with a CronJob in the
map form and a ConfigMap in the string form, checks it with kubeconform
-strict, and fails when a {{ is left unrendered.
2026-11-26 23:35:18 +01:00
Maurice 2ea1c99e31 ci(native): publish the Play-signed Android APK to liketrek/trek-android for installs outside Google Play
People who install apps from GitHub (Obtainium and the like) asked for the
Android app outside Google Play. After the Play upload, the release job now
fetches the universal APK Google Play builds of that same bundle, signed
with the Play app signing key, and publishes it with a checksum to
liketrek/trek-android: one release per app version, a newer build of the
same version replacing its APK. A phone can move between the Play install
and this APK without uninstalling, and Play Billing and push work in it
wherever Google Play services do.

It runs only inside the app builds that already happen, so a server release
without app changes publishes nothing. A build is held back while the app
needs a newer native API than the latest server release answers, so no APK
asks for a server that is not out yet. The APKs live in their own repository
so app releases never show up in the server's release list or update check.
2026-11-26 23:12:27 +01:00
Maurice d383d3527b fix(oauth): bind an authorization code to the session that consented, not to the password version
Reading the password version from the oauth domain meant injecting the
users repository, which the auth domain owns. The sessions domain answers
the same question and more: a password reset or change ends every session
of the user, and a sign-out ends the one that consented. The code now
carries that session's id and both token endpoints issue tokens for it
only while the session is active, checked in the transaction that writes
them. A token from before sessions were tracked has no session to check
and passes, as it does everywhere until it expires. A refused code is
audited as session_ended.
2026-11-26 22:46:15 +01:00
Maurice 05843c8e5b test(oauth): give the pending-code fixture its password version and format the controller test 2026-11-26 22:32:44 +01:00
Maurice 19270adef8 test(oauth): read the granted code without non-null assertions 2026-11-26 22:26:58 +01:00
Maurice f9ab280b7e fix(oauth): an authorization code mints tokens only while the password it was granted under holds
The consent page mints a two-minute authorization code from the cookie
session. A password reset or change revokes the user's OAuth tokens but
left such a pending code alone, so a code granted before the reset still
redeemed afterwards into a fresh token pair at either token endpoint.

The code now carries the password version of the session that consented,
and both token endpoints issue tokens for it only while that version is
still the account's, checked in the transaction that writes the tokens.
A refused code answers invalid_grant as any other and is audited as
password_changed.
2026-11-26 22:21:46 +01:00
Maurice c88d3abc5e fix(auth): a native app hand-off code redeems only while the session that minted it stands
The browser side of the native sign-in mints a one-time code from its
cookie session, and the app redeems it within a minute for a session of
its own. The code was bound to the account alone, so one minted before a
password reset, a sign-out or a revoked session still redeemed afterwards
into a fresh session, carrying access across the point where the account
took it back.

The code now carries the session it came from: its password version and,
for a tracked session, its id. Redeeming it mints a session only while the
password is unchanged and that session is still active, checked in the
same transaction that mints the new one.
2026-11-26 22:14:12 +01:00
Maurice 10d95a39ac fix(map): open a day the routing relay could not answer drawn, without waiting for it again
On an instance that routes its days with Valhalla (the TREK services by
default), a day the relay could not answer in time was drawn by OSRM and
kept only under the OSRM key. The next visit missed the Valhalla key, asked
the relay again and waited out its deadline, up to twelve seconds a day,
before the kept road showed, so every reload showed straight lines first.

OSRM's answer now stands in for such a day for an hour under a key of its
own, on the device only. Reopening the trip draws it at once; after the
hour the relay is asked again and its answer becomes the day's. Days that
avoid something keep asking Valhalla, since the stand-in drives the road
they mean to leave out.

Closes #3228
2026-11-26 22:09:59 +01:00
Maurice 7d802081ce test(assistant): replay the changed requests side by side in ANTH-010 2026-11-26 20:04:40 +01:00
Maurice 7586126797 fix(assistant): send Anthropic's thinking back only where the conversation before it is unchanged
Follow-up messages failed with HTTP 400 on Anthropic once a thread held an
answer that thought: the API binds each thinking block to everything the
request sends before it and refuses the request when any of that changed.
It changes in normal use: a tool group loaded later in the turn, an earlier
tool answer cut short once a new question follows, a held change applied
since, a trip card that moved on.

Each recorded step now keeps a fingerprint of what its request sent before
it (model, system blocks, tools, history). On replay its thinking blocks go
back only while that fingerprint still matches; otherwise the step goes back
without them, which the API accepts. Records written before this change
carry no fingerprint and go back without their thinking.

A refusal from Anthropic is now logged with the path its message names
(such as messages.1.content.0), without the rest of the message.

Closes #3094
2026-11-26 20:00:00 +01:00
Maurice 9fa2bef101 test(journey): keep the journey page suite's journal and handlers in its helper
The suite carried its sample journal and the journal's default handlers inline, and waiting for the reload in FE-PAGE-JOURNEYDETAIL-153 took it past its size limit. Both move to tests/helpers/journeyDetail.ts beside seedJourneyOwner; the file is 142 lines shorter and its size baseline follows.
2026-11-26 14:21:04 +01:00
Maurice ed1bba9371 test(client): finish moving the tests to msw 3
Two more window.location stand-ins sat on http://localhost while the
page runs on http://localhost:3000; they now use locationAt like the
rest, which brings back the plugin settings answer FE-COMP-
PLUGINSETTINGS-020 waits for. FE-PAGE-JOURNEYDETAIL-153 ended while the
journal reload it set off was still out, which timed out after the
test; it now waits for that read. The reload mocks in
versionHandover.test.ts carry the signatures of location.replace and
location.reload, as locationAt's overrides require.
2026-11-26 14:03:46 +01:00
Maurice 3c1cf8b347 chore(server): lower the strict baseline of the repository base class
MikroORM 7.2.12's typings leave trek-repository.ts with 4 strict errors instead of 8; the ratchet holds it there.
2026-11-26 14:03:46 +01:00
Maurice 1ed77870f9 test(db): see the unnamed temp files SQLite 3.54 opens on Linux
SQLite 3.54, which better-sqlite3 13.2.0 bundles, opens its temp files
with O_TMPFILE where the system has it. On Linux such a file has no
name: among the process's descriptors it reads <dir>/#<inode> (deleted)
instead of etilqs_<random>. The watcher only looked for the name, so
the control test saw nothing, and the test that TREK's own connection
never touches a temp file would have passed whatever happened. The
watcher now knows both forms; the control proves again that it sees
them.
2026-11-26 14:03:46 +01:00
Maurice 22ee4dbac7 ci(dependabot): let MikroORM and msw move again
Both are on their new versions now: MikroORM 7.2.12 with the OAuth
repositories writing the client the way it accepts, and the client tests
on msw 3. Their ignore entries go. better-sqlite3 and kysely, which
@mikro-orm/sqlite pins exactly, join the MikroORM group instead of being
ignored, so the three move in one pull request. cron and the musl rollup
pins stay held back for their own reasons.
2026-11-26 13:41:29 +01:00
Maurice 6926591112 fix(admin): a default setting reset right after typing is the value that stays
Typing a new Mapbox token or CARTO key and clicking that field's reset
link straight away sent two requests at once: the field's save on blur,
then the reset. Nothing ordered them, so when the server handled the
save last, the key typed a moment ago was stored again while the field
showed it cleared, on the desktop tab and on the phone screen alike.

The hook both shells share now sends its writes one after another, in
the order they were made (useWritesInOrder; a write that fails does not
hold up the next). FE-ADMIN-DUS-032 types, clicks reset at once and
makes the save the slower request; it fails without the order.
FE-HOOK-WRITES-001 to 003 cover the helper.
2026-11-26 13:41:28 +01:00
Maurice 66382e791b fix(admin): keep the dev notification buttons mounted while the panel updates
The desktop panel declared its button component inside its render, so
every state change (each lookup landing, each send starting and ending)
made a new component type and React remounted every button: focus and
hover were lost, and a click that arrived during a re-render went to a
button that was no longer there. Btn now lives at module level and takes
the send in flight as a prop, as the phone panel's Btn already does.
FE-ADMIN-DEVNOTIF-017 holds a button across the lookups landing and
expects the same element; it fails with the old panel.
2026-11-26 13:41:28 +01:00
Maurice 32837afe2e chore(deps-dev): bump msw from 2.15.0 to 3.0.8 and move the client tests to it
msw 3 renames onUnhandledRequest to onUnhandledFrame and reports every
network frame there; the setup judges the HTTP frames as before (another
origin is an error, the page's own a warning).

It also resolves a relative handler, and its fetch interceptor a
relative URL, against location.href at the time of the request, while
jsdom's XHR sends to the document's own address. Tests that replaced
window.location with a stand-in on http://localhost while the page runs
on http://localhost:3000 sent their requests past every handler.
tests/helpers/location.ts builds such stand-ins on the page's own origin
(locationAt, pageUrl), and every one of them now uses it.

msw no longer escapes fake timers, and responses are timed differently,
which surfaced tests that ended with work still running: a held request
answering in the next test, a lookup still out when the assertions ran,
a reload switched by counting reads. Each of those now waits for, or
releases, what it started, and answers by what happened rather than by
a count.

The day panel suites share their setup through
tests/helpers/dayDetailPanel.ts instead of a copy each, which keeps the
larger one under its size limit.
2026-11-26 13:15:45 +01:00
Maurice 05f4c84885 test(reservations): cover the traveller insert that ignores existing rows
ReservationTravelers.insertIgnore had no test of its own. MikroORM 7.2.10 changed how upsertMany with a composite conflict key matches rows read back after a conflict, which is exactly the case of a traveller already on the booking next to a new one in one call. RS9-001 to RS9-004 pin that case, a duplicate id, another booking's row and an empty list; the first two fail with a plain insert.
2026-11-26 12:57:32 +01:00
Maurice 6905729ab6 chore(deps): bump MikroORM from 7.2.8 to 7.2.12 with better-sqlite3 13.2.0 and kysely 0.29.9
From 7.2.9 on, MikroORM reads a bare value given for a relation as the
target's primary key. The client relation of oauth_tokens and
oauth_consents points at oauth_clients.client_id, a unique column that
is not the primary key, so every token mint and every consent grant was
refused ("Cannot set OauthTokens.client to a reference of OauthClients
without the value of OauthClients.client_id"): every OAuth and MCP
sign-in would have failed.

insertToken now hands the referenced column itself to the relation
(oauthClientRef), which MikroORM writes to client_id as it is.
upsertGrant writes the row with Kysely's onConflict on
UNIQUE(client_id, user_id), because em.upsert takes that same value as
the data of a new OauthClients entity. The test fixtures that seed
tokens and consents use the same helper. Reading client_id back is
unchanged; the repository tests seed clients whose primary key differs
from their client_id, one of them a decoy whose primary key equals
another client's client_id.

The lockfile resolves the MikroORM tree from scratch, so there is one
@mikro-orm/core again instead of a second copy next to @mikro-orm/nestjs.
better-sqlite3 13.2.0 ships prebuilt binaries for every platform the
image builds, musl included.
2026-11-26 12:39:43 +01:00
Maurice 85aa1c91ff test(booking-import): check the upload limits the route sets, not Nest's whole set
NestJS 11.2.12 adds its default parts limit to every multer interceptor, so the options hold one more key than the route names.
2026-11-26 11:26:35 +01:00
Maurice de9901d941 refactor(files): drop the drop zone's noClick option, which is its default
Keeps useFileManager within the function length limit now that it names noPaste; react-dropzone's noClick defaults to false, so a click still opens the picker.
2026-11-26 11:26:35 +01:00
Maurice 95a0cd2f77 ci(dependabot): hold back the updates that cannot move on their own
The last grouped update showed which packages break when Dependabot moves
them alone: MikroORM from 7.2.9 on refuses the OAuth repositories'
foreign key writes, better-sqlite3 and kysely are pinned by
@mikro-orm/sqlite, cron by @nestjs/schedule, the musl rollup pins have
to follow the installed rollup, and msw 3 is a migration of the client
tests. Each is held back with its reason and moves by hand. The rules
name the version update types rather than the whole package wherever
that is enough, and a security advisory for any of them still shows in
the Security tab.
2026-11-26 11:15:46 +01:00
Maurice f922068a8e chore(deps): bump express from 4.22.3 to 5.3.0 and @types/express to 5.0.6
Nest already serves every request through Express 5. Only the parsers,
the static handler and their types still came from the direct Express 4
dependency, so this moves those three and keeps their behaviour:

- body-parser 2 leaves req.body undefined when it did not read a body,
  where body-parser 1 left an empty object. A bodyless POST to a route
  whose fields are all optional answered 400, and a plugin route got
  null. emptyBodyDefault restores the empty object for everything but
  /mcp, which stays raw (BOOT-009, PACK-3T-004).
- serve-static 2 no longer exposes its mime table. The Brotli copy of
  an asset is typed through mime-types 3 with the fallback send uses,
  so it keeps the Content-Type of the original file (PRECOMP-001).
- @types/express 5 types a route param as string or string[]; the
  photo route names its single :filename param.

The MCP SDK resolves the same Express 5.3 now; Nest keeps the 5.2.1 it
pins.
2026-11-26 11:09:32 +01:00
Maurice 5c5d85ef60 chore(deps): bump NestJS to 11.2.12, @nestjs/swagger to 11.4.8 and jimp to 1.7.0
The NestJS part of the grouped Dependabot update, without the packages
that cannot move yet: MikroORM stays on 7.2.8 together with the
better-sqlite3 and kysely versions it pins, cron stays on the 4.4.0
that @nestjs/schedule pins exactly, and the musl rollup pins stay on
the rollup version the lockfile installs.

What changed in Nest does not reach TREK's own paths: TrekWsAdapter
builds its server and binds every handler itself, so the new WsAdapter
defaults do not apply, and the new limit of 1000 multipart parts per
request is far above what the upload routes receive.
2026-11-26 11:04:58 +01:00
Maurice d83e98366b chore(deps): bump react-dropzone from 14.4.1 to 20.2.1
react-dropzone 19.2 turned on a paste handler of its own on the drop
zone. The file panel already uploads pasted files once for the whole
panel, after the upload permission check, so a paste while the zone
had focus sent every file twice. The zone's paste handling is switched
off with noPaste; FE-COMP-FILEMANAGER-039 pastes on the zone itself
and expects a single upload.

prop-types and loose-envify leave the lockfile with the old version.
2026-11-26 11:03:21 +01:00
Maurice 756eae39ff chore(deps-dev): bump @types/node from 25.9.8 to 26.6.11
Type definitions only; the image and .nvmrc stay on Node 24. npm drops the stale peer flag from the optional rollup binaries while it rewrites the lockfile; nothing installs with --omit=peer.
2026-11-26 11:02:10 +01:00
Maurice 4f66a344ca fix(auth): retire password reset links when the account's email or password changes
A reset link is a credential sent to the address the account had when it
was asked for. It stayed valid for its full hour after the account moved
to another address or got a new password, so a link sent to the old
mailbox could still set a password on the account.

Changing the email in the user's own settings, changing the password,
and an admin changing a user's email or setting a password now consume
every live reset link of that user, in the same transaction as the
change. Saving the same address, or it in another case, keeps the link,
and a link asked for afterwards works as before.
2026-11-26 10:17:13 +01:00
Maurice 96b2778c2f fix(native): keep the server picker clear of Android's navigation bar
On Android the web view can report env(safe-area-inset-*) as 0 while the
app draws edge to edge, so the buttons at the foot of the app's first
screens sat under the three-button navigation bar and the logo under the
status bar. Capacitor's SystemBars plugin writes the real insets to the
page as --safe-area-inset-*; the first screens now read them as one more
floor next to env() and the insets iOS measures itself. Where Capacitor
lays the web view out between the bars it writes 0, and in a browser the
variables are unset, so nothing changes there.

Closes #3221
2026-11-26 10:10:22 +01:00
Maurice 98c883b4e8 test(assistant): load the tool cap's groups without awaiting in a loop
The cap suite added eleven no-await-in-loop and two non-null assertion
warnings to the server tests, past the lint ratchet. Independent sessions
now run side by side and the sequential loads go through a recursive
helper.
2026-11-25 22:48:57 +01:00
Maurice df82208bd5 fix(assistant): keep every step within the 128 tools OpenAI and Azure accept
A trip chat offered 130 tools in its first step and up to 359 with every
group loaded. OpenAI's APIs and Azure refuse a request with more than 128
function tools (array_above_max_length), so the trip assistant failed at
once on an OpenAI style or Azure Foundry connection, while Anthropic and
the ChatGPT login took the longer list.

The trip's bookings, its packing lists and to-dos, changes to its budget
and its tags now load as groups like the addons do, which brings the core
to 63 tools, so any one group fits beside it. Loading a group that would
pass the limit unloads the one used longest ago, a call to one of its
tools loads it again, and groups asked for together that do not fit are
named so the model loads them later. The groups that are part of the trip
carry no domain on their change cards. Reading the costs stays in the
core.
2026-11-25 22:34:41 +01:00
Maurice 18867d9499 fix(weather): answer the day 16 days out with climate instead of an error
The detailed weather took the forecast path for any day whose distance
from now was at most 16 days, measured as a fraction of a day. Open-Meteo's
forecast reaches today + 15 calendar days, and the day 16 out lies 15.x
days from now, so it was asked of the forecast, refused with a 400, and
the day showed "No weather data". The cutoff now counts calendar days and
sends anything past today + 15 to the climate path. The forecast measures
its range from the place's own date, which trails UTC in the Americas for
part of the day, so a refusal of that range also falls back to climate.

Closes #3216
2026-11-25 22:21:16 +01:00
github-actions[bot] 13910464e5 chore: bump version to 5.2.1 [skip ci] 2026-11-25 13:18:29 +00:00
Maurice 903868c08c feat(release): show the iOS and Android apps in the 5.2.1 notice, the account settings and the user menu
The release notice moves to 5.2.1 and gets a tile across the release column
with the App Store and Google Play cards, each with a QR code that opens the
store page. The headliner, intro, footnote and note texts are shorter so the
tile fits, in every locale.

Settings > Account shows the same store cards in its right column, except
inside the native app itself. The user menu footer adds round links to
Patreon, Ko-fi and Buy Me a Coffee beside Discord, left out on managed
installs and in the native apps like every donation link.
2026-11-25 13:32:18 +01:00
Maurice 434baaf6fd fix(native-auth): send the app's SSO sign-in through the identity provider every time
The app signs in through a browser sheet that shares the system browser's
cookies. When that browser still held a TREK session from an earlier
sign-in, the hand-off page skipped the identity provider and offered to
continue at once, so a provider set to demand re-authentication (Pocket ID's
"requires re-authentication") was never asked, and signing out of the app
and in again with SSO asked for nothing.

The SSO button now always goes through the identity provider. It decides as
before: a provider with a running session lets the user through, one that
demands re-authentication asks for it. A sign-in with a password or passkey
still continues with the browser's session after the explicit tap.

Refs #3014
2026-11-25 10:52:34 +01:00
Maurice d9d901e52d fix(ci): lower the client non-null baseline and arm the wait before PMEDIA-006 advances
Client lint was red because the day plan change took 13 non-null assertions
out of DayPlanSidebar: the count is 354 now, so the baseline goes down to it.

Server tests 6/10 timed out in PMEDIA-006. The test advanced the fake clock
right after asking for the rendition, but the wait it meant to run out is only
armed once the copy has started; on a slow runner the clock moved past a timer
that did not exist yet and the test hung for 15 seconds. It now waits for the
copy to start first, as PMEDIA-006b already does.
2026-11-25 10:37:46 +01:00
Maurice 50cb9364f6 fix(atlas): count the cities the address parser used to miss
The Atlas reads a place's city from its address text, and several common
address shapes lost it:

- The TREK index writes "street, postcode, locality" with no country, and the
  parser always dropped the last part as the country, so a place picked from
  TREK's own search counted no city.
- A city that is its own region (Berlin, Wien, Malé) was skipped as the region
  even where it stands beside its postcode, which is how such an address names
  its city.
- An atoll or a state written with its generic word ("Kaafu Atoll" for the
  region Kaafu) was not recognised as the region and counted as the city of
  every island in it.
- Country names came from a short English and German list, so "Maldives",
  "Österreich" or "Italia" could be counted as a city.

The locality of a postcode-and-locality tail now counts, a region-named part
with a postcode counts when no part before it names a city, a region matches
with its generic word, and countries are recognised by their name in every
language TREK speaks. A region named without a postcode (a mountain in
"Bayern", a resort in "Kaafu") still counts no city, and the lines the parser
already read right read the same.

Closes #3200
2026-11-25 10:29:09 +01:00
Maurice b6c50eb146 fix(wallet): date a booking's pass by its stay or linked day when it has no time of its own
The Wallet pass took its date only from the booking's own time or, for a
journey, its departure stop. A hotel whose check-in and check-out live on its
stay, and a booking linked to a day that carries only a clock, have neither,
so Wallet answered "Give the booking a date first" for a booking the app
shows with its dates. A TestFlight tester hit it with a hotel booked from
8 to 11 January.

The pass context now reads the dates of the days a booking is linked to and,
for a hotel, the first and last day of its stay with its check-in and
check-out times. The pass falls back to them in the order the app uses
(bookingDates): the booking's own time first, then the stay or the linked
day, with the booking's or the stay's clock. A booking with no date anywhere
is still refused.
2026-11-25 10:25:10 +01:00
Maurice c1c77d89b5 fix(day-plan): make the legs from a booking or the hotel tappable on the phone
On the phone timeline only a leg that leaves a stop opened the travel mode
menu. The leg from the morning hotel to the first stop, the leg from the last
stop back to the hotel and the leg from a booking's arrival to the next stop
stayed inert, although the desktop day plan already changes them through the
stop at their other end. A TestFlight tester could not tap the walk from their
train's arrival to the hotel.

The timeline now knows which stop owns each of these legs: the first stop's
incoming mode for the morning hotel leg and for a leg out of a booking, the
last stop's outgoing mode for the evening hotel leg. Tapping them in edit mode
opens the same menu as on the desktop, and the phone sets the incoming mode
the way the desktop does.

A leg no stop owns, such as a booking's arrival to the hotel, has no mode to
store. It follows the day default, and on both the phone and the desktop it
now offers the public transit search where a trip has dates, instead of
reacting to nothing.
2026-11-25 10:21:43 +01:00
Maurice 70af8132ef fix(booking-import): let the model choose when a document names several booking types
The keyword table that picks the extraction schema took the first pattern
that matched, with transport tested first since #2076. A hotel confirmation
that mentioned the airport bus, the train station or the cruise port was
therefore extracted with the bus, train or ferry schema. Those schemas have
no hotel name, address or check-in and check-out, so the model returned a
transport booking without the stay's data and the import dropped it.

The keywords now only decide alone when a document names one type. When it
names several, the model gets the union schema narrowed to exactly those
types, with each type's field meanings, and picks. The flight gate is
unchanged: flight numbers still take the flight path only when no other
transport is named. Event words decide only when nothing else is named,
since "ticket" is printed on every transport ticket, and the lodging
pattern also knows motel, accommodation, apartment, guest house, Unterkunft
and Ferienwohnung.
2026-11-25 10:09:24 +01:00
Maurice 85182d2f52 chore(deps): group MikroORM and NestJS updates, hold NestJS majors
Each family releases in lockstep and now arrives as one PR. NestJS majors wait until nestjs-zod supports NestJS 12.
2026-11-25 00:10:14 +01:00
Maurice c65e9bf76e fix(auth): move passkeys to SimpleWebAuthn 14, which no longer fetches a CRL a client names
@simplewebauthn/server 13.3.3 fetched the CRL address in an android-key
attestation certificate before it checked the chain or the signature, with
no timeout or size cap, so anyone signed in could make the server request
any URL by registering a passkey. 14.1.0 only checks revocation for a chain
it validated against Google's pinned roots.

14.x refuses an expected origin with a path, a trailing slash or an
uppercase host and an RP ID that is not lower case, where 13.x only failed
to match them. The configured origins are now reduced to the origin the
browser reports and the RP ID is lower-cased, so such settings keep
working; an origins list in which nothing parses leaves passkeys
unconfigured instead of falling back to APP_URL. Verification gets the
algorithm list the options offer, and stored transports are read as plain
strings.

Stored credentials keep their format. typescript-eslint moves to 8.73.0.
2026-11-25 00:10:14 +01:00
Maurice 3754518d37 fix(ai): say why ChatGPT refused a sign-in, and start a fresh one after any refusal
Every refusal of the code by OpenAI's token endpoint came back as "The
sign-in took too long", and the endpoint's own error was dropped without a
log line. Only invalid_grant means the code ran out or was used already; any
other refusal (invalid_client, a redirect or resource mismatch) now names
its OAuth error in the answer and in a warning with the endpoint's
description, so an admin can see what went wrong.

The server takes a sign-in once whatever it answers, but the panel only
started a fresh one after "expired", so the next try after any other
refusal used a spent sign-in. It now starts a fresh one after every refusal
the server sent; offline and a wrong address keep the one in progress, as
neither reached it.

The address the sign-in window ends on is also taken without http://, the
way the hint under the field and the address bar show it.

Closes #3196
2026-11-24 23:59:33 +01:00
Maurice eed5f75487 docs(readme): space Data sources like the other sections 2026-11-24 23:56:08 +01:00
Maurice f29112698e docs(readme): show See all features as a plain heading
The graphic card goes again; the toggle now reads as a third-level heading.
2026-11-24 23:54:54 +01:00
Maurice d556d706b7 docs(readme): drop the feature tile grid, make See all features a card
The Plan, track, share tile grid goes. The See all features toggle is now a card in the style of the app cards, light and dark, with the feature areas as small chips and a chevron, so the full list is easier to spot.
2026-11-24 23:53:58 +01:00
Maurice 71673085bb docs(readme): make the app store cards flatter
A smaller QR code, and the store's mark beside the first line instead of in a box of its own, so each card is about a quarter less tall.
2026-11-24 23:51:05 +01:00
Maurice 19a01d493b docs(readme): set the sponsor line in normal text size 2026-11-24 23:49:59 +01:00
Maurice 462f08727c docs(readme): shorten the sponsor and AI notes, drop the PWA section
The sponsor line at the top goes; the dataforest cloud block further down is now its logo under a small POWERED BY and one line. The AI usage section is one sentence with its link. The PWA install steps and their link in the quick navigation go, since the store apps now sit at the top.
2026-11-24 23:49:20 +01:00
Maurice 58298703e1 docs(readme): drop the line under the app cards 2026-11-24 23:48:23 +01:00
Maurice 17e75947f0 docs(readme): drop the Docker badge 2026-11-24 23:47:36 +01:00
Maurice 4f1e29b02c docs(readme): drop the Sonar and CI status badges 2026-11-24 23:46:48 +01:00
Maurice d1ee3ceccb docs(readme): show the app stores as cards with their QR code
Two cards, one per store, in a light and a dark version that follow GitHub's theme: the QR code on white on the left, the store's mark and name on the right. They replace the bordered table and the two shield badges, and each card links to its store.
2026-11-24 23:45:47 +01:00
Maurice 69a976e942 docs(readme): put the iOS and Android apps near the top, shorten the sponsor section
A QR code and a store button for the App Store and Google Play sit right
under the introduction, with a line that the app connects to your own TREK
server and a link to the Native Apps page. The QR codes are SVGs on a white
ground, so they scan in GitHub's light and dark theme alike.

The dataforest cloud section keeps its logo and every sponsor link but says
the same in one paragraph instead of four.
2026-11-24 23:41:22 +01:00
Maurice f928f4b1ca fix(postgres): connect over a Unix socket
TREK_DB_URL could not name a Unix socket. MikroORM builds the pool from the
URL's own host and drops a host parameter, so
postgresql://trek@localhost/trek?host=/var/run/postgresql connected to
localhost over TCP. A percent-encoded socket path as the host reached the
pool, but the client tools got it undecoded in PGHOST, so backups, restores
and the safety copy before a migration failed.

The server address is now read once, the way libpq reads a connection URL:
a host or port parameter takes the place of the URL's own, and a host
written into the URL is percent-decoded. The pool and the client tools both
get that address. The wiki and .env.example show the socket form.
2026-11-24 23:15:34 +01:00
Maurice aa79d6286a fix(paddle): read the Geofabrik region list again
The admin's paddle region picker failed with "The list of regions cannot be
fetched right now". Geofabrik's index now writes a continent's parent as
null instead of leaving the key out, and the schema took only a string or
nothing, so the whole list was refused over nine entries.

The optional fields now take null as well, and the entries are read one by
one: an entry in a shape TREK does not know costs only that region and is
counted in a warning. A list of which nothing can be read is still refused.

Closes #3195
2026-11-24 22:32:17 +01:00
Maurice eeff0398a7 fix(mail-import): retry a busy AI provider and never drop a booking mail in silence
A forwarded booking mail whose AI read failed in passing (a 503 "high
demand", a rate limit, a timeout) was settled at once with an inbox entry
nobody read again, and a manual import printed "no reservations found"
under the AI error as if the file held none.

Both LLM clients now send a failed request again up to twice, honouring
Retry-After within the request timeout. The mail pipeline puts such a mail
back in the queue and keeps the inbox entry only after its last try, and
these attempts no longer count toward the daily AI limit.

The mail prompt now names the answer's shape, { "bookings": [...] }, for
providers that get no tool. An answer in another shape used to read as
"not a booking" and the mail was discarded without a trace; it now ends
as a failed read the person sees in the inbox.

The import warnings lose their dashes, and the image sets LANG=C.UTF-8 so
KItinerary stops warning about the C locale on every run.
2026-11-24 13:30:22 +01:00
Maurice 7fe4fbb683 fix(plugins): mark a plugin that waits for re-consent as failed at boot
A plugin whose files now declare permissions it was never granted is
refused before its process starts, so the supervisor's status hook never
ran and the row kept the 'active' it had from the last run. The plugin
list and the navigation kept offering it while its page answered
"Plugin not available". The boot now stores the refusal as the plugin's
error, so Admin > Plugins says why and the navigation drops it.
2026-11-24 13:20:36 +01:00
Maurice afbeef64c2 style(notices): format the release notice strings with Prettier
The 5.2.0 release modal copy kept short strings on their own line, which
lint:format rejects for files outside its baseline.
2026-11-24 12:23:59 +01:00
Maurice 293ec89db4 fix(map): pin mapbox-gl to 3.32.0 so vector tiles load beside maplibre-gl
mapbox-gl 3.33 and later read the worker class registry key before they
handle Set and Error. maplibre-gl, which ships in the same bundle, stamps
that key on both built-ins, so mapbox-gl looks up a registry entry it never
made and every vector tile fails with "Cannot read properties of undefined
(reading 'omit')". The Mapbox basemap stays blank while raster layers such
as satellite still load. 5.2.0 shipped mapbox-gl 3.35.2; 3.36.0-rc.1 still
has the same order.

Pin the last release that handles the built-ins first, keep Dependabot off
3.33 and later, and add a test that reads the shipped serializer and fails
on a version with the registry read first.
2026-11-24 00:04:19 +01:00
277 changed files with 7680 additions and 3310 deletions
+33
View File
@@ -26,15 +26,48 @@ updates:
prefix: chore(deps) prefix: chore(deps)
prefix-development: chore(deps-dev) prefix-development: chore(deps-dev)
groups: groups:
# Packages that release in lockstep move together, so a PR never pins
# half of them on one version and half on the next.
# better-sqlite3 and kysely are pinned exactly by @mikro-orm/sqlite and
# share its connection, so they move with MikroORM.
mikro-orm:
patterns: ['@mikro-orm/*', better-sqlite3, kysely]
update-types: [minor, patch]
nestjs:
patterns: ['@nestjs/*']
update-types: [minor, patch]
npm-minor-and-patch: npm-minor-and-patch:
update-types: [minor, patch] update-types: [minor, patch]
ignore: ignore:
# nestjs-zod, which validates every request body, does not support
# NestJS 12 yet. The framework moves by hand once it does.
- dependency-name: '@nestjs/*'
update-types: [version-update:semver-major]
# TypeScript 7 is the native compiler and has no JavaScript API yet: # TypeScript 7 is the native compiler and has no JavaScript API yet:
# typescript-eslint, the coverage instrumenter and the Postgres probe all # typescript-eslint, the coverage instrumenter and the Postgres probe all
# call into it (readConfigFile, ScriptTarget). It moves by hand once the # call into it (readConfigFile, ScriptTarget). It moves by hand once the
# tooling supports it. # tooling supports it.
- dependency-name: typescript - dependency-name: typescript
update-types: [version-update:semver-major] update-types: [version-update:semver-major]
# mapbox-gl 3.33 and later read the worker registry key before handling
# Set and Error, and maplibre-gl, bundled beside it, stamps that key on
# both built-ins: every vector tile then fails with "reading 'omit'".
# glWorkerRegistry.test.ts fails on a version with that order; it moves
# by hand once mapbox-gl checks the built-ins first again.
- dependency-name: mapbox-gl
versions: ['>=3.33.0']
# The packages below move by hand, each for its reason. A security
# advisory for one of them still shows up in the Security tab, where it
# is handled together with that reason.
#
# Pinned exactly by @nestjs/schedule; a newer cron of our own would be a
# second copy whose CronJob the scheduler does not accept.
- dependency-name: cron
update-types: [version-update:semver-major, version-update:semver-minor, version-update:semver-patch]
# Root pins that must name the rollup version the lockfile installs (the
# Alpine image needs the musl binaries).
- dependency-name: '@rollup/rollup-linux-*-musl'
update-types: [version-update:semver-major, version-update:semver-minor, version-update:semver-patch]
# plugin-sdk is standalone with a lockfile of its own and ships to npm. # plugin-sdk is standalone with a lockfile of its own and ships to npm.
- package-ecosystem: npm - package-ecosystem: npm
+54 -1
View File
@@ -105,9 +105,62 @@ jobs:
track: ${{ inputs.track || 'internal' }} track: ${{ inputs.track || 'internal' }}
status: draft status: draft
# The same build for installs outside Google Play: the universal APK Google
# Play makes of this bundle, signed with the Play app signing key, published
# to liketrek/trek-android for Obtainium (wiki/Native-Apps.md). Held back
# while the app needs a server version that is not released yet.
- name: Whether the latest server release serves this build
id: released
env:
GH_TOKEN: ${{ github.token }}
run: |
tag=$(gh api "repos/$GITHUB_REPOSITORY/releases/latest" --jq .tag_name)
git fetch --depth=1 origin "refs/tags/$tag:refs/tags/$tag"
git show "$tag:server/src/nest/health/features.controller.ts" > "$RUNNER_TEMP/released-features.ts"
node scripts/ci/android-apk-release.mjs guard "$RUNNER_TEMP/released-features.ts" >> "$GITHUB_OUTPUT"
- name: Universal APK from Google Play
if: steps.released.outputs.publish == 'true'
env:
PLAY_APK_SERVICE_ACCOUNT_JSON: ${{ secrets.PLAY_APK_SERVICE_ACCOUNT_JSON }}
APK: trek-${{ steps.version.outputs.version }}.apk
run: |
printf '%s' "$PLAY_APK_SERVICE_ACCOUNT_JSON" > "$RUNNER_TEMP/play-apk.json"
node scripts/ci/android-apk-release.mjs download "$RUNNER_TEMP/play-apk.json" com.liketrek.trek \
"${{ steps.version.outputs.build }}" "$RUNNER_TEMP/$APK"
rm -f "$RUNNER_TEMP/play-apk.json"
cd "$RUNNER_TEMP" && sha256sum "$APK" > "$APK.sha256"
- uses: actions/create-github-app-token@v3
if: steps.released.outputs.publish == 'true'
id: apk-token
with:
app-id: ${{ secrets.RELEASE_APP_ID }}
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
owner: liketrek
repositories: trek-android
# One release per app version: a newer build of the same version replaces
# its APK, so the release always holds what Google Play holds for it.
- name: Publish to liketrek/trek-android
if: steps.released.outputs.publish == 'true'
env:
GH_TOKEN: ${{ steps.apk-token.outputs.token }}
VERSION: ${{ steps.version.outputs.version }}
BUILD: ${{ steps.version.outputs.build }}
run: |
apk="$RUNNER_TEMP/trek-$VERSION.apk"
notes="TREK $VERSION for Android (build $BUILD): the build Google Play distributes, with the same signature. Connect it to your own TREK server; push and TREK Cloud need Google Play services. Changes: https://github.com/liketrek/TREK/releases"
if gh release view "v$VERSION" -R liketrek/trek-android > /dev/null 2>&1; then
gh release upload "v$VERSION" -R liketrek/trek-android --clobber "$apk" "$apk.sha256"
gh release edit "v$VERSION" -R liketrek/trek-android --notes "$notes"
else
gh release create "v$VERSION" -R liketrek/trek-android --title "TREK $VERSION" --notes "$notes" "$apk" "$apk.sha256"
fi
- name: Remove the upload key - name: Remove the upload key
if: always() if: always()
run: rm -f "$RUNNER_TEMP/upload.jks" run: rm -f "$RUNNER_TEMP/upload.jks" "$RUNNER_TEMP/play-apk.json"
ios: ios:
if: github.repository == 'liketrek/TREK' if: github.repository == 'liketrek/TREK'
+17 -9
View File
@@ -35,7 +35,7 @@ permissions:
# Server tests i/10 one slice of the server suite, with coverage # Server tests i/10 one slice of the server suite, with coverage
# Server coverage merges the slices, checks the per-domain # Server coverage merges the slices, checks the per-domain
# thresholds, uploads lcov # thresholds, uploads lcov
# Server Postgres 14 i/3, Server Postgres 18 i/3 # Server Postgres 14 i/3, Server Postgres 19 i/3
# per supported major, in three slices: the probe # per supported major, in three slices: the probe
# (the repository SQL against Postgres, first slice # (the repository SQL against Postgres, first slice
# only), then a slice of the lane (every suite that # only), then a slice of the lane (every suite that
@@ -55,7 +55,7 @@ permissions:
# Client e2e i/2 one slice of the browser flows in Chromium and # Client e2e i/2 one slice of the browser flows in Chromium and
# WebKit, in the Playwright container # WebKit, in the Playwright container
# Docker and Helm builds the image and boots it until ready, on # Docker and Helm builds the image and boots it until ready, on
# SQLite and on Postgres 18; lints and renders the # SQLite and on Postgres 19; lints and renders the
# Helm chart and checks the compose files # Helm chart and checks the compose files
# Sonar SonarCloud analysis, not required # Sonar SonarCloud analysis, not required
# ci-ok the one required check (below) # ci-ok the one required check (below)
@@ -639,7 +639,7 @@ jobs:
retention-days: 1 retention-days: 1
# TREK on Postgres, once per supported major: the oldest (14) and the newest # TREK on Postgres, once per supported major: the oldest (14) and the newest
# (18). Both steps run against the same service, the probe on an empty # (19). Both steps run against the same service, the probe on an empty
# database of its own, the lane on databases it creates and drops. # database of its own, the lane on databases it creates and drops.
# #
# The probe (server/scripts/pg-probe.ts): against an empty Postgres it # The probe (server/scripts/pg-probe.ts): against an empty Postgres it
@@ -696,7 +696,7 @@ jobs:
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
postgres: [14, 18] postgres: [14, 19]
shard: [1, 2, 3] shard: [1, 2, 3]
services: services:
postgres: postgres:
@@ -757,14 +757,14 @@ jobs:
if-no-files-found: ignore if-no-files-found: ignore
retention-days: 14 retention-days: 14
# The image ships the 18 client tools, which write settings a 14 server # The image ships the 19 client tools, which write settings a 14 server
# does not know; the backup round trip runs with the same tools here. # does not know; the backup round trip runs with the same tools here.
- name: Install the PostgreSQL 18 client tools - name: Install the PostgreSQL 19 client tools
run: | run: |
set -euo pipefail set -euo pipefail
sudo /usr/share/postgresql-common/pgdg/apt.postgresql.org.sh -y >/dev/null sudo /usr/share/postgresql-common/pgdg/apt.postgresql.org.sh -y >/dev/null
sudo apt-get install -y --no-install-recommends postgresql-client-18 >/dev/null sudo apt-get install -y --no-install-recommends postgresql-client-19 >/dev/null
/usr/lib/postgresql/18/bin/pg_restore --version /usr/lib/postgresql/19/bin/pg_restore --version
- name: Run the Postgres lane - name: Run the Postgres lane
if: ${{ !cancelled() }} if: ${{ !cancelled() }}
@@ -1224,6 +1224,14 @@ jobs:
--set service.port=8080 \ --set service.port=8080 \
--set-json 'httpRoute={"enabled":true,"parentRefs":[{"name":"gateway","namespace":"gateway-system","sectionName":"https"}],"hostnames":["trek.example.com"],"paths":["/","/api"],"annotations":{"example.com/note":"custom route"},"timeouts":{"request":"0s","backendRequest":"0s"}}' \ --set-json 'httpRoute={"enabled":true,"parentRefs":[{"name":"gateway","namespace":"gateway-system","sectionName":"https"}],"hostnames":["trek.example.com"],"paths":["/","/api"],"annotations":{"example.com/note":"custom route"},"timeouts":{"request":"0s","backendRequest":"0s"}}' \
> "$out/http-route-variants.yaml" > "$out/http-route-variants.yaml"
helm template trek charts/trek \
--set-json 'extraObjects=[{"apiVersion":"batch/v1","kind":"CronJob","metadata":{"name":"{{ include \"trek.fullname\" . }}-backup-copy"},"spec":{"schedule":"0 3 * * *","jobTemplate":{"spec":{"template":{"spec":{"restartPolicy":"OnFailure","containers":[{"name":"copy","image":"busybox:1.36","command":["ls","/data/backups"],"volumeMounts":[{"name":"data","mountPath":"/data","readOnly":true}]}],"volumes":[{"name":"data","persistentVolumeClaim":{"claimName":"{{ include \"trek.fullname\" . }}-data","readOnly":true}}]}}}}}},"apiVersion: v1\nkind: ConfigMap\nmetadata:\n name: {{ .Release.Name }}-notes\ndata:\n release: {{ .Release.Name | quote }}\n"]' \
> "$out/extra-objects.yaml"
# kubeconform accepts a name that still reads {{ ... }}, so check that both forms went through tpl.
if grep -n '{{' "$out/extra-objects.yaml"; then
echo "::error::extraObjects left a template unrendered"
exit 1
fi
- name: Check the manifests against the Kubernetes schemas - name: Check the manifests against the Kubernetes schemas
# The pinned Gateway API schema adds HTTPRoute validation without skipping unknown resources. # The pinned Gateway API schema adds HTTPRoute validation without skipping unknown resources.
@@ -1339,7 +1347,7 @@ jobs:
set -euo pipefail set -euo pipefail
docker network create trek-ci-pg docker network create trek-ci-pg
docker run -d --name trek-ci-db --network trek-ci-pg \ docker run -d --name trek-ci-db --network trek-ci-pg \
-e POSTGRES_PASSWORD=ci -e POSTGRES_DB=trek postgres:18 -e POSTGRES_PASSWORD=ci -e POSTGRES_DB=trek postgres:19
for _ in $(seq 1 30); do for _ in $(seq 1 30); do
docker exec trek-ci-db pg_isready -U postgres -d trek >/dev/null 2>&1 && break docker exec trek-ci-db pg_isready -U postgres -d trek >/dev/null 2>&1 && break
sleep 2 sleep 2
+1 -1
View File
@@ -137,7 +137,7 @@ These principles come out of a full-repo audit and shape all new code:
## Quality gates in CI ## Quality gates in CI
`.github/workflows/test.yml` runs, per package: typecheck (server also `typecheck:tests`, client also the strict-mode ratchet `lint:strict`), lint (client and server through `lint:warnings`, which also holds the warning count per rule), `lint:pages`, `lint:rtl`, `lint:size` (client and server), the server's `lint:strict`, `lint:boundaries`, `lint:tx`, `lint:dialect`, `lint:engine-dispatch`, `lint:test-sql`, `lint:test-mocks`, `lint:test-new-service`, `lint:query-api`, `lint:mcp-zod`, `lint:service-http` and `lint:response-contracts`, the client's and server's `lint:format`, `lint:layers`, `lint:offline`, `lint:dup`, `lint:pairs`, `lint:skips`, `lint:i18n-keys` and `theme:lint`, shared's `contracts:open`, the repo-wide `lint:knip` (in `server-lint`), `check:plugin-facts`, `i18n:parity:strict` (with the untranslated-strings ratchet), the S3 contract suite, TREK on Postgres (`server-postgres`, once per supported major, 14 and 18, each in three slices: first the Postgres probe (in the first slice), every dialect helper on SQLite and Postgres and the statements every repository method reaches with sample arguments, its SQL errors per method and the methods it cannot measure held to a baseline that only shrinks and fails while it is still unmeasured; then the Postgres lane, every suite that boots the app on the real database module, found by `server/tests/postgres/lane.ts` rather than listed, plus PARITY-PG and the write lock; see `server/CLAUDE.md`), the browser end-to-end flows (Chromium and WebKit, in the Playwright container, in two slices), a client build with `check:gl-split`, coverage for all four packages, then a SonarCloud scan. It also builds the Docker image and boots it until `/api/health/ready` answers, on SQLite and on Postgres 18, and lints and renders the Helm chart against the Kubernetes schemas and runs `docker compose config` on every compose file (both in `docker`, each part when its area changed). `lint-prettier.yml` additionally runs `lint` + `lint:format` on `shared/`, both check-only. `plugin-sdk` has no lint script and is outside the eslint gates. **Not in CI**: the screenshot and help-media Playwright projects; run them locally. There are no git hooks; nothing runs before a commit except you. Other workflows build Docker images, scan them, and publish `trek-plugin-sdk` on `plugin-sdk-v*` tags. `.github/workflows/test.yml` runs, per package: typecheck (server also `typecheck:tests`, client also the strict-mode ratchet `lint:strict`), lint (client and server through `lint:warnings`, which also holds the warning count per rule), `lint:pages`, `lint:rtl`, `lint:size` (client and server), the server's `lint:strict`, `lint:boundaries`, `lint:tx`, `lint:dialect`, `lint:engine-dispatch`, `lint:test-sql`, `lint:test-mocks`, `lint:test-new-service`, `lint:query-api`, `lint:mcp-zod`, `lint:service-http` and `lint:response-contracts`, the client's and server's `lint:format`, `lint:layers`, `lint:offline`, `lint:dup`, `lint:pairs`, `lint:skips`, `lint:i18n-keys` and `theme:lint`, shared's `contracts:open`, the repo-wide `lint:knip` (in `server-lint`), `check:plugin-facts`, `i18n:parity:strict` (with the untranslated-strings ratchet), the S3 contract suite, TREK on Postgres (`server-postgres`, once per supported major, 14 and 19, each in three slices: first the Postgres probe (in the first slice), every dialect helper on SQLite and Postgres and the statements every repository method reaches with sample arguments, its SQL errors per method and the methods it cannot measure held to a baseline that only shrinks and fails while it is still unmeasured; then the Postgres lane, every suite that boots the app on the real database module, found by `server/tests/postgres/lane.ts` rather than listed, plus PARITY-PG and the write lock; see `server/CLAUDE.md`), the browser end-to-end flows (Chromium and WebKit, in the Playwright container, in two slices), a client build with `check:gl-split`, coverage for all four packages, then a SonarCloud scan. It also builds the Docker image and boots it until `/api/health/ready` answers, on SQLite and on Postgres 19, and lints and renders the Helm chart against the Kubernetes schemas and runs `docker compose config` on every compose file (both in `docker`, each part when its area changed). `lint-prettier.yml` additionally runs `lint` + `lint:format` on `shared/`, both check-only. `plugin-sdk` has no lint script and is outside the eslint gates. **Not in CI**: the screenshot and help-media Playwright projects; run them locally. There are no git hooks; nothing runs before a commit except you. Other workflows build Docker images, scan them, and publish `trek-plugin-sdk` on `plugin-sdk-v*` tags.
- **Job names read "<Area> <what>[ <variant>][ i/n]"** (`Server tests 3/10`, `Server Postgres 14 2/3`, `Docker and Helm`): the area first, one of Changes, Shared, Server, Client, Docker or Sonar, then lower case, with no colon, no parentheses and no middle dot, and a slice only at the end, so the checks list sorts by area. The workflow is named `CI`, so a check reads `CI / Server tests 3/10`. Job ids are the names in kebab-case (`server-tests`), the jobs stand in `test.yml` in area order, and the list at the top of `test.yml` says what each job holds. A new job follows the scheme and joins that list; `scripts/ci/workflow-jobs.test.mjs` fails on a name outside it. `ci-ok`, `lint` and `check-target` keep their names: the ruleset requires them by name. - **Job names read "<Area> <what>[ <variant>][ i/n]"** (`Server tests 3/10`, `Server Postgres 14 2/3`, `Docker and Helm`): the area first, one of Changes, Shared, Server, Client, Docker or Sonar, then lower case, with no colon, no parentheses and no middle dot, and a slice only at the end, so the checks list sorts by area. The workflow is named `CI`, so a check reads `CI / Server tests 3/10`. Job ids are the names in kebab-case (`server-tests`), the jobs stand in `test.yml` in area order, and the list at the top of `test.yml` says what each job holds. A new job follows the scheme and joins that list; `scripts/ci/workflow-jobs.test.mjs` fails on a name outside it. `ci-ok`, `lint` and `check-target` keep their names: the ruleset requires them by name.
- **What the folded jobs hold.** `Shared tests` is the plugin SDK's typecheck and coverage, run before the root install so the SDK resolves only its own dependencies, then i18n parity and shared's coverage. `Client types` is the typecheck and the strict ratchet; `Client checks` the source ratchets, then the production build with `check:gl-split`. `Docker and Helm` builds and boots the image when the image area changed and checks the chart and compose files when the deploy area changed. Inside a folded job each group of steps runs after a failure in another, so one red check shows every gate that failed; the step names say which. - **What the folded jobs hold.** `Shared tests` is the plugin SDK's typecheck and coverage, run before the root install so the SDK resolves only its own dependencies, then i18n parity and shared's coverage. `Client types` is the typecheck and the strict ratchet; `Client checks` the source ratchets, then the production build with `check:gl-split`. `Docker and Helm` builds and boots the image when the image area changed and checks the chart and compose files when the deploy area changed. Inside a folded job each group of steps runs after a failure in another, so one red check shows every gate that failed; the step names say which.
+19 -9
View File
@@ -73,22 +73,30 @@ COPY server/package.json ./server/
# The upgrade takes the Debian security fixes the base image was built before # The upgrade takes the Debian security fixes the base image was built before
# (zlib, 11/2026, failed the image scan until node:24-trixie-slim caught up). # (zlib, 11/2026, failed the image scan until node:24-trixie-slim caught up).
# #
# postgresql-client-18 brings pg_dump, pg_restore and psql to # postgresql-client-19 brings pg_dump, pg_restore and psql to
# /usr/lib/postgresql/18/bin, which back up and restore an install on Postgres # /usr/lib/postgresql/19/bin, which back up and restore an install on Postgres
# (TREK_DB_URL). A client handles every server up to its own major and refuses # (TREK_DB_URL). A client handles every server up to its own major and refuses
# a newer one, so the image carries the newest major TREK supports (14 to 18). # a newer one, so the image carries the newest major TREK supports (14 to 19).
# Debian 13 ships 17 only, so it comes from the PostgreSQL project's apt # Debian 13 ships 17 only, so it comes from the PostgreSQL project's apt
# repository (PGDG): the `18` component lists that major's packages and no # repository (PGDG): its `main` component carries every major the project
# other, and the repository's signing key (fingerprint B97B 0AFC AA1A 47F0 44F2 # supports, and the package name pins the one installed. The per-major
# 44A0 7FCC 7D46 ACCC 4CF8) is kept beside the entrypoint instead of fetched at # components can trail a new release, so the image does not rely on them. The
# build time. Raise both together when TREK supports a newer major. # repository's signing key (fingerprint B97B 0AFC AA1A 47F0 44F2 44A0 7FCC 7D46
# ACCC 4CF8) is kept beside the entrypoint instead of fetched at build time.
# Raise the package together with SUPPORTED_SERVER_MAJORS in
# server/src/db/engine/postgres/server-checks.ts.
# Earlier images carried the version 18 tools, and installs that set
# TREK_DB_PG_BIN_DIR=/usr/lib/postgresql/18/bin (the old .env.example value)
# would lose backups and the pre-migrate snapshot after updating, so that path
# stays as a link to the 19 tools, which handle every supported server.
COPY server/scripts/pgdg-apt-key.asc /etc/apt/keyrings/pgdg.asc COPY server/scripts/pgdg-apt-key.asc /etc/apt/keyrings/pgdg.asc
RUN echo 'deb [signed-by=/etc/apt/keyrings/pgdg.asc] http://apt.postgresql.org/pub/repos/apt trixie-pgdg main 18' \ RUN echo 'deb [signed-by=/etc/apt/keyrings/pgdg.asc] http://apt.postgresql.org/pub/repos/apt trixie-pgdg main' \
> /etc/apt/sources.list.d/pgdg.list && \ > /etc/apt/sources.list.d/pgdg.list && \
apt-get update && \ apt-get update && \
apt-get upgrade -y --no-install-recommends && \ apt-get upgrade -y --no-install-recommends && \
apt-get install -y --no-install-recommends tzdata dumb-init wget ca-certificates \ apt-get install -y --no-install-recommends tzdata dumb-init wget ca-certificates \
libkitinerary-bin libsqlite3-0 postgresql-client-18 && \ libkitinerary-bin libsqlite3-0 postgresql-client-19 && \
mkdir -p /usr/lib/postgresql/18 && ln -s /usr/lib/postgresql/19/bin /usr/lib/postgresql/18/bin && \
npm ci --workspace=server --omit=dev --ignore-scripts && \ npm ci --workspace=server --omit=dev --ignore-scripts && \
{ ln -sf "$(find /usr/lib -name kitinerary-extractor -type f | head -1)" /usr/local/bin/kitinerary-extractor || true; } && \ { ln -sf "$(find /usr/lib -name kitinerary-extractor -type f | head -1)" /usr/local/bin/kitinerary-extractor || true; } && \
rm -rf /var/lib/apt/lists/* /usr/local/lib/node_modules/npm /usr/local/bin/npm /usr/local/bin/npx && \ rm -rf /var/lib/apt/lists/* /usr/local/lib/node_modules/npm /usr/local/bin/npm /usr/local/bin/npx && \
@@ -101,6 +109,8 @@ COPY --from=gosu-build /out/gosu /usr/local/bin/gosu
ENV XDG_CACHE_HOME=/tmp/kf6-cache ENV XDG_CACHE_HOME=/tmp/kf6-cache
# Prevent Qt from probing for a display in headless containers. # Prevent Qt from probing for a display in headless containers.
ENV QT_QPA_PLATFORM=offscreen ENV QT_QPA_PLATFORM=offscreen
# A UTF-8 locale, so Qt does not warn about the C locale on every extractor run.
ENV LANG=C.UTF-8
# Fixed path for both amd64 (static binary) and arm64 (symlink to apt binary). # Fixed path for both amd64 (static binary) and arm64 (symlink to apt binary).
# Override with KITINERARY_EXTRACTOR_PATH if you install it elsewhere. # Override with KITINERARY_EXTRACTOR_PATH if you install it elsewhere.
ENV KITINERARY_EXTRACTOR_PATH=/usr/local/bin/kitinerary-extractor ENV KITINERARY_EXTRACTOR_PATH=/usr/local/bin/kitinerary-extractor
+15 -60
View File
@@ -12,14 +12,14 @@ TREK has grown from a travel planner into a whole ecosystem for trips: plan toge
<br /> <br />
<a href="https://apps.apple.com/app/id6831237775"><picture><source media="(prefers-color-scheme: dark)" srcset="docs/app/app-store-dark.svg" /><source media="(prefers-color-scheme: light)" srcset="docs/app/app-store-light.svg" /><img src="docs/app/app-store-light.svg" alt="Download TREK on the App Store, with a QR code" width="320" /></picture></a>
&nbsp;
<a href="https://play.google.com/store/apps/details?id=com.liketrek.trek"><picture><source media="(prefers-color-scheme: dark)" srcset="docs/app/google-play-dark.svg" /><source media="(prefers-color-scheme: light)" srcset="docs/app/google-play-light.svg" /><img src="docs/app/google-play-light.svg" alt="Get TREK on Google Play, with a QR code" width="320" /></picture></a>
<br />
<a href="https://demo.liketrek.com"><img alt="Demo" src="https://img.shields.io/badge/Demo-try-111827?style=for-the-badge" /></a> <a href="https://demo.liketrek.com"><img alt="Demo" src="https://img.shields.io/badge/Demo-try-111827?style=for-the-badge" /></a>
&nbsp; &nbsp;
<a href="https://hub.docker.com/r/mauriceboe/trek"><img alt="Docker" src="https://img.shields.io/badge/Docker-ready-2496ED?style=for-the-badge" /></a>
&nbsp;
<a href="https://sonarcloud.io/project/overview?id=liketrek_TREK"><img alt="Sonar Quality Gate" src="https://img.shields.io/sonar/quality_gate/liketrek_TREK?server=https%3A%2F%2Fsonarcloud.io&style=for-the-badge" /></a>
&nbsp;
<img alt="GitHub Actions Workflow Status" src="https://img.shields.io/github/actions/workflow/status/liketrek/TREK/test.yml?branch=main&style=for-the-badge">
&nbsp;
<a href="https://discord.gg/NhZBDSd4qW"><img alt="Discord" src="https://img.shields.io/badge/Discord-join-5865F2?style=for-the-badge" /></a> <a href="https://discord.gg/NhZBDSd4qW"><img alt="Discord" src="https://img.shields.io/badge/Discord-join-5865F2?style=for-the-badge" /></a>
&nbsp; &nbsp;
<a href="https://kanban.pakulat.org/shared/I4wxF6inOOMB0C6hH6kQm3efyNxFjwyI"><img alt="Roadmap" src="https://img.shields.io/badge/Roadmap-view-0EA5E9?style=for-the-badge" /></a> <a href="https://kanban.pakulat.org/shared/I4wxF6inOOMB0C6hH6kQm3efyNxFjwyI"><img alt="Roadmap" src="https://img.shields.io/badge/Roadmap-view-0EA5E9?style=for-the-badge" /></a>
@@ -38,7 +38,6 @@ TREK has grown from a travel planner into a whole ecosystem for trips: plan toge
&nbsp; &nbsp;
<a href="https://github.com/liketrek/TREK"><img alt="Stars" src="https://img.shields.io/github/stars/liketrek/trek?style=for-the-badge&label=Stars&color=6B7280" /></a> <a href="https://github.com/liketrek/TREK"><img alt="Stars" src="https://img.shields.io/github/stars/liketrek/trek?style=for-the-badge&label=Stars&color=6B7280" /></a>
<sub>PUBLIC SERVICES PROUDLY SPONSORED BY</sub><br /><a href="https://cloud.dataforest.net/en?mtm_campaign=trek"><picture><source media="(prefers-color-scheme: dark)" srcset="docs/sponsors/dataforest-light.svg" /><source media="(prefers-color-scheme: light)" srcset="docs/sponsors/dataforest-dark.svg" /><img src="docs/sponsors/dataforest-dark.svg" alt="dataforest cloud" height="30" /></picture></a>
</div> </div>
--- ---
@@ -53,14 +52,8 @@ TREK has grown from a travel planner into a whole ecosystem for trips: plan toge
## What you get ## What you get
<picture>
<source media="(max-width: 700px)" srcset="docs/tiles/grid-mobile.svg" />
<source media="(prefers-color-scheme: dark)" srcset="docs/tiles/grid-desktop-dark.svg" />
<img src="docs/tiles/grid-desktop.svg" alt="Plan, track, share" width="100%" />
</picture>
<details> <details>
<summary><b>See all features</b></summary> <summary><h3>See all features</h3></summary>
<br /> <br />
@@ -220,34 +213,12 @@ Most of what follows is an addon an admin switches on or off. Lists, Costs, Docu
<br /> <br />
## Powered by [dataforest cloud](https://cloud.dataforest.net/en?mtm_campaign=trek)
<div align="center"> <div align="center">
<br /> <sub>POWERED BY</sub><br />
<a href="https://cloud.dataforest.net/en?mtm_campaign=trek"><picture><source media="(prefers-color-scheme: dark)" srcset="docs/sponsors/dataforest-light.svg" /><source media="(prefers-color-scheme: light)" srcset="docs/sponsors/dataforest-dark.svg" /><img src="docs/sponsors/dataforest-dark.svg" alt="dataforest cloud" height="40" /></picture></a>
<a href="https://cloud.dataforest.net/en?mtm_campaign=trek"> The place index with 88 million places, the address search and the planet-wide routing run on <a href="https://cloud.dataforest.net/en?mtm_campaign=trek">dataforest cloud</a> in Frankfurt, free for every self-hosted TREK. Thank you! 💚
<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/sponsors/dataforest-light.svg" />
<source media="(prefers-color-scheme: light)" srcset="docs/sponsors/dataforest-dark.svg" />
<img src="docs/sponsors/dataforest-dark.svg" alt="dataforest cloud" height="60" />
</picture>
</a>
<br />
<br />
**Every TREK installation in the world searches through servers that [dataforest cloud](https://cloud.dataforest.net/en?mtm_campaign=trek) sponsors.**
The place index with over 88 million places, the address search in every TREK language and the planet-wide routing all run on [dataforest cloud](https://cloud.dataforest.net/en?mtm_campaign=trek) in Frankfurt, Germany, free of charge for everyone who self-hosts TREK. Without this sponsorship, these services would not exist in this form.
Thank you, [dataforest](https://cloud.dataforest.net/en?mtm_campaign=trek), for backing open source this generously. 💚
<br />
<a href="https://cloud.dataforest.net/en?mtm_campaign=trek"><img alt="Visit dataforest cloud" src="https://img.shields.io/badge/Visit-dataforest_cloud-02C382?style=for-the-badge" /></a>
Looking for a server for your own TREK? [dataforest cloud](https://cloud.dataforest.net/en?mtm_campaign=trek) is where TREK's own services live.
</div> </div>
@@ -255,13 +226,7 @@ Looking for a server for your own TREK? [dataforest cloud](https://cloud.datafor
## AI usage ## AI usage
We use LLM-assisted coding tools across parts of this codebase. Nothing ships that a We use LLM-assisted coding tools, and nothing ships that a maintainer has not read, reviewed, tested and can answer for. More in [How we use AI in TREK](https://github.com/liketrek/TREK/discussions/1851).
maintainer has not read and understood: every change goes through a pull request, is
reviewed and tested, and has a human who can answer for it. "The AI wrote that" is not
an answer any of us would accept from ourselves.
See [**How we use AI in TREK**](https://github.com/liketrek/TREK/discussions/1851) for
the details.
<br /> <br />
@@ -285,7 +250,7 @@ Open `http://localhost:3000`, or `http://<server-ip>:3000` from another machine.
<div align="center"> <div align="center">
<a href="#docker-compose-production">Docker Compose</a>&nbsp;&nbsp;·&nbsp;&nbsp;<a href="#helm-kubernetes">Helm / Kubernetes</a>&nbsp;&nbsp;·&nbsp;&nbsp;<a href="#install-as-app-pwa">Install as PWA</a>&nbsp;&nbsp;·&nbsp;&nbsp;<a href="#reverse-proxy">Reverse Proxy</a> <a href="#docker-compose-production">Docker Compose</a>&nbsp;&nbsp;·&nbsp;&nbsp;<a href="#helm-kubernetes">Helm / Kubernetes</a>&nbsp;&nbsp;·&nbsp;&nbsp;<a href="#reverse-proxy">Reverse Proxy</a>
</div> </div>
@@ -323,7 +288,7 @@ docker compose up -d
See [Install with Docker Compose](https://github.com/liketrek/TREK/wiki/Install-Docker-Compose) See [Install with Docker Compose](https://github.com/liketrek/TREK/wiki/Install-Docker-Compose)
for the full walkthrough. for the full walkthrough.
TREK stores its data in SQLite by default. Set `TREK_DB_URL` to run it on a PostgreSQL 14 to 18 database instead. The TREK stores its data in SQLite by default. Set `TREK_DB_URL` to run it on a PostgreSQL 14 to 19 database instead. The
[`docker-compose.postgres.yml`](docker-compose.postgres.yml) example starts one beside TREK, and the [`docker-compose.postgres.yml`](docker-compose.postgres.yml) example starts one beside TREK, and the
[Postgres guide](https://github.com/liketrek/TREK/wiki/Database-Postgres) covers the requirements, the backups and [Postgres guide](https://github.com/liketrek/TREK/wiki/Database-Postgres) covers the requirements, the backups and
how to move an existing SQLite install to Postgres with the command TREK ships for it. how to move an existing SQLite install to Postgres with the command TREK ships for it.
@@ -342,18 +307,6 @@ See [`charts/README.md`](https://github.com/liketrek/TREK/blob/main/charts/READM
<br /> <br />
<h2 id="install-as-app-pwa">Install as App (PWA)</h2>
TREK works as a Progressive Web App, and the TREK Travel Planner app for iPhone, iPad and Android connects to the same server ([Native Apps](https://github.com/liketrek/TREK/wiki/Native-Apps)). To install the web app instead:
1. Open TREK in the browser (HTTPS required)
2. **iOS**: Share ▸ *Add to Home Screen*
3. **Android**: Menu ▸ *Install app* (or *Add to Home Screen*)
TREK then launches fullscreen with its own icon, just like a native app.
<br />
## Updating ## Updating
See [Updating](https://github.com/liketrek/TREK/wiki/Updating) — Docker Compose, See [Updating](https://github.com/liketrek/TREK/wiki/Updating) — Docker Compose,
@@ -442,6 +395,8 @@ Caddy handles TLS and WebSockets automatically.
Every variable, its default and what it does: see Every variable, its default and what it does: see
[Environment Variables](https://github.com/liketrek/TREK/wiki/Environment-Variables). [Environment Variables](https://github.com/liketrek/TREK/wiki/Environment-Variables).
<br />
## Data sources ## Data sources
The Atlas map's country and sub-national (province/county) boundaries come from The Atlas map's country and sub-national (province/county) boundaries come from
+1
View File
@@ -60,3 +60,4 @@ See `values.yaml` for more options.
- Set `env.OIDC_DISCOVERY_URL` to override the auto-constructed OIDC discovery endpoint. Required for providers (e.g. Authentik) that expose it at a non-standard path. - Set `env.OIDC_DISCOVERY_URL` to override the auto-constructed OIDC discovery endpoint. Required for providers (e.g. Authentik) that expose it at a non-standard path.
- `podSecurityContext` defaults to `fsGroup: 1000` with `fsGroupChangePolicy: OnRootMismatch`, and `securityContext` (the container's) is empty. The container then starts as root, hands `/app/data` and `/app/uploads` to `node` (uid 1000) if the directory or anything directly inside it is not owned by `node` yet, and drops to `node`. Deeper files are not checked. Only the owning user is changed (plus a `root` group), so a different `fsGroup` stays in place. A volume that refuses `chown` (NFS with `root_squash`) logs a warning instead; set `runAsUser: 1000` then. To run as `node` from the start, for example under the `restricted` Pod Security Standard, set `podSecurityContext.runAsUser: 1000` and `runAsGroup: 1000`; the image then skips that step and the privilege drop. See the example in `values.yaml`. - `podSecurityContext` defaults to `fsGroup: 1000` with `fsGroupChangePolicy: OnRootMismatch`, and `securityContext` (the container's) is empty. The container then starts as root, hands `/app/data` and `/app/uploads` to `node` (uid 1000) if the directory or anything directly inside it is not owned by `node` yet, and drops to `node`. Deeper files are not checked. Only the owning user is changed (plus a `root` group), so a different `fsGroup` stays in place. A volume that refuses `chown` (NFS with `root_squash`) logs a warning instead; set `runAsUser: 1000` then. To run as `node` from the start, for example under the `restricted` Pod Security Standard, set `podSecurityContext.runAsUser: 1000` and `runAsGroup: 1000`; the image then skips that step and the privilege drop. See the example in `values.yaml`.
- Use `extraVolumes` and `extraVolumeMounts` to add your own volumes to the pod. To give the booking import more KItinerary extractors, mount a ConfigMap at `/usr/local/share/kitinerary/extractors`, with one `.json` and one `.js` key for each extractor; see the example in `values.yaml`. - Use `extraVolumes` and `extraVolumeMounts` to add your own volumes to the pod. To give the booking import more KItinerary extractors, mount a ConfigMap at `/usr/local/share/kitinerary/extractors`, with one `.json` and one `.js` key for each extractor; see the example in `values.yaml`.
- Use `extraObjects` to render further Kubernetes objects next to the chart's own, for example a backup `CronJob`. Each item is a map or a string of YAML, and `{{ }}` in it is evaluated, so `{{ .Release.Name }}` works. A backup job should copy TREK's own backups from `backups/` on the data volume and mount it read only, since that volume also holds the encryption key. The archives carry `.encryption_key` too unless `ENCRYPTION_KEY` is set, so protect the copy's destination like the data volume.
+2 -2
View File
@@ -1,5 +1,5 @@
apiVersion: v2 apiVersion: v2
name: trek name: trek
version: 5.2.0 version: 5.2.1
description: Minimal Helm chart for TREK app description: Minimal Helm chart for TREK app
appVersion: "5.2.0" appVersion: "5.2.1"
+8
View File
@@ -0,0 +1,8 @@
{{- range .Values.extraObjects }}
---
{{- if kindIs "string" . }}
{{ tpl . $ }}
{{- else }}
{{ tpl (toYaml .) $ }}
{{- end }}
{{- end }}
+24 -1
View File
@@ -190,7 +190,7 @@ env:
# starting it on SQLite. The role in the URL owns TREK's database and must not be a superuser # starting it on SQLite. The role in the URL owns TREK's database and must not be a superuser
# (nor a member of one, nor hold a right that reaches the server's files or programs): a # (nor a member of one, nor hold a right that reaches the server's files or programs): a
# restore runs the backup's SQL as that role and refuses one that could reach the database host. The wiki page shows the # restore runs the backup's SQL as that role and refuses one that could reach the database host. The wiki page shows the
# SQL that creates such a role. PostgreSQL 14 to 18 is supported. # SQL that creates such a role. PostgreSQL 14 to 19 is supported.
# url: "postgres://trek:<password>@postgres.example.internal:5432/trek?sslmode=require" # url: "postgres://trek:<password>@postgres.example.internal:5432/trek?sslmode=require"
database: database:
url: "" url: ""
@@ -338,6 +338,29 @@ extraVolumes: []
# readOnly: true # readOnly: true
extraVolumeMounts: [] extraVolumeMounts: []
# Further Kubernetes objects the chart renders next to its own, for example a Job, a
# CronJob or a ConfigMap. Each item is rendered as written, either as a map or as a
# string of YAML, and {{ }} in it is evaluated, so {{ include "trek.fullname" . }} or
# {{ .Release.Name }} work, in both forms. Write literal braces as {{ "{{" }}.
# A backup job must only read the data volume: it also holds the encryption key and the
# server's secrets, and a second writer corrupts travel.db. Rather than copying the live
# travel.db, copy TREK's own backups (Admin, Backup, automatic backups) from backups/ in
# that volume. Those archives carry .encryption_key too (unless ENCRYPTION_KEY is set),
# so protect the job's destination like the data volume itself.
# extraObjects:
# - apiVersion: v1
# kind: ConfigMap
# metadata:
# name: '{{ include "trek.fullname" . }}-extra'
# data:
# note: hello
# - |
# apiVersion: v1
# kind: ConfigMap
# metadata:
# name: {{ .Release.Name }}-notes
extraObjects: []
resources: resources:
requests: requests:
cpu: 100m cpu: 100m
+26 -5
View File
@@ -204,11 +204,32 @@
--sea: #cfe3ef; --sea: #cfe3ef;
--text-face: 'Plus Jakarta Sans', system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif; --text-face: 'Plus Jakarta Sans', system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
--display-face: 'Poppins', system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif; --display-face: 'Poppins', system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
/* The insets of the device, from the web view or, on iOS, from the native side. */ /* The insets of the device, from the web view or from the native side. On
--safe-top: max(env(safe-area-inset-top, 0px), var(--trek-native-safe-top, 0px)); * Android a web view can report env() as 0 while the page reaches under the
--safe-bottom: max(env(safe-area-inset-bottom, 0px), var(--trek-native-safe-bottom, 0px)); * status and navigation bars; Capacitor's SystemBars writes the real insets
--safe-start: max(env(safe-area-inset-left, 0px), var(--trek-native-safe-left, 0px)); * to --safe-area-inset-* instead (0 where it lays the web view out between
--safe-end: max(env(safe-area-inset-right, 0px), var(--trek-native-safe-right, 0px)); * the bars). iOS measures its own (TrekBridgeViewController publishSafeArea).
* In a browser the variables are unset: env() alone. */
--safe-top: max(
env(safe-area-inset-top, 0px),
var(--safe-area-inset-top, 0px),
var(--trek-native-safe-top, 0px)
);
--safe-bottom: max(
env(safe-area-inset-bottom, 0px),
var(--safe-area-inset-bottom, 0px),
var(--trek-native-safe-bottom, 0px)
);
--safe-start: max(
env(safe-area-inset-left, 0px),
var(--safe-area-inset-left, 0px),
var(--trek-native-safe-left, 0px)
);
--safe-end: max(
env(safe-area-inset-right, 0px),
var(--safe-area-inset-right, 0px),
var(--trek-native-safe-right, 0px)
);
color-scheme: light; color-scheme: light;
-webkit-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;
} }
+7 -7
View File
@@ -1,6 +1,6 @@
{ {
"name": "@trek/client", "name": "@trek/client",
"version": "5.2.0", "version": "5.2.1",
"engines": { "engines": {
"node": "^22.22.2 || ^24.15.0 || >=26.0.0" "node": "^22.22.2 || ^24.15.0 || >=26.0.0"
}, },
@@ -103,7 +103,7 @@
"@fontsource/yellowtail": "^5.3.0", "@fontsource/yellowtail": "^5.3.0",
"@maplibre/maplibre-gl-leaflet": "0.1.4", "@maplibre/maplibre-gl-leaflet": "0.1.4",
"@noble/hashes": "^1.8.0", "@noble/hashes": "^1.8.0",
"@simplewebauthn/browser": "^13.3.0", "@simplewebauthn/browser": "^14.0.0",
"@trek/shared": "*", "@trek/shared": "*",
"axios": "^1.21.0", "axios": "^1.21.0",
"dexie": "^4.4.7", "dexie": "^4.4.7",
@@ -112,13 +112,13 @@
"iso-3166-2": "^1.0.0", "iso-3166-2": "^1.0.0",
"leaflet": "^1.9.4", "leaflet": "^1.9.4",
"lucide-react": "^0.577.0", "lucide-react": "^0.577.0",
"mapbox-gl": "^3.35.2", "mapbox-gl": "3.32.0",
"maplibre-gl": "6.19.0", "maplibre-gl": "6.19.0",
"modern-screenshot": "4.7.0", "modern-screenshot": "4.7.0",
"plyr": "^3.8.5", "plyr": "^3.8.5",
"react": "^19.3.1", "react": "^19.3.1",
"react-dom": "^19.3.1", "react-dom": "^19.3.1",
"react-dropzone": "^14.4.1", "react-dropzone": "^20.2.1",
"react-leaflet": "^5.0.0", "react-leaflet": "^5.0.0",
"react-leaflet-cluster": "^4.1.3", "react-leaflet-cluster": "^4.1.3",
"react-markdown": "^10.1.0", "react-markdown": "^10.1.0",
@@ -141,7 +141,7 @@
"@testing-library/user-event": "^14.6.13", "@testing-library/user-event": "^14.6.13",
"@trivago/prettier-plugin-sort-imports": "^6.0.2", "@trivago/prettier-plugin-sort-imports": "^6.0.2",
"@types/leaflet": "^1.9.22", "@types/leaflet": "^1.9.22",
"@types/node": "^25.9.8", "@types/node": "^26.6.11",
"@types/react": "^19.3.0", "@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0", "@types/react-dom": "^19.3.0",
"@vitejs/plugin-react": "^6.2.1", "@vitejs/plugin-react": "^6.2.1",
@@ -154,7 +154,7 @@
"eslint-plugin-react-refresh": "^0.5.8", "eslint-plugin-react-refresh": "^0.5.8",
"fake-indexeddb": "^6.2.7", "fake-indexeddb": "^6.2.7",
"jsdom": "^29.1.1", "jsdom": "^29.1.1",
"msw": "^2.15.0", "msw": "^3.0.8",
"postcss": "^8.5.33", "postcss": "^8.5.33",
"prettier": "^3.10.1", "prettier": "^3.10.1",
"prettier-plugin-organize-imports": "^4.3.0", "prettier-plugin-organize-imports": "^4.3.0",
@@ -163,7 +163,7 @@
"sharp": "^0.35.5", "sharp": "^0.35.5",
"tailwindcss": "^3.4.19", "tailwindcss": "^3.4.19",
"typescript": "^6.0.3", "typescript": "^6.0.3",
"typescript-eslint": "^8.72.1", "typescript-eslint": "^8.73.0",
"vite": "8.3.8", "vite": "8.3.8",
"vite-plugin-pwa": "^2.0.0", "vite-plugin-pwa": "^2.0.0",
"vitest": "^4.1.12" "vitest": "^4.1.12"
+2 -2
View File
@@ -1,6 +1,6 @@
{ {
"src": { "src": {
"@typescript-eslint/no-non-null-assertion": 367, "@typescript-eslint/no-non-null-assertion": 354,
"@typescript-eslint/no-misused-promises": 820, "@typescript-eslint/no-misused-promises": 820,
"no-console": 88, "no-console": 88,
"complexity": 216, "complexity": 216,
@@ -15,7 +15,7 @@
"@typescript-eslint/no-unused-vars": 117, "@typescript-eslint/no-unused-vars": 117,
"react-hooks/immutability": 28, "react-hooks/immutability": 28,
"max-lines-per-function": 127, "max-lines-per-function": 127,
"react-hooks/static-components": 50, "react-hooks/static-components": 38,
"react-hooks/preserve-manual-memoization": 12, "react-hooks/preserve-manual-memoization": 12,
"no-useless-assignment": 7, "no-useless-assignment": 7,
"no-empty": 19, "no-empty": 19,
-1
View File
@@ -2121,7 +2121,6 @@
"tests/unit/sync/tripSyncManager.test.ts", "tests/unit/sync/tripSyncManager.test.ts",
"tests/unit/tripStore.test.ts", "tests/unit/tripStore.test.ts",
"tests/unit/utils/cleanAmount.test.ts", "tests/unit/utils/cleanAmount.test.ts",
"tests/unit/utils/fileDownload.test.ts",
"tests/unit/utils/formatters.test.ts", "tests/unit/utils/formatters.test.ts",
"tests/unit/utils/placeFiles.test.ts", "tests/unit/utils/placeFiles.test.ts",
"tests/unit/utils/shellGuard.test.ts", "tests/unit/utils/shellGuard.test.ts",
+3 -3
View File
@@ -8,16 +8,16 @@
"src/components/Map/MapView.tsx": 1200, "src/components/Map/MapView.tsx": 1200,
"src/components/Map/MapViewGL.test.tsx": 2919, "src/components/Map/MapViewGL.test.tsx": 2919,
"src/components/Map/MapViewGL.tsx": 2116, "src/components/Map/MapViewGL.tsx": 2116,
"src/components/Planner/DayDetailPanel.test.tsx": 2333, "src/components/Planner/DayDetailPanel.test.tsx": 2332,
"src/components/Planner/DayPlanSidebar.test.tsx": 5349, "src/components/Planner/DayPlanSidebar.test.tsx": 5349,
"src/components/Planner/DayPlanSidebar.tsx": 2910, "src/components/Planner/DayPlanSidebar.tsx": 2908,
"src/components/Planner/PlaceFormModal.test.tsx": 2836, "src/components/Planner/PlaceFormModal.test.tsx": 2836,
"src/components/Planner/PlaceInspector.tsx": 1128, "src/components/Planner/PlaceInspector.tsx": 1128,
"src/components/Studio/TravelElements.tsx": 1559, "src/components/Studio/TravelElements.tsx": 1559,
"src/components/Studio/countryShapes.ts": 2595, "src/components/Studio/countryShapes.ts": 2595,
"src/index.css": 1636, "src/index.css": 1636,
"src/mobile/screens/admin/MAdminPluginsPanel.tsx": 1503, "src/mobile/screens/admin/MAdminPluginsPanel.tsx": 1503,
"src/pages/JourneyDetailPage.test.tsx": 4028, "src/pages/JourneyDetailPage.test.tsx": 3886,
"src/pages/LoginPage.tsx": 1294, "src/pages/LoginPage.tsx": 1294,
"src/pages/TripPlannerPage.tsx": 1128, "src/pages/TripPlannerPage.tsx": 1128,
"src/pages/atlas/useAtlas.ts": 1207, "src/pages/atlas/useAtlas.ts": 1207,
+28 -4
View File
@@ -1,13 +1,14 @@
import React from 'react' import React from 'react'
import { render, screen, waitFor, act } from '@testing-library/react' import { render, screen, waitFor, act } from '@testing-library/react'
import { MemoryRouter, useLocation } from 'react-router' import { MemoryRouter, useLocation } from 'react-router'
import { describe, it, expect, beforeEach, vi } from 'vitest' import { describe, it, expect, beforeEach, onTestFinished, vi } from 'vitest'
import { http, HttpResponse } from 'msw' import { http, HttpResponse } from 'msw'
import { server } from '../tests/helpers/msw/server' import { server } from '../tests/helpers/msw/server'
import { useAuthStore } from './store/authStore' import { useAuthStore } from './store/authStore'
import { useSettingsStore } from './store/settingsStore' import { useSettingsStore } from './store/settingsStore'
import { resetAllStores } from '../tests/helpers/store' import { resetAllStores } from '../tests/helpers/store'
import { buildUser, buildSettings, buildTrip } from '../tests/helpers/factories' import { buildUser, buildSettings, buildTrip } from '../tests/helpers/factories'
import { locationAt } from '../tests/helpers/location'
import { offlineDb } from './db/offlineDb' import { offlineDb } from './db/offlineDb'
import { SETTINGS_WAIT_MS } from './utils/startDestination' import { SETTINGS_WAIT_MS } from './utils/startDestination'
import App from './App' import App from './App'
@@ -185,9 +186,29 @@ describe('RootRedirect — startup destination', () => {
seedAuth({ isAuthenticated: true, user: buildUser() }) seedAuth({ isAuthenticated: true, user: buildUser() })
useSettingsStore.setState({ isLoaded: false }) useSettingsStore.setState({ isLoaded: false })
stubActiveTrip({ id: 42, title: 'Japan' }) stubActiveTrip({ id: 42, title: 'Japan' })
// App asks for the settings on its own as soon as the user is signed in.
// Held until the redirect is decided, or whichever answer lands first wins
// and the test proves nothing about the mirror; released here, so it cannot
// land in the next test either.
let releaseSettings = () => {}
const settingsHeld = new Promise<void>((resolve) => { releaseSettings = resolve })
onTestFinished(() => releaseSettings())
server.use(
http.get('/api/settings', async () => {
await settingsHeld
return HttpResponse.json({
settings: buildSettings({ start_page: 'active_trip', start_trip_tab: 'finanzplan' }),
})
}),
)
renderApp('/') renderApp('/')
await waitFor(() => expect(screen.getByText('TripPlanner')).toBeInTheDocument()) await waitFor(() => expect(screen.getByText('TripPlanner')).toBeInTheDocument())
expect(currentPath()).toBe('/trips/42?tab=finanzplan')
expect(useSettingsStore.getState().isLoaded).toBe(false)
releaseSettings()
await waitFor(() => expect(useSettingsStore.getState().isLoaded).toBe(true))
}) })
}) })
@@ -532,7 +553,7 @@ describe('Version cache-busting', () => {
const reload = vi.fn() const reload = vi.fn()
Object.defineProperty(window, 'location', { Object.defineProperty(window, 'location', {
writable: true, writable: true,
value: { ...window.location, reload }, value: locationAt('/', { reload }),
}) })
server.use( server.use(
@@ -587,7 +608,7 @@ describe('Version cache-busting', () => {
// and try to update. // and try to update.
localStorage.setItem('trek_app_version', '2.9.9') localStorage.setItem('trek_app_version', '2.9.9')
const reload = vi.fn() const reload = vi.fn()
Object.defineProperty(window, 'location', { writable: true, value: { ...window.location, reload } }) Object.defineProperty(window, 'location', { writable: true, value: locationAt('/', { reload }) })
server.use( server.use(
http.get('/api/auth/app-config', () => http.get('/api/auth/app-config', () =>
@@ -609,7 +630,7 @@ describe('Version cache-busting', () => {
// failure neither deletes anything nor reloads into the old worker's shell. // failure neither deletes anything nor reloads into the old worker's shell.
localStorage.setItem('trek_app_version', '2.9.9') localStorage.setItem('trek_app_version', '2.9.9')
const reload = vi.fn() const reload = vi.fn()
Object.defineProperty(window, 'location', { writable: true, value: { ...window.location, reload } }) Object.defineProperty(window, 'location', { writable: true, value: locationAt('/', { reload }) })
const cachesDelete = vi.fn().mockResolvedValue(true) const cachesDelete = vi.fn().mockResolvedValue(true)
const unregister = vi.fn().mockResolvedValue(true) const unregister = vi.fn().mockResolvedValue(true)
vi.stubGlobal('caches', { keys: vi.fn().mockResolvedValue(['workbox-precache-v2', 'map-tiles']), delete: cachesDelete }) vi.stubGlobal('caches', { keys: vi.fn().mockResolvedValue(['workbox-precache-v2', 'map-tiles']), delete: cachesDelete })
@@ -685,6 +706,9 @@ describe('RootRedirect — preference not mirrored on this device', () => {
vi.useFakeTimers({ shouldAdvanceTime: true }) vi.useFakeTimers({ shouldAdvanceTime: true })
seedAuth({ isAuthenticated: true, user: buildUser() }) seedAuth({ isAuthenticated: true, user: buildUser() })
useSettingsStore.setState({ isLoaded: false }) useSettingsStore.setState({ isLoaded: false })
// No backend: the settings never arrive, so only the timeout can decide.
// Answered, they would open the dashboard on their own and hide the wait.
server.use(http.get('/api/settings', () => HttpResponse.error()))
renderApp('/') renderApp('/')
expect(screen.queryByText('Dashboard')).not.toBeInTheDocument() expect(screen.queryByText('Dashboard')).not.toBeInTheDocument()
@@ -1,7 +1,7 @@
// FE-ADMIN-DUS-001 to FE-ADMIN-DUS-031 // FE-ADMIN-DUS-001 to FE-ADMIN-DUS-031
import { render, screen, waitFor, within, fireEvent } from '../../../tests/helpers/render'; import { render, screen, waitFor, within, fireEvent } from '../../../tests/helpers/render';
import userEvent from '@testing-library/user-event'; import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw'; import { delay, http, HttpResponse } from 'msw';
import { server } from '../../../tests/helpers/msw/server'; import { server } from '../../../tests/helpers/msw/server';
import { resetAllStores, seedStore } from '../../../tests/helpers/store'; import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { buildAdmin } from '../../../tests/helpers/factories'; import { buildAdmin } from '../../../tests/helpers/factories';
@@ -341,12 +341,43 @@ describe('DefaultUserSettingsTab', () => {
expect(input).toHaveValue('pk.old'); expect(input).toHaveValue('pk.old');
await user.clear(input); await user.clear(input);
await user.type(input, 'pk.new'); await user.type(input, 'pk.new');
fireEvent.blur(input); // Leave the field for real: fireEvent.blur keeps the focus on it, so the reset click
// would blur it a second time and race that save against the reset request
await user.tab();
expect(input).not.toHaveFocus();
await waitFor(() => expect(puts).toEqual([{ mapbox_access_token: 'pk.new' }])); await waitFor(() => expect(puts).toEqual([{ mapbox_access_token: 'pk.new' }]));
// Clicking the reset link also blurs the field again, so only the last PUT is checked
await user.click(resetLink('Shared Mapbox token')); await user.click(resetLink('Shared Mapbox token'));
await waitFor(() => expect(puts[puts.length - 1]).toEqual({ mapbox_access_token: null })); await waitFor(() => expect(puts).toEqual([{ mapbox_access_token: 'pk.new' }, { mapbox_access_token: null }]));
await waitFor(() => expect(screen.getByPlaceholderText('pk.eyJ…')).toHaveValue(''));
});
it('FE-ADMIN-DUS-032: a reset clicked while the save of the field is still out is the one that stays', async () => {
const user = userEvent.setup();
const { state } = stubDefaults({ map_provider: 'mapbox-gl', mapbox_access_token: 'pk.old' });
// The save is the slower request: sent at once, the reset would overtake it.
const done: string[] = [];
server.use(
http.put('/api/admin/default-user-settings', async ({ request }) => {
const body = await request.json() as Record<string, unknown>;
if (body.mapbox_access_token !== null) await delay(100);
if (body.mapbox_access_token === null) delete state.mapbox_access_token;
else state.mapbox_access_token = body.mapbox_access_token;
done.push(body.mapbox_access_token === null ? 'reset' : 'save');
return HttpResponse.json({ ...state });
}),
);
render(<DefaultUserSettingsTab />);
await screen.findByText('Shared Mapbox token');
const input = screen.getByPlaceholderText('pk.eyJ…');
await user.clear(input);
await user.type(input, 'pk.new');
// The click leaves the field, which saves it, and resets it right after.
await user.click(resetLink('Shared Mapbox token'));
await waitFor(() => expect(done).toEqual(['save', 'reset']));
expect(state.mapbox_access_token).toBeUndefined();
await waitFor(() => expect(screen.getByPlaceholderText('pk.eyJ…')).toHaveValue('')); await waitFor(() => expect(screen.getByPlaceholderText('pk.eyJ…')).toHaveValue(''));
}); });
@@ -449,12 +480,14 @@ describe('DefaultUserSettingsTab', () => {
expect(input).toHaveValue('ck.old'); expect(input).toHaveValue('ck.old');
await user.clear(input); await user.clear(input);
await user.type(input, 'ck.new'); await user.type(input, 'ck.new');
fireEvent.blur(input); // Leave the field for real: fireEvent.blur keeps the focus on it, so the reset click
// would blur it a second time and race that save against the reset request
await user.tab();
expect(input).not.toHaveFocus();
await waitFor(() => expect(puts).toEqual([{ carto_api_key: 'ck.new' }])); await waitFor(() => expect(puts).toEqual([{ carto_api_key: 'ck.new' }]));
// Clicking the reset link also blurs the field again, so only the last PUT is checked
await user.click(resetLink('Shared CARTO key')); await user.click(resetLink('Shared CARTO key'));
await waitFor(() => expect(puts[puts.length - 1]).toEqual({ carto_api_key: null })); await waitFor(() => expect(puts).toEqual([{ carto_api_key: 'ck.new' }, { carto_api_key: null }]));
await waitFor(() => expect(cartoInput()).toHaveValue('')); await waitFor(() => expect(cartoInput()).toHaveValue(''));
}); });
@@ -11,6 +11,39 @@ import DevNotificationsPanel from './DevNotificationsPanel';
const ADMIN_USER = buildUser({ id: 1, username: 'testadmin', role: 'admin' }); const ADMIN_USER = buildUser({ id: 1, username: 'testadmin', role: 'admin' });
/**
* Renders the panel and waits until both lookups (trips and users) have landed, so a test
* acts on the settled panel and no lookup answers after it has ended.
*/
async function renderSettled() {
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Trip-Scoped Events');
await screen.findByText('User-Scoped Events');
}
const LOOKUPS = ['/api/admin/users', '/api/trips'];
/**
* Records the GET requests to `paths` that have been answered, for the tests whose lookups
* come back empty or failed and so change nothing on screen to wait for. Call before render;
* the returned function waits until exactly `paths` (a path once per expected request) ended.
*/
function trackRequests(paths: string[] = LOOKUPS) {
const answered: string[] = [];
const onEnd = ({ request }: { request: Request }) => {
const { pathname } = new URL(request.url);
if (request.method === 'GET' && paths.includes(pathname)) answered.push(pathname);
};
server.events.on('request:end', onEnd);
return async () => {
try {
await waitFor(() => expect([...answered].sort()).toEqual([...paths].sort()));
} finally {
server.events.removeListener('request:end', onEnd);
}
};
}
beforeEach(() => { beforeEach(() => {
resetAllStores(); resetAllStores();
seedStore(useAuthStore, { user: ADMIN_USER, isAuthenticated: true }); seedStore(useAuthStore, { user: ADMIN_USER, isAuthenticated: true });
@@ -21,9 +54,12 @@ afterEach(() => {
}); });
describe('DevNotificationsPanel', () => { describe('DevNotificationsPanel', () => {
it('FE-ADMIN-DEVNOTIF-001: "DEV ONLY" badge is always visible', () => { it('FE-ADMIN-DEVNOTIF-001: "DEV ONLY" badge is always visible', async () => {
render(<><ToastContainer /><DevNotificationsPanel /></>); render(<><ToastContainer /><DevNotificationsPanel /></>);
expect(screen.getByText('DEV ONLY')).toBeInTheDocument(); expect(screen.getByText('DEV ONLY')).toBeInTheDocument();
// Let the lookups the panel started land here, not in the next test
await screen.findByText('Trip-Scoped Events');
await screen.findByText('User-Scoped Events');
}); });
it('FE-ADMIN-DEVNOTIF-002: four section titles render after data loads', async () => { it('FE-ADMIN-DEVNOTIF-002: four section titles render after data loads', async () => {
@@ -36,8 +72,7 @@ describe('DevNotificationsPanel', () => {
}); });
it('FE-ADMIN-DEVNOTIF-003: trip selector populated from API', async () => { it('FE-ADMIN-DEVNOTIF-003: trip selector populated from API', async () => {
render(<><ToastContainer /><DevNotificationsPanel /></>); await renderSettled();
await screen.findByText('Trip-Scoped Events');
const [tripSelect] = screen.getAllByRole('combobox'); const [tripSelect] = screen.getAllByRole('combobox');
const options = Array.from(tripSelect.querySelectorAll('option')); const options = Array.from(tripSelect.querySelectorAll('option'));
const labels = options.map(o => o.textContent); const labels = options.map(o => o.textContent);
@@ -46,8 +81,7 @@ describe('DevNotificationsPanel', () => {
}); });
it('FE-ADMIN-DEVNOTIF-004: user selector populated from API', async () => { it('FE-ADMIN-DEVNOTIF-004: user selector populated from API', async () => {
render(<><ToastContainer /><DevNotificationsPanel /></>); await renderSettled();
await screen.findByText('User-Scoped Events');
const selects = screen.getAllByRole('combobox'); const selects = screen.getAllByRole('combobox');
// Second combobox is the user selector (first is trip selector) // Second combobox is the user selector (first is trip selector)
const userSelect = selects[1]; const userSelect = selects[1];
@@ -66,8 +100,7 @@ describe('DevNotificationsPanel', () => {
}), }),
); );
const user = userEvent.setup(); const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>); await renderSettled();
await screen.findByText('Type Testing');
await user.click(screen.getByText('Simple → Me').closest('button')!); await user.click(screen.getByText('Simple → Me').closest('button')!);
await waitFor(() => expect(capturedBody).toBeDefined()); await waitFor(() => expect(capturedBody).toBeDefined());
expect(capturedBody).toMatchObject({ expect(capturedBody).toMatchObject({
@@ -75,6 +108,8 @@ describe('DevNotificationsPanel', () => {
scope: 'user', scope: 'user',
targetId: ADMIN_USER.id, targetId: ADMIN_USER.id,
}); });
// The send settles inside this test, so its toast cannot land in the next one
await screen.findByText('Sent: simple-me');
}); });
it('FE-ADMIN-DEVNOTIF-006: success toast shown after fire', async () => { it('FE-ADMIN-DEVNOTIF-006: success toast shown after fire', async () => {
@@ -84,30 +119,34 @@ describe('DevNotificationsPanel', () => {
), ),
); );
const user = userEvent.setup(); const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>); await renderSettled();
await screen.findByText('Type Testing');
await user.click(screen.getByText('Simple → Me').closest('button')!); await user.click(screen.getByText('Simple → Me').closest('button')!);
expect(await screen.findByText('Sent: simple-me')).toBeInTheDocument(); expect(await screen.findByText('Sent: simple-me')).toBeInTheDocument();
}); });
it('FE-ADMIN-DEVNOTIF-007: all buttons disabled while a send is in-flight', async () => { it('FE-ADMIN-DEVNOTIF-007: all buttons disabled while a send is in-flight', async () => {
// The send is held open until the assertion ran, then released, so it settles in this test
let release!: () => void;
const gate = new Promise<void>(resolve => { release = resolve; });
server.use( server.use(
http.post('/api/admin/dev/test-notification', async () => { http.post('/api/admin/dev/test-notification', async () => {
await new Promise(() => {}); // never resolves — simulates in-flight await gate;
return HttpResponse.json({ ok: true }); return HttpResponse.json({ ok: true });
}), }),
); );
const user = userEvent.setup(); const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>); await renderSettled();
await screen.findByText('Type Testing');
// The request handler never resolves, so sending stays true after the click settles // The request handler is held, so sending stays true after the click settles
await user.click(screen.getByText('Simple → Me').closest('button')!); await user.click(screen.getByText('Simple → Me').closest('button')!);
await waitFor(() => { await waitFor(() => {
const buttons = screen.getAllByRole('button'); const buttons = screen.getAllByRole('button');
buttons.forEach(btn => expect(btn).toBeDisabled()); buttons.forEach(btn => expect(btn).toBeDisabled());
}); });
release();
await screen.findByText('Sent: simple-me');
}); });
it('FE-ADMIN-DEVNOTIF-008: the server error field is what the toast shows', async () => { it('FE-ADMIN-DEVNOTIF-008: the server error field is what the toast shows', async () => {
@@ -117,8 +156,7 @@ describe('DevNotificationsPanel', () => {
), ),
); );
const user = userEvent.setup(); const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>); await renderSettled();
await screen.findByText('Type Testing');
await user.click(screen.getByText('Simple → Me').closest('button')!); await user.click(screen.getByText('Simple → Me').closest('button')!);
expect(await screen.findByText('No channel configured')).toBeInTheDocument(); expect(await screen.findByText('No channel configured')).toBeInTheDocument();
}); });
@@ -130,8 +168,7 @@ describe('DevNotificationsPanel', () => {
), ),
); );
const user = userEvent.setup(); const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>); await renderSettled();
await screen.findByText('Type Testing');
await user.click(screen.getByText('Simple → Me').closest('button')!); await user.click(screen.getByText('Simple → Me').closest('button')!);
expect(await screen.findByText('Failed')).toBeInTheDocument(); expect(await screen.findByText('Failed')).toBeInTheDocument();
}); });
@@ -145,8 +182,7 @@ describe('DevNotificationsPanel', () => {
}), }),
); );
const user = userEvent.setup(); const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>); await renderSettled();
await screen.findByText('Trip-Scoped Events');
const [tripSelect] = screen.getAllByRole('combobox'); const [tripSelect] = screen.getAllByRole('combobox');
const tokyoOption = Array.from(tripSelect.querySelectorAll('option')).find( const tokyoOption = Array.from(tripSelect.querySelectorAll('option')).find(
@@ -159,15 +195,19 @@ describe('DevNotificationsPanel', () => {
await waitFor(() => expect(capturedBody).toBeDefined()); await waitFor(() => expect(capturedBody).toBeDefined());
expect(capturedBody!.targetId).toBe(tokyoId); expect(capturedBody!.targetId).toBe(tokyoId);
// The send settles inside this test, so its toast cannot land in the next one
await screen.findByText('Sent: booking_change');
}); });
it('FE-ADMIN-DEVNOTIF-010: Trip-Scoped section absent when no trips', async () => { it('FE-ADMIN-DEVNOTIF-010: Trip-Scoped section absent when no trips', async () => {
server.use( server.use(
http.get('/api/trips', () => HttpResponse.json({ trips: [] })), http.get('/api/trips', () => HttpResponse.json({ trips: [] })),
); );
const lookupsAnswered = trackRequests();
render(<><ToastContainer /><DevNotificationsPanel /></>); render(<><ToastContainer /><DevNotificationsPanel /></>);
// Wait for user data to confirm async effects have settled // Wait for user data to confirm async effects have settled
await screen.findByText('User-Scoped Events'); await screen.findByText('User-Scoped Events');
await lookupsAnswered();
expect(screen.queryByText('Trip-Scoped Events')).not.toBeInTheDocument(); expect(screen.queryByText('Trip-Scoped Events')).not.toBeInTheDocument();
}); });
@@ -180,8 +220,7 @@ describe('DevNotificationsPanel', () => {
}), }),
); );
const user = userEvent.setup(); const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>); await renderSettled();
await screen.findByText('Type Testing');
await user.click(screen.getByText('Boolean → Me').closest('button')!); await user.click(screen.getByText('Boolean → Me').closest('button')!);
await screen.findByText('Sent: boolean-me'); await screen.findByText('Sent: boolean-me');
@@ -216,8 +255,7 @@ describe('DevNotificationsPanel', () => {
}), }),
); );
const user = userEvent.setup(); const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>); await renderSettled();
await screen.findByText('Trip-Scoped Events');
const [tripSelect] = screen.getAllByRole('combobox'); const [tripSelect] = screen.getAllByRole('combobox');
const tripId = Number((tripSelect as HTMLSelectElement).value); const tripId = Number((tripSelect as HTMLSelectElement).value);
@@ -247,8 +285,7 @@ describe('DevNotificationsPanel', () => {
}), }),
); );
const user = userEvent.setup(); const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>); await renderSettled();
await screen.findByText('User-Scoped Events');
const userSelect = screen.getAllByRole('combobox')[1] as HTMLSelectElement; const userSelect = screen.getAllByRole('combobox')[1] as HTMLSelectElement;
const aliceOption = Array.from(userSelect.querySelectorAll('option')).find( const aliceOption = Array.from(userSelect.querySelectorAll('option')).find(
@@ -278,9 +315,11 @@ describe('DevNotificationsPanel', () => {
it('FE-ADMIN-DEVNOTIF-014: the User-Scoped section is hidden when no users come back', async () => { it('FE-ADMIN-DEVNOTIF-014: the User-Scoped section is hidden when no users come back', async () => {
server.use(http.get('/api/admin/users', () => HttpResponse.json({ users: [] }))); server.use(http.get('/api/admin/users', () => HttpResponse.json({ users: [] })));
const lookupsAnswered = trackRequests();
render(<><ToastContainer /><DevNotificationsPanel /></>); render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Trip-Scoped Events'); await screen.findByText('Trip-Scoped Events');
await lookupsAnswered();
expect(screen.queryByText('User-Scoped Events')).not.toBeInTheDocument(); expect(screen.queryByText('User-Scoped Events')).not.toBeInTheDocument();
}); });
@@ -288,22 +327,38 @@ describe('DevNotificationsPanel', () => {
server.use( server.use(
http.get('/api/trips', () => HttpResponse.error()), http.get('/api/trips', () => HttpResponse.error()),
http.get('/api/admin/users', () => HttpResponse.error()), http.get('/api/admin/users', () => HttpResponse.error()),
// A network error makes the API client probe /api/health before it rejects; the server
// is down here, so the probe fails too instead of going out to the real network
http.get('/api/health', () => HttpResponse.error()),
); );
const lookupsAnswered = trackRequests([...LOOKUPS, '/api/health', '/api/health']);
render(<><ToastContainer /><DevNotificationsPanel /></>); render(<><ToastContainer /><DevNotificationsPanel /></>);
expect(await screen.findByText('Type Testing')).toBeInTheDocument(); expect(await screen.findByText('Type Testing')).toBeInTheDocument();
await lookupsAnswered();
await waitFor(() => expect(screen.queryByText('Trip-Scoped Events')).not.toBeInTheDocument()); await waitFor(() => expect(screen.queryByText('Trip-Scoped Events')).not.toBeInTheDocument());
expect(screen.queryByText('User-Scoped Events')).not.toBeInTheDocument(); expect(screen.queryByText('User-Scoped Events')).not.toBeInTheDocument();
expect(screen.getByText('Admin-Scoped Events')).toBeInTheDocument(); expect(screen.getByText('Admin-Scoped Events')).toBeInTheDocument();
}); });
it('FE-ADMIN-DEVNOTIF-016: a trigger takes its hover background from CSS, not inline styles', async () => { it('FE-ADMIN-DEVNOTIF-016: a trigger takes its hover background from CSS, not inline styles', async () => {
render(<><ToastContainer /><DevNotificationsPanel /></>); await renderSettled();
await screen.findByText('Type Testing');
const btn = screen.getByText('Simple → Me').closest('button')!; const btn = screen.getByText('Simple → Me').closest('button')!;
fireEvent.mouseEnter(btn); fireEvent.mouseEnter(btn);
expect(btn.style.background).toBe(''); expect(btn.style.background).toBe('');
expect(btn.className).toContain('hover:bg-surface-secondary'); expect(btn.className).toContain('hover:bg-surface-secondary');
}); });
it('FE-ADMIN-DEVNOTIF-017: a send button stays the same element while the panel updates around it', async () => {
render(<><ToastContainer /><DevNotificationsPanel /></>);
const btn = screen.getByRole('button', { name: /Simple → Me/ });
// The lookups answer and re-render the panel.
await screen.findByText('Trip-Scoped Events');
await screen.findByText('User-Scoped Events');
expect(btn.isConnected).toBe(true);
expect(screen.getByRole('button', { name: /Simple → Me/ })).toBe(btn);
});
}); });
@@ -25,20 +25,17 @@ function ButtonGrid({ children }: { children: React.ReactNode }): React.ReactEle
return <div className="grid grid-cols-1 gap-2 sm:grid-cols-2">{children}</div> return <div className="grid grid-cols-1 gap-2 sm:grid-cols-2">{children}</div>
} }
export default function DevNotificationsPanel(): React.ReactElement { /**
const ids = useId() * One send button. Declared here, not inside the panel: a component made during
const { * render is a new type on every render, so React would remount every button on
sending, trips, selectedTripId, setSelectedTripId, users, selectedUserId, setSelectedUserId, * each state change and a click could land on one that is already gone.
tripInviteId, vacayInviteId, send, */
} = useDevNotifications() function Btn({
id, label, sub, icon: Icon, onClick, sending,
// ── Helpers ────────────────────────────────────────────────────────────── }: {
id: string; label: string; sub: string; icon: React.ElementType; onClick: () => void; sending: string | null
const Btn = ({ }): React.ReactElement {
id, label, sub, icon: Icon, onClick, return (
}: {
id: string; label: string; sub: string; icon: React.ElementType; onClick: () => void
}) => (
<button type="button" <button type="button"
onClick={onClick} onClick={onClick}
disabled={sending !== null} disabled={sending !== null}
@@ -54,6 +51,14 @@ export default function DevNotificationsPanel(): React.ReactElement {
{sending === id && <Loader2 size={15} className="flex-none animate-spin text-content-faint" />} {sending === id && <Loader2 size={15} className="flex-none animate-spin text-content-faint" />}
</button> </button>
) )
}
export default function DevNotificationsPanel(): React.ReactElement {
const ids = useId()
const {
sending, trips, selectedTripId, setSelectedTripId, users, selectedUserId, setSelectedUserId,
tripInviteId, vacayInviteId, send,
} = useDevNotifications()
return ( return (
<div> <div>
@@ -66,16 +71,16 @@ export default function DevNotificationsPanel(): React.ReactElement {
badge={<StatusPill tone="warning">DEV ONLY</StatusPill>} badge={<StatusPill tone="warning">DEV ONLY</StatusPill>}
> >
<ButtonGrid> <ButtonGrid>
<Btn id="simple-me" label="Simple → Me" sub="test_simple · user" icon={Bell} <Btn sending={sending} id="simple-me" label="Simple → Me" sub="test_simple · user" icon={Bell}
onClick={send.simpleMe} onClick={send.simpleMe}
/> />
<Btn id="boolean-me" label="Boolean → Me" sub="test_boolean · user" icon={CheckCircle} <Btn sending={sending} id="boolean-me" label="Boolean → Me" sub="test_boolean · user" icon={CheckCircle}
onClick={send.booleanMe} onClick={send.booleanMe}
/> />
<Btn id="navigate-me" label="Navigate → Me" sub="test_navigate · user" icon={Navigation} <Btn sending={sending} id="navigate-me" label="Navigate → Me" sub="test_navigate · user" icon={Navigation}
onClick={send.navigateMe} onClick={send.navigateMe}
/> />
<Btn id="simple-admins" label="Simple → All Admins" sub="test_simple · admin" icon={Zap} <Btn sending={sending} id="simple-admins" label="Simple → All Admins" sub="test_simple · admin" icon={Zap}
onClick={send.simpleAdmins} onClick={send.simpleAdmins}
/> />
</ButtonGrid> </ButtonGrid>
@@ -94,19 +99,19 @@ export default function DevNotificationsPanel(): React.ReactElement {
</SelectBox> </SelectBox>
</EditorField> </EditorField>
<ButtonGrid> <ButtonGrid>
<Btn id="booking_change" label="booking_change" sub="navigate · trip" icon={Calendar} <Btn sending={sending} id="booking_change" label="booking_change" sub="navigate · trip" icon={Calendar}
onClick={send.bookingChange} onClick={send.bookingChange}
/> />
<Btn id="trip_reminder" label="trip_reminder" sub="navigate · trip" icon={Clock} <Btn sending={sending} id="trip_reminder" label="trip_reminder" sub="navigate · trip" icon={Clock}
onClick={send.tripReminder} onClick={send.tripReminder}
/> />
<Btn id="photos_shared" label="photos_shared" sub="navigate · trip" icon={Image} <Btn sending={sending} id="photos_shared" label="photos_shared" sub="navigate · trip" icon={Image}
onClick={send.photosShared} onClick={send.photosShared}
/> />
<Btn id="collab_message" label="collab_message" sub="navigate · trip" icon={MessageSquare} <Btn sending={sending} id="collab_message" label="collab_message" sub="navigate · trip" icon={MessageSquare}
onClick={send.collabMessage} onClick={send.collabMessage}
/> />
<Btn id="packing_tagged" label="packing_tagged" sub="navigate · trip" icon={Tag} <Btn sending={sending} id="packing_tagged" label="packing_tagged" sub="navigate · trip" icon={Tag}
onClick={send.packingTagged} onClick={send.packingTagged}
/> />
</ButtonGrid> </ButtonGrid>
@@ -127,6 +132,7 @@ export default function DevNotificationsPanel(): React.ReactElement {
</EditorField> </EditorField>
<ButtonGrid> <ButtonGrid>
<Btn <Btn
sending={sending}
id={tripInviteId} id={tripInviteId}
label="trip_invite" label="trip_invite"
sub="navigate · user" sub="navigate · user"
@@ -134,6 +140,7 @@ export default function DevNotificationsPanel(): React.ReactElement {
onClick={send.tripInvite} onClick={send.tripInvite}
/> />
<Btn <Btn
sending={sending}
id={vacayInviteId} id={vacayInviteId}
label="vacay_invite" label="vacay_invite"
sub="navigate · user" sub="navigate · user"
@@ -147,7 +154,7 @@ export default function DevNotificationsPanel(): React.ReactElement {
{/* ── Admin-Scoped Events ──────────────────────────────────────────── */} {/* ── Admin-Scoped Events ──────────────────────────────────────────── */}
<SettingsCard icon={ShieldCheck} title="Admin-Scoped Events" hint="Fires to all admin users."> <SettingsCard icon={ShieldCheck} title="Admin-Scoped Events" hint="Fires to all admin users.">
<ButtonGrid> <ButtonGrid>
<Btn id="version_available" label="version_available" sub="navigate · admin" icon={Download} <Btn sending={sending} id="version_available" label="version_available" sub="navigate · admin" icon={Download}
onClick={send.versionAvailable} onClick={send.versionAvailable}
/> />
</ButtonGrid> </ButtonGrid>
@@ -137,19 +137,25 @@ describe('useDefaultUserSettings', () => {
act(() => result.current.pickTilePreset('')); act(() => result.current.pickTilePreset(''));
act(() => result.current.pickStylePreset('')); act(() => result.current.pickStylePreset(''));
// Writes go out in order, a microtask later: let any that was queued start first.
await act(async () => {});
expect(update).not.toHaveBeenCalled(); expect(update).not.toHaveBeenCalled();
act(() => result.current.pickTilePreset('https://tile.openstreetmap.de/{z}/{x}/{y}.png')); act(() => result.current.pickTilePreset('https://tile.openstreetmap.de/{z}/{x}/{y}.png'));
expect(result.current.mapTileUrl).toBe('https://tile.openstreetmap.de/{z}/{x}/{y}.png'); expect(result.current.mapTileUrl).toBe('https://tile.openstreetmap.de/{z}/{x}/{y}.png');
expect(update).toHaveBeenLastCalledWith({ map_tile_url: 'https://tile.openstreetmap.de/{z}/{x}/{y}.png' }); await waitFor(() =>
expect(update).toHaveBeenLastCalledWith({ map_tile_url: 'https://tile.openstreetmap.de/{z}/{x}/{y}.png' })
);
act(() => result.current.pickStylePreset('https://tiles.openfreemap.org/styles/positron')); act(() => result.current.pickStylePreset('https://tiles.openfreemap.org/styles/positron'));
expect(update).toHaveBeenLastCalledWith({ maplibre_style: 'https://tiles.openfreemap.org/styles/positron' }); await waitFor(() =>
expect(update).toHaveBeenLastCalledWith({ maplibre_style: 'https://tiles.openfreemap.org/styles/positron' })
);
act(() => result.current.setMapboxStyle('mapbox://styles/not-for-maplibre')); act(() => result.current.setMapboxStyle('mapbox://styles/not-for-maplibre'));
act(() => result.current.commitStyle()); act(() => result.current.commitStyle());
expect(result.current.mapboxStyle).toBe(OPENFREEMAP_DEFAULT_STYLE); expect(result.current.mapboxStyle).toBe(OPENFREEMAP_DEFAULT_STYLE);
expect(update).toHaveBeenLastCalledWith({ maplibre_style: OPENFREEMAP_DEFAULT_STYLE }); await waitFor(() => expect(update).toHaveBeenLastCalledWith({ maplibre_style: OPENFREEMAP_DEFAULT_STYLE }));
await waitFor(() => expect(toast.success).toHaveBeenCalledTimes(3)); await waitFor(() => expect(toast.success).toHaveBeenCalledTimes(3));
}); });
}); });
@@ -1,6 +1,7 @@
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { adminApi } from '../../api/client'; import { adminApi } from '../../api/client';
import { useWritesInOrder } from '../../hooks/useWritesInOrder';
import { useTranslation } from '../../i18n'; import { useTranslation } from '../../i18n';
import { useAuthStore } from '../../store/authStore'; import { useAuthStore } from '../../store/authStore';
import { useSettingsStore } from '../../store/settingsStore'; import { useSettingsStore } from '../../store/settingsStore';
@@ -87,32 +88,38 @@ export function useDefaultUserSettings({ errorMessage, previewCreatedAt }: Defau
.catch(() => setLoaded(true)); .catch(() => setLoaded(true));
}, []); }, []);
const save = async (patch: Partial<Defaults>) => { // A field's save on blur and the reset clicked right after it reach the server in
try { // that order, or the save landing last would store the old value again.
const updated = await adminApi.updateDefaultUserSettings(patch as Record<string, unknown>); const inOrder = useWritesInOrder();
setDefaults(updated);
toast.success(t('admin.defaultSettings.saved'));
} catch (err: unknown) {
toast.error(errorMessage(err, t('common.error')));
}
};
const reset = async (key: keyof Defaults) => { const save = (patch: Partial<Defaults>) =>
try { inOrder(async () => {
const updated = await adminApi.updateDefaultUserSettings({ [key]: null }); try {
setDefaults(updated); const updated = await adminApi.updateDefaultUserSettings(patch as Record<string, unknown>);
if (key === 'map_tile_url') setMapTileUrl(''); setDefaults(updated);
if (key === 'mapbox_access_token') setMapboxToken(''); toast.success(t('admin.defaultSettings.saved'));
if (key === 'carto_api_key') setCartoKey(''); } catch (err: unknown) {
if (key === 'mapbox_style' || key === 'maplibre_style') { toast.error(errorMessage(err, t('common.error')));
const provider = normalizeProvider(defaults.map_provider);
setMapboxStyle(provider === 'leaflet' ? '' : defaultStyleForProvider(provider));
} }
toast.success(t('admin.defaultSettings.reset')); });
} catch (err: unknown) {
toast.error(errorMessage(err, t('common.error'))); const reset = (key: keyof Defaults) =>
} inOrder(async () => {
}; try {
const updated = await adminApi.updateDefaultUserSettings({ [key]: null });
setDefaults(updated);
if (key === 'map_tile_url') setMapTileUrl('');
if (key === 'mapbox_access_token') setMapboxToken('');
if (key === 'carto_api_key') setCartoKey('');
if (key === 'mapbox_style' || key === 'maplibre_style') {
const provider = normalizeProvider(defaults.map_provider);
setMapboxStyle(provider === 'leaflet' ? '' : defaultStyleForProvider(provider));
}
toast.success(t('admin.defaultSettings.reset'));
} catch (err: unknown) {
toast.error(errorMessage(err, t('common.error')));
}
});
const isSet = (key: keyof Defaults) => defaults[key] !== undefined; const isSet = (key: keyof Defaults) => defaults[key] !== undefined;
@@ -111,11 +111,23 @@ export const CHATGPT_USAGE_URL = 'https://chatgpt.com/settings/usage';
* error page and the user pastes its address back; only the port may differ. * error page and the user pastes its address back; only the port may differ.
*/ */
export function isChatgptCallback(text: string): boolean { export function isChatgptCallback(text: string): boolean {
return chatgptCallbackUrl(text) !== null;
}
/**
* The pasted callback as the server reads it, or null when it is something
* else. The address bar and the hint under the field show it without `http://`,
* so an address pasted that way gets the scheme put back.
*/
export function chatgptCallbackUrl(text: string): string | null {
const trimmed = text.trim();
const address = /^[a-z][a-z\d+.-]*:\/\//i.test(trimmed) ? trimmed : `http://${trimmed}`;
let url: URL; let url: URL;
try { try {
url = new URL(text.trim()); url = new URL(address);
} catch { } catch {
return false; return null;
} }
return url.protocol === 'http:' && url.hostname === '127.0.0.1' && url.pathname === '/auth/callback'; const ok = url.protocol === 'http:' && url.hostname === '127.0.0.1' && url.pathname === '/auth/callback';
return ok ? address : null;
} }
@@ -40,7 +40,7 @@ beforeEach(() => {
describe('BackgroundTasksWidget', () => { describe('BackgroundTasksWidget', () => {
it('shows the warnings when a finished job produced no items', () => { it('shows the warnings when a finished job produced no items', () => {
const warning = 'voucher.pdf: AI parsing failed — LLM request failed (400): response_format unsupported' const warning = 'voucher.pdf: AI parsing failed: LLM request failed (400): response_format unsupported'
useBackgroundTasksStore.setState({ tasks: [task({ warnings: [warning] })] }) useBackgroundTasksStore.setState({ tasks: [task({ warnings: [warning] })] })
render(<BackgroundTasksWidget />) render(<BackgroundTasksWidget />)
expect(screen.getByText('No reservations could be extracted from the uploaded files.')).toBeInTheDocument() expect(screen.getByText('No reservations could be extracted from the uploaded files.')).toBeInTheDocument()
@@ -141,7 +141,7 @@ describe('BackgroundTasksWidget', () => {
* disappeared on save. * disappeared on save.
*/ */
it('shows the warnings on a job that did produce items', () => { it('shows the warnings on a job that did produce items', () => {
const warning = 'voucher.pdf: could not locate "Curbside Pickup Counter 7" — set it manually before saving' const warning = 'voucher.pdf: could not locate "Curbside Pickup Counter 7", set it manually before saving'
useBackgroundTasksStore.setState({ useBackgroundTasksStore.setState({
tasks: [task({ items: [{ id: 1 } as never], warnings: [warning] })], tasks: [task({ items: [{ id: 1 } as never], warnings: [warning] })],
}) })
@@ -526,6 +526,24 @@ describe('FileManager', () => {
}); });
}); });
it('FE-COMP-FILEMANAGER-039: a file pasted while the drop zone has focus is uploaded once', async () => {
const onUpload = vi.fn().mockResolvedValue({ file: { id: 56 } });
render(<FileManager {...defaultProps} onUpload={onUpload} />);
const zone = document.querySelector('[role="presentation"]') as HTMLElement;
const file = new File(['data'], 'pasted.png', { type: 'image/png' });
const pasteEvent = new Event('paste', { bubbles: true, cancelable: true });
Object.defineProperty(pasteEvent, 'clipboardData', {
value: { types: ['Files'], files: [file], items: [{ kind: 'file', type: 'image/png', getAsFile: () => file }] },
});
await fireEvent(zone, pasteEvent);
await waitFor(() => expect(onUpload).toHaveBeenCalled());
await new Promise((resolve) => setTimeout(resolve, 50));
expect(onUpload).toHaveBeenCalledTimes(1);
});
it('FE-COMP-FILEMANAGER-028: upload with places open assign modal after upload', async () => { it('FE-COMP-FILEMANAGER-028: upload with places open assign modal after upload', async () => {
const { buildPlace } = await import('../../../tests/helpers/factories'); const { buildPlace } = await import('../../../tests/helpers/factories');
const place = buildPlace({ id: 10, name: 'Sagrada Familia' }); const place = buildPlace({ id: 10, name: 'Sagrada Familia' });
@@ -124,7 +124,9 @@ export function useFileManager({ files = [], onUpload, onDelete, onUpdate, place
toast.error(t('files.uploadErrorSize', { max: maxUploadMb })) toast.error(t('files.uploadErrorSize', { max: maxUploadMb }))
} }
}, },
noClick: false, // Pasting is handled once for the whole panel (handlePaste), with the upload
// permission check; the zone's own paste upload would send each file twice.
noPaste: true,
}) })
const handlePaste = useCallback((e: React.ClipboardEvent) => { const handlePaste = useCallback((e: React.ClipboardEvent) => {
+2 -2
View File
@@ -544,9 +544,9 @@ describe('Navbar styling and menu details', () => {
const discord = screen.getByTitle('Discord'); const discord = screen.getByTitle('Discord');
fireEvent.mouseEnter(discord); fireEvent.mouseEnter(discord);
expect(discord.style.background).toBe('rgba(88, 101, 242, 0.125)'); expect(discord.style.background).toBe('rgba(88, 101, 242, 0.15)');
fireEvent.mouseLeave(discord); fireEvent.mouseLeave(discord);
expect(discord.style.background).toBe('var(--bg-tertiary)'); expect(discord.style.background).toBe('');
expect(document.querySelector('img[src="/text-light.svg"]')).not.toBeNull(); expect(document.querySelector('img[src="/text-light.svg"]')).not.toBeNull();
}); });
+3 -18
View File
@@ -17,6 +17,7 @@ import { useCollapseOnOverflow } from '../../hooks/useCollapseOnOverflow'
import { openMailInbox } from '../MailIngest/mailInboxOpener' import { openMailInbox } from '../MailIngest/mailInboxOpener'
import { useMailInboxShell } from '../MailIngest/useMailInboxShell' import { useMailInboxShell } from '../MailIngest/useMailInboxShell'
import MailInboxDialog from '../MailIngest/MailInboxDialog' import MailInboxDialog from '../MailIngest/MailInboxDialog'
import UserMenuFooter from './UserMenuFooter'
const ADDON_ICONS: Record<string, LucideIcon> = { CalendarDays, Briefcase, Globe, Compass, Bookmark } const ADDON_ICONS: Record<string, LucideIcon> = { CalendarDays, Briefcase, Globe, Compass, Bookmark }
@@ -311,7 +312,7 @@ export default function Navbar({ tripTitle, tripId, onBack, showBack, onSettings
{userMenuOpen && createPortal( {userMenuOpen && createPortal(
<> <>
<div style={{ position: 'fixed', inset: 0, zIndex: 9998 }} role="presentation" onClick={() => setUserMenuOpen(false)} /> <div style={{ position: 'fixed', inset: 0, zIndex: 9998 }} role="presentation" onClick={() => setUserMenuOpen(false)} />
<div className="trek-menu-enter w-52 rounded-xl shadow-xl border overflow-hidden bg-surface-card border-edge" style={{ position: 'fixed', top: 'var(--nav-h)', insetInlineEnd: 8, zIndex: 9999 }}> <div className="trek-menu-enter w-60 rounded-xl shadow-xl border overflow-hidden bg-surface-card border-edge" style={{ position: 'fixed', top: 'var(--nav-h)', insetInlineEnd: 8, zIndex: 9999 }}>
<div className="px-4 py-3 border-b border-edge-secondary"> <div className="px-4 py-3 border-b border-edge-secondary">
<p className="text-sm font-medium text-content">{user.username}</p> <p className="text-sm font-medium text-content">{user.username}</p>
<p className="text-xs truncate text-content-muted">{user.email}</p> <p className="text-xs truncate text-content-muted">{user.email}</p>
@@ -368,23 +369,7 @@ export default function Navbar({ tripTitle, tripId, onBack, showBack, onSettings
<LogOut className="w-4 h-4" /> <LogOut className="w-4 h-4" />
{t('nav.logout')} {t('nav.logout')}
</button> </button>
{appVersion && ( {appVersion && <UserMenuFooter appVersion={appVersion} dark={dark} managed={!!managed} />}
<div className="px-4 pt-2 pb-2.5 text-center border-t border-edge-secondary" style={{ marginTop: 4 }}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}>
<div style={{ display: 'inline-flex', alignItems: 'center', gap: 5, background: 'var(--bg-tertiary)', borderRadius: 99, padding: '4px 12px' }}>
<img src={dark ? '/text-light.svg' : '/text-dark.svg'} alt="TREK" style={{ height: 10, opacity: 0.5 }} />
<span style={{ fontSize: 'calc(10px * var(--fs-scale-caption, 1))', fontWeight: 600, color: 'var(--text-faint)' }}>v{appVersion}</span>
</div>
<a href="https://discord.gg/NhZBDSd4qW" target="_blank" rel="noopener noreferrer"
style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 24, height: 24, borderRadius: 99, background: 'var(--bg-tertiary)', transition: 'background 0.15s' }}
onMouseEnter={e => e.currentTarget.style.background = '#5865F220'}
onMouseLeave={e => e.currentTarget.style.background = 'var(--bg-tertiary)'}
title="Discord">
<svg width="12" height="12" viewBox="0 0 24 24" fill="var(--text-faint)"><path d="M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0 12.64 12.64 0 0 0-.617-1.25.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057 19.9 19.9 0 0 0 5.993 3.03.078.078 0 0 0 .084-.028c.462-.63.874-1.295 1.226-1.994a.076.076 0 0 0-.041-.106 13.107 13.107 0 0 1-1.872-.892.077.077 0 0 1-.008-.128 10.2 10.2 0 0 0 .372-.292.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127 12.299 12.299 0 0 1-1.873.892.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028 19.839 19.839 0 0 0 6.002-3.03.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.095 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.955-2.419 2.157-2.419 1.21 0 2.176 1.095 2.157 2.42 0 1.333-.946 2.418-2.157 2.418z"/></svg>
</a>
</div>
</div>
)}
</div> </div>
</div> </div>
</>, </>,
@@ -0,0 +1,44 @@
// FE-MENUFOOT-001 to FE-MENUFOOT-004
import { describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen } from '../../../tests/helpers/render';
import { isNativeApp } from '../../native/platform';
import UserMenuFooter from './UserMenuFooter';
vi.mock('../../native/platform', () => ({ isNativeApp: vi.fn(() => false) }));
function titles(): string[] {
return [...document.querySelectorAll('a[title]')].map((a) => a.getAttribute('title') ?? '');
}
describe('UserMenuFooter', () => {
it('FE-MENUFOOT-001: shows the version and the three support links beside Discord', () => {
render(<UserMenuFooter appVersion="5.2.1" dark={false} managed={false} />);
expect(screen.getByText('v5.2.1')).toBeInTheDocument();
expect(document.querySelector('img[src="/text-dark.svg"]')).not.toBeNull();
expect(titles()).toEqual(['Patreon', 'Ko-fi', 'Buy Me a Coffee', 'Discord']);
expect(screen.getByTitle('Ko-fi')).toHaveAttribute('href', 'https://ko-fi.com/mauriceboe');
expect(screen.getByTitle('Buy Me a Coffee')).toHaveAttribute('href', 'https://buymeacoffee.com/mauriceboe');
expect(screen.getByTitle('Patreon')).toHaveAttribute('href', 'https://www.patreon.com/cw/mauriceboe');
});
it('FE-MENUFOOT-002: a managed install keeps only Discord', () => {
render(<UserMenuFooter appVersion="5.2.1" dark managed />);
expect(titles()).toEqual(['Discord']);
expect(document.querySelector('img[src="/text-light.svg"]')).not.toBeNull();
});
it('FE-MENUFOOT-003: the native app shows no donation link', () => {
vi.mocked(isNativeApp).mockReturnValueOnce(true);
render(<UserMenuFooter appVersion="5.2.1" dark={false} managed={false} />);
expect(titles()).toEqual(['Discord']);
});
it('FE-MENUFOOT-004: hovering a link washes it in its brand colour and leaving clears it', () => {
render(<UserMenuFooter appVersion="5.2.1" dark={false} managed={false} />);
const kofi = screen.getByTitle('Ko-fi');
fireEvent.mouseEnter(kofi);
expect(kofi.style.background).toBe('rgba(255, 94, 91, 0.15)');
fireEvent.mouseLeave(kofi);
expect(kofi.style.background).toBe('');
});
});
@@ -0,0 +1,100 @@
import { Coffee, Heart } from 'lucide-react';
import React from 'react';
import { donationsShown } from '../../utils/donations';
import { PATREON_PATH, PATREON_URL } from '../shared/PatreonIcon';
const DISCORD_PATH =
'M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0 12.64 12.64 0 0 0-.617-1.25.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057 19.9 19.9 0 0 0 5.993 3.03.078.078 0 0 0 .084-.028c.462-.63.874-1.295 1.226-1.994a.076.076 0 0 0-.041-.106 13.107 13.107 0 0 1-1.872-.892.077.077 0 0 1-.008-.128 10.2 10.2 0 0 0 .372-.292.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127 12.299 12.299 0 0 1-1.873.892.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028 19.839 19.839 0 0 0 6.002-3.03.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.095 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.955-2.419 2.157-2.419 1.21 0 2.176 1.095 2.157 2.42 0 1.333-.946 2.418-2.157 2.418z';
interface FooterLink {
title: string;
href: string;
/** The brand's colour, as a faint wash behind the icon on hover. */
tint: string;
icon: React.ReactNode;
}
function brandSvg(path: string): React.ReactNode {
return (
<svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
<path d={path} />
</svg>
);
}
const DISCORD: FooterLink = {
title: 'Discord',
href: 'https://discord.gg/NhZBDSd4qW',
tint: '#5865F2', // Discord's brand colour
icon: brandSvg(DISCORD_PATH),
};
const SUPPORT: FooterLink[] = [
{
title: 'Patreon',
href: PATREON_URL,
tint: '#ff424d', // Patreon's brand colour
icon: brandSvg(PATREON_PATH),
},
{
title: 'Ko-fi',
href: 'https://ko-fi.com/mauriceboe',
tint: '#ff5e5b', // Ko-fi's brand colour
icon: <Heart size={12} strokeWidth={2.4} aria-hidden="true" />,
},
{
title: 'Buy Me a Coffee',
href: 'https://buymeacoffee.com/mauriceboe',
tint: '#ffdd00', // Buy Me a Coffee's brand colour
icon: <Coffee size={12} strokeWidth={2.4} aria-hidden="true" />,
},
];
interface Props {
appVersion: string;
dark: boolean;
/** A centrally administered install: its users are not the ones to ask for support. */
managed: boolean;
}
/**
* The foot of the user menu: the running version, then the round links to the
* community and, where donations may be shown, the three ways to support TREK.
*/
export default function UserMenuFooter({ appVersion, dark, managed }: Props): React.ReactElement {
const links = !managed && donationsShown() ? [...SUPPORT, DISCORD] : [DISCORD];
return (
<div className="mt-1 flex items-center justify-center gap-1.5 border-t border-edge-secondary px-3 pb-2.5 pt-2">
<div className="inline-flex items-center gap-[5px] rounded-full bg-surface-tertiary px-2.5 py-1">
<img src={dark ? '/text-light.svg' : '/text-dark.svg'} alt="TREK" className="h-2.5 opacity-50" />
<span
className="font-semibold text-content-faint"
style={{ fontSize: 'calc(10px * var(--fs-scale-caption, 1))' }}
>
v{appVersion}
</span>
</div>
{links.map((link) => (
<a
key={link.title}
href={link.href}
target="_blank"
rel="noopener noreferrer"
title={link.title}
aria-label={link.title}
className="grid h-6 w-6 flex-none place-items-center rounded-full bg-surface-tertiary text-content-faint transition-colors"
onMouseEnter={(e) => {
e.currentTarget.style.background = `${link.tint}26`;
e.currentTarget.style.color = 'var(--text-primary)';
}}
onMouseLeave={(e) => {
e.currentTarget.style.background = '';
e.currentTarget.style.color = '';
}}
>
{link.icon}
</a>
))}
</div>
);
}
@@ -14,8 +14,9 @@ export type InboxAction = 'add' | 'choose' | 'file' | 'manual' | 'discard';
const INFO_ONLY: ReadonlySet<MailIngestReason> = new Set(['forwarding_confirmation', 'newsletter', 'auto_reply']); const INFO_ONLY: ReadonlySet<MailIngestReason> = new Set(['forwarding_confirmation', 'newsletter', 'auto_reply']);
/** /**
* A passing AI failure is read again by the server on its own; an allowance * The server reads a mail again after a passing AI failure and keeps it here
* used up leaves the form and the document, so there is no "read again" here. * only once its last try failed too; an allowance used up leaves the form and
* the document, so there is no "read again" here.
*/ */
export function actionsOf(entry: MailIngestInboxEntry): InboxAction[] { export function actionsOf(entry: MailIngestInboxEntry): InboxAction[] {
const reason = entry.reason ?? entry.message.reason; const reason = entry.reason ?? entry.message.reason;
+14 -2
View File
@@ -3,7 +3,7 @@ import { pluginsApi } from '../../api/client'
import type { RouteEngine, RouteResult, RouteSegment, RouteWithLegs, SnappedWaypoint, Waypoint, RouteAnchors } from '../../types' import type { RouteEngine, RouteResult, RouteSegment, RouteWithLegs, SnappedWaypoint, Waypoint, RouteAnchors } from '../../types'
import { haversineKm } from '../../utils/geo' import { haversineKm } from '../../utils/geo'
import { countRoute } from './routeUsageCounter' import { countRoute } from './routeUsageCounter'
import { cacheRoute, rememberRoute, routeInMemory, storedRoute } from './routeStore' import { cacheRoute, keepStandIn, rememberRoute, routeInMemory, standIn, storedRoute } from './routeStore'
import { formatDuration, formatRouteDistance, getDistanceUnit, legSegment } from './routeText' import { formatDuration, formatRouteDistance, getDistanceUnit, legSegment } from './routeText'
import type { RouteAlternative } from './routeTypes' import type { RouteAlternative } from './routeTypes'
import { valhallaAvailable, valhallaPlansDays, valhallaRoutesDays, type AvoidClass } from './valhallaRoute' import { valhallaAvailable, valhallaPlansDays, valhallaRoutesDays, type AvoidClass } from './valhallaRoute'
@@ -289,6 +289,12 @@ function withEngine(route: RouteWithLegs, engine: RouteEngine): RouteWithLegs {
* A day planned with Valhalla: its answer, kept under the Valhalla key, or where it gives * A day planned with Valhalla: its answer, kept under the Valhalla key, or where it gives
* none OSRM's for the whole day, kept under the plain key. One engine per day, never one * none OSRM's for the whole day, kept under the plain key. One engine per day, never one
* leg from each. While the relay rests, a day that avoids nothing is not put to it at all. * leg from each. While the relay rests, a day that avoids nothing is not put to it at all.
*
* A day that avoids nothing and that Valhalla could not route is not put to it again for a
* while: OSRM's answer, the same road an OSRM instance draws, stands in for it under a key
* of its own, so every visit does not wait out the relay first (#3228). Never under the
* Valhalla key, which holds only what Valhalla answered. A day that avoids something is
* asked again, since the stand-in drives the very road it means to leave out.
*/ */
async function valhallaOrOsrmDay( async function valhallaOrOsrmDay(
waypoints: Waypoint[], waypoints: Waypoint[],
@@ -299,6 +305,9 @@ async function valhallaOrOsrmDay(
signal?: AbortSignal signal?: AbortSignal
}, },
): Promise<RouteWithLegs> { ): Promise<RouteWithLegs> {
const standInKey = avoiding.length ? null : `${keys.valhalla}:standin`
const stoodIn = standInKey ? await standIn(standInKey) : null
if (stoodIn) return stoodIn
const asking = avoiding.length > 0 || valhallaRoutesDays() const asking = avoiding.length > 0 || valhallaRoutesDays()
const routed = asking ? await valhallaDayRoute(waypoints, profile, avoiding, signal) : null const routed = asking ? await valhallaDayRoute(waypoints, profile, avoiding, signal) : null
if (routed) { if (routed) {
@@ -307,7 +316,10 @@ async function valhallaOrOsrmDay(
} }
const plain = (await storedRoute(keys.plain)) ?? await osrmWithLegs(waypoints, keys.coords, profile, signal) const plain = (await storedRoute(keys.plain)) ?? await osrmWithLegs(waypoints, keys.coords, profile, signal)
cacheRoute(keys.plain, plain) cacheRoute(keys.plain, plain)
return withFallbackNoted(plain, avoiding) const drawn = withFallbackNoted(plain, avoiding)
// A day left before Valhalla answered was never refused by it.
if (standInKey && !signal?.aborted) keepStandIn(standInKey, drawn)
return drawn
} }
/** Fetches a full route via OSRM and returns coordinates, distance, and duration estimates for driving/walking. */ /** Fetches a full route via OSRM and returns coordinates, distance, and duration estimates for driving/walking. */
@@ -0,0 +1,45 @@
import { readFileSync } from 'node:fs';
import { createRequire } from 'node:module';
import { dirname, join } from 'node:path';
import { describe, expect, it } from 'vitest';
// mapbox-gl and maplibre-gl ship in the same bundle, and both pass messages to
// their workers through a class registry that stamps `_classRegistryKey` on
// constructors. maplibre stamps the built-ins Set and Error globally. mapbox-gl
// 3.33 and later read that key before their own Set and Error handling, find no
// entry for "Set" in their registry and throw "Cannot read properties of
// undefined (reading 'omit')" for every vector tile, so the Mapbox basemap stays
// blank while raster layers still load. These read the shipped files because the
// clash only exists between the two real libraries.
const requireFromClient = createRequire(import.meta.url);
function distFile(pkg: string, file: string): string {
const root = dirname(requireFromClient.resolve(`${pkg}/package.json`));
return readFileSync(join(root, 'dist', file), 'utf8');
}
function functionBody(source: string, signature: string): string {
const start = source.indexOf(signature);
expect(start, `${signature} not found`).toBeGreaterThan(-1);
return source.slice(start, source.indexOf('\n}\n', start));
}
describe('GL worker class registry', () => {
it('FE-COMP-GLWORKERREGISTRY-001: maplibre-gl stamps the global Set and Error', () => {
const maplibre = distFile('maplibre-gl', 'maplibre-gl-dev.mjs');
expect(maplibre).toMatch(/register\("Set", Set\)/);
expect(maplibre).toMatch(/register\("Error", Error\)/);
});
it('FE-COMP-GLWORKERREGISTRY-002: mapbox-gl handles Set and Error before it reads the registry key', () => {
const serialize = functionBody(
distFile('mapbox-gl', 'mapbox-gl-dev.js'),
'function serialize(input, transferables)'
);
const registryRead = serialize.indexOf('._classRegistryKey');
expect(registryRead).toBeGreaterThan(-1);
expect(serialize.indexOf('instanceof Set')).toBeGreaterThan(-1);
expect(serialize.indexOf('instanceof Set')).toBeLessThan(registryRead);
expect(serialize.indexOf('instanceof Error')).toBeLessThan(registryRead);
});
});
+18
View File
@@ -39,3 +39,21 @@ export async function storedRoute(key: string): Promise<RouteWithLegs | null> {
if (kept) rememberRoute(key, kept); if (kept) rememberRoute(key, kept);
return kept; return kept;
} }
/**
* How long OSRM's answer stands in for a day Valhalla could not route. Long enough that
* reopening the trip draws that day at once instead of waiting out the relay again on
* every visit (#3228), short enough that a Valhalla back from an outage gets the day again
* the same day.
*/
const STAND_IN_MS = 60 * 60 * 1000;
/** Keeps OSRM's answer for a day Valhalla could not route, on the device only, for `STAND_IN_MS`. */
export function keepStandIn(key: string, route: RouteWithLegs): void {
void routeCacheRepo.put(key, route);
}
/** The answer that stood in for a day Valhalla could not route, while it is recent enough. */
export function standIn(key: string): Promise<RouteWithLegs | null> {
return routeCacheRepo.get<RouteWithLegs>(key, STAND_IN_MS);
}
@@ -59,6 +59,8 @@ interface Traffic {
osrm: string[]; osrm: string[];
} }
const HOUR = 60 * 60 * 1000;
const answered = (body: RouteBody) => HttpResponse.json({ trip: valhallaTrip(body.locations) }); const answered = (body: RouteBody) => HttpResponse.json({ trip: valhallaTrip(body.locations) });
/** Every routing host answering, the relay as `relay` says; what each was asked is recorded. */ /** Every routing host answering, the relay as `relay` says; what each was asked is recorded. */
@@ -274,9 +276,41 @@ describe('the route cache keeps the engine apart', () => {
up = true; up = true;
resetValhallaTurns(); resetValhallaTurns();
expect((await calculateRouteWithLegs(points, { profile: 'driving' })).distance).toBe(2000);
expect(traffic.relay).toHaveLength(1);
const now = Date.now();
vi.spyOn(Date, 'now').mockReturnValue(now + HOUR + 1);
expect((await calculateRouteWithLegs(points, { profile: 'driving' })).distance).toBe(4000); expect((await calculateRouteWithLegs(points, { profile: 'driving' })).distance).toBe(4000);
expect([traffic.relay.length, traffic.osrm.length]).toEqual([2, 1]); expect([traffic.relay.length, traffic.osrm.length]).toEqual([2, 1]);
}); });
it('VDAY-CACHE-005: a day the relay could not route opens drawn after a reload, without waiting for the relay again (#3228)', async () => {
const points = freshDay(3);
let slow = true;
const traffic = listen((body) =>
slow ? HttpResponse.json({ error: 'The TREK routing service took too long' }, { status: 504 }) : answered(body)
);
expect((await calculateRouteWithLegs(points, { profile: 'driving' })).engine).toBe('osrm');
const { offlineDb } = await import('../../db/offlineDb');
const stoodIn = (key: string) => key.includes(`${points[0].lng},${points[0].lat}`) && key.endsWith(':standin');
await vi.waitFor(async () => expect(await offlineDb.routeCache.filter((row) => stoodIn(row.key)).count()).toBe(1));
// A reload: the modules, and with them the routes in memory and the relay's rest, start over.
vi.resetModules();
const reloaded = await import('./RouteCalculator');
const again = await reloaded.calculateRouteWithLegs(points, { profile: 'driving' });
expect([again.distance, again.engine]).toEqual([2000, 'osrm']);
expect([traffic.relay.length, traffic.osrm.length]).toEqual([1, 1]);
// An hour on, the relay gets the day again and its answer is kept as the day's.
slow = false;
const now = Date.now();
vi.spyOn(Date, 'now').mockReturnValue(now + HOUR + 1);
const routed = await reloaded.calculateRouteWithLegs(points, { profile: 'driving' });
expect([routed.distance, routed.engine]).toEqual([4000, 'valhalla']);
expect([traffic.relay.length, traffic.osrm.length]).toEqual([2, 1]);
});
}); });
describe('the route cache while the relay rests', () => { describe('the route cache while the relay rests', () => {
@@ -1,32 +1,12 @@
// FE-PLANNER-DAYDETAIL-DF-001 to FE-PLANNER-DAYDETAIL-DF-002 // FE-PLANNER-DAYDETAIL-DF-001 to FE-PLANNER-DAYDETAIL-DF-002
// The day panel's heading with "date first in day headings" on (#2921). // The day panel's heading with "date first in day headings" on (#2921).
import userEvent from '@testing-library/user-event'; import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw'; import { dayDetailProps as props, resetDayDetailPanel } from '../../../tests/helpers/dayDetailPanel';
import { buildAdmin, buildDay, buildTrip } from '../../../tests/helpers/factories';
import { server } from '../../../tests/helpers/msw/server';
import { render, screen } from '../../../tests/helpers/render'; import { render, screen } from '../../../tests/helpers/render';
import { resetAllStores, seedStore } from '../../../tests/helpers/store'; import { seedStore } from '../../../tests/helpers/store';
import { useAuthStore } from '../../store/authStore';
import { useSettingsStore } from '../../store/settingsStore'; import { useSettingsStore } from '../../store/settingsStore';
import { useTripStore } from '../../store/tripStore';
import DayDetailPanel from './DayDetailPanel'; import DayDetailPanel from './DayDetailPanel';
const day = buildDay({ id: 1, trip_id: 1, date: '2025-06-15', title: 'Day in Paris' });
const props = {
day,
days: [day],
places: [],
categories: [],
tripId: 1,
assignments: {},
reservations: [],
lat: null,
lng: null,
onClose: vi.fn(),
onAccommodationChange: vi.fn(),
};
function settings(dayDateFirst: boolean) { function settings(dayDateFirst: boolean) {
seedStore(useSettingsStore, { seedStore(useSettingsStore, {
settings: { time_format: '24h', temperature_unit: 'celsius', day_date_first: dayDateFirst }, settings: { time_format: '24h', temperature_unit: 'celsius', day_date_first: dayDateFirst },
@@ -34,14 +14,7 @@ function settings(dayDateFirst: boolean) {
} }
beforeEach(() => { beforeEach(() => {
resetAllStores(); resetDayDetailPanel();
vi.clearAllMocks();
server.use(
http.get('/api/weather/detailed', () => HttpResponse.json({ error: true })),
http.get('/api/trips/1/accommodations', () => HttpResponse.json({ accommodations: [] }))
);
seedStore(useAuthStore, { user: buildAdmin(), isAuthenticated: true });
seedStore(useTripStore, { trip: buildTrip({ id: 1 }) });
}); });
describe('DayDetailPanel with the date first', () => { describe('DayDetailPanel with the date first', () => {
@@ -5,43 +5,17 @@ import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw'; import { http, HttpResponse } from 'msw';
import { server } from '../../../tests/helpers/msw/server'; import { server } from '../../../tests/helpers/msw/server';
import { useAuthStore } from '../../store/authStore'; import { useAuthStore } from '../../store/authStore';
import { useTripStore } from '../../store/tripStore';
import { useSettingsStore } from '../../store/settingsStore'; import { useSettingsStore } from '../../store/settingsStore';
import { usePermissionsStore } from '../../store/permissionsStore'; import { usePermissionsStore } from '../../store/permissionsStore';
import { usePluginStore } from '../../store/pluginStore'; import { usePluginStore } from '../../store/pluginStore';
import { resetAllStores, seedStore } from '../../../tests/helpers/store'; import { seedStore } from '../../../tests/helpers/store';
import { buildUser, buildAdmin, buildTrip, buildDay, buildPlace, buildReservation } from '../../../tests/helpers/factories'; import { buildUser, buildAdmin, buildDay, buildPlace, buildReservation } from '../../../tests/helpers/factories';
import { dayDetailDay as day, dayDetailProps as defaultProps, resetDayDetailPanel } from '../../../tests/helpers/dayDetailPanel';
import DayDetailPanel from './DayDetailPanel'; import DayDetailPanel from './DayDetailPanel';
import { isBlurred } from '../../../tests/helpers/bookingCodeBlur'; import { isBlurred } from '../../../tests/helpers/bookingCodeBlur';
const day = buildDay({ id: 1, trip_id: 1, date: '2025-06-15', title: 'Day in Paris' });
const defaultProps = {
day,
days: [day],
places: [],
categories: [],
tripId: 1,
assignments: {},
reservations: [],
lat: null,
lng: null,
onClose: vi.fn(),
onAccommodationChange: vi.fn(),
};
beforeEach(() => { beforeEach(() => {
resetAllStores(); resetDayDetailPanel({ time_format: '24h', temperature_unit: 'celsius', blur_booking_codes: false });
vi.clearAllMocks();
server.use(
http.get('/api/weather/detailed', () => HttpResponse.json({ error: true })),
http.get('/api/trips/1/accommodations', () => HttpResponse.json({ accommodations: [] })),
);
seedStore(useAuthStore, { user: buildAdmin(), isAuthenticated: true });
seedStore(useTripStore, { trip: buildTrip({ id: 1 }) });
seedStore(useSettingsStore, {
settings: { time_format: '24h', temperature_unit: 'celsius', blur_booking_codes: false },
});
}); });
/** The stay picker filters by category through a pill that opens its list; this picks one entry of it. */ /** The stay picker filters by category through a pill that opens its list; this picks one entry of it. */
@@ -147,13 +121,23 @@ describe('DayDetailPanel', () => {
}); });
it('FE-PLANNER-DAYDETAIL-009: weather loading state shown briefly', async () => { it('FE-PLANNER-DAYDETAIL-009: weather loading state shown briefly', async () => {
// The forecast is held until the spinner was seen, then released, so the request
// does not stay open past this test.
let release!: () => void;
const gate = new Promise<void>((resolve) => { release = resolve; });
server.use( server.use(
http.get('/api/weather/detailed', () => new Promise(() => {})), // never resolves http.get('/api/weather/detailed', async () => {
await gate;
return HttpResponse.json({ error: true });
}),
); );
render(<DayDetailPanel {...defaultProps} lat={48.8566} lng={2.3522} />); render(<DayDetailPanel {...defaultProps} lat={48.8566} lng={2.3522} />);
// The spinner announces itself as a loading status // The spinner announces itself as a loading status
const spinner = await screen.findByRole('status', { name: 'Loading...' }); const spinner = await screen.findByRole('status', { name: 'Loading...' });
expect(spinner.querySelector('.animate-spin')).not.toBeNull(); expect(spinner.querySelector('.animate-spin')).not.toBeNull();
release();
expect(await screen.findByText(/No weather/i)).toBeInTheDocument();
}); });
it('FE-PLANNER-DAYDETAIL-101: a late forecast for the previous day never replaces the one for the current day', async () => { it('FE-PLANNER-DAYDETAIL-101: a late forecast for the previous day never replaces the one for the current day', async () => {
@@ -1606,14 +1590,14 @@ describe('DayDetailPanel remaining branches', () => {
const user = userEvent.setup(); const user = userEvent.setup();
const onAccommodationChange = vi.fn(); const onAccommodationChange = vi.fn();
let updateBody: Record<string, unknown> | null = null; let updateBody: Record<string, unknown> | null = null;
let listCalls = 0; // The reload after the save reads the new name; keyed on the save, not on a
// count of reads, so a stray read before it cannot rename the stay early.
server.use( server.use(
http.get('/api/trips/1/accommodations', () => { http.get('/api/trips/1/accommodations', () =>
listCalls += 1; HttpResponse.json({
return HttpResponse.json({ accommodations: [hotel(updateBody ? { place_name: 'Reloaded Hotel' } : {})],
accommodations: [hotel(listCalls > 1 ? { place_name: 'Reloaded Hotel' } : {})], }),
}); ),
}),
http.put('/api/trips/1/accommodations/1', async ({ request }) => { http.put('/api/trips/1/accommodations/1', async ({ request }) => {
updateBody = (await request.json()) as Record<string, unknown>; updateBody = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({ accommodation: hotel() }); return HttpResponse.json({ accommodation: hotel() });
@@ -1874,25 +1858,40 @@ describe('DayDetailPanel remaining branches, part two', () => {
expect(await screen.findByText('15h 20m')).toBeInTheDocument(); expect(await screen.findByText('15h 20m')).toBeInTheDocument();
}); });
it('FE-W5DDP-021: a collapsed untitled day falls back to its position, or to ? when it has none', () => { it('FE-W5DDP-021: a collapsed untitled day falls back to its position, or to ? when it has none', async () => {
// Each mount reads the stays; wait for that read to be answered, so it cannot
// reach the handler of the test that runs next.
let staysRead = 0;
server.use(
http.get('/api/trips/1/accommodations', () => {
staysRead += 1;
return HttpResponse.json({ accommodations: [] });
}),
);
const bare = buildDay({ id: 2, trip_id: 1, date: null, title: null }); const bare = buildDay({ id: 2, trip_id: 1, date: null, title: null });
const { unmount } = render(<DayDetailPanel {...defaultProps} day={bare} days={[defaultProps.day, bare]} collapsed />); const { unmount } = render(<DayDetailPanel {...defaultProps} day={bare} days={[defaultProps.day, bare]} collapsed />);
expect(screen.getByText('Day 2')).toBeInTheDocument(); expect(screen.getByText('Day 2')).toBeInTheDocument();
await waitFor(() => expect(staysRead).toBe(1));
unmount(); unmount();
render(<DayDetailPanel {...defaultProps} day={bare} days={[]} collapsed />); render(<DayDetailPanel {...defaultProps} day={bare} days={[]} collapsed />);
expect(screen.getByText('Day ?')).toBeInTheDocument(); expect(screen.getByText('Day ?')).toBeInTheDocument();
await waitFor(() => expect(staysRead).toBe(2));
}); });
it('FE-W5DDP-020: an empty reload after the edit-save clears the accommodation', async () => { it('FE-W5DDP-020: an empty reload after the edit-save clears the accommodation', async () => {
const user = userEvent.setup(); const user = userEvent.setup();
let listCalls = 0; // The list empties once the edit is saved, not on a count of reads, so a stray
// read before the save cannot empty it early.
let saved = false;
server.use( server.use(
http.get('/api/trips/1/accommodations', () => { http.get('/api/trips/1/accommodations', () =>
listCalls += 1; saved ? HttpResponse.json({}) : HttpResponse.json({ accommodations: [hotel()] }),
return listCalls === 1 ? HttpResponse.json({ accommodations: [hotel()] }) : HttpResponse.json({}); ),
http.put('/api/trips/1/accommodations/1', () => {
saved = true;
return HttpResponse.json({ accommodation: hotel() });
}), }),
http.put('/api/trips/1/accommodations/1', () => HttpResponse.json({ accommodation: hotel() })),
); );
render(<DayDetailPanel {...defaultProps} places={[buildPlace({ id: 5, name: 'Grand Hotel' })]} />); render(<DayDetailPanel {...defaultProps} places={[buildPlace({ id: 5, name: 'Grand Hotel' })]} />);
@@ -585,3 +585,87 @@ describe('DayPlanSidebar, public transit between two city walks (CW-08)', () =>
expect(screen.getByTestId('tour-day-overrun')).toHaveTextContent('Ends at 14:00, after Harbour starts at 13:00'); expect(screen.getByTestId('tour-day-overrun')).toHaveTextContent('Ends at 14:00, after Harbour starts at 13:00');
}); });
}); });
// The walk from a train's arrival to the night's hotel: no stop is at either end, so
// there is no mode to change, and the desktop left it inert. The transit search is
// what can be planned for it, as for every other leg.
describe('DayPlanSidebar, public transit from a booking arrival to the hotel', () => {
it('FE-PLANNER-DAYPLAN-171f: the walk from a train arrival to the hotel, which no stop owns, offers public transport', async () => {
const user = userEvent.setup();
const onPlanTransitLeg = vi.fn();
const days = [
buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }),
buildDay({ id: 11, date: '2025-06-02', title: 'Day 2' }),
buildDay({ id: 12, date: '2025-06-03', title: 'Day 3' }),
];
const accommodations = [
{
id: 1,
trip_id: 1,
start_day_id: 10,
end_day_id: 12,
place_lat: 47.5,
place_lng: 19.05,
place_name: 'Basilica apARTment',
},
];
const train = buildReservation({
id: 430,
type: 'train',
title: 'Wien => Budapest',
day_id: 11,
end_day_id: 11,
day_plan_position: 5,
reservation_time: '2025-06-02T16:42:00',
reservation_end_time: '2025-06-02T19:29:00',
endpoints: [
{
role: 'from',
sequence: 0,
name: 'Wien Hbf',
code: null,
lat: 48.18,
lng: 16.37,
timezone: null,
local_date: null,
local_time: null,
},
{
role: 'to',
sequence: 1,
name: 'Budapest Keleti',
code: null,
lat: 47.5,
lng: 19.08,
timezone: null,
local_date: null,
local_time: null,
},
],
});
const albertina = buildPlace({ id: 1, name: 'Albertina', place_time: '12:00', lat: 48.2, lng: 16.37 });
render(
<DayPlanSidebar
{...makeDefaultProps({
days,
assignments: { '11': [buildAssignment({ id: 11, day_id: 11, order_index: 0, place: albertina })] },
accommodations,
reservations: [train],
selectedDayId: 11,
routeShown: true,
onPlanTransitLeg,
})}
/>
);
await user.click(await screen.findByLabelText('Public transit'));
expect(contextMenu().queryByRole('button', { name: 'Driving' })).not.toBeInTheDocument();
await user.click(contextMenu().getByRole('button', { name: 'Public transit' }));
expect(onPlanTransitLeg).toHaveBeenCalledWith(
expect.objectContaining({
dayId: 11,
from: expect.objectContaining({ lat: 47.5, lng: 19.08 }),
to: { name: 'Basilica apARTment', lat: 47.5, lng: 19.05 },
})
);
});
});
@@ -69,7 +69,7 @@ import { findTodayDayId } from './today'
import { markdownLinkComponents } from '../shared/markdownLink' import { markdownLinkComponents } from '../shared/markdownLink'
import { RouteConnector, HotelRouteConnector } from './DayPlanSidebarRouteConnector' import { RouteConnector, HotelRouteConnector } from './DayPlanSidebarRouteConnector'
import { resolveLegMode } from './legMode' import { resolveLegMode } from './legMode'
import { useLegModeActions } from './useLegModeActions' import { transitOnlyMenuItems, useLegModeActions } from './useLegModeActions'
import { dayExportStops, fillAroundLocked } from './dayRoute' import { dayExportStops, fillAroundLocked } from './dayRoute'
import { projectDayItinerary, projectedById, type TourStageStops } from '../Map/dayTourProjection' import { projectDayItinerary, projectedById, type TourStageStops } from '../Map/dayTourProjection'
import type { DayRoutePoint } from '../Map/dayRoutePlan' import type { DayRoutePoint } from '../Map/dayRoutePlan'
@@ -1413,6 +1413,27 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
} as unknown as React.MouseEvent) } as unknown as React.MouseEvent)
} }
// A hotel bookend leg opens the mode menu of the stop that owns it, the first stop's
// incoming mode at the top and the last stop's outgoing mode at the bottom. One no
// stop owns, a booking's arrival to the hotel, can only have transit planned.
const hotelLegRow = (dayId: number, leg: { seg: RouteSegment; name: string; targetId?: number }, placement: 'top' | 'bottom') => {
const connector = <HotelRouteConnector seg={leg.seg} name={leg.name} profile={routeProfile} placement={placement} />
const targetId = leg.targetId
const planTransit = targetId == null ? transitLegPlanner(dayId, leg.seg) : undefined
const open = targetId != null
? (e: React.MouseEvent) => (placement === 'top' ? openIncomingLegModeMenu : openLegModeMenu)(e, targetId, dayId, leg.seg)
: planTransit && ((e: React.MouseEvent) => ctxMenu.open(e, transitOnlyMenuItems(planTransit, t)))
if (!canEditDays || !open) return connector
const label = targetId != null ? t('dayplan.transportMode.change') : t('transit.title')
return (
<Tooltip label={label} placement="top">
<div role="button" tabIndex={0} onClick={open} onKeyDown={e => openLegMenuByKey(e, open)} style={{ cursor: 'pointer' }} aria-label={label}>
{connector}
</div>
</Tooltip>
)
}
return ( return (
// Sized as a flex child as well as by height: the desktop panel puts the Days / Road // Sized as a flex child as well as by height: the desktop panel puts the Days / Road
// trip switch above this, and at height 100% alone the list ran the switch's height // trip switch above this, and at height 100% alone the list ran the switch's height
@@ -1734,17 +1755,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
dropAfterLastItem(day.id, { assignmentId, noteId }) dropAfterLastItem(day.id, { assignmentId, noteId })
}} }}
> >
{hotelLegs[day.id]?.top && (() => { {hotelLegs[day.id]?.top && hotelLegRow(day.id, hotelLegs[day.id]!.top!, 'top')}
const targetId = hotelLegs[day.id]?.top?.targetId
const connector = <HotelRouteConnector seg={hotelLegs[day.id]!.top!.seg} name={hotelLegs[day.id]!.top!.name} profile={routeProfile} placement="top" />
return canEditDays && targetId != null ? (
<Tooltip label={t('dayplan.transportMode.change')} placement="top">
<div role="button" tabIndex={0} onClick={e => openIncomingLegModeMenu(e, targetId, day.id, hotelLegs[day.id]!.top!.seg)} onKeyDown={e => openLegMenuByKey(e, m => openIncomingLegModeMenu(m, targetId, day.id, hotelLegs[day.id]!.top!.seg))} style={{ cursor: 'pointer' }} aria-label={t('dayplan.transportMode.change')}>
{connector}
</div>
</Tooltip>
) : connector
})()}
{daySchedule.byPosition[day.id]?.start.map(si => <PluginDayScheduleRow key={`${si.pluginId}:${si.id}`} item={si} />)} {daySchedule.byPosition[day.id]?.start.map(si => <PluginDayScheduleRow key={`${si.pluginId}:${si.id}`} item={si} />)}
{visibleCount === 0 && !dayNoteUi ? ( {visibleCount === 0 && !dayNoteUi ? (
<div <div
@@ -2477,17 +2488,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
}) })
)} )}
{daySchedule.byPosition[day.id]?.end.map(si => <PluginDayScheduleRow key={`${si.pluginId}:${si.id}`} item={si} />)} {daySchedule.byPosition[day.id]?.end.map(si => <PluginDayScheduleRow key={`${si.pluginId}:${si.id}`} item={si} />)}
{hotelLegs[day.id]?.bottom && (() => { {hotelLegs[day.id]?.bottom && hotelLegRow(day.id, hotelLegs[day.id]!.bottom!, 'bottom')}
const targetId = hotelLegs[day.id]?.bottom?.targetId
const connector = <HotelRouteConnector seg={hotelLegs[day.id]!.bottom!.seg} name={hotelLegs[day.id]!.bottom!.name} profile={routeProfile} placement="bottom" />
return canEditDays && targetId != null ? (
<Tooltip label={t('dayplan.transportMode.change')} placement="top">
<div role="button" tabIndex={0} onClick={e => openLegModeMenu(e, targetId, day.id, hotelLegs[day.id]!.bottom!.seg)} onKeyDown={e => openLegMenuByKey(e, m => openLegModeMenu(m, targetId, day.id, hotelLegs[day.id]!.bottom!.seg))} style={{ cursor: 'pointer' }} aria-label={t('dayplan.transportMode.change')}>
{connector}
</div>
</Tooltip>
) : connector
})()}
<AssistantDayPreview tripId={tripId} dayId={day.id} />{/* The assistant's waiting changes, then the drop zone at the list end */} <AssistantDayPreview tripId={tripId} dayId={day.id} />{/* The assistant's waiting changes, then the drop zone at the list end */}
<div <div
style={{ minHeight: 12, padding: '2px 8px' }} style={{ minHeight: 12, padding: '2px 8px' }}
@@ -34,6 +34,15 @@ export function legModeMenuItems(
]; ];
} }
/**
* The menu of a leg no stop owns, a booking's arrival to the night's hotel: nothing
* keeps a mode for it, so it follows the day default and only public transit can be
* planned for it.
*/
export function transitOnlyMenuItems(planTransit: () => void, t: Translate): LegModeMenuItem[] {
return [{ label: t('transit.title'), icon: TramFront, onClick: planTransit }];
}
export interface LegModeDeps { export interface LegModeDeps {
tripId: number; tripId: number;
toast: { error: (message: string) => void }; toast: { error: (message: string) => void };
@@ -1,5 +1,6 @@
// FE-COMP-PLUGIN-USERSET-001 to -012: the per plugin user settings logic both settings shells share. // FE-COMP-PLUGIN-USERSET-001 to -012: the per plugin user settings logic both settings shells share.
import { act, renderHook, waitFor } from '@testing-library/react'; import { act, renderHook, waitFor } from '@testing-library/react';
import { locationAt } from '../../../tests/helpers/location';
import { pluginsApi, type PluginAction, type PluginUserSettingField } from '../../api/client'; import { pluginsApi, type PluginAction, type PluginUserSettingField } from '../../api/client';
import { SECRET_MASK } from './settingsForm'; import { SECRET_MASK } from './settingsForm';
import { usePluginOAuth, usePluginUserSettings } from './usePluginUserSettings'; import { usePluginOAuth, usePluginUserSettings } from './usePluginUserSettings';
@@ -150,7 +151,7 @@ describe('usePluginOAuth', () => {
it('FE-COMP-PLUGIN-USERSET-012: a connect hands off to the provider and keeps the button busy', async () => { it('FE-COMP-PLUGIN-USERSET-012: a connect hands off to the provider and keeps the button busy', async () => {
const realLocation = window.location; const realLocation = window.location;
const loc = { href: 'http://localhost/settings' }; const loc = locationAt('/settings');
Object.defineProperty(window, 'location', { writable: true, configurable: true, value: loc }); Object.defineProperty(window, 'location', { writable: true, configurable: true, value: loc });
try { try {
vi.spyOn(pluginsApi, 'oauthConnect').mockResolvedValue({ vi.spyOn(pluginsApi, 'oauthConnect').mockResolvedValue({
@@ -0,0 +1,41 @@
// FE-COMP-ACCOUNT-APPS-001 to FE-COMP-ACCOUNT-APPS-002
import { http, HttpResponse } from 'msw';
import { describe, expect, it, vi } from 'vitest';
import { buildSettings, buildUser } from '../../../tests/helpers/factories';
import { server } from '../../../tests/helpers/msw/server';
import { render, screen } from '../../../tests/helpers/render';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { isNativeApp } from '../../native/platform';
import { useAuthStore } from '../../store/authStore';
import { useSettingsStore } from '../../store/settingsStore';
import AccountTab from './AccountTab';
vi.mock('../../sync/syncTriggers', () => ({ registerSyncTriggers: vi.fn(), unregisterSyncTriggers: vi.fn() }));
vi.mock('../../native/platform', async (importOriginal) => ({
...(await importOriginal<typeof import('../../native/platform')>()),
isNativeApp: vi.fn(() => false),
}));
beforeEach(() => {
resetAllStores();
server.use(http.get('/api/auth/app-config', () => HttpResponse.json({ version: '5.2.1', mfa_enabled: false })));
seedStore(useAuthStore, { user: buildUser({ username: 'testuser', role: 'user' }), isAuthenticated: true });
seedStore(useSettingsStore, { settings: buildSettings() });
});
describe('AccountTab app stores', () => {
it('FE-COMP-ACCOUNT-APPS-001: in a browser it offers both app stores with their QR codes', () => {
render(<AccountTab />);
expect(screen.getByText('TREK app')).toBeInTheDocument();
expect(screen.getByText('Scan a code with your phone, then connect the app to this server.')).toBeInTheDocument();
expect(document.querySelectorAll('a.asc-card')).toHaveLength(2);
});
it('FE-COMP-ACCOUNT-APPS-002: inside the app itself there is nothing to download', () => {
vi.mocked(isNativeApp).mockReturnValue(true);
render(<AccountTab />);
expect(screen.queryByText('TREK app')).toBeNull();
expect(document.querySelector('a.asc-card')).toBeNull();
vi.mocked(isNativeApp).mockReturnValue(false);
});
});
+10 -1
View File
@@ -1,5 +1,5 @@
import React, { useId } from 'react' import React, { useId } from 'react'
import { User, Save, Lock, KeyRound, AlertTriangle, Shield, Camera, Trash2, Copy, Download, Printer, ShieldCheck } from 'lucide-react' import { User, Save, Lock, KeyRound, AlertTriangle, Shield, Camera, Trash2, Copy, Download, Printer, ShieldCheck, Smartphone } from 'lucide-react'
import { useTranslation } from '../../i18n' import { useTranslation } from '../../i18n'
import Section from './Section' import Section from './Section'
import PasskeysSection from './PasskeysSection' import PasskeysSection from './PasskeysSection'
@@ -12,6 +12,8 @@ import { EditorField, GRID_2, INPUT, PANEL } from '../shared/dialogParts'
import { SETTINGS_BUTTON, SETTINGS_BUTTON_DANGER, SETTINGS_BUTTON_PRIMARY, SettingRow, SettingRows, SettingsHint, StatusPill, SettingsColumns } from './settingsKit' import { SETTINGS_BUTTON, SETTINGS_BUTTON_DANGER, SETTINGS_BUTTON_PRIMARY, SettingRow, SettingRows, SettingsHint, StatusPill, SettingsColumns } from './settingsKit'
import { stripTrailingSlashes, useAccountSettings } from './useAccountSettings' import { stripTrailingSlashes, useAccountSettings } from './useAccountSettings'
import AccountDemoLock from './AccountDemoLock' import AccountDemoLock from './AccountDemoLock'
import AppStoreCards from '../shared/AppStoreCards'
import { isNativeApp } from '../../native/platform'
/** The small turning ring a button shows while its request is on the way. */ /** The small turning ring a button shows while its request is on the way. */
const SPINNER = 'h-3.5 w-3.5 flex-none animate-spin rounded-full border-2 border-current border-t-transparent' const SPINNER = 'h-3.5 w-3.5 flex-none animate-spin rounded-full border-2 border-current border-t-transparent'
@@ -366,6 +368,13 @@ export default function AccountTab(): React.ReactElement {
{/* Passkeys */} {/* Passkeys */}
<PasskeysSection demoMode={demoMode} /> <PasskeysSection demoMode={demoMode} />
{/* Where to get the phone app; inside the app itself there is nothing to fetch. */}
{!isNativeApp() && (
<Section title={t('settings.apps.title')} icon={Smartphone} hint={t('settings.apps.hint')}>
<AppStoreCards />
</Section>
)}
</>} </>}
/> />
</AccountDemoLock> </AccountDemoLock>
@@ -4,6 +4,7 @@ import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw'; import { http, HttpResponse } from 'msw';
import { render, screen, waitFor, within } from '../../../tests/helpers/render'; import { render, screen, waitFor, within } from '../../../tests/helpers/render';
import { server } from '../../../tests/helpers/msw/server'; import { server } from '../../../tests/helpers/msw/server';
import { locationAt } from '../../../tests/helpers/location';
import { ToastContainer } from '../shared/Toast'; import { ToastContainer } from '../shared/Toast';
import { usePluginStore, type ActivePlugin } from '../../store/pluginStore'; import { usePluginStore, type ActivePlugin } from '../../store/pluginStore';
import type { PluginAction, PluginUserSettingField } from '../../api/client'; import type { PluginAction, PluginUserSettingField } from '../../api/client';
@@ -367,7 +368,7 @@ describe('PluginSettingsTab', () => {
it('FE-COMP-PLUGINSETTINGS-020: an OAuth-only plugin gets a card and Connect hands off to the provider', async () => { it('FE-COMP-PLUGINSETTINGS-020: an OAuth-only plugin gets a card and Connect hands off to the provider', async () => {
const user = userEvent.setup(); const user = userEvent.setup();
const loc = { href: 'http://localhost/settings', origin: 'http://localhost', pathname: '/settings' }; const loc = locationAt('/settings');
vi.stubGlobal('location', loc); vi.stubGlobal('location', loc);
serve('weather', {}, { configured: true, connected: false }); serve('weather', {}, { configured: true, connected: false });
server.use(http.post('/api/plugin-oauth/weather/connect', () => server.use(http.post('/api/plugin-oauth/weather/connect', () =>
@@ -1,4 +1,4 @@
// FE-HOOK-AI-CONNECT-001 to FE-HOOK-AI-CONNECT-015: pasting a key, an own server, the ChatGPT sign-in and the OpenRouter return. // FE-HOOK-AI-CONNECT-001 to FE-HOOK-AI-CONNECT-017: pasting a key, an own server, the ChatGPT sign-in and the OpenRouter return.
import { act, fireEvent, renderHook, waitFor } from '@testing-library/react'; import { act, fireEvent, renderHook, waitFor } from '@testing-library/react';
import { createElement, type ReactNode } from 'react'; import { createElement, type ReactNode } from 'react';
import { MemoryRouter, useLocation } from 'react-router'; import { MemoryRouter, useLocation } from 'react-router';
@@ -20,6 +20,7 @@ vi.mock('../../shared/Toast', () => ({ useToast: () => toast }));
const { useChatgptConnect, useCustomConnect, useKeyConnect, useOpenrouterReturn, useOpenrouterStart } = const { useChatgptConnect, useCustomConnect, useKeyConnect, useOpenrouterReturn, useOpenrouterStart } =
await import('./useAiConnect'); await import('./useAiConnect');
const { rememberOpenrouterFlow } = await import('./aiConnectModel'); const { rememberOpenrouterFlow } = await import('./aiConnectModel');
const { OnlineOnlyError } = await import('../../../repo/onlineOnly');
function wrapperAt(url = '/settings') { function wrapperAt(url = '/settings') {
return ({ children }: { children: ReactNode }) => return ({ children }: { children: ReactNode }) =>
@@ -207,7 +208,7 @@ describe('useChatgptConnect', () => {
expect(repo.chatgptFinish).not.toHaveBeenCalled(); expect(repo.chatgptFinish).not.toHaveBeenCalled();
}); });
it('FE-HOOK-AI-CONNECT-010: an account ChatGPT will not share says so and keeps the flow', async () => { it('FE-HOOK-AI-CONNECT-010: an account ChatGPT will not share says so, and the next try is a fresh sign-in', async () => {
repo.chatgptFinish.mockRejectedValueOnce(refused('not_eligible')); repo.chatgptFinish.mockRejectedValueOnce(refused('not_eligible'));
const onConnected = vi.fn(); const onConnected = vi.fn();
const { result } = renderHook(() => useChatgptConnect({ active: true, onConnected }), { wrapper: wrapperAt() }); const { result } = renderHook(() => useChatgptConnect({ active: true, onConnected }), { wrapper: wrapperAt() });
@@ -216,7 +217,50 @@ describe('useChatgptConnect', () => {
await act(() => result.current.submit()); await act(() => result.current.submit());
expect(result.current.error).toEqual({ messageKey: 'assistant.error.notEligible', code: 'not_eligible' }); expect(result.current.error).toEqual({ messageKey: 'assistant.error.notEligible', code: 'not_eligible' });
expect(onConnected).not.toHaveBeenCalled(); expect(onConnected).not.toHaveBeenCalled();
expect(repo.chatgptStart).toHaveBeenCalledTimes(1); // The server took the sign-in when it refused it.
await waitFor(() => expect(repo.chatgptStart).toHaveBeenCalledTimes(2));
});
it('FE-HOOK-AI-CONNECT-016: any refusal the server sent starts exactly one fresh sign-in; offline and a wrong address keep this one', async () => {
const generic = Object.assign(new Error('generic'), {
response: { status: 400, data: { error: 'ChatGPT refused the sign-in (invalid_client)', code: 'generic' } },
});
repo.chatgptFinish.mockRejectedValueOnce(generic).mockRejectedValueOnce(new OnlineOnlyError());
const { result } = renderHook(() => useChatgptConnect({ active: true, onConnected: vi.fn() }), {
wrapper: wrapperAt(),
});
await waitFor(() => expect(result.current.flow).not.toBeNull());
act(() => result.current.change(CALLBACK));
await act(() => result.current.submit());
expect(result.current.error?.code).toBe('generic');
await waitFor(() => expect(repo.chatgptStart).toHaveBeenCalledTimes(2));
await waitFor(() => expect(result.current.flow).not.toBeNull());
act(() => result.current.change(CALLBACK));
await act(() => result.current.submit());
expect(result.current.error?.code).toBe('offline');
expect(repo.chatgptStart).toHaveBeenCalledTimes(2);
// The server refuses a wrong address before it takes the sign-in, so the right one still works.
repo.chatgptFinish.mockRejectedValueOnce(refused('wrong_url'));
act(() => result.current.change(CALLBACK));
await act(() => result.current.submit());
expect(result.current.error?.code).toBe('wrong_url');
expect(repo.chatgptStart).toHaveBeenCalledTimes(2);
});
it('FE-HOOK-AI-CONNECT-017: the address pasted without http://, as the hint shows it, is taken and sent with it', async () => {
const onConnected = vi.fn();
const { result } = renderHook(() => useChatgptConnect({ active: true, onConnected }), { wrapper: wrapperAt() });
await waitFor(() => expect(result.current.flow).not.toBeNull());
const bare = CALLBACK.replace('http://', '');
let taken = false;
act(() => {
taken = result.current.paste(` ${bare} `);
});
expect(taken).toBe(true);
await waitFor(() => expect(onConnected).toHaveBeenCalledTimes(1));
expect(repo.chatgptFinish).toHaveBeenCalledWith({ flowId: FLOW.flowId, pastedUrl: CALLBACK });
}); });
it('FE-HOOK-AI-CONNECT-013: the clipboard fills the field where the browser lets it be read, else the field gets the cursor', async () => { it('FE-HOOK-AI-CONNECT-013: the clipboard fills the field where the browser lets it be read, else the field gets the cursor', async () => {
@@ -3,7 +3,7 @@ import { useEffect, useEffectEvent, useRef, useState } from 'react';
import { useSearchParams } from 'react-router'; import { useSearchParams } from 'react-router';
import { useTranslation } from '../../../i18n'; import { useTranslation } from '../../../i18n';
import { aiConnectionsRepo } from '../../../repo/aiConnectionsRepo'; import { aiConnectionsRepo } from '../../../repo/aiConnectionsRepo';
import { detectKeyKind, isChatgptCallback, providerLabel } from '../../Assistant/providerCatalog'; import { chatgptCallbackUrl, detectKeyKind, isChatgptCallback, providerLabel } from '../../Assistant/providerCatalog';
import { useToast } from '../../shared/Toast'; import { useToast } from '../../shared/Toast';
import { import {
callbackMatchesFlow, callbackMatchesFlow,
@@ -243,9 +243,9 @@ export function useChatgptConnect({
}; };
const finish = async (raw: string) => { const finish = async (raw: string) => {
const url = raw.trim(); const url = chatgptCallbackUrl(raw);
if (!flow || finishing.current) return; if (!flow || finishing.current) return;
if (!isChatgptCallback(url) || !callbackMatchesFlow(url, flow.authorizeUrl)) { if (!url || !callbackMatchesFlow(url, flow.authorizeUrl)) {
setError({ messageKey: 'assistant.connect.chatgptWrong', code: 'wrong_url' }); setError({ messageKey: 'assistant.connect.chatgptWrong', code: 'wrong_url' });
return; return;
} }
@@ -264,7 +264,9 @@ export function useChatgptConnect({
} catch (err) { } catch (err) {
const code = refusalCode(err); const code = refusalCode(err);
setError({ messageKey: connectErrorKey(err), code }); setError({ messageKey: connectErrorKey(err), code });
if (code === 'expired') restart(); // The server takes a sign-in once, whatever it answers: any refusal it sent
// used this one up. Offline the request never left, and a wrong address is refused before the flow is taken.
if (code !== null && code !== 'offline' && code !== 'wrong_url') restart();
} finally { } finally {
finishing.current = false; finishing.current = false;
setBusy(false); setBusy(false);
@@ -298,7 +300,7 @@ export function useChatgptConnect({
useOnReturnToTab(opened, () => { useOnReturnToTab(opened, () => {
if (pasted.trim() || busy) return; if (pasted.trim() || busy) return;
readClipboard((text) => { readClipboard((text) => {
if (flow && !callbackMatchesFlow(text, flow.authorizeUrl)) focusField(); if (flow && !callbackMatchesFlow(chatgptCallbackUrl(text) ?? text, flow.authorizeUrl)) focusField();
else if (!paste(text)) focusField(); else if (!paste(text)) focusField();
}, focusField); }, focusField);
}); });
@@ -1,4 +1,4 @@
// FE-RN-001 to FE-RN-020 // FE-RN-001 to FE-RN-022
import userEvent from '@testing-library/user-event'; import userEvent from '@testing-library/user-event';
import { describe, expect, it, vi } from 'vitest'; import { describe, expect, it, vi } from 'vitest';
import { render, screen } from '../../../tests/helpers/render'; import { render, screen } from '../../../tests/helpers/render';
@@ -295,4 +295,23 @@ describe('ReleaseNoticeModal', () => {
expect(document.querySelectorAll('.rn-vis-route-stop')).toHaveLength(5); expect(document.querySelectorAll('.rn-vis-route-stop')).toHaveLength(5);
expect(document.querySelector('.rn-vis-route-line')).not.toBeNull(); expect(document.querySelector('.rn-vis-route-line')).not.toBeNull();
}); });
it('FE-RN-021: an apps block draws one tile with its title and both store cards', () => {
renderModal(withRelease({ apps: { titleKey: 'rel.apps.title' } }));
const tile = document.querySelector('.rn-apps');
expect(tile).toHaveTextContent('rel.apps.title');
const stores = tile?.querySelectorAll('a.asc-card') ?? [];
expect([...stores].map((a) => a.getAttribute('href'))).toEqual([
'https://apps.apple.com/app/id6831237775',
'https://play.google.com/store/apps/details?id=com.liketrek.trek',
]);
// On the release column, which is dark in either theme.
expect(tile?.querySelector('.asc-row')).toHaveClass('asc-dark');
});
it('FE-RN-022: without an apps block there is no apps tile', () => {
renderModal();
expect(document.querySelector('.rn-apps')).toBeNull();
expect(document.querySelector('.asc-card')).toBeNull();
});
}); });
@@ -2,6 +2,7 @@ import { ArrowRight, Heart, Infinity as InfinityIcon, ShieldCheck, X } from 'luc
import React from 'react'; import React from 'react';
import { useTranslation } from '../../i18n/TranslationContext.js'; import { useTranslation } from '../../i18n/TranslationContext.js';
import type { SystemNoticeDTO } from '../../store/systemNoticeStore.js'; import type { SystemNoticeDTO } from '../../store/systemNoticeStore.js';
import AppStoreCards from '../shared/AppStoreCards';
import { PATREON_PATH } from '../shared/PatreonIcon'; import { PATREON_PATH } from '../shared/PatreonIcon';
import { ReleaseFeatureVisual } from './ReleaseNoticeVisuals.js'; import { ReleaseFeatureVisual } from './ReleaseNoticeVisuals.js';
import './releaseNotice.css'; import './releaseNotice.css';
@@ -127,6 +128,16 @@ export function ReleaseNoticeModal({ notice, visible, onDismiss, onCTA, onSecond
{withSponsorLink(t(release.introKey))} {withSponsorLink(t(release.introKey))}
</p> </p>
{release.apps && (
<div className="rn-apps">
<div className="rn-feature-shine" aria-hidden="true" />
<div className="rn-apps-text">
<div className="rn-feature-title">{t(release.apps.titleKey)}</div>
</div>
<AppStoreCards tone="dark" className="rn-apps-stores" />
</div>
)}
<div className="rn-features-head"> <div className="rn-features-head">
<span className="rn-features-label">{t(release.featuresLabelKey)}</span> <span className="rn-features-label">{t(release.featuresLabelKey)}</span>
<span className="rn-features-rule" aria-hidden="true" /> <span className="rn-features-rule" aria-hidden="true" />
@@ -647,3 +647,28 @@
.rn-sponsor:hover { .rn-sponsor:hover {
text-decoration-color: currentColor; text-decoration-color: currentColor;
} }
/* ── The apps: one tile across the column, the text beside the store cards ── */
.rn-apps {
position: relative;
margin-top: 22px;
display: flex;
align-items: center;
gap: 22px;
padding: 16px 16px 16px 20px;
border-radius: 20px;
background: linear-gradient(160deg, oklch(1 0 0 / 0.1) 0%, oklch(1 0 0 / 0.045) 62%);
border: 1px solid oklch(1 0 0 / 0.13);
box-shadow: inset 0 1px 0 oklch(1 0 0 / 0.16), 0 12px 28px -16px oklch(0 0 0 / 0.7);
overflow: hidden;
}
.rn-apps-text { position: relative; flex: 1 1 200px; min-width: 0; }
.rn-apps-stores { position: relative; flex: 0 1 520px; min-width: 0; }
@media (max-width: 1280px) {
.rn-apps { flex-direction: column; align-items: stretch; }
.rn-apps-stores { flex-basis: auto; }
}
@@ -0,0 +1,39 @@
// FE-APPSTORE-001 to FE-APPSTORE-003
import { describe, expect, it } from 'vitest';
import { render } from '../../../tests/helpers/render';
import AppStoreCards from './AppStoreCards';
describe('AppStoreCards', () => {
it('FE-APPSTORE-001: links both stores in a new tab, each with its QR code', () => {
render(<AppStoreCards />);
const cards = [...document.querySelectorAll<HTMLAnchorElement>('a.asc-card')];
expect(cards.map((a) => a.href)).toEqual([
'https://apps.apple.com/app/id6831237775',
'https://play.google.com/store/apps/details?id=com.liketrek.trek',
]);
for (const a of cards) {
expect(a).toHaveAttribute('target', '_blank');
expect(a).toHaveAttribute('rel', 'noopener noreferrer');
expect(a.querySelector('.asc-qr path')?.getAttribute('d')).toMatch(/^M0 0\.5h7/);
}
});
it('FE-APPSTORE-002: names each store and translates the lines around it', () => {
render(<AppStoreCards />);
const [ios, android] = document.querySelectorAll('a.asc-card');
expect(ios).toHaveTextContent('Download on the');
expect(ios).toHaveTextContent('App Store');
expect(ios).toHaveTextContent('iPhone and iPad');
expect(android).toHaveTextContent('Get it on');
expect(android).toHaveTextContent('Google Play');
expect(android).toHaveTextContent('Phone and tablet');
});
it('FE-APPSTORE-003: the dark tone marks the row, the theme tone does not', () => {
const { unmount } = render(<AppStoreCards tone="dark" className="x" />);
expect(document.querySelector('.asc-row')).toHaveClass('asc-dark', 'x');
unmount();
render(<AppStoreCards />);
expect(document.querySelector('.asc-row')).not.toHaveClass('asc-dark');
});
});
@@ -0,0 +1,65 @@
import React from 'react';
import { useTranslation } from '../../i18n/TranslationContext.js';
import './appStoreCards.css';
/**
* The two app stores TREK is in, each as a card with its QR code: scanned with a
* phone it opens the store page, clicked it opens it here. The README draws the
* same cards. The QR codes are generated from the store addresses below (qrcode,
* margin 0, level M); regenerate them if an address changes.
*/
const APP_STORES = [
{
id: 'ios',
href: 'https://apps.apple.com/app/id6831237775',
store: 'App Store',
captionKey: 'settings.apps.downloadOn',
devicesKey: 'settings.apps.iosDevices',
logo: 'M12.152 6.896c-.948 0-2.415-1.078-3.96-1.04-2.04.027-3.91 1.183-4.961 3.014-2.117 3.675-.546 9.103 1.519 12.09 1.013 1.454 2.208 3.09 3.792 3.039 1.52-.065 2.09-.987 3.935-.987 1.831 0 2.35.987 3.96.948 1.637-.026 2.676-1.48 3.676-2.948 1.156-1.688 1.636-3.325 1.662-3.415-.039-.013-3.182-1.221-3.22-4.857-.026-3.04 2.48-4.494 2.597-4.559-1.429-2.09-3.623-2.324-4.39-2.376-2-.156-3.675 1.09-4.61 1.09zM15.53 3.83c.843-1.012 1.4-2.427 1.245-3.83-1.207.052-2.662.805-3.532 1.818-.78.896-1.454 2.338-1.273 3.714 1.338.104 2.715-.688 3.559-1.701',
qrSize: 29,
qr: 'M0 0.5h7m2 0h1m2 0h1m2 0h5m2 0h7M0 1.5h1m5 0h1m3 0h3m4 0h1m2 0h1m1 0h1m5 0h1M0 2.5h1m1 0h3m1 0h1m1 0h1m5 0h1m1 0h1m3 0h1m1 0h1m1 0h3m1 0h1M0 3.5h1m1 0h3m1 0h1m1 0h1m2 0h2m4 0h1m1 0h1m2 0h1m1 0h3m1 0h1M0 4.5h1m1 0h3m1 0h1m1 0h1m2 0h5m2 0h3m1 0h1m1 0h3m1 0h1M0 5.5h1m5 0h1m1 0h3m1 0h5m1 0h1m1 0h1m1 0h1m5 0h1M0 6.5h7m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h7M8 7.5h3m2 0h1m1 0h2m2 0h2M0 8.5h1m1 0h5m4 0h1m2 0h4m1 0h1m2 0h5M0 9.5h3m2 0h1m2 0h4m3 0h1m3 0h4m1 0h1m3 0h1M0 10.5h4m1 0h7m6 0h1m1 0h1m1 0h2M5 11.5h1m1 0h3m1 0h1m2 0h2m2 0h2m1 0h2m1 0h2m1 0h1M2 12.5h1m3 0h3m1 0h1m1 0h1m2 0h3m5 0h1m1 0h2M0 13.5h1m4 0h1m3 0h1m1 0h1m1 0h2m1 0h1m2 0h6m3 0h1M1 14.5h3m1 0h2m5 0h3m3 0h1m2 0h1m2 0h3M0 15.5h1m2 0h2m2 0h7m2 0h1m1 0h3m3 0h1m2 0h1M3 16.5h2m1 0h1m3 0h1m1 0h1m1 0h1m1 0h4m3 0h1m1 0h2M0 17.5h4m5 0h3m3 0h1m1 0h3m2 0h3m1 0h1m1 0h1M0 18.5h1m1 0h1m2 0h2m8 0h3m2 0h2m2 0h1m1 0h1M0 19.5h1m1 0h2m1 0h1m3 0h4m1 0h1m5 0h2m2 0h1m2 0h1M0 20.5h1m1 0h1m1 0h1m1 0h3m8 0h1m2 0h5m1 0h3M8 21.5h1m1 0h5m2 0h2m1 0h1m3 0h5M0 22.5h7m2 0h1m1 0h1m1 0h2m3 0h3m1 0h1m1 0h3M0 23.5h1m5 0h1m1 0h1m1 0h1m2 0h1m5 0h2m3 0h1M0 24.5h1m1 0h3m1 0h1m1 0h1m2 0h2m1 0h1m2 0h1m2 0h5m1 0h1m1 0h1M0 25.5h1m1 0h3m1 0h1m1 0h2m1 0h1m6 0h1m4 0h1m1 0h2M0 26.5h1m1 0h3m1 0h1m1 0h1m1 0h1m1 0h1m2 0h1m3 0h2m1 0h6M0 27.5h1m5 0h1m2 0h3m3 0h1m2 0h1m1 0h2m1 0h3m1 0h1M0 28.5h7m1 0h2m1 0h1m3 0h2m1 0h2m1 0h1m2 0h1m1 0h1',
},
{
id: 'android',
href: 'https://play.google.com/store/apps/details?id=com.liketrek.trek',
store: 'Google Play',
captionKey: 'settings.apps.getItOn',
devicesKey: 'settings.apps.androidDevices',
logo: 'M22.018 13.298l-3.919 2.218-3.515-3.493 3.543-3.521 3.891 2.202a1.49 1.49 0 0 1 0 2.594zM1.337.924a1.486 1.486 0 0 0-.112.568v21.017c0 .217.045.419.124.6l11.155-11.087L1.337.924zm12.207 10.065l3.258-3.238L3.45.195a1.466 1.466 0 0 0-.946-.179l11.04 10.973zm0 2.067l-11 10.933c.298.036.612-.016.906-.183l13.324-7.54-3.23-3.21z',
qrSize: 37,
qr: 'M0 0.5h7m2 0h1m3 0h1m1 0h1m2 0h1m1 0h3m1 0h2m4 0h7M0 1.5h1m5 0h1m4 0h1m2 0h1m2 0h3m5 0h4m1 0h1m5 0h1M0 2.5h1m1 0h3m1 0h1m1 0h2m2 0h5m2 0h4m1 0h1m1 0h1m3 0h1m1 0h3m1 0h1M0 3.5h1m1 0h3m1 0h1m1 0h2m1 0h1m1 0h1m2 0h5m1 0h1m2 0h2m3 0h1m1 0h3m1 0h1M0 4.5h1m1 0h3m1 0h1m1 0h2m3 0h1m4 0h3m1 0h2m1 0h1m2 0h1m1 0h1m1 0h3m1 0h1M0 5.5h1m5 0h1m1 0h6m4 0h1m3 0h1m2 0h4m1 0h1m5 0h1M0 6.5h7m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h7M8 7.5h1m1 0h4m2 0h1m6 0h1m4 0h1M0 8.5h1m1 0h5m2 0h1m3 0h3m2 0h1m1 0h7m3 0h5M0 9.5h5m5 0h1m4 0h3m3 0h1m4 0h1m1 0h1m2 0h1m3 0h1M0 10.5h3m1 0h4m1 0h3m1 0h1m3 0h1m2 0h9m1 0h1m2 0h1m1 0h2M2 11.5h2m3 0h1m5 0h1m2 0h1m4 0h1m1 0h1m2 0h3m1 0h4m2 0h1M1 12.5h1m1 0h1m2 0h1m3 0h1m1 0h2m2 0h2m2 0h1m1 0h6m1 0h4m1 0h3M0 13.5h1m6 0h1m1 0h3m1 0h1m2 0h6m1 0h2m3 0h1m2 0h1M2 14.5h1m3 0h2m1 0h1m1 0h5m1 0h1m3 0h1m4 0h3m2 0h3m1 0h2M2 15.5h2m3 0h1m1 0h1m2 0h7m2 0h2m5 0h5m2 0h2M1 16.5h1m2 0h3m3 0h2m1 0h2m1 0h1m4 0h1m1 0h1m1 0h3m1 0h2m1 0h1m1 0h1M2 17.5h1m2 0h1m2 0h2m1 0h2m2 0h1m2 0h1m1 0h1m1 0h1m1 0h3m1 0h1m2 0h1m2 0h2M1 18.5h1m4 0h1m3 0h2m2 0h3m2 0h1m2 0h1m3 0h2m1 0h1m2 0h1m2 0h2M1 19.5h3m4 0h5m2 0h1m2 0h5m1 0h1m5 0h3m3 0h1M0 20.5h1m1 0h1m1 0h1m1 0h2m2 0h1m4 0h1m1 0h1m1 0h2m1 0h1m1 0h4m1 0h2m1 0h3M1 21.5h1m6 0h2m1 0h1m1 0h2m1 0h1m1 0h3m1 0h2m4 0h1m4 0h1M2 22.5h1m1 0h5m1 0h1m2 0h4m1 0h1m1 0h1m1 0h1m2 0h1m1 0h1m3 0h3m1 0h2M0 23.5h1m2 0h1m1 0h1m5 0h2m2 0h1m7 0h1m4 0h2m1 0h2m2 0h1M1 24.5h2m3 0h1m3 0h4m4 0h1m1 0h7m1 0h3m1 0h1m1 0h2M0 25.5h4m1 0h1m2 0h4m3 0h2m4 0h1m6 0h1m4 0h1M0 26.5h1m2 0h1m1 0h2m3 0h1m1 0h3m5 0h1m2 0h2m1 0h2m2 0h2m2 0h3M0 27.5h1m1 0h3m3 0h2m6 0h1m4 0h1m1 0h1m2 0h7m2 0h1M0 28.5h1m1 0h1m1 0h1m1 0h1m1 0h2m1 0h2m1 0h1m2 0h1m4 0h4m1 0h9M8 29.5h6m2 0h2m1 0h3m1 0h1m3 0h2m3 0h2m1 0h1M0 30.5h7m2 0h1m5 0h3m2 0h2m4 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1M0 31.5h1m5 0h1m1 0h1m1 0h6m1 0h8m1 0h3m3 0h2m1 0h1M0 32.5h1m1 0h3m1 0h1m1 0h2m1 0h1m1 0h1m1 0h2m2 0h1m1 0h1m2 0h9m1 0h1m1 0h1M0 33.5h1m1 0h3m1 0h1m1 0h1m2 0h1m1 0h3m2 0h1m1 0h3m1 0h2m3 0h2m1 0h1m1 0h2M0 34.5h1m1 0h3m1 0h1m1 0h1m3 0h1m2 0h2m2 0h1m1 0h2m2 0h5m4 0h1m1 0h1M0 35.5h1m5 0h1m5 0h1m1 0h2m2 0h7m3 0h3m1 0h1m3 0h1M0 36.5h7m1 0h1m1 0h1m1 0h1m1 0h2m1 0h1m1 0h1m3 0h4m2 0h2m1 0h5',
},
] as const;
interface Props {
/** `dark` for a surface that stays dark in either theme, like the release modal. */
tone?: 'theme' | 'dark';
className?: string;
}
export default function AppStoreCards({ tone = 'theme', className }: Props): React.ReactElement {
const { t } = useTranslation();
return (
<div className={['asc-row', tone === 'dark' ? 'asc-dark' : '', className ?? ''].filter(Boolean).join(' ')}>
{APP_STORES.map((s) => (
<a key={s.id} className="asc-card" href={s.href} target="_blank" rel="noopener noreferrer">
<span className="asc-qr" aria-hidden="true">
<svg viewBox={`0 0 ${s.qrSize} ${s.qrSize}`} shapeRendering="crispEdges">
<path className="asc-qr-dots" d={s.qr} />
</svg>
</span>
<span className="asc-text">
<span className="asc-caption">
<svg className="asc-logo" viewBox="0 0 24 24" aria-hidden="true">
<path d={s.logo} />
</svg>
{t(s.captionKey)}
</span>
<span className="asc-store">{s.store}</span>
<span className="asc-devices">{t(s.devicesKey)}</span>
</span>
</a>
))}
</div>
);
}
@@ -0,0 +1,124 @@
/* The store cards: a QR code on its white tile, the store's mark and name beside it.
The theme tone follows the appearance tokens; .asc-dark is for a surface that is
dark in either theme (the release modal). */
.asc-row {
display: grid;
/* Always side by side: two compact cards read as one row of stores. */
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 10px;
}
.asc-card {
display: flex;
align-items: center;
gap: 10px;
min-width: 0;
padding: 8px 12px 8px 8px;
border-radius: 16px;
border: 1px solid var(--border-faint);
background: var(--bg-card);
color: var(--text-primary);
text-decoration: none;
transition:
transform 160ms ease,
border-color 160ms ease,
box-shadow 160ms ease;
}
.asc-card:hover {
transform: translateY(-1px);
border-color: var(--border-primary);
box-shadow: 0 10px 24px -14px rgb(0 0 0 / 0.35); /* a neutral lift shadow */
}
.asc-card:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
/* A QR code needs its light quiet zone in either theme to scan. */
.asc-qr {
flex: none;
display: grid;
place-items: center;
width: 56px;
height: 56px;
padding: 5px;
border-radius: 10px;
background: #ffffff; /* a QR code needs a white quiet zone to scan */
border: 1px solid var(--border-faint);
}
.asc-qr svg {
width: 100%;
height: 100%;
display: block;
}
.asc-qr-dots {
fill: none;
stroke: #0f172a;
} /* QR modules stay dark on their white tile */
.asc-text {
display: flex;
flex-direction: column;
min-width: 0;
line-height: 1.2;
}
.asc-caption {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: calc(10.5px * var(--fs-scale-caption, 1));
color: var(--text-muted);
white-space: nowrap;
}
.asc-logo {
width: 12px;
height: 12px;
flex: none;
fill: currentColor;
}
.asc-store {
margin-top: 2px;
font-size: calc(16px * var(--fs-scale-subtitle, 1));
font-weight: 700;
letter-spacing: -0.02em;
color: var(--text-primary);
white-space: nowrap;
}
.asc-devices {
margin-top: 2px;
font-size: calc(10.5px * var(--fs-scale-caption, 1));
color: var(--text-muted);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.asc-dark .asc-card {
background: linear-gradient(160deg, oklch(1 0 0 / 0.1) 0%, oklch(1 0 0 / 0.045) 62%);
border-color: oklch(1 0 0 / 0.13);
color: #f5f5f7; /* the release modal is dark in either theme */
box-shadow: inset 0 1px 0 oklch(1 0 0 / 0.16);
}
.asc-dark .asc-card:hover {
border-color: oklch(1 0 0 / 0.26);
}
.asc-dark .asc-qr {
border-color: transparent;
}
.asc-dark .asc-store {
color: #f5f5f7;
} /* the release modal is dark in either theme */
.asc-dark .asc-caption,
.asc-dark .asc-devices {
color: oklch(1 0 0 / 0.6);
}
@media (prefers-reduced-motion: reduce) {
.asc-card {
transition: none;
}
.asc-card:hover {
transform: none;
}
}
+73
View File
@@ -0,0 +1,73 @@
import { renderHook } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import { useWritesInOrder } from './useWritesInOrder';
/** A write that only finishes when the test says so, and notes when it starts and ends. */
function heldWrite(log: string[], name: string) {
let finish!: () => void;
let fail!: (err: Error) => void;
const done = new Promise<void>((resolve, reject) => {
finish = resolve;
fail = reject;
});
const write = async () => {
log.push(`${name} start`);
await done;
log.push(`${name} end`);
};
return { write, finish, fail };
}
describe('useWritesInOrder', () => {
it('FE-HOOK-WRITES-001: a write starts only once the one before it has finished', async () => {
const { result } = renderHook(() => useWritesInOrder());
const log: string[] = [];
const first = heldWrite(log, 'first');
const second = heldWrite(log, 'second');
const firstDone = result.current(first.write);
const secondDone = result.current(second.write);
await Promise.resolve();
expect(log).toEqual(['first start']);
second.finish();
first.finish();
await Promise.all([firstDone, secondDone]);
expect(log).toEqual(['first start', 'first end', 'second start', 'second end']);
});
it('FE-HOOK-WRITES-002: a failed write does not hold up the next one, and its caller sees the failure', async () => {
const { result } = renderHook(() => useWritesInOrder());
const log: string[] = [];
const first = heldWrite(log, 'first');
const second = heldWrite(log, 'second');
const firstDone = result.current(first.write);
const secondDone = result.current(second.write);
first.fail(new Error('offline'));
await expect(firstDone).rejects.toThrow('offline');
second.finish();
await secondDone;
expect(log).toEqual(['first start', 'second start', 'second end']);
});
it('FE-HOOK-WRITES-003: the order holds across renders of the component using it', async () => {
const { result, rerender } = renderHook(() => useWritesInOrder());
const log: string[] = [];
const first = heldWrite(log, 'first');
const second = heldWrite(log, 'second');
const firstDone = result.current(first.write);
rerender();
const secondDone = result.current(second.write);
await Promise.resolve();
expect(log).toEqual(['first start']);
first.finish();
second.finish();
await Promise.all([firstDone, secondDone]);
expect(log).toEqual(['first start', 'first end', 'second start', 'second end']);
});
});
+18
View File
@@ -0,0 +1,18 @@
import { useRef } from 'react';
/**
* Runs async writes one after another, in the order they were started.
*
* Two writes to the same record that leave close together, such as a field saved on
* blur and a reset clicked right after it, otherwise race: the server may handle them
* in either order, and whichever it handles last is what stays. A write that fails
* does not hold up the ones queued behind it.
*/
export function useWritesInOrder(): (write: () => Promise<void>) => Promise<void> {
const tail = useRef<Promise<void>>(Promise.resolve());
return (write) => {
const next = tail.current.then(write, write);
tail.current = next;
return next;
};
}
@@ -4,7 +4,7 @@ import type { LucideIcon } from 'lucide-react'
import { useContextMenu, ContextMenu } from '../../../../components/shared/ContextMenu' import { useContextMenu, ContextMenu } from '../../../../components/shared/ContextMenu'
import MarkdownText from '../../../../components/shared/MarkdownText' import MarkdownText from '../../../../components/shared/MarkdownText'
import { fmtTransitDuration } from '../../../../components/Planner/transitDisplay' import { fmtTransitDuration } from '../../../../components/Planner/transitDisplay'
import { legModeMenuItems } from '../../../../components/Planner/useLegModeActions' import { legModeMenuItems, transitOnlyMenuItems } from '../../../../components/Planner/useLegModeActions'
import { formatTime } from '../../../../utils/formatters' import { formatTime } from '../../../../utils/formatters'
import { useMPlanTimeline, type MPlanTimelineController } from './useMPlanTimeline' import { useMPlanTimeline, type MPlanTimelineController } from './useMPlanTimeline'
import { cityPillsForDay } from './planTimelineModel' import { cityPillsForDay } from './planTimelineModel'
@@ -114,16 +114,24 @@ function PlanDayPage({ planner, shell, dayId: pageDayId, active, editing, legMen
const { t, trip, can } = planner const { t, trip, can } = planner
const canEdit = can('day_edit', trip) const canEdit = can('day_edit', trip)
const canEditPlaces = can('place_edit', trip) const canEditPlaces = can('place_edit', trip)
const openLegMenu = (e: MouseEvent, assignmentId: number, seg: RouteSegment) => { // The tap on a leg while editing: the mode menu of the stop that owns it, its
// Public transit sits under the road profiles, as on the desktop (#2398). // outgoing mode for a leg it leaves, its incoming mode for one it enters from a
// booking or the morning hotel, as on the desktop. Public transit sits under the
// road profiles (#2398). A leg no stop owns, a booking's arrival to the hotel, can
// only have transit planned, and stays inert where that is not available.
const legTap = (seg: RouteSegment, owner: { id: number; incoming: boolean } | null): ((e: MouseEvent) => void) | undefined => {
if (!editing) return undefined
const transitLeg = tl.transitLegFor(seg) const transitLeg = tl.transitLegFor(seg)
legMenu.open(e, legModeMenuItems( const planTransit = transitLeg
tl.routeModeOptions, ? () => tl.planTransitLeg(transitLeg, owner && !owner.incoming ? owner.id : undefined)
mode => tl.setLegMode(assignmentId, mode), : undefined
t, if (owner) {
transitLeg ? () => tl.planTransitLeg(transitLeg, assignmentId) : undefined, const pick = (mode: string | null) => (owner.incoming ? tl.setIncomingLegMode(owner.id, mode) : tl.setLegMode(owner.id, mode))
)) return e => legMenu.open(e, legModeMenuItems(tl.routeModeOptions, pick, t, planTransit))
}
return planTransit ? e => legMenu.open(e, transitOnlyMenuItems(planTransit, t)) : undefined
} }
const owned = (id: number | undefined, incoming: boolean) => (id != null ? { id, incoming } : null)
const day = tl.day const day = tl.day
const dayId = day?.id const dayId = day?.id
// A stay chip shows the stay before anything can be changed, as on the // A stay chip shows the stay before anything can be changed, as on the
@@ -249,7 +257,12 @@ function PlanDayPage({ planner, shell, dayId: pageDayId, active, editing, legMen
)} )}
{tl.hotelLegs.top && ( {tl.hotelLegs.top && (
<HotelConnRow seg={tl.hotelLegs.top.seg} name={tl.hotelLegs.top.name} placement="top" /> <HotelConnRow
seg={tl.hotelLegs.top.seg}
name={tl.hotelLegs.top.name}
placement="top"
onTap={legTap(tl.hotelLegs.top.seg, owned(tl.hotelLegs.top.assignmentId, true))}
/>
)} )}
{dayId != null && daySchedule.byPosition[dayId]?.start.map(si => <PlanScheduleRow key={`${si.pluginId}:${si.id}`} item={si} />)} {dayId != null && daySchedule.byPosition[dayId]?.start.map(si => <PlanScheduleRow key={`${si.pluginId}:${si.id}`} item={si} />)}
@@ -321,13 +334,24 @@ function PlanDayPage({ planner, shell, dayId: pageDayId, active, editing, legMen
/> />
) )
case 'conn': case 'conn':
return <ConnRow key={row.key} seg={row.seg} onTap={editing && row.assignmentId != null ? e => openLegMenu(e, row.assignmentId!, row.seg) : undefined} /> return (
<ConnRow
key={row.key}
seg={row.seg}
onTap={legTap(row.seg, row.assignmentId != null ? owned(row.assignmentId, false) : owned(row.incomingAssignmentId, true))}
/>
)
} }
})} })}
{dayId != null && daySchedule.byPosition[dayId]?.end.map(si => <PlanScheduleRow key={`${si.pluginId}:${si.id}`} item={si} />)} {dayId != null && daySchedule.byPosition[dayId]?.end.map(si => <PlanScheduleRow key={`${si.pluginId}:${si.id}`} item={si} />)}
{tl.hotelLegs.bottom && ( {tl.hotelLegs.bottom && (
<HotelConnRow seg={tl.hotelLegs.bottom.seg} name={tl.hotelLegs.bottom.name} placement="bottom" /> <HotelConnRow
seg={tl.hotelLegs.bottom.seg}
name={tl.hotelLegs.bottom.name}
placement="bottom"
onTap={legTap(tl.hotelLegs.bottom.seg, owned(tl.hotelLegs.bottom.assignmentId, false))}
/>
)} )}
{tl.rows.length === 0 && !editing && ( {tl.rows.length === 0 && !editing && (
@@ -534,18 +534,19 @@ export function PlanScheduleRow({ item }: { item: PluginDayScheduleItem }) {
// ── b4b) Accommodation bookend leg (hotel → first stop / last stop → hotel) ── // ── b4b) Accommodation bookend leg (hotel → first stop / last stop → hotel) ──
export function HotelConnRow({ seg, name, placement }: { export function HotelConnRow({ seg, name, placement, onTap }: {
seg: RouteSegment seg: RouteSegment
name: string name: string
placement: 'top' | 'bottom' placement: 'top' | 'bottom'
onTap?: (e: MouseEvent) => void
}) { }) {
// Same line as the connectors between two stops, so a bookend leg routed with a // Same line as the connectors between two stops, so a bookend leg routed with a
// plugin profile or set to walking reads the same as the rest of the day (#1281). // plugin profile or set to walking reads the same as the rest of the day (#1281),
const travel = ( // and taps the same way. Only the line is the button, the stay's name stays text.
<div className="flex items-center gap-2 py-px text-[color:var(--m-conn)]"> const cls = 'flex w-full items-center gap-2 py-px text-[color:var(--m-conn)]'
<TravelLine seg={seg} /> const travel = onTap
</div> ? <button type="button" onClick={onTap} className={`${cls} transition-transform active:scale-[.98]`}><TravelLine seg={seg} /></button>
) : <div className={cls}><TravelLine seg={seg} /></div>
const hotel = ( const hotel = (
<div className="flex items-center justify-center gap-[5px] whitespace-nowrap font-geist text-[0.59375rem] font-semibold text-m-muted"> <div className="flex items-center justify-center gap-[5px] whitespace-nowrap font-geist text-[0.59375rem] font-semibold text-m-muted">
<BedDouble size={11} strokeWidth={2} className="flex-none" /> <BedDouble size={11} strokeWidth={2} className="flex-none" />
@@ -31,7 +31,12 @@ export type PlanRow =
| { key: string; kind: 'transport'; item: MergedItem; res: TransportEntry } | { key: string; kind: 'transport'; item: MergedItem; res: TransportEntry }
| { key: string; kind: 'transit'; item: MergedItem; res: TransportEntry; transit: TransitMeta } | { key: string; kind: 'transit'; item: MergedItem; res: TransportEntry; transit: TransitMeta }
| { key: string; kind: 'note'; item: MergedItem; note: DayNote } | { key: string; kind: 'note'; item: MergedItem; note: DayNote }
| { key: string; kind: 'conn'; seg: RouteSegment; assignmentId?: number } /**
* A leg between two rows. `assignmentId` is the stop it leaves, whose outgoing mode it
* uses; a leg that leaves a booking uses the incoming mode of the stop it enters,
* `incomingAssignmentId`, as on the desktop day plan.
*/
| { key: string; kind: 'conn'; seg: RouteSegment; assignmentId?: number; incomingAssignmentId?: number }
export function parseReservationMeta(res: Reservation): Record<string, unknown> { export function parseReservationMeta(res: Reservation): Record<string, unknown> {
let meta: unknown = res.metadata let meta: unknown = res.metadata
@@ -56,6 +61,26 @@ export function transportSubtitle(res: TransportEntry, t: TranslationFn): string
const sameCoord = (a: [number, number], b: [number, number]): boolean => const sameCoord = (a: [number, number], b: [number, number]): boolean =>
Math.abs(a[0] - b[0]) < 1e-9 && Math.abs(a[1] - b[1]) < 1e-9 Math.abs(a[0] - b[0]) < 1e-9 && Math.abs(a[1] - b[1]) < 1e-9
/**
* The stops whose mode the two hotel bookend legs use: the first waypoint of the
* day for the leg from the hotel (its incoming mode), the last for the leg back
* (its outgoing mode). Absent where that end of the day is a booking, which no
* stop owns.
*/
export interface BookendOwners {
top?: number
bottom?: number
}
type PlanRowsOptions = {
merged: MergedItem[]
reservations: Reservation[]
routeSegments: RouteSegment[]
dayId: number
toursEnabled?: boolean
places?: Place[]
}
/** /**
* Map the day's merged items to render rows and slot a travel-time connector * Map the day's merged items to render rows and slot a travel-time connector
* under the row each drawn leg belongs to. Segments are matched by their exact * under the row each drawn leg belongs to. Segments are matched by their exact
@@ -64,14 +89,12 @@ const sameCoord = (a: [number, number], b: [number, number]): boolean =>
* front: they belong to the day's edges, and a stop planned on the hotel's own * front: they belong to the day's edges, and a stop planned on the hotel's own
* spot would otherwise pair with them (#2501). * spot would otherwise pair with them (#2501).
*/ */
export function buildPlanRows(opts: { export function buildPlanRows(opts: PlanRowsOptions): PlanRow[] {
merged: MergedItem[] return buildPlanTimeline(opts).rows
reservations: Reservation[] }
routeSegments: RouteSegment[]
dayId: number /** buildPlanRows, plus the stops that own the day's two hotel bookend legs. */
toursEnabled?: boolean export function buildPlanTimeline(opts: PlanRowsOptions): { rows: PlanRow[]; bookendOwners: BookendOwners } {
places?: Place[]
}): PlanRow[] {
const { merged, reservations, routeSegments, dayId } = opts const { merged, reservations, routeSegments, dayId } = opts
const pool = routeSegments.filter(s => !s.hotelBookend) const pool = routeSegments.filter(s => !s.hotelBookend)
const projected = new Map(projectDayItinerary( const projected = new Map(projectDayItinerary(
@@ -133,15 +156,24 @@ export function buildPlanRows(opts: {
// A booking whose station is the stop itself leaves a leg that goes nowhere: the // A booking whose station is the stop itself leaves a leg that goes nowhere: the
// transit planner saves a journey between two of the day's places at their own // transit planner saves a journey between two of the day's places at their own
// coordinates. That is no walk and no drive, so it gets no connector. // coordinates. That is no walk and no drive, so it gets no connector.
//
// A leg out of a booking has no stop to keep its mode, so it uses the incoming mode
// of the stop it enters, `toAssignmentId`, the one the route calc routed it in.
type Origin = { at: [number, number]; row: number; assignmentId?: number } type Origin = { at: [number, number]; row: number; assignmentId?: number }
const legs = new Map<number, { seg: RouteSegment; assignmentId?: number }>() const legs = new Map<number, { seg: RouteSegment; assignmentId?: number; incomingAssignmentId?: number }>()
const connect = (origin: Origin | null, to: [number, number], toBooking = false) => { const connect = (origin: Origin | null, to: [number, number], toBooking = false, toAssignmentId?: number) => {
if (!origin) return if (!origin) return
const seg = takeSegment(origin.at, to) const seg = takeSegment(origin.at, to)
const fromBooking = origin.assignmentId == null const fromBooking = origin.assignmentId == null
if (!seg || ((toBooking || fromBooking) && sameCoord(origin.at, to))) return if (!seg || ((toBooking || fromBooking) && sameCoord(origin.at, to))) return
legs.set(origin.row, { seg, assignmentId: origin.assignmentId }) legs.set(origin.row, {
seg,
assignmentId: origin.assignmentId,
...(fromBooking && toAssignmentId != null ? { incomingAssignmentId: toAssignmentId } : {}),
})
} }
// The day's first waypoint, a stop or a booking's departure: the hotel leg runs into it.
let first: { assignmentId?: number } | null = null
let prev: Origin | null = null let prev: Origin | null = null
for (let i = 0; i < base.length; i++) { for (let i = 0; i < base.length; i++) {
const row = base[i] const row = base[i]
@@ -151,7 +183,10 @@ export function buildPlanRows(opts: {
if (row.assignment.route_excluded) continue if (row.assignment.route_excluded) continue
const itineraryItem = projected.get(row.assignment.id) const itineraryItem = projected.get(row.assignment.id)
if (itineraryItem?.kind === 'tour') { if (itineraryItem?.kind === 'tour') {
if (itineraryItem.start) connect(prev, [itineraryItem.start.lat, itineraryItem.start.lng]) if (itineraryItem.start) {
first ??= { assignmentId: row.assignment.id }
connect(prev, [itineraryItem.start.lat, itineraryItem.start.lng], false, row.assignment.id)
}
prev = itineraryItem.end prev = itineraryItem.end
? { at: [itineraryItem.end.lat, itineraryItem.end.lng], row: i, assignmentId: row.assignment.id } ? { at: [itineraryItem.end.lat, itineraryItem.end.lng], row: i, assignmentId: row.assignment.id }
: null : null
@@ -159,7 +194,8 @@ export function buildPlanRows(opts: {
} }
if (place?.lat == null || place?.lng == null) continue if (place?.lat == null || place?.lng == null) continue
const at: [number, number] = [place.lat, place.lng] const at: [number, number] = [place.lat, place.lng]
connect(prev, at) first ??= { assignmentId: row.assignment.id }
connect(prev, at, false, row.assignment.id)
// The leg's mode is stored on its ORIGIN place assignment (#1281), so carry // The leg's mode is stored on its ORIGIN place assignment (#1281), so carry
// that id for the tap-to-change menu. // that id for the tap-to-change menu.
prev = { at, row: i, assignmentId: row.assignment.id } prev = { at, row: i, assignmentId: row.assignment.id }
@@ -171,16 +207,23 @@ export function buildPlanRows(opts: {
if (prev) prev = { ...prev, row: i } if (prev) prev = { ...prev, row: i }
continue continue
} }
if (from) first ??= {}
// Only out of a stop: two bookings back to back are no drive (#1394). // Only out of a stop: two bookings back to back are no drive (#1394).
if (from && prev?.assignmentId != null) connect(prev, [from.lat, from.lng], true) if (from && prev?.assignmentId != null) connect(prev, [from.lat, from.lng], true)
prev = to ? { at: [to.lat, to.lng], row: i } : null prev = to ? { at: [to.lat, to.lng], row: i } : null
} }
} }
return base.flatMap((row, i): PlanRow[] => { const rows = base.flatMap((row, i): PlanRow[] => {
const leg = legs.get(i) const leg = legs.get(i)
return leg ? [row, { key: `conn-${row.key}`, kind: 'conn', seg: leg.seg, assignmentId: leg.assignmentId }] : [row] return leg ? [row, { key: `conn-${row.key}`, kind: 'conn', ...leg }] : [row]
}) })
// The last waypoint is where the day ends: a stop, or a booking's arrival (no owner).
const bookendOwners: BookendOwners = {
...(first?.assignmentId != null ? { top: first.assignmentId } : {}),
...(prev?.assignmentId != null ? { bottom: prev.assignmentId } : {}),
}
return { rows, bookendOwners }
} }
export interface HotelChip { export interface HotelChip {
@@ -218,7 +261,12 @@ export function hotelChipsForDay(day: Day, days: Day[], accommodations: Accommod
return chips.filter(c => c.name).sort((a, b) => rank[a.variant] - rank[b.variant]) return chips.filter(c => c.name).sort((a, b) => rank[a.variant] - rank[b.variant])
} }
export interface HotelLeg { seg: RouteSegment; name: string } export interface HotelLeg {
seg: RouteSegment
name: string
/** The stop whose mode the leg uses (see BookendOwners); absent when a booking ends it. */
assignmentId?: number
}
export interface HotelLegs { top: HotelLeg | null; bottom: HotelLeg | null } export interface HotelLegs { top: HotelLeg | null; bottom: HotelLeg | null }
/** /**
@@ -242,17 +290,19 @@ export function hotelLegsForDay(
days: Day[], days: Day[],
accommodations: Accommodation[], accommodations: Accommodation[],
routeSegments: RouteSegment[], routeSegments: RouteSegment[],
owners: BookendOwners = {},
): HotelLegs { ): HotelLegs {
const { morning, evening } = getDayBookendHotels(day, days, accommodations) const { morning, evening } = getDayBookendHotels(day, days, accommodations)
const legOf = (a: Accommodation | undefined, bookend: 'morning' | 'evening'): HotelLeg | null => { const legOf = (a: Accommodation | undefined, bookend: 'morning' | 'evening', owner?: number): HotelLeg | null => {
if (!a || a.place_lat == null || a.place_lng == null) return null if (!a || a.place_lat == null || a.place_lng == null) return null
const at: [number, number] = [a.place_lat, a.place_lng] const at: [number, number] = [a.place_lat, a.place_lng]
const seg = routeSegments.find(s => s.hotelBookend === bookend && sameCoord(bookend === 'morning' ? s.from : s.to, at)) const seg = routeSegments.find(s => s.hotelBookend === bookend && sameCoord(bookend === 'morning' ? s.from : s.to, at))
return seg ? { seg, name: accommodationName(a) } : null if (!seg) return null
return { seg, name: accommodationName(a), ...(owner != null ? { assignmentId: owner } : {}) }
} }
// A moving day without stops is one drive from one hotel to the next (#1297). The // A moving day without stops is one drive from one hotel to the next (#1297). The
// calc tags it as the morning leg, so it shows once, at the top (#2476). // calc tags it as the morning leg, so it shows once, at the top (#2476).
return { top: legOf(morning, 'morning'), bottom: legOf(evening, 'evening') } return { top: legOf(morning, 'morning', owners.top), bottom: legOf(evening, 'evening', owners.bottom) }
} }
/** The day headline as city pills — a "Tokyo → Kyoto" title becomes two pills with an arrow. */ /** The day headline as city pills — a "Tokyo → Kyoto" title becomes two pills with an arrow. */
@@ -14,8 +14,8 @@ import type { PlannedTransitLeg, TransitLeg } from '../../../../components/Plann
import { useTransitLegPlanner } from '../../../../components/Planner/useTransitLegPlanner' import { useTransitLegPlanner } from '../../../../components/Planner/useTransitLegPlanner'
import { dayItemOverrun } from '../../../../components/Tours/tourDayTime' import { dayItemOverrun } from '../../../../components/Tours/tourDayTime'
import { import {
buildPlanRows, breaksChronology, findUpNext, hotelChipsForDay, hotelLegsForDay, itemHasTime, buildPlanTimeline, breaksChronology, findUpNext, hotelChipsForDay, hotelLegsForDay, itemHasTime,
type HotelLegs, type PlanRow, type TransportEntry, type BookendOwners, type HotelLegs, type PlanRow, type TransportEntry,
} from './planTimelineModel' } from './planTimelineModel'
import type { TripPlanner } from '../MTripShell' import type { TripPlanner } from '../MTripShell'
import type { WeatherResult } from '@trek/shared' import type { WeatherResult } from '@trek/shared'
@@ -99,16 +99,17 @@ export function useMPlanTimeline(planner: TripPlanner, forDayId?: number | null)
tripAccommodations, tripAccommodations,
) )
const rows = useMemo<PlanRow[]>(() => { const timeline = useMemo<{ rows: PlanRow[]; bookendOwners: BookendOwners }>(() => {
if (!day) return [] if (!day) return { rows: [], bookendOwners: {} }
return buildPlanRows({ merged, reservations, routeSegments: connSegments, dayId: day.id, toursEnabled: planner.toursEnabled, places: planner.places }) return buildPlanTimeline({ merged, reservations, routeSegments: connSegments, dayId: day.id, toursEnabled: planner.toursEnabled, places: planner.places })
}, [day, merged, reservations, connSegments, planner.toursEnabled, planner.places]) }, [day, merged, reservations, connSegments, planner.toursEnabled, planner.places])
const rows = timeline.rows
// Accommodation bookend legs (hotel → first stop, last stop → hotel). The // Accommodation bookend legs (hotel → first stop, last stop → hotel). The
// segments already sit in connSegments; hotelLegsForDay picks the two out. // segments already sit in connSegments; hotelLegsForDay picks the two out.
const hotelLegs = useMemo<HotelLegs>( const hotelLegs = useMemo<HotelLegs>(
() => (day ? hotelLegsForDay(day, days, tripAccommodations, connSegments) : { top: null, bottom: null }), () => (day ? hotelLegsForDay(day, days, tripAccommodations, connSegments, timeline.bookendOwners) : { top: null, bottom: null }),
[day, days, tripAccommodations, connSegments], [day, days, tripAccommodations, connSegments, timeline.bookendOwners],
) )
const hotelChips = useMemo( const hotelChips = useMemo(
@@ -375,6 +376,17 @@ export function useMPlanTimeline(planner: TripPlanner, forDayId?: number | null)
persistLegMode(assignmentId, mode) persistLegMode(assignmentId, mode)
}, [day, persistLegMode]) }, [day, persistLegMode])
// The same for the leg entering a stop: from a booking's arrival or from the
// morning hotel, which no stop leaves (as on the desktop day plan).
const setIncomingLegMode = useCallback((assignmentId: number, mode: string | null) => {
if (!day) return
const key = String(day.id)
useTripStore.setState(state => ({
assignments: { ...state.assignments, [key]: (state.assignments[key] || []).map(a => (a.id === assignmentId ? { ...a, incoming_leg_transport_mode: mode } : a)) },
}))
persistLegMode(assignmentId, mode, 'incoming')
}, [day, persistLegMode])
// ── Public transit for one leg (#2398) ── // ── Public transit for one leg (#2398) ──
// The entry the desktop connector menu carries: the automated search, seeded with // The entry the desktop connector menu carries: the automated search, seeded with
// the leg's two ends and the time the stop it leaves is planned for, between two city // the leg's two ends and the time the stop it leaves is planned for, between two city
@@ -394,8 +406,9 @@ export function useMPlanTimeline(planner: TripPlanner, forDayId?: number | null)
toursEnabled: planner.toursEnabled, tourOf, onPlan: tripHasDates ? openTransitSearch : undefined, toursEnabled: planner.toursEnabled, tourOf, onPlan: tripHasDates ? openTransitSearch : undefined,
}) })
const transitLegFor = useCallback((seg: RouteSegment): TransitLeg | null => (day ? legFor(day.id, seg) : null), [day, legFor]) const transitLegFor = useCallback((seg: RouteSegment): TransitLeg | null => (day ? legFor(day.id, seg) : null), [day, legFor])
// `originId` is the stop the leg leaves, which tells two walks ending at one spot apart. // `originId` is the stop the leg leaves, which tells two walks ending at one spot apart;
const planTransitLeg = useCallback((leg: TransitLeg, originId: number) => { // a leg that leaves a booking or the hotel has none.
const planTransitLeg = useCallback((leg: TransitLeg, originId?: number) => {
if (day) plan(day.id, leg, originId) if (day) plan(day.id, leg, originId)
}, [day, plan]) }, [day, plan])
// A saved journey that now arrives after the walk it leads to starts (CW-08). // A saved journey that now arrives after the walk it leads to starts (CW-08).
@@ -414,7 +427,7 @@ export function useMPlanTimeline(planner: TripPlanner, forDayId?: number | null)
moveRowTo, moveRowTo,
addPlace, addBooking, addTransport, addPlace, addBooking, addTransport,
optimize, canExportRoute, routeTargets, exportGoogleMaps, exportCoMaps, renameDay, fullPlaceOf, optimize, canExportRoute, routeTargets, exportGoogleMaps, exportCoMaps, renameDay, fullPlaceOf,
routeModeOptions, setLegMode, transitLegFor, planTransitLeg, journeyLate, tourOverrun, routeModeOptions, setLegMode, setIncomingLegMode, transitLegFor, planTransitLeg, journeyLate, tourOverrun,
} }
} }
+4 -2
View File
@@ -1535,8 +1535,10 @@ describe('AdminPage', () => {
const matrixCard = matrixHeading.closest<HTMLElement>('section'); const matrixCard = matrixHeading.closest<HTMLElement>('section');
// The matrix switch is named after its event and channel; the card's first // The matrix switch is named after its event and channel; the card's first
// buttons belong to the webhook and ntfy targets above the matrix. // buttons belong to the webhook and ntfy targets above the matrix. The card's
fireEvent.click(within(matrixCard!).getByRole('button', { name: /, email$/i })); // heading renders before the matrix fetch lands (a loading row stands in until
// then), so wait for the switch itself.
fireEvent.click(await within(matrixCard!).findByRole('button', { name: /, email$/i }));
await waitFor(() => { await waitFor(() => {
expect(prefUpdateCalled).toBe(true); expect(prefUpdateCalled).toBe(true);
+6 -1
View File
@@ -276,7 +276,10 @@ describe('AtlasPage wiring', () => {
fireEvent.click(screen.getByText('atlas.unmark')); fireEvent.click(screen.getByText('atlas.unmark'));
await waitFor(() => expect(atlas.setConfirmAction).toHaveBeenLastCalledWith(null)); // The cancel above already closed with null, so wait for the unmark's own close:
// it comes only after the region delete and the country check have both answered.
await waitFor(() => expect(atlas.setConfirmAction).toHaveBeenCalledTimes(2));
expect(atlas.setConfirmAction).toHaveBeenLastCalledWith(null);
expect(atlas.visitedRegions).toEqual({}); expect(atlas.visitedRegions).toEqual({});
const data = atlas.data as AtlasData; const data = atlas.data as AtlasData;
expect(data.countries.map((c) => c.code)).toEqual(['FR']); expect(data.countries.map((c) => c.code)).toEqual(['FR']);
@@ -379,6 +382,8 @@ describe('AtlasPage wiring', () => {
fireEvent.click(screen.getByText('atlas.addToBucket')); fireEvent.click(screen.getByText('atlas.addToBucket'));
await waitFor(() => expect(body).toMatchObject({ name: 'Bretagne', country_code: 'FR', target_date: null })); await waitFor(() => expect(body).toMatchObject({ name: 'Bretagne', country_code: 'FR', target_date: null }));
// Let the post answer and the popup close here, not in the next test.
await waitFor(() => expect(atlas.setConfirmAction).toHaveBeenLastCalledWith(null));
}); });
it('FE-PAGE-ATLASW-018b: a country already wishlisted for that date is not posted again (#1898)', async () => { it('FE-PAGE-ATLASW-018b: a country already wishlisted for that date is not posted again (#1898)', async () => {
+9 -152
View File
@@ -5,7 +5,7 @@ import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw'; import { http, HttpResponse } from 'msw';
import { server } from '../../tests/helpers/msw/server'; import { server } from '../../tests/helpers/msw/server';
import { resetAllStores } from '../../tests/helpers/store'; import { resetAllStores } from '../../tests/helpers/store';
import { seedJourneyOwner } from '../../tests/helpers/journeyDetail'; import { journeyNow as now, mockJourneyDetail, seedJourneyOwner, setupJourneyHandlers as setupDefaultHandlers } from '../../tests/helpers/journeyDetail';
import { buildUser } from '../../tests/helpers/factories'; import { buildUser } from '../../tests/helpers/factories';
import { useJourneyStore } from '../store/journeyStore'; import { useJourneyStore } from '../store/journeyStore';
import JourneyDetailPage from './JourneyDetailPage'; import JourneyDetailPage from './JourneyDetailPage';
@@ -77,157 +77,6 @@ vi.mock('react-router', async () => {
}; };
}); });
// ── Mock Data ────────────────────────────────────────────────────────────────
const now = Date.now();
const mockJourneyDetail = {
id: 1,
user_id: 1,
title: 'Italy 2026',
subtitle: 'Rome, Florence, Venice',
status: 'active',
cover_image: null,
cover_gradient: null,
created_at: now,
updated_at: now,
entries: [
{
id: 10,
journey_id: 1,
author_id: 1,
type: 'entry',
entry_date: '2026-03-15',
title: 'Arrived in Rome',
story: 'Amazing city!',
location_name: 'Rome',
location_lat: 41.9,
location_lng: 12.5,
mood: 'amazing',
weather: 'sunny',
tags: ['culture'],
pros_cons: { pros: ['Great food'], cons: ['Crowded'] },
visibility: 'private',
sort_order: 0,
entry_time: '10:00',
photos: [
{
id: 100,
entry_id: 10,
photo_id: 100,
provider: 'local',
file_path: 'photos/test.jpg',
asset_id: null,
owner_id: null,
thumbnail_path: null,
caption: 'Colosseum',
sort_order: 0,
width: 800,
height: 600,
shared: 1,
created_at: now,
},
],
created_at: now,
updated_at: now,
},
{
id: 11,
journey_id: 1,
author_id: 1,
type: 'entry',
entry_date: '2026-03-16',
title: 'Florence Day',
story: null,
location_name: 'Florence',
location_lat: 43.77,
location_lng: 11.25,
mood: 'good',
weather: 'cloudy',
tags: [],
pros_cons: null,
visibility: 'private',
sort_order: 0,
entry_time: null,
photos: [],
created_at: now,
updated_at: now,
},
],
trips: [
{
trip_id: 5,
added_at: now,
title: 'Italy Trip',
start_date: '2026-03-14',
end_date: '2026-03-20',
cover_image: null,
currency: 'EUR',
place_count: 8,
},
],
contributors: [
{
journey_id: 1,
user_id: 1,
role: 'owner',
added_at: now,
username: 'testuser',
avatar: null,
},
],
stats: { entries: 2, photos: 1, places: 2 },
gallery: [
{
id: 100,
journey_id: 1,
photo_id: 100,
provider: 'local',
file_path: 'photos/test.jpg',
asset_id: null,
owner_id: null,
thumbnail_path: null,
caption: 'Colosseum',
sort_order: 0,
width: 800,
height: 600,
shared: 1,
created_at: now,
},
],
};
// ── MSW Handlers ─────────────────────────────────────────────────────────────
function setupDefaultHandlers(journeyOverride?: Record<string, unknown>) {
const journey = journeyOverride
? { ...mockJourneyDetail, ...journeyOverride }
: mockJourneyDetail;
server.use(
http.get('/api/journeys/1', () => {
return HttpResponse.json(journey);
}),
http.get('/api/addons', () => {
return HttpResponse.json({
addons: [
{ id: 'journey', name: 'Journey', type: 'feature', icon: 'book', enabled: true },
{ id: 'immich', name: 'Immich', type: 'photo_provider', icon: 'camera', enabled: true },
],
});
}),
http.get('/api/integrations/memories/:provider/status', () => {
return HttpResponse.json({ connected: false });
}),
http.patch('/api/journeys/1', () => {
return HttpResponse.json({ ...mockJourneyDetail, title: 'Updated' });
}),
http.get('/api/journeys/1/share-link', () => {
return HttpResponse.json({ link: null });
}),
);
}
// ── Setup ──────────────────────────────────────────────────────────────────── // ── Setup ────────────────────────────────────────────────────────────────────
const ownerUser = buildUser({ id: 1, username: 'testuser' }); const ownerUser = buildUser({ id: 1, username: 'testuser' });
@@ -3805,8 +3654,13 @@ describe('JourneyDetailPage', () => {
let createCalls = 0; let createCalls = 0;
let updateCalls = 0; let updateCalls = 0;
let providerCalls = 0; let providerCalls = 0;
let journeyReads = 0;
server.use( server.use(
http.get('/api/journeys/1', () => {
journeyReads++;
return HttpResponse.json(mockJourneyDetail);
}),
http.get('/api/integrations/memories/:provider/status', () => HttpResponse.json({ connected: true })), http.get('/api/integrations/memories/:provider/status', () => HttpResponse.json({ connected: true })),
http.post('/api/integrations/memories/:provider/search', () => HttpResponse.json({ http.post('/api/integrations/memories/:provider/search', () => HttpResponse.json({
assets: [{ id: 'context-1', takenAt: '2026-03-15T12:00:00Z', city: 'Rome' }], assets: [{ id: 'context-1', takenAt: '2026-03-15T12:00:00Z', city: 'Rome' }],
@@ -3851,10 +3705,13 @@ describe('JourneyDetailPage', () => {
expect(createCalls).toBe(1); expect(createCalls).toBe(1);
expect(screen.getByText('New Entry')).toBeInTheDocument(); expect(screen.getByText('New Entry')).toBeInTheDocument();
const readsBeforeRetry = journeyReads;
await user.click(screen.getByRole('button', { name: 'Save' })); await user.click(screen.getByRole('button', { name: 'Save' }));
await waitFor(() => expect(providerCalls).toBe(2)); await waitFor(() => expect(providerCalls).toBe(2));
expect(createCalls).toBe(1); expect(createCalls).toBe(1);
expect(updateCalls).toBe(1); expect(updateCalls).toBe(1);
// The photos landed and the journal reloads; let that read answer here, not after the test.
await waitFor(() => expect(journeyReads).toBeGreaterThan(readsBeforeRetry));
}); });
}); });
@@ -5,6 +5,7 @@ import React from 'react';
import { MemoryRouter } from 'react-router'; import { MemoryRouter } from 'react-router';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { buildAppConfig } from '../../../tests/helpers/factories'; import { buildAppConfig } from '../../../tests/helpers/factories';
import { locationAt, pageUrl } from '../../../tests/helpers/location';
import { server } from '../../../tests/helpers/msw/server'; import { server } from '../../../tests/helpers/msw/server';
import { act, renderHook, waitFor } from '../../../tests/helpers/render'; import { act, renderHook, waitFor } from '../../../tests/helpers/render';
import { resetAllStores } from '../../../tests/helpers/store'; import { resetAllStores } from '../../../tests/helpers/store';
@@ -54,7 +55,7 @@ beforeEach(() => {
Object.defineProperty(window, 'location', { Object.defineProperty(window, 'location', {
configurable: true, configurable: true,
writable: true, writable: true,
value: { ...realLocation, pathname: '/login', href: 'http://localhost/login', search: '' }, value: locationAt('/login'),
}); });
}); });
@@ -78,7 +79,7 @@ describe('useLogin in the native app', () => {
); );
const { result } = renderLogin(); const { result } = renderLogin();
await waitFor(() => expect(result.current.appConfig).not.toBeNull()); await waitFor(() => expect(result.current.appConfig).not.toBeNull());
expect(window.location.href).toBe('http://localhost/login'); expect(window.location.href).toBe(pageUrl('/login'));
expect(result.current.oidcOnly).toBe(true); expect(result.current.oidcOnly).toBe(true);
}); });
+17 -10
View File
@@ -7,6 +7,7 @@ import { http, HttpResponse } from 'msw';
import { server } from '../../../tests/helpers/msw/server'; import { server } from '../../../tests/helpers/msw/server';
import { resetAllStores } from '../../../tests/helpers/store'; import { resetAllStores } from '../../../tests/helpers/store';
import { buildAppConfig } from '../../../tests/helpers/factories'; import { buildAppConfig } from '../../../tests/helpers/factories';
import { locationAt, pageUrl } from '../../../tests/helpers/location';
import { markSignedOut, clearSignedOut, wasSignedOut } from '../../utils/signedOut'; import { markSignedOut, clearSignedOut, wasSignedOut } from '../../utils/signedOut';
import { TranslationProvider } from '../../i18n/TranslationContext'; import { TranslationProvider } from '../../i18n/TranslationContext';
import { useAuthStore, type LoginResult } from '../../store/authStore'; import { useAuthStore, type LoginResult } from '../../store/authStore';
@@ -54,7 +55,7 @@ function setSearch(search: string) {
Object.defineProperty(window, 'location', { Object.defineProperty(window, 'location', {
configurable: true, configurable: true,
writable: true, writable: true,
value: { ...realLocation, pathname: '/login', href: 'http://localhost/login', search }, value: locationAt(`/login${search}`),
}); });
} }
@@ -196,7 +197,7 @@ describe('useLogin — app config probe', () => {
await ready(result); await ready(result);
expect(result.current.noRedirect).toBe(true); expect(result.current.noRedirect).toBe(true);
expect(window.location.href).toBe('http://localhost/login'); expect(window.location.href).toBe(pageUrl('/login'));
}); });
it('FE-LOGIN-HOOK-009: never auto-redirects on a cached config', async () => { it('FE-LOGIN-HOOK-009: never auto-redirects on a cached config', async () => {
@@ -210,7 +211,7 @@ describe('useLogin — app config probe', () => {
await ready(result); await ready(result);
expect(result.current.oidcOnly).toBe(true); expect(result.current.oidcOnly).toBe(true);
expect(window.location.href).toBe('http://localhost/login'); expect(window.location.href).toBe(pageUrl('/login'));
}); });
}); });
@@ -1183,13 +1184,13 @@ describe('useLogin — the wait before the sign-in is known (#1167)', () => {
await waitFor(() => expect(result.current.redirectScreen).toBe(false)); await waitFor(() => expect(result.current.redirectScreen).toBe(false));
expect(result.current.configWait).toBe(false); expect(result.current.configWait).toBe(false);
expect(result.current.oidcOnly).toBe(true); expect(result.current.oidcOnly).toBe(true);
expect(window.location.href).toBe('http://localhost/login'); expect(window.location.href).toBe(pageUrl('/login'));
}); });
it('FE-LOGIN-HOOK-208: a redirect that stalls offers the way on by hand after eight seconds', () => { it('FE-LOGIN-HOOK-208: a redirect that stalls offers the way on by hand after eight seconds', async () => {
vi.useFakeTimers(); vi.useFakeTimers();
localStorage.setItem(CONFIG_CACHE_KEY, JSON.stringify(oidcOnlyConfig())); localStorage.setItem(CONFIG_CACHE_KEY, JSON.stringify(oidcOnlyConfig()));
heldConfig(oidcOnlyConfig()); const release = heldConfig(oidcOnlyConfig());
const { result } = renderLogin(); const { result } = renderLogin();
expect(result.current.redirectScreen).toBe(true); expect(result.current.redirectScreen).toBe(true);
@@ -1197,6 +1198,12 @@ describe('useLogin — the wait before the sign-in is known (#1167)', () => {
expect(result.current.idpSlow).toBe(false); expect(result.current.idpSlow).toBe(false);
act(() => { vi.advanceTimersByTime(1); }); act(() => { vi.advanceTimersByTime(1); });
expect(result.current.idpSlow).toBe(true); expect(result.current.idpSlow).toBe(true);
// The probe answers in the end and the redirect goes ahead, here and not in
// the next test.
vi.useRealTimers();
release();
await waitFor(() => expect(window.location.href).toBe('/api/auth/oidc/login?remember=1'));
}); });
it('FE-LOGIN-HOOK-209: a failed sign-in at the IdP shows the OIDC-only screen and its error, without going back', async () => { it('FE-LOGIN-HOOK-209: a failed sign-in at the IdP shows the OIDC-only screen and its error, without going back', async () => {
@@ -1209,7 +1216,7 @@ describe('useLogin — the wait before the sign-in is known (#1167)', () => {
expect(result.current.configWait).toBe(false); expect(result.current.configWait).toBe(false);
expect(result.current.redirectScreen).toBe(false); expect(result.current.redirectScreen).toBe(false);
expect(result.current.error).not.toBe(''); expect(result.current.error).not.toBe('');
expect(window.location.href).toBe('http://localhost/login'); expect(window.location.href).toBe(pageUrl('/login?oidc_error=token_failed'));
}); });
it('FE-LOGIN-HOOK-215: with the auto redirect turned off the page stays, with its SSO button (#2925)', async () => { it('FE-LOGIN-HOOK-215: with the auto redirect turned off the page stays, with its SSO button (#2925)', async () => {
@@ -1222,7 +1229,7 @@ describe('useLogin — the wait before the sign-in is known (#1167)', () => {
expect(result.current.oidcOnly).toBe(true); expect(result.current.oidcOnly).toBe(true);
expect(result.current.redirectScreen).toBe(false); expect(result.current.redirectScreen).toBe(false);
expect(result.current.configWait).toBe(false); expect(result.current.configWait).toBe(false);
expect(window.location.href).toBe('http://localhost/login'); expect(window.location.href).toBe(pageUrl('/login'));
}); });
it('FE-LOGIN-HOOK-216: a cached config with the auto redirect off announces no redirect while the probe is out', async () => { it('FE-LOGIN-HOOK-216: a cached config with the auto redirect off announces no redirect while the probe is out', async () => {
@@ -1237,7 +1244,7 @@ describe('useLogin — the wait before the sign-in is known (#1167)', () => {
release(); release();
await ready(result); await ready(result);
expect(result.current.redirectScreen).toBe(false); expect(result.current.redirectScreen).toBe(false);
expect(window.location.href).toBe('http://localhost/login'); expect(window.location.href).toBe(pageUrl('/login'));
}); });
it('FE-LOGIN-HOOK-217: a server from before the switch, with no field, keeps the redirect', async () => { it('FE-LOGIN-HOOK-217: a server from before the switch, with no field, keeps the redirect', async () => {
@@ -1259,6 +1266,6 @@ describe('useLogin — the wait before the sign-in is known (#1167)', () => {
release(); release();
await ready(result); await ready(result);
expect(window.location.href).toBe('http://localhost/login'); expect(window.location.href).toBe(pageUrl('/login'));
}); });
}); });
@@ -1,7 +1,8 @@
// FE-NATIVE-HANDOFF-001 to FE-NATIVE-HANDOFF-011 // FE-NATIVE-HANDOFF-001 to FE-NATIVE-HANDOFF-012
import React from 'react'; import React from 'react';
import { MemoryRouter } from 'react-router'; import { MemoryRouter } from 'react-router';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { locationAt } from '../../../tests/helpers/location';
import { act, renderHook, waitFor } from '../../../tests/helpers/render'; import { act, renderHook, waitFor } from '../../../tests/helpers/render';
import { resetAllStores } from '../../../tests/helpers/store'; import { resetAllStores } from '../../../tests/helpers/store';
import { rememberHandoffReturn, requestHandoffCode, signInWithPasskey } from '../../native/browserSignIn'; import { rememberHandoffReturn, requestHandoffCode, signInWithPasskey } from '../../native/browserSignIn';
@@ -28,7 +29,7 @@ function setSearch(search: string) {
Object.defineProperty(window, 'location', { Object.defineProperty(window, 'location', {
configurable: true, configurable: true,
writable: true, writable: true,
value: { ...realLocation, search, href: 'http://localhost/native-handoff' + search, replace: vi.fn() }, value: locationAt(`/native-handoff${search}`, { replace: vi.fn() }),
}); });
} }
@@ -93,6 +94,16 @@ describe('useNativeHandoff', () => {
expect(rememberHandoffReturn).toHaveBeenCalledWith(`/native-handoff?challenge=${challenge}`); expect(rememberHandoffReturn).toHaveBeenCalledWith(`/native-handoff?challenge=${challenge}`);
}); });
it('FE-NATIVE-HANDOFF-012: goes through the identity provider for SSO even when this browser is still signed in', () => {
// A session left from an earlier sign-in skipped the provider, and with it the
// re-authentication it demands (#3014).
setSearch(`?challenge=${challenge}&start=oidc`);
const { result } = renderHandoff();
expect(window.location.replace).toHaveBeenCalledWith('/api/auth/oidc/login?remember=1');
expect(result.current.ready).toBe(false);
expect(mockNavigate).not.toHaveBeenCalled();
});
it('FE-NATIVE-HANDOFF-005: waits while the session is still being checked', () => { it('FE-NATIVE-HANDOFF-005: waits while the session is still being checked', () => {
useAuthStore.setState({ isAuthenticated: false, isLoading: true }); useAuthStore.setState({ isAuthenticated: false, isLoading: true });
const { result } = renderHandoff(); const { result } = renderHandoff();
@@ -35,17 +35,22 @@ export function useNativeHandoff() {
// Back here once signed in, without `start`, so an SSO round trip cannot loop. // Back here once signed in, without `start`, so an SSO round trip cannot loop.
const returnPath = `${HANDOFF_PATH}?challenge=${challenge}`; const returnPath = `${HANDOFF_PATH}?challenge=${challenge}`;
// The app's SSO button always goes through the identity provider, even when this
// browser still holds a TREK session from an earlier sign-in. That session would
// otherwise skip the provider, and with it a re-authentication it demands.
const startOidc = valid && params.get('start') === 'oidc';
useEffect(() => { useEffect(() => {
if (!valid || isLoading || isAuthenticated || passkeyStep) return; if (!valid || isLoading || passkeyStep) return;
if (params.get('start') === 'oidc') { if (startOidc) {
sessionStorage.setItem('oidc_redirect', returnPath); sessionStorage.setItem('oidc_redirect', returnPath);
rememberHandoffReturn(returnPath); rememberHandoffReturn(returnPath);
window.location.replace('/api/auth/oidc/login?remember=1'); window.location.replace('/api/auth/oidc/login?remember=1');
return; return;
} }
if (isAuthenticated) return;
void navigate(`/login?redirect=${encodeURIComponent(returnPath)}`, { replace: true }); void navigate(`/login?redirect=${encodeURIComponent(returnPath)}`, { replace: true });
}, [valid, isLoading, isAuthenticated, passkeyStep, params, returnPath, navigate]); }, [valid, isLoading, isAuthenticated, passkeyStep, startOidc, returnPath, navigate]);
const openApp = async (): Promise<void> => { const openApp = async (): Promise<void> => {
setStatus('sending'); setStatus('sending');
@@ -90,7 +95,7 @@ export function useNativeHandoff() {
passkeyStep: valid && !isLoading && !isAuthenticated && passkeyStep, passkeyStep: valid && !isLoading && !isAuthenticated && passkeyStep,
continueWithPasskey, continueWithPasskey,
otherSignIn, otherSignIn,
ready: valid && !isLoading && isAuthenticated, ready: valid && !isLoading && isAuthenticated && !startOidc,
userName, userName,
status, status,
openApp, openApp,
+3 -3
View File
@@ -23,11 +23,11 @@ async function prune(): Promise<void> {
* anything this store cannot read or write is simply routed again. * anything this store cannot read or write is simply routed again.
*/ */
export const routeCacheRepo = { export const routeCacheRepo = {
/** The route kept under `key`, unless it is missing or too old. */ /** The route kept under `key`, unless it is missing or older than `maxAgeMs`. */
async get<T>(key: string): Promise<T | null> { async get<T>(key: string, maxAgeMs = MAX_AGE_MS): Promise<T | null> {
try { try {
const row = await offlineDb.routeCache.get(key); const row = await offlineDb.routeCache.get(key);
if (!row || Date.now() - row.savedAt > MAX_AGE_MS) return null; if (!row || Date.now() - row.savedAt > maxAgeMs) return null;
return row.route as T; return row.route as T;
} catch { } catch {
// A closed or blocked database: the leg is routed again. // A closed or blocked database: the leg is routed again.
+7
View File
@@ -160,6 +160,13 @@ describe('helpStore: search', () => {
}) })
describe('helpStore: doc index', () => { describe('helpStore: doc index', () => {
// Loading the index has no debounce, so these tests await the response directly.
// msw no longer runs its own timers outside fake ones, and a successful mocked
// response only arrives once a timer fires, so these tests run on real timers.
beforeEach(() => {
vi.useRealTimers()
})
it('loads the table of contents once and resolves titles from it', async () => { it('loads the table of contents once and resolves titles from it', async () => {
let calls = 0 let calls = 0
server.use( server.use(
+9 -7
View File
@@ -1,4 +1,5 @@
import { isChunkLoadError, reloadOnceForChunk, clearChunkReloadMarker, reloadFresh, importChunk, FRESH_LOAD_PARAM } from './chunkReload'; import { isChunkLoadError, reloadOnceForChunk, clearChunkReloadMarker, reloadFresh, importChunk, FRESH_LOAD_PARAM } from './chunkReload';
import { locationAt, pageUrl } from '../../tests/helpers/location';
const net = vi.hoisted(() => ({ const net = vi.hoisted(() => ({
probeNow: vi.fn(async () => 'online' as 'online' | 'offline' | 'proxy-wall'), probeNow: vi.fn(async () => 'online' as 'online' | 'offline' | 'proxy-wall'),
@@ -38,11 +39,11 @@ describe('isChunkLoadError', () => {
* A recovery reload is a location.replace onto a fresh URL (reloadFresh), so the * A recovery reload is a location.replace onto a fresh URL (reloadFresh), so the
* stub records the replace. `plain` is the location.reload() it must not use. * stub records the replace. `plain` is the location.reload() it must not use.
*/ */
function stubLocation(href = 'http://localhost/trips/4?tab=plan#day-2') { function stubLocation(path = '/trips/4?tab=plan#day-2', overrides: Partial<Location> = {}) {
const reload = vi.fn(); const reload = vi.fn();
const plain = vi.fn(); const plain = vi.fn();
Object.defineProperty(window, 'location', { Object.defineProperty(window, 'location', {
value: { ...window.location, href, replace: reload, reload: plain }, value: locationAt(path, { replace: reload, reload: plain, ...overrides }),
writable: true, writable: true,
}); });
return { reload, plain }; return { reload, plain };
@@ -56,7 +57,8 @@ describe('reloadFresh', () => {
expect(plain).not.toHaveBeenCalled(); expect(plain).not.toHaveBeenCalled();
expect(reload).toHaveBeenCalledTimes(1); expect(reload).toHaveBeenCalledTimes(1);
const target = new URL(reload.mock.calls[0][0] as string); const target = new URL(reload.mock.calls[0][0] as string);
// Path, query and hash stay, so the app comes back where it was. // Origin, path, query and hash stay, so the app comes back where it was.
expect(target.origin).toBe(new URL(pageUrl('/')).origin);
expect(target.pathname).toBe('/trips/4'); expect(target.pathname).toBe('/trips/4');
expect(target.searchParams.get('tab')).toBe('plan'); expect(target.searchParams.get('tab')).toBe('plan');
expect(target.hash).toBe('#day-2'); expect(target.hash).toBe('#day-2');
@@ -64,7 +66,7 @@ describe('reloadFresh', () => {
}); });
it('FE-UTIL-CHUNK-016: two reloads never share a URL', () => { it('FE-UTIL-CHUNK-016: two reloads never share a URL', () => {
const { reload } = stubLocation('http://localhost/dashboard'); const { reload } = stubLocation('/dashboard');
const now = vi.spyOn(Date, 'now').mockReturnValue(1790358416100); const now = vi.spyOn(Date, 'now').mockReturnValue(1790358416100);
reloadFresh(); reloadFresh();
now.mockReturnValue(1790358416101); now.mockReturnValue(1790358416101);
@@ -73,7 +75,7 @@ describe('reloadFresh', () => {
}); });
it('FE-UTIL-CHUNK-017: falls back to a plain reload when the URL cannot be built', () => { it('FE-UTIL-CHUNK-017: falls back to a plain reload when the URL cannot be built', () => {
const { reload, plain } = stubLocation('not a url'); const { reload, plain } = stubLocation('/', { href: 'not a url' });
reloadFresh(); reloadFresh();
expect(reload).not.toHaveBeenCalled(); expect(reload).not.toHaveBeenCalled();
expect(plain).toHaveBeenCalledTimes(1); expect(plain).toHaveBeenCalledTimes(1);
@@ -145,7 +147,7 @@ describe('reloadOntoCurrentBuild', () => {
const deleted: string[] = []; const deleted: string[] = [];
Object.defineProperty(globalThis, 'caches', { Object.defineProperty(globalThis, 'caches', {
value: { value: {
keys: vi.fn(async () => ['workbox-precache-v2-http://localhost/', 'map-tiles']), keys: vi.fn(async () => [`workbox-precache-v2-${pageUrl('/')}`, 'map-tiles']),
delete: vi.fn(async (name: string) => { deleted.push(name); return true; }), delete: vi.fn(async (name: string) => { deleted.push(name); return true; }),
}, },
configurable: true, configurable: true,
@@ -191,7 +193,7 @@ describe('reloadOntoCurrentBuild', () => {
// Not before the shell is gone: the reload would come back to the same error. // Not before the shell is gone: the reload would come back to the same error.
expect(reload).not.toHaveBeenCalled(); expect(reload).not.toHaveBeenCalled();
await vi.waitFor(() => expect(reload).toHaveBeenCalledTimes(1)); await vi.waitFor(() => expect(reload).toHaveBeenCalledTimes(1));
expect(deleted).toEqual(['workbox-precache-v2-http://localhost/']); expect(deleted).toEqual([`workbox-precache-v2-${pageUrl('/')}`]);
expect(registration.unregister).toHaveBeenCalledTimes(1); expect(registration.unregister).toHaveBeenCalledTimes(1);
}); });
+60 -15
View File
@@ -39,13 +39,51 @@ function triggerAnchorDownload(blobUrl: string, filename?: string): void {
setTimeout(() => { URL.revokeObjectURL(blobUrl); a.remove() }, 100) setTimeout(() => { URL.revokeObjectURL(blobUrl); a.remove() }, 100)
} }
// How long a live download may take before a copy stored for offline use is
// served instead. Without a stored copy the live download keeps going as long
// as it takes, since there is nothing better to show.
const STORED_COPY_WAIT_MS = 5000
// A network failure (the request or the body read rejected) serves the stored
// copy when there is one. After our own abort the stored copy is already being
// served, so the error only has to end this read.
async function storedCopyOr(url: string, err: unknown, signal: AbortSignal): Promise<Blob> {
if (signal.aborted) throw err
const cached = await getCachedBlob(url)
if (cached) return cached
throw err
}
async function readLive(url: string, signal: AbortSignal): Promise<Blob> {
let resp: Response
try {
resp = await fetch(url, { credentials: 'include', signal })
} catch (err) {
// Genuine network failure: the fetch itself rejected (offline, or a flaky
// link even though navigator.onLine is true). Serve the pre-downloaded copy.
return storedCopyOr(url, err, signal)
}
// The server answered: a non-ok status (401/403/404/…) is a real error and must
// surface, not be masked by a stale cached copy.
if (!resp.ok) throw new Error(resp.status === 401 ? 'Unauthorized' : `HTTP ${resp.status}`)
try {
return await resp.blob()
} catch (err) {
// The connection broke while the body was still arriving.
return storedCopyOr(url, err, signal)
}
}
/** /**
* Resolves a protected file to a Blob, preferring the live server but falling * Resolves a protected file to a Blob, preferring the live server but falling
* back to the offline cache (pre-downloaded by the trip sync manager). This is * back to the offline cache (pre-downloaded by the trip sync manager). This is
* what lets attachments open in a PWA / airplane mode. When offline we go * what lets attachments open in a PWA / airplane mode. When offline we go
* straight to the cache; when online we fetch live and only fall back if the * straight to the cache; when online we fetch live and fall back if the
* network actually fails — which also covers flaky links where navigator.onLine * network fails, which also covers flaky links where navigator.onLine still
* still reports true ("sometimes it works, sometimes it doesn't"). * reports true ("sometimes it works, sometimes it doesn't"). A stalled link
* never rejects, so once the live download has run for STORED_COPY_WAIT_MS the
* stored copy, if there is one, is served and the download aborted. The cache
* is only read then, so a quick HTTP error still surfaces on its own.
*/ */
async function getFileBlob(url: string): Promise<Blob> { async function getFileBlob(url: string): Promise<Blob> {
assertRelativeUrl(url) assertRelativeUrl(url)
@@ -54,20 +92,27 @@ async function getFileBlob(url: string): Promise<Blob> {
if (cached) return cached if (cached) return cached
throw new Error('File not available offline') throw new Error('File not available offline')
} }
let resp: Response // A controller and a timer rather than AbortSignal.timeout, which Safari only
// has from 16 on.
const live = new AbortController()
let settled = false
let timer: ReturnType<typeof setTimeout> | undefined
const storedAfterWait = new Promise<Blob>((resolve) => {
timer = setTimeout(() => {
void getCachedBlob(url).then((cached) => {
// Nothing stored: keep waiting on the live download, as before.
if (!cached || settled) return
resolve(cached)
live.abort()
})
}, STORED_COPY_WAIT_MS)
})
try { try {
resp = await fetch(url, { credentials: 'include' }) return await Promise.race([readLive(url, live.signal), storedAfterWait])
} catch (err) { } finally {
// Genuine network failure — the fetch itself rejected (offline, or a flaky settled = true
// link even though navigator.onLine is true). Serve the pre-downloaded copy. clearTimeout(timer)
const cached = await getCachedBlob(url)
if (cached) return cached
throw err
} }
// The server answered: a non-ok status (401/403/404/…) is a real error and must
// surface, not be masked by a stale cached copy.
if (!resp.ok) throw new Error(resp.status === 401 ? 'Unauthorized' : `HTTP ${resp.status}`)
return await resp.blob()
} }
/** /**
+7 -6
View File
@@ -1,4 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest'
import { locationAt } from '../../tests/helpers/location'
/* /*
* reconcileAppVersion notes the worker that served the page when its module * reconcileAppVersion notes the worker that served the page when its module
@@ -75,17 +76,17 @@ function breakStorage(method: 'getItem' | 'setItem', broken: () => Storage) {
const marker = () => localStorage.getItem('trek_app_version') const marker = () => localStorage.getItem('trek_app_version')
// The version the bundle under test is built as (vite define, from package.json). // The version the bundle under test is built as (vite define, from package.json).
const BUILT = __TREK_UI_VERSION__ const BUILT = __TREK_UI_VERSION__
let reload: ReturnType<typeof vi.fn> let reload: Mock<Location['replace']>
let plainReload: ReturnType<typeof vi.fn> let plainReload: Mock<Location['reload']>
beforeEach(() => { beforeEach(() => {
// Every reload here asks for the page under a fresh URL (reloadFresh), which is // Every reload here asks for the page under a fresh URL (reloadFresh), which is
// a location.replace. `plainReload` is the location.reload() it must not use. // a location.replace. `plainReload` is the location.reload() it must not use.
reload = vi.fn() reload = vi.fn<Location['replace']>()
plainReload = vi.fn() plainReload = vi.fn<Location['reload']>()
Object.defineProperty(window, 'location', { Object.defineProperty(window, 'location', {
writable: true, writable: true,
value: { ...window.location, href: 'http://localhost/dashboard', replace: reload, reload: plainReload }, value: locationAt('/dashboard', { replace: reload, reload: plainReload }),
}) })
}) })
+44
View File
@@ -0,0 +1,44 @@
import { http, HttpResponse } from 'msw';
import { vi } from 'vitest';
import { useAuthStore } from '../../src/store/authStore';
import { useSettingsStore } from '../../src/store/settingsStore';
import { useTripStore } from '../../src/store/tripStore';
import type { Settings } from '../../src/types';
import { buildAdmin, buildDay, buildTrip } from './factories';
import { server } from './msw/server';
import { resetAllStores, seedStore } from './store';
/** The day the day panel suites open. */
export const dayDetailDay = buildDay({ id: 1, trip_id: 1, date: '2025-06-15', title: 'Day in Paris' });
/** The panel's props for that day, with nothing planned on it. */
export const dayDetailProps = {
day: dayDetailDay,
days: [dayDetailDay],
places: [],
categories: [],
tripId: 1,
assignments: {},
reservations: [],
lat: null,
lng: null,
onClose: vi.fn(),
onAccommodationChange: vi.fn(),
};
/**
* Fresh stores for each day panel test: an admin on trip 1, the forecast and the stays
* answering empty, and the given settings when the suite wants them before rendering.
*/
export function resetDayDetailPanel(settings?: Partial<Settings>): void {
resetAllStores();
vi.clearAllMocks();
server.use(
http.get('/api/weather/detailed', () => HttpResponse.json({ error: true })),
http.get('/api/trips/1/accommodations', () => HttpResponse.json({ accommodations: [] }))
);
seedStore(useAuthStore, { user: buildAdmin(), isAuthenticated: true });
seedStore(useTripStore, { trip: buildTrip({ id: 1 }) });
if (settings) seedStore(useSettingsStore, { settings });
}
+150
View File
@@ -1,7 +1,9 @@
import { http, HttpResponse } from 'msw';
import { useAddonStore } from '../../src/store/addonStore'; import { useAddonStore } from '../../src/store/addonStore';
import { useAuthStore } from '../../src/store/authStore'; import { useAuthStore } from '../../src/store/authStore';
import { usePermissionsStore } from '../../src/store/permissionsStore'; import { usePermissionsStore } from '../../src/store/permissionsStore';
import type { User } from '../../src/types'; import type { User } from '../../src/types';
import { server } from './msw/server';
import { seedStore } from './store'; import { seedStore } from './store';
/** /**
@@ -15,3 +17,151 @@ export function seedJourneyOwner(user: User): void {
addons: [{ id: 'immich', name: 'Immich', type: 'photo_provider', enabled: true } as never], addons: [{ id: 'immich', name: 'Immich', type: 'photo_provider', enabled: true } as never],
}); });
} }
/** When the suite's journal was made; its entries and photos are dated by it. */
export const journeyNow = Date.now();
/** The journal the page suite opens: an owner's active trip journal with entries, photos and a synced trip. */
export const mockJourneyDetail = {
id: 1,
user_id: 1,
title: 'Italy 2026',
subtitle: 'Rome, Florence, Venice',
status: 'active',
cover_image: null,
cover_gradient: null,
created_at: journeyNow,
updated_at: journeyNow,
entries: [
{
id: 10,
journey_id: 1,
author_id: 1,
type: 'entry',
entry_date: '2026-03-15',
title: 'Arrived in Rome',
story: 'Amazing city!',
location_name: 'Rome',
location_lat: 41.9,
location_lng: 12.5,
mood: 'amazing',
weather: 'sunny',
tags: ['culture'],
pros_cons: { pros: ['Great food'], cons: ['Crowded'] },
visibility: 'private',
sort_order: 0,
entry_time: '10:00',
photos: [
{
id: 100,
entry_id: 10,
photo_id: 100,
provider: 'local',
file_path: 'photos/test.jpg',
asset_id: null,
owner_id: null,
thumbnail_path: null,
caption: 'Colosseum',
sort_order: 0,
width: 800,
height: 600,
shared: 1,
created_at: journeyNow,
},
],
created_at: journeyNow,
updated_at: journeyNow,
},
{
id: 11,
journey_id: 1,
author_id: 1,
type: 'entry',
entry_date: '2026-03-16',
title: 'Florence Day',
story: null,
location_name: 'Florence',
location_lat: 43.77,
location_lng: 11.25,
mood: 'good',
weather: 'cloudy',
tags: [],
pros_cons: null,
visibility: 'private',
sort_order: 0,
entry_time: null,
photos: [],
created_at: journeyNow,
updated_at: journeyNow,
},
],
trips: [
{
trip_id: 5,
added_at: journeyNow,
title: 'Italy Trip',
start_date: '2026-03-14',
end_date: '2026-03-20',
cover_image: null,
currency: 'EUR',
place_count: 8,
},
],
contributors: [
{
journey_id: 1,
user_id: 1,
role: 'owner',
added_at: journeyNow,
username: 'testuser',
avatar: null,
},
],
stats: { entries: 2, photos: 1, places: 2 },
gallery: [
{
id: 100,
journey_id: 1,
photo_id: 100,
provider: 'local',
file_path: 'photos/test.jpg',
asset_id: null,
owner_id: null,
thumbnail_path: null,
caption: 'Colosseum',
sort_order: 0,
width: 800,
height: 600,
shared: 1,
created_at: journeyNow,
},
],
};
/** The journal's own reads and writes, answered with that journal (merged with `journeyOverride`). */
export function setupJourneyHandlers(journeyOverride?: Record<string, unknown>) {
const journey = journeyOverride ? { ...mockJourneyDetail, ...journeyOverride } : mockJourneyDetail;
server.use(
http.get('/api/journeys/1', () => {
return HttpResponse.json(journey);
}),
http.get('/api/addons', () => {
return HttpResponse.json({
addons: [
{ id: 'journey', name: 'Journey', type: 'feature', icon: 'book', enabled: true },
{ id: 'immich', name: 'Immich', type: 'photo_provider', icon: 'camera', enabled: true },
],
});
}),
http.get('/api/integrations/memories/:provider/status', () => {
return HttpResponse.json({ connected: false });
}),
http.patch('/api/journeys/1', () => {
return HttpResponse.json({ ...mockJourneyDetail, title: 'Updated' });
}),
http.get('/api/journeys/1/share-link', () => {
return HttpResponse.json({ link: null });
})
);
}
+35
View File
@@ -0,0 +1,35 @@
// The page's own location, taken when this module loads, before any test
// replaces window.location with a stand-in.
const pageLocation = window.location;
const pageOrigin = new URL(document.baseURI).origin;
/** `path` as an absolute URL on the page's own origin, for asserting on location.href. */
export function pageUrl(path: string): string {
return new URL(path, pageOrigin).href;
}
/**
* A stand-in for window.location that shows `path` on the page's own origin.
*
* Requests have to stay on one origin for the HTTP mocks to answer them: msw
* resolves its relative handlers, and its fetch interceptor a relative URL,
* against location.href, while jsdom's XHR resolves against the document. A
* stand-in on another origin (`http://localhost/` while the page runs on
* `http://localhost:3000`) sends every request past its handler.
*/
export function locationAt(path: string, overrides: Partial<Location> = {}): Location {
const url = new URL(path, pageOrigin);
return {
...pageLocation,
href: url.href,
origin: url.origin,
protocol: url.protocol,
host: url.host,
hostname: url.hostname,
port: url.port,
pathname: url.pathname,
search: url.search,
hash: url.hash,
...overrides,
};
}
+27 -19
View File
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { http, HttpResponse } from 'msw'; import { http, HttpResponse } from 'msw';
import { server } from '../../helpers/msw/server'; import { server } from '../../helpers/msw/server';
import { buildUser } from '../../helpers/factories'; import { buildUser } from '../../helpers/factories';
import { locationAt, pageUrl } from '../../helpers/location';
// The global setup.ts mocks websocket with getSocketId returning null. // The global setup.ts mocks websocket with getSocketId returning null.
// We need to be able to control what getSocketId returns per-test. // We need to be able to control what getSocketId returns per-test.
@@ -59,7 +60,7 @@ describe('API client interceptors', () => {
// Reset window.location to a neutral path // Reset window.location to a neutral path
Object.defineProperty(window, 'location', { Object.defineProperty(window, 'location', {
writable: true, writable: true,
value: { href: 'http://localhost/', pathname: '/', search: '', hash: '' }, value: locationAt('/'),
}); });
}); });
@@ -97,7 +98,7 @@ describe('API client interceptors', () => {
it('FE-API-003: 401 with AUTH_REQUIRED → redirects to /login with redirect param', async () => { it('FE-API-003: 401 with AUTH_REQUIRED → redirects to /login with redirect param', async () => {
Object.defineProperty(window, 'location', { Object.defineProperty(window, 'location', {
writable: true, writable: true,
value: { href: 'http://localhost/', pathname: '/dashboard', search: '', hash: '' }, value: locationAt('/dashboard'),
}); });
server.use( server.use(
@@ -118,7 +119,7 @@ describe('API client interceptors', () => {
it('FE-API-003b: 401 without AUTH_REQUIRED code does not redirect', async () => { it('FE-API-003b: 401 without AUTH_REQUIRED code does not redirect', async () => {
Object.defineProperty(window, 'location', { Object.defineProperty(window, 'location', {
writable: true, writable: true,
value: { href: 'http://localhost/dashboard', pathname: '/dashboard', search: '' }, value: locationAt('/dashboard'),
}); });
const originalHref = window.location.href; const originalHref = window.location.href;
@@ -141,7 +142,7 @@ describe('API client interceptors', () => {
it('FE-API-003c: 401 on /login page does not redirect', async () => { it('FE-API-003c: 401 on /login page does not redirect', async () => {
Object.defineProperty(window, 'location', { Object.defineProperty(window, 'location', {
writable: true, writable: true,
value: { href: 'http://localhost/login', pathname: '/login', search: '' }, value: locationAt('/login'),
}); });
server.use( server.use(
@@ -157,13 +158,13 @@ describe('API client interceptors', () => {
} }
// href should NOT have been changed to /login?redirect=... // href should NOT have been changed to /login?redirect=...
expect(window.location.href).toBe('http://localhost/login'); expect(window.location.href).toBe(pageUrl('/login'));
}); });
it('FE-API-004: 403 with MFA_REQUIRED → redirects to /settings?mfa=required', async () => { it('FE-API-004: 403 with MFA_REQUIRED → redirects to /settings?mfa=required', async () => {
Object.defineProperty(window, 'location', { Object.defineProperty(window, 'location', {
writable: true, writable: true,
value: { href: 'http://localhost/', pathname: '/dashboard', search: '' }, value: locationAt('/dashboard'),
}); });
server.use( server.use(
@@ -184,7 +185,7 @@ describe('API client interceptors', () => {
it('FE-API-004b: 403 with MFA_REQUIRED on /settings page does not redirect', async () => { it('FE-API-004b: 403 with MFA_REQUIRED on /settings page does not redirect', async () => {
Object.defineProperty(window, 'location', { Object.defineProperty(window, 'location', {
writable: true, writable: true,
value: { href: 'http://localhost/settings', pathname: '/settings', search: '' }, value: locationAt('/settings'),
}); });
server.use( server.use(
@@ -200,7 +201,7 @@ describe('API client interceptors', () => {
} }
// Should NOT redirect when already on /settings // Should NOT redirect when already on /settings
expect(window.location.href).toBe('http://localhost/settings'); expect(window.location.href).toBe(pageUrl('/settings'));
}); });
it('FE-API-005: successful API call returns response data', async () => { it('FE-API-005: successful API call returns response data', async () => {
@@ -253,7 +254,7 @@ describe('API client interceptors', () => {
it('FE-API-008: 401 AUTH_REQUIRED on /register path does not redirect', async () => { it('FE-API-008: 401 AUTH_REQUIRED on /register path does not redirect', async () => {
Object.defineProperty(window, 'location', { Object.defineProperty(window, 'location', {
writable: true, writable: true,
value: { href: 'http://localhost/register', pathname: '/register', search: '' }, value: locationAt('/register'),
}); });
server.use( server.use(
@@ -264,13 +265,13 @@ describe('API client interceptors', () => {
try { await authApi.me(); } catch { /* expected */ } try { await authApi.me(); } catch { /* expected */ }
expect(window.location.href).toBe('http://localhost/register'); expect(window.location.href).toBe(pageUrl('/register'));
}); });
it('FE-API-009: 401 AUTH_REQUIRED on /shared/:token path does not redirect', async () => { it('FE-API-009: 401 AUTH_REQUIRED on /shared/:token path does not redirect', async () => {
Object.defineProperty(window, 'location', { Object.defineProperty(window, 'location', {
writable: true, writable: true,
value: { href: 'http://localhost/shared/abc123', pathname: '/shared/abc123', search: '' }, value: locationAt('/shared/abc123'),
}); });
server.use( server.use(
@@ -281,13 +282,13 @@ describe('API client interceptors', () => {
try { await authApi.me(); } catch { /* expected */ } try { await authApi.me(); } catch { /* expected */ }
expect(window.location.href).toBe('http://localhost/shared/abc123'); expect(window.location.href).toBe(pageUrl('/shared/abc123'));
}); });
it('FE-API-010: 401 AUTH_REQUIRED still rejects the promise even when redirect fires', async () => { it('FE-API-010: 401 AUTH_REQUIRED still rejects the promise even when redirect fires', async () => {
Object.defineProperty(window, 'location', { Object.defineProperty(window, 'location', {
writable: true, writable: true,
value: { href: 'http://localhost/dashboard', pathname: '/dashboard', search: '' }, value: locationAt('/dashboard'),
}); });
server.use( server.use(
@@ -304,7 +305,7 @@ describe('API client interceptors', () => {
it('FE-API-011: 403 without MFA_REQUIRED code does not redirect', async () => { it('FE-API-011: 403 without MFA_REQUIRED code does not redirect', async () => {
Object.defineProperty(window, 'location', { Object.defineProperty(window, 'location', {
writable: true, writable: true,
value: { href: 'http://localhost/dashboard', pathname: '/dashboard', search: '' }, value: locationAt('/dashboard'),
}); });
server.use( server.use(
@@ -315,13 +316,13 @@ describe('API client interceptors', () => {
try { await authApi.me(); } catch { /* expected */ } try { await authApi.me(); } catch { /* expected */ }
expect(window.location.href).toBe('http://localhost/dashboard'); expect(window.location.href).toBe(pageUrl('/dashboard'));
}); });
it('FE-API-012: 403 MFA_REQUIRED still rejects the promise after redirect fires', async () => { it('FE-API-012: 403 MFA_REQUIRED still rejects the promise after redirect fires', async () => {
Object.defineProperty(window, 'location', { Object.defineProperty(window, 'location', {
writable: true, writable: true,
value: { href: 'http://localhost/dashboard', pathname: '/dashboard', search: '' }, value: locationAt('/dashboard'),
}); });
server.use( server.use(
@@ -962,11 +963,13 @@ describe('mapsApi', () => {
it('FE-MAPS-004: mapsApi.autocomplete rejects when AbortSignal is aborted', async () => { it('FE-MAPS-004: mapsApi.autocomplete rejects when AbortSignal is aborted', async () => {
const controller = new AbortController(); const controller = new AbortController();
let release!: () => void;
const gate = new Promise<void>(resolve => { release = resolve; });
server.use( server.use(
http.post('/api/maps/autocomplete', async () => { http.post('/api/maps/autocomplete', async () => {
// Never resolves — request will be aborted // Held until the request has been aborted
await new Promise(() => {}); await gate;
return HttpResponse.json({ suggestions: [] }); return HttpResponse.json({ suggestions: [] });
}) })
); );
@@ -974,6 +977,11 @@ describe('mapsApi', () => {
const promise = mapsApi.autocomplete('Paris', undefined, undefined, controller.signal); const promise = mapsApi.autocomplete('Paris', undefined, undefined, controller.signal);
controller.abort(); controller.abort();
await expect(promise).rejects.toThrow(); try {
await expect(promise).rejects.toThrow();
} finally {
// Let the held handler finish here, not in whatever runs after this test.
release();
}
}); });
}); });
+6 -3
View File
@@ -26,10 +26,13 @@ vi.mock('../src/api/websocket', () => ({
// lets it through, so the runner really talks to frankfurter or a tile server and settles // lets it through, so the runner really talks to frankfurter or a tile server and settles
// a promise after the test environment is gone (see handlers/external.ts). Those fail now. // a promise after the test environment is gone (see handlers/external.ts). Those fail now.
// An unhandled same-origin call stays a warning: that is a missing handler, not egress. // An unhandled same-origin call stays a warning: that is a missing handler, not egress.
// Only HTTP frames are judged, as before msw 3 reported every network frame here.
beforeAll(() => server.listen({ beforeAll(() => server.listen({
onUnhandledRequest: (request, print) => { onUnhandledFrame: ({ frame, defaults }) => {
if (new URL(request.url).origin === location.origin) print.warning(); if (frame.protocol !== 'http') return;
else print.error(); const { request } = frame.data as { request: Request };
if (new URL(request.url).origin === location.origin) defaults.warn();
else defaults.error();
}, },
})); }));
afterEach(() => { afterEach(() => {
@@ -442,6 +442,9 @@ describe('MSettingsPlugins', () => {
expect(frame).toHaveAttribute('data-plugin', 'p1'); expect(frame).toHaveAttribute('data-plugin', 'p1');
expect(frame).toHaveAttribute('data-path', 'settings.html'); expect(frame).toHaveAttribute('data-path', 'settings.html');
expect(frame).toHaveAttribute('data-title', 'Weather Pro'); expect(frame).toHaveAttribute('data-title', 'Weather Pro');
// The framed card renders at once, the declared-field form only once its
// settings request answered; wait for that form before counting the cards.
await screen.findByPlaceholderText('https://api.example');
// Declared-field form and framed surface are two separate cards // Declared-field form and framed surface are two separate cards
expect(screen.getAllByText('Weather Pro')).toHaveLength(2); expect(screen.getAllByText('Weather Pro')).toHaveLength(2);
}); });
@@ -266,7 +266,9 @@ describe('MCollabChat', () => {
expect(send).toBeEnabled() expect(send).toBeEnabled()
fireEvent.click(send) fireEvent.click(send)
expect(await screen.findByText('Landed safely')).toBeInTheDocument() // React mirrors the draft into the textarea's text, so the composer itself
// matches the trimmed text; wait for the appended bubble, not the draft.
expect(await screen.findByText('Landed safely', { ignore: 'script, style, textarea' })).toBeInTheDocument()
expect(sentBodies).toEqual([{ text: 'Landed safely' }]) expect(sentBodies).toEqual([{ text: 'Landed safely' }])
expect(input).toHaveValue('') expect(input).toHaveValue('')
}) })
@@ -128,6 +128,7 @@ function buildTl(over: Record<string, unknown> = {}): MPlanTimelineController {
{ key: 'plugin:ev/fastest', label: 'EV fastest' }, { key: 'plugin:ev/fastest', label: 'EV fastest' },
], ],
setLegMode: vi.fn(), setLegMode: vi.fn(),
setIncomingLegMode: vi.fn(),
transitLegFor: vi.fn(() => null), transitLegFor: vi.fn(() => null),
planTransitLeg: vi.fn(), planTransitLeg: vi.fn(),
journeyLate: vi.fn(() => null), journeyLate: vi.fn(() => null),
@@ -506,6 +507,74 @@ describe('MPlanTimeline', () => {
expect(screen.getByText('7 min').closest('button')).toBeNull() expect(screen.getByText('7 min').closest('button')).toBeNull()
}) })
// The legs a booking or the hotel starts: the phone used to leave them inert while
// the desktop opened the mode menu of the stop at their other end.
describe('legs that start at a booking or the hotel', () => {
const HOTEL_SEG: RouteSegment = { ...SEG, drivingText: '12 min', walkingText: '35 min', distanceText: '2.7 km' }
const hotelLeg = () => screen.getByText('12 min').closest('button') as HTMLElement
const leg = { from: { name: 'Budapest Keleti', lat: 47.5, lng: 19.08 }, to: { name: 'Basilica apARTment', lat: 47.5, lng: 19.05 }, time: '19:29' }
it('FE-MOB-PLTL-050: the leg back to the hotel sets the outgoing mode of the last stop', () => {
renderTimeline({ hotelLegs: { top: null, bottom: { seg: HOTEL_SEG, name: 'Basilica', assignmentId: 12 } } }, {}, { mode: 'edit' })
fireEvent.click(hotelLeg())
fireEvent.click(screen.getByText('Walking'))
expect(mocks.tl.setLegMode).toHaveBeenCalledWith(12, 'walking')
expect(mocks.tl.setIncomingLegMode).not.toHaveBeenCalled()
})
it('FE-MOB-PLTL-051: the leg from the hotel sets the incoming mode of the first stop', () => {
renderTimeline({ hotelLegs: { top: { seg: HOTEL_SEG, name: 'Basilica', assignmentId: 11 }, bottom: null } }, {}, { mode: 'edit' })
fireEvent.click(hotelLeg())
fireEvent.click(screen.getByText('dayplan.transportMode.useDefault'))
expect(mocks.tl.setIncomingLegMode).toHaveBeenCalledWith(11, null)
expect(mocks.tl.setLegMode).not.toHaveBeenCalled()
})
it('FE-MOB-PLTL-052: a walk from the train to the hotel that no stop owns offers public transit only', () => {
renderTimeline(
{ hotelLegs: { top: null, bottom: { seg: HOTEL_SEG, name: 'Basilica' } }, transitLegFor: vi.fn(() => leg) },
{}, { mode: 'edit' },
)
fireEvent.click(hotelLeg())
expect(screen.queryByText('Driving')).not.toBeInTheDocument()
expect(screen.queryByText('dayplan.transportMode.useDefault')).not.toBeInTheDocument()
fireEvent.click(screen.getByText('transit.title'))
expect(mocks.tl.planTransitLeg).toHaveBeenCalledWith(leg, undefined)
})
it('FE-MOB-PLTL-053: without a transit search that walk stays plain text', () => {
renderTimeline({ hotelLegs: { top: null, bottom: { seg: HOTEL_SEG, name: 'Basilica' } } }, {}, { mode: 'edit' })
expect(screen.getByText('12 min').closest('button')).toBeNull()
})
it('FE-MOB-PLTL-054: the leg from a booking to the next stop sets the incoming mode of that stop', () => {
const rows: PlanRow[] = [
{ key: 'tr-21', kind: 'transport', item: M_FLIGHT, res: FLIGHT },
{ key: 'conn-tr-21', kind: 'conn', seg: HOTEL_SEG, incomingAssignmentId: 12 },
{ key: 'pl-12', kind: 'place', item: M_PLACE2, assignment: PARK, linkedReservations: [] },
]
renderTimeline({ rows }, {}, { mode: 'edit' })
fireEvent.click(hotelLeg())
fireEvent.click(screen.getByText('Walking'))
expect(mocks.tl.setIncomingLegMode).toHaveBeenCalledWith(12, 'walking')
})
it('FE-MOB-PLTL-055: go mode keeps the hotel legs read-only', () => {
renderTimeline({ hotelLegs: { top: null, bottom: { seg: HOTEL_SEG, name: 'Basilica', assignmentId: 12 } } })
expect(screen.getByText('12 min').closest('button')).toBeNull()
})
})
}) })
describe('plugin day schedule', () => { describe('plugin day schedule', () => {
@@ -488,6 +488,23 @@ describe('HotelConnRow', () => {
expect(screen.getByText('1 h 5 min')).toBeInTheDocument() expect(screen.getByText('1 h 5 min')).toBeInTheDocument()
expect(screen.queryByText('14 min')).not.toBeInTheDocument() expect(screen.queryByText('14 min')).not.toBeInTheDocument()
}) })
it('FE-MOB-PLROW-045: the leg is a button when it can be tapped, the stay name stays text', () => {
const onTap = vi.fn()
render(<HotelConnRow seg={SEG} name="Hotel Sacher" placement="bottom" onTap={onTap} />)
const button = screen.getByRole('button')
expect(button.textContent).toContain('14 min')
expect(button.textContent).not.toContain('Hotel Sacher')
fireEvent.click(button)
expect(onTap).toHaveBeenCalledTimes(1)
})
it('FE-MOB-PLROW-046: without a tap handler nothing on the row is a button', () => {
render(<HotelConnRow seg={SEG} name="Hotel Sacher" placement="top" />)
expect(screen.queryByRole('button')).not.toBeInTheDocument()
})
}) })
describe('NoteRow', () => { describe('NoteRow', () => {
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from 'vitest' import { describe, expect, it, vi } from 'vitest'
import { import {
breaksChronology, buildPlanRows, cityPillsForDay, findUpNext, getTransitMeta, hotelChipsForDay, breaksChronology, buildPlanRows, buildPlanTimeline, cityPillsForDay, findUpNext, getTransitMeta, hotelChipsForDay,
hotelLegsForDay, itemHasTime, parseReservationMeta, transportSubtitle, hotelLegsForDay, itemHasTime, parseReservationMeta, transportSubtitle,
type TransportEntry, type TransportEntry,
} from '../../../../src/mobile/screens/trip/plan/planTimelineModel' } from '../../../../src/mobile/screens/trip/plan/planTimelineModel'
@@ -956,3 +956,76 @@ describe('planTimelineModel: a rental car picked up or returned on the day', ()
expect(connectors(rows).map(s => [s.from, s.to])).toEqual([[at(PICKUP), at(MIRADOR)]]) expect(connectors(rows).map(s => [s.from, s.to])).toEqual([[at(PICKUP), at(MIRADOR)]])
}) })
}) })
describe('planTimelineModel: which stop owns a leg that touches a booking or the hotel', () => {
// Day 2 of a stay from day 1 to day 3: the traveller walks from the hotel to the
// museum, takes the train to the lake and walks from the station to the hotel. The
// two legs a booking starts and the two bookend legs are the ones the phone could
// not change before; the desktop takes their mode from the stop at their other end.
const HOTEL = { lat: 47.3769, lng: 8.5417 }
const MUSEUM = { lat: 47.3792, lng: 8.5403 }
const STATION_FROM = { lat: 47.378, lng: 8.54 }
const STATION_TO = { lat: 47.05, lng: 8.31 }
const PIER = { lat: 47.052, lng: 8.309 }
const stay = accommodation({
id: 40, place_id: 950, place_name: 'Hotel Limmat', place_lat: HOTEL.lat, place_lng: HOTEL.lng,
start_day_id: 1, end_day_id: 3,
})
const museum = buildAssignment({ id: 31, day_id: 2, order_index: 0, place: place(960, 'Museum', MUSEUM.lat, MUSEUM.lng) })
const pier = buildAssignment({ id: 32, day_id: 2, order_index: 2, place: place(961, 'Pier', PIER.lat, PIER.lng) })
const train = (id: number, position: number) => buildReservation({
id, type: 'train', title: `IR ${id}`, day_id: 2, end_day_id: 2, day_plan_position: position,
reservation_time: '2026-05-02T11:00', reservation_end_time: '2026-05-02T12:00',
endpoints: [
{ role: 'from', sequence: 0, name: 'Zurich HB', code: null, ...STATION_FROM, timezone: null, local_date: null, local_time: null },
{ role: 'to', sequence: 1, name: 'Lucerne', code: null, ...STATION_TO, timezone: null, local_date: null, local_time: null },
],
})
const timelineOf = (dayAssignments: Assignment[], reservations: Reservation[]) => {
const merged = getMergedItems({
dayAssignments,
dayNotes: [],
dayTransports: getTransportForDay({ reservations, dayId: 2, dayAssignmentIds: dayAssignments.map(a => a.id), days: DAYS }),
dayId: 2,
})
const segments = segmentsOf(buildDayRouteRuns(2, {
days: DAYS, assignments: { '2': dayAssignments }, reservations, accommodations: [stay], optimizeFromAccommodation: true,
}))
const { rows, bookendOwners } = buildPlanTimeline({ merged, reservations, routeSegments: segments, dayId: 2 })
return { rows, legs: hotelLegsForDay(DAY2, DAYS, [stay], segments, bookendOwners) }
}
const conns = (rows: ReturnType<typeof buildPlanRows>) => rows.flatMap(r => (r.kind === 'conn' ? [r] : []))
it('FE-MOB-PTLM-064: the leg out of a booking uses the incoming mode of the stop it reaches', () => {
const { rows } = timelineOf([museum, pier], [train(70, 1)])
expect(rows.map(r => r.kind)).toEqual(['place', 'conn', 'transport', 'conn', 'place'])
const [toStation, toPier] = conns(rows)
// Out of a stop: the stop's own outgoing mode, as before.
expect(toStation).toMatchObject({ assignmentId: 31 })
expect(toStation.incomingAssignmentId).toBeUndefined()
// Out of the train: no stop leaves it, so the pier's incoming mode is the one it uses.
expect(toPier).toMatchObject({ seg: { from: [STATION_TO.lat, STATION_TO.lng], to: [PIER.lat, PIER.lng] }, incomingAssignmentId: 32 })
expect(toPier.assignmentId).toBeUndefined()
})
it('FE-MOB-PTLM-065: the hotel legs belong to the first and the last stop of the day', () => {
const { legs } = timelineOf([museum, pier], [train(70, 1)])
expect(legs.top).toMatchObject({ name: 'Hotel Limmat', assignmentId: 31, seg: { from: [HOTEL.lat, HOTEL.lng], to: [MUSEUM.lat, MUSEUM.lng] } })
expect(legs.bottom).toMatchObject({ name: 'Hotel Limmat', assignmentId: 32, seg: { from: [PIER.lat, PIER.lng], to: [HOTEL.lat, HOTEL.lng] } })
})
it('FE-MOB-PTLM-066: a day that ends with the train has no stop owning the walk to the hotel', () => {
const { legs } = timelineOf([museum], [train(71, 5)])
expect(legs.bottom).toMatchObject({ seg: { from: [STATION_TO.lat, STATION_TO.lng], to: [HOTEL.lat, HOTEL.lng] } })
expect(legs.bottom?.assignmentId).toBeUndefined()
expect(legs.top).toMatchObject({ assignmentId: 31 })
})
it('FE-MOB-PTLM-067: a day that starts with the train has no stop owning the walk from the hotel', () => {
const { legs } = timelineOf([pier], [train(72, -1)])
expect(legs.top).toMatchObject({ seg: { from: [HOTEL.lat, HOTEL.lng], to: [STATION_FROM.lat, STATION_FROM.lng] } })
expect(legs.top?.assignmentId).toBeUndefined()
expect(legs.bottom).toMatchObject({ assignmentId: 32 })
})
})
@@ -1,21 +1,39 @@
// FE-MOB-MVACINV-001 to FE-MOB-MVACINV-010 // FE-MOB-MVACINV-001 to FE-MOB-MVACINV-010
import React from 'react'; import React from 'react';
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; import { describe, it, expect, beforeEach, afterEach, vi, type MockInstance } from 'vitest';
import { http, HttpResponse } from 'msw'; import { http, HttpResponse } from 'msw';
import { render, screen, fireEvent, waitFor, within } from '../../../helpers/render'; import { render, screen, fireEvent, waitFor, within, act } from '../../../helpers/render';
import { server } from '../../../helpers/msw/server'; import { server } from '../../../helpers/msw/server';
import { resetAllStores } from '../../../helpers/store'; import { resetAllStores } from '../../../helpers/store';
import { useVacayStore } from '../../../../src/store/vacayStore'; import { useVacayStore } from '../../../../src/store/vacayStore';
import apiClient from '../../../../src/api/client';
import MVacayInviteSheet from '../../../../src/mobile/screens/vacay/MVacayInviteSheet'; import MVacayInviteSheet from '../../../../src/mobile/screens/vacay/MVacayInviteSheet';
const toasts: { type: string; message: string }[] = []; const toasts: { type: string; message: string }[] = [];
const USERS_ENDPOINT = '/addons/vacay/available-users';
let getSpy: MockInstance<typeof apiClient.get>;
function availableUsers(users: { id: number; username: string; color: string | null }[]) { function availableUsers(users: { id: number; username: string; color: string | null }[]) {
server.use(http.get('/api/addons/vacay/available-users', () => HttpResponse.json({ users }))); server.use(http.get('/api/addons/vacay/available-users', () => HttpResponse.json({ users })));
} }
/**
* Waits until the sheet has asked for the invitable users `lookups` times and
* every answer has come back and been applied. The answer is not on screen when
* it changes nothing (an empty list, the same list on a reload), and a lookup
* still out when the test ends would land in the next one.
*/
async function usersSettled(lookups: number) {
const calls = () => getSpy.mock.calls.flatMap(([url], i) => (url === USERS_ENDPOINT ? [getSpy.mock.results[i].value] : []));
await waitFor(() => expect(calls()).toHaveLength(lookups));
await act(async () => {
await Promise.allSettled(calls());
});
}
beforeEach(() => { beforeEach(() => {
resetAllStores(); resetAllStores();
getSpy = vi.spyOn(apiClient, 'get');
toasts.length = 0; toasts.length = 0;
window.__addToast = ((message: string, type?: string) => { window.__addToast = ((message: string, type?: string) => {
toasts.push({ type: type ?? 'info', message }); toasts.push({ type: type ?? 'info', message });
@@ -28,6 +46,7 @@ beforeEach(() => {
}); });
afterEach(() => { afterEach(() => {
getSpy.mockRestore();
delete window.__addToast; delete window.__addToast;
}); });
@@ -54,6 +73,7 @@ describe('MVacayInviteSheet', () => {
it('FE-MOB-MVACINV-003: falls back to the empty state when the lookup fails', async () => { it('FE-MOB-MVACINV-003: falls back to the empty state when the lookup fails', async () => {
server.use(http.get('/api/addons/vacay/available-users', () => HttpResponse.json({ error: 'nope' }, { status: 500 }))); server.use(http.get('/api/addons/vacay/available-users', () => HttpResponse.json({ error: 'nope' }, { status: 500 })));
renderSheet(); renderSheet();
await usersSettled(1);
expect(await screen.findByText('No users available')).toBeInTheDocument(); expect(await screen.findByText('No users available')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Select user' })).not.toBeInTheDocument(); expect(screen.queryByRole('button', { name: 'Select user' })).not.toBeInTheDocument();
@@ -74,7 +94,9 @@ describe('MVacayInviteSheet', () => {
const send = await screen.findByRole('button', { name: 'Send Invite' }); const send = await screen.findByRole('button', { name: 'Send Invite' });
expect(send).toBeDisabled(); expect(send).toBeDisabled();
fireEvent.click(screen.getByRole('button', { name: 'Select user' })); // The picker shows up once the users are in; nobody is picked yet.
fireEvent.click(await screen.findByRole('button', { name: 'Select user' }));
expect(screen.getByRole('button', { name: 'Send Invite' })).toBeDisabled();
fireEvent.click(screen.getByRole('button', { name: 'bob' })); fireEvent.click(screen.getByRole('button', { name: 'bob' }));
expect(screen.getByRole('button', { name: 'Send Invite' })).toBeEnabled(); expect(screen.getByRole('button', { name: 'Send Invite' })).toBeEnabled();
}); });
@@ -122,6 +144,7 @@ describe('MVacayInviteSheet', () => {
fireEvent.click(within(row).getByRole('button', { name: 'Cancel' })); fireEvent.click(within(row).getByRole('button', { name: 'Cancel' }));
expect(cancelInvite).toHaveBeenCalledWith(9); expect(cancelInvite).toHaveBeenCalledWith(9);
await usersSettled(1);
}); });
it('FE-MOB-MVACINV-009: the close icon and the cancel button both dismiss the sheet', async () => { it('FE-MOB-MVACINV-009: the close icon and the cancel button both dismiss the sheet', async () => {
@@ -131,6 +154,7 @@ describe('MVacayInviteSheet', () => {
const dialog = screen.getByRole('dialog', { name: 'Invite User' }); const dialog = screen.getByRole('dialog', { name: 'Invite User' });
fireEvent.click(within(dialog).getAllByRole('button', { name: 'Cancel' })[0]); fireEvent.click(within(dialog).getAllByRole('button', { name: 'Cancel' })[0]);
expect(onClose).toHaveBeenCalledTimes(2); expect(onClose).toHaveBeenCalledTimes(2);
await usersSettled(1);
}); });
it('FE-MOB-MVACINV-010: reopening resets the previous selection', async () => { it('FE-MOB-MVACINV-010: reopening resets the previous selection', async () => {
@@ -141,6 +165,7 @@ describe('MVacayInviteSheet', () => {
rerender(<MVacayInviteSheet open={false} onClose={() => {}} />); rerender(<MVacayInviteSheet open={false} onClose={() => {}} />);
rerender(<MVacayInviteSheet open onClose={() => {}} />); rerender(<MVacayInviteSheet open onClose={() => {}} />);
await usersSettled(2);
expect(await screen.findByRole('button', { name: 'Select user' })).toBeInTheDocument(); expect(await screen.findByRole('button', { name: 'Select user' })).toBeInTheDocument();
}); });
+16 -1
View File
@@ -4,7 +4,7 @@ import { describe, expect, it } from 'vitest';
import { directionOf, pickLocale, translator } from '../../../native-shell/i18n'; import { directionOf, pickLocale, translator } from '../../../native-shell/i18n';
// FE-NATIVE-SHELL-001 to FE-NATIVE-SHELL-006 // FE-NATIVE-SHELL-001 to FE-NATIVE-SHELL-007
// //
// The app's own first screens (client/native-shell): which language and reading // The app's own first screens (client/native-shell): which language and reading
// direction they start in, and the layout rules in shell.css that no component // direction they start in, and the layout rules in shell.css that no component
@@ -97,4 +97,19 @@ describe('native shell', () => {
/margin-left|margin-right|padding-left|padding-right|text-align:\s*left|[^-]left:\s|[^-]right:\s/ /margin-left|margin-right|padding-left|padding-right|text-align:\s*left|[^-]left:\s|[^-]right:\s/
); );
}); });
it("FE-NATIVE-SHELL-007: every edge clears the system bars from Android's injected insets too, and the foot keeps clear of the navigation bar", () => {
const root = find(':root')
.map((r) => r.body)
.join('');
const side = (name: string, edge: string) =>
new RegExp(
`--${name}:\\s*max\\(\\s*env\\(safe-area-inset-${edge}, 0px\\),\\s*var\\(--safe-area-inset-${edge}, 0px\\),\\s*var\\(--trek-native-safe-${edge}, 0px\\)\\s*\\)`
);
expect(root).toMatch(side('safe-top', 'top'));
expect(root).toMatch(side('safe-bottom', 'bottom'));
expect(root).toMatch(side('safe-start', 'left'));
expect(root).toMatch(side('safe-end', 'right'));
expect(find('.dock')[0]?.body).toMatch(/padding-block:[^;]*var\(--safe-bottom\)/);
});
}); });
+264 -134
View File
@@ -1,225 +1,355 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { downloadFile, openFile } from '../../../src/utils/fileDownload' import { getCachedBlob } from '../../../src/db/offlineDb';
import { getCachedBlob } from '../../../src/db/offlineDb' import { downloadFile, openFile } from '../../../src/utils/fileDownload';
// Mock the offline DB so these tests never touch Dexie/IndexedDB. // Mock the offline DB so these tests never touch Dexie/IndexedDB.
vi.mock('../../../src/db/offlineDb', () => ({ getCachedBlob: vi.fn() })) vi.mock('../../../src/db/offlineDb', () => ({ getCachedBlob: vi.fn() }));
function makeFetchMock(status: number, blob: Blob = new Blob(['data'], { type: 'application/pdf' })) { function makeFetchMock(status: number, blob: Blob = new Blob(['data'], { type: 'application/pdf' })) {
return vi.fn().mockResolvedValue({ return vi.fn().mockResolvedValue({
status, status,
ok: status >= 200 && status < 300, ok: status >= 200 && status < 300,
blob: () => Promise.resolve(blob), blob: () => Promise.resolve(blob),
}) });
} }
beforeEach(() => { beforeEach(() => {
vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:mock-url') vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:mock-url');
vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {}) vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {});
vi.spyOn(document.body, 'appendChild').mockImplementation((el) => el) vi.spyOn(document.body, 'appendChild').mockImplementation((el) => el);
vi.spyOn(document.body, 'removeChild').mockImplementation((el) => el) vi.spyOn(document.body, 'removeChild').mockImplementation((el) => el);
vi.useFakeTimers() vi.useFakeTimers();
}) });
afterEach(() => { afterEach(() => {
vi.restoreAllMocks() vi.restoreAllMocks();
vi.useRealTimers() vi.useRealTimers();
}) });
describe('assertRelativeUrl (URL guard)', () => { describe('assertRelativeUrl (URL guard)', () => {
it('rejects absolute http URLs', async () => { it('rejects absolute http URLs', async () => {
await expect(downloadFile('https://evil.com/x')).rejects.toThrow('Refusing to fetch non-relative URL') await expect(downloadFile('https://evil.com/x')).rejects.toThrow('Refusing to fetch non-relative URL');
}) });
it('rejects protocol-relative URLs', async () => { it('rejects protocol-relative URLs', async () => {
await expect(downloadFile('//evil.com/x')).rejects.toThrow('Refusing to fetch non-relative URL') await expect(downloadFile('//evil.com/x')).rejects.toThrow('Refusing to fetch non-relative URL');
}) });
it('allows relative paths', async () => { it('allows relative paths', async () => {
vi.stubGlobal('fetch', makeFetchMock(200)) vi.stubGlobal('fetch', makeFetchMock(200));
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {}) vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {});
await expect(downloadFile('/trips/1/files/2/download')).resolves.toBeUndefined() await expect(downloadFile('/trips/1/files/2/download')).resolves.toBeUndefined();
}) });
}) });
describe('downloadFile', () => { describe('downloadFile', () => {
it('fetches with credentials:include and triggers anchor download', async () => { it('fetches with credentials:include and triggers anchor download', async () => {
const fetchMock = makeFetchMock(200) const fetchMock = makeFetchMock(200);
vi.stubGlobal('fetch', fetchMock) vi.stubGlobal('fetch', fetchMock);
const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {}) const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {});
await downloadFile('/uploads/files/test.pdf', 'test.pdf') await downloadFile('/uploads/files/test.pdf', 'test.pdf');
expect(fetchMock).toHaveBeenCalledWith('/uploads/files/test.pdf', { credentials: 'include' }) expect(fetchMock).toHaveBeenCalledWith('/uploads/files/test.pdf', {
expect(URL.createObjectURL).toHaveBeenCalled() credentials: 'include',
expect(clickSpy).toHaveBeenCalled() signal: expect.any(AbortSignal),
});
expect(URL.createObjectURL).toHaveBeenCalled();
expect(clickSpy).toHaveBeenCalled();
// Revoke happens after setTimeout(100) // Revoke happens after setTimeout(100)
vi.runAllTimers() vi.runAllTimers();
expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:mock-url') expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:mock-url');
}) });
it('sets download attribute to filename when provided', async () => { it('sets download attribute to filename when provided', async () => {
vi.stubGlobal('fetch', makeFetchMock(200)) vi.stubGlobal('fetch', makeFetchMock(200));
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {}) vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {});
await downloadFile('/uploads/files/report.pdf', 'report.pdf') await downloadFile('/uploads/files/report.pdf', 'report.pdf');
// Check anchor was created with download attribute // Check anchor was created with download attribute
const appendCalls = (document.body.appendChild as ReturnType<typeof vi.fn>).mock.calls const appendCalls = (document.body.appendChild as ReturnType<typeof vi.fn>).mock.calls;
const anchor = appendCalls[0]?.[0] as HTMLAnchorElement const anchor = appendCalls[0]?.[0] as HTMLAnchorElement;
expect(anchor.download).toBe('report.pdf') expect(anchor.download).toBe('report.pdf');
}) });
it('throws on 401 response', async () => { it('throws on 401 response', async () => {
vi.stubGlobal('fetch', makeFetchMock(401)) vi.stubGlobal('fetch', makeFetchMock(401));
await expect(downloadFile('/uploads/files/secret.pdf')).rejects.toThrow('Unauthorized') await expect(downloadFile('/uploads/files/secret.pdf')).rejects.toThrow('Unauthorized');
expect(URL.createObjectURL).not.toHaveBeenCalled() expect(URL.createObjectURL).not.toHaveBeenCalled();
}) });
}) });
describe('openFile', () => { describe('openFile', () => {
it('fetches with credentials:include and opens blob URL via target=_blank anchor', async () => { it('fetches with credentials:include and opens blob URL via target=_blank anchor', async () => {
vi.stubGlobal('fetch', makeFetchMock(200)) vi.stubGlobal('fetch', makeFetchMock(200));
const openSpy = vi.spyOn(window, 'open').mockReturnValue(null) const openSpy = vi.spyOn(window, 'open').mockReturnValue(null);
const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {}) const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {});
await openFile('/uploads/files/doc.pdf') await openFile('/uploads/files/doc.pdf');
expect(window.fetch).toHaveBeenCalledWith('/uploads/files/doc.pdf', { credentials: 'include' }) expect(window.fetch).toHaveBeenCalledWith('/uploads/files/doc.pdf', {
expect(URL.createObjectURL).toHaveBeenCalled() credentials: 'include',
signal: expect.any(AbortSignal),
});
expect(URL.createObjectURL).toHaveBeenCalled();
// Must NOT call window.open — that path returns null when noreferrer is // Must NOT call window.open — that path returns null when noreferrer is
// set, which previously caused the file to also open in the current tab. // set, which previously caused the file to also open in the current tab.
expect(openSpy).not.toHaveBeenCalled() expect(openSpy).not.toHaveBeenCalled();
expect(clickSpy).toHaveBeenCalledTimes(1) expect(clickSpy).toHaveBeenCalledTimes(1);
// The anchor used to open the new tab must be target=_blank, must NOT // The anchor used to open the new tab must be target=_blank, must NOT
// carry a `download` attribute (otherwise it would download in-page // carry a `download` attribute (otherwise it would download in-page
// instead of opening), and must use rel=noopener noreferrer. // instead of opening), and must use rel=noopener noreferrer.
const appendCalls = (document.body.appendChild as ReturnType<typeof vi.fn>).mock.calls const appendCalls = (document.body.appendChild as ReturnType<typeof vi.fn>).mock.calls;
const anchor = appendCalls[0]?.[0] as HTMLAnchorElement const anchor = appendCalls[0]?.[0] as HTMLAnchorElement;
expect(anchor.target).toBe('_blank') expect(anchor.target).toBe('_blank');
expect(anchor.rel).toBe('noopener noreferrer') expect(anchor.rel).toBe('noopener noreferrer');
expect(anchor.hasAttribute('download')).toBe(false) expect(anchor.hasAttribute('download')).toBe(false);
// Revoke happens after 30s timeout // Revoke happens after 30s timeout
vi.runAllTimers() vi.runAllTimers();
expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:mock-url') expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:mock-url');
}) });
it('does not trigger a second in-page action for safe inline types (regression: no double-open)', async () => { it('does not trigger a second in-page action for safe inline types (regression: no double-open)', async () => {
vi.stubGlobal('fetch', makeFetchMock(200)) vi.stubGlobal('fetch', makeFetchMock(200));
const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {}) const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {});
await openFile('/uploads/files/doc.pdf', 'doc.pdf') await openFile('/uploads/files/doc.pdf', 'doc.pdf');
// Exactly ONE anchor click — opening the new tab. No fallback download. // Exactly ONE anchor click — opening the new tab. No fallback download.
expect(clickSpy).toHaveBeenCalledTimes(1) expect(clickSpy).toHaveBeenCalledTimes(1);
}) });
it('throws on 401 response', async () => { it('throws on 401 response', async () => {
vi.stubGlobal('fetch', makeFetchMock(401, new Blob([], { type: 'application/pdf' }))) vi.stubGlobal('fetch', makeFetchMock(401, new Blob([], { type: 'application/pdf' })));
await expect(openFile('/uploads/files/secret.pdf')).rejects.toThrow('Unauthorized') await expect(openFile('/uploads/files/secret.pdf')).rejects.toThrow('Unauthorized');
expect(URL.createObjectURL).not.toHaveBeenCalled() expect(URL.createObjectURL).not.toHaveBeenCalled();
}) });
it('forces download for unsafe MIME types (HTML) instead of opening inline', async () => { it('forces download for unsafe MIME types (HTML) instead of opening inline', async () => {
const htmlBlob = new Blob(['<script>alert(1)</script>'], { type: 'text/html' }) const htmlBlob = new Blob(['<script>alert(1)</script>'], { type: 'text/html' });
vi.stubGlobal('fetch', makeFetchMock(200, htmlBlob)) vi.stubGlobal('fetch', makeFetchMock(200, htmlBlob));
const openSpy = vi.spyOn(window, 'open').mockReturnValue({} as Window) const openSpy = vi.spyOn(window, 'open').mockReturnValue({} as Window);
const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {}) const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {});
await openFile('/uploads/files/malicious.html', 'malicious.html') await openFile('/uploads/files/malicious.html', 'malicious.html');
// Must NOT open inline — download anchor clicked instead // Must NOT open inline — download anchor clicked instead
expect(openSpy).not.toHaveBeenCalled() expect(openSpy).not.toHaveBeenCalled();
expect(clickSpy).toHaveBeenCalledTimes(1) expect(clickSpy).toHaveBeenCalledTimes(1);
const appendCalls = (document.body.appendChild as ReturnType<typeof vi.fn>).mock.calls const appendCalls = (document.body.appendChild as ReturnType<typeof vi.fn>).mock.calls;
const anchor = appendCalls[0]?.[0] as HTMLAnchorElement const anchor = appendCalls[0]?.[0] as HTMLAnchorElement;
expect(anchor.download).toBe('malicious.html') expect(anchor.download).toBe('malicious.html');
}) });
it('forces download for SVG MIME type', async () => { it('forces download for SVG MIME type', async () => {
const svgBlob = new Blob(['<svg><script>alert(1)</script></svg>'], { type: 'image/svg+xml' }) const svgBlob = new Blob(['<svg><script>alert(1)</script></svg>'], { type: 'image/svg+xml' });
vi.stubGlobal('fetch', makeFetchMock(200, svgBlob)) vi.stubGlobal('fetch', makeFetchMock(200, svgBlob));
const openSpy = vi.spyOn(window, 'open').mockReturnValue({} as Window) const openSpy = vi.spyOn(window, 'open').mockReturnValue({} as Window);
const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {}) const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {});
await openFile('/uploads/files/malicious.svg') await openFile('/uploads/files/malicious.svg');
expect(openSpy).not.toHaveBeenCalled() expect(openSpy).not.toHaveBeenCalled();
expect(clickSpy).toHaveBeenCalledTimes(1) expect(clickSpy).toHaveBeenCalledTimes(1);
}) });
it('falls back to download in iOS PWA standalone mode (blob URL inaccessible to Safari)', async () => { it('falls back to download in iOS PWA standalone mode (blob URL inaccessible to Safari)', async () => {
vi.stubGlobal('fetch', makeFetchMock(200)) vi.stubGlobal('fetch', makeFetchMock(200));
const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {}) const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {});
// Simulate iOS PWA (Add-to-Home-Screen) context // Simulate iOS PWA (Add-to-Home-Screen) context
Object.defineProperty(navigator, 'standalone', { configurable: true, value: true }) Object.defineProperty(navigator, 'standalone', { configurable: true, value: true });
try { try {
await openFile('/uploads/files/doc.pdf', 'doc.pdf') await openFile('/uploads/files/doc.pdf', 'doc.pdf');
// Single anchor click — and it must be a DOWNLOAD anchor (no target=_blank), // Single anchor click — and it must be a DOWNLOAD anchor (no target=_blank),
// because target="_blank" in iOS PWA would hand off to Safari which cannot // because target="_blank" in iOS PWA would hand off to Safari which cannot
// read the in-WebView blob URL. // read the in-WebView blob URL.
expect(clickSpy).toHaveBeenCalledTimes(1) expect(clickSpy).toHaveBeenCalledTimes(1);
const appendCalls = (document.body.appendChild as ReturnType<typeof vi.fn>).mock.calls const appendCalls = (document.body.appendChild as ReturnType<typeof vi.fn>).mock.calls;
const anchor = appendCalls[0]?.[0] as HTMLAnchorElement const anchor = appendCalls[0]?.[0] as HTMLAnchorElement;
expect(anchor.target).toBe('') expect(anchor.target).toBe('');
expect(anchor.download).toBe('doc.pdf') expect(anchor.download).toBe('doc.pdf');
} finally { } finally {
// Clean up the non-standard iOS-only property we forced above. // Clean up the non-standard iOS-only property we forced above.
delete (navigator as any).standalone delete (navigator as any).standalone;
} }
}) });
}) });
describe('offline fallback (#1046)', () => { describe('offline fallback (#1046)', () => {
function setOnline(value: boolean) { function setOnline(value: boolean) {
Object.defineProperty(navigator, 'onLine', { value, configurable: true }) Object.defineProperty(navigator, 'onLine', { value, configurable: true });
} }
beforeEach(() => vi.mocked(getCachedBlob).mockReset()) beforeEach(() => vi.mocked(getCachedBlob).mockReset());
afterEach(() => setOnline(true)) afterEach(() => setOnline(true));
it('serves the cached blob without a network call when offline', async () => { it('serves the cached blob without a network call when offline', async () => {
setOnline(false) setOnline(false);
const blob = new Blob(['x'], { type: 'application/pdf' }) const blob = new Blob(['x'], { type: 'application/pdf' });
vi.mocked(getCachedBlob).mockResolvedValue(blob) vi.mocked(getCachedBlob).mockResolvedValue(blob);
const fetchSpy = vi.fn() const fetchSpy = vi.fn();
vi.stubGlobal('fetch', fetchSpy) vi.stubGlobal('fetch', fetchSpy);
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {}) vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {});
await downloadFile('/uploads/files/cached.pdf') await downloadFile('/uploads/files/cached.pdf');
expect(fetchSpy).not.toHaveBeenCalled() expect(fetchSpy).not.toHaveBeenCalled();
expect(getCachedBlob).toHaveBeenCalledWith('/uploads/files/cached.pdf') expect(getCachedBlob).toHaveBeenCalledWith('/uploads/files/cached.pdf');
expect(URL.createObjectURL).toHaveBeenCalledWith(blob) expect(URL.createObjectURL).toHaveBeenCalledWith(blob);
}) });
it('falls back to the cache when a live fetch rejects (network error) while online', async () => { it('falls back to the cache when a live fetch rejects (network error) while online', async () => {
setOnline(true) setOnline(true);
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('network down'))) vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('network down')));
const blob = new Blob(['x'], { type: 'application/pdf' }) const blob = new Blob(['x'], { type: 'application/pdf' });
vi.mocked(getCachedBlob).mockResolvedValue(blob) vi.mocked(getCachedBlob).mockResolvedValue(blob);
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {}) vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {});
await downloadFile('/uploads/files/cached.pdf') await downloadFile('/uploads/files/cached.pdf');
expect(getCachedBlob).toHaveBeenCalledWith('/uploads/files/cached.pdf') expect(getCachedBlob).toHaveBeenCalledWith('/uploads/files/cached.pdf');
expect(URL.createObjectURL).toHaveBeenCalledWith(blob) expect(URL.createObjectURL).toHaveBeenCalledWith(blob);
}) });
it('throws when offline and the file was never cached', async () => { it('throws when offline and the file was never cached', async () => {
setOnline(false) setOnline(false);
vi.mocked(getCachedBlob).mockResolvedValue(null) vi.mocked(getCachedBlob).mockResolvedValue(null);
await expect(downloadFile('/uploads/files/missing.pdf')).rejects.toThrow(/offline/i) await expect(downloadFile('/uploads/files/missing.pdf')).rejects.toThrow(/offline/i);
}) });
it('does not consult the cache on an HTTP error — a 401 still surfaces', async () => { it('does not consult the cache on an HTTP error — a 401 still surfaces', async () => {
setOnline(true) setOnline(true);
vi.stubGlobal('fetch', makeFetchMock(401)) vi.stubGlobal('fetch', makeFetchMock(401));
await expect(downloadFile('/uploads/files/secret.pdf')).rejects.toThrow('Unauthorized') await expect(downloadFile('/uploads/files/secret.pdf')).rejects.toThrow('Unauthorized');
expect(getCachedBlob).not.toHaveBeenCalled() expect(getCachedBlob).not.toHaveBeenCalled();
}) });
}) });
describe('stalled connection with a stored copy (#3066)', () => {
const stored = new Blob(['stored'], { type: 'application/pdf' });
// A promise that never settles on its own and rejects like fetch once the
// signal aborts, which is what a stalled link looks like to the page.
function stallUntilAbort<T>(signal: AbortSignal | undefined): Promise<T> {
return new Promise<T>((_resolve, reject) => {
signal?.addEventListener('abort', () => reject(new DOMException('Aborted', 'AbortError')));
});
}
function track<T>(promise: Promise<T>) {
const state = { done: false };
const finish = () => {
state.done = true;
};
promise.then(finish, finish);
return state;
}
beforeEach(() => {
vi.mocked(getCachedBlob).mockReset();
Object.defineProperty(navigator, 'onLine', { value: true, configurable: true });
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {});
});
it('serves the stored copy once a stalled request has run past the wait', async () => {
vi.mocked(getCachedBlob).mockResolvedValue(stored);
let signal: AbortSignal | undefined;
vi.stubGlobal(
'fetch',
vi.fn((_url: string, init?: RequestInit) => {
signal = init?.signal ?? undefined;
return stallUntilAbort<Response>(signal);
})
);
const pending = downloadFile('/uploads/files/stalled.pdf');
const state = track(pending);
await vi.advanceTimersByTimeAsync(4999);
expect(state.done).toBe(false);
await vi.advanceTimersByTimeAsync(1);
await pending;
expect(URL.createObjectURL).toHaveBeenCalledWith(stored);
expect(signal?.aborted).toBe(true);
});
it('serves the stored copy when the body stalls mid download', async () => {
vi.mocked(getCachedBlob).mockResolvedValue(stored);
let signal: AbortSignal | undefined;
vi.stubGlobal(
'fetch',
vi.fn((_url: string, init?: RequestInit) => {
signal = init?.signal ?? undefined;
return Promise.resolve({ ok: true, status: 200, blob: () => stallUntilAbort<Blob>(signal) });
})
);
const pending = openFile('/uploads/files/half.pdf');
await vi.advanceTimersByTimeAsync(5000);
await pending;
expect(URL.createObjectURL).toHaveBeenCalledWith(stored);
expect(signal?.aborted).toBe(true);
});
it('still surfaces an HTTP error over the stored copy', async () => {
vi.mocked(getCachedBlob).mockResolvedValue(stored);
vi.stubGlobal('fetch', makeFetchMock(403));
await expect(downloadFile('/uploads/files/forbidden.pdf')).rejects.toThrow('HTTP 403');
expect(URL.createObjectURL).not.toHaveBeenCalled();
});
it('serves the stored copy when the connection breaks while the body arrives', async () => {
vi.mocked(getCachedBlob).mockResolvedValue(stored);
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue({ ok: true, status: 200, blob: () => Promise.reject(new TypeError('network')) })
);
await openFile('/uploads/files/broken.pdf');
expect(URL.createObjectURL).toHaveBeenCalledWith(stored);
});
it('surfaces a broken body read when nothing is stored', async () => {
vi.mocked(getCachedBlob).mockResolvedValue(null);
const broken = new TypeError('network');
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, status: 200, blob: () => Promise.reject(broken) }));
await expect(openFile('/uploads/files/broken.pdf')).rejects.toBe(broken);
expect(URL.createObjectURL).not.toHaveBeenCalled();
});
it('keeps waiting on the live download when nothing is stored', async () => {
vi.mocked(getCachedBlob).mockResolvedValue(null);
const live = new Blob(['live'], { type: 'application/pdf' });
let answer: ((resp: unknown) => void) | undefined;
let signal: AbortSignal | undefined;
vi.stubGlobal(
'fetch',
vi.fn((_url: string, init?: RequestInit) => {
signal = init?.signal ?? undefined;
return new Promise((resolve) => {
answer = resolve;
});
})
);
const pending = downloadFile('/uploads/files/slow.pdf');
const state = track(pending);
await vi.advanceTimersByTimeAsync(60_000);
expect(state.done).toBe(false);
expect(signal?.aborted).toBe(false);
answer?.({ ok: true, status: 200, blob: () => Promise.resolve(live) });
await pending;
expect(URL.createObjectURL).toHaveBeenCalledWith(live);
});
});
+10 -7
View File
@@ -5,10 +5,13 @@
*/ */
import { readFileSync } from 'node:fs'; import { readFileSync } from 'node:fs';
import { resolve } from 'node:path'; import { resolve } from 'node:path';
import { locationAt, pageUrl } from '../../helpers/location';
const SOURCE = readFileSync(resolve(process.cwd(), 'public/shell-guard.js'), 'utf8'); const SOURCE = readFileSync(resolve(process.cwd(), 'public/shell-guard.js'), 'utf8');
const ENTRY = '/assets/index-BZcJ9-lk.js'; const ENTRY = '/assets/index-BZcJ9-lk.js';
const MARKER = 'trek:shell-reload'; const MARKER = 'trek:shell-reload';
// Workbox names its precache after the scope the worker was registered for.
const PRECACHE = `workbox-precache-v2-${pageUrl('/')}`;
type Listener = [string, EventListenerOrEventListenerObject, boolean | AddEventListenerOptions | undefined]; type Listener = [string, EventListenerOrEventListenerObject, boolean | AddEventListenerOptions | undefined];
let listeners: Listener[] = []; let listeners: Listener[] = [];
@@ -51,21 +54,21 @@ interface Env {
deleted: string[]; deleted: string[];
} }
/** A page a service worker served, unless `controlled` is false. */ /** The page at `path`, one a service worker served unless `controlled` is false. */
function install(href = 'http://localhost/trips/4?tab=plan#day-2', controlled = true): Env { function install(path = '/trips/4?tab=plan#day-2', controlled = true): Env {
const replace = vi.fn(); const replace = vi.fn();
Object.defineProperty(window, 'location', { value: { ...window.location, href, replace }, writable: true, configurable: true }); Object.defineProperty(window, 'location', { value: locationAt(path, { replace }), writable: true, configurable: true });
const fetch = vi.fn(async () => healthAnswer(true, 'application/json; charset=utf-8')); const fetch = vi.fn(async () => healthAnswer(true, 'application/json; charset=utf-8'));
vi.stubGlobal('fetch', fetch); vi.stubGlobal('fetch', fetch);
const unregister = vi.fn(async () => true); const unregister = vi.fn(async () => true);
Object.defineProperty(navigator, 'serviceWorker', { Object.defineProperty(navigator, 'serviceWorker', {
value: { controller: controlled ? { scriptURL: 'http://localhost/sw.js' } : null, getRegistration: vi.fn(async () => ({ unregister })) }, value: { controller: controlled ? { scriptURL: pageUrl('/sw.js') } : null, getRegistration: vi.fn(async () => ({ unregister })) },
configurable: true, configurable: true,
}); });
const deleted: string[] = []; const deleted: string[] = [];
Object.defineProperty(globalThis, 'caches', { Object.defineProperty(globalThis, 'caches', {
value: { value: {
keys: vi.fn(async () => ['workbox-precache-v2-http://localhost/', 'map-tiles', 'gl-map-offline', 'user-uploads']), keys: vi.fn(async () => [PRECACHE, 'map-tiles', 'gl-map-offline', 'user-uploads']),
delete: vi.fn(async (name: string) => { deleted.push(name); return true; }), delete: vi.fn(async (name: string) => { deleted.push(name); return true; }),
}, },
configurable: true, configurable: true,
@@ -117,7 +120,7 @@ describe('shell-guard.js', () => {
expect(env.fetch).toHaveBeenCalledWith('/api/health', expect.objectContaining({ cache: 'no-store', redirect: 'manual' })); expect(env.fetch).toHaveBeenCalledWith('/api/health', expect.objectContaining({ cache: 'no-store', redirect: 'manual' }));
// Only the precache: offline map regions and cached uploads were downloaded on purpose. // Only the precache: offline map regions and cached uploads were downloaded on purpose.
expect(env.deleted).toEqual(['workbox-precache-v2-http://localhost/']); expect(env.deleted).toEqual([PRECACHE]);
expect(env.unregister).toHaveBeenCalledTimes(1); expect(env.unregister).toHaveBeenCalledTimes(1);
const target = new URL(env.replace.mock.calls[0][0] as string); const target = new URL(env.replace.mock.calls[0][0] as string);
expect(target.pathname + target.hash).toBe('/trips/4#day-2'); expect(target.pathname + target.hash).toBe('/trips/4#day-2');
@@ -191,7 +194,7 @@ describe('shell-guard.js', () => {
it('FE-SHELLGUARD-011: a page that came from the network is reloaded afresh and its worker kept', async () => { it('FE-SHELLGUARD-011: a page that came from the network is reloaded afresh and its worker kept', async () => {
// Nothing the worker keeps answered this load, so throwing it away would only // Nothing the worker keeps answered this load, so throwing it away would only
// cost the offline shell. // cost the offline shell.
const env = install('http://localhost/dashboard', false); const env = install('/dashboard', false);
runGuard(); runGuard();
fail(moduleScript(ENTRY)); fail(moduleScript(ENTRY));
await vi.waitFor(() => expect(env.replace).toHaveBeenCalledTimes(1)); await vi.waitFor(() => expect(env.replace).toHaveBeenCalledTimes(1));
+7 -6
View File
@@ -21,11 +21,12 @@
# superuser trek; the wiki page Database-Postgres ("Moving a compose install # superuser trek; the wiki page Database-Postgres ("Moving a compose install
# off the superuser") shows how to move it to this layout. # off the superuser") shows how to move it to this layout.
# #
# The database runs PostgreSQL 18. TREK supports 14 to 18: to run 14 to 17, # The database runs PostgreSQL 18. TREK supports 14 to 19: a new database
# change the image tag and mount the volume at /var/lib/postgresql/data # may run postgres:19 on the same volume path. To run 14 to 17, change the
# instead, where those images keep their data (the 18 image refuses that # image tag and mount the volume at /var/lib/postgresql/data instead, where
# path). An existing database stays on the major it was created with: when # those images keep their data (the 18 and 19 images refuse that path). An
# you update this file, keep your image tag and volume path. Moving to # existing database stays on the major it was created with: when you update
# this file, keep your image tag and volume path. Moving to
# another major needs pg_upgrade, or a dump and restore (a TREK backup # another major needs pg_upgrade, or a dump and restore (a TREK backup
# restored into a new, empty database of the same or a newer major), never # restored into a new, empty database of the same or a newer major), never
# just a new image tag. # just a new image tag.
@@ -46,7 +47,7 @@ services:
- no-new-privileges:true - no-new-privileges:true
# No ports are published: only the trek service on the compose network reaches the database. # No ports are published: only the trek service on the compose network reaches the database.
volumes: volumes:
# The path the postgres:18 image expects. Images 14 to 17 need # The path the postgres:18 and :19 images expect. Images 14 to 17 need
# /var/lib/postgresql/data here (see the top of this file). # /var/lib/postgresql/data here (see the top of this file).
- trek-pgdata:/var/lib/postgresql - trek-pgdata:/var/lib/postgresql
healthcheck: healthcheck:
File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 16 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 16 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 24 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 24 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 33 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 33 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 32 KiB

+1104 -1573
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "@trek/root", "name": "@trek/root",
"private": true, "private": true,
"version": "5.2.0", "version": "5.2.1",
"engines": { "engines": {
"node": "^22.22.2 || ^24.15.0 || >=26.0.0" "node": "^22.22.2 || ^24.15.0 || >=26.0.0"
}, },
+148
View File
@@ -0,0 +1,148 @@
#!/usr/bin/env node
// The Android app as an APK outside Google Play, for Obtainium and the like.
//
// native-release.yml uploads each Android build to Google Play, which signs it
// with the app signing key only Google holds. Google Play also builds a
// universal APK of that bundle, signed with the same key. This script fetches
// that APK, so the copy published in liketrek/trek-android carries the very
// signature of the Play install: a phone can move between the two without
// uninstalling, and Play Billing and push work in it wherever Google Play
// services do.
//
// guard <features.controller.ts of the latest server release>
// Whether this build may go out now. The app refuses a server older than
// its MIN_NATIVE_API (client/src/native/serverAddress.ts), and a build can
// be cut from dev before the server it needs is released. It may go out
// once the latest server release answers a nativeApi at least that high
// (its server/src/nest/health/features.controller.ts, which the workflow
// writes out with git show). Prints publish=true or publish=false, for
// $GITHUB_OUTPUT.
//
// download <service account json> <package> <version code> <out.apk>
// Asks the Play Developer API for the universal APK of that version code,
// waiting a while for Google to generate it, and writes it to <out.apk>.
//
// No secret is printed: the service account file is read, not echoed.
import { createSign } from 'node:crypto';
import { readFileSync, writeFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
const APP_MIN_FILE = 'client/src/native/serverAddress.ts';
const SERVER_API_FILE = 'server/src/nest/health/features.controller.ts';
const API = 'https://androidpublisher.googleapis.com/androidpublisher/v3/applications';
const REQUEST_TIMEOUT_MS = 30_000;
const APK_TIMEOUT_MS = 5 * 60_000;
const WAIT_STEPS_MS = [15_000, 30_000, 60_000, 120_000, 240_000];
const MAX_APK_BYTES = 400 * 1024 * 1024;
/** The app's MIN_NATIVE_API in the source of serverAddress.ts; throws when it cannot be read. */
export function appMinimumApi(source) {
const found = /\bconst MIN_NATIVE_API = (\d+);/.exec(source);
if (!found) throw new Error(`MIN_NATIVE_API not found in ${APP_MIN_FILE}`);
return Number(found[1]);
}
/** The nativeApi the server answers in the source of features.controller.ts; throws when it cannot be read. */
export function serverApi(source) {
const found = /\bnativeApi: (\d+),/.exec(source);
if (!found) throw new Error(`nativeApi not found in ${SERVER_API_FILE}`);
return Number(found[1]);
}
/** Whether a build that needs `appMinimum` may go out while the newest server release answers `released`. */
export function mayPublish(appMinimum, released) {
return released >= appMinimum;
}
function guard(releasedFeatures) {
const appMinimum = appMinimumApi(readFileSync(APP_MIN_FILE, 'utf8'));
const released = serverApi(readFileSync(releasedFeatures, 'utf8'));
const publish = mayPublish(appMinimum, released);
console.error(`the app needs native API ${appMinimum}, the latest release answers ${released}: ${publish ? 'publish' : 'hold back'}`);
console.log(`publish=${publish}`);
}
const b64url = (value) => Buffer.from(typeof value === 'string' ? value : JSON.stringify(value)).toString('base64url');
async function accessToken(account) {
const now = Math.floor(Date.now() / 1000);
const unsigned = `${b64url({ alg: 'RS256', typ: 'JWT' })}.${b64url({
iss: account.client_email,
scope: 'https://www.googleapis.com/auth/androidpublisher',
aud: account.token_uri,
iat: now,
exp: now + 600,
})}`;
const signature = createSign('RSA-SHA256').update(unsigned).sign(account.private_key).toString('base64url');
const response = await fetch(account.token_uri, {
method: 'POST',
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
headers: { 'content-type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
assertion: `${unsigned}.${signature}`,
}),
});
const body = await response.json();
if (!response.ok || typeof body.access_token !== 'string') {
throw new Error(`Google refused the service account: HTTP ${response.status} ${body.error ?? ''}`);
}
return body.access_token;
}
/** The download id of the universal APK in a generatedApks.list answer, or null while Google has none yet. */
export function universalDownloadId(answer) {
for (const generated of answer?.generatedApks ?? []) {
const id = generated?.generatedUniversalApk?.downloadId;
if (typeof id === 'string' && id.length > 0) return id;
}
return null;
}
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function download(accountFile, pkg, versionCode, out) {
if (!/^[\w.]+$/.test(pkg) || !/^\d+$/.test(versionCode)) throw new Error('package or version code malformed');
const token = await accessToken(JSON.parse(readFileSync(accountFile, 'utf8')));
const headers = { authorization: `Bearer ${token}` };
const base = `${API}/${pkg}/generatedApks/${versionCode}`;
let id = null;
for (let attempt = 0; id === null; attempt++) {
const response = await fetch(base, { headers, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
const body = await response.json();
// 404 while Google has not processed the bundle yet; anything else is final.
if (!response.ok && response.status !== 404) {
throw new Error(`generatedApks.list: HTTP ${response.status} ${body.error?.message ?? ''}`);
}
id = response.ok ? universalDownloadId(body) : null;
if (id === null) {
if (attempt >= WAIT_STEPS_MS.length) throw new Error(`no universal APK for version code ${versionCode} yet`);
console.error(`waiting for Google to build the universal APK of ${versionCode}`);
await sleep(WAIT_STEPS_MS[attempt]);
}
}
const response = await fetch(`${base}/downloads/${encodeURIComponent(id)}:download?alt=media`, {
headers,
signal: AbortSignal.timeout(APK_TIMEOUT_MS),
});
if (!response.ok) throw new Error(`generatedApks.download: HTTP ${response.status}`);
const apk = Buffer.from(await response.arrayBuffer());
// An APK is a zip archive; anything else is an error page.
if (apk.length > MAX_APK_BYTES || apk.subarray(0, 2).toString('latin1') !== 'PK') {
throw new Error(`the download is not an APK (${apk.length} bytes)`);
}
writeFileSync(out, apk);
console.error(`wrote ${out} (${apk.length} bytes)`);
}
if (process.argv[1] === fileURLToPath(import.meta.url)) {
const [command, ...args] = process.argv.slice(2);
try {
if (command === 'guard' && args.length === 1) guard(args[0]);
else if (command === 'download' && args.length === 4) await download(...args);
else throw new Error('usage: android-apk-release.mjs guard <features.controller.ts> | download <account.json> <package> <code> <out.apk>');
} catch (err) {
console.error(`::error::${err instanceof Error ? err.message : String(err)}`);
process.exit(1);
}
}
+39
View File
@@ -0,0 +1,39 @@
import { appMinimumApi, mayPublish, serverApi, universalDownloadId } from './android-apk-release.mjs';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { describe, it } from 'node:test';
import { fileURLToPath } from 'node:url';
const read = (path) => readFileSync(fileURLToPath(new URL(`../../${path}`, import.meta.url)), 'utf8');
describe('android-apk-release', () => {
it('reads the native API the app needs and the one the server answers from the real files', () => {
const appMinimum = appMinimumApi(read('client/src/native/serverAddress.ts'));
const answered = serverApi(read('server/src/nest/health/features.controller.ts'));
assert.ok(Number.isInteger(appMinimum) && appMinimum >= 1);
// A commit never needs more than the server it ships with.
assert.ok(answered >= appMinimum);
});
it('refuses to guess when a constant moved', () => {
assert.throws(() => appMinimumApi('export const MIN_API = 3;'), /MIN_NATIVE_API not found/);
assert.throws(() => serverApi('nativeApi = 3'), /nativeApi not found/);
});
it('holds back a build that needs a server not released yet', () => {
assert.equal(mayPublish(3, 3), true);
assert.equal(mayPublish(3, 4), true);
assert.equal(mayPublish(4, 3), false);
});
it('finds the universal APK in a generatedApks answer, and nothing in one without it', () => {
assert.equal(
universalDownloadId({ generatedApks: [{ generatedSplitApks: [{}] }, { generatedUniversalApk: { downloadId: 'abc' } }] }),
'abc',
);
assert.equal(universalDownloadId({ generatedApks: [{ generatedSplitApks: [{}] }] }), null);
assert.equal(universalDownloadId({}), null);
assert.equal(universalDownloadId(null), null);
});
});
+2 -2
View File
@@ -52,8 +52,8 @@ DEMO_MODE=false # Demo mode: resets data hourly
# BACKUP_MAX_DECOMPRESSED_MB=5120 # Max size (MB) a restore archive may unpack to, on both restore paths: the zip-bomb guard. Raise it if a large backup is refused with "Backup exceeds the maximum decompressed size". (default: 5120) # BACKUP_MAX_DECOMPRESSED_MB=5120 # Max size (MB) a restore archive may unpack to, on both restore paths: the zip-bomb guard. Raise it if a large backup is refused with "Backup exceeds the maximum decompressed size". (default: 5120)
# BACKUP_UPLOAD_LIMIT_MB=500 # Max size (MB) of a backup archive you can upload when restoring. Raise it if your backup exceeds 500 MB. If you sit behind a reverse proxy, raise its upload limit too (e.g. nginx client_max_body_size). # BACKUP_UPLOAD_LIMIT_MB=500 # Max size (MB) of a backup archive you can upload when restoring. Raise it if your backup exceeds 500 MB. If you sit behind a reverse proxy, raise its upload limit too (e.g. nginx client_max_body_size).
# TREK_DB_URL=postgres://trek:password@db:5432/trek # Run on a Postgres database instead of the SQLite file in data/. TREK creates its schema in an empty database and refuses one holding tables it did not create. sslmode=disable, require, verify-ca or verify-full (the last three always verify the certificate; sslrootcert= names the CA file). Cannot be combined with TREK_DB_FILE, TREK_DB_JOURNAL_MODE or TREK_DB_SYNCHRONOUS. # TREK_DB_URL=postgres://trek:password@db:5432/trek # Run on a Postgres database instead of the SQLite file in data/. TREK creates its schema in an empty database and refuses one holding tables it did not create. sslmode=disable, require, verify-ca or verify-full (the last three always verify the certificate; sslrootcert= names the CA file). For a server that asks for a client certificate, sslcert= and sslkey= name the certificate and its key file, both together and only with a verifying sslmode. A Unix socket: postgresql://trek@localhost/trek?host=/var/run/postgresql (a host= or port= parameter takes the place of the URL's own, as in libpq). Cannot be combined with TREK_DB_FILE, TREK_DB_JOURNAL_MODE or TREK_DB_SYNCHRONOUS.
# TREK_DB_PG_BIN_DIR=/usr/lib/postgresql/18/bin # The directory holding pg_dump, pg_restore and psql, which back up and restore a Postgres database. Unset, TREK looks in /usr/lib/postgresql/<18..14>/bin, newest first, then /usr/local/bin and /usr/bin (the Docker image installs the version 18 tools, which work with every supported server; tools older than the server are refused). Unused on SQLite. # TREK_DB_PG_BIN_DIR=/usr/lib/postgresql/19/bin # The directory holding pg_dump, pg_restore and psql, which back up and restore a Postgres database. Unset, TREK looks in /usr/lib/postgresql/<19..14>/bin, newest first, then /usr/local/bin and /usr/bin (the Docker image installs the version 19 tools, which work with every supported server; tools older than the server are refused). Unused on SQLite.
# TREK_DB_POOL_MAX=10 # Most connections TREK opens to the Postgres database (1 to 100). Unused on SQLite. (default: 10) # TREK_DB_POOL_MAX=10 # Most connections TREK opens to the Postgres database (1 to 100). Unused on SQLite. (default: 10)
# TREK_DB_JOURNAL_MODE=WAL # SQLite journal mode (DELETE, TRUNCATE, PERSIST, MEMORY, WAL, OFF). WAL is fastest and the right choice on local disk. Set DELETE if the data directory lives on network storage (Azure App Service, an SMB/NFS volume on a NAS) — WAL coordinates writers through a shared-memory file that those filesystems do not implement reliably. The mode is stored inside the database file, so it survives a restart; changing this applies on the next boot. # TREK_DB_JOURNAL_MODE=WAL # SQLite journal mode (DELETE, TRUNCATE, PERSIST, MEMORY, WAL, OFF). WAL is fastest and the right choice on local disk. Set DELETE if the data directory lives on network storage (Azure App Service, an SMB/NFS volume on a NAS) — WAL coordinates writers through a shared-memory file that those filesystems do not implement reliably. The mode is stored inside the database file, so it survives a restart; changing this applies on the next boot.
# TREK_DB_PRE_MIGRATE_SNAPSHOT=true # Copy the database to data/pre-migrate-<schema>-<time>.db (a .pgdump made with pg_dump on Postgres) before a startup migrates it, so the previous image can run on the copy again. A copy that cannot be written stops the startup; false migrates without one. # TREK_DB_PRE_MIGRATE_SNAPSHOT=true # Copy the database to data/pre-migrate-<schema>-<time>.db (a .pgdump made with pg_dump on Postgres) before a startup migrates it, so the previous image can run on the copy again. A copy that cannot be written stops the startup; false migrates without one.
+3 -3
View File
File diff suppressed because one or more lines are too long
+26 -24
View File
@@ -1,6 +1,6 @@
{ {
"name": "@trek/server", "name": "@trek/server",
"version": "5.2.0", "version": "5.2.1",
"engines": { "engines": {
"node": "^22.22.2 || ^24.15.0 || >=26.0.0" "node": "^22.22.2 || ^24.15.0 || >=26.0.0"
}, },
@@ -65,42 +65,43 @@
"dependencies": { "dependencies": {
"@aws-lite/client": "^0.24.1", "@aws-lite/client": "^0.24.1",
"@aws-lite/s3": "^0.2.7", "@aws-lite/s3": "^0.2.7",
"@mikro-orm/cli": "^7.2.7", "@mikro-orm/cli": "^7.2.12",
"@mikro-orm/core": "^7.2.7", "@mikro-orm/core": "^7.2.12",
"@mikro-orm/migrations": "^7.2.7", "@mikro-orm/migrations": "^7.2.12",
"@mikro-orm/nestjs": "^7.1.0", "@mikro-orm/nestjs": "^7.1.0",
"@mikro-orm/postgresql": "^7.2.7", "@mikro-orm/postgresql": "^7.2.12",
"@mikro-orm/seeder": "^7.2.7", "@mikro-orm/seeder": "^7.2.12",
"@mikro-orm/sql": "^7.2.1", "@mikro-orm/sql": "^7.2.12",
"@mikro-orm/sqlite": "^7.2.7", "@mikro-orm/sqlite": "^7.2.12",
"@modelcontextprotocol/sdk": "^1.32.2", "@modelcontextprotocol/sdk": "^1.32.2",
"@nestjs/common": "^11.2.5", "@nestjs/common": "^11.2.12",
"@nestjs/config": "^4.0.4", "@nestjs/config": "^4.0.4",
"@nestjs/core": "^11.2.5", "@nestjs/core": "^11.2.12",
"@nestjs/platform-express": "^11.2.5", "@nestjs/platform-express": "^11.2.12",
"@nestjs/platform-ws": "^11.2.5", "@nestjs/platform-ws": "^11.2.12",
"@nestjs/schedule": "^12.0.4", "@nestjs/schedule": "^12.0.4",
"@nestjs/swagger": "^11.4.7", "@nestjs/swagger": "^11.4.8",
"@nestjs/websockets": "^11.2.5", "@nestjs/websockets": "^11.2.12",
"@simplewebauthn/server": "^13.3.3", "@simplewebauthn/server": "^14.1.0",
"@trek/shared": "*", "@trek/shared": "*",
"archiver": "^6.0.2", "archiver": "^6.0.2",
"bcryptjs": "^2.4.3", "bcryptjs": "^2.4.3",
"better-sqlite3": "^13.0.3", "better-sqlite3": "^13.2.0",
"compression": "^1.8.2", "compression": "^1.8.2",
"cookie-parser": "^1.4.7", "cookie-parser": "^1.4.7",
"cors": "^2.8.6", "cors": "^2.8.6",
"cron": "^4.4.0", "cron": "^4.4.0",
"dotenv": "^18.0.10", "dotenv": "^18.0.10",
"exifr": "7.1.3", "exifr": "7.1.3",
"express": "^4.22.3", "express": "^5.3.0",
"fast-xml-parser": "^5.12.1", "fast-xml-parser": "^5.12.1",
"helmet": "^8.3.0", "helmet": "^8.3.0",
"imapflow": "^1.0.0", "imapflow": "^1.0.0",
"jimp": "^1.6.1", "jimp": "^1.7.0",
"json5": "^2.2.3", "json5": "^2.2.3",
"jsonwebtoken": "^9.0.3", "jsonwebtoken": "^9.0.3",
"kysely": "^0.29.6", "kysely": "^0.29.9",
"mime-types": "^3.0.2",
"multer": "^2.5.0", "multer": "^2.5.0",
"nestjs-zod": "^5.6.0", "nestjs-zod": "^5.6.0",
"nodemailer": "^10.6.1", "nodemailer": "^10.6.1",
@@ -124,8 +125,8 @@
"devDependencies": { "devDependencies": {
"@aws-lite/s3-types": "^0.2.8", "@aws-lite/s3-types": "^0.2.8",
"@eslint/js": "^10.0.1", "@eslint/js": "^10.0.1",
"@mikro-orm/entity-generator": "^7.2.7", "@mikro-orm/entity-generator": "^7.2.12",
"@nestjs/testing": "^11.2.5", "@nestjs/testing": "^11.2.12",
"@swc/core": "^1.16.22", "@swc/core": "^1.16.22",
"@trivago/prettier-plugin-sort-imports": "^6.0.2", "@trivago/prettier-plugin-sort-imports": "^6.0.2",
"@types/archiver": "^7.0.0", "@types/archiver": "^7.0.0",
@@ -134,10 +135,11 @@
"@types/compression": "^1.8.1", "@types/compression": "^1.8.1",
"@types/cookie-parser": "^1.4.10", "@types/cookie-parser": "^1.4.10",
"@types/cors": "^2.8.19", "@types/cors": "^2.8.19",
"@types/express": "^4.17.25", "@types/express": "^5.0.6",
"@types/jsonwebtoken": "^9.0.10", "@types/jsonwebtoken": "^9.0.10",
"@types/mime-types": "^3.0.1",
"@types/multer": "^2.3.0", "@types/multer": "^2.3.0",
"@types/node": "^25.9.8", "@types/node": "^26.6.11",
"@types/nodemailer": "^8.0.2", "@types/nodemailer": "^8.0.2",
"@types/qrcode": "^1.5.6", "@types/qrcode": "^1.5.6",
"@types/semver": "^7.8.0", "@types/semver": "^7.8.0",
@@ -151,7 +153,7 @@
"prettier": "^3.10.1", "prettier": "^3.10.1",
"prettier-plugin-organize-imports": "^4.3.0", "prettier-plugin-organize-imports": "^4.3.0",
"supertest": "^7.3.1", "supertest": "^7.3.1",
"typescript-eslint": "^8.72.1", "typescript-eslint": "^8.73.0",
"unplugin-swc": "^1.6.0", "unplugin-swc": "^1.6.0",
"vitest": "^4.1.11" "vitest": "^4.1.11"
} }
+1 -1
View File
@@ -5,7 +5,7 @@
"@typescript-eslint/no-require-imports": 18, "@typescript-eslint/no-require-imports": 18,
"@typescript-eslint/no-unsafe-function-type": 1, "@typescript-eslint/no-unsafe-function-type": 1,
"@typescript-eslint/no-unused-vars": 34, "@typescript-eslint/no-unused-vars": 34,
"no-await-in-loop": 556, "no-await-in-loop": 555,
"no-console": 231, "no-console": 231,
"no-empty": 6 "no-empty": 6
}, },
+1 -1
View File
@@ -13,7 +13,7 @@
"src/nest/doc-sync/providers/synology-drive.client.ts": 1160, "src/nest/doc-sync/providers/synology-drive.client.ts": 1160,
"src/nest/journey/journey-domain.service.ts": 1659, "src/nest/journey/journey-domain.service.ts": 1659,
"src/nest/places/places.service.ts": 1546, "src/nest/places/places.service.ts": 1546,
"src/nest/plugins/plugin-runtime.service.ts": 1459, "src/nest/plugins/plugin-runtime.service.ts": 1458,
"src/nest/plugins/runtime/plugin-sdk.ts": 1093, "src/nest/plugins/runtime/plugin-sdk.ts": 1093,
"src/nest/reservations/reservations.service.ts": 1163, "src/nest/reservations/reservations.service.ts": 1163,
"src/nest/vacay/vacay.service.ts": 1393 "src/nest/vacay/vacay.service.ts": 1393

Some files were not shown because too many files have changed in this diff Show More