Compare commits

...

361 Commits

Author SHA1 Message Date
Maurice f1d8995d66 chore(deps): hold typescript-eslint at 8.72, lower the knip baseline
typescript-eslint 8.74 reports more no-unused-vars and lifts the client
warning count past its baseline; it gets its own round. knip 6.48 finds
two fewer unused exports and types, so their entries go down with it.
2026-11-23 21:57:06 +01:00
Maurice aab09afc53 fix(notices): pass the Patreon handler in the modal test, logical sides in the card drawings, no non-null assertions 2026-11-23 21:25:39 +01:00
Maurice 34e28d082d chore(deps): bump the npm minor and patch group, MikroORM held
Takes Dependabot's group update except MikroORM, which stays on 7.2.8:
7.2.9 broke the Postgres probe on OauthTokens.insertToken and
OauthConsents.upsertGrant, and 7.2.11 gets its own round. The rollup
musl pins stay with the rollup version the lockfile resolves. The
Playwright container moves to v1.65.1-noble with its digest, as the
lockfile now pins @playwright/test 1.65.1.
2026-11-23 21:19:18 +01:00
Maurice e6d682b99e chore(plugin-sdk): bump the plugin-sdk minor and patch group 2026-11-23 21:19:17 +01:00
Maurice cb1d400251 ci: bump docker/scout-action from 1.29.0 to 1.30.0 2026-11-23 21:19:17 +01:00
Maurice bcdcd69a64 feat(notices): 5.2.0 release modal and Patreon for monthly support
The release modal now shows 5.2.0: booking mails that land in the trip,
live flight status and the new trip PDF, each with its own drawn card,
and links the 5.2.0 release notes. The maintainer note and the support
block are rewritten, shorter and without the sponsor wording.

Patreon joins Buy Me a Coffee and Ko-fi as the monthly way to support
TREK: a full-width button in the release and thank-you notices (a new
optional tertiaryCta on the notice contract), a tile in About and in the
admin GitHub panel on desktop and phone, the README badges and
FUNDING.yml. Like the other donation links it stays hidden inside the
native apps.
2026-11-23 21:15:54 +01:00
Maurice d18a4b2180 fix(flight-live): keep a late inbound aircraft holding near the origin from reading as departed
After the scheduled time an aircraft near the origin that neither climbs nor descends is taken for the leg only when it was on the ground at the origin before or flies away from it.
2026-11-23 20:02:10 +01:00
Maurice 4519430610 fix(plugins): bind the single-array args form on Postgres as on SQLite
A plugin that passed its values as one array had the whole array bound to $1 on Postgres. The array is now spread when it fills the statement's placeholders, unless a placeholder takes an array itself.
2026-11-23 19:59:41 +01:00
Maurice b3845dbdfc fix(memories): wait for a public media copy just under the proxy timeout
No public page retries a 503 by itself, so a first view of a large video that took over 10 s showed a dead player. The request now waits up to 50 s before answering come back later.
2026-11-23 19:57:47 +01:00
Maurice e6a5ba095d docs(postgres): a backup restores into the same or a newer major only
The restore now refuses a dump from a newer PostgreSQL major, so the guide and the compose file no longer promise restores across every major.
2026-11-23 19:57:21 +01:00
Maurice 7a643d5f75 feat(plugin-sdk): let the mock host switch Documents off like the real host
With documentsAddonEnabled: false, files.* works only on attached files and files.create needs a link target, so a plugin's tests see what the host does on a trip with Documents off. The plugin guide says the same.
2026-11-23 19:57:20 +01:00
Maurice 4498f68cc9 fix(mcp): end live sessions again when documents is switched off
The doc-sync tools still gate on documents through instanceAddonGate, which the parity scan did not see, so documents is back on the list and the scan now reads that gate too.
2026-11-23 19:56:08 +01:00
Maurice 429a2fb017 fix(help): leave the guides a managed install cannot follow out of its help
A managed install offers no connection to a server the reader runs (photo libraries, AirTrail, Dawarich, wanderer) and no assistant or AI setup of its own, so the help no longer shows their guides there.
2026-11-23 19:55:53 +01:00
Maurice 07eeae8486 fix(dashboard): name Etc/GMT world clocks by their real offset
An Etc/GMT zone counts westward as positive, so Etc/GMT-4 is four hours ahead of UTC. The clock's title and the zone picker printed the id's own sign, and someone who picked GMT+4 got a clock four hours behind UTC; both now read the real offset, on the desktop and the phone.

Closes #3175
2026-11-23 19:42:40 +01:00
Maurice c8adf6e1da ci(client): give the client typecheck the heap the strict check already has
The whole program outgrew Node's default heap and the typecheck ran out of memory.
2026-11-23 19:40:15 +01:00
Maurice 44c7026e74 feat(i18n): translate the updated help center into every locale 2026-11-23 19:30:08 +01:00
Maurice b185375762 feat(help): bring every help center guide up to date and add guides for the new features
Every guide was checked against the current app, its text and script corrected where the UI had moved on, and its pictures rendered again in the library's style. New guides cover the trip assistant and setting up AI, tags on places, KML for Google My Maps, totals-only costs, split by shares, costs in another currency, receipts from trip files, per-trip addons, editing the trip in Trip settings, booking mails and their notices, live flight status, the collections map lock, album date ranges, the journey satellite layer, the folding place card, a tour's route in a map app and more.
2026-11-23 19:30:07 +01:00
Maurice ea8202948d chore(help-media): let many media runs share one built client
E2E_WEB_PREVIEW serves client/dist with vite preview instead of a dev server per run; a dozen dev servers compiling the app at once timed out the setup login. The README also notes that mocked services need page.context().route once the service worker controls the page.
2026-11-23 19:30:05 +01:00
Maurice 7065e18454 fix(memories): answer 503 while a large public copy is still being made
A request now waits at most ten seconds for the location-free copy and is otherwise told to come back with Retry-After while the copy goes on being made, so a long video no longer holds the first request past a reverse proxy's timeout. Nothing but the copy is ever sent.
2026-11-23 17:33:00 +01:00
Maurice c4326ec545 fix(backup): refuse a Postgres dump from a newer server major before restoring it
The restore reads the server version the dump was taken from in its table of contents and refuses, naming both majors, before anything is cleared, from the admin restore (400) and from RESTORE_FROM_BACKUP alike.
2026-11-23 17:33:00 +01:00
Maurice b03597957c fix(db): let the primary key index serve MikroORM find orders on Postgres
A find ordered by its entity's own primary key now renders the NULL position the btree holds, so ORDER BY id DESC LIMIT n reads the index instead of sorting every matching row. A key is never NULL, so the rows come back in the same order.
2026-11-23 17:33:00 +01:00
Maurice 97da0c5ba6 fix(plugins): send file events for attached files while Documents is off
A file that belongs to a booking, place, expense, note or message stays readable with Documents off, so its events now reach subscribed plugins too; loose files still wait for Documents, and a trip's events keep their order.
2026-11-23 17:30:23 +01:00
Maurice e1147504c2 fix(files): refuse a plugin upload that attaches nothing while Documents is off
files.list hides loose files on such a trip, so files.create now needs a reservation_id or place_id there instead of writing a file the plugin cannot list back.
2026-11-23 17:20:52 +01:00
Maurice b2ba89fe4f fix(immich): keep a public video's location check across its range requests
The verdict is held for five minutes per owner and asset, so a seek no longer asks Immich twice before it streams, and an Immich that times out or fails answers 502 instead of 404. A located video Immich did not transcode still never plays.
2026-11-23 17:18:25 +01:00
Maurice eb32eb1690 fix(flight-live): take a departure near the origin without a vertical rate
After the scheduled time an airborne aircraft within 60 km of the origin is the leg unless it is clearly descending, so a level climb-out or a feed without rates still records departed_at and the delay.
2026-11-23 17:15:56 +01:00
Maurice 5588b7efbb fix(dawarich): read unnamed stays again in turns across runs
Each run now goes on after the last unnamed stay it read, so stays beyond the first twenty get their reread even when the first ones never resolve.
2026-11-23 17:13:57 +01:00
Maurice 20c86f3a44 refactor(auth): hand the trip tags over through the trip members repository
Kept out of MaintenanceRepository, whose raw SQL strings are pinned.
2026-11-23 16:44:45 +01:00
Maurice 3cef8eae5e chore(native): keep the page script list private to the offline shell 2026-11-23 16:41:11 +01:00
Maurice 6e0c2b894d refactor(auth): hand a deleted user's trip tags over through the maintenance repository
The account deletion no longer reaches into the tags domain, which closed an import cycle between the two.
2026-11-23 16:34:51 +01:00
Maurice 0fe536bbd2 fix(mcp): type the input refusal as the Error it is, so the strict build reads it 2026-11-23 16:29:35 +01:00
Maurice 96fa7ca4e8 refactor(server): keep the fixes within the size and strict ratchets
The admin settings audit summary moves to auth.helpers, the booking stay check to DayAccommodationsRepository.idOnTrip, the strict typings declare the MCP SDK types module, and the useAdmin test leaves the format baseline.
2026-11-23 16:23:21 +01:00
Maurice 8a9f5367b1 chore(lint): keep the fixes within the lint ratchets
No promise in a condition, sequential awaits through a reduce instead of a loop, no non-null assertions or any in the new tests, an awaited act, one options object for a stop edit and a handled rejection for the offline copy.
2026-11-23 16:09:59 +01:00
Maurice f6d52727f7 test(mcp): follow the mail tools and file tools that left their addon gates
Documents leaves the list of addons whose switch ends MCP sessions, since no tool waits for it any more.
2026-11-23 16:04:29 +01:00
Maurice 38381bc03a refactor(costs): let the summary card tell an unknown balance itself
Keeps the Costs panel within its size budget.
2026-11-23 16:02:38 +01:00
Maurice af88aef35e fix(server): resolve the MCP SDK types module at runtime
The tool registry imports McpError from @modelcontextprotocol/sdk/types, which Node only finds through the tsconfig path list the other SDK modules use.
2026-11-23 16:02:37 +01:00
Maurice 0aa53b81e1 docs(wiki): say when a public journey link plays an Immich video 2026-11-23 15:54:13 +01:00
Maurice 4b6911b51f fix(plugins): bind a Buffer in the single-array bind form of ctx.db as its bytes 2026-11-23 15:53:58 +01:00
Maurice 907fc95b00 fix(plugins): let a file write past Documents off only for the targets it writes
files.update and files.createLink took any target key in the call as an attachment, also one they never store.
2026-11-23 15:53:58 +01:00
Maurice 1c6bdb4129 fix(immich): keep a shared journey from streaming an Immich video original with its location
A public link now plays an Immich video only when the asset has no recorded location or Immich serves its own transcode, which it writes without metadata; the original file of a located video is refused with a 404.
2026-11-23 15:45:28 +01:00
Maurice 503b82a149 docs(wiki): say key rotation re-encrypts Wanderer tokens and where the key file goes
The rotation script has covered wanderer_connections.token since it learned to, and writes the key file beside a DB_PATH database or else into the data directory; the page now says so.
2026-11-23 15:45:28 +01:00
Maurice 8349c5066b fix(dawarich): name stays never read before reading unnamed ones again
Unnamed stays are now read again at the end of a run, from the budget the others left and at most 20 per window, so new stays get their names and a Dawarich without a geocoder is not asked about every stay on each run.
2026-11-23 15:45:28 +01:00
Maurice 5e8cc0b90a fix(mail-ingest): read a transfer booking with a numeric code instead of filing it as a forwarding confirmation
Outside Gmail and Outlook senders, only a subject naming mail forwarding counts, so a bare 'transfert' in a shuttle or airport transfer confirmation no longer hides the booking.
2026-11-23 15:45:27 +01:00
Maurice 950942f7b9 fix(backup): refuse a Postgres restore of another schema or past the size limit with a 400
The admin restore now writes and checks the restore script while it verifies the archive, so a dump without TREK's tables in the target schema or one expanding past BACKUP_MAX_DECOMPRESSED_MB is refused before a pre-restore copy is kept, and the restore runs the checked script.
2026-11-23 15:45:27 +01:00
Maurice ac5c91bcaf fix(plugins): bind a Buffer a plugin passes to its own database as bytes
A Buffer crosses the plugin IPC as its JSON form, so db.query, db.exec and db.tx now turn that form back into the bytes before binding, as the plugin docs promise.
2026-11-23 15:45:27 +01:00
Maurice 10f0cb7d04 fix(flight-live): keep a late earlier sector from reading as this flight departing
Until a leg has departed, an aircraft in the air that is no nearer the destination than the origin is now stays the earlier sector's after the scheduled departure too, unless it is climbing out near the origin.
2026-11-23 15:45:27 +01:00
Maurice 08f3a8fe0b fix(flight-live): tell each booking of a flight its own delay once it is late
Bookings sharing a tracked flight can hold different departure times, so the delay notice now goes to each booking when its own delay crosses the line instead of being spent on the first one.
2026-11-23 15:45:27 +01:00
Maurice 091ad0f23d fix(collab): keep the keyboard open after sending a chat message
The send button in the trip chat cancels its mousedown like the note format bar, so the native app no longer closes the keyboard after every message.
2026-11-23 15:45:26 +01:00
Maurice 2b21407cf9 fix(admin): open the tab a link names while the admin page is already open
The active tab now follows ?tab= when only the query changes, so a help guide's go to screen link reaches the Services tab from the Security tab.
2026-11-23 15:45:26 +01:00
Maurice 464d5aa902 fix(native-share): read every trip's Collaboration when the share sheet opens and keep it settled
A Collaboration switch on a trip not open on this device now counts for a shared link, and a later reload of a trip's list no longer hides the trips or saves a refused link again.
2026-11-23 15:45:26 +01:00
Maurice b9637ff90c fix(trip-addons): let a second reader wait for the trip's list being read
A read started while another one runs now answers with that read's list instead of the one held before, so the offline sync no longer skips the Tours and Road trip caches next to a planner load.
2026-11-23 15:45:26 +01:00
Maurice 918efe35fe fix(costs): show the owe and owed cards as unknown instead of settled while the balances are
A failed read, a read still running or flows in another currency no longer print zero with the settled line on desktop and phone. Flows the server answered in the trip currency are converted at the rate the read sent along.
2026-11-23 15:45:26 +01:00
Maurice a0c41bce0a fix(notifications): list the wanderer hints for users whose trip switched Tours on
The user's matrix decides that row by the same per-user Tours rule the wanderer watch sends by, so a user who gets the hints can see and switch them.
2026-11-23 15:45:25 +01:00
Maurice 1a6639eb74 fix(trips): end a plugin-added member's MCP sessions where the trip opened an addon
trips.addMember now calls reattachJoinedMember like the REST, MCP and invite joins, so the new member's session lists the trip's addon tools.
2026-11-23 15:45:25 +01:00
Maurice 807c6a16b4 fix(plugins): handle a failed addon read while an earlier trip event still waits
The addon read of a queued plugin event now settles to off on its own, so a rejection that comes before the earlier event's turn can no longer go unhandled and stop the server.
2026-11-23 15:45:25 +01:00
Maurice 5d7d6072f7 fix(mail-ingest): refresh MCP sessions when an admin switches the mail import
The mail import tools are listed only while the import is on, so a save that changes mail_ingest_enabled now ends the live MCP sessions, as the addon switches do.
2026-11-23 15:45:25 +01:00
Maurice 4cd3f3d650 fix(files): serve a plugin the files a trip keeps while Documents is off
The plugin file surface follows the REST rule: the list and reads keep booking, place, expense, note and message files, a write on a loose file goes through when it attaches it, and uploads and deletes stay open.
2026-11-23 15:45:25 +01:00
Maurice a0d66eb898 fix(files): attach a loose file while the trip has Documents off
update and link go through when the request itself attaches the file to a booking, place, stop or expense, on REST and MCP alike, and upload_trip_file takes budget_item_id like the REST upload.
2026-11-23 15:45:24 +01:00
Maurice 8a2045c619 fix(mail-ingest): attach a booking's documents while the trip has Documents off
A booking's files belong to the booking, so the mail's documents now reach it whatever the Documents switch says; a mail filed without a booking still needs Documents.
2026-11-23 15:17:02 +01:00
Maurice 34d5fba437 fix(plugins): deliver a trip's core events to plugins in emission order
The addon check in front of the event sink made each family event wait for
its own read, so on Postgres a later snapshot could overtake an earlier one,
and a trip event could arrive before the budget event emitted ahead of it.
The reads still run side by side, but a trip's events now leave in order.
2026-11-23 15:15:37 +01:00
Maurice 8b9de04960 fix(wanderer): offer the connection and run the watch where a trip switched Tours on
With Tours off for the instance, a trip that switched it on opened the wanderer
import, but Settings hid the connection and the watch cron never ran. The addon
feed now tells each user whether wanderer applies to them, and the watch looks
for every user who has Tours on somewhere; the others only take their turn.
2026-11-23 15:15:36 +01:00
Maurice c289541c43 fix(notifications): list the paddle region request for admins while any trip has Tours on
The admin matrix decided a trip addon by the admin's own trips, so with Tours
off for the instance and on for a member's trip the paddle region request still
reached admins but had no row to switch it. Admin-scoped rows now follow the
addon being on for the instance or any trip.
2026-11-23 15:15:36 +01:00
Maurice 146f46c5e3 fix(addons): give a member who joins a trip with an opened addon a new MCP session
A trip that switched on an addon the instance has off ended the MCP sessions
of the members it had then, but somebody added later, or joining through the
invite link, kept a session without that addon's tools. Joining now ends it too.
2026-11-23 15:15:36 +01:00
Maurice 8709f67ff4 fix(trip-members): leave expenses out of a guest deletion while Costs is off
Deleting a guest re-sent every expense that named them as budget:updated,
even on a trip with Costs switched off, so each member's offline cache took
rows the bundle keeps out. The re-split expenses now go out only while the
trip has Costs on.
2026-11-23 15:15:36 +01:00
Maurice 363889b97a docs(plugin-sdk): state the transaction-control and NUL rules of ctx.db
A plugin's own database refuses BEGIN/COMMIT in every call and NUL in SQL,
bound values and migration ids on every engine; the guide and the ctx.db types
now say so and point at ctx.db.tx() and Buffer binding instead.
2026-11-23 15:15:36 +01:00
Maurice 48e54d5a62 fix(files): keep booking, place and expense files reachable with Documents off
The Documents addon now gates only the file manager: the list leaves out loose
files, and the trash, starring and loose files answer 404, while uploads, deletes
and every file a booking, place, expense, note or message carries stay reachable
over REST, the download route, MCP and the offline bundle.
2026-11-23 15:15:36 +01:00
Maurice d83841f53b ci(postgres): restore with the 18 client tools the image ships
The backup round trip now runs with pg_restore 18 against both lane servers, so a setting an older server does not know fails the lane.
2026-11-23 15:12:16 +01:00
Maurice 485fb93f78 fix(helm): render when an upgrade reuses values from before the database block
The templates read the database settings through a default dict, so helm upgrade --reuse-values from a release without them no longer stops on a nil pointer; CI renders the chart with the block removed.
2026-11-23 15:11:40 +01:00
Maurice ca367d9cfc docs(postgres): name the Docker Compose version the Postgres compose file needs
The file creates TREK's role from an inline config, which Compose reads only from 2.23.1 on; the file header and the wiki now say so, with the error an older Compose prints.
2026-11-23 15:11:40 +01:00
Maurice 9ae99b42ec fix(ci): give the release mirror a recovery hint that works
With no push run for the dev head, the mirror now says to push a new commit to dev; a run started by hand is not a push run and never satisfied it.
2026-11-23 15:11:40 +01:00
Maurice 8fb720ea49 fix(mcp): validate a tool or prompt field again once NUL stripping changed it
The SDK validates the arguments before the input mapper drops NUL characters, so a field the mapper changes is now checked against its own schema again and a name of nothing but NUL is refused over MCP as it is over REST.
2026-11-23 15:11:39 +01:00
Maurice 1fb1b102e8 fix(dawarich): name an unnamed stay once Dawarich has geocoded its points
A stay stored as 'Unnamed stay' because none of its points was geocoded yet is now read again on the next sync, so a slow background geocoder or a stay from before the upgrade gets its town once Dawarich knows it.
2026-11-23 15:11:39 +01:00
Maurice a604f84899 fix(memories): send share link viewers the Immich preview instead of the original file
A public view of an Immich image now asks for the preview rendition, which Immich re-encodes without the stored metadata, so photo locations no longer go out with share links; owners still get the fullsize original.
2026-11-23 15:11:39 +01:00
Maurice e7e3592d97 fix(flight-live): tell a delay only to the bookings it is late for
Bookings that share one flight state can hold different scheduled times, so the delay notice now goes only to the legs whose own departure is at least fifteen minutes late instead of telling the others it is delayed by 0 minutes.
2026-11-23 15:11:39 +01:00
Maurice 8e51410251 fix(flight-live): do not read an earlier sector's aircraft as this flight having departed
Before the scheduled departure, an aircraft in the air that is no nearer the destination than the origin is now stays unpicked, so booking only the later sector of a through flight no longer sends the departure notice hours early.
2026-11-23 15:11:39 +01:00
Maurice 22c3381044 fix(tags): keep a trip's tags when the member who created them deletes their account
The trip tags a deleted user created now pass to each trip's owner before the user row goes, so the tag and its place assignments no longer cascade away for everyone else on the trip.
2026-11-23 15:11:38 +01:00
Maurice 25ded7319a fix(ios): hand a widget launch link to the UI only once
A tap that launched the app went to the UI as a held quick action and to
Capacitor as the launch URL, which a server UI before appLinks followed
as well, pushing the page twice. Capacitor now gets the launch without it.
2026-11-23 15:11:38 +01:00
Maurice b6006c8265 fix(ios): hide the status bar beside a corner element only on an iPhone
The status bar goes for the iPhone Duo's status capsule; an iPad's window
controls give the same corner signal and no longer hide its bar. The corner
insets still reach the page on every device.
2026-11-23 15:11:38 +01:00
Maurice bd215b7ec7 fix(ios): open the offline copy when an update rechecks an unreachable server
The recheck after an update ran on every bridge, also on the one the
offline start restarts, and moved the server it had just put back out
again, so the app looped between the address screen and a restart.
2026-11-23 15:11:38 +01:00
Maurice 98a05fa1fd fix(ios): read widget and watch dates in the Gregorian calendar
The app writes its days as Gregorian yyyy-MM-dd, but the widgets and the
watch built their keys in the device's calendar, so a Buddhist or Japanese
calendar matched no trip day and dropped every dated booking.
2026-11-23 15:11:38 +01:00
Maurice 0e918820c3 fix(widgets): keep every stop of the day the snapshot was written on
The days ahead keep only their first 16 stops, and the widget read today
from that list too, so on a busy day it showed the wrong next stop. The
full day the app wrote now stays in place on its own date.
2026-11-23 15:11:38 +01:00
Maurice a701d89fb9 fix(android): keep the start page's boot scripts in the offline copy
theme-boot.js and shell-guard.js come from the public folder, which the
build manifest does not list, so an offline start waited on the unreachable
server for them before the first paint. They are now stored and refreshed
on every launch.
2026-11-23 15:11:37 +01:00
Maurice 4fead3259d fix(android): keep a sign-in proxy's page out of the offline copy
The copy now only stores answers that come from the server itself and no
HTML in place of a script or stylesheet, so a proxy's login page no longer
replaces the stored UI.
2026-11-23 15:11:37 +01:00
Maurice 4fd8f3987f fix(planner): treat the trip opened before as still loading when another one opens
The store kept the previous trip until loadTrip ran after the first render, so the desktop planner mounted with that trip under the new id for a frame.
2026-11-23 15:11:37 +01:00
Maurice 855ec37935 fix(mail-ingest): read the inbox again when it changes while a read is on its way
A reload asked for during a read was dropped and the older answer overwrote the newer count, and an entry decided meanwhile came back with it.
2026-11-23 15:11:37 +01:00
Maurice 310e5fba8f fix(mail-ingest): forget the mail import of an account on sign-out
The store kept the forwarding address, the inbox and the badge count across a logout, so the next account on the same tab saw them until its own read landed, or for good when that read failed.
2026-11-23 15:11:37 +01:00
Maurice 8f5324c901 fix(pdf): draw the cover route of a long road trip without spreading every point into one call
The bounds came from Math.min and Math.max over all routed points, which throws past the engine's argument limit and failed the whole export on Safari and the iOS app.
2026-11-23 15:11:36 +01:00
Maurice 97c0d992c8 fix(pdf): order a day's bookings in the overview by the clock in 12h too
The booking list sorted on the printed time, so for a 12h reader 1:00 PM and 10:00 AM came before 9:30 AM.
2026-11-23 15:11:36 +01:00
Maurice cd32f07bf5 fix(roadtrip): offer and save a visit's stay under the day plan right on the desktop
The rail and the inspector offered the stay to anyone who may edit places, while a saved visit's stay needs day_edit, so the dialog closed without saving and the stop popup wrote half its change before a 403. Refusals now say so before anything is written.
2026-11-23 15:11:36 +01:00
Maurice 3c00544e93 fix(native): keep the keyboard open for controls that hold the focus in their field
A tap away blurred the field on touchend, before the sign toggle or the note format bar could cancel their mousedown, so the keypad closed mid entry. The field now lets go only once the tap's pointerdown and mousedown pass uncancelled.
2026-11-23 15:11:36 +01:00
Maurice dec3058777 fix(help): show the settings help on the admin Security and Services tabs
Both tabs fell back to the admin overview without guides, and the guides for API keys, providers and file types opened the Security tab instead of Services.
2026-11-23 15:11:36 +01:00
Maurice e459ec6e60 fix(mail-ingest): ask before closing the booking mail setup with changes not saved
The setup only keeps its fields through its own Save, yet Close, the close mark, the backdrop and the phone sheet dropped them without a word. Now each way out asks, and discarding puts the saved values back.
2026-11-23 15:11:36 +01:00
Maurice ba45dbc874 fix(admin): draw no divider under an addon whose sub-rows render nothing
A switched-off booking mail import passed false as its only child, which Children.count counts, so an empty list with a top border showed under the row.
2026-11-23 15:11:35 +01:00
Maurice fa8e1b68bd fix(mail-ingest): set an inbox entry aside once its booking is saved through Fill in yourself
The entry stayed pending after the prefilled booking was saved, kept its Add action and counted in the badge, so it could be added a second time.
2026-11-23 15:11:35 +01:00
Maurice 755ca865a4 fix(mail-ingest): open the prefilled form again for an entry asked for twice in the same trip
The guard kept the last handled entry after the link left the address, so a second Fill in yourself for it in the open trip did nothing.
2026-11-23 15:11:35 +01:00
Maurice a3caa9ca1a fix(costs): count only balances read in the shown currency in the owe and owed cards
After a currency switch the cards kept summing the flows of the previous currency, offline or while the new read ran, and printed them in the new one.
2026-11-23 15:11:35 +01:00
Maurice 344580d343 fix(share): decide what a shared link is for once the trips' Collab is read
The share sheet waits for the trip list and each trip's own Collaboration before
it acts on the share sheet's trip, and reads only the addon lists it does not hold.
2026-11-23 15:11:35 +01:00
Maurice 36ea9bdb3e fix(trip-addons): keep a pushed addon list over an older sync read
The sync reads a trip's addons through the store's load, so a tripAddons:changed
push that lands during the read stays on screen and in the offline copy.
2026-11-23 15:11:34 +01:00
Maurice c3d60e1c43 fix(sync): read the open trip's addons again after the socket reconnects
A tripAddons:changed push is not replayed, so a switch made while the socket was
down now reaches the member on the reconnect refetch.
2026-11-23 15:11:34 +01:00
Maurice 769293a554 fix(trip-addons): read the trip's lists again when their addon is switched back on
The sections of an addon that was off were read as empty, so switching Lists,
Costs or Documents back on while the trip is open now reads the trip again.
2026-11-23 15:11:34 +01:00
Maurice 56ce66f666 fix(offline): park a queued delete that a switched-off addon refuses
The 404 a route answers while its addon is off keeps the entity on the server, so
the queued delete is parked as failed and offered for retry instead of dropped.
2026-11-23 15:11:34 +01:00
Maurice fd10ce2876 fix(plugins): show a trip page that replaces a core tab while that tab's addon is off
A trip-page plugin that replaces Lists, Costs, Documents or Collab is a stand-in
for the core tab, so its own tab stays on the trip whatever that addon is set to.
2026-11-23 15:11:34 +01:00
Maurice 9d4e52ddfc perf(db): let Postgres serve ORDER BY id from the primary key
A Kysely ORDER BY on the id of a table the statement reads in its FROM no longer gets SQLite's NULL position, which no primary key row needs and which kept Postgres from reading paged latest-first lists such as the audit log off the index.
2026-11-23 15:11:34 +01:00
Maurice 52a6fbbc92 fix(scripts): read the server's .env in the admin reset and the key rotation
Both scripts now load server/.env as the server does, so an install whose TREK_DB_URL lives there resets the admin and rotates the key in its Postgres database instead of in a SQLite file left behind by the move.
2026-11-23 15:11:33 +01:00
Maurice de1c3b8ea6 fix(scripts): rotate the SQLite file TREK_DB_FILE names
The key rotation now opens the database the server runs on when TREK_DB_FILE is set, writes the new key to the key file the server reads, and refuses DB_PATH and TREK_DB_FILE naming different files.
2026-11-23 15:11:33 +01:00
Maurice 60885627b1 fix(scripts): rotate the wanderer token with the encryption key
The key rotation now re-encrypts wanderer_connections.token, so a wanderer connection keeps working after the key changes instead of calling out without its token.
2026-11-23 15:11:33 +01:00
Maurice 9c454a04e1 fix(db): keep plugin index names when moving plugin data to Postgres
The move now creates each index a plugin named under that name, so a later plugin migration that drops or alters it by name finds it on a moved install as on a fresh one.
2026-11-23 15:11:33 +01:00
Maurice 6a6c403860 fix(db): keep booking to stay links of old installs when moving to Postgres
An install from before April 2026 stores reservations.accommodation_id as an INTEGER, so the move now writes such a stay id as the '<id>.0' text TREK compares it as, instead of '14', which no longer matched the stay on Postgres.
2026-11-23 15:11:33 +01:00
Maurice e51902a03b fix(reservations): drop a stay id from another trip when a booking is created
Create now checks that the linked stay belongs to the trip, as update already does, instead of storing a link to a stay that does not exist there.
2026-11-23 15:11:33 +01:00
Maurice 3a2645a3e4 fix(db): match a booking to its stay on Postgres without failing on odd ids
The Postgres stay match now casts the leading digits of the stored text as bigint, the way SQLite reads it, so a non-numeric or oversized accommodation_id no longer fails the calendar, share and stay reads for every trip.
2026-11-23 15:11:32 +01:00
Maurice bf8677a28c fix(backup): name the client tool when pg_restore cannot read a Postgres dump
A missing pg_restore, or one older than the pg_dump that wrote the archive, was reported as an invalid dump. The refusal now says which tool to install or point TREK_DB_PG_BIN_DIR at.
2026-11-23 15:11:32 +01:00
Maurice 89da19e535 fix(backup): refuse a Postgres restore the role or tools cannot run before anything is copied
The admin restore now answers a privileged role, old client tools or an unreachable server with a 400 naming the reason, before it keeps a pre-restore dump. RESTORE_FROM_BACKUP checks the same before it unpacks the archive, and removes the unpacked copy when the load fails.
2026-11-23 15:11:32 +01:00
Maurice e630e92183 fix(backup): clear a Postgres schema holding views or functions over TREK's tables
A table dropped with CASCADE takes its views and functions along, and the clear then rendered their stale oids as bare numbers and failed the restore. Rows whose object is already gone are now skipped.
2026-11-23 15:11:32 +01:00
Maurice bb2b4a1f5a fix(backup): restore Postgres backups into PostgreSQL 14, 15 and 16
pg_restore 17 and later write SET transaction_timeout at the top of every script, which older servers refuse under ON_ERROR_STOP. The restore now leaves settings the target server does not know out of the script while it streams.
2026-11-23 15:11:32 +01:00
Maurice 626e19c534 fix(mail-ingest): keep bookings the data names that the AI left out
When the AI returned fewer bookings than the machine-readable data, the others were dropped without an entry.
2026-11-23 15:11:31 +01:00
Maurice 8f5988ee33 fix(mail-ingest): match each AI leg to the data leg it agrees with
Under one booking reference every leg after the first was compared with the first and went to the inbox as a disagreement.
2026-11-23 15:11:31 +01:00
Maurice 4cef885e12 fix(mail-ingest): never queue a mail again for a failure after its commit
An error in the announcements, documents or notices after a mail was written sent it back to the queue, which duplicated its entries or marked it failed.
2026-11-23 15:11:31 +01:00
Maurice 303d161ecf fix(mail-ingest): keep a booking that fails the item shape in the inbox
Such a booking made the whole mail fail and retry instead of waiting to be filled in by hand. A reference read as a number is now read as its text.
2026-11-23 15:11:31 +01:00
Maurice eaa557343e fix(mail-ingest): compare look-alike bookings at their wall time on any server zone
The window around a booking's start went through the host time zone, so on a server outside UTC it missed a booking at the same local time and added it twice.
2026-11-23 15:11:31 +01:00
Maurice dea903f011 fix(booking-import): treat a booking a forwarded mail added as already imported
The file and assistant import only looked for bookings the file import wrote, so the same booking arrived twice when it had come in by mail first.
2026-11-23 15:11:30 +01:00
Maurice 91edf0c565 fix(mail-ingest): announce a place a mail created with its whole row
The open planners of the trip received only the new place's id and kept a nameless place without coordinates until a reload. The broadcast now carries the row the place routes send.
2026-11-23 15:11:30 +01:00
Maurice 403b7d2f93 fix(mail-ingest): make the own address once when two views ask for it together
The first look at the settings made the address outside a transaction and always revoked the live one, so two requests at once could leave a view showing a revoked address. It is now checked and made in one transaction and never replaces an address it finds.
2026-11-23 15:11:30 +01:00
Maurice 5d4cfec3b6 fix(mail-ingest): list the mail import tools only while the import is on
Every mail tool answered 'Mail import is not available' on installs that never switched the import on, which is the default, so they are now gated like the addon tools.
2026-11-23 15:11:30 +01:00
Maurice b9608bf684 fix(mail-ingest): keep the webhook open for real deliveries while bodies trickle in
The webhook now limits the memory the bodies being read hold instead of the number of open requests, and gives up on a body still arriving after a minute, so a few slow requests no longer turn every delivery away.
2026-11-23 15:11:29 +01:00
Maurice 3b65da7626 fix(mail-ingest): read transfer bookings instead of filing them as forwarding confirmations
A forwarding subject now counts only from Gmail or Microsoft or together with a code in the body, so 'Votre transfert est confirmé' is read as a booking. The subject and From header are also matched in linear time.
2026-11-23 15:11:29 +01:00
Maurice 327539df14 fix(mail-ingest): read forwarded attributions and HTML tags in linear time
A long line of reply verbs, or HTML with line break, script or style tags that never close, made the mail walk backtrack once per word and block the server. Attribution lines past 500 characters are no longer tested.
2026-11-23 15:11:29 +01:00
Maurice 965b519f23 test(notes): wait for the caret frame before typing in the numbered list test 2026-11-23 12:11:46 +01:00
Maurice 3ec7cc73b2 fix(notes): number list items in order from the format toolbar
The numbered list button always inserted '1. ' and only on the caret's line, so writing a list item by item left 1. 1. 1. in the field. It now continues from the item above and formats every line of a multi-line selection (bullets and quotes too).
2026-11-23 12:05:03 +01:00
Maurice 493571c559 fix(android): log the address and sender of a page that fails with an HTTP error
When the server's page came back with an error status, the app went to the
address screen with "HTTP 503" and logged nothing, not even which page it
was. A report could then not tell the server, a proxy in front of it and
something on the phone apart: the reporter's Cloudflare and Traefik logs
show no 503, and the page was not requested at all.

Every main-frame HTTP error is now logged under TrekShell with the page's
address (without its query, where a sign-in page carries a challenge), the
status, the reason phrase and the headers that name whoever answered
(Server, Via, CF-Ray, Content-Type). An answer with none of them says so,
which points at something on the phone. What the app does with the error
is unchanged.

Refs #3014
2026-11-22 22:58:02 +01:00
Maurice 4212fcdfc8 style(i18n): format the new PDF strings with an apostrophe
lint:format in shared: Prettier writes a string holding an apostrophe in
double quotes; the Catalan, French and Dutch PDF strings now follow it.
2026-11-22 22:39:01 +01:00
Maurice 28f750f7c4 fix(pdf): give formatMoney a locale, lower the strict entry of the export
lint:strict: a place's price passed the export's locale, which can be
undefined, to formatMoney; it falls back to en like the export's other
money figures. The rewritten TripPDF.tsx holds 1 strict error instead of 38,
and its entry is lowered to that.
2026-11-22 22:28:09 +01:00
Maurice 8c9cf4a80c fix(pdf): handle a failed cover bake where it happens, lower the eslint baseline
Client types: the overview test used Array.prototype.at, which the client's
lib setting does not include; it reads the last cell with slice instead.

Client lint: the export swallowed a failed cover bake with .catch(() => null).
bakePdfCover now catches a canvas that will not draw or encode itself and says
why, so the export calls it plainly. The rewrite also leaves fewer warnings,
and the baseline is lowered to the counts the run measured: complexity 216,
no-explicit-any 138, no-unused-vars 117, and in the tests
no-non-null-assertion 1872.
2026-11-22 22:19:51 +01:00
Maurice b33d592325 perf(pdf): draw the first pages once, not on every scroll
The cover and the route overview stuttered in the preview and in the saved
file, in every viewer:

- The cover photo was embedded at its upload size, 4000 px and more, under
  a translucent gradient across the whole page, which every viewer had to
  composite again on each redraw. The export now crops the photo to the
  page at print size (A4 at 150 dpi) and paints the shade into it, one flat
  JPEG. A photo from another origin keeps the photo and the gradient.
- The route overview drew every point of the routed roads, about 35,000 on
  a two-week trip and most of them on the same pixel, twice each (casing
  and line). Points that round onto the one before are dropped and the rest
  thinned within a third of a pixel (Douglas-Peucker): about 900 points,
  the same shape on paper.
- The cover's glass is a tinted fill without a backdrop blur, and the
  casing under the cover route is opaque.

Also spells out the span and status keys so the key check can follow them,
keeps types nothing imports private, and drops the export's theme and rtl
baseline entries, which reach zero.
2026-11-22 22:10:52 +01:00
Maurice 590b174dd1 feat(pdf): draw the trip's route on the cover, keep its figures on one line
The cover gains the trip's own shape: every routed day drawn in its map
colour on a glass card beside the title, a band of the days' colours with
the first and last date under it, and the dates on a pill above the title.
The figures sit in one row and never break inside a number.

Print engines leave out a backdrop blur, so the glass gets a tinted fill
that reads on paper; the blur stays for the preview. The dates of the day
overview are aligned to the start.
2026-11-22 21:52:27 +01:00
Maurice 2a833c4ba9 fix(pdf): keep a note's second line in its card, fill the preview width
A day note's time field is the free line the day plan prints under its
text, not a clock: it printed in the narrow time column and broke into a
word per line. It stays in the card again, and the time column is empty.

The preview showed the A4 sheet at its print width inside the wider
dialog, with a pale band on either side; on screen the document now fills
the frame, as it did before. The stops column of the day overview is
centred under its pin.

Tests for the day's cards, the cover and overview, and the new preview
switches.
2026-11-22 21:43:34 +01:00
Maurice a5de1bc52d feat(pdf): redesign the trip PDF
The trip PDF gets a new layout in the app's current look, with nothing it
printed before left out and more of each place on the page.

- Cover: the trip photo full bleed, title and dates over it, the trip's
  figures on frosted tiles.
- Overview: the route map, every day at a glance (colour, date, plan, the
  night's stay, stops, cost) and all bookings and stays with their codes.
- Days: the header in the day's map colour, a photo strip of the day's
  stops, where the night is spent, then the plan as a timeline with the
  times on the left.
- Places: photo or category tile, category, duration, price, rating, tags,
  address, coordinates, description, notes, opening hours of that day,
  phone, website, e-mail and the members going. The rating, e-mail, hours
  and reservation note come from the trip's place, since the assignment
  only carries a projection of it.
- Bookings: route first, then airline, number, seat or platform as badges,
  each leg with its own code, status and the booking's code.
- A second row of switches in the preview: overview, photos, coordinates,
  and contact and hours, next to page per day, large text and transport
  notes. Each one is a class on the document and remembered.

The document is split into modules for its helpers, icons, stylesheet,
cover and overview, and the day, so the export itself only gathers the data.
2026-11-22 21:34:29 +01:00
Maurice 1b20214a7f fix(planner): show the drive to a rental car's return and away from its pickup
On the day a rental car is picked up the route ended at the desk, and on the
day it is returned it started at the return, the way it does for an overnight
train. The drive with the car itself showed nowhere: a stop planned before the
return got no travel time to it, in the day plan on the phone and the desktop
and on the map, and neither did the first stop after the pickup.

A car or bicycle rental is now a stop the day's drive passes through on those
two days. Bookings that are ridden keep their one-sided endpoint, and two
bookings back to back still get no drive between them (#1394).
2026-11-22 19:48:34 +01:00
Maurice 3e8496dce6 feat(ios): hide the status bar where a corner capsule was measured
On a window where the app measured an element in a top corner, an iPhone
Duo's status capsule, it now hides the status bar, which is meant to take
the capsule away; whatever still covers the corner stays in the safe area
the page keeps clear of. Each window size keeps its answer once seen, so
hiding the bar never brings it back, and the folded and unfolded displays
decide on their own. Devices without such an element are not affected.
2026-11-22 19:36:31 +01:00
Maurice ea1b75e639 fix(mobile): keep every screen clear of the iPhone Duo's status capsule
The capsule in a top corner was handled screen by screen: the m-corner-*
classes and --m-corner-clear put bars beside it and lifted content below
it, so every layer that did not opt in sat under it, and testers found it
on almost every page.

It now counts as safe area in mobile.css. Upright the top inset reaches
below the capsule and the sides keep their full width; on a wide window
its side is given up over the whole height instead. The per-screen
handling and corner.css are gone. Control rows a screen places itself and
layers that fill the window keep to the side insets through m-safe-row and
m-safe-trail, and the trip's pane keeps its content off the capsule's side
on a wide window. On every other device the insets come out as before.
2026-11-22 19:36:31 +01:00
Maurice c0f6551cf4 test(server): send the API key requests without awaiting in a loop
Server lint counted one no-await-in-loop warning over the tests baseline, from the loop in the new API key test.
2026-11-22 18:24:15 +01:00
Maurice 1fdf74e7f2 fix(auth): mark an address the account moved before an admin saved it
Both backfills of email_self_asserted skip any account with an
admin.user_update row naming email. The edit dialog sends the email on every
save, so a role change made long after an account moved its own address kept
it at 0, and a verified SSO sign-in with that address still linked into it.

A new migration reads the address each admin save found (targetUser): an
account is marked when every save already found its current address, or when
the last save that found another one sent no email. A save that may have typed
the current address in still leaves the account alone, since the audit rows
cannot tell it from a change the account made itself before 5.0.0. Only rows
still at 0 are touched and nothing is cleared.
2026-11-22 18:15:51 +01:00
Maurice c7de823c78 fix(auth): renew a session cookie only after it verifies on its own
SessionRenewalInterceptor took req.user as proof that the trek_session cookie
had been verified. On a route with its own guard chain that does not hold:
ApiTokenGuard authenticates a public API key and sets req.user, and the cookie
sent beside it is never checked. Past half its lifetime such a cookie was
decoded without its signature and renewed, so a holder of a read-only key
could come away with a signed session of the key's owner.

The interceptor now runs the cookie through the guards' own check (signature,
expiry, password version, active session) before it renews, requires it to
name the request's user, and renews nothing on a request a public API key
authenticated.
2026-11-22 18:15:51 +01:00
Maurice 49b9ffc77d fix(client): keep the seat change clear of the sheet's held ref and of non-null assertions
Client lint was red: passing the ref-held reservation to bookingSeats added a react-hooks/refs warning in MTransportSheet, so the sheet now reads the seats from the legs it already has (seatsOfLegs). The new PDF test used a non-null assertion.
2026-11-21 15:45:04 +01:00
Maurice 7006891ce0 style(server): format the legs-only seat test
Server lint was red: lint:format found the new update_transport cases in tools-transports.test.ts unformatted.
2026-11-21 15:37:00 +01:00
Maurice 4d01439c75 test(server): type the created transport in the legs-only seat test
Server lint was red: the new MCP test cast its result to any, one no-explicit-any warning over the tests baseline.
2026-11-21 15:29:53 +01:00
Maurice adb6a2c80d fix(planner): show each leg's own seat on a flight with a stop
A flight with a stop saves a seat per leg, but every view read the
booking's flat seat, which mirrors the first leg's. A seat booked only on
the second leg showed nowhere, and one on the first leg showed on both.
#2701 had fixed this for trains only.

- getFlightLegs reads each leg's seat. The first leg falls back to the flat
  seat, as the booking form does, so older bookings keep theirs.
- bookingSeats lists the seat of every leg that has one with its route.
  The detail views (the phone's transport sheet, the booking detail) show
  each leg's seat under its route ("Seat IST → JFK"), and a leg opened
  from its row shows its own. The cards and field grids (bookings list,
  the phone's Bookings and Transports tabs, the day plan's transport
  detail) hold every seat in one Seat cell, so a card cutting its grid
  short no longer drops the second leg's.
- The day plan's flight leg rows carry their seat, and the PDF prints a
  flight's seat, direct or per leg.
- The watch and the Wallet pass name every leg's seat of the booking.
- A legs-only MCP update sets the flat seat, airline and flight number
  (train number and platform) again from the new first leg, so a seat
  taken off the first leg does not live on in the flat seat. A flat value
  the stored first leg never had stays.

Closes #3158
2026-11-21 15:24:52 +01:00
Maurice 1824cc77ec fix(ci): bring the per-trip addon tests and ratchets in step
The second run of #3157 was red in six jobs:
- Server types: ReminderJobsService takes AddonsService now; RJOB-007 built
  it with five arguments.
- Server tests 2/10: the doc-sync job tests stubbed AddonsService without
  isEnabledForTrip, which the sync asks per trip now.
- Client tests 4/10: toursPermissions mocked useAuthStore as a bare
  selector; tripAddonsStore keys its lists by account through getState.
- Server lint (knip): TripAddonRow was exported without a reader outside
  its file.
- Client lint and Client types: no-unused-vars and the strict errors in
  useTripPlanner.ts went down by one, so their entries are lowered.
2026-11-21 14:00:02 +01:00
Maurice 9e2805fc89 chore(lint): lower the server no-unused-vars baseline to 34
Server lint was red: the per-trip addon change left one unused variable fewer in src, and the ratchet fails on an entry above the count.
2026-11-21 13:28:06 +01:00
Maurice 77380ea5cf docs(wiki): describe the trip settings' Addons area and its MCP tools 2026-11-21 13:23:09 +01:00
Maurice 9956c58dd5 feat(client): follow and switch a trip's own addons
- The trip's addon list is read through tripAddonsRepo into
  tripAddonsStore (per account and trip, kept in Dexie version 16 for
  offline), refreshed when the connection returns and live on
  tripAddons:changed.
- The planner's tabs, dock, rail and deep links, the cost, tour and list
  readers, the PDF export, the share link options, the widgets and the
  watch follow the trip instead of the instance switch.
- Trip settings gets an Addons area for the owner, on the desktop dialog
  and the phone sheet, on one useTripAddonRows hook: each trip addon with
  its switch, marked "This trip only" while it differs from the instance.
  Switching back to the instance's value drops the trip's choice.
  Switching needs a connection.
2026-11-21 13:23:09 +01:00
Maurice 3f38621024 feat(server): let a trip owner switch trip addons for one trip
A trip can now turn a trip addon (lists, costs, documents, collab, road
trip, tours) on or off for itself, whatever the instance switch says. No
row in the new trip_addon_overrides table means the trip follows the
instance; a row is the owner's choice. Going back to the instance setting
deletes the row, and no addon data is touched either way.

- GET/PUT /api/trips/:tripId/addons[/:addonId] (every member reads, the
  owner writes) and the MCP tools get_trip_addons and set_trip_addon, on
  the shared tripAddons contract; tripAddons:changed tells the members.
- Every trip-scoped addon surface asks the trip: REST through
  TripAddonGuard, MCP through a per-call gate on the named or pinned trip,
  plugin RPC and events, the share link, the offline bundle, reminders,
  doc sync, the assistant (tools, keep_attached_file), booking costs, the
  trip summary prompt, and the cross-trip tour reads (library, Atlas
  stats, collection save).
- Routes without a trip open while the addon is on in any of the user's
  trips. Switching an addon on that the instance has off ends the members'
  MCP sessions so they reconnect with its tools.
- A copied trip takes its owner's choices along.

Behaviour changes: an anonymous call to an addon route that is off now
gets 401 instead of 404, and with an instance switch off the packing,
todo and files plugin RPC methods, the files MCP tools, todo reminder
mails, core plugin events, plugin view contributions, the share link's
lists, costs and chat sections and the offline bundle's lists follow it.
2026-11-21 13:23:09 +01:00
Maurice 2f7b8357ce fix(server): schema-qualify the table the move asks Postgres for its sequence
Server Postgres 18 3/3 was red on dev: PGMOVENUL-007 failed with relation "information_schema_catalog_name" does not exist. readTargetSchema called pg_get_serial_sequence(format('%I', table_name), ...) over information_schema.columns, and Postgres does not promise to apply the table_schema filter first, so the call could see rows of information_schema itself, whose bare names do not resolve on the search path. The name now carries its schema, so the call answers for every row whatever the plan. The fake Postgres of the move tests matches the new text.
2026-11-21 11:30:06 +01:00
Maurice 6861687b1f fix(server): queue the backfill's updates instead of awaiting them in a loop
Server lint was red on dev: lint:warnings counted 557 no-await-in-loop warnings in src against a baseline of 556, from the UPDATE the new admin-made account backfill awaited per account. The updates are now queued with addSql, the way the Ireland counties migration queues its row writes, with the id checked to be an integer. The migration does the same as before; it has not shipped in a release.
2026-11-21 11:22:47 +01:00
Maurice 8fc9fe7945 fix(auth): mark an address an admin-made account changed itself, so SSO no longer links to it
The 5.0.0 backfill (Migration20200101042800) set email_self_asserted only for accounts whose address moved away from their user.register audit row. An account created in Admin > Users has only an admin.user_create row, so it kept 0 even when the account had changed its own address in its settings before the upgrade, and a verified SSO sign-in asserting that address was still linked into it.

A new migration applies the same rule with the address in the admin.user_create row as the baseline: an admin-made account whose address is none it was created or registered with, and whose email no admin edited, is marked. Only rows still at 0 are touched and nothing is cleared. The shipped migration stays as it is.
2026-11-21 11:12:34 +01:00
Maurice f668eee227 test(client): drop the two new non-null assertions in the addon card tests
Client lint was red: lint:warnings counted 1877 no-non-null-assertion warnings in tests against a baseline of 1875, both from closest('section')! in FE-ADMIN-ADDON-045 and 046. Cast to HTMLElement like the other card lookups in the file.
2026-11-21 10:59:35 +01:00
Maurice 711015d5fd feat(admin): live flight status, booking mail import and paddle water data as rows of the addon cards
The addons page listed the trip, global and integration addons and then three
loose cards under them: live flight status, the booking mail import and the
paddle water data. They now sit where they belong, as rows of the cards:

- Live flight status is a row of the trip card, with its switch, locked when
  FLIGHT_LIVE_ENABLED holds it.
- The booking mail import is a row of the integration card with its switch;
  while it is on, "Set up mail import" opens the transport, address, AI
  allowance, test and status in a dialog, the way AI is set up.
- The paddle water data are a row under the Tours addon that opens the
  regions in a dialog, counting the open requests, else the regions.

The phone follows with the same rows and bottom sheets. The setup row and the
setup dialog are shared components (AddonSetupRow, AddonSetupDialog on the
desktop, MAdminOptionRow and MAdminSetupRow on the phone), the card counts
stay the addons' own, and the settings tab loses its features part.
2026-11-21 00:23:13 +01:00
Maurice 6ebd5cf0c7 fix(mobile): a road trip stage draws only its own rides, not the drive's flight home
The phone's road trip tab shows one stage at a time, but its map drew the
arcs of every ride that seams the whole drive, plus every booking switched on
for any day. A flight home on the 12th then crossed the map of the stage on
the 9th, with its airport label, as if it were part of that day.

The stage now draws the rides that seam its own drive, whatever day they were
booked on, and of the bookings switched on by hand only those that run on the
stage's day. The all-days view and the desktop, which shows the whole drive,
are unchanged.
2026-11-20 23:00:52 +01:00
Maurice 8ab7547edf fix(calendar): a booking linked to a plan stop gets its zone and is exported once
The calendar feed and the .ics export wrote a restaurant booking linked to a
plan stop twice, and the booking's copy without a time zone:

- The zone of a booking came only from its own place. A booking whose place
  is its linked stop (reservations.assignment_id) had none, so its DTSTART and
  DTEND went out as floating times and calendar apps placed them in the
  device's zone, an hour early for a London lunch read in Paris. The zone now
  comes from the booking's place, then its linked stop's place, then the zone
  all stops of its day or of the trip agree on. Transports keep their
  endpoint zones and still float when those are unknown, since either end can
  be in another zone.
- The stop and its booking were both emitted (trek-assign-<id> and
  trek-res-<id>). As for hotels, a stop whose booking yields a timed event on
  the same day is no longer emitted on its own; the booking event takes over
  the stop's place as LOCATION, its notes and, when it has none, its end. A
  booking without a clock, on another day, or still staged leaves the stop as
  it was, so no event is lost.

The VTIMEZONE builder moved unchanged into calendar-timezones.helpers.ts to
keep the service under the size cap.

Closes #3150
2026-11-20 22:19:11 +01:00
Maurice f599892a4b test(server): delete the tracked uploads together, not one await per loop turn 2026-11-20 21:49:40 +01:00
Maurice 1436cec35c test(server): suites remove only the uploads they stored, not whole shared folders
files, security, collections, journey and trips cleaned up by removing a whole
uploads category folder (uploads/files, covers, places, journey). Every suite
that boots the app writes into the same uploads tree, and on the Postgres lane
several run at once, so that removal took the files of the suite running
beside it: ATTE2E-008 then failed with "storage object not found" for its
attached file.

A small helper wraps StorageService.put on the app's instance, records what
the suite stores and deletes exactly that afterwards. The journey upload tests
that counted the files in uploads/journey (and so also counted what another
suite wrote there) now check that every object they stored is gone again.
2026-11-20 21:45:05 +01:00
Maurice fe90502955 fix(mobile): show stay names whole in the day card's chip strip
The stay chips in the day card's header shrank to fit beside the day pill and
the weather, so a name could end after one or two letters (H..., Br...). They
now keep their size and show the whole name; the strip scrolls sideways
instead, with its ends fading while more waits behind them.
2026-11-20 19:29:57 +01:00
Maurice 0431741ad7 fix(widgets): size the timeline's time column to the longest time shown
The day timeline in the trip widgets gave every time a fixed 38 pt column,
enough for 09:30 but not for a 12-hour clock: 5:45 AM was cut to 5:4... at
every widget size. The column now takes the width of the longest visible time
(and the now marker's label), at least the old 38 pt, so the dots still stand
in one line.
2026-11-20 19:29:56 +01:00
Maurice fa99940945 test(platform): a share-token photo whose copy fails to build is a 404 2026-11-20 19:15:48 +01:00
Maurice 09316025c3 test(share): sweep tests in the thumbnail job, tx and strict baselines follow the resolver split 2026-11-20 18:33:42 +01:00
Maurice 100313cfa9 fix(share): compare the pending rendition build with undefined 2026-11-20 18:23:20 +01:00
Maurice 411ec4af59 fix(share): keep private data and photo locations out of public trip and journey links
Public trip and journey share links handed out more than the owner chose to
share:

- A travel-only trip link still returned every day's title, and every link with
  the map returned the free-text day notes the shared page never shows. Days now
  go out through a public projection without notes, and travel-only links carry
  no day titles. Day notes, packing, budget and chat use explicit field lists
  too, and the category list holds only the categories the shared places use,
  without creator ids.
- The public journey payload spread whole entry and photo rows, including
  storage keys (file_path, thumbnail_path) and internal fields. It is now built
  from allow-lists and pinned by a strict response contract.
- /uploads/journey served every entry photo, original and video to anyone who
  knew the file name, so a URL kept working after a share link was revoked or
  the gallery switched off. It now serves journey covers and other non-entry
  objects only; entry media go through the token-checked proxy.
- Anonymous byte paths served stored originals unchanged, so EXIF GPS left the
  server even with map sharing off. Every public path (journey share proxy,
  covers, trip share photos, public uploads) now sends a copy with location
  data blanked in place (EXIF GPS, XMP and IPTC location, MP4/MOV location
  atoms), falling back to a metadata-free re-encode or a 404, never the raw
  file. Owners and members still get their originals.
- An entry's visibility field never decided the share link but was offered by
  MCP and the assistant as if it did. It is now documented as having no effect
  and no longer shown as a privacy label; is_draft keeps an entry off the link.
2026-11-20 18:18:50 +01:00
Maurice ec7f5e0585 test(atlas): cache the test places' regions in one go rather than an awaited loop 2026-11-19 22:11:29 +01:00
Maurice 8e38749bc3 fix(transit): show every stop name and each ride's arrival in the folded-out itinerary
The same gap as on the phone (#3139) in the desktop day plan's folded-out
transit row and the assistant's transit card: each ride cut its stop names
to one line and showed only its departure, and a walk cut its target. The
names and the walk target now wrap, and each ride shows its arrival under
its departure. The phone's booking sheet lets the route line under its
title wrap too.
2026-11-19 21:57:28 +01:00
Maurice 2c17edd74c docs(docker): the entrypoint drops to node with setpriv, say so beside its copy 2026-11-19 21:57:28 +01:00
Maurice c5e2afc21b fix(atlas): count places and cities the same way on the Atlas page and in the stats API
The Atlas page showed 100 cities and 169 places where GET /api/v1/stats
and the dashboard's passport card showed 66 and 164 for the same account.
The two sides counted with their own code. The Atlas page took the address
part right before the country as the city, which is often the region
(Bavaria for Munich, Nuremberg and Regensburg alike), and counted a bare
place name with no comma as a city. The stats side read its places with a
DISTINCT over address, coordinates and region only, so two places that
looked alike (the same hotel on two trips, places with neither address nor
coordinates) counted once, and its city reader skipped every address part
with a digit, so "10178 Berlin" never counted as Berlin.

Both now take places and cities from one method: every place counts once,
a city is read with cityFromAddress, which skips the region (#1115) and now
reads a city written beside its postcode (German, French, US, Japanese,
Dutch, British and Canadian forms) while a street with its house number
still does not count, and two spellings that differ only in case are one
city. The Atlas page, the passport card, /api/v1/stats and the MCP atlas
tool follow it. The response shapes are unchanged.

Closes #3137
2026-11-19 21:57:28 +01:00
Maurice 502e6916d9 fix(docker): start under rootful Podman on hosts that block gosu's signals
Started as root, the entrypoint dropped to the node user with gosu. gosu is
a Go program, and Go changes a process's ids by sending every runtime thread
a realtime signal and spinning until each one has answered, with no limit.
On a host whose security module drops that signal inside the container
(AppArmor on recent Ubuntu, under rootful Podman) gosu spun at full CPU
forever, before Node printed a line: no logs, no database, port 3000 never
served. Running as uid 1000 worked only because that path skips gosu.

The entrypoint now drops privileges with setpriv from util-linux, which is
already in the image: single-threaded C that makes the same id changes
without any signal. Node still runs as uid and gid 1000 with no
capabilities and HOME=/home/node. gosu stays in the image for anyone who
calls it by hand.

Closes #3135
2026-11-19 21:57:28 +01:00
Maurice 61674cf918 fix(transit): show every stop name and each ride's arrival in the journey details
The expanded transit card on the phone cut a ride's "from -> to" line to
one line, so a long first stop pushed the destination out of sight, and
it showed only the departure of each ride. The phone's booking sheet and
the desktop leg list (booking dialog, booking card, journey modal) cut
the stop names and the sheet title the same way.

The detail views now let stop names, walk targets and the booking title
wrap instead of truncating, and the expanded card shows each ride's
arrival time under its departure. The collapsed card still shortens its
headline, since expanding it shows everything.

Closes #3139
2026-11-19 21:57:28 +01:00
Maurice ac01925be7 fix(mobile): show a place's full name in its details sheet
The details sheet cut the place name to one line, and nothing in the
sheet showed the rest; only the edit form did. The sheet is where a
place is read in full, so the name now wraps onto as many lines as it
needs, as the desktop inspector already does. The address under it
wrapped before and still does.

Closes #3140
2026-11-19 21:57:28 +01:00
Maurice 99465d04de fix(mobile): the add-place button of the stay sheet takes the caption size
It uses the planner's add-place label, which no view named before, so the
unused-key baseline of planner.ts drops by one.
2026-11-19 21:41:54 +01:00
Maurice 73a7c4843b fix(mobile): a stay can be added to a trip that has no place yet
A stay belongs to one of the trip's places, so on a new trip the
accommodation sheet only said "Add places to your trip first", and the
booking could not be saved without leaving the sheet (TestFlight feedback,
5.1.3). The hint now carries the "Add place/activity" button for anyone
allowed to add places: the place form opens over the sheet, and the place
is listed to pick once it is saved.
2026-11-19 21:31:46 +01:00
Maurice 6e919696bb fix(native): a tap beside a field closes the keyboard
The app hides the keyboard's bar with its "done" button, and a textarea
keeps its return key for new lines, so after typing a note in the place
editor nothing closed the keyboard and it covered the rest of the sheet,
times and Save included (TestFlight feedback, 5.1.3). A tap away from the
focused field now lets go of the focus. A scroll keeps the keyboard open,
and a tap on another field moves the focus there.
2026-11-19 21:27:54 +01:00
Maurice d32cfb3635 fix(native): give the Apple Watch app icon a light background
watchOS crops the icon to a circle on a black face, so the black icon did
not read as a circle at all (App Review, guideline 4). The mark now sits
dark on a light grey ground, drawn from the same master silhouette.
2026-11-19 21:26:38 +01:00
Maurice 31c9f40550 fix(native): App Review builds can buy TREK Cloud while orders are closed
While TREK Cloud's orders are closed, the plan picker on iOS offers the
subscriptions only to builds that buy in the App Store sandbox (TestFlight,
App Review, Xcode). That was read from the receipt's file name alone, which
App Review's build did not carry: the reviewer saw "TREK Cloud opens soon"
and no way to buy, and the app was rejected under 2.1(b) because its
in-app purchases could not be found.

The environment now comes from the signed app transaction (StoreKit 2, iOS
16 and later), with the receipt's file name as the fallback on iOS 15 or
when the app transaction cannot be read. A production build still sees the
plans without a buy button until orders open, and the cloud refuses a
production purchase before the opening as before.
2026-11-19 21:26:38 +01:00
Maurice 7ae4dcba51 fix(db): sort the Postgres move's names with an explicit code-unit compare
Five sorts in the Postgres bootstrap and the move from SQLite relied on the
default sort, which SonarCloud reports as a bug because it compares by code
unit implicitly. They order migration names, table names and JSON keys for a
checksum, where locale-aware ordering would change the result, so each now
names the code-unit compare the default already used. Nothing changes.
2026-11-18 23:58:20 +01:00
Maurice daa4e1dfcf test(planner): an older place lookup that answers last does not replace the newer results 2026-11-18 23:30:37 +01:00
Raz Erlich 9a7bce6fd8 fix(planner): scope transit picks by day and rank other stays by date 2026-11-18 23:30:36 +01:00
Maurice 0834d4f8fe docs(airtrail): name the API key scopes AirTrail 3.13 checks 2026-11-18 23:17:47 +01:00
Maurice d8c28c9998 fix(airtrail): read the v1 answers at the boundary and refuse an arrival before the departure
The v1 bodies were cast to their types unchecked, so a flight page whose data
was not a list, or a passenger list of another shape, failed deeper down as a
TypeError instead of an AirTrail request error. Each v1 answer (a flight, a
page of flights, a created flight, a reference lookup, the key owner) is now
read through a small schema that keeps the fields TREK does not need lenient.

The legacy save refuses an arrival before the departure; the v1 body passed
it on, so an overnight arrival time without its date would have been stored
before the departure. The v1 write-back now refuses it with the same message.
2026-11-18 23:17:27 +01:00
aaronspruit 76ff6e15b1 feat(airtrail): use the AirTrail /api/v1 routes, and keep the legacy routes
AirTrail 3.13 adds /api/v1 and marks the /api/flight/* routes as
deprecated. TREK now asks the public discovery document GET /api/v1
and uses v1 when the instance has it. It uses the legacy routes for
an older instance. The client methods keep their signatures, and the
sync hash stays the same, so a linked flight does not sync again
when an instance changes to v1.

The probe cache holds only a clear answer: 200 with the discovery
document gives v1, and 404 gives legacy. The cache is per AirTrail
URL, for 10 minutes. A timeout, a 5xx or a network error fails that
call only. A 401, a 403 or a page that is not the discovery document
uses legacy for that call only. A 404 for one flight makes the client
ask the probe again before it reports the flight as deleted.

A missing scope gives AirtrailScopeError, which names the scope. It
does not unlink a flight. The API key hint and the help step list
the scopes for read and for write-back, in all languages.

Each new request goes through safeFetch, with the SSRF guard, the
timeout and the size cap. The flight list reads pages of 100 and
fails above 50 pages. A failed list unlinks nothing.

airtrail-v1.ts translates between the v1 shapes and the legacy
shapes. A write-back looks up the airport, airline and aircraft ids,
and changes each local time to a UTC instant in the zone of its own
airport. It writes each instant in the +00:00 form of the legacy
save, because AirTrail stores the string as it gets it and the sync
hash reads that string.

The tests cover both APIs over HTTP, the probe cache rules, the sync
hash on a switch and on a save, the page limit, the scope error, and
the UTC conversion across midnight, the date line and daylight-saving
changes.
2026-11-18 23:07:35 +01:00
Maurice 3e0a2ef8ed fix(native): widgets turn to the next trip day by themselves
TestFlight feedback: during a trip the widgets stayed on day 1 until the app
was opened again. The app wrote only today's day into the widget snapshot,
and only while it ran, so every timeline entry after midnight still showed
the day it last ran, with its stops all ahead again.

The snapshot now also carries the trip's days from today on (a month at
most, sixteen stops a day), each with its date. On iOS every timeline entry
takes the day of its own date, so the quarter-hour entry at midnight turns
the widget to the next day, and the bookings list drops the days behind; the
Android widgets do the same on each update. A snapshot from an app without
the days reads as it was written, and an older app binary ignores them.
2026-11-18 22:21:26 +01:00
Maurice fd35f79c36 fix(mobile): keep every screen clear of an iPhone Duo's status capsule
TestFlight feedback: on an iPhone Duo the status capsule in the top right
corner covered the trip's controls, its day chips, the map's category bar and
the first cards of every trip tab, upright and on its side. The app has
measured the capsule since 0f42b8b8a, but only the shell's own bars and page
used it, and the trip, its map and the sheets place their own controls.

- Upright, a control row in the capsule's height stands beside it and the
  content starts below it: the trip's top row and day chips, the map's
  category bar, the road trip's stage bar, every trip tab's first row, the
  places browser, the plan timeline, docked and card sheets, the assistant,
  the account menu, the image viewer's close button, the atlas search,
  vacay's header and a journey's content and map controls.
- On a wide window the page gives up the capsule's side over the whole
  height instead, as an iPhone on its side does for its camera: lifting each
  page below the capsule cost a quarter of the height of an unfolded Duo.
  The list tabs, the assistant panel and the form sheets end before it too.
- Screens whose first row is part of the page (settings, administration,
  collections) are lifted until that row is below the capsule; screens that
  keep clear of it by themselves (atlas, vacay, a journey) are not lifted.
- Right to left the rail stands on the capsule's side and takes it.

All of it reads the corner variables the app publishes, which are 0 on every
other device and before iOS 26, so nothing else moves. The rules for the
screens that place their own controls live in mobile/corner.css.
2026-11-18 21:23:14 +01:00
Maurice 294a386d23 fix(planner): take a ?tab=, ?day= or ?assistant= link once per URL
React Router lands the URL without the link as a transition. Until it does,
every render still read the link, and the tab link took it again on each of
them: selectTab is a new function per render and onLinked sets state, so a
notification's ?tab= link rendered the planner into React's update limit and
the route's error page replaced the trip on an iPad or an unfolded foldable.
Both link hooks now take a link once per URL and wait for the cleaned one;
the same link in a new URL is taken again.
2026-11-18 21:23:03 +01:00
Maurice ee79413653 fix(mobile): keep the navigation rail's list ref stable
The rail's list ref was an inline function that set state. React 19 detaches
and re-attaches a ref whose function changed, so every commit set the list to
null and back and asked for one more render of the rail. The ref is one
function for the rail's lifetime now.
2026-11-18 21:23:03 +01:00
Maurice ec08915a16 fix(trips): a day added before the start leaves the plan on its dates
Adding a day before a trip's start with "Keep bookings on their dates"
moved almost everything a day earlier and emptied the last day. The day
grid was always rebuilt by position: the n-th day row took the n-th date
of the new range. With bookings kept on their dates, only timed bookings
and stays were re-anchored afterwards. Places, day notes, bookings with no
time and a booking's place in a day's order stayed on their re-dated rows
and slid to the day before. Days added at both ends had the same problem.

planDayGrid now takes keepDates. When the new range still holds every
dated day, each of them keeps its date and the new days go around them.
The server passes it unless the traveller chose to shift everything, and
the trip dialog's warning check uses the same rule. A moved or shorter
range still follows the positional rule the dialog describes, and "Shift
everything" still moves the whole plan with the new start.

Two things keyed outside the day rows followed the old rule. Road trip day
boundaries are keyed by day number, so a new first day left each one on
the day before its own. They now follow their days to their new numbers
and go out to every screen. The owner's leave days moved by the change of
start even when days were only added. They now move by as far as the
trip's first day moved, which is nothing when days are only added. The
help text of the option and the MCP description say what happens when
days are added.

Closes #3119
2026-11-18 17:14:38 +01:00
Maurice 40f9c020bb fix(bookings): show the calendar date beside transport times
Tapping a transport in the compact Transports or Bookings list on the phone
opens the transport sheet, and its time boxes showed only the clock time. The
sheet named a date only in its subline, and only for a booking with no route
and no airline or number, so a flight or ferry could not be placed on a day
without unfolding the whole list. A transport holding only times (its date
lives on the linked trip day) had no date at all, and the desktop transport
detail dialog had the same gap: it read the date off reservation_time alone
and never named the arrival day of an overnight trip.

The dates now come from one helper, bookingDates(), which reads the booking's
own date, then the stop's local date, then the linked day's date, the rule
bookingFacts already used and now shares. The phone sheet prints the date
above each time (a leg opened from its row uses its own days); when no time
box carries a date, because no time is entered yet or the live flight card
stands in their place, the subline names the day instead. The desktop dialog
names the day, or both days of an overnight trip in reading order, in the
user's locale.

Closes #3122
2026-11-18 16:52:18 +01:00
Maurice 684a3bf5f5 fix(roadtrip): draw the drive between connected days in the arrival day's colour
With "Connect the days" and "A colour per day" on, the drive from one day's
last stop to the next day's first stop was coloured as the day it left. A stop
reached after midnight was handled the same way: the line into it kept the
colour of the day it came from. The road trip panel counts both drives toward
the arriving day (its distance includes them, and the setting's hint says
connecting drives count toward the arrival day). So the map showed the drive
under one day while the panel counted it under the other. This also happened
with daily travel times set to end the day at the last place, whenever the
schedule could not be kept (a drive longer than the window) and the days were
drawn as stored.

assembleRoadtrip now puts every line drawn into a day under that day's
number, the day whose figures count it, and still marks it as a join, so the
one-day stage view still leaves it off. Every map takes its day colours
from this list: desktop Leaflet and Mapbox GL, the phone map and its stage
view. The client tests that pinned the old colouring and the old join order
now expect the new ones.

Closes #3123
2026-11-18 16:52:17 +01:00
Maurice 26122a4208 ci(test): mirror the dev push run on the release pull request
Every push to dev started test.yml twice for the same commit: the push
run on dev and the pull_request run of the open release PR into main.
Together about 72 long jobs exceeded the 60 organisation slots, so jobs
queued and ci-ok landed minutes later.

On a pull request from dev into main (head in this repository) the
changes job now sets mirror and turns every area off
(scripts/ci/changed-areas.mjs), so no gate, test, coverage or scan job
runs. ci-ok keeps its needs verdict and then runs
scripts/ci/mirror-push-run.mjs, which waits for the ci-ok of the push
run of test.yml on dev for exactly the PR head commit and passes or
fails with it. A missing push run, one that ended without a verdict,
an API that keeps failing or a wait past 17 minutes fails with a
re-run hint. ci-ok reads with actions, checks and contents only, and
its timeout rises to 20 minutes.

A push to dev now lists its changes against the merge base with main
instead of the previous push, so the run the mirror copies covers
every area the release pull request brings in, also when an earlier
push's run was cancelled or red.

The release workflows keep reading the newest ci-ok on a commit. A
green mirror implies a green push ci-ok before it; a mirror that fails
on its own blocks a release until it is re-run.
2026-11-18 16:18:46 +01:00
Maurice 9dc80760f7 feat(server): name the database in the start banner
The move guide tells the operator to check that the log reports the Postgres engine, but the start banner never said which database the process runs on. It now carries a Database line with the engine's own description: the SQLite file, or the Postgres URL with its password masked. The guide's check and the manual checklist point at that line.
2026-11-18 15:43:26 +01:00
Maurice 090db8519d docs(postgres): document the volume path per major and what the move carries over
The compose pages name postgres:18, list the volume path for 18 and for 14
to 17, and say that changing a database's major needs pg_upgrade or a
backup and restore. The move steps say to carry the install's own
environment variables, container name and port over, and to append the
passwords and COMPOSE_FILE to the existing .env instead of replacing it,
so later plain docker compose commands, the ones in Updating included, keep
using the Postgres file instead of starting TREK on the old travel.db. The
pages also say which data is lost to an anonymous volume, which compose
service waits for the database, what tables that differ from the Postgres
schema mean, and how to recover from a first start without a password.
2026-11-18 15:22:52 +01:00
Maurice efc55ac700 fix(deploy): run the Postgres compose on postgres:18 without the Swarm-only config mode
The postgres image refuses a volume at /var/lib/postgresql/data from 18 on,
so the db service now mounts /var/lib/postgresql, and the file says that 14
to 17 need the old path and that an existing database keeps its image tag
and path. Compose ignores a config's mode outside Swarm and warned about it
on every command, while the image sourced the init script anyway. The mode
is gone and the script runs its work in a subshell, so set -eu and exit stay
inside it and a failure still fails the first start whether the script is
sourced or executed.
2026-11-18 15:22:52 +01:00
Maurice 85b773420c fix(db): say what a schema difference means when the move to Postgres refuses it
The refusal listed the differences and nothing else. A table or column
only one side has now comes with what that means: the file is at this
version's level, the start that brought it there added every column it
could, the start log names the rest, and the operator keeps running on
SQLite and reports it. A column of TREK's own schema the move cannot copy
is listed apart and named a bug in TREK, since the file is not at fault.
The server guide describes the gap, the repair, the check and the refusal.
2026-11-18 15:22:51 +01:00
Maurice 771dab7c35 feat(db): name the tables and columns the database lacks on every start
After the migrations, both engines compare the declared entities with the
live schema in one catalog statement and log a warning naming each table or
column that is missing, what fails because of it, and that it should be
reported. It never refuses a start, not even when the check itself fails,
and says nothing on a database the migrations built; a Postgres lane suite
holds that on a real server.
2026-11-18 15:22:38 +01:00
Maurice ca7cdcebcc fix(db): add every column an upgraded pre-ORM install can lack
The legacy baseline records the positional runner's steps up to
schema_version as executed without running them, so a column that runner
never added stays missing for good. Two things in its history left such
gaps: a step inserted below a version a build had already shipped (step 53,
users.mfa_backup_codes, so turning on MFA failed there) and a column added
to createTables() with no step (users.immich_access_token).

Migration20200101046460 adds, where missing, every column the schema held
at legacy step 258 that head still holds and ALTER TABLE ADD COLUMN can
add, declared as head declares it; on Postgres every one of them is in the
baseline, so nothing is added there. The list is derived again from the
migrations in tests/unit/db/legacy-column-repair.test.ts, which also adds
all of them to a database lacking them and upgrades a v244 install shaped
like the one whose move to Postgres was refused.
2026-11-18 15:22:38 +01:00
Maurice 6bc27a259b ci(test): give the e2e container a compiler on a node_modules cache miss
better-sqlite3 compiles on install, and the Playwright container has no make or g++, so the first e2e run of a lockfile failed in npm ci. The setup action now installs both when they are missing, before npm ci; a cache hit skips the step.
2026-11-18 14:52:59 +01:00
Maurice a2d9c2416d ci(native): drop the watch-bridge job and the lockfile trigger
watch-bridge repeated the client typecheck and three client test files
that test.yml already runs on every change under client/, inside ci-ok.
The shells link only @capacitor/* packages, all declared in
client/package.json, which stays a trigger, so a native dependency bump
still builds iOS and Android while lockfile-only bumps no longer queue a
Mac build.
2026-11-18 14:48:44 +01:00
Maurice fd1942afab ci(test): restructure test.yml for a ten-minute ci-ok
Rename the workflow to CI and name every job "<Area> <what>[ i/n]" with
ids in kebab-case, in area order. Fold i18n parity, shared coverage and
the plugin SDK into Shared tests, split the client gates into Client
types and Client checks (with the bundle), and merge the image and chart
jobs into Docker and Helm with per-area step conditions. Server and
client tests run in ten slices, the Postgres lane in three per major,
and e2e in two slices inside the digest-pinned Playwright container.

A local setup action restores node_modules and shared/dist from exact
cache keys and falls back to npm ci and the shared build. The
node_modules key covers the lockfile and every workspace package.json,
so npm ci still refuses a package.json out of step with the lockfile.
Only pushes to dev and main save, the npm download cache included, and
only a full install saves that one. The plugin SDK installs and runs
before the root install so it resolves only its own dependencies.
Timeouts drop to 15/10/5 minutes. The workflow tests now check the name
form, the Playwright tag against the lockfile, scan's needs, timeouts,
the cache keys and saves, and that installs go through the setup action;
.github/actions/ counts like test.yml in changed-areas.
2026-11-18 14:48:43 +01:00
Maurice 23eabe1499 style(server): format the doc-sync controller test 2026-11-18 13:44:54 +01:00
Maurice bcc82db7bd test(server): pass numeric row ids to controllers and seed addons with booleans
Controllers read their path ids through the rowId pipe now, so unit tests that call a handler directly pass the number the pipe hands it. The e2e suites enable addons with true, the type of the entity's field. The realtime gateway test builds its book sockets through one helper instead of a second hand-built TripAccessService.
2026-11-18 13:36:37 +01:00
Maurice 26b220470a fix(shared): parse an id param's digits with Number before the integer check
The union of an integer and a digit string fed z.coerce.number() through pipe(), which Zod 4 types with an unknown input and tsc refuses. The digits are now turned into a number with Number and checked by z.number().int().positive(), the same rule as before.
2026-11-18 13:24:09 +01:00
Maurice cdc31967b2 docs(db): describe the final Postgres, plugin data and deployment behaviour
wiki/Database-Postgres.md, server/CLAUDE.md and the plugin SDK docs now
describe what plugin SQL may name on Postgres, the pinned output
settings, the shared contract (NUL and transaction control refused on
every engine), the move's refusals, the Postgres lane in two slices per
major on 14 and 18, and that TREK runs as one instance on either engine.
server/.env.example names the version 18 client tools the image ships,
and the troubleshooting entry and the Helm values name the full set of
roles a restore refuses. A doc-paths baseline entry that no longer
applies is removed.
2026-11-18 13:20:10 +01:00
Maurice 4a435df6e4 fix(plugin-sdk): apply TREK's plugin data contract under trek-plugin dev and the mock host
trek-plugin dev and createMockHost copied the db:own checks by hand and
let through what TREK refuses (NUL, transaction control outside tx()), so
a plugin worked locally and failed in TREK. Both now read the contract
from src/plugin-data-contract.ts, a byte-identical copy of the server's
file that the parity test compares, and check in the server's order.
Tests compare every refusal of the dev database and the mock host with
the contract's text.
2026-11-18 13:20:09 +01:00
Maurice 21f4f7d5de docs(server): plain wording in the comments and test titles this change added
Comments and test titles added on this branch cited review labels and
planning documents that do not exist in the repository, and some used
dashes as separators. They now say what the code does and why in plain
sentences, and the Postgres lane's suites share one header format. Test
ids stay as they were.
2026-11-18 13:20:09 +01:00
Maurice e3d195896c ci(postgres): run the lane in two slices per major with fsync off
Before Postgres 15, every CREATE DATABASE ... TEMPLATE the lane runs per
file is two checkpoints waiting for fsync, and the lane took 20 to 23
minutes on 14 against about 12 on 18. The service now runs with fsync
off, set through ALTER SYSTEM and a reload and checked afterwards. A test
database has nothing to keep through a crash.

Two slices per major replace three, so four long jobs replace six. The
job-count note in test.yml now states the real count: up to 30 jobs, 24
of them long, for 20 organisation-wide slots. At least four long jobs
start only after another has ended. A run with six slices started nine
long jobs four to five minutes late and ended its client coverage eight
minutes after the on-time shards. The job comment says what was measured
on CI and what only locally. The lane docs say two slices, and the root
guide describes the slice gate.
2026-11-18 13:20:09 +01:00
Maurice 911bd825c1 test(ci): fail every sliced job whose slice count the gate cannot hold to one
A sliced job states its slice count three times: the matrix shard axis,
the i/n in its name and the --shard=i/n it hands vitest. Changing one and
not the others still passes and leaves part of the suite in no slice or
reports the wrong count. workflow-jobs.test.mjs now treats every job that
names matrix.shard or runs --shard as sliced and fails, naming the exact
fix, until the three agree. A job whose axis is not the one-line
"shard: [1, ..., n]" form fails too, instead of going unchecked, and so
does a fixed --shard. Tests on small inline workflows hold the reader
itself to these cases.
2026-11-18 13:20:08 +01:00
Maurice 81628d78ee fix(db): name the Postgres compose file in the move command hint
The boot refusal beside a SQLite install told the operator to run the move
with plain `docker compose run`, which uses the SQLite compose file. It now
gives the command the wiki gives, and PGBOOT-037 holds both to the page.
2026-11-18 13:20:08 +01:00
Maurice 69e791206e fix(db): trace a broken key in the move without blaming the wrong row
The move read unique indexes by joining indkey to pg_attribute. An expression key such as lower(email) has attnum 0 there, so idx_users_email_lower was missing from the plan. The catalog query now reads each index's key as Postgres prints it, whether any part of it is an expression, and the columns it reads: the plain key columns and the Var nodes of indexprs, without INCLUDE columns or the predicate.

A broken unique key no longer names --drop-nul as its cause. The refusal names the key and the shared value from Postgres's detail. It explains that the SQLite file held the two rows apart, and the hint about SQLite's lower() appears only for an expression key. Values --drop-nul changed in the key's columns are listed as rows to check first, and only when the duplicate value holds their text. An unrelated value that lost a NUL is no longer named. A plain key over a quoted column is named by its column, not as an expression.

A row that breaks a constraint (SQLSTATE class 23) is now a MoveRefusal that says what to correct, in the SQLite file or in a plugin's plugin.db. Before, it was a bare error with a stack. A value Postgres refuses by its type (class 22) stays a failure: it names no row, and values.ts should have refused it first, so the message asks for a bug report. MoveRefusal and the remedy text move to refusal.ts so copy.ts can use them without an import cycle. The usage text of --drop-nul and the wiki's move section describe NUL in JSON, the key listing and these refusals.
2026-11-18 13:20:08 +01:00
Maurice e66330e226 fix(db): treat a raw NUL in JSON like any NUL in the move
A raw U+0000 in TREK's JSON text, which an old or hand-edited travel.db can hold, was refused as "not valid JSON" without naming the NUL or the remedy. It is now refused with the NUL reason, so the refusal names --drop-nul. With --drop-nul, raw and escaped NULs are removed and nothing else, the way TREK's own writes drop them, and each change is listed. Text that is not valid JSON even without its NULs is refused as that, and the checksum's source side follows the same rule.

A \u escape of half a surrogate pair parses in JavaScript but jsonb refuses it. Before, that failed the insert without naming a row. It is now refused by table, row and column.
2026-11-18 13:20:07 +01:00
Maurice c970245e0d fix(plugins): hold plugin data on Postgres to its own schema and to one contract on both engines
The plugin SQL guard now refuses what still reached outside a plugin's
schema or depended on the server:
- reads of the system columns (xmin, xmax, cmin, cmax, ctid, tableoid),
  which show transaction ids and storage layout and do not exist on
  SQLite; a value of the plugin's own may still be named xmin with AS
- the xid and xid8 types wherever the word stands for the type, since
  age() of an xid is the cluster's transaction counter
- the text search functions that coerce a text argument to regconfig, a
  catalog lookup by name, which leave the allowlist
- collations and access methods outside the set every server has, which
  could tell whether a locale or an extension exists

Every plugin transaction pins, with SET LOCAL, the settings that decide
how values print and parse (TimeZone UTC, DateStyle, the C locales, float,
bytea and xml output, the text search configuration), so a plugin's output
neither depends on nor reveals the server's configuration.

Both stores now keep one contract. Its texts and caps live once, in
plugin-data-contract.ts, and both stores throw only those: NUL in SQL,
an argument or a migration id is refused on SQLite as on Postgres,
transaction control is refused in every call on both engines (tx() is
how a batch becomes atomic), a closed store refuses every call, and the
Postgres store answers the cases better-sqlite3 names with its words.
The SQLite store moves beside the Postgres one as SqlitePluginDataStore
in db/engine/sqlite, takes its file from the backend so src/db never
imports src/nest, and no longer needs the driver exemption. A contract
test runs every violation on both stores and fails when they answer
differently. The Postgres lane holds the allowlist, the pinned settings
and the SQL plugins commonly write against a real database.
2026-11-18 13:20:07 +01:00
Maurice cc0fe6ce2b test(api): hold every request row id to toRowId on paths, bodies, queries, MCP URIs and plugin RPC
ROUTEID walks every route the app registers.
- ROUTEID-001 sends 'abc' and the non-canonical spellings of a seeded row's id to each path param named like an id, and requires no 5xx and the answer 'abc' gets. It then sends the spellings of an id no row has and records what the database drivers are handed (tests/helpers/sql-capture.ts, below MikroORM and Kysely). It fails when a spelling, or the number Number() makes of it, reaches SQL, so a route over a table the suite seeds nothing in is held too. Stale NOT_ROW_IDS entries fail, and the walk runs on one listening keep-alive server.
- ROUTEID-002 walks every @trek/shared request, body and query schema and every route's body and query DTO, and fails on a field named like a row id that accepts such a spelling. String ids are listed with their reason; open fields name the handler test that holds them.

Three more suites cover the other entry points:
- MCPROWID does the same for every MCP resource template.
- RPCROWID refuses a plugin RPC id param read past rowIdParam.
- BODYID, JRNID and QUERYID cover the open accommodation update body, the collab reply, the journey fields a handler parses itself and the notifications limit and offset.

All suites that boot the app run in the SQLite suite and in the Postgres lane on 14 and 18. server/CLAUDE.md states the rule and the four gates.
2026-11-18 13:20:07 +01:00
Maurice 39346ceca7 fix(mcp,rpc): parse resource URI, websocket and plugin RPC ids with toRowId
Eleven MCP tool files carried their own parseId, which used Number() and so took '0x1' and '1e20'; they now share uriRowId. The websocket join and book:join read the id with toRowId instead of Number().

Plugin RPC ids go through rowIdParam instead of num(), and a param that may be left out goes through the new optionalRowIdParam. num() let '0x5', 1.5 and 1e20 through, which Postgres refuses or reads its own way while SQLite matches nothing.

accommodations.create read its refs with Math.trunc(Number()), and accommodations.update bound its open input's refs as sent. collab.createMessage took replyTo only when typeof was 'number', which let 1.5 and 1e20 through. All three now read their ids as row ids. A canonical numeric string still passes, as the published contract says, and the refusal keeps num()'s message.
2026-11-18 13:20:06 +01:00
Maurice 6dfba51f21 fix(api): read body, query and handler-parsed ids with toRowId instead of Number() and parseInt
The services and controllers that took an id from a request with Number(), parseInt() or not at all now use toRowId. That covers admin users, notifications (and their limit and offset), trip members and guests, day notes, assignments, memories (photo owner, album link, body photo_id), photos, mail-ingest, the assistant id parsers, dawarich, registration invites, the plugin contribution routes and the collab reply.

The accommodation update body is open, so AccommodationsService reads the place and day refs of every stay write with toRowId and answers a refused one with the create schema's 400.

AdminService.deleteUser checked the caller with parseInt and deleted with Number(), so an admin could delete their own account by spelling its id in hex; both now use one parse.

The OAuth session revoke called Number(id) first and so revoked session 5 for '0x5'; the service now reads the id as sent.
2026-11-18 13:20:06 +01:00
Maurice 3973741509 fix(shared): refuse a malformed row id in every request schema
Request fields that hold a row id took z.union([z.number(), z.string()]), a bare z.string() or z.array(z.number()), so '0x5', '5e0', 1.5 and 1e20 reached the handler and from there SQL, where SQLite matches nothing, Postgres 14 and 15 refuse the cast and 16 and later read hex and underscores as a number. Two primitives join idParamSchema: rowIdInputSchema takes a safe integer or its digits and keeps the value as sent, so field types do not change; rowIdStringSchema takes digits only, for multipart fields. Both refuse with 'Invalid id'. The accommodation, assignment, reservation position, admin invite, collab reply, vacay, file and memories photo ids now use them, and every list of ids is z.array(z.number().int()). idParamSchema takes only the decimal spelling or a whole number, and the trip-journal-link and tour library ids use it. A body id spelled '0x5' is now a 400 on SQLite too.
2026-11-18 13:20:05 +01:00
Maurice 3eac508baf fix(api): parse path ids with a rowId pipe that answers like an unknown id
RowIdPipe (src/nest/common/row-id.pipe.ts) parses a path param with toRowId. It answers a refused spelling with the route's own not-found answer, so '0x5', '5e0' and 'abc' get what an id that names no row gets. ParseRowIdPipe replaces Nest's ParseIntPipe with the same 400 and message: ParseIntPipe let '-1' and numbers past 2^53 through, and Postgres refuses the latter as out of range. Journey, journey recordings, day import, book design, map, public photo, collections, doc-sync, vacay, atlas and the plugin user-data export declare their ids through it. The upload routes parse in the handler with withRowId, so a refused id takes the existing cleanup path, or carry SpoolCleanupInterceptor (collections).
2026-11-18 13:20:05 +01:00
Maurice 7f6f2eb97c fix(db): read every request row id through toRowId, at the trip guards and the repository lookups
toRowId moves to src/db/row-id.ts so repositories can use it (src/db sits below src/nest), together with a new withRowId helper; src/nest/common/row-id.ts re-exports both. Its docstring is rewritten to state the rule plainly. TripsRepository read its number | string trip ids raw: SQLite matched '0x1' against nothing, Postgres 14 and 15 refused the cast with a 500, and 16 and later read it as trip 1. Its access reads, DaysRepository.existsInTrip and the packing template lookups now parse the id first, so an id toRowId refuses is no row on every engine. TripAccessGuard, TripOwnerGuard and JourneyAssistantGuard used Number(), which read '0x1' and '1e0' as row 1; they now use toRowId.
2026-11-18 13:20:05 +01:00
Maurice f2cfbc4041 fix(db): close the move's remaining silent changes
An attack on the move to Postgres with real SQLite files found five values
that changed without a refusal or a listing, or a valid file that failed:

- Negative zero in a plugin column became 0: pg sends the number -0 as "0",
  and the checksum printed both as "0". It is sent as text and kept apart in
  the checksum on both sides.
- Text whose bytes are not valid UTF-8 was read with each bad sequence
  replaced by U+FFFD, and the checksum was built from the replaced text.
  Text is now read as its bytes and decoded strictly in the file's encoding
  (UTF-8, or UTF-16 for a file created so); such a value is refused in
  TREK's and in plugin data, with --drop-nul too, and listed with its bytes.
- --drop-nul serialized a JSON value again, so a large number lost digits
  and 1.0 became 1. Only the \u0000 escapes are removed now.
- A plugin default Postgres refuses for the column (DEFAULT 0 on a BLOB
  column) failed the move, and DEFAULT 1.5 on an integer column would have
  been rounded. Such a default is left off and listed as not carried over.
- A plugin index or primary key SQLite compared with COLLATE NOCASE or RTRIM
  became one that compares exactly. It is still created, and the summary
  lists the collation it lost.

Each case has a regression test that fails without its fix, on SQLite and
on the Postgres lane.
2026-11-17 23:30:35 +00:00
Maurice 636fc7d0a6 fix(db): refuse the column notation without parentheses and aclitem in plugin SQL
Postgres reads x.f as the call f(x) when x has no column f. The guard counted
that spelling only after ")." or "].", so over a function in FROM that
returns a single value, or a parameter, the allowlist was bypassed:
"select g.obj_description from generate_series(...) g" returned the comments
on every object of the database, and g.current_schemas, g.txid_status and
$1.ts_token_type passed as well. A refused catalog function after a dot is
now refused too, except the names in COLUMN_NAMES (money, name, oid, version,
xid, xml), which take no argument or only convert it to their type, so t.name
keeps working. PGPLUG-021 holds that list to pg_proc on the lane's server.

The type aclitem names roles: '=r'::aclitem printed the cluster's first
superuser and 'x=r/x'::aclitem told whether a role exists. It is refused in
every spelling like the reg* types.

The allowlist itself moves to assets/postgres/plugin-functions.txt, beside
the catalog list it is checked against. As TypeScript it spelled 'like' and
'json_each', names of Postgres functions that the SQLite dialect gate reads
as SQLite SQL.
2026-11-17 23:30:29 +00:00
Maurice adcda60f7d ci(postgres): run the Postgres lane in three slices per major
Since the lane runs every suite that boots the app it takes about ten
minutes on Postgres 18 and about 25 on 14, past the job's 20 minute timeout.
Each major now runs it in three slices (--shard=i/3), each on its own runner
and service with its own template; the probe and its artifact stay once per
major, in the first slice. ci-ok still needs server-postgres, whose result is
failure when any slice fails or is cancelled, so every slice is required.
2026-11-17 22:50:02 +00:00
Maurice e8f808b67f fix(reservations): parse every referenced id in a booking body with toRowId
The booking body is not schema-checked, so day_id, end_day_id, place_id,
assignment_id, accommodation_id and the create_accommodation ids can arrive
as any string. The reference guards passed them to SQL as they came. SQLite
compares '0x5', '5e0' or 'abc' against an integer id and matches nothing
(or, for '5e0', the row), so the guard answered "Unknown reference". Postgres
refuses the cast on 14 and 15 and reads hex as a number from 16 on, so the
same body answered a 500 on one major and reached a real row on another;
the Postgres 14 lane caught it in L2.

Both guards now read each id through toRowId, the rule every other untrusted
row id follows: an id it refuses resolves to nothing, so referencesOutsideTrip
does not name it and unresolvedReferences does, and the answer is the same
400 on every engine. create() reads the payload's accommodation_id through
toRowId as update() already did, instead of storing '0x5.0', which the
reads' join could not cast back on Postgres.

ReservationRow and ReservationTraveler move to reservation-rows.ts, the way
reservation-inputs.ts holds the input shapes, so the service stays within
its size baseline; the service exports them on and it is lowered to 1166.
2026-11-17 22:49:55 +00:00
Maurice 70108e5694 test(memories): type the Synology fakes' request init as RequestInit
The fakes that answer safeFetch by API took their init as any; safeFetch
declares it as RequestInit, which is what they read (the body as
URLSearchParams or text). The SSRF album case had gained one more of them,
which put the tests' no-explicit-any count one over its baseline. All five
are typed now, and the baseline is lowered to the 1545 the tests hold.
2026-11-17 22:49:55 +00:00
Maurice c75fb22289 docs(db): describe the move's refusals and --drop-nul
The wiki's move section, the server guide and the nul-free header said
the move drops NUL as every write does. They now say what it does: a
plugin's data moves unchanged or the move is refused with the values
listed, TREK's own NUL is refused unless --drop-nul is given, which lists
every value it changed, and the checksum comes from the SQLite values.
2026-11-17 23:28:42 +01:00
Maurice 621b2f17df test(db): run the move's NUL and plugin type rules on a real Postgres
The plugin in the move suite gains a BLOB column holding text and an
untyped column holding numbers, and the plugin store must read both back
as they were stored. A new suite moves a file whose plugin and own rows
hold NUL: the plugin's refuses before anything is written, TREK's
refuses until --drop-nul, a username that dropping the NUL makes
duplicate is named with users_username_unique, and a move without a
collision lists the value it changed and stores it without the NUL.
2026-11-17 23:28:41 +01:00
Maurice bc6728678b fix(db): let the move to Postgres change nothing silently
The move stripped NUL from a plugin's own text, merging keys that were
distinct, and turned a plugin's values into another type (text in a BLOB
column into bytea, numbers in an untyped column into text). Its checksum
was built from the converted values, so both passed as verified.

A plugin's data now moves exactly as the Postgres plugin store would
hand it back, or not at all: a NUL, a value of another storage class
than its column, or an integer past 2^53 refuses the move before
anything is written, listing plugin, table, row and column. A column
left open by SQLite's affinity takes the kind its values need, so text
in a BLOB column stays text.

TREK's own text holding a NUL from an older install is refused by
default too. --drop-nul drops it, lists every changed value in the
summary, and names a unique key that dropping a NUL broke.

Every table's checksum is now built from the values read from SQLite,
so a conversion that changes a value fails the verification.
2026-11-17 23:28:41 +01:00
Maurice 6040b60e86 fix(db): keep NUL only in the password fields TREK hashes, not every key naming a password
nulFreeInput left a string as sent under any key containing "password".
That covered the admin settings password_login and password_registration,
which are flags: 'true\u0000' failed the lockout check as a disabled
password login while the database stored 'true'. It also tested the raw
key, so 'pass\u0000word' lost the NUL of the password it carried.

The exemption is now HASHED_PASSWORD_KEYS, the fields TREK only ever hashes
with bcrypt (password, current_password, new_password), matched exactly on
the key without its NUL. A unit test reads every field of the shared
schemas and the instance settings named like a password, passphrase or
secret and fails until each is either in that list or decided against with
its reason.
2026-11-17 23:22:59 +01:00
Maurice 2edf5f807a fix(db): let a plugin call only an allowlist of Postgres's catalog functions
The plugin SQL guard refused functions by name, so every function that reads
the catalogs or the server and was not listed passed: obj_description,
col_description and shobj_description returned the comments on TREK's
tables, columns, database and roles by OID, format_type named a type by its
OID, and version(), current_database(), inet_server_addr() and the session
keywords described the server.

A call to a pg_catalog function is now refused unless the function is on
PLUGIN_FUNCTIONS (string, number, date and time, JSON, array, aggregate,
window, UUID, range, geometry, network and text search functions), in
either spelling of a call, f(...) and the column notation (x).f. The
catalog's function names of Postgres 14 to 18 are kept in
assets/postgres/catalog-functions.txt, and PGPLUG-021 fails on the lane
when the server has a function that list does not name, so a new major
cannot widen what a plugin may call. The session keywords current_user,
session_user, current_role, user, system_user, current_catalog and
current_schema are refused unquoted.
2026-11-17 23:22:59 +01:00
Maurice fd864cc441 chore(lint): read the rule test's parser from typescript-eslint and drop a stale knip entry 2026-11-17 23:04:13 +01:00
Maurice b004d3b88e test(journey): a NUL inside a share token is dropped before the lookup 2026-11-17 23:04:13 +01:00
Maurice 9b1bd6e435 test(memories): answer the SSRF album case by API, not by call order 2026-11-17 23:04:12 +01:00
Maurice 73f3aa8309 test(db): give the stand-in migration storage the master transaction calls 2026-11-17 23:04:12 +01:00
Maurice 82195c7418 fix(db): type the cleaned cookies for the strict compiler 2026-11-17 23:04:12 +01:00
Maurice 9fd77b04fa docs(db): describe the layers that hold plugin SQL on Postgres and the NUL rule for plugin data
The plugin-sdk README, the Postgres wiki page and server/CLAUDE.md now name
the layers as the code enforces them: the refusal on a privileged role and
the boot log line, the guard (the reg* types, INTO after the statement's
own INSERT or MERGE only, TEMP only where it makes a temporary object), the
targets Postgres resolves before an ALTER, DROP, REFRESH, TRUNCATE or
CREATE INDEX, one statement per round trip, pg_temp last, and the quota over
every relation with the object cap. They also say that a plugin argument
holding NUL is refused on Postgres and bound exactly on SQLite.
2026-11-17 23:04:12 +01:00
Maurice f1ea716305 fix(db): hold plugin SQL on Postgres in layers the database enforces
The token guard kept leaking: on a superuser connection an unqualified
`alter type int4 rename to int4x` renamed pg_catalog's type for the whole
server, sequences and catalog-only objects grew the database past the quota,
regtype/regconfig/regdictionary looked TREK's objects up by name, and a
column alias named insert or merge in front of INTO made a table. Instead
of a longer word list, the store now asks the database:

- No plugin SQL while TREK's role is privileged in the sense of the restore
  check (PRIVILEGED_ROLE_SQL, imported from server-checks.ts): every db:own
  call fails with PRIVILEGED_ROLE_PLUGIN_REFUSAL, read once per pool
  connection, and the boot log says why.
- The objects an ALTER, DROP, REFRESH, TRUNCATE or CREATE INDEX ... ON
  changes, and the tables a CREATE or ALTER TABLE ties to its own, are
  resolved with to_regclass/to_regtype in the transaction right before the
  statement, and it is refused unless each one found lies in the plugin's
  schema. An unqualified int4, text or box is pg_catalog's and refused even
  with the role check off.
- The quota counts every relation of the schema with its TOAST table, and a
  schema holds at most PLUGIN_SCHEMA_MAX_OBJECTS catalog objects (relations,
  types, constraints, enum labels).
- The guard refuses every reg* type and its array in every spelling, the
  has_*_privilege functions, currtid2 and the BRIN/GIN maintenance
  functions; INTO only after the INSERT or MERGE that is the statement's
  verb or a WITH body's; TEMP only where it makes a temporary object
  (CREATE TEMP/TEMPORARY, SELECT ... INTO TEMP), so a column named temp
  works again; a base type; and a NUL anywhere in the SQL text.
- A bound value or a migration id holding NUL is refused with the reason
  instead of being stripped, so the plugin's keys never change meaning.

Every bypass from the re-review is a test on the real database, on the
role the plugin data is meant to run as and on a superuser connection with
the role check off.
2026-11-17 23:04:12 +01:00
Maurice da1a02e7a8 fix(plugins): bind a plugin's own SQLite arguments exactly again, NUL included
5ff5e7660 stripped U+0000 from every argument a plugin bound to its own
SQLite file, but left the rows it had stored alone. A key written with a
NUL (through a bound arg or char(0) in the plugin's SQL) could no longer be
found by the same key, upserts added duplicates, and keys that differ only
in where a NUL sits ('a\0bc', 'ab\0c') collapsed into one and collided.

A plugin's data is the plugin's, so its file binds the arguments exactly as
sent again, as before that commit. TREK's own data still holds no NUL; the
Postgres store, whose text cannot hold the character, refuses it instead.
2026-11-17 23:04:11 +01:00
Maurice 9808e113e4 fix(db): refuse restores for CREATEROLE members, server file grants and parameter grants
The privileged-role check missed three ways a role can reach the database
host from SQL. Before PostgreSQL 16 a member of a CREATEROLE role sets its
role to it and grants itself pg_execute_server_program, since role
attributes are not inherited but the grant checks the role in effect. A role
granted EXECUTE on lo_export, lo_import, pg_read_file, pg_ls_dir and their
siblings reads or writes server files, and lo_export keeps the file after the
transaction rolls back. From PostgreSQL 15 on a role can be granted ALTER
SYSTEM on a setting or SET on a superuser-only one.

PRIVILEGED_ROLE_SQL now counts all three. The parameter grants are read
through query_to_xml inside a CASE taken only on 15 or later, because a
statement naming pg_parameter_acl does not parse on 14. A SET grant on a
setting every role may change anyway, and pg_monitor, stay ordinary. The
lane test creates each kind of role and shows the escalation the check is
for on the server it runs against.
2026-11-17 23:04:11 +01:00
Maurice 13e81c04ab fix(db): drop NUL from every request value before any logic runs
The database stores no NUL on either engine, but the application still held
the value a client sent. A key or a check made from it was then a different
value from the one the database compared: `victim@x.test` followed by NUL
was a fresh key for the per-email password-reset throttle while the lookup
found the victim's row, so every spelling mailed a new link and voided the
last one.

Every input now loses its NUL where it enters TREK: the nulFreeRequest
middleware after the body parsers (path, query string, body, cookies), the
first global pipe for what a route parses itself (a multipart body), the
websocket adapter for every frame, and the MCP registry through a new
host-supplied input mapper, since /mcp keeps its raw body. Headers need
nothing: Node refuses a NUL in one with a 400. A string under a key naming a
password stays as sent: it is only ever hashed, and stripping it would lock
out an account whose password was set with one. The stripping in the
database layer stays as the backstop for what does not come from a request.
2026-11-17 23:04:11 +01:00
Maurice fd42d06d55 docs(db): drop the pg_restore rollback that fails and name the client tool directories the code searches
Updating offered a second way to roll back a Postgres update: drop the
database, create it again and pg_restore the pre-migrate copy into it. TREK's
copy is a dump of its schema by name, so pg_restore creates public again,
stops at "schema public already exists" and rolls the load back, leaving an
empty database in the middle of a rollback. The page now says so and keeps the
steps that clear the schema instead.

Environment-Variables listed /usr/lib/postgresql/17 to 14 as the default
search path for the client tools; the code and the image start at 18.
2026-11-17 23:04:11 +01:00
Maurice e6f4f7a5f3 fix(db): leave nothing behind when a first Postgres boot fails, so RESTORE_FROM_BACKUP still runs
createFromBaseline created the migration history's table through MikroORM's
storage before, and outside, the transaction that runs the baseline. Without a
master transaction MikroORM commits that table on its own, so a first boot that
failed in the baseline (a server without ICU, a timeout, a dropped connection)
left an empty mikro_orm_migrations behind. The next start with
RESTORE_FROM_BACKUP took that for a database in use, skipped the restore with a
warning and brought up an empty instance, after which the restore never ran.

The table is now created on the baseline's own transaction, so a failed first
boot leaves the database empty. The boot restore also treats a lone migration
history that records nothing as no database, which a restore clears anyway; any
other answer keeps it, so the check fails closed. Database-Postgres says both.
2026-11-17 23:04:11 +01:00
Maurice 9497b586b7 test(db): read the raw-SQL exemptions without awaiting in a loop
The two checks over every file under src/ awaited ESLint's config file by
file, which lint:warnings counts as no-await-in-loop. They read the configs
with Promise.all instead.
2026-11-17 23:04:10 +01:00
Maurice 77d90be4f8 docs(db): describe plugin SQL on its own pool client instead of the marker hook
The guard's header, server/CLAUDE.md and the Postgres wiki page named
extended-query.ts and a hook on every pool connection. They now say that the
store sends each plugin statement over the extended protocol on a client it
checks out per call, and drops that client's temporary tables and session
state before handing it back.
2026-11-17 23:04:10 +01:00
Maurice a884539a2b fix(db): run plugin SQL on a pool client of its own instead of patching the pool
Plugin statements on Postgres went over the extended query protocol through a
marker parameter and a hook that replaced query() on every client of TREK's
pool. That kept a plugin to one statement per round trip, but it changed
TREK's own hot path for a concern only plugin data has.

The plugin data store now checks a pg client out of the ORM's pool for each
transaction, through MikroORM's getNativeClient, and runs the transaction on
it directly. Every plugin write goes as a query with queryMode 'extended' and
every read through a pg-cursor on that client, so Postgres parses exactly one
statement either way. The settings the transaction makes are local, and
before the client goes back to the pool the store drops temporary tables,
cursors, listeners, session advisory locks and sequence state, or closes a
client it cannot bring back to that state. The row cap, quota, time budget,
untimed migrate, per-plugin queue, pool share and script commits are as
before, and plugin args are still sent without NUL.

The marker, the hook and its install in the Postgres driver are gone.
2026-11-17 23:04:10 +01:00
Maurice 633df91bd6 fix(db): refuse raw SQL everywhere under src/, not only in the repositories
The ESLint walls against raw(), the sql tag and SQL text handed to
execute/run/all/get applied to src/db/repositories and src/db/seeders only. A
service, job, guard or MCP tool could send its own SQLite-only SQL through
em.getConnection().execute(...), which the Postgres probe never runs, since it
only calls the repositories. The walls now cover all of src/. The dialect layer,
the engines and the migrations stay the homes of raw SQL, and the four boot-time
lifecycle files that hold SQL text today are named and pinned to their count.
2026-11-17 23:04:10 +01:00
Maurice dd98469a02 fix(db): pass the chunk size and the abort options through the NUL-free connection
The wrapper took the chunk size of a stream as optional, which lint:strict refuses, and dropped the abort options Kysely hands executeQuery and streamQuery, so a cancelled query kept running.
2026-11-17 23:04:10 +01:00
Maurice 223a7605ed test: import vi in the trip members suite and type the move's SQLite ORM options 2026-11-17 23:04:10 +01:00
Maurice 0e04eeaf9a test: send the reset and seeding steps one by one or together, not awaited in a loop
resetDatabase empties tables and puts back the default categories one after another through the repo's oneByOne helper, where the order can matter, and the default addons and photo providers together; the MCP suites switch their addons on together and create ordered stops through oneByOne. The warnings this brings below the baseline, and the no-explicit-any and no-unused-vars counts earlier commits lowered, are lowered in scripts/eslint-baseline.json.
2026-11-17 23:04:09 +01:00
Maurice aa77e21d4b fix(db): refuse to regenerate a frozen Postgres baseline and check its trigger ports once frozen
gen:pg-baseline rewrote the baseline with its cut at the newest migration on
disk, so after a migration landed after the cut, running it moved the cut over
that migration while Postgres installs created from the old baseline would
still run it through the migrator. It now refuses while a migration follows the
committed cut, names those migrations and the routine, and moves the cut only
with --move-cut (lint:dialect keeps such a migration under the post-cut rules
either way).

check:pg-baseline stopped comparing SQLite triggers with POSTGRES_TRIGGERS once
the baseline was frozen, so a trigger a later migration created on SQLite went
unnoticed. The comparison now runs in both states, with advice that points at
the migration when the baseline is frozen.
2026-11-17 23:04:09 +01:00
Maurice 8c8cfb5d5d fix(db): hold SQLite-only functions, LIKE and the sqlite member of a post-cut migration in lint:dialect
lint:dialect missed several classes of SQL that SQLite reads and Postgres does
not, or reads differently:

- group_concat, ifnull, instr, iif, printf, typeof, total(), changes() and
  json_object/json_array/json_valid/json_type/json_quote, as calls in SQL text
  and as the bare name handed to eb.fn.
- LIKE in SQL text, Kysely's 'like' operator and MikroORM's $like, which ignore
  case on SQLite only. A LIKE that is exact on purpose now says so in a
  like-exact comment; the six existing ones (setting keys, storage paths, the
  lowercased reference search, sqlite_master) carry it.
- The sqlite member of engineDdl was not read at all, so a trigger or a data
  backfill put there never reached Postgres. It may now hold only the schema
  change and a rebuild's copy and sqlite_sequence bookkeeping, and SQLite
  statements with an empty postgres member need a sqlite-only reason.
- execBestEffort, bestEffort and execUnlessTableMissing in a post-cut
  migration: on Postgres a swallowed failure aborts the migration transaction.
- The post-cut rules follow POSTGRES_FIRST_CUT as well as the manifest, so
  regenerating the baseline over a new migration no longer releases it.

src/db/engine/sqlite/ is SQLite's own code and is no longer scanned.
2026-11-17 23:04:09 +01:00
Maurice 9eeb59997e fix(db): count every spelling of an engine check in lint:engine-dispatch
The gate matched only isSqlite(/isPostgres(, instanceof on a platform class
and a comparison on a property named engine or id. A destructured engine name,
the literal on the left, a switch over the engine, instanceof on a driver class
and a comparison with a driver class all passed with an empty baseline, and
standalone-orm.ts already held one such check. The regex now matches every one
of them, the guard in standalone-orm.ts moves into the engine port as
assertSqliteOrmConfig, and the advice names where a check belongs.
2026-11-17 23:04:09 +01:00
Maurice 8179d7d707 test(db): list the carry-over migration among the ones without a legacy step 2026-11-17 23:04:09 +01:00
Maurice f211a1c614 docs(db): describe the NUL, whole-number and calendar-date rules
server/CLAUDE.md names where NUL is dropped, INTCOL and the .int() rule
for integer columns, and the calendar-date check for a bound date, and no
longer lists the places NUL suite as SQLite-only. The Postgres wiki says
the move drops a NUL instead of refusing it.
2026-11-17 23:04:09 +01:00
Maurice f42ef5246c fix(db): store no NUL character on either engine
Postgres text cannot hold U+0000, so any write or filter carrying one (a
request body, a query string, an import, a feed, a forwarded mail, a
plugin's own SQL) answered a 500 on Postgres while SQLite stored it. Both
engines now drop the character where every value leaves for the database
(src/db/nul-free.ts): the MikroORM platforms when they inline a string or
serialize a JSON value, the Kysely dialects for every parameter, a
plugin's own SQLite file for its arguments, and the move from SQLite,
which used to refuse such text. The same request now answers the same
status and leaves the same row on both engines, so the places NUL suite
runs on Postgres as well and leaves SQLITE_ONLY.
2026-11-17 23:04:08 +01:00
Maurice e1a5864406 fix(storage): find a stored reference in any case on Postgres too
The release queue narrows each owner's rows with LIKE '%run%' before it
parses them, and relied on SQLite's LIKE ignoring ASCII case. On Postgres
LIKE is exact, so a row naming an object in uppercase was not found and
the release deleted an object that row still names. likeAny now matches
LOWER(column) against the lowercase run, which reads alike on both
engines. RELI-010 fails on Postgres without it.
2026-11-17 23:04:08 +01:00
Maurice 62c03d71bf fix(db): find no nearest day for a date the calendar does not have
The nearest-day fallback of a booking's time cast the bound date to a
timestamp on Postgres, which refuses 2024-02-30 with a 500, while SQLite's
JULIANDAY rolled it over into March and placed the booking there.
dayDistance now refuses anything but a calendar date on both engines
(isCalendarDate), so a caller that forgets the check fails on SQLite too,
and findNearestDayId answers no day for such a date. The size baseline of
Reservations.repository.ts drops by one line.
2026-11-17 23:04:08 +01:00
Maurice f4ce2c2bd0 fix(db): keep a carried-over half day as a half on both engines
A vacation day can be taken as a half day, so what a year carries into
the next can end in a half. vacay_user_years.carried_over was an INTEGER
column: SQLite stored 29.5 as a REAL, Postgres (bigint) rounded it to 30,
and the move refused such a SQLite value. The column becomes REAL on
SQLite (a table rebuild that keeps every id and the AUTOINCREMENT counter)
and double precision on Postgres, through the first migration after the
Postgres baseline's cut. VACAY-046 books a half day and reads the
carry-over on both engines.
2026-11-17 23:04:08 +01:00
Maurice d643f8c329 test(memories): answer the session retry cases by API, not by call order
The album list asks three sources at once; which call reaches the fake first
depends on how database reads interleave, which differs between the engines.
The fake now answers by API and category and the cases assert the retry with
a fresh session itself.
2026-11-17 23:04:08 +01:00
Maurice 1b270806a1 test(share): write the place photo cache through the app's own ORM
The suite built the cache over a second SQLite ORM, so on Postgres its rows
went to a database the app never reads.
2026-11-17 23:04:07 +01:00
Maurice 2d7392c4c0 fix(db): refuse a fraction for an integer column at the request boundary
Every integer column is bigint on Postgres. SQLite stored a fraction sent
to one (a packing quantity of 1.5, a budget item for 2.5 days, an id of
3.5) as a REAL, while Postgres rounded it in a statement MikroORM renders
and refused it with a 500 in a Kysely statement, so the engines held
different data for the same request.

The request schemas of those fields now take whole numbers only, and
INTCOL (tests/unit/contracts/integer-columns.test.ts) holds the class: it
reads the integer columns from the entities and fails on any DTO field or
inline MCP tool field of that name that takes any number.
2026-11-17 23:04:07 +01:00
Maurice a9cdb2f91c docs(db): describe the plugin SQL layers and the refused restore roles
The Postgres wiki page and the plugin author guide list what the plugin
SQL guard now refuses and the two layers behind it, and the wiki and
server/CLAUDE.md name every kind of role a restore refuses, including
CREATEROLE on PostgreSQL 14 and 15, which the managed postgres role on
such a server holds.
2026-11-17 23:04:07 +01:00
Maurice 2983971c8b fix(db): refuse restores for every role that can reach the database host
The privileged-role check looked only at the role's own rolsuper and at
pg_execute_server_program and pg_write_server_files. A role that is no
superuser itself but a member of one passed it and could SET ROLE to the
superuser from a crafted archive; on PostgreSQL 14 and 15 a role with
CREATEROLE could grant itself pg_execute_server_program; and
pg_read_server_files let COPY read the server's files into TREK's tables.

The check now counts membership in any superuser role, the three
predefined server roles, and CREATEROLE before 16. The boot warning and
the restore refusal describe the same list from one constant. A Postgres
lane suite creates each kind of role and evaluates the check as it, and
shows on the server it runs against whether CREATEROLE can grant itself
pg_execute_server_program.
2026-11-17 23:04:07 +01:00
Maurice e6a0a39a51 fix(db): read plugin SQL the way the Postgres lexer does and refuse INTO and TEMP anywhere
The guard ended a -- comment at LF only, while Postgres ends it at CR as
well, so "select 1 --\rfrom public.users" hid a qualified name from the
guard that Postgres then read, and with no args a second statement after
the CR ran as TREK's role. It also only looked for INTO at the top level
of a SELECT, so "(select ... into temp users)" made a temporary table that
shadowed TREK's own users table on the pooled connection.

The tokenizer now skips exactly what Postgres skips as whitespace, ends a
line comment at CR or LF, and refuses any character the two read
differently (other control characters, non-ASCII whitespace such as
U+00A0, U+FEFF and U+2028, and the non-decimal and underscored numbers
Postgres before 16 reads another way) instead of guessing. INTO is refused
anywhere but after INSERT or MERGE, at any depth, and the words TEMP and
TEMPORARY anywhere outside a string or quoted name.

The guard tests carry both payloads and their variants; the Postgres lane
runs them against the real database, proves a second statement in one
text is refused by Postgres over the extended protocol, and that a
temporary table never shadows TREK's or a plugin's tables.
2026-11-17 23:04:07 +01:00
Maurice 87612c0c79 fix(db): run plugin SQL one statement at a time and search pg_temp last
The plugin SQL guard was the only thing between a plugin and TREK's tables
on Postgres, and two gaps in it were enough to leave the plugin schema.
Two layers now hold even when the guard is fooled.

A plugin write with no bound args went over the simple query protocol,
which runs every statement in its text. Plugin statements now go through
extendedQuery, which pg sends over the extended protocol whatever the
args, so a second statement is a syntax error instead of a statement that
runs. A marker parameter carries the request to the pool's clients, and a
client without the hook binds one value too many, so it fails closed.

pg_temp is searched before the search_path unless the path names it, and
a temporary table lives as long as its pooled connection, so one left
behind would stand in for users, sessions and every other table for the
next caller. Every connection of TREK's pool now puts pg_temp last on the
search_path the role configured, and a plugin transaction sets its schema
with pg_temp last.
2026-11-17 23:04:07 +01:00
Maurice ff57883e3d test(db): run the notifications and advanced packing MCP suites on the real database module
They seed through the booted container's ORM instead of the SQLite snapshot
mock and reset through resetDatabase, so they run in the Postgres lane as
well. The tag notification case waits for the fire-and-forget row with
vi.waitFor instead of one turn of the event loop: on SQLite the insert
lands within that turn, on Postgres it needs a few round trips more.
2026-11-17 23:04:06 +01:00
Maurice cd1a3fd433 test(realtime): run the websocket wire envelope suite on the real database module
It takes the ORM from the app buildApp boots, seeds through the factories
and resets through resetDatabase instead of the SQLite snapshot mock, so
it runs in the Postgres lane as well.
2026-11-17 23:04:06 +01:00
Maurice 377f22972b test(db): run the trips and vacay MCP suites and the route inventory on the real database module
The MCP suites seed through the booted container's ORM instead of the
SQLite snapshot mock and reset through resetDatabase. The route inventory
never touched the database and only mocked it; without the mock it
compiles AppModule over the real module, so it runs in the Postgres lane
as well.
2026-11-17 23:04:06 +01:00
Maurice fff7d123f6 test(db): run the transports, trip members and trip warnings MCP suites on the real database module
They seed through the booted container's ORM instead of the SQLite snapshot
mock and reset through resetDatabase, so they run in the Postgres lane as
well. The trip warnings suite seeded through the factories but only closed
the snapshot handle; it now boots the container to reach the ORM the reset
needs.
2026-11-17 23:04:06 +01:00
Maurice bedb70c479 test(db): run the share, tags, maps and weather, and transit MCP suites on the real database module
They seed through the booted container's ORM instead of the SQLite snapshot
mock and reset through resetDatabase, so they run in the Postgres lane as
well. The transit suite saves its permission levels through the
container's PermissionsService in a request context instead of one built
by hand over the SQLite handle.
2026-11-17 23:04:06 +01:00
Maurice 3b8270edc3 test(db): run the reservations, road trip and settings MCP suites on the real database module
They seed through the booted container's ORM instead of the SQLite snapshot
mock and reset through resetDatabase, so they run in the Postgres lane as
well. The road trip suite saves its permission levels through the
container's PermissionsService in a request context instead of one built
by hand over the SQLite handle.
2026-11-17 23:04:05 +01:00
Maurice 6137aaf716 test(db): run the packing, places and plugin MCP suites on the real database module
They seed through the booted container's ORM instead of the SQLite snapshot
mock and reset through resetDatabase, so they run in the Postgres lane as
well. The plugin search suite seeded nothing through the snapshot handle
and only closed it; it now boots the container to reach the ORM the reset
needs.
2026-11-17 23:04:05 +01:00
Maurice 97a3389409 test(db): run the feeds and invite, journey, leg transport mode, memories and notes MCP suites on the real database module
They seed through the booted container's ORM instead of the SQLite snapshot
mock and reset through resetDatabase, so they run in the Postgres lane as
well.
2026-11-17 23:04:05 +01:00
Maurice 95ade9cbb2 test(db): run the days, accommodations, files and help MCP suites on the real database module
They seed through the booted container's ORM instead of the SQLite snapshot
mock and reset through resetDatabase, so they run in the Postgres lane as
well. The collab sub-feature case in the help suite toggles through the
container's AddonsService in a request context instead of one built by
hand over the SQLite handle.
2026-11-17 23:04:05 +01:00
Maurice c4c278d2f3 test(db): run the budget and collections MCP suites on the real database module
They seed through the booted container's ORM instead of a second ORM over
the SQLite snapshot mock, and reset through resetDatabase, so they run in
the Postgres lane as well. The settlement parity cases call the
container's BudgetController in a request context instead of one built by
hand over the SQLite handle, and the collections suite drops its raw
per-table DELETE for the same reset.
2026-11-17 23:04:05 +01:00
Maurice 2cb1964863 test(db): run the AirTrail, atlas expanded, collab and categories MCP suites on the real database module
They seed through the booted container's ORM instead of a second ORM over
the SQLite snapshot mock, and reset through resetDatabase, so they run in
the Postgres lane as well. The PermissionsService the AirTrail cases save
through and the CategoriesMcp and DemoService the categories write
harness attaches are the container's own, called in a request context,
instead of instances built by hand over the SQLite handle.

include_coords compares the coordinates as a set: getTravelStats reads
them through a SELECT DISTINCT without an order, and Postgres returns
them in hash order.
2026-11-17 23:04:05 +01:00
Maurice 876cc5e0f0 test(db): run the demo tool gate, addon gating, atlas and assignments MCP suites on the real database module
They seed through the booted container's ORM instead of a second ORM over
the SQLite snapshot mock, and reset through resetDatabase, so they run in
the Postgres lane as well. The tour the assignment cases put on a day is
made with makeTour instead of a raw insert.
2026-11-17 23:04:04 +01:00
Maurice caae538056 test(db): merge the factory imports of the newly ported integration suites
One import per module, and the resetTestDb import that no longer has a
caller dropped.
2026-11-17 23:04:04 +01:00
Maurice 1cebddac0e test(db): run the trips and vacay suites on the real database module
They reset through resetDatabase and seed through the ORM factories on the
booted app's ORM instead of the SQLite snapshot mock, so they run in the
Postgres lane as well.
2026-11-17 23:04:04 +01:00
Maurice 78bfa8183a test(db): run the share, system notices and trip access primitives suites on the real database module
They reset through resetDatabase and seed through the ORM factories on the
booted app's ORM instead of the SQLite snapshot mock, so they run in the
Postgres lane as well.
2026-11-17 23:04:04 +01:00
Maurice 43af349391 test(db): run the security, settings, tags and todo suites on the real database module
They reset through resetDatabase and seed through the ORM factories on the
booted app's ORM instead of the SQLite snapshot mock, so they run in the
Postgres lane as well.
2026-11-17 23:04:04 +01:00
Maurice 9c35343d9d test(db): run the scheduler gate, storage health context and uploads suites on the real database module
They drop the SQLite snapshot mock and, where they seed, reset through
resetDatabase and seed through the ORM factories, so they run in the
Postgres lane as well.
2026-11-17 23:04:03 +01:00
Maurice b0b1986377 test(db): keep the legacy upgrade suites on SQLite by name
They boot on a SQLite file the retired positional runner built, which no
Postgres database ever came from, so they belong in SQLITE_ONLY rather
than in the snapshot baseline. The lane scan now tells such a suite apart
from the snapshot mock: it mocks src/db/database onto a database of its
own, never names createSnapshotTestDb, and is named in SQLITE_ONLY with
its reason. A snapshot suite added to SQLITE_ONLY stays in the baseline.
2026-11-17 23:04:03 +01:00
Maurice f11f021e15 test(db): run the Immich, Synology and unified memories suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well.

IMMICH-057 and SYNO-035 need a shared photo row whose trip is gone, which
the foreign key's cascade rules out on a database that enforces it; they
write it with SQLite's foreign keys off as before and are skipped on
Postgres, which has no such switch.
2026-11-17 23:04:03 +01:00
Maurice 6e7336b8d7 test(db): run the MCP and OAuth suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well. The OAuth service they drove by hand over a second ORM on the
SQLite handle is now the container's own, called in a request context.

The MCP audit cases wait for the mcp.tool_call row: the transport writes
it without awaiting it, so on Postgres it can land after the response.
2026-11-17 23:04:03 +01:00
Maurice 927fcab67f test(db): run the places and incoming leg mode suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well.

The two cases about a NUL byte in a place name move to
places-nul-sqlite.test.ts, listed in SQLITE_ONLY: they pin SQLite's value
quoting, and Postgres text cannot hold U+0000. The control characters
0x01 to 0x1F stay in places.test.ts and run on both engines.
2026-11-17 23:04:03 +01:00
Maurice c51f4f78bb test(db): run the packing, reservations and journey suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well.
2026-11-17 23:04:02 +01:00
Maurice 12f4a40d7c test(db): run the OIDC, passkey, profile, notifications and ORM request context seam suites on the real database module
They reset through resetDatabase (the seam suite needs no reset) and seed
through the ORM factories instead of the SQLite snapshot mock, so they run
in the Postgres lane as well.
2026-11-17 23:04:02 +01:00
Maurice 3a6e91e26b test(db): run the journey place order, maps, misc and local OIDC provider suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well.
2026-11-17 23:04:02 +01:00
Maurice 680ce7324a test(db): run the admin and auth suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well, the user erasure cases included.
2026-11-17 23:04:02 +01:00
Maurice f5fbd60b5e test(db): run the files and collab suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well.
2026-11-17 23:04:02 +01:00
Maurice 8c1395c8f1 test(db): run the atlas and backup suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well.
2026-11-17 23:04:02 +01:00
Maurice 19bfa77ace test(db): run the assignments, day notes and async closure guard suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well.
2026-11-17 23:04:01 +01:00
Maurice 2fb041a428 test(db): run the feeds, atlas geocode, collections and Immich suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well.
2026-11-17 23:04:01 +01:00
Maurice be1983c9a4 test(db): run the boot, boot sweep, demo seed, AirTrail and doc sync context suites on the real database module
They boot the app without the SQLite snapshot mock, so they run in the
Postgres lane as well. The demo seed suite spies on the real runDemoSeed
export instead of replacing the database module to wrap it.
2026-11-17 23:04:01 +01:00
Maurice 2288487fe1 fix(oauth): narrow the refused registration for the strict compiler 2026-11-17 23:04:01 +01:00
Maurice b2384892a8 test(db): run the session revocation, api docs, app config and help suites on the real database module
They boot the app without the SQLite snapshot mock, so they run in the
Postgres lane as well. sessionRowsOf reads a user's session rows through
a booted app's ORM, next to sessionRows for the suites that still hand in
a better-sqlite3 handle.
2026-11-17 23:04:01 +01:00
Maurice 43e30ca28e test(realtime): run the websocket connection suite on the real database module
Seeds through the ORM factories, resets through resetDatabase and mints
ws-tokens through the container's TokenService instead of one built by hand
over the SQLite snapshot mock, so it runs in the Postgres lane as well.
2026-11-17 23:04:01 +01:00
Maurice 42f0705f07 test(todo): run the todo MCP tool suite on the real database module
Seeds through the booted container's ORM instead of a second ORM over the
SQLite snapshot mock, and resets through resetDatabase, so it runs in the
Postgres lane as well.
2026-11-17 23:04:00 +01:00
Maurice e97dbc89c9 fix(db): keep the stay filter inside src/db and cover the flag type's missing read
src/db may not import src/nest, so the '<id>.0' shape is spelled where the
filter is. The flag type's undefined read had no test, which left the types
folder below its branch threshold.
2026-11-17 23:04:00 +01:00
Maurice 76dfbe0a00 test(days): run the days suite on the real database module
Seeds through the ORM factories and resets through resetDatabase instead of
the SQLite snapshot mock, so it runs in the Postgres lane as well.
2026-11-17 23:04:00 +01:00
Maurice 424fa538e0 test(budget): run the budget suite on the real database module
Seeds through the ORM factories and resets through resetDatabase instead of
the SQLite snapshot mock, so it runs in the Postgres lane as well.
2026-11-17 23:04:00 +01:00
Maurice 863ff62b6c test(categories): run the categories suite on the real database module
It resets through resetDatabase instead of the SQLite snapshot mock, so it
runs in the Postgres lane as well.
2026-11-17 23:04:00 +01:00
Maurice e2b0910e28 test(db): reset a suite's database between tests on either engine
resetTestDb needs the SQLite snapshot mock's better-sqlite3 handle, so a
suite resetting with it can only run on SQLite. resetDatabase takes the
booted app's ORM and leaves the same state on SQLite and Postgres: every
table but the kept ones emptied (read from the live schema), sequences left
counting, seedDefaults' rows back through the ORM, and on the first call the
users sequence restarted as the snapshot mock normalises it.
2026-11-17 23:03:59 +01:00
Maurice cf9172f9e7 fix(db): type the move's value conversion and client for the server's compiler
Formats the two files the format gate listed.
2026-11-17 23:03:59 +01:00
Maurice 0e911608af fix(db): match a stay's bookings by the stored '<id>.0' text, as SQLite did
Reading the TEXT column as an integer also matched '14', ' 14' and '14abc',
which the legacy REAL-bound compare never did (AC37/AC40). Comparing with the
'<id>.0' text the services store keeps that contract on both engines.
2026-11-17 23:03:59 +01:00
Maurice 95d067ad6d test(auth): a plugin table missing from the schema fails the user erasure
The erasure no longer skips a missing plugin table in a savepoint of its own (61ea6b648); USER-CLEANUP-005 still expected the skip.
2026-11-17 23:03:59 +01:00
Maurice ba043cb1c0 style(plugins): keep the runtime and the SDK within their size baselines
The plugin data engine added three lines to each; six comments that wrapped past 120 columns now fit in one.
2026-11-17 23:03:59 +01:00
Maurice 3a4c523509 test(db): the move command's own output and target ORM 2026-11-17 23:03:58 +01:00
Maurice 057748c47a fix(db): set no deferred references once the move refused a value
Nothing is inserted after the first refused value, so the self-references held back had no rows to land on, and the move failed on them instead of listing the values (MOVE-006).
2026-11-17 23:03:58 +01:00
Maurice e4457ed9eb style(db): format postgresTarget as Prettier does 2026-11-17 23:03:58 +01:00
Maurice f430cbe59e chore(lint): lower the server's no-console baseline to 231
AuthService no longer warns through console when an invite's last use was taken: the registration now refuses it inside its transaction.
2026-11-17 23:03:58 +01:00
Maurice 5316362e9e fix(db): open the move's SQLite source through openDatabase, keep the drop failure as the cause
ESLint refused both: better-sqlite3 is imported only in src/db/connection.ts and its named neighbours, and an error thrown in a catch carries what that catch caught.
2026-11-17 23:03:58 +01:00
Maurice 900f2bfc30 test(realtime): read each parity case after its notification sends have settled
On Postgres a fire-and-forget notification still ran when the case read its recording, so it landed in the next case. The harness now waits for NotificationsService.settled() after each write and each exemption; a late send of any other kind still fails the next case.
2026-11-17 23:03:58 +01:00
Maurice b7c8f0629c feat(notifications): know when the sends a write left running have finished
Most writes start their notification without waiting for it. NotificationsService now tracks each send until it settles, and settled() resolves once every send started before it has finished. The channel check moves to channel-gate.ts, which keeps the service under the size limit.
2026-11-17 23:03:57 +01:00
Maurice 45fef1077a test(demo): read the baseline refusal from the logger 2026-11-17 23:03:57 +01:00
Maurice ddb42ecf0a test(db): name the restore's plugin schemas as plugin ids allow 2026-11-17 23:03:57 +01:00
Maurice 09295781f4 test(integrations): give the AirTrail suites' UnitOfWork its engine 2026-11-17 23:03:57 +01:00
Maurice 5938609f69 test(db): no await inside a loop in the Postgres tests 2026-11-17 23:03:57 +01:00
Maurice d3cd484519 test(db): stand-in pg tools write --file=- to their own stdout
The CI runner gives a child process a socket for stdout, which /dev/stdout cannot open, so every case whose pg_restore streams its script failed there. The COPY terminators in PGTOOLS-020 are spelled as a dump spells them.
2026-11-17 23:03:56 +01:00
Maurice 410d2393e0 fix(db): log the demo baseline refusal through the logger, read the tool versions at once 2026-11-17 23:03:56 +01:00
Maurice 44b6340be5 docs(db): every transaction goes through UnitOfWork, checks read inside it 2026-11-17 23:03:56 +01:00
Maurice 2f3dc4ea79 feat(lint): refuse a transaction outside UnitOfWork under src/
trek/transactions-through-unit-of-work reads the receiver's type and reports
transactional() on anything but a UnitOfWork (an untyped receiver
included), and begin() or transaction() on an EntityManager, a connection
or Kysely. src/db/engine/ and the two boot-time schema files are left out.
It runs with the rest of the server's ESLint, so lint:warnings fails on a
new one, and its message names UnitOfWork, writeTransaction and the rule in
server/CLAUDE.md.
2026-11-17 23:03:56 +01:00
Maurice af861e5816 fix(db): read the checks a write relies on in the transaction that writes
On Postgres a check read before a transaction, or outside one, no longer
holds at the write that follows: the pool runs other requests' writes in
between. Moved into the unit of work that writes:

- the last-admin guard of an admin's role edit and of an account deletion
  (deleteUserCompletely takes a precondition run in its transaction)
- the login lockout guards of the auth settings save and the SSO settings
  save
- the first-account check of an SSO sign-up, which starts over as an
  ordinary sign-up when another account won
- the OAuth client caps, the token cap and the mail intake limits
- the year check before a vacay year is opened, and the label name check of
  a rename

A password sign-up that loses the last use of an invite is now refused, as
the SSO sign-up already was, and a reset link is burned by one conditional
update, so two resets with one link cannot both change the password.
2026-11-17 23:03:56 +01:00
Maurice c1bbe27ac6 fix(db): take the write lock in every transaction that writes
UnitOfWork took the engine's write lock, but four repositories opened
transactions of their own: the demo addon set, the plugin user erasure's
savepoints, and the plugin metadata and scheduler cap checks. On Postgres
those ran beside the others on the pool.

writeTransaction (src/db/engine/write-transaction.ts) is now the one
transaction that writes: UnitOfWork wraps it, and the demo seed and reset,
which run outside the container, call it with the engine the environment
names. The capped plugin writes run in their caller's unit of work instead
of a transaction of their own, and the plugin erasure runs in the erasure's
transaction without savepoints, since its three tables come with the
migrations on both engines. lint:tx counts writeTransaction as a
transaction.
2026-11-17 23:03:56 +01:00
Maurice 11f4373076 docs(db): rotating the encryption key on Postgres 2026-11-17 23:03:55 +01:00
Maurice f57fb7f9de test(db): the key rotation on Postgres, and its refusals before a key is asked 2026-11-17 23:03:55 +01:00
Maurice 96f2427518 fix(db): rotate the encryption key on Postgres through the server's engine
The rotation ran on the SQLite file only and refused when TREK_DB_URL was
set. Its statements now go through a small store per engine: better-sqlite3
for the file, unchanged, and on Postgres the server's own MikroORM
connection, in one transaction that takes the engine's write lock first. The
Postgres path checks that it reaches a database holding TREK's tables and
that the data directory is writable before it asks for a key, writes a
pg_dump copy before it changes anything, refuses DB_PATH or TREK_DB_FILE
beside the URL, and reads the jsonb addon config the driver hands back
parsed. The SQLite transaction is now BEGIN IMMEDIATE, since better-sqlite3
takes no async function.
2026-11-17 23:03:55 +01:00
Maurice 3f51153dcc docs(db): moving an existing install to Postgres, and the refusal of an empty database beside one 2026-11-17 23:03:55 +01:00
Maurice fc37eb95d1 test(db): move a factory-seeded SQLite install into Postgres and read it back through the app 2026-11-17 23:03:55 +01:00
Maurice 55607ff2f9 feat(db): move a SQLite install into an empty Postgres database
npm run db:move-to-postgres (dist/move-to-postgres.js in the image) copies
a SQLite file at this build's migration level into an empty Postgres
database. It refuses a file at another level, rows whose references point
at nothing and a target holding any table or plugin schema, creates the
schema with the engine's own bootstrap, then in one transaction copies every
table in foreign key order (setting a self-reference once its rows are in),
converts each value to its column's type and refuses one Postgres cannot
hold exactly, copies each plugin's plugin.db into its schema, moves the
sequences past the copied ids and compares every table's row count and an
order-free checksum over all rows before it commits. A failure drops the
schema again. The SQLite files and the uploads are never written.
2026-11-17 23:03:54 +01:00
Maurice 1ea08dcf0a fix(db): refuse a Postgres boot that would leave a SQLite install behind
Setting TREK_DB_URL on an existing SQLite install booted a new, empty
instance beside its data. The Postgres bootstrap now refuses an empty
database, or a migrated one without a single account, while the data
directory's travel.db holds accounts, and names the move command. A file
that cannot be read counts as holding them. TREK_DB_IGNORE_SQLITE_FILE=true
starts anyway, with a warning; the file is opened read-only and only when
the database holds no TREK data.
2026-11-17 23:03:54 +01:00
Maurice c6f6dd2d57 fix(db): find a stay's bookings on Postgres
reservations.accommodation_id is TEXT and holds '14.0'. Compared with a bare
number, Postgres binds the number as the text '14' and finds nothing, so
deleting a stay, a day or a place left its bookings behind with no error. The
three filters read the column as an integer, as the joins already do.
2026-11-17 23:03:54 +01:00
Maurice 579df97bba fix(db): type the integer flag and the owner literal for the server's compiler
The server compiles without strictNullChecks, where a narrowed value returned
as is keeps its full type, and two literal arms of one UNION column must share
a type.
2026-11-17 23:03:54 +01:00
Maurice aa2f7ca8b4 test(db): the Postgres plugin data store against a stand-in client
Covers what every call sets up, the schema check before plugin SQL runs, the
row cap, the time budget between chunks and at statement_timeout, the quota,
a script committed statement by statement, the tx and migrate shapes and one
call at a time per plugin, without a database. The Postgres lane runs the
same store on a real one.
2026-11-17 23:03:54 +01:00
Maurice 17c9c0758f docs(db): plugin data on Postgres, its SQL rules and one TREK per database
The plugin-sdk README says what dialect a plugin writes when TREK runs on
Postgres, what the guard refuses and how the limits hold there. The wiki's
Postgres page describes the plugin schemas, their backup and restore and
the one-instance-per-database limit, and its key rotation path now names
the file where it is.
2026-11-17 23:03:54 +01:00
Maurice 7340087353 fix(db): carry the plugin data schemas in Postgres backups and restores
pg_dump now names the trek_plugin_ schemas TREK's role owns beside its own
schema. A restore reads the dump's plugin schemas from its table of
contents, drops the plugin schemas the role owns, creates the dump's and
loads them with TREK's schema, all in the one psql transaction. Schemas of
another role and every other schema of the database are never read or
dropped.

The dump's migration history is read from TREK's mikro_orm_migrations only,
so a plugin table of that name cannot pass for it.
2026-11-17 23:03:53 +01:00
Maurice 910c98b971 feat(plugins): store plugin data on the engine TREK runs on
PLUGIN_DATA binds the plugin data backend to the engine (the same
{ sqlite, postgres }[engine.id] binding the backup port uses): the SQLite
file per plugin, unchanged, or the Postgres schema per plugin. The host
opens a plugin's store through it and an uninstall that deletes data erases
through it, which drops the schema on Postgres. Nothing outside db/engine
asks which engine runs.

A plugin's SQL is passed through as written, so a plugin needs to know the
dialect: db.engine (db:own) answers 'sqlite' or 'postgres', and the SDK
exposes it as ctx.db.engine(), in the mock host (dbEngine option) and in
dev. The plugin facts are regenerated and the SDK goes to 1.10.0.

The Postgres lane's PGPLUG suite installs, uses and erases plugin data on
Postgres and shows that a plugin reaches neither TREK's users table nor
another plugin's schema.
2026-11-17 23:03:53 +01:00
Maurice b144781e9f feat(db): keep a plugin's own data in a Postgres schema of its own
A plugin with db:own got a SQLite WAL file in the data volume whatever the
engine, so a Postgres install still needed a local disk (discussion #386).
This adds the plugin data port (db/engine/plugin-data.ts) and its Postgres
side: one schema per plugin, trek_plugin_<id>, reached through TREK's pool.

Every call runs in a transaction that creates the schema if missing, puts
only it on the search_path and sets statement_timeout to the call's budget.
Reads stream through a cursor and stop at the row cap, a write that grows
the schema past the quota rolls back, and the calls of one plugin run one at
a time on at most half of the pool.

TREK's role may read every table, and a role per plugin would need
CREATEROLE, so plugin-sql-guard.ts checks each statement first: it lexes the
SQL as Postgres does and refuses another schema as a qualifier, the pg_
catalogs and functions, functions that run SQL from a string or reach an
object by a name in one, temporary tables, and every statement but DML and
DDL on tables, indexes, views, sequences and types.
2026-11-17 23:03:53 +01:00
Maurice a26db47cb6 refactor(db): keep the touched files within their size baselines
The users identity guard moves to repositories/_shared/user-identity.ts
(Users.repository.ts re-exports UserIdentityTakenError), the flag text pass
of the entity generator to scripts/generate-entities-flags.ts, and the
Wallet pass query takes the repository's EntityManager. The size baseline
of Users.repository.ts is lowered to what it holds now (1445 to 1421); a
few exports only their own file used are no longer exported.
2026-11-17 23:03:53 +01:00
Maurice 9e5379d092 fix(demo): keep a demo baseline per engine and check it before every reset
The baseline was travel-baseline.db on both engines and went straight into
the swap, so a SQLite baseline left in the data directory made every hourly
reset of a Postgres demo fail inside pg_restore, and never got replaced. It
is now named after the engine's archive entry (travel-baseline.db on
SQLite, travel-baseline.pgdump on Postgres), and the backup port's new
checkCopy refuses one the engine cannot restore before the swap; the reset
then saves a fresh baseline and logs the reason instead of failing hourly.
2026-11-17 23:03:53 +01:00
Maurice 693acd5580 fix(db): reset the admin on Postgres and keep the key rotation off it
reset-admin.js opened data/travel.db with better-sqlite3 whatever the
engine, so on a Postgres install it created a stray SQLite file or reset
the admin in a leftover one. With TREK_DB_URL set it now resets the account
in Postgres through the built server's engine (its pool, SSL and write
lock, in one transaction), and refuses a TREK_DB_FILE beside the URL; the
SQLite branch is unchanged. migrate-encryption.ts cannot re-encrypt the
secrets in Postgres yet, so it now stops before it opens or writes any file
when TREK_DB_URL is set. The wiki says what each does on Postgres.
2026-11-17 23:03:52 +01:00
Maurice c3f6177be1 fix(db): sort NULLs where SQLite sorts them on Postgres
SQLite takes NULL as the smallest value and Postgres as the largest, so any
list ordered by a nullable column (bookings without a time, trips without
dates) came back in another order on Postgres. Instead of every ORDER BY
spelling its NULL position, the Postgres engine renders SQLite's wherever a
statement names none: a Kysely query compiler for this.kysely() statements
and a MikroORM platform for find() and the query builder. An explicit
position is kept.

A new Postgres-lane suite checks the answers the probe cannot see: the NULL
order, a stay linked as '14.0' in the public reads, the traveller owner
flag, the identity errors for a lost race, and the plugin caps under a race
on the pool.
2026-11-17 23:03:52 +01:00
Maurice 60642cc18b fix(plugins): hold the write lock for the plugin cap checks on Postgres
meta.set and scheduler.set checked their caps in a transaction of the
repository's own, which keeps check and write together on SQLite's single
writer but not on Postgres, where two pool connections both read the same
count. Both RPCs now run the capped write inside UnitOfWork.transactional,
which takes the engine's write lock; the repository's transaction becomes a
savepoint of it.
2026-11-17 23:03:52 +01:00
Maurice 54b843ae29 fix(db): store addons.enabled as the integer flag on Postgres too
addons.enabled was the one flag MikroORM's boolean type declared as a
Postgres boolean, while SQLite and every other flag hold 0/1, so an addon
migration's usual SET enabled = 1 would fail there and a Kysely read would
answer true instead of 1. The column now uses IntegerFlagType: the entity
still reads a boolean, both engines store 0/1, and the regenerated Postgres
baseline declares it bigint default 0. The entity generator renders the
type for the columns in BOOLEAN_COLUMNS.
2026-11-17 23:03:52 +01:00
Maurice 633e9bcdc1 docs(db): Postgres 14 to 18, the database role, restore limits and the manual rollback
- Database-Postgres: supported versions, the version 18 client and the tool
  search order, sslrootcert with a client before 16, how to create a role
  that is not a superuser and move an older compose install to one, a
  current schema other than public, and the space a restore needs.
- Updating: the manual rollback clears the whole schema and loads the copy
  in one transaction, as TREK's restore does; dropping only the tables left
  the collation, the trigger functions and the sequences behind. A unit
  test keeps the printed statement equal to CLEAR_SCHEMA_SQL, and the boot's
  rollback hint points at that section.
- Troubleshooting, Install-Docker-Compose, Environment-Variables, README
  and server/CLAUDE.md follow.
2026-11-17 23:03:52 +01:00
Maurice eab501925f fix(deploy): run TREK as a role that is not a superuser in the Postgres compose file
The compose file let the postgres image create TREK's role as the
superuser, so a crafted backup restored by TREK could run commands in the
database container. The superuser is now postgres, with a password of its
own, and an init script creates the role trek that owns TREK's database and
nothing more. The Helm values say the same about the role in the URL.
2026-11-17 23:03:51 +01:00
Maurice 2630d7e8ec build(docker): ship the PostgreSQL 18 client tools from the PGDG repository
A client handles every server up to its own major and refuses a newer one,
so the image needs the newest supported major, 18, which Debian 13 does not
ship. The PGDG repository is added with its signing key kept in the
repository and its component pinned to 18.
2026-11-17 23:03:51 +01:00
Maurice 116ba52fbb fix(db): check the Postgres server and tools before a dump or a restore
- The client tools are looked for newest first, from 18 down: a client
  handles every server up to its own major and refuses a newer one. A dump
  or a restore now refuses a client older than the server up front, naming
  both versions, and the boot refuses a server outside PostgreSQL 14 to 18.
- sslrootcert=system is used only by a client from libpq 16 on; an older
  client is refused with a message that names sslrootcert and the bin dir.
- The restore's CVE-2025-8714 table covers 18.
- A restore refuses a role that is a superuser or may run programs or write
  files on the database host, since the archive's SQL runs as that role;
  the boot warns about such a role.
- pg_restore's script is streamed to its work file and stopped once it
  passes BACKUP_MAX_DECOMPRESSED_MB, so a small dump can no longer expand
  without limit on the data volume.
- A failed tool's error keeps only the summarized stderr; its cause names
  the exit code and signal instead of carrying the process error, whose
  message and stderr quoted row data into the log.
- The migration history is looked for in the current schema, where the
  tables and the backups are, so a role whose search_path is not public
  boots a second time.
2026-11-17 23:03:51 +01:00
Maurice e5fb6d9107 fix(db): read unique violations and missing tables the same way on both engines
guardIdentity matched only SQLite's message text, so on Postgres a lost
race for an email or a username escaped as a 500 instead of a 409. The new
dialect module driver-errors.ts reads a unique violation by Postgres's
SQLSTATE 23505 and constraint name, or by SQLite's message, and the users
repository maps the key names of both engines. isMissingTableError moves
there too and also knows Postgres's 42P01 for an unconverted error.
2026-11-17 23:03:51 +01:00
Maurice 98529bc84c fix(db): return the traveller owner flag as a number on Postgres
The owner and member branches of listTravellerUsernames selected bound
values, which Postgres resolves to text in a UNION column, so the public
API reported every traveller as owner: false. The literals are written into
the statement as integers now.
2026-11-17 23:03:51 +01:00
Maurice 4a3ad562a7 fix(db): match a stay-linked booking on Postgres in the public stay check
publicStayExists cast reservations.accommodation_id straight to integer,
which Postgres refuses for the stored '14.0', so the calendar feed and the
share links failed for every trip once any booking was linked to a stay.
The correlation now goes through accommodationIdMatches, which compares
through the new dialect helper integerTextEqualsKysely, and the Wallet pass
context uses the same helper instead of its own numeric cast.
2026-11-17 23:03:50 +01:00
Maurice 518287ff12 docs(db): describe the discovered Postgres lane and the 14/18 job 2026-11-17 23:03:50 +01:00
Maurice 0cdfb9eb42 ci(db): run the Postgres probe and lane on Postgres 14 and 18
TREK supports Postgres 14 to 18, and CI tested 17 only. One server-postgres
job per major now runs the probe and then the lane against the same service,
so the change keeps the job count of the two jobs it replaces. The lane's
global setup refuses a service whose major is not TREK_TEST_PG_MAJOR, and
the image's Postgres boot moves to 18, the major its client tools target.

scripts/ci/workflow-jobs.test.mjs fails when a job other than the scan is
missing from ci-ok's needs, and changed-areas pins that migrations,
repositories, the engine and the lane's files always run the job.
2026-11-17 23:03:50 +01:00
Maurice 4d0067a455 test(db): find the Postgres lane's suites instead of listing them
The lane ran a hand-kept list of 26 suites that had already missed
trip-tags-mcp and the broadcast-parity suites, and listed two that never
touch a database. tests/postgres/lane.ts now takes every test file that
reaches src/bootstrap.ts or src/nest/app.module.ts through its imports and
does not vi.mock src/db/database, minus a named SQLITE_ONLY map with the
reason for each.

tests/unit/postgres-lane.test.ts (PGLANE, in the SQLite lane) fails on a
suite that names a boot entry point the discovery does not see, on a stale
exclusion, and on a new suite that boots the app over the SQLite snapshot
mock; the 105 that still do are held in snapshot-suites-baseline.json,
which only shrinks.
2026-11-17 23:03:50 +01:00
Maurice 66d4431d26 docs(db): the routine for a migration after the Postgres cut 2026-11-17 23:03:50 +01:00
Maurice 293a48c26a fix(db): keep check:pg-baseline speaking once the baseline is frozen
A frozen baseline still has its manifest verified, and the check now lists the
migrations that run on Postgres after the cut and what holds them. Every
problem it reports says what to do about it.
2026-11-17 23:03:50 +01:00
Maurice 80fca10784 feat(db): hold migrations after the Postgres cut to engineDdl in lint:dialect
A migration newer than the baseline's through (read from
assets/postgres/baseline.json) fails on a schema statement outside engineDdl,
a plain string column for addColumnIfMissing or a SQLite-only helper, and on a
SQLite spelling in an engineDdl postgres member. The advice names the two
steps, and the baseline cannot hold an allowance for these rules.
2026-11-17 23:03:49 +01:00
Maurice 830cd6e3b5 feat(db): print the Postgres side of a new migration with gen:pg-migration
The script builds a scratch database the way a boot does (the baseline, then
the migrations after its cut) up to the target migration, compares it with the
entities by PARITY-PG's rules and prints the remaining statements as the
postgres member of engineDdl. The scratch database is always dropped.
2026-11-17 23:03:49 +01:00
Maurice 0f338d5484 refactor(db): move PARITY-PG's schema comparison into the Postgres engine
Which comparator statements change nothing (drop not null on a live primary
key, spelling-only defaults and checks proven by a rolled-back fingerprint, the
hand-ported triggers) is now one module the parity test and the migration
generator share, with unit tests for the sorting and the rollback.
2026-11-17 23:03:49 +01:00
Maurice a99cd40f4d feat(db): write a migration's schema change once per engine
A migration after the Postgres baseline's cut runs on both engines, but its DDL
is not one language. engineDdl(this, { sqlite, postgres }) queues the statements
of the engine the migration runs on, like addSql, and addColumnIfMissing takes a
column definition per engine, both picked in the dialect layer so a migration
never branches on the engine itself.
2026-11-17 23:03:49 +01:00
Maurice f3ea50b17b fix(db): cut the Postgres baseline at the newest migration again
The merge with dev brought eight migrations written for SQLite (DATETIME,
INTEGER PRIMARY KEY without identity); run verbatim on Postgres they stop the
first boot. No Postgres install has been released, so the baseline moves to
the newest migration and those tables come from the entities.
2026-11-17 23:03:49 +01:00
Isaias Tavares 2e3762afe1 feat(db): run TREK on PostgreSQL
TREK runs on PostgreSQL when TREK_DB_URL is set, and on SQLite as before
otherwise: an engine port under src/db/engine, the dialect helpers under
src/db/dialect, a Postgres baseline for the migrations up to the cut,
pg_dump/pg_restore backups, a probe of every repository method against a
real server and a Postgres test lane in CI.
2026-11-17 23:03:33 +01:00
3183 changed files with 93628 additions and 24725 deletions
+1
View File
@@ -1,2 +1,3 @@
patreon: mauriceboe
ko_fi: mauriceboe
buy_me_a_coffee: mauriceboe
+156
View File
@@ -0,0 +1,156 @@
name: Set up Node and the workspaces
description: >-
Node from .nvmrc, the workspace dependencies from an exact cache or npm ci,
and optionally shared/dist from a cache or a build. Runs after checkout.
# A local action, so it is versioned with the workflow that calls it and needs
# no SHA pin. scripts/ci/changed-areas.mjs counts .github/actions/ like
# test.yml: a change here runs everything.
#
# node_modules is restored only on an exact key: the runner image, the scope,
# the Node ABI, the lockfile and every workspace package.json. There are no
# restore-keys, so a hit is the tree npm ci would build and a miss is a plain
# npm ci. The package.json files are in the key because npm ci is also the
# check that they agree with the lockfile: an edited range without a fresh
# lockfile misses the cache and fails the install, as it did when every job
# ran npm ci. Only pushes to dev and main save, the npm download cache
# included, so pull requests read what their base left and cannot evict it or
# fill the repository's cache quota with entries of their own.
inputs:
scope:
description: >-
Which workspaces to install: full (npm ci), client (shared and client)
or shared (shared alone).
required: true
build-shared:
description: "'true' to restore shared/dist, or build it on a miss."
required: false
default: 'false'
runs:
using: composite
steps:
- uses: actions/setup-node@v6
with:
node-version-file: .nvmrc
# ImageOS and ImageVersion name the runner image, whose system libraries
# the native modules were built against. They live in the runner's
# environment, not in the env context, so the key is put together here. A
# job in a container has neither; the container's OS release stands in,
# and that job's tree is kept apart from the runner's.
- name: Work out the cache keys
id: keys
shell: bash
env:
SCOPE: ${{ inputs.scope }}
DEPS: ${{ hashFiles('.nvmrc', 'package-lock.json', 'package.json', 'client/package.json', 'server/package.json', 'shared/package.json') }}
SHARED: ${{ hashFiles('shared/src/**', 'shared/package.json', 'shared/tsconfig*.json', 'shared/tsdown.config.ts', 'package-lock.json') }}
run: |
set -euo pipefail
case "$SCOPE" in
full | client | shared) ;;
*) echo "::error::scope must be full, client or shared, not '$SCOPE'"; exit 1 ;;
esac
if [ -n "${ImageOS:-}" ]; then
image="$ImageOS-${ImageVersion:-unknown}"
else
image="container-$(. /etc/os-release && echo "$ID$VERSION_ID")"
fi
abi="$(node -p process.versions.modules)"
echo "nm=nm-$RUNNER_OS-$image-$SCOPE-node$abi-$DEPS" >> "$GITHUB_OUTPUT"
echo "sd=sd-$RUNNER_OS-$SHARED" >> "$GITHUB_OUTPUT"
echo "save=${{ github.event_name == 'push' && (github.ref == 'refs/heads/dev' || github.ref == 'refs/heads/main') }}" >> "$GITHUB_OUTPUT"
- name: Restore node_modules
id: nm
uses: actions/cache/restore@v6
with:
path: |
node_modules
server/node_modules
client/node_modules
shared/node_modules
key: ${{ steps.keys.outputs.nm }}
# The npm download cache only matters when npm ci runs, so it is restored
# only then. It may fall back to an older lockfile's cache: npm ci checks
# every tarball against the lockfile's integrity hash and fetches what is
# missing, so a stale entry only costs downloads.
- name: Restore the npm download cache
id: npm
if: steps.nm.outputs.cache-hit != 'true'
uses: actions/cache/restore@v6
with:
path: ~/.npm
key: npm-${{ runner.os }}-${{ hashFiles('package-lock.json') }}
restore-keys: npm-${{ runner.os }}-
- name: Install dependencies
if: steps.nm.outputs.cache-hit != 'true'
shell: bash
env:
SCOPE: ${{ inputs.scope }}
run: |
set -euo pipefail
# better-sqlite3 ships no prebuilt binary and compiles on install. The
# hosted runners carry a compiler; the Playwright container of the e2e
# jobs does not, so on a cache miss there it gets one first. A hit,
# the usual case once a push to dev has saved the container's key,
# never reaches this step.
if ! command -v make >/dev/null || ! command -v g++ >/dev/null; then
export DEBIAN_FRONTEND=noninteractive
timeout 300 apt-get update -qq
timeout 300 apt-get install -y -qq --no-install-recommends make g++
fi
case "$SCOPE" in
full) npm ci ;;
# The scoped install keeps @testing-library/dom (a peer of
# @testing-library/react) in the tree.
client) npm ci --workspace shared --workspace client ;;
shared) npm ci --workspace shared ;;
esac
- name: Save node_modules
if: steps.nm.outputs.cache-hit != 'true' && steps.keys.outputs.save == 'true'
uses: actions/cache/save@v6
with:
path: |
node_modules
server/node_modules
client/node_modules
shared/node_modules
key: ${{ steps.keys.outputs.nm }}
# Only a full install saves the download cache, so the entry holds every
# tarball; a scoped job that finished first would otherwise claim the key
# with part of the tree and no later run would fill it.
- name: Save the npm download cache
if: steps.nm.outputs.cache-hit != 'true' && steps.keys.outputs.save == 'true' && steps.npm.outputs.cache-hit != 'true' && inputs.scope == 'full'
uses: actions/cache/save@v6
with:
path: ~/.npm
key: npm-${{ runner.os }}-${{ hashFiles('package-lock.json') }}
# The key holds every input of the build: the sources, the package and
# build configs, and the lockfile that pins tsdown and zod.
- name: Restore shared/dist
id: sd
if: inputs.build-shared == 'true'
uses: actions/cache/restore@v6
with:
path: shared/dist
key: ${{ steps.keys.outputs.sd }}
- name: Build shared
if: inputs.build-shared == 'true' && steps.sd.outputs.cache-hit != 'true'
shell: bash
run: npm run build --workspace=shared
- name: Save shared/dist
if: inputs.build-shared == 'true' && steps.sd.outputs.cache-hit != 'true' && steps.keys.outputs.save == 'true'
uses: actions/cache/save@v6
with:
path: shared/dist
key: ${{ steps.keys.outputs.sd }}
+4 -1
View File
@@ -7,8 +7,11 @@
# enforce-target-branch.yml moves those onto dev.
#
# Every PR runs test.yml like any other, so ci-ok decides whether it can
# merge. Dependabot runs get no Actions secrets, so s3-contract and the Sonar
# merge. Dependabot runs get no Actions secrets, so server-s3 and the Sonar
# scan skip themselves on these PRs and ci-ok counts the skip as passed.
# A bump of @playwright/test also needs the Playwright container tag and
# digest in test.yml's client-e2e moved by hand; workflow-jobs.test.mjs
# fails the PR until they match.
version: 2
updates:
# The root lockfile covers the client, server and shared workspaces.
+8 -1
View File
@@ -18,9 +18,16 @@ jobs:
- uses: actions/setup-node@v6
with:
node-version-file: .nvmrc
cache: npm
cache-dependency-path: package-lock.json
# shared's ESLint and Prettier plugins are its own devDependencies, and
# the format ratchet in scripts/lib/ resolves prettier from the root, so
# shared plus the root is the whole tree these checks read. npm ci
# installs exactly what the lockfile says, where npm install could
# resolve anew.
- name: Install dependencies
run: npm install
run: npm ci --workspace shared --include-workspace-root
- name: Run lint & format check
# Both are check-only: lint used to run eslint --fix, which rewrote the
+7 -29
View File
@@ -10,6 +10,13 @@ permissions:
#
# Unsigned on purpose: signing and store uploads need secrets that fork PRs do
# not get, and belong in a release workflow of their own.
#
# package-lock.json is not a trigger: every dependency bump touches it, and a
# Mac build per bump only held the queue. The shells link nothing but the
# @capacitor/* packages, all declared in client/package.json, and a Dependabot
# bump of one of them raises the range there too, so it still runs. The client
# typecheck and the watch and widget snapshot tests run in test.yml on every
# change under client/.
on:
pull_request:
paths:
@@ -24,7 +31,6 @@ on:
- 'client/scripts/check-store-metadata.mjs'
- 'client/fastlane/**'
- 'client/package.json'
- 'package-lock.json'
- 'shared/src/i18n/*/native.ts'
- '.github/workflows/native.yml'
workflow_dispatch:
@@ -182,34 +188,6 @@ jobs:
path: client/ios/WidgetPreviews/out
retention-days: 14
# The watch's half in the UI (client/src/native/watch.ts): the snapshot it
# builds and the ticks it takes back, typechecked and tested here as well,
# so a change to the bridge is checked next to the Swift that reads it.
watch-bridge:
runs-on: ubuntu-24.04
timeout-minutes: 15
steps:
- uses: actions/checkout@v6
- uses: actions/setup-node@v6
with:
node-version-file: .nvmrc
cache: npm
- name: Install
run: npm ci --workspace=shared --workspace=client
- name: Build shared
run: npm run build --workspace=shared
- name: Typecheck the client
working-directory: client
run: npm run typecheck
- name: Test the widget and watch snapshots
working-directory: client
run: npx vitest run src/native/watch.test.ts src/native/widgets.test.ts src/native/widgetExtras.test.ts
# The watch app on watchOS simulators in its screenshot mode (DemoMode.swift):
# every screen on the largest and the smallest watch, the main ones in every
# language, and the complications, as PNGs to look at without a watch.
+2 -2
View File
@@ -13,7 +13,7 @@ name: Security Scan
# - scout scans the built image, base image packages included. It needs
# the Docker Hub login, so it runs on PRs and pushes into main only and
# skips fork PRs. Whether the image builds at all is test.yml's
# docker-image job, which a red scan cannot hide.
# docker job, which a red scan cannot hide.
on:
pull_request:
branches: [main, dev]
@@ -79,7 +79,7 @@ jobs:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- uses: docker/scout-action@e7e2a72bf1485d10a58f30696b6c513b261ce4fa # v1.29.0
- uses: docker/scout-action@b265cd48f8a1451d2680815b3e8dc4ed65ee16e7 # v1.30.0
with:
command: cves
image: trek:scan
+938 -747
View File
File diff suppressed because it is too large Load Diff
+13 -5
View File
@@ -31,6 +31,7 @@ Tests:
npm run test # all workspaces
npm run test --workspace=server # vitest run (server); also test:unit / test:integration / test:ws
npm run test:e2e # server e2e (boots Nest against a temp SQLite)
npm run test:pg --workspace=server # the Postgres lane (vitest.pg.config.ts; needs TREK_TEST_DB_URL, e.g. postgres://postgres:trek@127.0.0.1:55432/postgres)
npm run test:cov # coverage (lcov) for all four packages incl. plugin-sdk
cd client && npm run test # client vitest run
cd client && npm run e2e # Playwright (CI runs the public and app projects; the screenshot and help-media ones are local)
@@ -51,7 +52,9 @@ cd client && npm run lint:skips # no .only; skipped tests may
cd client && npm run lint:i18n-keys # every key the client names exists in en; unused en keys may only shrink (CI gate)
cd server && npm run lint:boundaries # no new import cycles or cross-domain reach-ins (CI gate)
cd server && npm run lint:dialect # SQLite-only SQL spellings may only shrink (CI gate; rules in server/CLAUDE.md)
cd server && npm run lint:engine-dispatch # engine checks outside src/db/dialect/ and src/db/engine/ may only shrink (CI gate)
cd server && npm run probe:pg # dialect helpers + the repository statements it reaches against Postgres (CI job; needs TREK_PG_PROBE_URL)
cd server && npm run check:pg-baseline # the Postgres baseline in server/assets/postgres/ matches the entities and the migrations (CI gate)
cd server && npm run lint:tx # no new method writing twice outside one transaction (CI gate)
cd server && npm run lint:test-sql # raw SQL fixtures in tests/ may only shrink; seed through tests/helpers/factories (CI gate)
cd server && npm run lint:test-mocks # vi.mock of config, realtime and db modules in tests/ may only shrink (CI gate)
@@ -134,13 +137,18 @@ These principles come out of a full-repo audit and shape all new code:
## 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: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-checks), `check:plugin-facts`, `i18n:parity:strict` (with the untranslated-strings ratchet), the S3 contract suite, the Postgres probe (`postgres-probe`: every dialect helper on SQLite and Postgres, and the statements every repository method reaches with sample arguments against a Postgres service; the SQL errors per method and the list of methods it cannot measure are held to a baseline that only shrinks and fails while it is still unmeasured; see `server/CLAUDE.md`), the browser end-to-end flows (Chromium and WebKit), 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 (`docker-image`), and lints and renders the Helm chart against the Kubernetes schemas and runs `docker compose config` on every compose file (`deploy-manifests`). `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 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.
- **Job names read "package: what"** (`Server: Types`, `Client: Tests 3/7`), and the list at the top of `test.yml` says what each job holds. A new job follows the scheme and joins that list, and the job-count note there says when a long job needs a slot freed first.
- **Tests run beside the gates, in shards.** The client and server suites run in slices on parallel runners (`client-tests`, `server-tests`, through each package's `vitest.shard.config.ts`), and `client-coverage`/`server-coverage` merge their blob reports and check the thresholds against the whole. A red slice is usually a failing test, a red merge job usually a threshold.
- **`ci-ok` is the required check.** The branch ruleset requires `ci-ok` (plus `lint` and `check-target` from their own workflows), and `ci-ok` needs every job above except the scan. It fails if any of them failed or was cancelled and passes if they passed or were skipped. A new gate job counts only once it is listed in `ci-ok`'s `needs:`.
- **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.
- **Tests run beside the gates, in shards.** The client and server suites run in ten slices each on parallel runners (`client-tests`, `server-tests`, through each package's `vitest.shard.config.ts`), the Postgres lane in three per major, and the end-to-end flows in two, and `client-coverage`/`server-coverage` merge their blob reports and check the thresholds against the whole. A red slice is usually a failing test, a red merge job usually a threshold. A sliced job states its slice count in its matrix's shard axis, the `i/n` in its name and its `--shard=i/n`; `scripts/ci/workflow-jobs.test.mjs` fails until all three agree, and on any job naming `matrix.shard` or `--shard` whose axis is not the one-line `shard: [1, ..., n]` it reads.
- **`ci-ok` is the required check.** The branch ruleset requires `ci-ok` (plus `lint` and `check-target` from their own workflows), and `ci-ok` needs every job above except the scan. It fails if any of them failed or was cancelled and passes if they passed or were skipped. A new gate job counts only once it is listed in `ci-ok`'s `needs:`, and `scripts/ci/workflow-jobs.test.mjs` (in `test:ci-scripts`) fails while a job other than the scan is missing there.
- **The release pull request mirrors the push run.** On the pull request from `dev` into `main` (head branch in this repository), `changes` sets `mirror` and turns every area off (`scripts/ci/changed-areas.mjs`), so no test, gate or scan job runs, and `ci-ok` runs `scripts/ci/mirror-push-run.mjs`: it waits for the `ci-ok` of the push run of `test.yml` on `dev` for exactly the PR's head commit and passes or fails with it. No such push run, one that ended without a verdict, or a wait past 17 minutes fails with a re-run hint, never passes. A push to `dev` lists its changes against the merge base with `main`, not against the previous push, so the run it mirrors covers every area the pull request brings in, even when an earlier push's run was cancelled or red. Testing that commit twice doubled the jobs past the 60 slots.
- **Guides name paths that exist**: the `changes` job runs `scripts/ci/doc-paths.mjs`, which resolves every backtick path in the CLAUDE.md files, `README.md`, `server/src/nest/README.md` and the wiki against the tracked files; the missing ones are listed in `scripts/ci/doc-paths-baseline.json`, which only shrinks (`--update` after a fix).
- **What runs is decided by `changes`, not by `on.paths`**: `scripts/ci/changed-areas.mjs` maps the changed files to the `code`, `image` and `deploy` areas (tests: `npm run test:ci-scripts`). A path filter on the workflow would leave `ci-ok` unreported on a docs-only PR and block it. Add a new top-level file the build reads to the right area there.
- **What runs is decided by `changes`, not by `on.paths`**: `scripts/ci/changed-areas.mjs` maps the changed files to the `code`, `image` and `deploy` areas (tests: `npm run test:ci-scripts`). A path filter on the workflow would leave `ci-ok` unreported on a docs-only PR and block it. Add a new top-level file the build reads to the right area there. A change to `test.yml`, to `scripts/ci/` or to a local action under `.github/actions/` runs everything.
- **Setup goes through one local action.** Every job that installs dependencies uses `.github/actions/setup/action.yml` (`scope` full, client or shared; `build-shared`) instead of its own `npm ci`; `workflow-jobs.test.mjs` fails on a job that installs on its own (plugin-sdk's own install in its directory excepted). The action restores node_modules on an exact key (runner image, scope, Node ABI, `.nvmrc`, the lockfile and every workspace `package.json`, so npm ci still refuses a `package.json` out of step with the lockfile; no restore-keys) and shared/dist on a key over shared's sources and build config, and runs `npm ci` or the shared build on a miss. Only pushes to dev and main save, the npm download cache included; pull requests only read.
- **End-to-end runs in the Playwright container**, `mcr.microsoft.com/playwright:v<version>-noble` pinned by digest, so no step installs browsers or system libraries. Dependabot bumps only the lockfile: on every Playwright PR move the tag and its digest in `client-e2e` by hand (`docker buildx imagetools inspect mcr.microsoft.com/playwright:v<version>-noble`); `workflow-jobs.test.mjs` fails until the tag names the lockfile's `@playwright/test` version.
- **Budget: `ci-ok` within ten minutes.** One code run starts at most about 35 long jobs (gates, slices, Postgres, e2e, Docker), so two PR runs fit in the organisation's 60 concurrent jobs. Every job sets `timeout-minutes` of at most 20 (15 for the long ones, 10 for the short ones), which `workflow-jobs.test.mjs` holds. A new long job, slice or shard needs a reason that outweighs its slot; the job-count note at the top of `test.yml` has the numbers.
- **Runners and Node**: jobs run on `ubuntu-24.04`, not `ubuntu-latest`, and every `setup-node` reads `.nvmrc`. Third-party actions (anything outside `actions/*`) are pinned by commit SHA with the tag in a comment; Dependabot keeps both current.
- **Security scans are advisory.** `security.yml` runs `npm audit` (what the image installs, plus `plugin-sdk`) on every PR and push into dev and main, and Docker Scout on the built image for main. Neither is required: a newly published advisory would turn every open PR red at once. Fixes are held as floors in the root `package.json` `overrides`; npm ignores an `overrides` block in a workspace `package.json`, so never put one there.
- **Releases** are dispatched by hand and refuse a commit whose `ci-ok` is not green. `docker-dev.yml` (any branch, usually dev) is the canary: it builds the dispatched commit as the next minor or major `-pre.N` and moves only `:latest-pre` and `:<major>-pre`. `docker.yml` (main only) bumps the version, commits and tags it, builds both platforms from exactly that commit and moves `:latest`, `:<major>`, `:<major>.<minor>` and `:<version>`. Its `bump=auto` only finalizes a prerelease in flight; without one it stops and asks for patch, minor or major. Ship a release that migrates or changes a lot as a prerelease first, and as a minor, so installs pinned to `:<major>.<minor>` can wait it out.
+24 -10
View File
@@ -72,17 +72,30 @@ COPY server/package.json ./server/
# package, and a telemetry ping.
# 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).
RUN apt-get update && \
#
# postgresql-client-18 brings pg_dump, pg_restore and psql to
# /usr/lib/postgresql/18/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
# a newer one, so the image carries the newest major TREK supports (14 to 18).
# 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
# other, and the 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 both together when TREK supports a newer major.
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' \
> /etc/apt/sources.list.d/pgdg.list && \
apt-get update && \
apt-get upgrade -y --no-install-recommends && \
apt-get install -y --no-install-recommends tzdata dumb-init wget ca-certificates \
libkitinerary-bin libsqlite3-0 && \
libkitinerary-bin libsqlite3-0 postgresql-client-18 && \
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; } && \
rm -rf /var/lib/apt/lists/* /usr/local/lib/node_modules/npm /usr/local/bin/npm /usr/local/bin/npx && \
chown -R node:node /app
# gosu rebuilt with a current Go toolchain (stage 0) — the entrypoint script uses
# it to drop to node.
# gosu rebuilt with a current Go toolchain (stage 0). The entrypoint drops to node
# with setpriv since #3135; gosu stays in the image for anyone who calls it by hand.
COPY --from=gosu-build /out/gosu /usr/local/bin/gosu
ENV XDG_CACHE_HOME=/tmp/kf6-cache
@@ -94,8 +107,9 @@ ENV KITINERARY_EXTRACTOR_PATH=/usr/local/bin/kitinerary-extractor
COPY --chown=node:node --from=server-builder /app/server/dist ./server/dist
# Runtime data assets read from server/assets at runtime: airports.json (flight
# transport search) and atlas/*.geojson.gz + atlas/admin1/*.geojson.gz (Atlas
# country/region map). The build
# transport search), atlas/*.geojson.gz + atlas/admin1/*.geojson.gz (Atlas
# country/region map) and postgres/baseline.* (the schema a fresh Postgres
# database starts from). The build
# only emits dist, so these must be copied explicitly or the features silently
# degrade to empty in the image.
COPY --chown=node:node --from=server-builder /app/server/assets ./server/assets
@@ -106,9 +120,9 @@ COPY --chown=node:node wiki ./wiki
# tsconfig-paths/register reads this at runtime to resolve MCP SDK paths.
COPY --chown=node:node server/tsconfig.json ./server/
# Encryption-key rotation is run on demand via tsx (a prod dep) straight from the
# raw .ts source — it never enters dist, so it must be copied in explicitly or
# raw .ts source (the command and its stores module). They never enter dist, so they must be copied in explicitly or
# `node --import tsx scripts/migrate-encryption.ts` fails with module-not-found.
COPY --chown=node:node server/scripts/migrate-encryption.ts ./server/scripts/migrate-encryption.ts
COPY --chown=node:node server/scripts/migrate-encryption.ts server/scripts/migrate-encryption-stores.ts ./server/scripts/
# Admin recovery script (node server/reset-admin.js) for locked-out installs.
COPY --chown=node:node server/reset-admin.js ./server/reset-admin.js
COPY --chown=node:node --from=shared-builder /app/shared/dist ./shared/dist
@@ -159,8 +173,8 @@ HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
# carrying quotes does not survive that round-trip (the container then dies with
# a shell syntax error before Node starts). A CMD of one bare token does.
COPY server/scripts/entrypoint.sh /usr/local/bin/trek-entrypoint
# Root-owned on purpose — this is what calls gosu, so it runs before the drop to
# node. chmod is explicit because a checkout on Windows carries no exec bit.
# Root-owned on purpose: it runs as root and drops to node itself, with setpriv.
# chmod is explicit because a checkout on Windows carries no exec bit.
RUN chmod 0755 /usr/local/bin/trek-entrypoint
ENTRYPOINT ["dumb-init", "--"]
+7
View File
@@ -24,6 +24,8 @@ TREK has grown from a travel planner into a whole ecosystem for trips: plan toge
&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>
&nbsp;
<a href="https://www.patreon.com/cw/mauriceboe"><img alt="Patreon" src="https://img.shields.io/badge/Patreon-monthly-141518?style=for-the-badge" /></a>
&nbsp;
<a href="https://ko-fi.com/mauriceboe"><img alt="Ko-fi" src="https://img.shields.io/badge/Ko--fi-support-FF5E5B?style=for-the-badge" /></a>
&nbsp;
<a href="https://www.buymeacoffee.com/mauriceboe"><img alt="BMAC" src="https://img.shields.io/badge/BMAC-support-FFDD00?style=for-the-badge" /></a>
@@ -321,6 +323,11 @@ docker compose up -d
See [Install with Docker Compose](https://github.com/liketrek/TREK/wiki/Install-Docker-Compose)
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
[`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
how to move an existing SQLite install to Postgres with the command TREK ships for it.
<br />
<h2 id="helm-kubernetes">Helm (Kubernetes)</h2>
+1
View File
@@ -46,6 +46,7 @@ See `values.yaml` for more options.
- Both PVCs are `ReadWriteOnce`. Set `persistence.data.accessModes` and/or `persistence.uploads.accessModes` to override, for example `[ReadWriteMany]` so a backup pod can mount the volume. On the data volume such a pod may only read: SQLite corrupts `travel.db` when a second process writes it over a network filesystem.
- To use your own PVCs, set `persistence.data.existingClaim` and/or `persistence.uploads.existingClaim`. The other values for that volume (size, storageClassName, accessModes, annotations) are then ignored.
- With `persistence.enabled: false`, the data and uploads volumes use an `emptyDir` — storage is ephemeral and lost on pod restart. Intended for testing only.
- `database.url` runs TREK on a PostgreSQL database instead of the SQLite file. The chart writes it into its Secret as `TREK_DB_URL`; `database.existingSecret` and `database.existingSecretKey` read it from a Secret you manage. Leave both empty for SQLite. Keep `replicas: 1` either way. See the wiki page `Database-Postgres`.
- `JWT_SECRET` is managed entirely by the server — auto-generated into the data PVC on first start and rotatable via the admin panel (Settings → Danger Zone). No Helm configuration needed.
- `ENCRYPTION_KEY` encrypts stored secrets (API keys, MFA, SMTP, OIDC) at rest. Recommended: set via `secretEnv.ENCRYPTION_KEY` or `existingSecret`. If left empty, the server falls back automatically: existing installs use `data/.jwt_secret` (no action needed on upgrade); fresh installs auto-generate a key persisted to the data PVC.
- Liveness and readiness probes are configurable under `probes`. Overrides are merged over the defaults, so `--set probes.liveness.initialDelaySeconds=60` keeps the `httpGet` handler. When switching to `exec` or `tcpSocket`, clear `httpGet` in the same override. Set `probes.liveness: null` to remove a probe.
+18 -4
View File
@@ -1,3 +1,7 @@
{{- $db := default dict .Values.database }}
{{- if and $db.url (not $db.existingSecret) .Values.existingSecret }}
{{- fail "database.url is written into the chart's own Secret, which existingSecret replaces. Put TREK_DB_URL in your Secret and set database.existingSecret instead." }}
{{- end }}
apiVersion: apps/v1
kind: Deployment
metadata:
@@ -5,11 +9,13 @@ metadata:
labels:
app: {{ include "trek.name" . }}
spec:
# One replica. Its rate limits, pending codes, permission cache and WebSocket
# connections live in the process's memory, so a second pod would not share them. That
# holds with database.url (PostgreSQL) too; see updateStrategy in values.yaml.
replicas: 1
# TREK is a single-writer SQLite app on a ReadWriteOnce PVC, so the default
# RollingUpdate would start a second pod holding the same volume before the old one
# exits — a Multi-Attach deadlock, or two processes on one travel.db. Recreate tears
# the old pod down first. Keep it, see updateStrategy in values.yaml.
# The default RollingUpdate would start a second pod on the same ReadWriteOnce PVC
# before the old one exits: a Multi-Attach deadlock, or two processes on one travel.db.
# Recreate tears the old pod down first. Keep it, see updateStrategy in values.yaml.
strategy:
type: {{ .Values.updateStrategy | default "Recreate" }}
selector:
@@ -61,6 +67,14 @@ spec:
name: {{ default (printf "%s-secret" (include "trek.fullname" .)) .Values.existingSecret }}
key: {{ .Values.existingSecretKey | default "ENCRYPTION_KEY" }}
optional: true
{{- if or $db.url $db.existingSecret }}
# Required when set: a missing key stops the pod rather than starting it on SQLite.
- name: TREK_DB_URL
valueFrom:
secretKeyRef:
name: {{ default (printf "%s-secret" (include "trek.fullname" .)) $db.existingSecret }}
key: {{ if $db.existingSecret }}{{ $db.existingSecretKey | default "TREK_DB_URL" }}{{ else }}TREK_DB_URL{{ end }}
{{- end }}
- name: ADMIN_EMAIL
valueFrom:
secretKeyRef:
+7
View File
@@ -1,3 +1,4 @@
{{- $db := default dict .Values.database }}
{{- if and (not .Values.existingSecret) (not .Values.generateEncryptionKey) }}
apiVersion: v1
kind: Secret
@@ -8,6 +9,9 @@ metadata:
type: Opaque
data:
{{ .Values.existingSecretKey | default "ENCRYPTION_KEY" }}: {{ .Values.secretEnv.ENCRYPTION_KEY | b64enc | quote }}
{{- if $db.url }}
TREK_DB_URL: {{ $db.url | b64enc | quote }}
{{- end }}
{{- if .Values.secretEnv.ADMIN_EMAIL }}
ADMIN_EMAIL: {{ .Values.secretEnv.ADMIN_EMAIL | b64enc | quote }}
{{- end }}
@@ -65,6 +69,9 @@ stringData:
{{- else }}
{{ .Values.existingSecretKey | default "ENCRYPTION_KEY" }}: {{ randAlphaNum 32 | quote }}
{{- end }}
{{- if $db.url }}
TREK_DB_URL: {{ $db.url | quote }}
{{- end }}
{{- if .Values.secretEnv.ADMIN_EMAIL }}
ADMIN_EMAIL: {{ .Values.secretEnv.ADMIN_EMAIL | quote }}
{{- end }}
+23 -4
View File
@@ -4,10 +4,13 @@ image:
# tag: latest
pullPolicy: IfNotPresent
# Deployment update strategy. Keep Recreate: TREK is a single-writer SQLite app, and
# during a RollingUpdate the new pod migrates the database while the old one still
# writes to it. A ReadWriteMany volume does not make that safe; SQLite's WAL needs both
# processes on one host, which network filesystems do not provide.
# Deployment update strategy. Keep Recreate. The new pod migrates the database when it
# starts, and during a RollingUpdate it would do that while the old pod still writes to
# it. Recreate stops the old pod first. On SQLite two processes on one travel.db are
# unsafe, and a ReadWriteOnce volume cannot be attached to both pods at once.
# With database.url the database is PostgreSQL, but the reason for one replica stays: TREK
# keeps rate limits, pending codes, the permission cache and WebSocket connections in
# memory, so a second pod would not share them. Postgres does not make more replicas safe.
updateStrategy: Recreate
# Pod-level security context. fsGroup gives the node user (uid/gid 1000) group access
@@ -178,6 +181,22 @@ env:
# address is sent unless you set one here.
# Database. Empty (the default) keeps TREK on its SQLite file in the data volume. Set url to
# run TREK on a PostgreSQL database instead (see the wiki page Database-Postgres). The URL
# carries the password, so it is never a plain env value: with url, the chart writes it into
# its own Secret as TREK_DB_URL; with existingSecret, TREK reads TREK_DB_URL from that Secret
# under existingSecretKey and the chart writes nothing. existingSecret wins over url. The
# variable is required when either is set: a missing Secret key stops the pod instead of
# 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
# 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.
# url: "postgres://trek:<password>@postgres.example.internal:5432/trek?sslmode=require"
database:
url: ""
existingSecret: ""
existingSecretKey: TREK_DB_URL
# Secret environment variables stored in a Kubernetes Secret.
# JWT_SECRET is managed entirely by the server (auto-generated into the data PVC,
# rotatable via the admin panel) — it is not configured here.
@@ -0,0 +1,60 @@
package com.liketrek.trek;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* The log line for a page of the server that came back with an error status.
* "HTTP 503" on the address screen cannot tell the server, a proxy in front of
* it and something on the phone apart, so the line names the page and the
* headers that say who answered (#3014).
*/
final class PageErrorLog {
/** The headers that name whoever answered a page, in the order they are logged. */
private static final String[] SENDER_HEADERS = { "Server", "Via", "CF-Ray", "Content-Type" };
private PageErrorLog() {}
/**
* For example "Page answered HTTP 503 Service Unavailable for
* https://trek.example.com/login (server: cloudflare, cf-ray: 8f1a2b3c4d5e6f70-FRA)".
* The address goes without its query and fragment, where a sign-in page
* carries a challenge or a code. A header the answer did not have is left
* out, and an answer with none of them says so: no server sends a page
* without at least its type, so that points at something on the phone.
*/
static String describe(String url, int status, String reason, Map<String, String> headers) {
StringBuilder line = new StringBuilder("Page answered HTTP ").append(status);
if (reason != null && !reason.trim().isEmpty()) line.append(' ').append(reason.trim());
line.append(" for ").append(withoutQuery(url));
List<String> senders = new ArrayList<>();
for (String name : SENDER_HEADERS) {
String value = header(headers, name);
if (value != null && !value.trim().isEmpty()) senders.add(name.toLowerCase(Locale.ROOT) + ": " + value.trim());
}
line.append(senders.isEmpty() ? " (no server headers)" : " (" + String.join(", ", senders) + ")");
return line.toString();
}
/** A header by name, whatever case the answer wrote it in. */
private static String header(Map<String, String> headers, String name) {
if (headers == null) return null;
for (Map.Entry<String, String> entry : headers.entrySet()) {
if (name.equalsIgnoreCase(entry.getKey())) return entry.getValue();
}
return null;
}
private static String withoutQuery(String url) {
if (url == null) return "";
int end = url.length();
int query = url.indexOf('?');
if (query >= 0) end = query;
int fragment = url.indexOf('#');
if (fragment >= 0 && fragment < end) end = fragment;
return url.substring(0, end);
}
}
@@ -556,7 +556,7 @@ public class TrekShellPlugin extends Plugin {
if (path == null || path.isEmpty()) continue;
String clean = path.startsWith("/") ? path.substring(1) : path;
keep.add(clean);
if (TrekOfflineShell.hasFile(context, clean)) continue;
if (clean.contains("/") && TrekOfflineShell.hasFile(context, clean)) continue;
byte[] data = download(server, clean, null);
if (data == null || !TrekOfflineShell.saveFile(context, clean, data)) complete = false;
}
@@ -572,7 +572,10 @@ public class TrekShellPlugin extends Plugin {
}).start();
}
/** A file of the server's UI, or null: only a 200 counts, and the page only as HTML. */
/**
* A file of the server's UI, or null: only a 200 from the server itself
* counts, the page only as HTML and a file only as something else.
*/
private static byte[] download(String server, String path, String wantType) {
java.net.HttpURLConnection connection = null;
try {
@@ -584,8 +587,11 @@ public class TrekShellPlugin extends Plugin {
connection.setInstanceFollowRedirects(true);
if (wantType != null) connection.setRequestProperty("Accept", wantType);
if (connection.getResponseCode() != 200) return null;
java.net.URL landed = connection.getURL();
if (!landed.getProtocol().equals(base.getProtocol()) || !landed.getHost().equalsIgnoreCase(base.getHost()) || portOf(landed) != portOf(base)) return null;
String type = connection.getContentType();
if (wantType != null && (type == null || !type.startsWith(wantType))) return null;
if (wantType == null && type != null && type.startsWith("text/html") && !path.endsWith(".html")) return null;
try (java.io.InputStream in = connection.getInputStream()) {
java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
byte[] buffer = new byte[16384];
@@ -599,6 +605,10 @@ public class TrekShellPlugin extends Plugin {
}
}
private static int portOf(java.net.URL url) {
return url.getPort() == -1 ? url.getDefaultPort() : url.getPort();
}
/**
* The address screen found the server out of reach: with a copy of its UI
* the app restarts on that instead (TrekOfflineShell), the same way it
@@ -202,14 +202,23 @@ class TrekWebViewClient extends BridgeWebViewClient {
* none, as Cloudflare does with a 403, sends the app to the address screen,
* which says so and offers to add one. Any other 4xx page (a proxy's block
* page, a certificate it refused) stays up with the bar and its way out, so
* the app is never stuck on a page without TREK's UI.
* the app is never stuck on a page without TREK's UI. Each one is logged
* with its address and whoever answered it (PageErrorLog).
*/
@Override
public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
int status = errorResponse.getStatusCode();
if (!request.isForMainFrame()) {
super.onReceivedHttpError(view, request, errorResponse);
} else if (status >= 500 || (status >= 400 && wantedCertificate(request.getUrl()))) {
return;
}
Log.w("TrekShell", PageErrorLog.describe(
request.getUrl().toString(),
status,
errorResponse.getReasonPhrase(),
errorResponse.getResponseHeaders()
));
if (status >= 500 || (status >= 400 && wantedCertificate(request.getUrl()))) {
TrekServerStore.setFailure(view.getContext(), "HTTP " + status);
onUnreachable.run();
} else if (status >= 400) {
@@ -82,10 +82,12 @@ abstract class TrekWidget : GlanceAppWidget() {
// Read inside the composition: a session outlives one update, and every
// write (the dashboard's, then each trip's) must reach it.
val version by WidgetStore.version.collectAsState()
val snapshot = remember(version) {
val stored = remember(version) {
val tripId = if (perTrip && appWidgetId >= 0) WidgetStore.tripFor(context, appWidgetId) else WidgetStore.AUTO
WidgetStore.load(context, tripId)
}
// The day of the trip is today's on every update, not the one the app last wrote.
val snapshot = stored?.on(LocalDate.now())
TrekWidgetTheme.Themed { Content(snapshot) }
}
}
@@ -27,7 +27,28 @@ data class WidgetSnapshot(
val labels: Labels,
/** The trip's next flight or the one in the air; last and defaulted, so older callers keep compiling. */
val flight: Flight? = null,
/**
* The trip's days from the day the app wrote this on, each with its date, so
* the widget turns to the next day itself (see [on]); empty from an app
* that predates them.
*/
val days: List<Today> = emptyList(),
) {
/**
* The snapshot as it reads on [date]: that date's trip day out of [days],
* none before or after the trip, and only the bookings from that date on.
* The app writes its snapshot only while it runs, so without this a widget
* showed the day it last ran. A snapshot without [days] reads as written.
*/
fun on(date: LocalDate): WidgetSnapshot {
if (days.isEmpty()) return this
val key = date.toString()
return copy(
today = if (today?.date == key) today else days.firstOrNull { it.date == key },
bookings = bookings.filter { (it.date ?: key) >= key },
)
}
data class Trip(
val title: String,
val start: String,
@@ -52,7 +73,8 @@ data class WidgetSnapshot(
val symbol: String?,
)
data class Today(val dayLabel: String, val stops: List<Stop>, val index: Int?, val total: Int?)
/** A trip day; [date] (yyyy-MM-dd) is absent from an app that predates the days ahead. */
data class Today(val dayLabel: String, val stops: List<Stop>, val index: Int?, val total: Int?, val date: String? = null)
data class Weather(
val temp: Int,
@@ -212,6 +234,16 @@ data class WidgetSnapshot(
null
}
private fun dayOf(t: JSONObject): Today = Today(
dayLabel = t.optString("dayLabel"),
stops = t.optJSONArray("stops").objects().map {
Stop(it.str("time"), it.optString("name"), it.int("minutes"), it.str("color"), it.str("symbol"))
},
index = t.int("index"),
total = t.int("total"),
date = t.str("date"),
)
fun fromJson(o: JSONObject): WidgetSnapshot = WidgetSnapshot(
trip = o.optJSONObject("trip")?.let {
Trip(
@@ -226,16 +258,8 @@ data class WidgetSnapshot(
memberCount = it.int("memberCount"),
)
},
today = o.optJSONObject("today")?.let { t ->
Today(
dayLabel = t.optString("dayLabel"),
stops = t.optJSONArray("stops").objects().map {
Stop(it.str("time"), it.optString("name"), it.int("minutes"), it.str("color"), it.str("symbol"))
},
index = t.int("index"),
total = t.int("total"),
)
},
today = o.optJSONObject("today")?.let(::dayOf),
days = o.optJSONArray("days").objects().map(::dayOf),
weather = o.optJSONObject("weather")?.let {
Weather(it.optInt("temp"), it.int("high"), it.int("low"), it.optString("main"), it.optString("label"), it.str("place"), it.int("rain"))
},
@@ -0,0 +1,51 @@
package com.liketrek.trek
import org.junit.Assert.assertEquals
import org.junit.Test
/** The log line for a page that came back with an error status (#3014). */
class PageErrorLogTest {
@Test
fun namesThePageItsStatusAndWhoAnswered() {
val line = PageErrorLog.describe(
"https://trek.example.com/login?redirect=%2F#top",
503,
"Service Unavailable",
mapOf(
"server" to "cloudflare",
"CF-RAY" to "8f1a2b3c4d5e6f70-FRA",
"content-type" to "text/html; charset=UTF-8",
"Set-Cookie" to "session=secret",
),
)
// Any case of a header name is read, only the naming headers are logged,
// and the query with its sign-in state is left off.
assertEquals(
"Page answered HTTP 503 Service Unavailable for https://trek.example.com/login " +
"(server: cloudflare, cf-ray: 8f1a2b3c4d5e6f70-FRA, content-type: text/html; charset=UTF-8)",
line,
)
}
@Test
fun anAnswerWithoutHeadersSaysSo() {
assertEquals(
"Page answered HTTP 503 for https://trek.example.com/ (no server headers)",
PageErrorLog.describe("https://trek.example.com/", 503, null, emptyMap()),
)
assertEquals(
"Page answered HTTP 502 Bad Gateway for (no server headers)",
PageErrorLog.describe(null, 502, "Bad Gateway", null),
)
}
@Test
fun aFragmentBeforeAQuestionMarkEndsTheAddressThere() {
assertEquals(
"Page answered HTTP 500 for https://trek.example.com/trips/4 (via: 1.1 proxy)",
PageErrorLog.describe("https://trek.example.com/trips/4#a?b", 500, " ", mapOf("Via" to "1.1 proxy")),
)
}
}
@@ -99,4 +99,49 @@ class WidgetSnapshotTest {
assertEquals("ferry.fill", TrekIcons.booking("cruise").first)
assertEquals("bookmark.fill", TrekIcons.booking("something").first)
}
@Test
fun turnsToTheDayOfTheDateItIsReadOn() {
val json = """{"trip":{"title":"T","start":"2026-11-06","end":"2026-11-08","path":"/trips/1"},
"today":{"date":"2026-11-06","dayLabel":"Day 1 of 3","stops":[{"time":"09:00","name":"Museum","minutes":540}]},
"days":[
{"date":"2026-11-06","dayLabel":"Day 1 of 3","stops":[{"time":"09:00","name":"Museum","minutes":540}]},
{"date":"2026-11-07","dayLabel":"Day 2 of 3","stops":[{"time":"10:00","name":"Harbour","minutes":600}]}
],
"bookings":[
{"title":"Hotel","kind":"hotel","date":"2026-11-06","confirmed":true,"path":"/trips/1"},
{"title":"Train","kind":"train","date":"2026-11-07","confirmed":true,"path":"/trips/1"}
],
"labels":{}}"""
val snapshot = WidgetSnapshot.parse(json)!!
assertEquals("Day 1 of 3", snapshot.on(LocalDate.of(2026, 11, 6)).today!!.dayLabel)
val second = snapshot.on(LocalDate.of(2026, 11, 7))
assertEquals("Day 2 of 3", second.today!!.dayLabel)
assertEquals("Harbour", second.today!!.stops.single().name)
assertEquals(listOf("Train"), second.bookings.map { it.title })
// A day the app wrote nothing for (the trip is over) shows no day.
assertNull(snapshot.on(LocalDate.of(2026, 11, 9)).today)
}
@Test
fun keepsEveryStopOfTheDayItWasWrittenOn() {
val json = """{"trip":{"title":"T","start":"2026-11-06","end":"2026-11-07","path":"/trips/1"},
"today":{"date":"2026-11-06","dayLabel":"Day 1 of 2","stops":[
{"time":"09:00","name":"Museum","minutes":540},{"time":"21:00","name":"Concert","minutes":1260}]},
"days":[
{"date":"2026-11-06","dayLabel":"Day 1 of 2","stops":[{"time":"09:00","name":"Museum","minutes":540}]},
{"date":"2026-11-07","dayLabel":"Day 2 of 2","stops":[{"time":"10:00","name":"Harbour","minutes":600}]}
],
"labels":{}}"""
val snapshot = WidgetSnapshot.parse(json)!!
assertEquals(listOf("Museum", "Concert"), snapshot.on(LocalDate.of(2026, 11, 6)).today!!.stops.map { it.name })
assertEquals("Day 2 of 2", snapshot.on(LocalDate.of(2026, 11, 7)).today!!.dayLabel)
}
@Test
fun aSnapshotWithoutDaysReadsAsWritten() {
val snapshot = WidgetSnapshot.parse(WidgetSamples.json(running = true, now = today))!!
assertTrue(snapshot.days.isEmpty())
assertEquals(snapshot, snapshot.on(today.plusDays(3)))
}
}
+9
View File
@@ -117,6 +117,15 @@ so look at three or four pictures from a subset run before starting it.
each run rebuilds it under the servers of the others. Give each run its own
`TREK_PLUGINS_DIR` and `TREK_PLUGINS_DATA_DIR` as well (the seed installs a
plugin), and its own Vite `cacheDir` when it starts a Vite of its own.
- More than three or four runs at once: build the client once (`npm run build`)
and set `E2E_WEB_PREVIEW=1` as well, so each run serves `dist/` with
`vite preview` instead of a dev server of its own. A dozen dev servers compiling
the app at the same time take the whole machine, and the login of the setup
step times out after 45 s. The pictures do not change: the guides drive the
same app.
- A mocked outside service (a photo library, an AI provider) is answered with
`page.context().route`, not `page.route`: once the service worker of the built
app controls the page, its requests no longer pass a page route.
- A plugin installed by a run lives in `server/data/plugins/`; the dev server
imports it on its next restart. Guides that install one uninstall it in `cleanup`.
- The trip's last day is the run day by construction (`e2e/dates.ts`: every
+290 -78
View File
@@ -2,8 +2,9 @@ import { test, expect, type Page, type Locator } from '@playwright/test'
import { clearNotices } from '../screenshots/shot'
import { captureGuide, captureHero, dismissReleaseNotice, beat, typeInto, settle, VIEWPORT, type GuideScript } from './guide'
import { ensureAdminFixtures, pluginPackage } from './fixtures'
import { deleteUser, resetDefaults } from './fixtures-admin'
import { clearOidc, configureOidc, deleteUser, putAppSettings, resetDefaults } from './fixtures-admin'
import { toggleAddon } from './external'
import { mockInstanceConnection, AI_KEY } from './fixtures-assistant'
import { adminContext, adminTabContexts, adminGuides } from '../../src/help/contexts/admin'
import type { HelpGuide } from '../../src/help/types'
@@ -16,14 +17,15 @@ import type { HelpGuide } from '../../src/help/types'
const TAB_OF: Record<string, string> = {
'admin-users': 'Users',
'admin-defaults': 'User Defaults',
'admin-defaults': 'Defaults',
'admin-config': 'Personalization',
'admin-settings': 'Settings',
// One help screen for the two tabs the old Settings tab became; the hero shows Security.
'admin-settings': 'Security',
'admin-addons': 'Addons',
'admin-plugins': 'Plugins',
'admin-storage': 'Storage',
'admin-notifications': 'Notifications',
'admin-mcp-tokens': 'MCP Access',
'admin-mcp-tokens': 'MCP',
'admin-github': 'GitHub',
'admin-backup': 'Backup',
'admin-audit': 'Audit',
@@ -35,24 +37,30 @@ const guide = (id: string): HelpGuide => {
return g
}
const sidebar = (page: Page) => page.locator('nav').filter({ has: page.getByRole('button', { name: 'User Defaults' }) }).first()
const sidebar = (page: Page) => page.locator('nav').filter({ has: page.getByRole('button', { name: 'Personalization' }) }).first()
/** The nearest card around an element: the admin cards are rounded-xl or rounded-2xl boxes, or a <section>. */
const cardOf = (el: Locator) => el.locator('xpath=ancestor::*[contains(@class,"rounded-xl") or contains(@class,"rounded-2xl") or self::section][1]')
/** An admin card by the text of its h2. */
const section = (page: Page, title: string | RegExp) => cardOf(page.locator('h2').filter({ hasText: title }).first())
/** A provider block under Settings, a <section> headed by an h3. */
const block = (page: Page, title: string) => page.locator('h3').filter({ hasText: new RegExp(`^${title}$`) }).first().locator('xpath=ancestor::section[1]')
/** A block inside a card (a provider, a nested section), a <section> headed by an h3. */
const block = (page: Page, title: string) => page.locator('h3').filter({ hasText: new RegExp(`^${title.replace(/[()]/g, '\\$&')}$`) }).first().locator('xpath=ancestor::section[1]')
/** One settings row (label, hint, control) by its label. */
const row = (scope: Locator, label: string) =>
scope.locator('label').filter({ hasText: new RegExp(`^${label}$`) }).first()
.locator('xpath=ancestor::div[contains(@class,"px-4") and contains(@class,"py-3")][1]')
const modal = (page: Page) => page.locator('.trek-modal-backdrop').last()
const dialogPanel = (page: Page) => modal(page).locator('> [role="presentation"], > div').first()
/** A row of the user table by its username. */
const userRow = (page: Page, username: string) => page.locator('table tbody tr').filter({ hasText: username }).first()
/** A labelled field of the Map card on User Defaults: its label and everything under it. */
/** A labelled field of the Map card on Defaults: its label and everything under it. */
const mapField = (page: Page, label: string) => section(page, /^Map$/).locator('label').filter({ hasText: label }).first().locator('xpath=..')
/** The Map engine row's label, which also holds its reset link once the engine is set. */
const engineLabel = (page: Page) => section(page, /^Map$/).locator('label').filter({ hasText: 'Map engine' }).first()
/** The TREK Places API card at the top of API Keys, found by its pill. */
const trekApiCard = (page: Page) => page.getByText('Recommended default', { exact: true }).first().locator('xpath=ancestor::div[contains(@class,"rounded-[14px]")][1]')
/** An addon tile by the addon's name. */
/** The TREK API block at the top of Place search and routing, found by its pill. */
const trekApiCard = (page: Page) => page.getByText('Recommended default', { exact: true }).first().locator('xpath=ancestor::section[1]')
/** An addon row by the addon's name. */
const tile = (page: Page, name: string) => page.locator('h4').filter({ hasText: new RegExp(`^${name}$`) }).first().locator('xpath=ancestor::article[1]')
const authCard = (page: Page) => section(page, 'Authentication Methods')
async function openAdmin(page: Page, tab: string): Promise<void> {
await page.goto('/admin')
@@ -68,8 +76,29 @@ async function openAdmin(page: Page, tab: string): Promise<void> {
await settle(page)
}
const opener = (contextId: string) => (page: Page) => openAdmin(page, TAB_OF[contextId])
/**
* The release list comes from GitHub through the server, which gives up after
* eight seconds; a slow answer leaves "Failed to load releases" in the picture,
* so the tab is opened again until the list is there.
*/
async function openGithub(page: Page): Promise<void> {
for (let attempt = 0; attempt < 4; attempt++) {
await openAdmin(page, 'GitHub')
const details = section(page, 'Release History').getByRole('button', { name: 'Show details' }).first()
const failed = page.getByText('Failed to load releases', { exact: true })
await expect(details.or(failed).first()).toBeVisible({ timeout: 30_000 })
if (await details.isVisible()) return settle(page)
}
throw new Error('GitHub did not answer with the release list')
}
const opener = (contextId: string) => (page: Page) => contextId === 'admin-github' ? openGithub(page) : openAdmin(page, TAB_OF[contextId])
const services = (page: Page) => openAdmin(page, 'Services')
const only = (target: (p: Page) => Locator) => ({ target })
/** The AI tile's settings dialog, named by its title. */
const aiDialog = (page: Page) => page.getByRole('dialog').filter({ hasText: 'Set up AI' }).last()
/** The admin's AI settings as the run found them, put back after the AI guide. */
let aiSettingsBefore: unknown = null
const SCRIPTS: Record<string, GuideScript> = {
// ── Users ────────────────────────────────────────────────────────────────
@@ -92,7 +121,7 @@ const SCRIPTS: Record<string, GuideScript> = {
await typeInto(p, modal(p).getByPlaceholder('Password'), 'Lena12345!')
await beat(p, 300)
},
target: p => modal(p).locator('> [role="presentation"], > div').first(),
target: p => dialogPanel(p),
},
{
target: p => modal(p).getByRole('button', { name: 'Create User' }),
@@ -120,7 +149,7 @@ const SCRIPTS: Record<string, GuideScript> = {
},
},
{
target: p => modal(p).locator('> [role="presentation"], > div').first(),
target: p => dialogPanel(p),
act: async p => {
await modal(p).getByRole('button', { name: 'Cancel' }).click()
await expect(modal(p)).toHaveCount(0)
@@ -146,7 +175,7 @@ const SCRIPTS: Record<string, GuideScript> = {
await modal(p).getByRole('button', { name: '14d', exact: true }).click()
await beat(p, 300)
},
target: p => modal(p).locator('> [role="presentation"], > div').first(),
target: p => dialogPanel(p),
act: async p => {
await modal(p).getByRole('button', { name: 'Create & Copy' }).click()
await expect(modal(p)).toHaveCount(0)
@@ -169,14 +198,14 @@ const SCRIPTS: Record<string, GuideScript> = {
steps: [
{
prepare: async p => {
const row = section(p, 'Permission Settings').getByText('Delete trips', { exact: true }).locator('xpath=../..')
const permRow = row(section(p, 'Permission Settings'), 'Delete trips')
// The select's trigger is the row's only button; its options are buttons too.
await row.locator('button').first().click()
await permRow.locator('button').first().click()
await p.getByRole('button', { name: 'Admin only', exact: true }).last().click()
await expect(row.getByText('customized')).toBeVisible({ timeout: 10_000 })
await expect(permRow.getByText('customized')).toBeVisible({ timeout: 10_000 })
await settle(p)
},
target: p => section(p, 'Permission Settings').getByText('Delete trips', { exact: true }).locator('xpath=../..'),
target: p => row(section(p, 'Permission Settings'), 'Delete trips'),
},
{
target: p => section(p, 'Permission Settings').getByRole('button', { name: 'Save', exact: true }),
@@ -189,7 +218,7 @@ const SCRIPTS: Record<string, GuideScript> = {
],
},
// ── User Defaults ────────────────────────────────────────────────────────
// ── Defaults ─────────────────────────────────────────────────────────────
'default-user-settings': {
guide: guide('default-user-settings'),
start: opener('admin-defaults'),
@@ -203,7 +232,9 @@ const SCRIPTS: Record<string, GuideScript> = {
await expect(section(p, 'Default User Settings').locator('button').filter({ hasText: /^reset$/ })).toBeVisible({ timeout: 10_000 })
await settle(p)
},
target: p => section(p, 'Default User Settings').locator('label').filter({ hasText: 'Color Mode' }).locator('xpath=..'),
// The whole row: its name with the reset link, and the choice on the right.
target: p => section(p, 'Default User Settings').locator('label').filter({ hasText: 'Color Mode' }).first()
.locator('xpath=ancestor::div[contains(@class,"px-4") and contains(@class,"py-3")][1]'),
act: async p => {
await section(p, 'Default User Settings').locator('button').filter({ hasText: /^reset$/ }).first().click()
await expect(section(p, 'Default User Settings').locator('button').filter({ hasText: /^reset$/ })).toHaveCount(0, { timeout: 10_000 })
@@ -249,6 +280,7 @@ const SCRIPTS: Record<string, GuideScript> = {
// Typed, never committed: the field saves on blur only when the value changed,
// and emptying it first leaves the saved value (none) as it was.
steps: [
only(p => section(p, /^Routing$/)),
{
prepare: async p => {
await typeInto(p, p.getByLabel('Own routing engine', { exact: true }), 'https://osrm.example.org')
@@ -319,7 +351,7 @@ const SCRIPTS: Record<string, GuideScript> = {
await settle(p)
},
// The new category opens in a dialog, its name in the dialog's head.
target: p => modal(p).locator('> [role="presentation"], > div').first(),
target: p => dialogPanel(p),
act: async p => {
await modal(p).getByRole('button', { name: 'Cancel' }).click()
await expect(p.getByPlaceholder('Category name')).toHaveCount(0)
@@ -358,7 +390,7 @@ const SCRIPTS: Record<string, GuideScript> = {
await expect(modal(p).getByRole('textbox', { name: 'Holiday name' }).first()).toHaveValue('Autumn break', { timeout: 10_000 })
await settle(p)
},
target: p => modal(p).locator('> [role="presentation"], > div').first(),
target: p => dialogPanel(p),
act: async p => {
await modal(p).getByRole('button', { name: 'Cancel' }).click()
await expect(modal(p)).toHaveCount(0)
@@ -367,23 +399,29 @@ const SCRIPTS: Record<string, GuideScript> = {
],
},
// ── Settings ─────────────────────────────────────────────────────────────
// ── Security ─────────────────────────────────────────────────────────────
'auth-methods': {
guide: guide('auth-methods'),
start: opener('admin-settings'),
// The SSO rows exist only once OIDC is configured, so the guide sets an
// issuer and a client id up front and takes them away again afterwards.
start: async p => {
await configureOidc(p.request)
await openAdmin(p, 'Security')
await expect(row(authCard(p), 'SSO Login')).toBeVisible({ timeout: 10_000 })
},
steps: [
only(p => section(p, 'Authentication Methods').getByText('Password Login', { exact: true }).locator('xpath=../..')),
// The SSO rows exist only once OIDC is configured; the run shows where that happens.
only(p => section(p, 'Single Sign-On (OIDC)')),
only(p => section(p, 'Require 2FA')),
only(p => row(authCard(p), 'Password Login')),
only(p => row(authCard(p), 'SSO Auto-Provisioning')),
only(p => row(authCard(p), 'Require 2FA')),
],
cleanup: p => clearOidc(p.request),
},
'admin-passkeys': {
guide: guide('admin-passkeys'),
start: opener('admin-settings'),
steps: [
// Not flipped: the switch saves at once, and the seed keeps passkeys off.
only(p => section(p, 'Passkey login').getByRole('button', { name: 'Enable passkey login' }).locator('xpath=ancestor::div[contains(@class,"divide-y")][1]')),
only(p => row(authCard(p), 'Enable passkey login')),
only(p => section(p, 'Passkey login')),
],
},
@@ -391,41 +429,36 @@ const SCRIPTS: Record<string, GuideScript> = {
guide: guide('oidc'),
start: opener('admin-settings'),
steps: [
only(p => section(p, 'Single Sign-On (OIDC)')),
only(p => section(p, 'Authentication Methods')),
],
},
'instance-keys': {
guide: guide('instance-keys'),
start: opener('admin-settings'),
steps: [
only(p => trekApiCard(p)),
{
prepare: async p => {
const details = p.locator('details').filter({ hasText: 'What the key may be used for' })
if (!(await details.evaluate(el => (el as HTMLDetailsElement).open))) await details.locator('summary').click()
await settle(p)
const card = section(p, 'Single Sign-On (OIDC)')
await typeInto(p, card.locator('#oidc-display-name'), 'Authentik')
await typeInto(p, card.locator('#oidc-issuer'), 'https://auth.example.org/application/o/trek/')
await typeInto(p, card.locator('#oidc-client-id'), 'trek')
await typeInto(p, card.locator('#oidc-client-secret'), 'a-long-client-secret')
await beat(p, 300)
},
target: p => section(p, 'Single Sign-On (OIDC)'),
hover: async p => { await section(p, 'Single Sign-On (OIDC)').getByRole('button', { name: 'Save', exact: true }).hover() },
act: async p => {
await section(p, 'Single Sign-On (OIDC)').getByRole('button', { name: 'Save', exact: true }).click()
await expect.poll(async () => {
const res = await p.request.get('/api/admin/oidc')
return ((await res.json()) as { client_id?: string }).client_id
}, { timeout: 10_000 }).toBe('trek')
},
// The whole Google block: key, Test and the fold opened under it.
target: p => block(p, 'Google Maps API Key'),
},
only(p => block(p, 'Unsplash API Key')),
],
},
'places-transit': {
guide: guide('places-transit'),
start: opener('admin-settings'),
steps: [
only(p => block(p, 'Transit Provider')),
only(p => block(p, 'Place search provider')),
],
},
'file-types': {
guide: guide('file-types'),
start: opener('admin-settings'),
steps: [
only(p => section(p, 'Allowed File Types')),
{
// The card and the sign-in rows read the configuration when the page loads.
prepare: async p => {
await openAdmin(p, 'Security')
await expect(row(authCard(p), 'SSO Login')).toBeVisible({ timeout: 10_000 })
},
target: p => row(authCard(p), 'SSO Login'),
},
only(p => row(authCard(p), 'Go straight to SSO')),
],
cleanup: p => clearOidc(p.request),
},
'rotate-jwt-secret': {
guide: guide('rotate-jwt-secret'),
@@ -440,7 +473,7 @@ const SCRIPTS: Record<string, GuideScript> = {
},
},
{
target: p => modal(p).locator('> [role="presentation"], > div').first(),
target: p => dialogPanel(p),
// Never confirmed: rotating would sign the run itself out.
hover: async p => { await modal(p).getByRole('button', { name: 'Rotate & Log out' }).hover() },
act: async p => {
@@ -451,6 +484,33 @@ const SCRIPTS: Record<string, GuideScript> = {
],
},
// ── Services ─────────────────────────────────────────────────────────────
'instance-keys': {
guide: guide('instance-keys'),
start: services,
steps: [
only(p => trekApiCard(p)),
// The whole Google block: key, Test and what the key may be used for under it.
only(p => block(p, 'Google Maps API Key')),
only(p => block(p, 'Unsplash API Key')),
],
},
'places-transit': {
guide: guide('places-transit'),
start: services,
steps: [
only(p => block(p, 'Transit Provider')),
only(p => block(p, 'Place search provider')),
],
},
'file-types': {
guide: guide('file-types'),
start: services,
steps: [
only(p => section(p, 'Allowed File Types')),
],
},
// ── Addons ───────────────────────────────────────────────────────────────
'toggle-addon': {
guide: guide('toggle-addon'),
@@ -475,11 +535,12 @@ const SCRIPTS: Record<string, GuideScript> = {
guide: guide('document-providers'),
start: opener('admin-addons'),
steps: [
// The tile with its shelf: Documents is on in the seed, so the five rows are drawn.
// The row with its options: Documents is on in the seed, so the five stores are drawn.
only(p => tile(p, 'Documents')),
{
// The row's switch is a ToggleSwitch whose aria-label is the row's title.
target: p => tile(p, 'Documents').getByRole('button', { name: 'Nextcloud', exact: true }),
// The whole row, so its name is in the frame; the switch's aria-label is the row's title.
target: p => tile(p, 'Documents').getByRole('button', { name: 'Nextcloud', exact: true }).locator('xpath=ancestor::li[1]'),
hover: async p => { await tile(p, 'Documents').getByRole('button', { name: 'Nextcloud', exact: true }).hover() },
act: async p => {
const toggle = tile(p, 'Documents').getByRole('button', { name: 'Nextcloud', exact: true })
await toggle.click()
@@ -491,6 +552,157 @@ const SCRIPTS: Record<string, GuideScript> = {
// Back to the seed, where every store is off; the files run switches this one on for itself.
cleanup: p => toggleAddon(p.request, 'nextcloud', false),
},
'mail-import-setup': {
guide: guide('mail-import-setup'),
start: opener('admin-addons'),
steps: [
{
target: p => tile(p, 'Booking mail import'),
act: async p => {
const toggle = tile(p, 'Booking mail import').getByRole('button', { name: 'Import booking mails' })
await toggle.click()
await expect(toggle).toHaveAttribute('aria-pressed', 'true', { timeout: 10_000 })
await expect(p.getByRole('button', { name: 'Set up mail import' })).toBeVisible({ timeout: 10_000 })
await settle(p)
},
},
{
target: p => p.getByRole('button', { name: 'Set up mail import' }),
act: async p => {
await p.getByRole('button', { name: 'Set up mail import' }).click()
await expect(modal(p)).toBeVisible()
await settle(p)
},
},
{
// IMAP draws every field the step names; nothing is saved, so no mailbox is asked.
prepare: async p => {
await modal(p).getByRole('button', { name: 'Upload only' }).click()
await p.getByRole('button', { name: 'IMAP mailbox', exact: true }).last().click()
await expect(modal(p).locator('#mail-imap-host')).toBeVisible()
await typeInto(p, modal(p).locator('#mail-template'), 'trek+{token}@example.org')
await typeInto(p, modal(p).locator('#mail-imap-host'), 'imap.example.org')
await typeInto(p, modal(p).locator('#mail-imap-user'), 'trek@example.org')
await typeInto(p, modal(p).locator('#mail-imap-pass'), 'mailbox-password')
await beat(p, 300)
},
target: p => dialogPanel(p),
},
{
target: p => modal(p).getByRole('button', { name: 'Test connection' }).locator('xpath=..'),
hover: async p => { await modal(p).getByRole('button', { name: 'Save', exact: true }).hover() },
act: async p => {
await modal(p).getByRole('button', { name: 'Close', exact: true }).last().click()
// The setup asks before it drops what was typed.
await p.getByRole('button', { name: 'Discard', exact: true }).click()
await expect(modal(p)).toHaveCount(0)
},
},
],
cleanup: p => putAppSettings(p.request, { mail_ingest_enabled: false }),
},
'ai-setup': {
guide: guide('ai-setup'),
// The key is never tested against a provider: fixtures-assistant.ts answers for the connection.
start: async p => {
const res = await p.request.get('/api/admin/ai/settings')
aiSettingsBefore = res.ok() ? await res.json() : null
await toggleAddon(p.request, 'ai_assistant', false)
await mockInstanceConnection(p)
await openAdmin(p, TAB_OF['admin-addons'])
},
steps: [
{
target: p => tile(p, 'AI'),
act: async p => {
const toggle = tile(p, 'AI').getByRole('button', { name: 'AI Assistant', exact: true })
await toggle.click()
await expect(toggle).toHaveAttribute('aria-pressed', 'true', { timeout: 10_000 })
await expect(tile(p, 'AI').getByRole('button', { name: 'Set up AI' })).toBeVisible({ timeout: 10_000 })
await settle(p)
},
},
{
target: p => tile(p, 'AI').getByRole('button', { name: 'Set up AI' }),
act: async p => {
await tile(p, 'AI').getByRole('button', { name: 'Set up AI' }).click()
await expect(aiDialog(p).getByRole('radiogroup', { name: 'Who pays' })).toBeVisible({ timeout: 15_000 })
await settle(p)
},
},
{
target: p => aiDialog(p).getByRole('radiogroup', { name: 'Who pays' }).locator('xpath=..'),
hover: async p => { await aiDialog(p).getByRole('radio', { name: 'I pay, own allowed' }).hover() },
act: async p => {
await aiDialog(p).getByRole('radio', { name: 'I pay, own allowed' }).click()
await expect(aiDialog(p).getByRole('radio', { name: 'I pay, own allowed' })).toHaveAttribute('aria-checked', 'true')
await settle(p)
},
},
{
prepare: async p => {
await aiDialog(p).getByRole('button', { name: /^Paste an API key/ }).click()
await typeInto(p, aiDialog(p).getByPlaceholder('Paste your key here'), AI_KEY)
await expect(aiDialog(p).getByText('Detected: Anthropic')).toBeVisible()
await settle(p)
},
target: p => aiDialog(p).getByText('Connection for everyone', { exact: true }).locator('xpath=..'),
hover: async p => { await aiDialog(p).getByRole('button', { name: 'Connect', exact: true }).hover() },
act: async p => {
await aiDialog(p).getByRole('button', { name: 'Connect', exact: true }).click()
await expect(aiDialog(p).getByRole('button', { name: 'Remove connection' })).toBeVisible({ timeout: 15_000 })
await settle(p)
},
},
{
target: p => aiDialog(p).getByRole('button', { name: 'Remove connection' }).locator('xpath=ancestor::div[contains(@class,"p-3")][1]'),
act: async p => {
await aiDialog(p).getByRole('button', { name: 'AI Assistant', exact: true }).click()
await expect(aiDialog(p).getByText('Keep chats', { exact: true })).toBeVisible({ timeout: 10_000 })
await settle(p)
},
},
only(p => aiDialog(p).getByText('Keep chats', { exact: true }).locator('xpath=ancestor::div[contains(@class,"gap-4")][1]')),
],
cleanup: async p => {
if (aiSettingsBefore) await p.request.put('/api/admin/ai/settings', { data: aiSettingsBefore })
await toggleAddon(p.request, 'ai_assistant', false)
},
},
'paddle-water-data': {
guide: guide('paddle-water-data'),
start: opener('admin-addons'),
steps: [
{
target: p => p.getByRole('button', { name: /^Paddle water data/ }),
act: async p => {
await p.getByRole('button', { name: /^Paddle water data/ }).click()
await expect(modal(p)).toBeVisible()
await expect(modal(p).getByTestId('paddle-auto-load')).toBeVisible({ timeout: 15_000 })
await settle(p)
},
},
only(p => modal(p).getByTestId('paddle-auto-load')),
{
// A search shows the hits with their Add; Geofabrik's list comes through the server.
prepare: async p => {
const field = modal(p).getByPlaceholder('Search Geofabrik, for example Oberpfalz')
await typeInto(p, field, 'Oberpfalz')
const hit = modal(p).getByRole('button', { name: 'Add', exact: true }).first()
const failed = modal(p).getByRole('alert')
await expect(hit.or(failed).first()).toBeVisible({ timeout: 30_000 })
// Without Geofabrik the field stays empty rather than showing an error.
if (!(await hit.isVisible())) await field.fill('')
await settle(p)
},
target: p => modal(p).getByPlaceholder('Search Geofabrik, for example Oberpfalz').locator('xpath=ancestor::div[contains(@class,"gap-2")][1]'),
act: async p => {
await modal(p).getByRole('button', { name: 'Close', exact: true }).last().click()
await expect(modal(p)).toHaveCount(0)
},
},
],
},
// ── Plugins ──────────────────────────────────────────────────────────────
'install-plugin': {
@@ -518,9 +730,9 @@ const SCRIPTS: Record<string, GuideScript> = {
{
target: p => p.getByTestId('plugin-row-menu-btn-trip-doctor').locator('xpath=ancestor::div[contains(@class,"group") and contains(@class,"px-3.5")][1]'),
act: async p => {
const row = p.getByTestId('plugin-row-menu-btn-trip-doctor').locator('xpath=ancestor::div[contains(@class,"group") and contains(@class,"px-3.5")][1]')
await row.getByRole('button', { name: 'Enable plugin' }).click()
await expect(row.getByText('Active', { exact: true })).toBeVisible({ timeout: 30_000 })
const pluginRow = p.getByTestId('plugin-row-menu-btn-trip-doctor').locator('xpath=ancestor::div[contains(@class,"group") and contains(@class,"px-3.5")][1]')
await pluginRow.getByRole('button', { name: 'Enable plugin' }).click()
await expect(pluginRow.getByText('Active', { exact: true })).toBeVisible({ timeout: 30_000 })
await settle(p)
},
},
@@ -555,7 +767,7 @@ const SCRIPTS: Record<string, GuideScript> = {
await settle(p)
},
// The new backend opens in a dialog.
target: p => modal(p).locator('> [role="presentation"], > div').first(),
target: p => dialogPanel(p),
act: async p => {
await modal(p).getByRole('button', { name: 'Cancel' }).click()
await expect(modal(p).getByText('Add backend', { exact: true })).toHaveCount(0)
@@ -573,19 +785,19 @@ const SCRIPTS: Record<string, GuideScript> = {
guide: guide('channels-instance'),
start: opener('admin-notifications'),
steps: [
only(p => section(p, 'Email (SMTP)')),
only(p => section(p, /^Ntfy$/)),
only(p => section(p, 'Trip Reminders')),
only(p => block(p, 'Email (SMTP)')),
only(p => section(p, /^Channels$/).locator('div.divide-y').first()),
only(p => row(section(p, /^Channels$/), 'Trip Reminders')),
],
},
'admin-channels': {
guide: guide('admin-channels'),
start: opener('admin-notifications'),
steps: [
only(p => section(p, 'Admin Ntfy')),
only(p => section(p, 'Admin Ntfy').getByRole('button', { name: 'Send test ntfy' })),
// The admin matrix: the card whose title is the tab's own name.
only(p => section(p, /^Notifications$/)),
only(p => section(p, 'Admin alerts')),
only(p => block(p, 'Admin Ntfy').getByRole('button', { name: 'Send test ntfy' })),
// The admin matrix at the foot of the same card.
only(p => section(p, 'Admin alerts').locator('div.overflow-x-auto').first()),
],
},
'notification-defaults': {
@@ -598,7 +810,7 @@ const SCRIPTS: Record<string, GuideScript> = {
],
},
// ── MCP Access ───────────────────────────────────────────────────────────
// ── MCP ──────────────────────────────────────────────────────────────────
'mcp-tokens-admin': {
guide: guide('mcp-tokens-admin'),
start: opener('admin-mcp-tokens'),
@@ -660,11 +872,11 @@ const SCRIPTS: Record<string, GuideScript> = {
target: p => section(p, 'Auto-Backup').getByRole('button', { name: /^Enable auto-backup/ }).locator('xpath=ancestor::label[1]'),
act: async p => {
await section(p, 'Auto-Backup').getByRole('button', { name: /^Enable auto-backup/ }).click()
await expect(section(p, 'Auto-Backup').getByText('Interval', { exact: true })).toBeVisible({ timeout: 10_000 })
await expect(section(p, 'Auto-Backup').getByText('Interval', { exact: true }).first()).toBeVisible({ timeout: 10_000 })
await settle(p)
},
},
only(p => section(p, 'Auto-Backup').getByText('Delete old backups after', { exact: true }).locator('xpath=..')),
only(p => row(section(p, 'Auto-Backup'), 'Delete old backups after')),
],
cleanup: async p => {
await section(p, 'Auto-Backup').getByRole('button', { name: /^Enable auto-backup/ }).click()
+26 -6
View File
@@ -236,6 +236,13 @@ async function excludedTours(page: Page): Promise<Set<number>> {
/** What was left out before the tour guide ran, so `cleanup` counts exactly its own change again. */
let excludedBefore = new Set<number>()
/** Why the Dawarich connection could not be made in `beforeAll`, if it could not. */
let dawarichMissing: Error | null = null
async function openAtlasWithDawarich(page: Page): Promise<void> {
if (dawarichMissing) throw dawarichMissing
await openAtlas(page)
}
const SCRIPTS: Record<string, GuideScript> = {
'mark-country': {
guide: guide('mark-country'),
@@ -364,6 +371,9 @@ const SCRIPTS: Record<string, GuideScript> = {
await expect(detailCard(p, 'Portugal')).toBeVisible()
},
target: p => detailCard(p, 'Portugal'),
// On the name with its Planned label: the centre of the card is the
// Places badge, whose tooltip covered the trip chip under it.
hover: p => panel(p).locator('p.text-sm.font-bold').filter({ hasText: 'Portugal' }).hover(),
},
],
},
@@ -607,7 +617,9 @@ const SCRIPTS: Record<string, GuideScript> = {
// The side column: the Planned and Recorded badges, what does not
// count yet, and the i whose tooltip states the rule.
target: p => showToursButton(p).locator('xpath=..'),
hover: p => tourPane(p).getByRole('button', { name: 'My tour activities', exact: true }).hover(),
// On Still ahead, whose tooltip is one short line. The i's tooltip is the
// whole rule in one wide line, and it covered the badges the step names.
hover: p => tourPane(p).getByText('Still ahead', { exact: true }).hover(),
},
{
target: showToursButton,
@@ -619,7 +631,9 @@ const SCRIPTS: Record<string, GuideScript> = {
},
{
target: p => firstTourRow(p),
hover: p => firstTourRow(p).locator('[data-testid^="tour-activity-toggle-"]').hover(),
// On the tour's name, which has no tooltip: the button's own tooltip ran
// past the frame's edge and over the row below.
hover: p => firstTourRow(p).locator('span.font-semibold').first().hover(),
act: async p => {
// Found again by its own id afterwards: the list may sort a left-out tour elsewhere.
const id = await firstTourRow(p).getAttribute('data-testid')
@@ -644,7 +658,7 @@ const SCRIPTS: Record<string, GuideScript> = {
'dawarich-countries': {
guide: guide('dawarich-countries'),
start: async p => {
await openAtlas(p)
await openAtlasWithDawarich(p)
visitedBefore = await visitedCodes(p)
},
steps: [
@@ -708,7 +722,7 @@ const SCRIPTS: Record<string, GuideScript> = {
'dawarich-wishes': {
guide: guide('dawarich-wishes'),
start: openAtlas,
start: openAtlasWithDawarich,
steps: [
{
target: p => tile(p, 'Wishlist'),
@@ -773,8 +787,14 @@ test.beforeAll(async ({ request }) => {
const { ensureToursFixtures } = await import('./tour-fixtures')
await ensureToursFixtures(request)
// After the Atlas fixtures: the connection adds two wishes with coordinates
// (Fushimi Inari Taisha, Wadi Rum) to the list the fixtures create.
await ensureDawarichConnection(request)
// (Fushimi Inari Taisha, Wadi Rum) to the list the fixtures create. Without
// media.env it cannot be made; the two Dawarich guides then fail at their
// start with the reason, and every other guide of the file still runs.
try {
await ensureDawarichConnection(request)
} catch (err) {
dawarichMissing = err instanceof Error ? err : new Error(String(err))
}
})
test.afterAll(async ({ request }) => {
+29
View File
@@ -862,6 +862,35 @@ const SCRIPTS: Record<string, GuideScript> = {
],
},
'collection-map-lock': {
guide: guide('collection-map-lock'),
start: p => openList(p, KYOTO),
steps: [
{
target: p => mapShell(p).getByTestId('map-lock-pill'),
act: async p => {
await mapShell(p).getByTestId('map-lock-pill').click()
await expect(mapShell(p).getByRole('button', { name: 'Let the map follow the selection' })).toBeVisible()
await blurFocus(p)
await settle(p)
},
},
{
target: p => placeRows(p).nth(1),
act: async p => {
await placeRows(p).nth(1).click()
await expect(detail(p)).toBeVisible()
// Locked, the map keeps the frame of the whole list, so every pin stays in view.
await pageReady(p)
},
},
],
cleanup: async p => {
const unlock = mapShell(p).getByRole('button', { name: 'Let the map follow the selection' })
if (await unlock.count()) await unlock.click()
},
},
'tour-collection-add-to-trip': {
guide: guide('tour-collection-add-to-trip'),
start: async p => {
+23 -2
View File
@@ -468,6 +468,24 @@ const SCRIPTS: Record<string, GuideScript> = {
],
},
'travel-stats': {
guide: guide('travel-stats'),
start: async p => {
await openDashboard(p)
// The flags load from flagcdn; wait for them so the card is not half drawn.
await expect(p.locator('.atlas-card.passport .passport-flags img').first()).toBeVisible({ timeout: 15_000 })
await settle(p)
},
steps: [
{
target: p => p.locator('.atlas-card.passport'),
},
{
target: p => p.locator('section.atlas'),
},
],
},
widgets: {
guide: guide('widgets'),
start: openDashboard,
@@ -497,8 +515,11 @@ const SCRIPTS: Record<string, GuideScript> = {
await p.getByText('Dashboard widgets', { exact: true }).first().scrollIntoViewIfNeeded()
await beat(p, 400)
},
// The Section card itself: the nearest rounded container around its heading.
target: p => p.getByText('Dashboard widgets', { exact: true }).first().locator('xpath=ancestor::section[1]'),
// The Desktop block of the card (its groups and the Right sidebar switch). The
// whole card with its Mobile half is taller than the frame, and the settings
// pane scrolls on its own, so its top ended up under the navigation bar.
target: p => p.getByText('Dashboard widgets', { exact: true }).first().locator('xpath=ancestor::section[1]')
.getByText('Desktop', { exact: true }).locator('xpath=ancestor::section[1]'),
},
{
target: p => p.getByRole('link', { name: 'My Trips' }),
+31
View File
@@ -27,3 +27,34 @@ export async function resetDefaults(api: APIRequestContext, keys: string[]): Pro
if (!res.ok()) throw new Error(`could not reset the default "${key}": ${res.status()} ${await res.text()}`);
}
}
/** Writes instance settings the way the admin page does (PUT /api/auth/app-settings). */
export async function putAppSettings(api: APIRequestContext, patch: Record<string, string | boolean>): Promise<void> {
const res = await api.put('/api/auth/app-settings', { data: patch });
if (!res.ok()) throw new Error(`could not save the app settings: ${res.status()} ${await res.text()}`);
}
const OIDC_EMPTY = { issuer: '', client_id: '', client_secret: '', display_name: '', discovery_url: '' };
/**
* An issuer and a client id, which is all TREK needs to call OIDC configured and
* draw the SSO rows. Nothing is fetched from the issuer on save.
*/
export async function configureOidc(api: APIRequestContext): Promise<void> {
const res = await api.put('/api/admin/oidc', {
data: {
...OIDC_EMPTY,
issuer: 'https://auth.example.org/application/o/trek/',
client_id: 'trek',
client_secret: 'a-long-client-secret',
display_name: 'Authentik',
},
});
if (!res.ok()) throw new Error(`could not configure OIDC: ${res.status()} ${await res.text()}`);
}
/** Back to the seed, where no identity provider is set. Password login is on there, so the server allows it. */
export async function clearOidc(api: APIRequestContext): Promise<void> {
const res = await api.put('/api/admin/oidc', { data: OIDC_EMPTY });
if (!res.ok()) throw new Error(`could not clear OIDC: ${res.status()} ${await res.text()}`);
}
+410
View File
@@ -0,0 +1,410 @@
import type { APIRequestContext, Page, Route } from '@playwright/test';
import { toggleAddon } from './external';
import { seededTrip } from './fixtures';
import { PICTURE_DAY } from './guide';
/**
* What the AI guides need: an AI provider that answers. The run has none and
* must not depend on one, so the browser's side of the conversation is
* answered here instead, with `page.context().route` (a route on the page
* alone misses what the PWA's service worker fetches, see the Immich mock in
* `journey.guide.ts`):
*
* - `/api/ai/status`: whether the assistant runs and on whose connection,
* - `/api/ai/connection` and `/api/ai/models`: a person's own key, taken as good,
* - `/api/admin/ai/connection` and `/api/admin/ai/models`: the admin's,
* - `/api/trips/:id/assistant/...`: the chat, its decisions and sharing.
*
* What the provider would write is fixed below, short and in the shape the
* server streams it (`uiStreamChunkSchema`). What a decision changes in the
* trip is done for real through the REST API, so the plan behind the window
* shows the new place the way it would after a real Apply, and the answer
* shared to the trip chat is a real chat message. Cleanup takes both away.
*
* Only the addons are switched for real (the AI tile and the Integrations card
* show by them); the admin's AI settings are the server's own.
*/
const PROVIDER = { kind: 'anthropic', host: 'api.anthropic.com' } as const;
const MODEL = 'claude-sonnet-4-5';
export const AI_KEY = 'sk-ant-api03-hm7Rk2vLq9Tz4Wc8Yp1Nd6Fs3Bx5Gj0Ue-x7Qa';
const HINT = '…x7Qa';
const MODELS = {
models: [
{ id: MODEL, label: 'Claude Sonnet 4.5', supportsTools: true, recommended: true },
{ id: 'claude-haiku-4-5', label: 'Claude Haiku 4.5', supportsTools: true },
{ id: 'claude-opus-4-1', label: 'Claude Opus 4.1', supportsTools: true },
],
};
const RETENTION = { mode: 'days', days: 90 } as const;
/** The assistant on the admin's connection, as everyone on the instance sees it. */
function instanceStatus() {
return {
available: true,
policy: 'instance_or_user',
canConnectOwn: true,
effective: { source: 'instance', kind: PROVIDER.kind, model: MODEL, host: PROVIDER.host, paidBy: 'instance' },
own: null,
instance: { kind: PROVIDER.kind, model: MODEL, host: PROVIDER.host },
quota: { used: 3, limit: 50 },
privacyAcked: true,
retention: RETENTION,
openrouterOAuth: false,
};
}
/** Everyone brings their own: nothing yet, or the key the guide connected. */
function ownStatus(connected: boolean) {
const own = { scope: 'user', kind: PROVIDER.kind, model: MODEL, hint: HINT, status: 'ok', host: PROVIDER.host };
return {
available: connected,
policy: 'user',
canConnectOwn: true,
effective: connected
? { source: 'user', kind: PROVIDER.kind, model: MODEL, host: PROVIDER.host, paidBy: 'user' }
: null,
own: connected ? own : null,
instance: null,
quota: null,
privacyAcked: connected,
retention: RETENTION,
openrouterOAuth: false,
};
}
/** A server-sent event stream as the server writes it: one `data:` per chunk, closed by [DONE]. */
function sse(chunks: unknown[]): string {
return [...chunks.map((c) => `data: ${JSON.stringify(c)}\n\n`), 'data: [DONE]\n\n'].join('');
}
const fulfillStream = (route: Route, chunks: unknown[]) =>
route.fulfill({
status: 200,
contentType: 'text/event-stream',
headers: { 'cache-control': 'no-cache' },
body: sse(chunks),
});
const pathOf = (route: Route) => new URL(route.request().url()).pathname;
// ── Settings: a person's own key ─────────────────────────────────────────────
/** Settings, Integrations: the AI card with nothing connected, and a key that connects. */
export async function mockOwnConnection(page: Page): Promise<void> {
await toggleAddon(page.request, 'ai_assistant', true);
let connected = false;
await page.context().route(/\/api\/ai\/(status|connection|models|privacy-ack)(\/.*)?(\?.*)?$/, async (route) => {
const path = pathOf(route);
const method = route.request().method();
if (path.endsWith('/ai/status')) return route.fulfill({ json: ownStatus(connected) });
if (path.endsWith('/ai/models')) return route.fulfill({ json: MODELS });
if (path.endsWith('/ai/privacy-ack')) return route.fulfill({ json: { success: true } });
if (path.endsWith('/ai/connection') && method === 'PUT') {
connected = true;
return route.fulfill({ json: ownStatus(true).own });
}
if (path.endsWith('/ai/connection') && method === 'DELETE') {
connected = false;
return route.fulfill({ json: { success: true } });
}
return route.fallback();
});
}
export async function resetOwnConnection(api: APIRequestContext): Promise<void> {
await toggleAddon(api, 'ai_assistant', false);
}
// ── Admin: the connection for everyone ──────────────────────────────────────
/** Admin, Addons: the AI dialog with no connection for everyone yet, and a key that connects. */
export async function mockInstanceConnection(page: Page): Promise<void> {
let connected = false;
const view = () => ({
connection: connected
? {
scope: 'instance',
kind: PROVIDER.kind,
model: MODEL,
hint: HINT,
status: 'ok',
host: PROVIDER.host,
baseUrl: null,
}
: null,
prefill: null,
});
await page.context().route(/\/api\/admin\/ai\/(connection|models)(\/.*)?(\?.*)?$/, async (route) => {
const path = pathOf(route);
const method = route.request().method();
if (path.endsWith('/admin/ai/models')) return route.fulfill({ json: MODELS });
if (method === 'PUT') connected = true;
if (method === 'DELETE') {
connected = false;
return route.fulfill({ json: { success: true } });
}
return route.fulfill({ json: view() });
});
}
// ── Trip: the chat ───────────────────────────────────────────────────────────
/** What the guide asks, and the place the answer suggests for day 1. */
export const QUESTION = 'Where should we have dinner near Senso-ji on day 1?';
export const SUGGESTED = {
name: 'Asakusa Imahan',
address: '3-1-12 Nishiasakusa, Taito City, Tokyo',
lat: 35.7127,
lng: 139.7905,
notes: 'Sukiyaki dinner, around 19:00. Book a table a day ahead.',
// Its own front on Kokusai-dori (Wikimedia Commons, CC0); the lookup by position found a car park nearby.
image:
'https://thumb.wikimedia.org/wikipedia/commons/thumb/8/86/Asakusa_Imahan_Kokusai-dori_main_branch.jpg/960px-Asakusa_Imahan_Kokusai-dori_main_branch.jpg',
};
const THREAD = { id: 901, title: 'Dinner near Senso-ji' };
const MESSAGE_ID = 'msg-9002';
const QUESTION_ID = 'msg-9001';
const CALL_ID = 'call-help-imahan-0001';
const ANSWER =
'**Asakusa Imahan** is a good fit: a sukiyaki restaurant known for its wagyu, a short walk from Senso-ji. ' +
'Your day ends at teamLab Planets at 16:00, so a table at 19:00 leaves time to get back to Asakusa.\n\n' +
'It fills up in the evening, so book a day ahead. Shall I put it on day 1?';
const FOLLOW_UPS = [
'What else is near Senso-ji?',
'Is day 1 too packed now?',
'Where can we have breakfast in Asakusa?',
];
/** What the mock made for real, so cleanup can take it away again. */
export interface AssistantRun {
placeIds: number[];
chatMessageIds: number[];
}
const listIn = <T>(body: unknown, key: string): T[] =>
Array.isArray(body) ? (body as T[]) : (((body as Record<string, unknown>)?.[key] as T[] | undefined) ?? []);
/** A day as the change card names it: its date the way the server writes it in English. */
function dayLabel(date: string | null | undefined, number: number): string {
if (!date) return `Day ${number}`;
return new Intl.DateTimeFormat('en', { weekday: 'short', day: 'numeric', month: 'short', timeZone: 'UTC' }).format(
new Date(`${date.slice(0, 10)}T00:00:00Z`)
);
}
/**
* The trip's assistant: switched on, answering on the admin's connection, with
* one turn that suggests dinner on day 1 and holds it as a change to apply.
*/
export async function mockTripAssistant(page: Page): Promise<AssistantRun> {
const run: AssistantRun = { placeIds: [], chatMessageIds: [] };
const api = page.request;
const { tripId, dayIds } = seededTrip();
await toggleAddon(api, 'ai_assistant', true);
const days = listIn<{ id: number; date?: string | null }>(
await (await api.get(`/api/trips/${tripId}/days`)).json(),
'days'
);
const dayId = dayIds[0];
const day = days.find((d) => d.id === dayId);
const categories = listIn<{ id: number; name: string }>(
await (await api.get('/api/categories')).json(),
'categories'
);
const category = categories.find((c) => /restaurant|food/i.test(c.name)) ?? null;
const args = {
dayId,
name: SUGGESTED.name,
address: SUGGESTED.address,
lat: SUGGESTED.lat,
lng: SUGGESTED.lng,
...(category ? { category_id: category.id } : {}),
place_notes: SUGGESTED.notes,
};
const rows = [
{ op: 'add', labelKey: 'day', before: null, after: dayLabel(day?.date, 1) },
{ op: 'add', labelKey: 'address', before: null, after: SUGGESTED.address },
...(category ? [{ op: 'add', labelKey: 'category', before: null, after: category.name }] : []),
{ op: 'add', labelKey: 'notes', before: null, after: SUGGESTED.notes },
];
const preview = {
toolCallId: CALL_ID,
verbKey: 'addPlaceToDay',
subject: SUGGESTED.name,
rows,
dayId,
placeIds: [],
undoable: true,
effect: {
kind: 'add',
dayId,
fromDayId: null,
placeId: null,
assignmentId: null,
place: { name: SUGGESTED.name, lat: SUGGESTED.lat, lng: SUGGESTED.lng, categoryId: category?.id ?? null },
},
};
const createdAt = PICTURE_DAY.toISOString();
const question = {
id: QUESTION_ID,
role: 'user',
status: 'complete',
createdAt,
parts: [{ type: 'text', text: QUESTION }],
};
const answer: { id: string; role: string; status: string; createdAt: string; parts: Record<string, unknown>[] } = {
id: MESSAGE_ID,
role: 'assistant',
status: 'awaiting_approval',
createdAt,
parts: [
{ type: 'text', text: ANSWER },
{ type: 'tool-call', toolCallId: CALL_ID, toolName: 'create_and_assign_place', args, approval: { id: CALL_ID } },
{ type: 'data-trek-change', data: preview },
{ type: 'data-trek-follow-ups', data: { questions: FOLLOW_UPS } },
],
};
let asked = false;
const turn = [
{ type: 'start', messageId: MESSAGE_ID },
{ type: 'data-trek-thread', data: { threadId: THREAD.id, title: THREAD.title } },
{ type: 'start-step' },
{ type: 'text-start', id: 'text-1' },
{ type: 'text-delta', id: 'text-1', delta: ANSWER },
{ type: 'text-end', id: 'text-1' },
{ type: 'tool-input-start', toolCallId: CALL_ID, toolName: 'create_and_assign_place' },
{ type: 'tool-input-available', toolCallId: CALL_ID, toolName: 'create_and_assign_place', input: args },
{ type: 'data-trek-change', data: preview },
{ type: 'tool-approval-request', approvalId: CALL_ID, toolCallId: CALL_ID },
{ type: 'finish-step' },
{ type: 'data-trek-follow-ups', data: { questions: FOLLOW_UPS } },
{ type: 'data-trek-quota', data: { used: 4, limit: 50 } },
{ type: 'finish', finishReason: 'tool-calls' },
];
/** Apply: the place made and planned for real, then the receipt the server would stream. */
async function apply(): Promise<unknown[]> {
const placeRes = await api.post(`/api/trips/${tripId}/places`, {
data: {
name: SUGGESTED.name,
address: SUGGESTED.address,
lat: SUGGESTED.lat,
lng: SUGGESTED.lng,
notes: SUGGESTED.notes,
image_url: SUGGESTED.image,
...(category ? { category_id: category.id } : {}),
},
});
if (!placeRes.ok())
throw new Error(`could not create ${SUGGESTED.name}: ${placeRes.status()} ${await placeRes.text()}`);
const placeBody = (await placeRes.json()) as { place?: { id: number }; id?: number };
const placeId = placeBody.place?.id ?? placeBody.id;
if (typeof placeId !== 'number') throw new Error('the new place came back without an id');
run.placeIds.push(placeId);
const assigned = await api.post(`/api/trips/${tripId}/days/${dayId}/assignments`, { data: { place_id: placeId } });
if (!assigned.ok())
throw new Error(`could not plan ${SUGGESTED.name}: ${assigned.status()} ${await assigned.text()}`);
const applied = {
toolCallId: CALL_ID,
entity: 'place',
ids: [placeId],
dayId,
undoUntil: new Date(PICTURE_DAY.getTime() + 2 * 3600_000).toISOString(),
};
answer.status = 'complete';
answer.parts = answer.parts.map((p) =>
p.type === 'tool-call'
? { ...p, result: { place: { id: placeId } }, isError: false, approval: { id: CALL_ID, approved: true } }
: p
);
answer.parts.push({ type: 'data-trek-applied', data: applied });
return [
{ type: 'start', messageId: MESSAGE_ID },
{ type: 'tool-output-available', toolCallId: CALL_ID, output: { place: { id: placeId } } },
{ type: 'data-trek-applied', data: applied },
{ type: 'finish', finishReason: 'stop' },
];
}
await page
.context()
.route(/\/api\/ai\/(status|privacy-ack)(\?.*)?$/, (route) =>
pathOf(route).endsWith('/status')
? route.fulfill({ json: instanceStatus() })
: route.fulfill({ json: { success: true } })
);
await page.context().route(new RegExp(`/api/trips/${tripId}/assistant/`), async (route) => {
const path = pathOf(route).replace(`/api/trips/${tripId}/assistant`, '');
const method = route.request().method();
if (path === '/threads' && method === 'GET') {
return route.fulfill({
json: { threads: asked ? [{ id: THREAD.id, title: THREAD.title, lastMessageAt: createdAt }] : [] },
});
}
if (path === `/threads/${THREAD.id}` && method === 'GET') {
return route.fulfill({
json: {
thread: { id: THREAD.id, title: THREAD.title, lastMessageAt: createdAt },
messages: [question, answer],
},
});
}
if (path === '/chat' && method === 'POST') {
asked = true;
return fulfillStream(route, turn);
}
if (path === `/threads/${THREAD.id}/decisions` && method === 'POST') {
const body = route.request().postDataJSON() as { decisions?: { toolCallId: string; approved: boolean }[] };
const approved = body.decisions?.find((d) => d.toolCallId === CALL_ID)?.approved;
if (!approved) {
answer.status = 'complete';
return fulfillStream(route, [
{ type: 'start', messageId: MESSAGE_ID },
{ type: 'tool-output-denied', toolCallId: CALL_ID },
{ type: 'finish', finishReason: 'stop' },
]);
}
return fulfillStream(route, await apply());
}
if (path.startsWith(`/threads/${THREAD.id}/messages/`) && path.endsWith('/share') && method === 'POST') {
// A real message in the trip chat, so the chat shows what was shared.
const { text } = route.request().postDataJSON() as { text: string };
const posted = await api.post(`/api/trips/${tripId}/collab/messages`, { data: { text } });
const json = (await posted.json()) as { message?: { id: number } };
if (json.message?.id) run.chatMessageIds.push(json.message.id);
return route.fulfill({ status: posted.status(), json });
}
if (path === '/stop') return route.fulfill({ json: { success: true } });
if (path.startsWith('/tool-calls/') && path.endsWith('/undo')) {
for (const id of run.placeIds.splice(0)) await api.delete(`/api/trips/${tripId}/places/${id}`);
return route.fulfill({ json: { undone: true } });
}
return route.fulfill({ status: 404, json: { error: 'not mocked' } });
});
return run;
}
/** Take away what the chat made, and switch the assistant off again. */
export async function resetTripAssistant(api: APIRequestContext, run: AssistantRun | null): Promise<void> {
const { tripId } = seededTrip();
for (const id of run?.chatMessageIds ?? []) await api.delete(`/api/trips/${tripId}/collab/messages/${id}`);
// By name as well: a run that stopped between the create and the receipt left one the list does not know.
const places = listIn<{ id: number; name: string }>(
await (await api.get(`/api/trips/${tripId}/places`)).json(),
'places'
);
for (const place of places.filter((p) => p.name === SUGGESTED.name)) {
await api.delete(`/api/trips/${tripId}/places/${place.id}`);
}
await toggleAddon(api, 'ai_assistant', false);
}
+111
View File
@@ -1,4 +1,6 @@
import type { APIRequestContext } from '@playwright/test';
import { createHmac } from 'node:crypto';
import { day, mailHeaderDate } from '../dates';
import { seededTrip } from './fixtures';
import { asMember, PARTNER } from './fixtures-vacay';
@@ -156,3 +158,112 @@ export async function removeNotificationFixtures(api: APIRequestContext): Promis
if (ours) await api.delete(`${INBOX}/${n.id}`);
}
}
// ── Booking mails ─────────────────────────────────────────────────────────────
/** The notice a mail whose booking waits for the reader leaves under the bell. */
export const MAIL_PENDING_TITLE = 'Forwarded bookings to review';
const MAIL_PENDING_KEY = 'notif.mail_booking_pending.title';
/** The media run's own webhook key; a mail service signs with the admin's. */
const WEBHOOK_SECRET = 'help-media-webhook-secret-for-the-notifications';
/** The forwarded mail, as Pending bookings lists it. */
export const MAIL_SUBJECT = 'Your ryokan in Hakone';
async function putAppSettings(api: APIRequestContext, data: Record<string, string | boolean>): Promise<void> {
await ok(await api.put('/api/auth/app-settings', { data }), 'could not save the mail import settings');
}
/**
* The mail import on, the way an admin switches it on, with the signed webhook
* as its transport so the fixture can deliver a mail itself, and the admin's
* own Read with AI off: no model answers in the media run and no extractor is
* needed, so the mail waits in Pending bookings and TREK sends the "Forwarded
* bookings to review" notice, which is what the guide shows. Then a plain text
* confirmation goes to the Japan trip's address, and the fixture waits for
* the notice.
*/
export async function ensureMailPendingNotice(api: APIRequestContext): Promise<void> {
await putAppSettings(api, {
mail_ingest_enabled: true,
mail_ingest_transport: 'webhook',
mail_ingest_address_template: 'trips+{token}@example.com',
mail_ingest_webhook_secret: WEBHOOK_SECRET,
});
await ok(
await api.patch('/api/mail-ingest/settings', { data: { ai_enabled: false } }),
'could not turn Read with AI off'
);
const { tripId } = seededTrip();
let found = (await (await api.get(`/api/trips/${tripId}/mail-ingest/address`)).json()) as {
address: { address: string } | null;
};
if (!found.address) {
await ok(
await api.post(`/api/trips/${tripId}/mail-ingest/address`, { data: {} }),
'could not create the trip address'
);
found = (await (await api.get(`/api/trips/${tripId}/mail-ingest/address`)).json()) as typeof found;
}
const to = found.address?.address;
if (!to) throw new Error('the trip has no mail address');
const raw = Buffer.from(
[
'From: Hakone Ginyu <stay@ginyu.example>',
`To: ${to}`,
`Subject: ${MAIL_SUBJECT}`,
`Date: ${mailHeaderDate(-28, '09:12', '+0900')}`,
'Message-ID: <gny-40218@ginyu.example>',
'MIME-Version: 1.0',
'Content-Type: text/plain; charset=utf-8',
'',
'Dear guest,',
'',
'thank you for choosing Hakone Ginyu. Your room with a private open-air bath is reserved.',
'',
`Check-in: ${day(-6)}, from 15:00`,
`Check-out: ${day(-5)}, until 11:00`,
'Guests: 2',
'Confirmation number: GNY-40218',
'',
'Hakone Ginyu, 100-1 Miyanoshita, Hakone, Kanagawa',
'',
].join('\r\n')
);
const timestamp = String(Math.floor(Date.now() / 1000));
const signature = createHmac('sha256', WEBHOOK_SECRET).update(`${timestamp}\n${to}\n`).update(raw).digest('hex');
await ok(
await api.post('/api/mail-ingest/inbound', {
headers: {
'Content-Type': 'message/rfc822',
'X-Trek-Timestamp': timestamp,
'X-Trek-Recipient': to,
'X-Trek-Signature': `sha256=${signature}`,
},
data: raw,
}),
'the webhook refused the mail'
);
for (let i = 0; i < 90; i++) {
if ((await inbox(api)).some((n) => n.title_key === MAIL_PENDING_KEY && !n.is_read)) return;
await new Promise((res) => setTimeout(res, 1000));
}
throw new Error('no "Forwarded bookings to review" notification arrived');
}
/** Back to the seed: the waiting entry, the trip address, the notice and the import itself go. */
export async function removeMailPendingNotice(api: APIRequestContext): Promise<void> {
const open = await api.get('/api/mail-ingest/inbox?status=open');
if (open.ok()) {
const { entries = [] } = (await open.json()) as { entries?: { id: number }[] };
for (const entry of entries) await api.post(`/api/mail-ingest/candidates/${entry.id}/discard`, { data: {} });
}
const { tripId } = seededTrip();
await api.delete(`/api/trips/${tripId}/mail-ingest/address`);
await api.patch('/api/mail-ingest/settings', { data: { ai_enabled: true } });
for (const n of await inbox(api)) if (n.title_key === MAIL_PENDING_KEY) await api.delete(`${INBOX}/${n.id}`);
await putAppSettings(api, {
mail_ingest_enabled: false,
mail_ingest_transport: 'off',
mail_ingest_webhook_secret: '',
});
}
+89 -3
View File
@@ -1,4 +1,6 @@
import type { APIRequestContext } from '@playwright/test';
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
import path from 'node:path';
import { ensureDawarichConnection, toggleAddon } from './external';
/**
@@ -52,9 +54,9 @@ export async function resetDawarichStays(api: APIRequestContext, tripId: number)
}
/**
* Tours is on for every install, and with it on the places column has no
* Import file. The file guide pictures the column of an install that switched
* it off, and switches it back on afterwards.
* Tours is on for every install. No guide of the places column switches it off
* any more; the run still switches it on after the file, in case an older
* attempt left it off.
*/
export const setTours = (api: APIRequestContext, enabled: boolean): Promise<void> => toggleAddon(api, 'tours', enabled);
@@ -73,3 +75,87 @@ export async function undoDawarichStays(api: APIRequestContext, tripId: number):
}
await resetDawarichStays(api, tripId);
}
/** The pins of the file import: three Kyoto sights the seed does not have, as Google My Maps exports them. */
export const KML_PINS: [string, number, number][] = [
['Kiyomizu-dera', 34.9949, 135.785],
['Yasaka Shrine', 35.0037, 135.7785],
['Gion Shirakawa', 35.0059, 135.7748],
];
/** A KML layer of pins only, no line: the file the places column imports as places. Drawn once, on first use. */
export function pinsKmlFixture(): string {
const dir = path.join(process.cwd(), 'e2e', '.tmp');
mkdirSync(dir, { recursive: true });
const file = path.join(dir, 'kyoto-sights.kml');
if (existsSync(file)) return file;
const marks = KML_PINS.map(
([name, lat, lng]) =>
` <Placemark><name>${name}</name><Point><coordinates>${lng},${lat},0</coordinates></Point></Placemark>`
).join('\n');
writeFileSync(
file,
`<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<name>Kyoto sights</name>
${marks}
</Document>
</kml>
`
);
return file;
}
interface TripTag {
id: number;
name: string;
}
/** The tags the tag guide starts with, and the one it adds itself. */
export const GUIDE_TAGS = [
{ name: 'Must see', color: '#f97316' },
{ name: 'Rainy day', color: '#6366f1' },
{ name: 'Night view', color: '#ec4899' },
];
export const NEW_TAG = 'Photo spot';
async function tripTags(api: APIRequestContext, tripId: number): Promise<TripTag[]> {
const res = await api.get(`/api/trips/${tripId}/tags`);
if (!res.ok()) throw new Error(`could not list the trip's tags: ${res.status()} ${await res.text()}`);
return ((await res.json()) as { tags: TripTag[] }).tags;
}
/** Deletes the guide's tags, which takes them off every place too. */
export async function removeGuideTags(api: APIRequestContext, tripId: number): Promise<void> {
const names = new Set([...GUIDE_TAGS.map((tag) => tag.name), NEW_TAG].map((name) => name.toLowerCase()));
for (const tag of await tripTags(api, tripId)) {
if (!names.has(tag.name.toLowerCase())) continue;
const res = await api.delete(`/api/trips/${tripId}/tags/${tag.id}`);
if (!res.ok() && res.status() !== 404) throw new Error(`could not delete the tag ${tag.name}: ${res.status()}`);
}
}
/**
* The trip's tags for the tag guide, fresh: Must see, Rainy day and Night view,
* with Must see already on two places, so the filter at the end has more than
* the one place the guide tags itself.
*/
export async function ensureGuideTags(api: APIRequestContext, tripId: number, tagged: string[]): Promise<void> {
await removeGuideTags(api, tripId);
const ids: Record<string, number> = {};
for (const tag of GUIDE_TAGS) {
const res = await api.post(`/api/trips/${tripId}/tags`, { data: tag });
if (!res.ok()) throw new Error(`could not add the tag ${tag.name}: ${res.status()} ${await res.text()}`);
ids[tag.name] = ((await res.json()) as { tag: TripTag }).tag.id;
}
const list = await api.get(`/api/trips/${tripId}/places`);
const body = (await list.json()) as { places?: { id: number; name: string }[] } | { id: number; name: string }[];
const places = Array.isArray(body) ? body : (body.places ?? []);
for (const name of tagged) {
const place = places.find((x) => x.name === name);
if (!place) throw new Error(`no seeded place "${name}" to tag`);
const res = await api.put(`/api/trips/${tripId}/places/${place.id}`, { data: { tags: [ids['Must see']] } });
if (!res.ok()) throw new Error(`could not tag ${name}: ${res.status()} ${await res.text()}`);
}
}
+36 -1
View File
@@ -1,6 +1,7 @@
import type { APIRequestContext, Page } from '@playwright/test';
import { readFileSync } from 'node:fs';
import { at, day } from '../dates';
import { seededTrip } from './fixtures';
import { coverFixture, seededTrip } from './fixtures';
import { PICTURE_DAY } from './guide';
/**
@@ -43,6 +44,8 @@ export const FUEL_STOP = {
address: 'Ebina, Kanagawa',
description: 'Fuel and food on the Tomei Expressway, halfway to Hakone.',
stop_type: 'fuel',
// What a fuel stop starts with; a new place would otherwise stand an hour at the pump.
duration_minutes: 10,
};
/**
@@ -82,6 +85,38 @@ export async function removeFuelStop(api: APIRequestContext): Promise<void> {
if (id !== null) await api.delete(`/api/trips/${tripId}/places/${id}`);
}
// ── A stop on the way with a picture, for the stop photo guide ───────────────
/**
* Owakudani, the volcanic valley above Hakone on day 4, as a Sights stop on the
* way with a picture of its own. The cover drawing is a mountain ridge at
* sunset, which is what the valley looks like towards Fuji in the evening.
*/
export const PHOTO_STOP = 'Owakudani';
/** The picture uploaded as the place's own image, and the valley made a Sights stop. */
export async function ensurePhotoStop(api: APIRequestContext): Promise<void> {
const { tripId } = seededTrip();
const id = await placeIdOf(api, PHOTO_STOP);
if (id === null) throw new Error(`the seeded place "${PHOTO_STOP}" is missing`);
const image = await api.post(`/api/trips/${tripId}/places/${id}/image`, {
multipart: {
image: { name: 'owakudani-evening.jpg', mimeType: 'image/jpeg', buffer: readFileSync(await coverFixture()) },
},
});
if (!image.ok()) throw new Error(`could not give "${PHOTO_STOP}" a picture: ${image.status()} ${await image.text()}`);
const put = await api.put(`/api/trips/${tripId}/places/${id}`, { data: { stop_type: 'sights' } });
if (!put.ok())
throw new Error(`could not make "${PHOTO_STOP}" a stop on the way: ${put.status()} ${await put.text()}`);
}
/** The valley a destination without a picture again; the update reclaims the uploaded file. */
export async function removePhotoStop(api: APIRequestContext): Promise<void> {
const { tripId } = seededTrip();
const id = await placeIdOf(api, PHOTO_STOP);
if (id !== null) await api.put(`/api/trips/${tripId}/places/${id}`, { data: { stop_type: null, image_url: null } });
}
// ── A ferry on day 3, for the bookings guide ─────────────────────────────────
/** The boat across Lake Ashi, between the two Hakone stops of day 3. */
+18
View File
@@ -115,11 +115,29 @@ export async function waitForFlyover(page: Page): Promise<void> {
await expect(playButton(page).or(pauseButton(page))).toBeVisible({ timeout: 120_000 });
}
/**
* Search again while the card says a kind could not be searched. The public
* Overpass servers answer 429 and 504 under load, and a picture of that banner
* teaches nothing; a calm try or two usually gets through.
*/
export async function searchAgainWhileUnavailable(page: Page): Promise<void> {
const banner = page.getByText(/^Could not be searched right now/).first();
// Two tries, 20 s apart: more does not fit the test's time, and a longer outage needs a later run.
for (let attempt = 0; attempt < 2; attempt++) {
if (!(await banner.isVisible())) return;
await page.waitForTimeout(20_000);
await alongSearch(page).click();
await expect(alongSearch(page)).toHaveText(/Search again/, { timeout: 90_000 });
await page.waitForTimeout(1_000);
}
}
/** Ask "Along the tour" with what it starts with (the first three kinds, 500 m) and wait for the list. */
export async function searchAlong(page: Page): Promise<void> {
await alongCard(page).scrollIntoViewIfNeeded();
await alongSearch(page).click();
await expect(alongSearch(page)).toHaveText(/Search again/, { timeout: 90_000 });
await searchAgainWhileUnavailable(page);
await expect(alongList(page), 'the search along the tour found nothing (Overpass or the places index)').toBeVisible();
}
+22 -12
View File
@@ -35,8 +35,9 @@ export const PLANNER_TOURS = {
export const SPARE_DESCRIPTION = 'From the hut across the Cisles meadows and down to the Col Raiser gondola.';
/** What the description reads after the "someone else saved it" write of the conflict guide. */
export const REMOTE_DESCRIPTION = 'Mira: we take the gondola down, the last stretch is closed this week.';
/** The query the drawing guide types into the map search; the hut is where its points lie. */
export const SEARCH_QUERY = 'Rifugio Firenze';
/** The query the drawing guide types into the map search; the hut is where its points lie. OSM names it
* "Ncisles - Regensburger - Firenze", and "Rifugio Firenze" alone finds other huts of the valley first. */
export const SEARCH_QUERY = 'Regensburger Firenze';
async function body<T>(
res: { ok(): boolean; status(): number; text(): Promise<string>; json(): Promise<unknown> },
@@ -440,24 +441,33 @@ export async function centreOf(locator: Locator): Promise<{ x: number; y: number
return { x: box.x + box.width / 2, y: box.y + box.height / 2 };
}
/**
* RouteHitBand's path: transparent and 20 px wide. Its 'cursor-copy' class is
* not on the rendered path, so the band is found by its stroke instead.
*/
const ROUTE_BAND = '.leaflet-overlay-pane path[stroke="transparent"][stroke-width="20"]';
/**
* A spot on the drawn route, `share` of the way along its widest hit band:
* the invisible band Leaflet lays along the line to take the click that adds
* a shaping point.
*/
export async function spotOnRoute(page: Page, share = 0.3): Promise<{ x: number; y: number }> {
const at = await page.evaluate((k) => {
const bands = Array.from(document.querySelectorAll('.leaflet-overlay-pane path.cursor-copy')) as SVGPathElement[];
const band = bands.sort((a, b) => b.getTotalLength() - a.getTotalLength())[0];
const ctm = band?.getScreenCTM();
if (!band || !ctm) return null;
const p = band.getPointAtLength(band.getTotalLength() * k);
const s = new DOMPoint(p.x, p.y).matrixTransform(ctm);
return { x: s.x, y: s.y };
}, share);
const at = await page.evaluate(
({ k, sel }) => {
const bands = Array.from(document.querySelectorAll(sel)) as SVGPathElement[];
const band = bands.sort((a, b) => b.getTotalLength() - a.getTotalLength())[0];
const ctm = band?.getScreenCTM();
if (!band || !ctm) return null;
const p = band.getPointAtLength(band.getTotalLength() * k);
const s = new DOMPoint(p.x, p.y).matrixTransform(ctm);
return { x: s.x, y: s.y };
},
{ k: share, sel: ROUTE_BAND }
);
if (!at) throw new Error('no drawn route to click on');
return at;
}
/** The drawn route's click band, for the ring: the widest one. */
export const routeBand = (page: Page) => page.locator('.leaflet-overlay-pane path.cursor-copy').first();
export const routeBand = (page: Page) => page.locator(ROUTE_BAND).first();
+202 -5
View File
@@ -2,8 +2,9 @@ import { test, expect, type APIResponse, type Locator, type Page } from '@playwr
import { readFileSync } from 'node:fs'
import { clearNotices } from '../screenshots/shot'
import { captureGuide, captureHero, dismissReleaseNotice, beat, typeInto, settle, VIEWPORT, type GuideScript } from './guide'
import { ensureExtraTrips, ensureJourneyFixtures, filesImageFixture, SECOND_JOURNEY, SPARE_TRIP } from './fixtures'
import { coverFixture, ensureExtraTrips, ensureJourneyFixtures, filesImageFixture, SECOND_JOURNEY, SPARE_TRIP } from './fixtures'
import { connectJournalDawarich, releaseJournalDawarich, STAY_DAY, writtenEntryIds } from './fixtures-journey'
import { day } from '../dates'
import { journeyGuides, journeyContext, journalGuides, journalContext, studioGuides, studioContext } from '../../src/help/contexts/journey'
import type { HelpGuide } from '../../src/help/types'
@@ -355,6 +356,78 @@ async function setJourney(page: Page, data: Record<string, boolean>): Promise<vo
await answer(await page.request.patch(`/api/journeys/${journeyId}`, { data }), `update the journey with ${JSON.stringify(data)}`)
}
// ── A photo library (Immich) ──────────────────────────────────────────────────
/**
* The album guide needs a connected Immich holding an album that is bigger than
* the trip. No library runs beside the media run, so the page's own calls to
* one are answered here: the addon list names Immich as on, its status says
* connected, and the album holds the trip's last week plus a summer and a
* spring before it. The thumbnails are the drawn fixtures, taken in turn, since
* no photograph may live in this repository. The routes sit on the context,
* not the page: once the app's service worker has taken the page over, its
* requests no longer pass a page route. The context is the guide's own, so
* nothing is left behind for the next guide.
*/
const ALBUM = { id: 'help-album', albumName: 'Shared with Mia', assetCount: 16 }
const ALBUM_RANGE = { from: -7, to: 0 }
const ALBUM_SHOTS: { offset: number; city: string }[] = [
{ offset: 0, city: 'Kyoto' }, { offset: 0, city: 'Kyoto' },
{ offset: -1, city: 'Kyoto' }, { offset: -2, city: 'Hakone' },
{ offset: -4, city: 'Tokyo' }, { offset: -4, city: 'Tokyo' },
{ offset: -6, city: 'Tokyo' }, { offset: -7, city: 'Tokyo' },
{ offset: -96, city: 'Lisbon' }, { offset: -96, city: 'Lisbon' }, { offset: -97, city: 'Sintra' },
{ offset: -98, city: 'Lisbon' }, { offset: -150, city: 'Hamburg' }, { offset: -150, city: 'Hamburg' },
{ offset: -151, city: 'Hamburg' }, { offset: -152, city: 'Lübeck' },
]
const albumAssets = () => ALBUM_SHOTS.map((shot, i) => {
const taken = `${day(shot.offset)}T${String(9 + (i % 8)).padStart(2, '0')}:20:00`
return { id: `help-asset-${i}`, takenAt: `${taken}.000Z`, localTakenAt: taken, city: shot.city, mediaType: 'image' }
})
async function fakePhotoLibrary(page: Page): Promise<void> {
const files = [
await coverFixture(), await filesImageFixture('arashiyama'), await filesImageFixture('hakone-ryokan'),
await filesImageFixture('nishiki-market'), await filesImageFixture('jr-pass-map'),
].map(f => readFileSync(f))
const assets = albumAssets()
await page.context().route(/\/api\/addons(\?.*)?$/, async route => {
const res = await route.fetch()
const body = (await res.json()) as { addons?: { id: string }[] }
const addons = (body.addons ?? []).filter(a => a.id !== 'immich')
await route.fulfill({ response: res, json: { ...body, addons: [...addons, { id: 'immich', name: 'Immich', type: 'photo_provider', enabled: true }] } })
})
await page.context().route(/\/api\/integrations\/memories\/immich\//, async route => {
const path = new URL(route.request().url()).pathname
if (path.endsWith('/status')) return route.fulfill({ json: { connected: true } })
if (path.endsWith('/albums')) return route.fulfill({ json: { albums: [ALBUM, { id: 'help-album-2', albumName: 'Camera roll', assetCount: 1284 }] } })
if (path.includes('/albums/')) return route.fulfill({ json: { assets } })
if (path.endsWith('/search')) {
const trip = assets.filter(a => a.localTakenAt.slice(0, 10) >= day(ALBUM_RANGE.from))
return route.fulfill({ json: { assets: trip, hasMore: false } })
}
const asset = /help-asset-(\d+)/.exec(path)
if (asset) return route.fulfill({ contentType: 'image/jpeg', body: files[Number(asset[1]) % files.length] })
return route.fulfill({ status: 404, json: { error: 'not found' } })
})
}
const pickerDialog = (page: Page) => page.getByRole('dialog', { name: 'Immich' })
const albumRange = (page: Page) => pickerDialog(page).getByRole('group', { name: 'Taken between' })
/** Open one of the range's two calendars and pick a day, going back month by month from the picture day's. */
async function pickAlbumDay(page: Page, which: 0 | 1, iso: string): Promise<void> {
await albumRange(page).getByRole('button').nth(which).click()
const today = day(0)
const months = (Number(today.slice(0, 4)) - Number(iso.slice(0, 4))) * 12 + Number(today.slice(5, 7)) - Number(iso.slice(5, 7))
const back = page.getByRole('button', { name: 'Previous month' })
await expect(back).toBeVisible()
for (let i = 0; i < months; i++) await back.click()
// The calendar floats over the page in a portal: its day cells are the last buttons of that number.
await page.getByRole('button', { name: String(Number(iso.slice(8, 10))), exact: true }).last().click()
await expect(back).toHaveCount(0)
}
// ── The map and a recorded day ────────────────────────────────────────────────
/** The frosted switches at the top of the map: Plan, Recorded, Entries, Photos and the key. */
@@ -468,6 +541,7 @@ async function markTextTarget(page: Page): Promise<void> {
const words = page.locator('.st-sheet').getByText(/\p{L}{3,}/u).first()
await expect(words).toBeVisible()
await words.evaluate(el => {
for (const old of Array.from(document.querySelectorAll('[data-help-text]'))) old.removeAttribute('data-help-text')
const r = el.getBoundingClientRect()
const hit = document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2)
hit?.setAttribute('data-help-text', '')
@@ -501,8 +575,9 @@ async function openStudio(page: Page): Promise<void> {
await expect(page.locator('.st-bar')).toBeVisible({ timeout: 30_000 })
await expect(rail(page)).toBeVisible({ timeout: 30_000 })
await studioSection(page, 'Pages')
// An untouched book is cover, first page, one empty spread, last page and back: five thumbnails.
if ((await thumbs(page).count()) < 7) await relayoutBook(page)
// The book is laid out anew for every guide: the guides before this one leave
// photos, words, stickers and backgrounds on its pages.
await relayoutBook(page)
await settle(page)
await page.waitForTimeout(800)
}
@@ -884,6 +959,55 @@ const SCRIPTS: Record<string, GuideScript> = {
],
},
// Immich is answered by fakePhotoLibrary: an album of sixteen photos, half of
// them from the trip's last week, the rest from two earlier trips.
'album-date-range': {
guide: guide('album-date-range'),
start: async p => {
await fakePhotoLibrary(p)
await openJournal(p)
await p.getByRole('button', { name: 'Gallery' }).first().click()
await expect(p.getByRole('button', { name: 'Immich', exact: true })).toBeVisible({ timeout: 20_000 })
await settle(p)
},
steps: [
{
target: p => p.getByRole('button', { name: 'Immich', exact: true }),
act: async p => {
await p.getByRole('button', { name: 'Immich', exact: true }).click()
await expect(pickerDialog(p)).toBeVisible()
await settle(p)
},
},
{
prepare: async p => {
await pickerDialog(p).getByRole('button', { name: 'Albums', exact: true }).click()
await expect(pickerDialog(p).getByRole('button', { name: /^Shared with Mia/ })).toBeVisible()
await settle(p)
},
target: p => pickerDialog(p).getByRole('button', { name: /^Shared with Mia/ }),
act: async p => {
await pickerDialog(p).getByRole('button', { name: /^Shared with Mia/ }).click()
await expect(albumRange(p)).toBeVisible()
await expect(pickerDialog(p).getByRole('button', { name: /^Select all \(16\)/ })).toBeVisible({ timeout: 15_000 })
await settle(p)
},
},
{
target: albumRange,
act: async p => {
await pickAlbumDay(p, 0, day(ALBUM_RANGE.from))
await pickAlbumDay(p, 1, day(ALBUM_RANGE.to))
const all = pickerDialog(p).getByRole('button', { name: /^Select all \(8\)/ })
await expect(all).toBeVisible()
await all.click()
await expect(pickerDialog(p).getByRole('button', { name: /^Add \(8\)/ })).toBeEnabled()
await settle(p)
},
},
],
},
'journey-map-layers': {
guide: guide('journey-map-layers'),
start: openJournal,
@@ -927,6 +1051,31 @@ const SCRIPTS: Record<string, GuideScript> = {
],
},
'journey-satellite': {
guide: guide('journey-satellite'),
start: openJournal,
steps: [
{
target: p => mapPanel(p).getByRole('button', { name: 'Switch to satellite view' }),
act: async p => {
await mapPanel(p).getByRole('button', { name: 'Switch to satellite view' }).click()
await expect(mapPanel(p).getByRole('button', { name: 'Switch to map view' })).toBeVisible()
await p.waitForTimeout(1500) // the imagery
await settle(p)
},
},
{
target: p => mapPanel(p).getByRole('button', { name: 'Switch to map view' }),
act: async p => {
await mapPanel(p).getByRole('button', { name: 'Switch to map view' }).click()
await expect(mapPanel(p).getByRole('button', { name: 'Switch to satellite view' })).toBeVisible()
await p.waitForTimeout(1000) // the map tiles
await settle(p)
},
},
],
},
// ── A recorded day (Dawarich) ───────────────────────────────────────────
'journey-keep-route': {
guide: guide('journey-keep-route'),
@@ -1517,8 +1666,21 @@ const SCRIPTS: Record<string, GuideScript> = {
await settle(p)
},
target: p => sidePanel(p).locator('.st-theme-apply'),
act: async p => {
await sidePanel(p).getByRole('button', { name: 'Apply to the book' }).click()
await settle(p)
await p.waitForTimeout(800)
},
},
],
// Applying the theme is one undo step; the next guides find the book in its own theme again.
cleanup: async p => {
await p.getByRole('button', { name: 'Undo', exact: true }).first().click()
// The book saves a moment after the change; leaving earlier would keep the theme.
await p.waitForTimeout(3_000)
await expect(p.getByText('Saved', { exact: true }).first()).toBeVisible({ timeout: 15_000 })
await expect(p.locator('.st-bar').getByText('Saving', { exact: true })).toHaveCount(0, { timeout: 15_000 })
},
},
'studio-stickers': {
@@ -1536,6 +1698,14 @@ const SCRIPTS: Record<string, GuideScript> = {
},
{
target: p => sidePanel(p).locator('.st-shape-grid').first(),
// The step says to click one, and the result shows it on the spread, selected.
act: async p => {
const before = await sheetElements(p).count()
await sidePanel(p).locator('.st-sticker-btn').first().click()
await expect.poll(async () => sheetElements(p).count()).toBeGreaterThan(before)
await settle(p)
await p.waitForTimeout(600)
},
},
],
},
@@ -1545,6 +1715,15 @@ const SCRIPTS: Record<string, GuideScript> = {
start: openStudio,
steps: [
{
// A new, empty spread: every page Auto layout made already holds words or figures,
// and the element would land on top of them. It opens selected, ready to take it.
prepare: async p => {
await studioSection(p, 'Pages')
const before = await thumbs(p).count()
await sidePanel(p).getByRole('button', { name: 'Add spread' }).click()
await expect(thumbs(p)).toHaveCount(before + 1)
await settle(p)
},
target: p => railButton(p, 'Travel'),
act: async p => {
await studioSection(p, 'Travel')
@@ -1557,6 +1736,13 @@ const SCRIPTS: Record<string, GuideScript> = {
},
{
target: p => sidePanel(p).locator('.st-travel-card').first(),
act: async p => {
const before = await sheetElements(p).count()
await sidePanel(p).locator('.st-travel-card').first().click()
await expect.poll(async () => sheetElements(p).count()).toBeGreaterThan(before)
await settle(p)
await p.waitForTimeout(600)
},
},
],
},
@@ -1566,10 +1752,21 @@ const SCRIPTS: Record<string, GuideScript> = {
start: openStudio,
steps: [
{
// The first words on a spread can belong to a figure, so the spreads are
// tried in turn until a click selects text and the inspector offers Effects.
prepare: async p => {
await studioSection(p, 'Pages')
await thumbs(p).nth(2).locator('.st-thumb').click()
await settle(p)
const count = await thumbs(p).count()
for (let i = 2; i < count; i++) {
await thumbs(p).nth(i).locator('.st-thumb').click()
await settle(p)
if (!(await markTextTarget(p).then(() => true, () => false))) continue
await textTarget(p).click()
const isText = await inspector(p).getByRole('button', { name: 'Effects' }).waitFor({ timeout: 3_000 }).then(() => true, () => false)
await p.keyboard.press('Escape')
await settle(p)
if (isText) break
}
await markTextTarget(p)
},
target: p => textTarget(p),
+52 -8
View File
@@ -4,8 +4,12 @@ import type { HelpGuide } from '../../src/help/types';
import { clearNotices } from '../screenshots/shot';
import {
BOOKING_TITLE,
ensureMailPendingNotice,
ensureNotificationFixtures,
MAIL_PENDING_TITLE,
MAIL_SUBJECT,
markUnread,
removeMailPendingNotice,
removeNotificationFixtures,
SHARE_TITLE,
unreadIds,
@@ -37,12 +41,18 @@ const guide = (id: string): HelpGuide => {
*/
const bell = (page: Page): Locator => page.getByTitle('Notifications', { exact: true }).first();
/** The panel the bell opens, found through its footer button. */
const panel = (page: Page): Locator => page.getByRole('button', { name: 'Show all notifications' }).locator('xpath=..');
const panel = (page: Page): Locator =>
page
.locator('div.shadow-xl')
.filter({ has: page.getByRole('button', { name: 'Show all notifications' }) })
.first();
/** The column of the /notifications page: header, filter pills and the list. */
const pageColumn = (page: Page): Locator => page.locator('.max-w-2xl').first();
/** One notification (InAppNotificationItem's root) by its title, in the panel or the page. */
const item = (scope: Locator, title: string): Locator =>
scope.locator('div.relative.px-4.py-3').filter({ hasText: title }).first();
const ITEM = 'div.group.relative';
const item = (scope: Locator, title: string): Locator => scope.locator(ITEM).filter({ hasText: title }).first();
/** Pending bookings, the inbox of forwarded mails the Review button opens. */
const mailInbox = (page: Page): Locator => page.getByRole('dialog', { name: 'Pending bookings' });
/** The user menu button at the top right: avatar, name and chevron. */
const userMenu = (page: Page): Locator =>
page
@@ -89,9 +99,10 @@ const SCRIPTS: Record<string, GuideScript> = {
{ target: bell, act: openBell },
{
target: panel,
// Over the newest one, so its unread tint is not covered by the pointer.
// On the panel's head: a pointed-at row trades its time and dot for its tools,
// and the text is about the time and the dot.
hover: async (p) => {
await item(panel(p), SHARE_TITLE).hover();
await panel(p).locator('span.bg-accent-subtle').first().hover();
},
},
{
@@ -171,9 +182,7 @@ const SCRIPTS: Record<string, GuideScript> = {
target: (p) => item(pageColumn(p), BOOKING_TITLE).getByTitle('Delete', { exact: true }),
act: async (p) => {
await item(pageColumn(p), BOOKING_TITLE).getByTitle('Delete', { exact: true }).click();
await expect(pageColumn(p).locator('div.relative.px-4.py-3').filter({ hasText: BOOKING_TITLE })).toHaveCount(
0
);
await expect(pageColumn(p).locator(ITEM).filter({ hasText: BOOKING_TITLE })).toHaveCount(0);
await settle(p);
},
},
@@ -185,6 +194,41 @@ const SCRIPTS: Record<string, GuideScript> = {
},
},
'booking-mail-notifications': {
guide: guide('booking-mail-notifications'),
start: async (p) => {
await ensureMailPendingNotice(p.request);
await openDashboard(p);
},
steps: [
{
target: bell,
act: async (p) => {
await bell(p).click();
await expect(item(panel(p), MAIL_PENDING_TITLE)).toBeVisible();
await settle(p);
},
},
{
target: (p) => item(panel(p), MAIL_PENDING_TITLE),
// On the button the text names, so the row's tools stay out of the way.
hover: async (p) => {
await item(panel(p), MAIL_PENDING_TITLE).getByRole('button', { name: 'Review' }).hover();
},
act: async (p) => {
await item(panel(p), MAIL_PENDING_TITLE).getByRole('button', { name: 'Review' }).click();
await expect(mailInbox(p)).toBeVisible({ timeout: 15_000 });
await expect(mailInbox(p).getByText(MAIL_SUBJECT).first()).toBeVisible({ timeout: 15_000 });
await settle(p);
},
},
{ target: mailInbox },
],
cleanup: async (p) => {
await removeMailPendingNotice(p.request);
},
},
'notification-settings': {
guide: guide('notification-settings'),
start: openNotifications,
+104 -5
View File
@@ -7,6 +7,7 @@ import {
mediaEnv, wandererUrl, wandererToken, allowWanderer, ensureWandererConnection, disconnectWanderer,
ensureActivePlugin, removeSideloadedPlugin, parkOfflineChanges, clearParkedChanges,
} from './fixtures-settings'
import { mockOwnConnection, resetOwnConnection, AI_KEY } from './fixtures-assistant'
import { settingsContext, settingsTabContexts, settingsGuides } from '../../src/help/contexts/settings'
import type { HelpGuide } from '../../src/help/types'
@@ -18,7 +19,7 @@ import type { HelpGuide } from '../../src/help/types'
* with, because settings is the last file of the run.
*
* The cards come from `components/Settings/settingsKit.tsx`: a <section> with an
* <h2> in its head band, rows inside (`SettingRow`, a div with `px-3.5`), boxes
* <h2> in its head band, rows inside (`SettingRow`, a div with `px-4 py-3`), boxes
* of rows (`SettingRows`, a div with `divide-y`). A stacked row puts its wide
* control in a sibling below the label, so a row is found from its label by its
* own div, never by the label's parent.
@@ -57,7 +58,7 @@ const label = (page: Page, sectionTitle: string | RegExp, text: string) =>
const field = (page: Page, sectionTitle: string | RegExp, text: string) => label(page, sectionTitle, text).locator('xpath=..')
/** A whole row (label, control and whatever the row holds below them) by its label. */
const row = (page: Page, sectionTitle: string | RegExp, text: string) =>
label(page, sectionTitle, text).locator('xpath=ancestor::div[contains(@class,"px-3.5")][1]')
label(page, sectionTitle, text).locator('xpath=ancestor::div[contains(@class,"px-4") and contains(@class,"py-3")][1]')
/** The box of rows a row sits in. */
const rows = (page: Page, sectionTitle: string | RegExp, text: string) =>
label(page, sectionTitle, text).locator('xpath=ancestor::div[contains(@class,"divide-y")][1]')
@@ -102,6 +103,24 @@ function totp(secretBase32: string): string {
const only = (target: (p: Page) => Locator) => ({ target })
/**
* The booking mail import, switched on the way an admin does it (the same
* settings the Bookings guides use), so the Booking mails card shows the
* person's own address. Off again in cleanup.
*/
async function mailImport(page: Page, on: boolean): Promise<void> {
const data = on
? {
mail_ingest_enabled: true,
mail_ingest_transport: 'webhook',
mail_ingest_address_template: 'trips+{token}@example.com',
mail_ingest_webhook_secret: 'help-media-webhook-secret-for-the-pictures',
}
: { mail_ingest_enabled: false, mail_ingest_transport: 'off', mail_ingest_webhook_secret: '' }
const res = await page.request.put('/api/auth/app-settings', { data })
if (!res.ok()) throw new Error(`could not switch the mail import: ${res.status()} ${await res.text()}`)
}
/**
* Save, wait for the card to say Connected, then Test connection and wait for
* its answer: the order the connect guides tell the reader.
@@ -121,11 +140,11 @@ const SCRIPTS: Record<string, GuideScript> = {
start: opener('settings-display'),
steps: [
{
target: p => field(p, 'Startup', 'Start page').locator('xpath=..'),
target: p => row(p, 'Startup', 'Start page'),
// The start tab only exists once the app opens on the active trip.
act: async p => { await section(p, 'Startup').getByRole('button', { name: 'Active trip' }).click(); await settle(p) },
},
only(p => field(p, 'Startup', 'Start tab').locator('xpath=..')),
only(p => row(p, 'Startup', 'Start tab')),
],
cleanup: async p => { await section(p, 'Startup').getByRole('button', { name: 'Dashboard', exact: true }).click(); await settle(p) },
},
@@ -207,6 +226,31 @@ const SCRIPTS: Record<string, GuideScript> = {
],
cleanup: async p => { await p.reload(); await settle(p) },
},
'map-hide-pois': {
guide: guide('map-hide-pois'),
start: opener('settings-map'),
steps: [
{
// Mapbox GL with its default style, Mapbox Standard; nothing is saved, the reload in cleanup drops it.
prepare: async p => {
const card = section(p, /^Map$/)
await card.getByRole('button', { name: /Mapbox GL/ }).click()
await settle(p)
// Mapbox GL starts on its default style, Mapbox Standard, the style the step names.
await expect(card.getByRole('button', { name: /^Mapbox Standard/ })).toBeVisible()
},
target: p => section(p, /^Map$/).getByText('Map Style', { exact: true }).first().locator('xpath=..'),
},
{
target: p => row(p, /^Map$/, 'Hide Points of Interest'),
act: async p => {
await row(p, /^Map$/, 'Hide Points of Interest').locator('button[aria-pressed]').click()
await settle(p)
},
},
],
cleanup: async p => { await p.reload(); await settle(p) },
},
// ── Notifications ────────────────────────────────────────────────────────
'notification-channels': {
@@ -229,6 +273,23 @@ const SCRIPTS: Record<string, GuideScript> = {
},
// ── Integrations ─────────────────────────────────────────────────────────
'booking-mail-address': {
guide: guide('booking-mail-address'),
start: async p => {
await mailImport(p, true)
await openSettings(p, 'Integrations')
await expect(section(p, 'Booking mails').locator('code')).toBeVisible({ timeout: 20_000 })
await settle(p)
},
steps: [
// The address with its copy and New address buttons.
only(p => section(p, 'Booking mails').locator('code').locator('xpath=..')),
only(p => section(p, 'Booking mails').getByText('Forward automatically', { exact: true }).locator('xpath=..')),
only(p => rows(p, 'Booking mails', 'Import booking mails')),
only(p => section(p, 'Booking mails').getByRole('button', { name: /Pending bookings/ }).locator('xpath=..')),
],
cleanup: async p => { await mailImport(p, false); await p.reload(); await settle(p) },
},
'photo-providers': {
guide: guide('photo-providers'),
start: opener('settings-integrations'),
@@ -344,6 +405,43 @@ const SCRIPTS: Record<string, GuideScript> = {
],
cleanup: p => disconnectWanderer(p.request),
},
'connect-ai': {
guide: guide('connect-ai'),
// The key is never tested against a provider: fixtures-assistant.ts answers for the connection.
start: async p => {
await mockOwnConnection(p)
await openSettings(p, TAB_OF['settings-integrations'])
await expect(p.getByRole('group', { name: 'What would you like to chat with?' })).toBeVisible({ timeout: 20_000 })
await settle(p)
},
steps: [
{
target: p => p.getByRole('group', { name: 'What would you like to chat with?' }),
hover: async p => { await p.getByRole('button', { name: /^Paste an API key/ }).hover() },
act: async p => {
await p.getByRole('button', { name: /^Paste an API key/ }).click()
await expect(p.getByPlaceholder('Paste your key here')).toBeVisible()
await settle(p)
},
},
{
prepare: async p => {
await typeInto(p, p.getByPlaceholder('Paste your key here'), AI_KEY)
await expect(p.getByText('Detected: Anthropic')).toBeVisible()
await settle(p)
},
target: p => p.getByPlaceholder('Paste your key here').locator('xpath=ancestor::div[contains(@class,"gap-3")][1]'),
hover: async p => { await p.getByRole('button', { name: 'Connect', exact: true }).hover() },
act: async p => {
await p.getByRole('button', { name: 'Connect', exact: true }).click()
await expect(p.getByRole('button', { name: 'Open assistant' })).toBeVisible({ timeout: 15_000 })
await settle(p)
},
},
only(p => p.getByRole('button', { name: 'Open assistant' }).locator('xpath=ancestor::div[contains(@class,"divide-y")][1]')),
],
cleanup: p => resetOwnConnection(p.request),
},
'api-keys': {
guide: guide('api-keys'),
start: opener('settings-integrations'),
@@ -408,7 +506,8 @@ const SCRIPTS: Record<string, GuideScript> = {
guide: guide('plugin-settings'),
start: opener('settings-plugins'),
steps: [
only(p => section(p, 'Plugin settings')),
// The first plugin's own card, which follows the Plugin settings heading card.
only(p => section(p, 'Plugin settings').locator('xpath=following::section[1]')),
only(p => section(p, 'Plugin activity')),
],
},
+210 -12
View File
@@ -1,9 +1,10 @@
import { createHmac } from 'node:crypto'
import { test, expect, type Locator, type Page } from '@playwright/test'
import { captureGuide, captureHero, beat, typeInto, settle, VIEWPORT, type GuideScript } from './guide'
import { day } from '../dates'
import { day, mailHeaderDate } from '../dates'
import { seededTrip, ensureBookingsFixtures, bookingPdfFixture, bookingEmlFixture, BOOKING_EML, HOTEL_TO_BOOK, UNATTACHED_FILE } from './fixtures'
import { openTrip, modal, portalDialog, importSteps, importTask, dismissImportTask, deleteTripFiles } from './trip-shared'
import { requireExtractor, allowEmlUploads } from './external'
import { openTrip, modal, portalDialog, importDialog, importSteps, importTask, dismissImportTask, deleteTripFiles } from './trip-shared'
import { requireExtractor, allowEmlUploads, toggleAddon } from './external'
import { tripBookingsContext, tripBookingsGuides } from '../../src/help/contexts/tripBookings'
import type { HelpGuide } from '../../src/help/types'
@@ -220,6 +221,116 @@ const closeModal = async (page: Page): Promise<void> => {
}
}
// ── Booking mails ─────────────────────────────────────────────────────────────
/** The trip's own address, under the drop box of the import dialog. */
const forwardCard = (page: Page) => importDialog(page).getByText('Or forward by mail', { exact: true }).locator('xpath=..')
/** The user menu button at the top right: avatar, name and chevron. */
const userMenu = (page: Page) => page.getByRole('button').filter({ has: page.locator('span.max-w-40') }).first()
/** Pending bookings in the user menu, with the count of waiting mails after its label. */
const inboxEntryPoint = (page: Page) => page.getByRole('button', { name: /^Pending bookings/ })
const mailInbox = (page: Page) => page.getByRole('dialog', { name: 'Pending bookings' })
const inboxEntry = (page: Page) => mailInbox(page).getByRole('listitem').filter({ hasText: MAIL_SUBJECT }).first()
const MAIL_SUBJECT = 'Your table at Kikunoi'
/** What the guide saves: the title corrected in the form, the code TREK read from the mail. */
const MAIL_BOOKING = { title: 'Dinner at Kikunoi', code: 'KKN-77310' }
/** The media run's own webhook key; a mail service signs with the admin's. */
const WEBHOOK_SECRET = 'help-media-webhook-secret-for-the-pictures'
/**
* The mail import, switched on the way an admin does it, with the signed
* webhook as its transport so the guide can deliver a mail itself. The import
* dialog only opens where the server can read confirmations, so AI Parsing is
* on as well, while the person's own Read with AI is off: no model answers in
* the media run, and without it the mail waits in the inbox, which is the
* part of the flow the guide shows. Off again in cleanup, entries and the
* trip address with it.
*/
async function mailImportOn(page: Page, on: boolean): Promise<void> {
const api = page.request
const { tripId } = seededTrip()
if (on) {
await putAppSettings(page, {
mail_ingest_enabled: true,
mail_ingest_transport: 'webhook',
mail_ingest_address_template: 'trips+{token}@example.com',
mail_ingest_webhook_secret: WEBHOOK_SECRET,
})
await toggleAddon(api, 'llm_parsing', true)
await api.patch('/api/mail-ingest/settings', { data: { ai_enabled: false } })
return
}
const inbox = await api.get('/api/mail-ingest/inbox?status=open')
if (inbox.ok()) {
const { entries = [] } = (await inbox.json()) as { entries?: { id: number }[] }
for (const entry of entries) await api.post(`/api/mail-ingest/candidates/${entry.id}/discard`, { data: {} })
}
await api.delete(`/api/trips/${tripId}/mail-ingest/address`)
await api.patch('/api/mail-ingest/settings', { data: { ai_enabled: true } })
await toggleAddon(api, 'llm_parsing', false)
await putAppSettings(page, { mail_ingest_enabled: false, mail_ingest_transport: 'off', mail_ingest_webhook_secret: '' })
}
async function putAppSettings(page: Page, data: Record<string, string | boolean>): Promise<void> {
const res = await page.request.put('/api/auth/app-settings', { data })
if (!res.ok()) throw new Error(`could not save the mail import settings: ${res.status()} ${await res.text()}`)
}
/**
* Forward the restaurant's confirmation to the trip's address, the way a mail
* service hands a mail to TREK: raw, signed with the webhook key over the
* time, the recipient and every byte. Then wait until it was read and waits
* in the inbox. A plain text mail on purpose: nothing machine-readable in it,
* so the booking form starts from what the mail says in words.
*/
async function forwardMail(page: Page): Promise<void> {
const { tripId } = seededTrip()
const found = await page.request.get(`/api/trips/${tripId}/mail-ingest/address`)
const { address } = (await found.json()) as { address: { address: string } | null }
if (!address) throw new Error('the trip has no mail address after Create an address for this trip')
const raw = Buffer.from(
[
'From: Kikunoi Honten <reservations@kikunoi.example>',
`To: ${address.address}`,
`Subject: ${MAIL_SUBJECT}`,
`Date: ${mailHeaderDate(-30, '10:24', '+0900')}`,
'Message-ID: <kkn-77310@kikunoi.example>',
'MIME-Version: 1.0',
'Content-Type: text/plain; charset=utf-8',
'',
'Dear Ms Lindberg,',
'',
'thank you for your reservation at Kikunoi Honten. We look forward to welcoming you.',
'',
`Date: ${day(-3)}, 19:00`,
'Guests: 2',
`Reservation number: ${MAIL_BOOKING.code}`,
'',
'Kikunoi Honten, 459 Shimokawara-cho, Higashiyama-ku, Kyoto',
'',
].join('\r\n'),
)
const timestamp = String(Math.floor(Date.now() / 1000))
const signature = createHmac('sha256', WEBHOOK_SECRET).update(`${timestamp}\n${address.address}\n`).update(raw).digest('hex')
const res = await page.request.post('/api/mail-ingest/inbound', {
headers: {
'Content-Type': 'message/rfc822',
'X-Trek-Timestamp': timestamp,
'X-Trek-Recipient': address.address,
'X-Trek-Signature': `sha256=${signature}`,
},
data: raw,
})
if (!res.ok()) throw new Error(`the webhook refused the mail: ${res.status()} ${await res.text()}`)
await expect
.poll(async () => {
const count = await page.request.get('/api/mail-ingest/inbox/count')
return count.ok() ? ((await count.json()) as { pending?: number }).pending ?? 0 : 0
}, { timeout: 90_000, intervals: [1000] })
.toBeGreaterThan(0)
}
const only = (target: (p: Page) => Locator) => ({ target })
const SCRIPTS: Record<string, GuideScript> = {
@@ -290,7 +401,7 @@ const SCRIPTS: Record<string, GuideScript> = {
target: p => viewItem(p, 'Type'),
act: async p => {
await viewItem(p, 'Type').click()
await expect(sectionHead(p, 'Tour')).toBeVisible()
await expect(sectionHead(p, 'Guided tour')).toBeVisible()
await settle(p)
},
},
@@ -309,10 +420,12 @@ const SCRIPTS: Record<string, GuideScript> = {
await closeViewOptions(p)
await settle(p)
},
target: p => sectionHead(p, 'Tour'),
// The label: the heading itself spans the whole width, and a frame
// centred on it would cut the label off at the left.
target: p => sectionHead(p, 'Guided tour').getByText('Guided tour', { exact: true }),
act: async p => {
await sectionHead(p, 'Tour').click()
await expect(sectionHead(p, 'Tour')).toHaveAttribute('aria-expanded', 'false')
await sectionHead(p, 'Guided tour').click()
await expect(sectionHead(p, 'Guided tour')).toHaveAttribute('aria-expanded', 'false')
await expect(bookingCard(p, 'Kyoto Cycling Tour')).toHaveCount(0)
await settle(p)
},
@@ -489,9 +602,9 @@ const SCRIPTS: Record<string, GuideScript> = {
},
},
{
target: p => detail(p, VIEWED.title).getByRole('button', { name: 'On map', exact: true }),
target: p => detail(p, VIEWED.title).getByRole('button', { name: 'Map', exact: true }),
act: async p => {
await detail(p, VIEWED.title).getByRole('button', { name: 'On map', exact: true }).click()
await detail(p, VIEWED.title).getByRole('button', { name: 'Map', exact: true }).click()
await expect(detail(p, VIEWED.title)).toHaveCount(0)
// The tab goes and the plan opens on the tour's day with its place selected.
await expect(p.getByRole('heading', { name: 'Bookings', exact: true, level: 2 })).toHaveCount(0)
@@ -590,7 +703,9 @@ const SCRIPTS: Record<string, GuideScript> = {
await expect(modal(p).getByRole('button', { name: UNATTACHED_FILE, exact: true })).toBeVisible()
await beat(p, 300)
},
target: p => modal(p).getByRole('button', { name: 'Link existing file' }).locator('xpath=..'),
// The list it opens above the button: what the reader picks from. The
// button's own box leaves the list out, since it floats over the form.
target: p => modal(p).getByRole('button', { name: UNATTACHED_FILE, exact: true }).locator('xpath=..'),
act: async p => {
await modal(p).getByRole('button', { name: UNATTACHED_FILE, exact: true }).click()
await expect(modal(p).getByRole('button', { name: UNATTACHED_FILE, exact: true })).toHaveCount(0)
@@ -711,9 +826,9 @@ const SCRIPTS: Record<string, GuideScript> = {
},
},
{
target: p => filterMenu(p).getByRole('button', { name: /^Tour\b/ }),
target: p => filterMenu(p).getByRole('button', { name: /^Guided tour\b/ }),
act: async p => {
await filterMenu(p).getByRole('button', { name: /^Tour\b/ }).click()
await filterMenu(p).getByRole('button', { name: /^Guided tour\b/ }).click()
await expect(bookingCard(p, 'Haneda Airport P4')).toHaveCount(0)
await expect(bookingCard(p, 'Kyoto Cycling Tour')).toBeVisible()
await settle(p)
@@ -819,6 +934,89 @@ const SCRIPTS: Record<string, GuideScript> = {
await deleteTripFiles(p, BOOKING_EML)
},
},
'forward-booking-mail': {
guide: guide('forward-booking-mail'),
start: async p => {
await mailImportOn(p, true)
await openBookings(p)
},
steps: [
{
target: p => p.getByRole('button', { name: 'Import booking confirmations', exact: true }),
act: async p => {
await p.getByRole('button', { name: 'Import booking confirmations', exact: true }).click()
await expect(importDialog(p)).toBeVisible()
await expect(forwardCard(p)).toBeVisible({ timeout: 15_000 })
await settle(p)
},
},
{
target: forwardCard,
act: async p => {
await forwardCard(p).getByRole('button', { name: 'Create an address for this trip' }).click()
await expect(forwardCard(p).locator('code')).toContainText('@', { timeout: 15_000 })
await settle(p)
},
},
{
// The address and its copy button; copying itself needs a clipboard the headless browser lacks.
target: p => forwardCard(p).locator('code').locator('xpath=..'),
act: async p => {
await importDialog(p).getByRole('button', { name: 'Cancel', exact: true }).click()
await expect(importDialog(p)).toHaveCount(0)
await forwardMail(p)
},
},
{
prepare: async p => {
// A fresh page reads the waiting count, as anyone arriving later would.
await openBookings(p)
await userMenu(p).click()
await expect(inboxEntryPoint(p)).toBeVisible()
await expect(inboxEntryPoint(p)).toContainText('1')
await beat(p, 300)
},
target: inboxEntryPoint,
act: async p => {
await inboxEntryPoint(p).click()
await expect(inboxEntry(p)).toBeVisible({ timeout: 15_000 })
await settle(p)
},
},
{
target: inboxEntry,
act: async p => {
await inboxEntry(p).getByRole('button', { name: 'Fill in yourself' }).click()
await expect(mailInbox(p)).toHaveCount(0)
await expect(modal(p).getByRole('heading', { name: 'New Reservation' })).toBeVisible({ timeout: 20_000 })
await expect(codeBox(p)).toHaveValue(MAIL_BOOKING.code)
await settle(p)
},
},
{
prepare: async p => {
await typeInto(p, titleBox(p), MAIL_BOOKING.title)
await settle(p)
},
target: p => modal(p).getByRole('dialog'),
act: async p => {
await saveButton(p, 'Add').click()
await expect(modal(p)).toHaveCount(0, { timeout: 20_000 })
// Fill in yourself opens the trip without its tab; the result shows the booking where it belongs.
await openBookings(p)
await expect(bookingCard(p, MAIL_BOOKING.title)).toBeVisible({ timeout: 20_000 })
await bookingCard(p, MAIL_BOOKING.title).scrollIntoViewIfNeeded()
await settle(p)
},
},
],
cleanup: async p => {
await closeModal(p)
await clearPanelState(p)
await deleteBookings(p, MAIL_BOOKING.title)
await mailImportOn(p, false)
},
},
'edit-booking': {
guide: guide('edit-booking'),
start: openBookings,
+249 -2
View File
@@ -1,7 +1,8 @@
import { readFileSync } from 'node:fs'
import { test, expect, type Locator, type Page } from '@playwright/test'
import { captureGuide, captureHero, beat, typeInto, settle, VIEWPORT, type GuideScript } from './guide'
import { day, long, short } from '../dates'
import { seededTrip, ensureCostsFixtures } from './fixtures'
import { seededTrip, ensureCostsFixtures, filesPdfFixture } from './fixtures'
import { openTrip, modal } from './trip-shared'
import { RAMEN, RECEIPT_FILE, receiptFixture, removeReceiptFiles } from './fixtures-trip-costs'
import { tripCostsContext, tripCostsGuides } from '../../src/help/contexts/tripCosts'
@@ -30,7 +31,8 @@ const SEEDED_EUR = 'Flights FRA → HND'
const BOOKING = 'LH716 FRA → HND'
/** A seeded expense costs-table gives its days to. */
const JR_PASS = 'JR Pass (14 days)'
const DINNER = 'Kaiseki dinner in Gion'
/** The dinner add-expense records; not the seed's Kaiseki dinner, which cleanup would delete with it. */
const DINNER = 'Yakitori dinner in Pontocho'
const UPGRADE = 'Shinkansen seat upgrade'
const LUNCH = { name: 'Nishiki Market lunch', category: 'food', total_price: 4800, currency: 'JPY', expense_date: day(-4) }
/** The row costs-table adds to Food & drink; the table names a new row this until it is renamed. */
@@ -38,6 +40,12 @@ const MATCHA = 'Matcha in Uji'
const NEW_ROW = 'New Entry'
/** Where the tab keeps the list/table choice (CostsPanel's COSTS_VIEW_KEY). */
const VIEW_KEY = 'trek:costs-view'
/** A stay split-by-shares divides by nights: three, three and two, so the shares come out even. */
const MACHIYA = { name: 'Machiya stay in Kyoto', category: 'accommodation', total_price: 39000, currency: 'JPY', expense_date: day(-5) }
/** The trip file link-receipt-file puts on the JR Pass; the voucher is the pass's invoice. */
const VOUCHER = 'JR-Pass-voucher.pdf'
/** Where useCostsCurrency keeps one trip's picked currency. */
const SHOWN_IN_KEY = (tripId: number) => `trek:costs-currency:${tripId}`
/** The Costs tab, waited out: its panel is lazy and its figures come from the server. */
const openCosts = async (p: Page): Promise<void> => {
@@ -185,6 +193,36 @@ async function pickCurrency(page: Page, code: string): Promise<void> {
await settle(page)
}
// ── The bar's currency picker and the sidebar's switches ─────────────────────
const showIn = (page: Page) => page.getByRole('button', { name: 'Show amounts in', exact: true })
const showInList = (page: Page) => page.getByRole('group', { name: 'Show amounts in', exact: true })
const modeSwitch = (page: Page) => page.getByRole('button', { name: 'Split costs between travelers', exact: true })
async function setCostsMode(page: Page, mode: 'split' | 'totals'): Promise<void> {
const { tripId } = seededTrip()
const res = await page.request.put(`/api/trips/${tripId}`, { data: { costs_mode: mode } })
if (!res.ok()) throw new Error(`could not set costs_mode ${mode}: ${res.status()} ${await res.text()}`)
}
/** The voucher as a trip file, uploaded once; the seed has no document of its own. */
async function ensureVoucher(page: Page): Promise<void> {
const { tripId } = seededTrip()
const res = await page.request.get(`/api/trips/${tripId}/files`)
const { files = [] } = (await res.json()) as { files?: { original_name: string }[] }
if (files.some(f => f.original_name === VOUCHER)) return
const uploaded = await page.request.post(`/api/trips/${tripId}/files`, {
multipart: { file: { name: VOUCHER, mimeType: 'application/pdf', buffer: readFileSync(filesPdfFixture('JR-Pass-voucher')) } },
})
if (!uploaded.ok()) throw new Error(`could not upload ${VOUCHER}: ${uploaded.status()} ${await uploaded.text()}`)
}
/** Open the expense editor on a ledger row with its pencil. */
async function editRow(page: Page, name: string): Promise<void> {
await rowActions(page, name).getByRole('button', { name: 'Edit' }).click()
await expect(nameBox(page)).toHaveValue(name)
await settle(page)
}
const SCRIPTS: Record<string, GuideScript> = {
'add-expense': {
guide: guide('add-expense'),
@@ -422,6 +460,90 @@ const SCRIPTS: Record<string, GuideScript> = {
cleanup: p => deleteExpenses(p, UPGRADE),
},
'split-by-shares': {
guide: guide('split-by-shares'),
start: async p => {
await createExpense(p, MACHIYA)
await openCosts(p)
},
steps: [
{
prepare: p => editRow(p, MACHIYA.name),
target: p => block(p, 'Split').getByRole('button', { name: 'Custom', exact: true }),
act: async p => {
await block(p, 'Split').getByRole('button', { name: 'Custom', exact: true }).click()
await expect(block(p, 'Split').getByRole('group', { name: 'Enter shares as' })).toBeVisible()
await settle(p)
},
},
{
target: p => block(p, 'Split').getByRole('group', { name: 'Enter shares as' }),
act: async p => {
await block(p, 'Split').getByRole('group', { name: 'Enter shares as' }).getByRole('button', { name: 'Shares', exact: true }).click()
await expect(block(p, 'Split').getByRole('textbox', { name: /^Shares for / })).toHaveCount(3)
await settle(p)
},
},
{
// Three nights, three nights, and jonas came a day later.
prepare: async p => {
const fields = block(p, 'Split').getByRole('textbox', { name: /^Shares for / })
await fields.nth(0).fill('3')
await fields.nth(1).fill('3')
await fields.nth(2).fill('2')
await expect(block(p, 'Split').getByText('Split matches total')).toBeVisible()
await settle(p)
},
target: p => block(p, 'Split').getByRole('textbox', { name: /^Shares for / }).first().locator('xpath=ancestor::div[contains(@class,"divide-y")][1]'),
},
{
target: p => modal(p).getByRole('button', { name: 'Save', exact: true }),
act: async p => {
await modal(p).getByRole('button', { name: 'Save', exact: true }).click()
await expect(modal(p)).toHaveCount(0)
await dropFocus(p)
await expect(expRow(p, MACHIYA.name)).toBeVisible()
await expRow(p, MACHIYA.name).evaluate(el => el.scrollIntoView({ block: 'center' }))
await settle(p)
},
},
],
cleanup: async p => {
await closeModal(p)
await deleteExpenses(p, MACHIYA.name)
},
},
'costs-show-in': {
guide: guide('costs-show-in'),
start: openCosts,
steps: [
only(showIn),
{
prepare: async p => {
await showIn(p).click()
await expect(showInList(p)).toBeVisible()
await beat(p, 300)
},
target: showInList,
act: async p => {
await showInList(p).locator('input').first().fill('EUR')
await showInList(p).getByRole('button', { name: /^EUR/ }).click()
await expect(showIn(p)).toHaveText(/EUR/)
await expect(card(p, 'Total trip spend')).toHaveText(/€/, { timeout: 20_000 })
await settle(p)
},
},
only(p => p.locator('.costs-summary')),
// Ringed in its new state; the reader picks the first entry to go back.
only(showIn),
],
cleanup: async p => {
const { tripId } = seededTrip()
await p.evaluate(key => { try { localStorage.removeItem(key) } catch { /* no storage: nothing to put back */ } }, SHOWN_IN_KEY(tripId))
},
},
'expense-receipts': {
guide: guide('expense-receipts'),
start: async p => {
@@ -488,6 +610,62 @@ const SCRIPTS: Record<string, GuideScript> = {
},
},
'link-receipt-file': {
guide: guide('link-receipt-file'),
start: async p => {
await ensureVoucher(p)
await openCosts(p)
},
steps: [
{
target: p => rowActions(p, JR_PASS).getByRole('button', { name: 'Edit' }),
act: async p => {
await editRow(p, JR_PASS)
await expect(block(p, 'Receipts & Invoices')).toBeVisible()
},
},
{
// Opened for the picture, so the files it offers stand under the icon.
prepare: async p => {
await block(p, 'Receipts & Invoices').getByRole('button', { name: 'Link', exact: true }).click()
await expect(modal(p).getByRole('button', { name: VOUCHER })).toBeVisible()
await settle(p)
},
target: p => block(p, 'Receipts & Invoices').getByRole('button', { name: 'Link', exact: true }),
// Pointer on the offered file, so the icon's tooltip does not cover the list.
hover: async p => {
await modal(p).getByRole('button', { name: VOUCHER }).hover()
},
},
{
target: p => modal(p).getByRole('button', { name: VOUCHER }),
act: async p => {
await modal(p).getByRole('button', { name: VOUCHER }).click()
await expect(block(p, 'Receipts & Invoices').getByText(VOUCHER)).toBeVisible()
await settle(p)
},
},
{
target: p => modal(p).getByRole('button', { name: 'Save', exact: true }),
act: async p => {
await modal(p).getByRole('button', { name: 'Save', exact: true }).click()
await expect(modal(p)).toHaveCount(0, { timeout: 20_000 })
await dropFocus(p)
await expect(expRow(p, JR_PASS).getByRole('button', { name: 'View receipt' })).toBeVisible({ timeout: 20_000 })
await expRow(p, JR_PASS).evaluate(el => el.scrollIntoView({ block: 'center' }))
await settle(p)
},
},
],
cleanup: async p => {
await closeModal(p)
const { tripId } = seededTrip()
for (const item of (await budgetItems(p)).filter(i => i.name === JR_PASS)) {
await p.request.put(`/api/trips/${tripId}/budget/${item.id}`, { data: { receipt_file_ids: [] } })
}
},
},
'filter-costs': {
guide: guide('filter-costs'),
start: openCosts,
@@ -559,6 +737,31 @@ const SCRIPTS: Record<string, GuideScript> = {
],
},
'leave-out-category': {
guide: guide('leave-out-category'),
start: openCosts,
steps: [
only(p => card(p, 'By category')),
{
prepare: async p => {
await card(p, 'By category').getByRole('button', { name: 'Leave Transport out of the totals' }).click()
await expect(card(p, 'By category').getByRole('button', { name: 'Count all', exact: true })).toBeVisible()
await settle(p)
},
target: p => card(p, 'By category'),
},
only(p => card(p, 'Total trip spend')),
{
target: p => card(p, 'By category').getByRole('button', { name: 'Count all', exact: true }),
act: async p => {
await card(p, 'By category').getByRole('button', { name: 'Count all', exact: true }).click()
await expect(card(p, 'By category').getByText('Select a category to leave it out of the totals.')).toBeVisible()
await settle(p)
},
},
],
},
'settle-up': {
guide: guide('settle-up'),
start: async p => {
@@ -638,6 +841,50 @@ const SCRIPTS: Record<string, GuideScript> = {
],
},
'costs-totals-only': {
guide: guide('costs-totals-only'),
start: openCosts,
steps: [
only(p => card(p, 'Split costs between travelers')),
{
prepare: async p => {
await modeSwitch(p).click()
await expect(modeSwitch(p)).toHaveAttribute('aria-pressed', 'false', { timeout: 15_000 })
await expect(card(p, 'Settle up')).toHaveCount(0)
await settle(p)
},
// The count under the total, which stands alone now; the frame around it
// shows the total and the ledger under it without payers or split. The
// card itself spans the whole width and would be cut at both sides.
target: p => card(p, 'Total trip spend').getByText(/^\d+ expenses?$/),
},
{
prepare: async p => {
await addExpense(p).click()
await expect(nameBox(p)).toBeVisible()
await expect(modal(p).getByText('Who paid?', { exact: true })).toHaveCount(0)
await settle(p)
},
// The editor itself, not the dimmed backdrop around it.
target: p => p.getByRole('dialog').last(),
act: closeModal,
},
{
target: p => card(p, 'Split costs between travelers'),
act: async p => {
await modeSwitch(p).click()
await expect(modeSwitch(p)).toHaveAttribute('aria-pressed', 'true', { timeout: 15_000 })
await expect(card(p, 'Settle up')).toBeVisible()
await settle(p)
},
},
],
cleanup: async p => {
await closeModal(p)
await setCostsMode(p, 'split')
},
},
'expense-from-booking': {
guide: guide('expense-from-booking'),
start: async p => {
+22 -3
View File
@@ -224,7 +224,12 @@ const SCRIPTS: Record<string, GuideScript> = {
only(p => stop(p, 'Arashiyama Bamboo Grove')),
only(p => stop(p, 'Nishiki Market')),
only(connector),
only(routeBar),
{
// Hovered on Route itself: the bar's centre is the Walking button, whose
// tooltip would stand over the ring.
target: routeBar,
hover: async p => { await routeBar(p).getByRole('button', { name: 'Route', exact: true }).hover() },
},
],
},
'place-onto-day': {
@@ -252,7 +257,16 @@ const SCRIPTS: Record<string, GuideScript> = {
target: p => toOpenDay(p, SPARE.name),
},
only(p => p.getByRole('button', { name: 'Add place to this day' }).first()),
only(p => p.getByRole('button', { name: 'Add to the open day' })),
{
target: p => p.getByRole('button', { name: 'Add to the open day' }),
// The result shows the place as a stop on day 2, where step 1 dropped it,
// with the details panel of the open day out of the way.
act: async p => {
await closeDayDetails(p)
await stop(p, SPARE.name).evaluate(el => el.scrollIntoView({ block: 'center' }))
await settle(p)
},
},
],
cleanup: p => deleteByName(p, SPARE.name),
},
@@ -474,6 +488,8 @@ const SCRIPTS: Record<string, GuideScript> = {
},
{
target: p => noteDialog(p).getByText('Icon', { exact: true }).locator('xpath=../..'),
// Pointed at the heading: the block's centre is an icon whose tooltip would stand in it.
hover: async p => { await noteDialog(p).getByText('Icon', { exact: true }).hover() },
act: async p => {
await noteDialog(p).getByRole('button', { name: 'Add', exact: true }).click()
await expect(noteDialog(p)).toHaveCount(0)
@@ -528,7 +544,9 @@ const SCRIPTS: Record<string, GuideScript> = {
guide: guide('manage-days'),
start: p => openTrip(p),
steps: [
only(p => dayHeader(p, 1)),
// The dates, and with them the days, are changed in the trip's edit form,
// which Trip settings at the top of the planner opens.
only(p => p.getByRole('button', { name: 'Trip settings' }).first()),
{
prepare: async p => {
await p.getByRole('button', { name: 'Reorder days' }).click()
@@ -655,6 +673,7 @@ const SCRIPTS: Record<string, GuideScript> = {
only(p => modal(p).getByText('Document', { exact: true }).locator('xpath=ancestor::section[1]')),
only(p => modal(p).getByText('Calendar', { exact: true }).locator('xpath=ancestor::section[1]')),
only(p => modal(p).getByText(/^Maps & GPS/).locator('xpath=ancestor::section[1]')),
only(p => modal(p).getByText(/^Google Maps/).locator('xpath=ancestor::section[1]')),
],
cleanup: closeModal,
},
+307 -143
View File
@@ -17,8 +17,12 @@ import type { HelpGuide } from '../../src/help/types'
* not undo their changes one by one: the list is snapshotted once before the
* first guide (`fixtures-trip-lists.ts`) and put back from that snapshot when
* each packing guide starts and again when it ends. What lives outside the
* items (a template, a bag, a list's assignees, a task) is removed by the
* guide that made it.
* items (a template, a bag, a list's assignees, who brings or sees an item, a
* task) is removed by the guide that made it.
*
* A packing row shows only what is set; a click on its name opens the item's
* window, where every choice about the item lives. The list-wide actions sit
* in the menu behind the three dots next to Add list.
*/
const guide = (id: string): HelpGuide => {
@@ -57,16 +61,23 @@ const OPEN_ITEM = 'Slip-on shoes for temples'
/** A list with one open item, so Check All visibly finishes it. */
const CHECK_ALL_LIST = 'Electronics'
const CHECK_ALL_OPEN = 'eSIM activation code'
/** Fully packed in the seed, so the Open filter hides its list. */
/** Fully packed in the seed, so Hide packed hides its list. */
const PACKED_ITEM = 'Passport'
/** What the ordering guide moves: the third list onto the first, then the last item of that first list to its top. */
const MOVED_LIST = 'Electronics'
const FIRST_LIST = 'Documents'
const MOVED_ITEM = 'Credit card and some yen'
const TOP_ITEM = 'Passport'
/** A to Z puts this one first in Clothing, where the seed has it in the middle. */
const SORTED_LIST = 'Clothing'
const SORTED_FIRST = 'Light layers'
/** Packed in the seed; the counting guide unticks it and counts five pairs in. */
const PIECES_ITEM = 'Merino socks'
const PIECES = 5
/** The item whose window the editing guide walks through; it gets a second bringer. */
const EDIT_ITEM = 'Power bank'
/** The list the whole-list sharing guide hands to one person. */
const SHARE_LIST = 'Toiletries'
/** The count in the label moves with what is ticked, so it is matched, not spelled. */
const CLEAR_CHECKED = /^Remove \d+ checked$/
@@ -76,8 +87,8 @@ const CLEAR_CHECKED = /^Remove \d+ checked$/
const cat = (page: Page, name: string): Locator =>
page.getByText(name, { exact: true }).first().locator('xpath=ancestor::div[2]')
/**
* The head band of a card. The ⋯ has to be taken from here: every item row
* carries a ⋯ of its own, so the card as a whole holds several of them.
* The head band of a card. The ⋯ has to be taken from here: the card's rows
* and its add field hold buttons of their own.
*/
const catHeader = (page: Page, name: string): Locator => cat(page, name).locator('> div').first()
const catMenu = (page: Page, name: string): Locator =>
@@ -91,48 +102,38 @@ const item = (page: Page, name: string): Locator =>
page.locator('.packing-item-row').filter({ hasText: name }).first()
/** A row's own grip is a bare draggable div, the first thing in the row. */
const rowGrip = (page: Page, name: string): Locator => item(page, name).locator('div[draggable="true"]')
/** The name of a row is the button that opens the item's window. */
const itemName = (page: Page, name: string): Locator => item(page, name).locator('button[aria-haspopup="dialog"]')
/** The item's window, portalled to <body>; only one is ever open. */
const itemWindow = (page: Page): Locator => page.locator('div[role="dialog"].trek-menu-enter')
/** The short list a pill of the window opens under its line. */
const choiceList = (page: Page): Locator => itemWindow(page).locator('div.max-h-56')
/** A line of the window found by its label, for the pill on it. */
const windowLine = (page: Page, label: string): Locator =>
itemWindow(page).getByText(label, { exact: true }).locator('xpath=..')
/** The two-column grid of list cards; its children are the cards, in order. */
const listGrid = (page: Page): Locator =>
page.locator('div.grid').filter({ has: page.locator('.packing-item-row') }).first()
/** The only item of the list the first guide builds; its name changes mid-guide. */
const onlyRow = (page: Page): Locator => cat(page, NEW_LIST).locator('.packing-item-row').first()
/** An item's own ⋯, which holds Move to List, Sharing, Rename and Delete. */
const rowMenu = (page: Page, name: string): Locator => item(page, name).locator('.packing-row-overflow button')
/** The open item menu; Sharing is a whole line in it. */
const rowMenuSharing = (page: Page): Locator =>
page.locator('.trek-menu-enter').getByRole('button', { name: /^Sharing/ })
/**
* The progress card's count and percentage. The total is a span of its own
* that reads "/28"; the category badges hold "n/m" in one span, so they never match.
*/
const progressCount = (page: Page): Locator =>
page.getByText(/^\/\d+$/).first().locator('xpath=ancestor::div[2]')
/** The quantity badge is the first field among a row's inline actions while it has no counter. */
const quantityField = (page: Page, name: string): Locator =>
item(page, name).locator('.packing-row-inline-actions input').first()
/** The packed counter of a multi-piece item, named "3 of 5 packed". */
const piecesCounter = (page: Page, name: string): Locator =>
item(page, name).getByRole('group', { name: / of \d+ packed$/ })
/** The line beside Shared and My list that counts what is packed. */
const progressLine = (page: Page): Locator => page.getByText(/^\d+ of \d+ packed$/).first().locator('xpath=..')
/** The name dialog that Add list and Save as template open. */
const nameDialog = (page: Page, confirm: string): Locator => page.getByRole('button', { name: confirm, exact: true })
/** The sharing dropdown is portalled to <body>, so the hint's parent is the card itself. */
const shareMenu = (page: Page): Locator =>
page.getByText('In the group pool, visible to everyone').locator('xpath=ancestor::div[1]')
/** Its click-catcher, the only way back out of the menu once a name is ticked. */
const shareOverlay = (page: Page): Locator => page.locator('div[role="presentation"][style*="z-index: 1099"]').last()
/** The three dots next to Add list, and the menu they open. */
const listsMenuButton = (page: Page): Locator =>
page.getByRole('button', { name: 'Add list' }).locator('xpath=..').getByRole('button', { name: 'Show more' })
const listsMenu = (page: Page): Locator => page.getByRole('menu')
/** The bulk-import dialog, a DialogShell whose head band carries its title. */
const importCard = (page: Page): Locator =>
page.getByRole('dialog').filter({ has: page.getByText('Import Packing List', { exact: true }) })
/**
* The bag picker of a row and the member picker of a bag both hang off the
* body, so they are found by their caption rather than inside the row.
*/
const bagPicker = (page: Page): Locator => page.locator('.trek-menu-enter').filter({ hasText: 'Bags' }).last()
/** The whole-list sharing dialog, found by its footer button. */
const listSharing = (page: Page): Locator =>
page.getByRole('dialog').filter({ has: page.getByRole('button', { name: 'Apply to list' }) })
/** The member picker of a bag hangs off the body, so it is found by its caption. */
const bagMemberPicker = (page: Page): Locator => page.locator('.trek-menu-enter').filter({ hasText: 'Assign members' }).last()
/** The calendar a date field opens, a portal of its own. */
const datePicker = (page: Page): Locator => page.getByRole('dialog', { name: 'Date picker' })
/** The Export button's menu: print, Markdown and CSV. */
const exportMenu = (page: Page): Locator => page.getByRole('menu')
/** The printable page inside the preview, a srcdoc frame of its own. */
const printFrame = (page: Page) => page.frameLocator('iframe[title^="Packing List"]')
/** The bag sidebar: the innermost box holding the guide's bag and the weight summary below the cards. */
@@ -177,6 +178,35 @@ async function openTodos(page: Page): Promise<void> {
await settle(page)
}
/** The three dots next to Add list, opened. */
async function openListsMenu(page: Page): Promise<void> {
await listsMenuButton(page).click()
await expect(listsMenu(page)).toBeVisible()
await beat(page, 300)
}
/**
* The menu and the item window sit over a full-viewport catcher; a click in
* the corner closes either without touching what is under it.
*/
async function clickAside(page: Page): Promise<void> {
await page.mouse.click(20, VIEWPORT.height - 40)
}
/** Opens an item's window, with its row in the middle of the screen so the window has room below it. */
async function openItem(page: Page, name: string): Promise<void> {
await item(page, name).evaluate(el => el.scrollIntoView({ block: 'center' }))
await itemName(page, name).click()
await expect(itemWindow(page)).toBeVisible()
await settle(page)
}
async function closeItem(page: Page): Promise<void> {
await itemWindow(page).getByRole('button', { name: 'Close', exact: true }).click()
await expect(itemWindow(page)).toHaveCount(0)
await settle(page)
}
// ── Putting the seed back ────────────────────────────────────────────────────
/** The packing list as the seed and the fixtures left it, taken in beforeAll. */
@@ -198,6 +228,9 @@ async function startLists(page: Page): Promise<void> {
interface PackingRow {
id: number
name: string
category: string | null
is_private?: number | boolean
contributors?: { user_id: number; username: string }[]
}
async function packingItems(page: Page): Promise<PackingRow[]> {
@@ -207,6 +240,24 @@ async function packingItems(page: Page): Promise<PackingRow[]> {
return body.items ?? []
}
/** Puts items back into the group pool, the seed's tier for every item. */
async function shareWithEveryone(page: Page, rows: PackingRow[]): Promise<void> {
const { tripId } = seededTrip()
for (const row of rows) {
await page.request.put(`/api/trips/${tripId}/packing/${row.id}/sharing`, { data: { visibility: 'common', recipient_ids: [] } })
}
}
/** Takes a member off the people who bring an item. */
async function dropBringer(page: Page, itemName: string, username: string): Promise<void> {
const { tripId } = seededTrip()
const row = (await packingItems(page)).find(x => x.name === itemName)
if (!row) return
for (const c of (row.contributors ?? []).filter(x => x.username === username)) {
await page.request.delete(`/api/trips/${tripId}/packing/${row.id}/contributors/${c.user_id}`)
}
}
async function deleteTemplate(page: Page, name: string): Promise<void> {
const res = await page.request.get('/api/admin/packing-templates')
const body = (await res.json()) as { templates?: { id: number; name: string }[] }
@@ -266,7 +317,7 @@ const SCRIPTS: Record<string, GuideScript> = {
await cat(p, NEW_LIST).getByRole('button', { name: 'Add item' }).click()
const field = p.getByPlaceholder('Item name...')
await typeInto(p, field, FIRST_ITEM)
// Enter renames the list's '...' row rather than adding a second one,
// Enter fills the list's empty row rather than adding a second one,
// and leaves the field open; Escape is how it closes.
await field.press('Enter')
await expect(item(p, FIRST_ITEM)).toBeVisible({ timeout: 20_000 })
@@ -275,18 +326,19 @@ const SCRIPTS: Record<string, GuideScript> = {
},
},
{
prepare: async p => { await onlyRow(p).hover() },
// A click on the name renames it; the row has no pencil of its own.
target: p => onlyRow(p).getByRole('button', { name: FIRST_ITEM }),
prepare: async p => {
await onlyRow(p).locator('button[aria-haspopup="dialog"]').click()
await expect(itemWindow(p)).toBeVisible()
await settle(p)
},
// The name at the top of the window is the field the text means.
target: p => itemWindow(p).getByRole('textbox', { name: 'Rename' }),
act: async p => {
await onlyRow(p).getByRole('button', { name: FIRST_ITEM }).click()
// While editing, the name is the row's first input; the quantity and
// the weight come after it.
const field = onlyRow(p).locator('input').first()
const field = itemWindow(p).getByRole('textbox', { name: 'Rename' })
await typeInto(p, field, RENAMED_ITEM)
await field.press('Enter')
await expect(item(p, RENAMED_ITEM)).toBeVisible({ timeout: 20_000 })
await settle(p)
await closeItem(p)
},
},
{
@@ -301,8 +353,11 @@ const SCRIPTS: Record<string, GuideScript> = {
},
},
{
// Shown on the first list: the new one is the last card on the page, and
// its menu would run past the bottom of the screen.
prepare: async p => {
await catMenu(p, NEW_LIST).click()
await catHeader(p, FIRST_LIST).evaluate(el => el.scrollIntoView({ block: 'center' }))
await catMenu(p, FIRST_LIST).click()
await expect(p.getByRole('button', { name: 'Delete List' })).toBeVisible()
await beat(p, 300)
},
@@ -310,14 +365,15 @@ const SCRIPTS: Record<string, GuideScript> = {
// The pointer rests on the three dots that opened it, not on an entry.
// Moved by coordinates: the menu's click-catcher covers the button.
hover: async p => {
const b = await catMenu(p, NEW_LIST).boundingBox()
const b = await catMenu(p, FIRST_LIST).boundingBox()
if (b) await p.mouse.move(b.x + b.width / 2, b.y + b.height / 2)
},
act: async p => {
// The menu sits over a full-viewport catcher; a click in the corner
// closes it without deleting the list the picture was just taken of.
await p.mouse.click(20, VIEWPORT.height - 40)
// A click in the corner closes the menu without deleting the list the picture was just taken of.
await clickAside(p)
await expect(p.getByRole('button', { name: 'Delete List' })).toHaveCount(0)
// Back to the new list for the after-picture.
await cat(p, NEW_LIST).evaluate(el => el.scrollIntoView({ block: 'center' }))
await settle(p)
},
},
@@ -328,6 +384,61 @@ const SCRIPTS: Record<string, GuideScript> = {
await p.request.put(`/api/trips/${tripId}/packing/category-assignees/${encodeURIComponent(NEW_LIST)}`, { data: { user_ids: [] } })
},
},
'edit-packing-item': {
guide: guide('edit-packing-item'),
start: async p => {
await dropBringer(p, EDIT_ITEM, MEMBER)
await startLists(p)
},
steps: [
{
target: p => itemName(p, EDIT_ITEM),
act: p => openItem(p, EDIT_ITEM),
},
only(p => itemWindow(p).getByRole('textbox', { name: 'Rename' })),
{
prepare: async p => {
await windowLine(p, 'List').getByRole('button').click()
await expect(choiceList(p)).toBeVisible()
await settle(p)
},
target: choiceList,
// The pointer on another list, as if about to pick it.
hover: async p => { await choiceList(p).getByRole('button', { name: FIRST_LIST, exact: true }).hover() },
act: async p => {
// Shown, not picked: the item would leave its row and the window with it.
await windowLine(p, 'List').getByRole('button').click()
await expect(choiceList(p)).toHaveCount(0)
await settle(p)
},
},
{
prepare: async p => {
await windowLine(p, 'Brought by').getByRole('button').click()
await expect(choiceList(p)).toBeVisible()
await settle(p)
},
target: choiceList,
hover: async p => { await choiceList(p).getByRole('button', { name: MEMBER, exact: true }).hover() },
act: async p => {
await choiceList(p).getByRole('button', { name: MEMBER, exact: true }).click()
await expect(windowLine(p, 'Brought by')).toContainText(MEMBER, { timeout: 20_000 })
await windowLine(p, 'Brought by').getByRole('button').click()
await expect(choiceList(p)).toHaveCount(0)
await settle(p)
},
},
{
target: p => itemWindow(p).getByRole('button', { name: 'Delete', exact: true }),
// Shown, not pressed: the window closes with its cross.
act: closeItem,
},
],
cleanup: async p => {
await dropBringer(p, EDIT_ITEM, MEMBER)
await resetPacking(p)
},
},
'arrange-packing-list': {
guide: guide('arrange-packing-list'),
start: startLists,
@@ -355,10 +466,14 @@ const SCRIPTS: Record<string, GuideScript> = {
},
},
{
target: p => p.getByRole('button', { name: 'A to Z' }),
prepare: openListsMenu,
target: p => listsMenu(p).getByRole('button', { name: 'A to Z' }),
act: async p => {
await p.getByRole('button', { name: 'A to Z' }).click()
await expect(p.getByRole('button', { name: 'A to Z' })).toHaveAttribute('aria-pressed', 'true')
await listsMenu(p).getByRole('button', { name: 'A to Z' }).click()
// The order is a switch with a tick; the menu stays open for the next one.
await clickAside(p)
await expect(listsMenu(p)).toHaveCount(0)
await expect(cat(p, SORTED_LIST).locator('.packing-item-row').first()).toContainText(SORTED_FIRST, { timeout: 20_000 })
await settle(p)
},
},
@@ -375,17 +490,14 @@ const SCRIPTS: Record<string, GuideScript> = {
start: startLists,
steps: [
{
// The grip is a div, so the tick box is the row's first button.
target: p => item(p, OPEN_ITEM).getByRole('button').first(),
target: p => item(p, OPEN_ITEM).locator('.packing-check'),
act: async p => {
await item(p, OPEN_ITEM).getByRole('button').first().click()
await item(p, OPEN_ITEM).locator('.packing-check').click()
await expect(item(p, OPEN_ITEM).locator('.packing-check')).toHaveAttribute('aria-pressed', 'true', { timeout: 20_000 })
await settle(p)
},
},
// The count and the percentage, with the bar beside them: the whole card is
// wider than any frame and would lose both at its edges.
only(progressCount),
only(progressLine),
{
prepare: async p => {
await catMenu(p, CHECK_ALL_LIST).click()
@@ -400,23 +512,27 @@ const SCRIPTS: Record<string, GuideScript> = {
},
},
{
target: p => p.getByRole('button', { name: 'Open', exact: true }),
prepare: openListsMenu,
target: p => listsMenu(p).getByRole('button', { name: 'Hide packed' }),
act: async p => {
await p.getByRole('button', { name: 'Open', exact: true }).click()
await listsMenu(p).getByRole('button', { name: 'Hide packed' }).click()
await clickAside(p)
await expect(listsMenu(p)).toHaveCount(0)
await expect(item(p, PACKED_ITEM)).toHaveCount(0, { timeout: 20_000 })
await settle(p)
},
},
{
target: p => p.getByRole('button', { name: CLEAR_CHECKED }),
prepare: openListsMenu,
target: p => listsMenu(p).getByRole('button', { name: CLEAR_CHECKED }),
act: async p => {
// A native window.confirm, which cannot be pictured. The step shows the
// button and answers the browser with Cancel: with the Open filter on,
// the screen looks the same either way, and the seed's ticked items
// (most of the list) stay where they are for the guides after this one.
// entry and answers the browser with Cancel: with the packed items
// hidden, the screen looks the same either way, and the seed's ticked
// items (most of the list) stay where they are for the guides after this one.
p.once('dialog', d => { void d.dismiss() })
await p.getByRole('button', { name: CLEAR_CHECKED }).click()
await expect(p.getByRole('button', { name: CLEAR_CHECKED })).toBeVisible()
await listsMenu(p).getByRole('button', { name: CLEAR_CHECKED }).click()
await expect(listsMenu(p)).toHaveCount(0)
await settle(p)
},
},
@@ -432,39 +548,34 @@ const SCRIPTS: Record<string, GuideScript> = {
},
steps: [
{
prepare: async p => { await item(p, PIECES_ITEM).hover() },
target: p => quantityField(p, PIECES_ITEM),
target: p => itemName(p, PIECES_ITEM),
act: p => openItem(p, PIECES_ITEM),
},
{
target: p => itemWindow(p).getByRole('group', { name: 'Qty' }),
act: async p => {
const field = quantityField(p, PIECES_ITEM)
const field = itemWindow(p).getByRole('group', { name: 'Qty' }).locator('input')
await typeInto(p, field, String(PIECES))
await field.press('Enter')
await expect(piecesCounter(p, PIECES_ITEM)).toHaveAccessibleName(`0 of ${PIECES} packed`, { timeout: 20_000 })
await expect(itemWindow(p).getByRole('group', { name: `0 of ${PIECES} packed` })).toBeVisible({ timeout: 20_000 })
await settle(p)
},
},
{
target: p => piecesCounter(p, PIECES_ITEM),
target: p => itemWindow(p).getByRole('group', { name: / of \d+ packed$/ }),
act: async p => {
for (let n = 1; n <= 3; n++) {
await item(p, PIECES_ITEM).getByRole('button', { name: 'Pack one more' }).click()
await expect(piecesCounter(p, PIECES_ITEM)).toHaveAccessibleName(`${n} of ${PIECES} packed`, { timeout: 20_000 })
await itemWindow(p).getByRole('button', { name: 'Pack one more' }).click()
await expect(itemWindow(p).getByRole('group', { name: `${n} of ${PIECES} packed` })).toBeVisible({ timeout: 20_000 })
}
await settle(p)
},
},
{
// Partly packed: the counter in the accent, the tick box outlined in it.
// Partly packed: the count in the row, the tick box outlined in the accent.
prepare: closeItem,
target: p => item(p, PIECES_ITEM),
act: async p => {
for (let n = 4; n <= PIECES; n++) {
await item(p, PIECES_ITEM).getByRole('button', { name: 'Pack one more' }).click()
await expect(piecesCounter(p, PIECES_ITEM)).toHaveAccessibleName(`${n} of ${PIECES} packed`, { timeout: 20_000 })
}
await expect(item(p, PIECES_ITEM).locator('.packing-check')).toHaveAttribute('aria-pressed', 'true', { timeout: 20_000 })
await settle(p)
},
},
only(p => item(p, PIECES_ITEM)),
],
cleanup: resetPacking,
},
@@ -473,26 +584,32 @@ const SCRIPTS: Record<string, GuideScript> = {
start: startLists,
steps: [
{
target: p => p.getByRole('button', { name: 'Apply template' }),
target: listsMenuButton,
act: async p => {
await p.getByRole('button', { name: 'Apply template' }).click()
await expect(p.locator('.trek-menu-enter').last()).toBeVisible()
await openListsMenu(p)
await settle(p)
},
},
{
target: p => p.locator('.trek-menu-enter').last(),
prepare: async p => {
await listsMenu(p).getByRole('button', { name: 'Apply template' }).click()
await expect(listsMenu(p).getByRole('button', { name: new RegExp(`^${TEMPLATE.name}`) })).toBeVisible()
await settle(p)
},
target: p => listsMenu(p).getByRole('button', { name: new RegExp(`^${TEMPLATE.name}`) }),
act: async p => {
await p.locator('.trek-menu-enter').last().getByRole('button', { name: new RegExp(`^${TEMPLATE.name}`) }).click()
await listsMenu(p).getByRole('button', { name: new RegExp(`^${TEMPLATE.name}`) }).click()
await expect(cat(p, TEMPLATE.category)).toBeVisible({ timeout: 30_000 })
await expect(listsMenu(p)).toHaveCount(0)
await settle(p)
},
},
only(p => p.getByRole('button', { name: /^Shared/ })),
{
target: p => p.getByRole('button', { name: 'Save as template' }),
prepare: openListsMenu,
target: p => listsMenu(p).getByRole('button', { name: 'Save as template' }),
act: async p => {
await p.getByRole('button', { name: 'Save as template' }).click()
await listsMenu(p).getByRole('button', { name: 'Save as template' }).click()
const field = p.getByPlaceholder('Template name')
await typeInto(p, field, SAVED_TEMPLATE)
await nameDialog(p, 'Save').click()
@@ -511,10 +628,10 @@ const SCRIPTS: Record<string, GuideScript> = {
start: startLists,
steps: [
{
// An icon at the right end of the bar, named Import by its label and tooltip.
target: p => p.getByRole('button', { name: 'Import', exact: true }),
prepare: openListsMenu,
target: p => listsMenu(p).getByRole('button', { name: 'Import', exact: true }),
act: async p => {
await p.getByRole('button', { name: 'Import', exact: true }).click()
await listsMenu(p).getByRole('button', { name: 'Import', exact: true }).click()
await expect(importCard(p)).toBeVisible()
await settle(p)
},
@@ -555,19 +672,21 @@ const SCRIPTS: Record<string, GuideScript> = {
start: startLists,
steps: [
{
target: p => p.getByRole('button', { name: 'Export', exact: true }),
target: listsMenuButton,
act: async p => {
await p.getByRole('button', { name: 'Export', exact: true }).click()
await expect(exportMenu(p)).toBeVisible()
await openListsMenu(p)
await settle(p)
},
},
// The two file entries download at once; the step shows them, it does not press them.
only(exportMenu),
{
target: p => exportMenu(p).getByRole('menuitem', { name: 'Print or save as PDF' }),
target: listsMenu,
hover: async p => { await listsMenu(p).getByRole('button', { name: 'CSV for import (.csv)' }).hover() },
},
{
target: p => listsMenu(p).getByRole('button', { name: 'Print or save as PDF' }),
act: async p => {
await exportMenu(p).getByRole('menuitem', { name: 'Print or save as PDF' }).click()
await listsMenu(p).getByRole('button', { name: 'Print or save as PDF' }).click()
await expect(printFrame(p).locator('h1')).toBeVisible({ timeout: 15_000 })
// The page carries the app's own Poppins; the result picture waits for it.
await printFrame(p).locator('body').evaluate(async () => { await document.fonts.ready })
@@ -577,7 +696,7 @@ const SCRIPTS: Record<string, GuideScript> = {
// Pressing it opens the operating system's print dialog, which is not part
// of the picture; the button is shown, not pressed. The result picture is the
// preview itself.
only(p => p.getByRole('button', { name: 'Print or save as PDF' })),
only(p => p.getByRole('button', { name: 'Print or save as PDF' }).last()),
],
cleanup: async p => {
await p.getByRole('button', { name: 'Close', exact: true }).first().click()
@@ -598,24 +717,17 @@ const SCRIPTS: Record<string, GuideScript> = {
},
},
{
prepare: async p => {
await item(p, SHARED_ITEM).hover()
await rowMenu(p, SHARED_ITEM).click()
await expect(rowMenuSharing(p)).toBeVisible()
await beat(p, 300)
},
target: rowMenuSharing,
act: async p => {
await rowMenuSharing(p).click()
await expect(shareMenu(p)).toBeVisible()
await settle(p)
},
prepare: p => openItem(p, SHARED_ITEM),
// The whole line: its label and the three choices.
target: p => itemWindow(p).getByRole('radiogroup', { name: 'Visible to' }).locator('xpath=../..'),
},
{
target: shareMenu,
target: p => itemWindow(p).getByRole('radio', { name: 'Only me' }),
act: async p => {
await shareMenu(p).getByRole('button', { name: /^Personal/ }).click()
await itemWindow(p).getByRole('radio', { name: 'Only me' }).click()
// The row leaves the shared list, and its window goes with it.
await expect(item(p, SHARED_ITEM)).toHaveCount(0, { timeout: 20_000 })
await expect(itemWindow(p)).toHaveCount(0)
await settle(p)
},
},
@@ -629,31 +741,80 @@ const SCRIPTS: Record<string, GuideScript> = {
},
{
prepare: async p => {
await item(p, SHARED_ITEM).hover()
await rowMenu(p, SHARED_ITEM).click()
await rowMenuSharing(p).click()
await expect(shareMenu(p)).toBeVisible()
await openItem(p, SHARED_ITEM)
await itemWindow(p).getByRole('radio', { name: 'Selected' }).click()
await expect(choiceList(p)).toBeVisible()
await settle(p)
},
target: choiceList,
hover: async p => { await choiceList(p).getByRole('button', { name: MEMBER, exact: true }).hover() },
act: async p => {
await choiceList(p).getByRole('button', { name: MEMBER, exact: true }).click()
await expect(item(p, SHARED_ITEM).getByLabel('shared with 1')).toBeVisible({ timeout: 20_000 })
await closeItem(p)
},
},
],
cleanup: async p => {
await shareWithEveryone(p, (await packingItems(p)).filter(x => x.name === SHARED_ITEM))
await resetPacking(p)
},
},
'share-packing-list': {
guide: guide('share-packing-list'),
start: async p => {
await shareWithEveryone(p, (await packingItems(p)).filter(x => x.category === SHARE_LIST))
await startLists(p)
},
steps: [
{
prepare: async p => {
await catMenu(p, SHARE_LIST).click()
await expect(p.getByRole('button', { name: 'Sharing for Whole List' })).toBeVisible()
await beat(p, 300)
},
target: p => shareMenu(p).getByRole('button', { name: MEMBER }),
target: p => p.getByRole('button', { name: 'Sharing for Whole List' }),
act: async p => {
await shareMenu(p).getByRole('button', { name: MEMBER }).click()
// Ticking a name leaves the menu open on purpose; its catcher closes it,
// and the item menu under it has one of its own.
await shareOverlay(p).click({ position: { x: 5, y: 5 } })
await p.mouse.click(20, VIEWPORT.height - 40)
await expect(p.locator('.trek-menu-enter')).toHaveCount(0)
await expect(item(p, SHARED_ITEM).getByLabel('shared with 1')).toBeVisible({ timeout: 20_000 })
await p.getByRole('button', { name: 'Sharing for Whole List' }).click()
await expect(listSharing(p)).toBeVisible()
await settle(p)
},
},
{
// The box of the three tiers; the list starts on Shared, where the seed has it.
target: p => listSharing(p).getByRole('button', { name: /^Shared with/ }).locator('xpath=..'),
hover: async p => { await listSharing(p).getByRole('button', { name: /^Shared with/ }).hover() },
act: async p => {
await listSharing(p).getByRole('button', { name: /^Shared with/ }).click()
await expect(listSharing(p).getByRole('button', { name: MEMBER, exact: true })).toBeVisible()
await settle(p)
},
},
{
target: p => listSharing(p).getByRole('button', { name: MEMBER, exact: true }),
act: async p => {
await listSharing(p).getByRole('button', { name: MEMBER, exact: true }).click()
await expect(listSharing(p).getByRole('button', { name: MEMBER, exact: true })).toHaveAttribute('aria-pressed', 'true')
await settle(p)
},
},
{
target: p => listSharing(p).getByRole('button', { name: 'Apply to list' }),
act: async p => {
await listSharing(p).getByRole('button', { name: 'Apply to list' }).click()
await expect(listSharing(p)).toHaveCount(0, { timeout: 30_000 })
// The confirmation is a toast; the after-picture waits for it to go.
const done = p.getByText(`Sharing changed for "${SHARE_LIST}"`)
await expect(done).toBeVisible({ timeout: 20_000 })
await p.getByRole('button', { name: /^My list/ }).click()
await expect(cat(p, SHARE_LIST)).toBeVisible({ timeout: 20_000 })
await expect(done).toHaveCount(0, { timeout: 20_000 })
await settle(p)
},
},
],
cleanup: async p => {
const { tripId } = seededTrip()
const row = (await packingItems(p)).find(x => x.name === SHARED_ITEM)
if (row) {
await p.request.put(`/api/trips/${tripId}/packing/${row.id}/sharing`, { data: { visibility: 'common', recipient_ids: [] } })
}
await shareWithEveryone(p, (await packingItems(p)).filter(x => x.category === SHARE_LIST))
await resetPacking(p)
},
},
@@ -666,35 +827,38 @@ const SCRIPTS: Record<string, GuideScript> = {
},
steps: [
{
prepare: p => openItem(p, BAG_ITEM),
// The weight field's placeholder really is a dash: it is the app's own
// string, not prose, so it is matched exactly as rendered.
target: p => item(p, BAG_ITEM).getByPlaceholder('—'),
// string, not prose, so it is matched exactly as rendered. The ring takes
// the whole pill, the grams with it.
target: p => itemWindow(p).getByPlaceholder('—').locator('xpath=..'),
act: async p => {
const field = item(p, BAG_ITEM).getByPlaceholder('—')
const field = itemWindow(p).getByPlaceholder('—')
await typeInto(p, field, '620')
await field.press('Enter')
await expect(field).toHaveValue('620', { timeout: 20_000 })
await settle(p)
},
},
{
prepare: async p => { await item(p, BAG_ITEM).hover() },
// The circle is dashed with a parcel in it while the item is in no bag.
target: p => item(p, BAG_ITEM).locator('button:has(svg.lucide-package)'),
target: p => windowLine(p, 'Bag').getByRole('button'),
act: async p => {
await item(p, BAG_ITEM).locator('button:has(svg.lucide-package)').click()
await expect(bagPicker(p).getByRole('button', { name: 'Add bag' })).toBeVisible()
await windowLine(p, 'Bag').getByRole('button').click()
await expect(itemWindow(p).getByPlaceholder('Add bag')).toBeVisible()
await settle(p)
},
},
{
target: p => bagPicker(p).getByRole('button', { name: 'Add bag' }),
// The line at the end of the bag list, with its round add button.
target: p => itemWindow(p).getByPlaceholder('Add bag').locator('xpath=..'),
act: async p => {
await bagPicker(p).getByRole('button', { name: 'Add bag' }).click()
const field = bagPicker(p).getByPlaceholder('Bag name...')
const field = itemWindow(p).getByPlaceholder('Add bag')
await typeInto(p, field, BAG)
await field.press('Enter')
await expect(windowLine(p, 'Bag')).toContainText(BAG, { timeout: 30_000 })
// The window repeats Total weight and the bag's name, so it goes before the card is looked for.
await closeItem(p)
await expect(bagSidebar(p)).toBeVisible({ timeout: 30_000 })
await expect(bagPicker(p)).toHaveCount(0)
await settle(p)
},
},
@@ -722,7 +886,7 @@ const SCRIPTS: Record<string, GuideScript> = {
await bagSidebar(p).locator('button[style*="dashed"]').first().click()
await bagMemberPicker(p).getByRole('button', { name: MEMBER }).click()
// The picker closes on a click anywhere beside it.
await p.mouse.click(20, VIEWPORT.height - 40)
await clickAside(p)
await expect(bagSidebar(p).getByRole('button', { name: MEMBER })).toBeVisible({ timeout: 20_000 })
// A bag with someone on it fills Per person at the foot of the card.
await expect(p.getByText('Per person', { exact: true })).toBeVisible({ timeout: 20_000 })
+87 -15
View File
@@ -310,6 +310,32 @@ interface TrekGlMap {
easeTo: (o: { bearing: number; pitch: number; duration: number }) => unknown
}
/** Turn the GL map to a bearing at once, and wait until it has painted it. */
/**
* How far the compass guide turns the map. The vector labels stay level at any
* bearing, and the compass icon is drawn leaning 45° to the right, so at 35°
* the map read as north up and the arrow as upright. At 70° the coast lies
* visibly askew and the arrow leans the other way.
*/
const TURN = 70
async function turnMap(page: Page, bearing: number): Promise<void> {
await page.evaluate(b => {
const m = (window as unknown as { __trek_map?: TrekGlMap }).__trek_map
if (!m) throw new Error('no GL map on the page')
m.easeTo({ bearing: b, pitch: 0, duration: 0 })
}, bearing)
await page.waitForFunction(b => {
const m = (window as unknown as { __trek_map?: TrekGlMap }).__trek_map
return !!m && Math.abs(m.getBearing() - b) < 0.5 && !m.isMoving()
}, bearing)
await page.evaluate(() => new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r))))
}
/** The GL map's bearing now. */
const mapBearing = (page: Page): Promise<number> =>
page.evaluate(() => (window as unknown as { __trek_map?: TrekGlMap }).__trek_map?.getBearing() ?? 0)
/** Wait until the GL map has its style, its tiles and a still camera. */
async function glMapIdle(page: Page): Promise<void> {
await page.waitForFunction(
@@ -369,6 +395,8 @@ let found = ''
let tourOnDay: TourOnDay | null = null
let line = { index: 0, x: 0, y: 0 }
let clickedTour = ''
/** Why the Dawarich connection could not be made (no media.env), for the one guide that needs it. */
let dawarichMissing: Error | null = null
const NEW_PLACE = 'Lunch stop'
@@ -421,6 +449,28 @@ const SCRIPTS: Record<string, GuideScript> = {
// captureGuide hovers the target itself; this only makes sure the card
// is up before the shot rather than a frame after it.
prepare: async p => {
// The card asks for the full photo, not the pin's thumb, and for some
// seeded places the photo proxy answers nothing: the card then shows a
// broken image. Walk the reachable photo pins until one card shows its
// photo, and keep that pin for the steps after this one.
const total = await photoPins(p).count()
for (let i = 0; i < total; i++) {
const candidate = photoPins(p).nth(i)
try {
await candidate.hover({ timeout: 1500 })
} catch {
continue
}
if (!(await hoverCard(p).isVisible().catch(() => false))) continue
const loaded = await expect.poll(
() => hoverCard(p).locator('img').evaluateAll(imgs => imgs.length > 0 && imgs.every(img => (img as HTMLImageElement).complete && (img as HTMLImageElement).naturalWidth > 0)),
{ timeout: 6_000 },
).toBe(true).then(() => true, () => false)
if (!loaded) continue
await p.locator('#trek-map [data-help-pin]').evaluateAll(els => els.forEach(el => el.removeAttribute('data-help-pin')))
await candidate.evaluate(el => el.setAttribute('data-help-pin', ''))
break
}
await markerPin(p).hover()
await expect(hoverCard(p)).toBeVisible({ timeout: 10_000 })
},
@@ -451,6 +501,13 @@ const SCRIPTS: Record<string, GuideScript> = {
await settle(p)
},
target: p => badged(p, 1),
// The badge is the subject, not the pin's card: the pointer waits on
// an empty spot, so no hover card covers the numbers.
hover: async p => {
const box = await map(p).boundingBox()
if (!box) throw new Error('the map has no box')
await p.mouse.move(box.x + EMPTY.x, box.y + EMPTY.y)
},
},
{
// Picture only, like the other drags in this family: HTML5 drag is what
@@ -726,7 +783,10 @@ const SCRIPTS: Record<string, GuideScript> = {
// along the Shinkansen and the walks through the cities vanish under the
// pins, so the map is framed on a day before the button is pressed;
// nothing fits the map to the trail.
start: openOnTokyo,
start: async p => {
if (dawarichMissing) throw dawarichMissing
await openOnTokyo(p)
},
steps: [
{
target: trailPill,
@@ -873,22 +933,28 @@ const SCRIPTS: Record<string, GuideScript> = {
{
// The turn itself is the map's own camera move rather than a synthetic
// right-button drag: a drag has to start on bare canvas, and the pins,
// the two floating columns and the explore pill all sit over it. 35°
// the two floating columns and the explore pill all sit over it. 70°
// is enough for the streets to lie visibly askew and the arrow to lean.
// A fit of the map to the day (MapLibre's fitBounds) also puts the
// bearing back to north, and one can still land after the turn while the
// trip's data settles: the earlier pictures caught the map upright for
// exactly that reason. So the turn is made again until it holds through
// a settle, and once more right before the shot.
prepare: async p => {
await p.evaluate(() => {
const m = (window as unknown as { __trek_map?: TrekGlMap }).__trek_map
if (!m) throw new Error('no GL map on the page')
m.easeTo({ bearing: 35, pitch: 0, duration: 0 })
})
await p.waitForFunction(() => {
const m = (window as unknown as { __trek_map?: TrekGlMap }).__trek_map
return !!m && Math.abs(m.getBearing() - 35) < 0.5 && !m.isMoving()
})
await settle(p)
for (let attempt = 0; attempt < 4; attempt++) {
await turnMap(p, TURN)
await settle(p)
if (Math.abs((await mapBearing(p)) - TURN) < 0.5) break
}
},
target: compassPill,
// The loop: the map turning from north to the still's 35°, the arrow
hover: async p => {
await resetNorth(p).hover()
if (Math.abs((await mapBearing(p)) - TURN) >= 0.5) await turnMap(p, TURN)
// The arrow follows the bearing with a 100 ms transition.
await p.waitForTimeout(300)
},
// The loop: the map turning from north to the still's bearing, the arrow
// leaning with it, and a pointer dragging sideways as a right-button
// turn would. The camera is moved by the map's own API, a notch a
// frame, for the reason the still's preparation gives.
@@ -915,7 +981,7 @@ const SCRIPTS: Record<string, GuideScript> = {
for (let i = 0; i < 3; i++) await frame()
for (let i = 1; i <= 14; i++) {
await p.mouse.move(x + (120 * i) / 14, y)
await turnTo((35 * i) / 14)
await turnTo((TURN * i) / 14)
await frame()
}
for (let i = 0; i < 4; i++) await frame()
@@ -952,7 +1018,13 @@ test.beforeAll(async ({ request }) => {
tourOnDay = await ensureTourOnDay(request)
// The recorded route: the addon on, the signed-in user connected to the
// Dawarich from media.env, the synthetic recording of the trip uploaded.
await ensureDawarichConnection(request)
// Without media.env it cannot be made; the Dawarich guide then fails at its
// start with the reason, and every other guide of the file still runs.
try {
await ensureDawarichConnection(request)
} catch (err) {
dawarichMissing = err instanceof Error ? err : new Error(String(err))
}
})
test.afterAll(async ({ request }) => {
+179 -33
View File
@@ -85,10 +85,25 @@ const weekday = (offset: number) => long(offset).split(',')[0]
const hoursRow = (page: Page) => card(page).locator('button:has(svg.lucide-clock)')
/** The hours block: the row and, once unfolded, the week in its place. */
const hoursBox = (page: Page) => section(page, 'Opening Hours')
/** The round picture in the head; its name says whether a picture of your own is set. */
const avatar = (page: Page) => card(page).getByRole('button', { name: /^(Upload image|Change image)$/ })
/** The popover the picture opens when the place has photos among its files. */
const imageChooser = (page: Page) => page.getByRole('dialog', { name: 'Choose a picture' })
/** Edit, the dark button at the right end of the card's footer. */
const editButton = (page: Page) => footer(page).getByRole('button', { name: 'Edit', exact: true })
/** Update, the place form's save button once the place exists. */
const updateButton = (page: Page) => modal(page).getByRole('button', { name: 'Update', exact: true })
/** The three dots of the footer: Remove from Day and Delete live there. */
const moreButton = (page: Page) => footer(page).getByRole('button', { name: 'More options', exact: true })
/** Pick a picture in the place form: the tiles and the credit line under them. */
const picker = (page: Page) =>
modal(page).getByText('Pick a picture', { exact: true }).first().locator('xpath=ancestor::section[1]')
/** The picker's first tile, which takes a picture from the device. */
const uploadTile = (page: Page) => picker(page).getByRole('button', { name: 'Upload image', exact: true })
/** The fold chevron in the card's head; its name follows the state. */
const foldButton = (page: Page, name: 'Collapse' | 'Expand') => head(page).getByRole('button', { name, exact: true })
/** The place the off-map guide puts in: an address a traveller typed, no pick from the search. */
const OFF_MAP = { name: 'Ramen at Karasuma Oike', address: 'Karasuma Oike, Nakagyo Ward, Kyoto', lat: '35.0107', lng: '135.7596' }
const NO_COORDINATES = 'No coordinates, so not on the map'
/** The form's location block: the address with its hint, and the two coordinate fields. */
const coordinates = (page: Page) => modal(page).getByRole('group', { name: 'Coordinates', exact: true })
const locationPanel = (page: Page) => coordinates(page).locator('xpath=..')
/** The place form's hours editor, found by its remove button (only there while editing). */
const hoursEditor = (page: Page) =>
modal(page).getByRole('button', { name: 'Remove opening hours' }).locator('xpath=ancestor::section[1]')
@@ -175,7 +190,7 @@ async function openStop(page: Page, name: string): Promise<void> {
// ── The seed over the API, for the cleanups ──────────────────────────────────
type ApiPlace = { id: number; name: string; lat?: number | null; lng?: number | null }
type ApiPlace = { id: number; name: string; lat?: number | null; lng?: number | null; image_url?: string | null }
type ApiAssignment = { id: number; place_id: number }
async function tripPlaces(page: Page): Promise<ApiPlace[]> {
@@ -216,6 +231,28 @@ const closeModal = async (page: Page): Promise<void> => {
const only = (target: (p: Page) => Locator) => ({ target })
/** Open the place's form from the card. */
async function openEditor(page: Page): Promise<void> {
await editButton(page).click()
await expect(updateButton(page)).toBeVisible()
await settle(page)
}
/** Save the form and wait until the place carries a picture of its own. */
async function saveWithPicture(page: Page, name: string): Promise<void> {
await updateButton(page).click()
await expect(modal(page)).toHaveCount(0, { timeout: 30_000 })
await expect.poll(async () => (await findPlace(page, name))?.image_url ?? null, { timeout: 30_000 }).toBeTruthy()
await settle(page)
}
async function removeOffMapPlace(page: Page): Promise<void> {
const { tripId } = seededTrip()
for (const place of (await tripPlaces(page)).filter(p => p.name === OFF_MAP.name)) {
await page.request.delete(`/api/trips/${tripId}/places/${place.id}`)
}
}
/**
* Take a place out of every collection it sits in.
*
@@ -300,26 +337,70 @@ const SCRIPTS: Record<string, GuideScript> = {
if (place) await p.request.delete(`/api/trips/${tripId}/places/${place.id}/rating`)
},
},
'place-image': {
guide: guide('place-image'),
start: p => openTrip(p, { day: null }),
'fold-place-card': {
guide: guide('fold-place-card'),
// From the stop, like the hero: the map then sits close enough that the
// highlighted marker is in the folded bar's picture.
start: async p => {
await openTrip(p, { day: null })
await selectDay(p, 1)
await openStop(p, 'Senso-ji Temple')
},
steps: [
{
target: p => row(p, 'Arashiyama Bamboo Grove'),
act: p => openPlace(p, 'Arashiyama Bamboo Grove'),
},
{
target: avatar,
target: p => foldButton(p, 'Collapse'),
act: async p => {
await card(p).locator('input[accept*="image/jpeg"]').setInputFiles(await coverFixture())
await expect(card(p).getByRole('button', { name: 'Remove image' })).toBeVisible({ timeout: 30_000 })
await foldButton(p, 'Collapse').click()
await expect(foldButton(p, 'Expand')).toBeVisible()
await expect(footer(p)).toBeHidden()
await settle(p)
},
},
only(head),
only(p => row(p, 'Arashiyama Bamboo Grove')),
{
// The map moved the way the step says, which brings the marker down to the bar.
prepare: async p => {
await p.mouse.move(960, 300)
await p.mouse.down()
await p.mouse.move(960, 450, { steps: 8 })
await p.mouse.move(960, 600, { steps: 8 })
await p.mouse.up()
await settle(p)
},
target: head,
},
{
target: p => foldButton(p, 'Expand'),
act: async p => {
await foldButton(p, 'Expand').click()
await expect(footer(p)).toBeVisible()
},
},
],
cleanup: p => patchPlace(p, 'Arashiyama Bamboo Grove', { image_url: null }),
},
'place-image': {
guide: guide('place-image'),
start: async p => {
await openTrip(p, { day: null })
await openPlace(p, 'Arashiyama Bamboo Grove')
},
steps: [
{ target: editButton, act: openEditor },
{
target: uploadTile,
act: async p => {
await picker(p).locator('input[type="file"]').setInputFiles(await coverFixture())
await expect(uploadTile(p)).toHaveAttribute('aria-pressed', 'true', { timeout: 30_000 })
await settle(p)
},
},
// Pointed at the label, not a tile: a hovered tile puts its own credit under the grid.
{ target: picker, hover: p => picker(p).getByText('Pick a picture', { exact: true }).hover() },
{ target: updateButton, act: p => saveWithPicture(p, 'Arashiyama Bamboo Grove') },
],
cleanup: async p => {
await closeModal(p)
await patchPlace(p, 'Arashiyama Bamboo Grove', { image_url: null })
},
},
'place-image-from-file': {
guide: guide('place-image-from-file'),
@@ -337,27 +418,28 @@ const SCRIPTS: Record<string, GuideScript> = {
target: p => section(p, 'Files'),
},
{
target: avatar,
act: async p => {
await avatar(p).click()
await expect(imageChooser(p)).toBeVisible()
// The thumbnails load as blobs one request later.
await expect(imageChooser(p).locator('img').first()).toBeVisible({ timeout: 20_000 })
prepare: async p => {
await openEditor(p)
// The attached photo's tile loads as a blob one request later.
await expect(picker(p).getByRole('button', { name: PHOTO_FILE, exact: true }).locator('img')).toBeVisible({ timeout: 20_000 })
await settle(p)
},
target: picker,
},
{
target: p => imageChooser(p).getByRole('button', { name: PHOTO_FILE, exact: true }),
target: p => picker(p).getByRole('button', { name: PHOTO_FILE, exact: true }),
act: async p => {
await imageChooser(p).getByRole('button', { name: PHOTO_FILE, exact: true }).click()
await expect(imageChooser(p)).toHaveCount(0)
await expect(card(p).getByRole('button', { name: 'Remove image' })).toBeVisible({ timeout: 30_000 })
await picker(p).getByRole('button', { name: PHOTO_FILE, exact: true }).click()
await expect(picker(p).getByRole('button', { name: PHOTO_FILE, exact: true })).toHaveAttribute('aria-pressed', 'true')
await settle(p)
},
},
only(head),
{ target: updateButton, act: p => saveWithPicture(p, PHOTO_PLACE) },
],
cleanup: p => removePlacePhoto(p.request),
cleanup: async p => {
await closeModal(p)
await removePlacePhoto(p.request)
},
},
'place-own-hours': {
guide: guide('place-own-hours'),
@@ -426,6 +508,61 @@ const SCRIPTS: Record<string, GuideScript> = {
await patchPlace(p, HOURS_PLACE, { phone: '', email: '', opening_hours: '' })
},
},
'place-off-map': {
guide: guide('place-off-map'),
// Put in over the API before the trip opens, the way a traveller leaves it:
// a name and a typed address, never picked from the search.
start: async p => {
await removeOffMapPlace(p)
const { tripId } = seededTrip()
const res = await p.request.post(`/api/trips/${tripId}/places`, { data: { name: OFF_MAP.name, address: OFF_MAP.address } })
if (!res.ok()) throw new Error(`could not add ${OFF_MAP.name}: ${res.status()} ${await res.text()}`)
await openTrip(p, { day: null })
},
steps: [
{
target: p => row(p, OFF_MAP.name),
act: async p => {
await openPlace(p, OFF_MAP.name)
await expect(head(p).getByText(NO_COORDINATES)).toBeVisible()
},
},
// Hovered for the picture, which brings up the tooltip with the way out.
only(p => head(p).getByText(NO_COORDINATES)),
{
prepare: async p => {
await openEditor(p)
await expect(locationPanel(p).getByText(/has no coordinates yet/)).toBeVisible()
},
target: locationPanel,
},
{
// Filled before the picture: the step is about the two values going in.
prepare: async p => {
await typeInto(p, coordinates(p).getByLabel('Latitude', { exact: true }), OFF_MAP.lat)
await typeInto(p, coordinates(p).getByLabel('Longitude', { exact: true }), OFF_MAP.lng)
await expect(locationPanel(p).getByText(/has no coordinates yet/)).toHaveCount(0)
await settle(p)
},
target: coordinates,
},
{
target: updateButton,
act: async p => {
await updateButton(p).click()
await expect(modal(p)).toHaveCount(0, { timeout: 20_000 })
await expect(head(p).getByText(NO_COORDINATES)).toHaveCount(0)
// Picked again, so the map goes to the new marker for the result.
await closeCard(p)
await openPlace(p, OFF_MAP.name)
},
},
],
cleanup: async p => {
await closeModal(p)
await removeOffMapPlace(p)
},
},
'place-day-assign': {
guide: guide('place-day-assign'),
start: p => openTrip(p, { day: null }),
@@ -445,7 +582,8 @@ const SCRIPTS: Record<string, GuideScript> = {
target: p => footer(p).getByRole('button', { name: 'Add to Day' }),
act: async p => {
await footer(p).getByRole('button', { name: 'Add to Day' }).click()
await expect(footer(p).getByRole('button', { name: 'Remove from Day' })).toBeVisible({ timeout: 20_000 })
await expect(stop(p, SPARE)).toBeVisible({ timeout: 20_000 })
await expect(footer(p).getByRole('button', { name: 'Add to Day' })).toHaveCount(0)
await settle(p)
},
},
@@ -453,9 +591,15 @@ const SCRIPTS: Record<string, GuideScript> = {
// last step's picture, and the arrow already says what to do.
{ target: p => stop(p, SPARE), dropTo: p => stop(p, 'Arashiyama Bamboo Grove') },
{
target: p => footer(p).getByRole('button', { name: 'Remove from Day' }),
// Remove from Day waits behind the three dots, so the menu is open for the picture.
prepare: async p => {
await moreButton(p).click()
await expect(p.getByRole('menu').getByRole('button', { name: 'Remove from Day' })).toBeVisible()
await settle(p)
},
target: p => p.getByRole('menu').getByRole('button', { name: 'Remove from Day' }),
act: async p => {
await footer(p).getByRole('button', { name: 'Remove from Day' }).click()
await p.getByRole('menu').getByRole('button', { name: 'Remove from Day' }).click()
await expect(footer(p).getByRole('button', { name: 'Add to Day' })).toBeVisible({ timeout: 20_000 })
await settle(p)
},
@@ -623,6 +767,8 @@ const SCRIPTS: Record<string, GuideScript> = {
act: async p => {
await p.keyboard.press('Escape')
await expect(p.getByRole('menu')).toHaveCount(0)
// Escape leaves the focus ring on Navigation, which the next picture would show.
await p.evaluate(() => (document.activeElement as HTMLElement | null)?.blur())
},
},
only(p => footer(p).getByRole('button', { name: 'Open Website' })),
+137 -28
View File
@@ -3,7 +3,9 @@ import { captureGuide, captureHero, beat, typeInto, settle, dragLoop, VIEWPORT,
import { seededTrip, gpxFixture } from './fixtures'
import { openTrip, modal, dialog, confirmDialog } from './trip-shared'
import { disconnectDawarich } from './external'
import { ensureDawarichStays, undoDawarichStays, setTours } from './fixtures-trip-places'
import {
ensureDawarichStays, undoDawarichStays, setTours, pinsKmlFixture, KML_PINS, ensureGuideTags, removeGuideTags, NEW_TAG,
} from './fixtures-trip-places'
import { tripPlacesContext, tripPlacesGuides } from '../../src/help/contexts/tripPlaces'
import type { HelpGuide } from '../../src/help/types'
@@ -11,10 +13,10 @@ import type { HelpGuide } from '../../src/help/types'
* Actions for the places column of a trip, keyed by the ids in
* `src/help/contexts/tripPlaces.ts`. They run on the seeded "Autumn in Japan"
* with the Tours add-on on, as on every install: the column has the Places and
* Tours switch, no Import file and no Tracks filter. The file import is
* pictured with Tours off, and the Dawarich stays with a connection, each for
* its own guide only; what a guide creates or switches it takes back again in
* `cleanup`, so the next one starts the same.
* Tours switch and no Tracks filter, and Import file sends a file with a line
* to the Tours import first. The Dawarich stays are pictured with a connection
* for their own guide only; what a guide creates or switches it takes back
* again in `cleanup`, so the next one starts the same.
*/
const guide = (id: string): HelpGuide => {
@@ -45,7 +47,7 @@ const head = (page: Page) =>
page.getByRole('button', { name: 'Import Places' }).locator('xpath=ancestor::div[contains(@class,"flex-col")][1]')
/** The list import's entry: List Import, Google List while Google is the only list provider. */
const LIST_IMPORT = /^(Google List|List Import)$/
/** The import button's menu: the list import, and Import file where Tours is off. */
/** The import button's menu: Import file and the list import. */
const importMenu = (page: Page) =>
page.locator('.trek-popover-enter').filter({ has: page.getByRole('button', { name: LIST_IMPORT }) }).last()
/** The Show dropdown (All, Unplanned, Planned; Tracks only with Tours off) and the list it opens. */
@@ -72,8 +74,30 @@ const importFileDialog = (page: Page) =>
page.getByRole('dialog').filter({ has: page.locator('input[type="file"][accept*=".gpx"]') })
/** ListImportModal, recognised by the link box. */
const listImportDialog = (page: Page) => page.getByRole('dialog').filter({ has: page.getByPlaceholder(/goo\.gl|naver/) })
/** The drop box of the file dialog: the dashed button that opens the file picker. */
const dropBox = (page: Page) => importFileDialog(page).locator('button.border-dashed').first()
/** The Tours import preview a file with a line opens, recognised by its points switch. */
const tourPreview = (page: Page) => page.getByRole('dialog').filter({ has: page.getByTestId('gpx-preview-points') })
/**
* Import file with Tours on: the Tours import's own file picker, a detached
* input, so the file goes in through the chooser it opens.
*/
async function pickImportFile(page: Page, file: string): Promise<void> {
const [chooser] = await Promise.all([
page.waitForEvent('filechooser'),
importMenu(page).getByRole('button', { name: 'Import file' }).click(),
])
await chooser.setFiles(file)
}
/** The tag guide's place, and the places that carry Must see before it starts. */
const TAGGED = 'Shibuya Crossing'
const ALREADY_TAGGED = ['Senso-ji Temple', 'Kinkaku-ji']
/** The group of tag pills in the place form. */
const tagGroup = (page: Page) => modal(page).getByRole('group', { name: 'Tags', exact: true })
/** The Tags card of the place form: the panel around the section with the pills. */
const tagsCard = (page: Page) => tagGroup(page).locator('xpath=ancestor::section[1]/..')
/** A tag's pill: its name button, which ticks it for the place. */
const tagPill = (page: Page, name: string) => tagGroup(page).getByRole('button', { name, exact: true })
const newTagField = (page: Page) => modal(page).getByRole('textbox', { name: 'New tag' })
const palette = (page: Page) => modal(page).getByRole('group', { name: 'Colour of Rainy day' })
/** The column itself: the header block around the search box. */
const column = (page: Page) => searchBox(page).locator('xpath=ancestor::div[contains(@class,"scroll") or @data-places-sidebar][1]')
@@ -496,11 +520,7 @@ const SCRIPTS: Record<string, GuideScript> = {
},
'import-places-file': {
guide: guide('import-places-file'),
// Import file is only in the menu of an install with the Tours add-on off.
start: async p => {
await setTours(p.request, false)
await openTrip(p)
},
start: p => openTrip(p),
steps: [
{
prepare: async p => {
@@ -509,35 +529,125 @@ const SCRIPTS: Record<string, GuideScript> = {
await beat(p, 300)
},
target: p => importMenu(p).getByRole('button', { name: 'Import file' }),
// A GPX with a track and two waypoints: the Tours import takes it first.
act: async p => {
await importMenu(p).getByRole('button', { name: 'Import file' }).click()
await expect(importFileDialog(p)).toBeVisible()
await pickImportFile(p, gpxFixture('arashiyama-loop'))
await expect(tourPreview(p)).toBeVisible({ timeout: 30_000 })
await settle(p)
},
},
{
target: p => p.getByTestId('gpx-preview-points'),
// Closing the preview stores nothing; the pins of the next step are what gets imported.
act: async p => {
await tourPreview(p).getByRole('button', { name: 'Cancel', exact: true }).click()
await expect(tourPreview(p)).toHaveCount(0)
await settle(p)
},
},
{
// A KML of pins only has no line for the Tours import, so Import file opens with it.
prepare: async p => {
await p.getByRole('button', { name: 'Import Places' }).click()
await expect(importMenu(p)).toBeVisible()
await pickImportFile(p, pinsKmlFixture())
await expect(importFileDialog(p).getByText('Points (Placemarks)')).toBeVisible({ timeout: 30_000 })
await settle(p)
},
target: importFileDialog,
},
{
target: p => importFileDialog(p).getByRole('button', { name: 'Import', exact: true }),
act: async p => {
await importFileDialog(p).getByRole('button', { name: 'Import', exact: true }).click()
// A KML answer keeps the dialog open with its summary; close it to show the new rows.
await expect(row(p, KML_PINS[0][0]).or(importFileDialog(p).getByText(/^Placemarks: /)).first())
.toBeVisible({ timeout: 60_000 })
if (await importFileDialog(p).isVisible().catch(() => false)) {
await importFileDialog(p).getByRole('button', { name: 'Cancel', exact: true }).click()
await expect(importFileDialog(p)).toHaveCount(0)
}
await expect(row(p, KML_PINS[0][0])).toBeVisible({ timeout: 20_000 })
await settle(p)
},
},
],
cleanup: p => deleteByName(p, ...KML_PINS.map(([name]) => name)),
},
'place-tags': {
guide: guide('place-tags'),
start: async p => {
await ensureGuideTags(p.request, seededTrip().tripId, ALREADY_TAGGED)
await openTrip(p)
},
steps: [
{
prepare: async p => {
await row(p, TAGGED).click({ button: 'right' })
await menu(p).getByRole('button', { name: 'Edit' }).click()
await expect(modal(p).getByPlaceholder('e.g. Eiffel Tower')).toHaveValue(TAGGED)
await tagPill(p, 'Must see').click()
await expect(tagPill(p, 'Must see')).toHaveAttribute('aria-pressed', 'true')
await settle(p)
},
target: tagsCard,
},
{
prepare: async p => {
await typeInto(p, newTagField(p), NEW_TAG)
await settle(p)
},
target: p => newTagField(p).locator('xpath=..'),
act: async p => {
await newTagField(p).press('Enter')
await expect(tagPill(p, NEW_TAG)).toHaveAttribute('aria-pressed', 'true', { timeout: 15_000 })
await settle(p)
},
},
{
prepare: async p => {
await importFileDialog(p).locator('input[type="file"]').setInputFiles(gpxFixture('arashiyama-loop'))
await expect(importFileDialog(p).getByText('Tracks (with path geometry)')).toBeVisible({ timeout: 15_000 })
await modal(p).getByRole('button', { name: 'Colour of Rainy day' }).click()
await expect(palette(p)).toBeVisible()
await beat(p, 300)
},
// The palette; the pill it colours sits right above it in the frame.
target: palette,
hover: p => palette(p).getByRole('button', { name: '#06b6d4' }).hover(),
act: async p => {
await palette(p).getByRole('button', { name: '#06b6d4' }).click()
await expect(palette(p)).toHaveCount(0)
await settle(p)
},
target: importFileDialog,
},
only(dropBox),
{
target: p => importFileDialog(p).getByRole('button', { name: 'Import', exact: true }),
target: p => modal(p).getByRole('button', { name: 'Update', exact: true }),
act: async p => {
await importFileDialog(p).getByRole('button', { name: 'Import', exact: true }).click()
await expect(importFileDialog(p)).toHaveCount(0, { timeout: 30_000 })
await expect(row(p, 'Arashiyama loop')).toBeVisible({ timeout: 20_000 })
await modal(p).getByRole('button', { name: 'Update', exact: true }).click()
await expect(modal(p)).toHaveCount(0, { timeout: 15_000 })
await settle(p)
},
},
{
prepare: async p => {
await categoryTrigger(p).click()
await expect(categoryList(p)).toBeVisible()
await categoryList(p).getByRole('button', { name: 'Must see', exact: true }).click()
await expect(categoryList(p).getByRole('button', { name: 'Clear filter' })).toBeVisible()
// The tags are at the foot of the list, under the categories.
await categoryList(p).evaluate(el => { el.scrollTop = el.scrollHeight })
await beat(p, 300)
},
target: categoryList,
// The list closes on a second click of its trigger; the filter stays.
act: async p => {
await categoryTrigger(p).click()
await expect(categoryList(p)).toHaveCount(0)
await expect(row(p, TAGGED)).toBeVisible()
await settle(p)
},
},
],
cleanup: async p => {
await deleteByName(p, 'Arashiyama loop', 'Togetsukyo Bridge', 'Okochi Sanso Villa')
await setTours(p.request, true)
},
cleanup: p => removeGuideTags(p.request, seededTrip().tripId),
},
'import-places-list': {
guide: guide('import-places-list'),
@@ -549,7 +659,6 @@ const SCRIPTS: Record<string, GuideScript> = {
await expect(importMenu(p)).toBeVisible()
await beat(p, 300)
},
// With Tours on, the list import is the menu's only entry.
target: p => importMenu(p).getByRole('button', { name: LIST_IMPORT }),
act: async p => {
await importMenu(p).getByRole('button', { name: LIST_IMPORT }).click()
+167 -20
View File
@@ -3,8 +3,9 @@ import { captureGuide, captureHero, settle, dragLoop, nudgeClock, VIEWPORT, type
import { seededTrip, ensureRoadtripFixtures } from './fixtures'
import { openTrip, modal, dialog } from './trip-shared'
import {
FERRY, FUEL_STOP, GOOGLE_ROUTE, HAZARD_TITLE, assignmentsOn, ensureFerry, ensureFuelStop, hideHazards, overnightFlight, placeIdOf,
removeFerry, removeFuelStop, removeImportedStops, removeNightAt, restoreFlight, stubGooglePreview, stubHazards,
FERRY, FUEL_STOP, GOOGLE_ROUTE, HAZARD_TITLE, PHOTO_STOP, assignmentsOn, ensureFerry, ensureFuelStop, ensurePhotoStop, hideHazards,
overnightFlight, placeIdOf, removeFerry, removeFuelStop, removeImportedStops, removeNightAt, removePhotoStop, restoreFlight,
stubGooglePreview, stubHazards,
} from './fixtures-trip-roadtrip'
import { tripRoadtripContext, tripRoadtripGuides } from '../../src/help/contexts/tripRoadtrip'
import type { HelpGuide } from '../../src/help/types'
@@ -89,14 +90,18 @@ const addFuelStop = (page: Page) => dryBand(page).getByRole('button', { name: /a
const viaHandle = (page: Page) => page.locator('.leaflet-marker-icon.leaflet-marker-draggable').first()
/** The Search button's card: Looking for, the day, Within, Search and Manual. */
const searchCard = (page: Page) => corridor(page).getByRole('button', { name: 'Search', exact: true }).locator('xpath=../..')
/** A hotel hit: its add button is the bed, Add as an overnight stay. */
/**
* A hotel hit: its add button is the bed, Add as an overnight stay. The last one,
* because the hits run in the order the drive passes them: the first lies a few
* kilometres into the morning, and a night there would read as a hotel at 10:30.
*/
const nightButton = (page: Page) =>
corridor(page).getByRole('button', { name: 'Add as an overnight stay', exact: true }).first()
corridor(page).getByRole('button', { name: 'Add as an overnight stay', exact: true }).last()
const nightRow = (page: Page) =>
corridor(page)
.getByRole('listitem')
.filter({ has: page.getByRole('button', { name: 'Add as an overnight stay', exact: true }) })
.first()
.last()
/**
* The battery badge of a refuelling stop. It has no label of its own: its name
* is its figure, "80 %", or the "+" it shows while nothing says how full.
@@ -112,6 +117,15 @@ const selectMenu = (page: Page) => page.locator('body > div[style*="99999"]').la
/** A warning area drawn by the hazard layer, in the warning colour. */
const hazardArea = (page: Page) => page.locator('.leaflet-overlay-pane path[stroke="var(--warning)"]').first()
const hazardPopup = (page: Page) => page.locator('.leaflet-popup.trek-hazard-popup')
/** Edit in the footer of the card the photo stop opens over the map. */
const cardEdit = (page: Page) =>
placeCardHead(page, PHOTO_STOP)
.locator('xpath=ancestor::*[.//button[@aria-label="Edit"]][1]')
.getByRole('button', { name: 'Edit', exact: true })
/** The picture in the stop dialog's head: the gallery trigger, named Show photos. */
const stopDialogPhoto = (page: Page) => modal(page).getByRole('button', { name: 'Show photos', exact: true })
/** The full-screen gallery the picture opens; portalled to the body, labelled like its trigger. */
const lightbox = (page: Page) => page.locator('div[role="dialog"][aria-modal="true"][aria-label="Show photos"]')
// ── Getting there ─────────────────────────────────────────────────────────────
@@ -182,8 +196,8 @@ type RoutePoint = { leg: number; x: number; y: number }
* what sits in the middle of it is usually somebody else's pin.
*
* The drawn casing is not what takes the click: it is non-interactive, and an
* invisible band over the same line (`RouteHitBand`, a transparent stroke with
* the class `cursor-copy`) catches it instead. So the point is read off the
* invisible band over the same line (`RouteHitBand`, a transparent stroke)
* catches it instead. So the point is read off the
* casing, which is the line the reader sees and the one the ring sits on, and
* the hit test asks for the band of that same leg. Both are drawn from the same
* positions, so their `d` is the same string.
@@ -206,7 +220,8 @@ async function routePoints(page: Page): Promise<RoutePoint[]> {
// The two panels float over the map; a point under one of them is not clickable.
if (x < 430 || x > 1550 || y < 220 || y > 950) continue
const hit = document.elementFromPoint(x, y)
const ownBand = hit instanceof SVGPathElement && hit.classList.contains('cursor-copy') && hit.getAttribute('d') === d
// By its transparent stroke: react-leaflet no longer carries the band's class onto the path.
const ownBand = hit instanceof SVGPathElement && hit.getAttribute('stroke') === 'transparent' && hit.getAttribute('d') === d
if (hit === path || ownBand) found.push({ leg, x, y })
}
})
@@ -229,8 +244,11 @@ async function aimAtLeg(page: Page): Promise<void> {
const points = await routePoints(page)
if (points.length === 0) {
const legs = await page.locator('.leaflet-overlay-pane svg path[stroke="#0a5cc2"]').count()
const bands = await page.locator('.leaflet-overlay-pane svg path.cursor-copy').count()
throw new Error(`no drawn leg is reachable on the map (${legs} drawn legs, ${bands} click bands)`)
const bands = await page.locator('.leaflet-overlay-pane svg path[stroke="transparent"]').count()
const kinds = await page.evaluate(() =>
[...new Set(Array.from(document.querySelectorAll('.leaflet-overlay-pane svg path')).map(el => `${el.getAttribute('stroke')}|${el.getAttribute('class')}`))].join(', '),
)
throw new Error(`no drawn leg is reachable on the map (${legs} drawn legs, ${bands} click bands; paths: ${kinds})`)
}
const counts = new Map<number, number>()
for (const point of points) counts.set(point.leg, (counts.get(point.leg) ?? 0) + 1)
@@ -270,12 +288,53 @@ async function aimAtHazard(page: Page): Promise<void> {
const top = document.elementFromPoint(box.left + box.width / 2, box.top + box.height / 2)
const why = `area at ${Math.round(box.left)},${Math.round(box.top)} ${Math.round(box.width)}x${Math.round(box.height)}, ` +
`on top at its centre: ${top ? `${top.tagName.toLowerCase()}.${String(top.getAttribute('class') ?? '')}` : 'nothing'}`
return { point: found[Math.floor(found.length / 2)] ?? null, why }
// Low in the area, not its middle: the popup opens above the click, and from the
// middle its title ends up under the map's category pills.
return { point: found[Math.floor(found.length * 0.8)] ?? null, why }
})
if (!aim.point) throw new Error(`no part of the warning area is reachable on the map (${aim.why})`)
hazardAt = aim.point
}
/**
* Drag the map so the warning area sits low enough for its popup. The popup
* opens above the click and is taller than the room left under the category
* pills when the area stays where framing on Hakone puts it, and Leaflet's own
* auto pan does not reliably clear the pills. The drag starts on bare map.
*/
async function lowerHazardArea(page: Page): Promise<void> {
const plan = await page.evaluate(() => {
const path = document.querySelector<SVGPathElement>('.leaflet-overlay-pane path[stroke="var(--warning)"]')
if (!path) return null
const box = path.getBoundingClientRect()
const dy = Math.round(760 - box.bottom)
for (let y = 300; y <= 700; y += 40) {
for (let x = 700; x <= 1400; x += 50) {
// Bare map: inside the map, but not a pin, a popup, a control or a drawn line.
const el = document.elementFromPoint(x, y)
const bare =
!!el?.closest('.leaflet-container') &&
!el.closest('.leaflet-marker-pane, .leaflet-popup-pane, .leaflet-tooltip-pane, .leaflet-control-container') &&
!(el instanceof SVGPathElement)
if (bare) return { x, y, dy }
}
}
return { x: 0, y: 0, dy }
})
if (!plan || plan.dy <= 0) return
if (plan.x === 0) {
console.warn('[roadtrip-hazards] no bare map to drag the warning area down from')
return
}
await page.mouse.move(plan.x, plan.y)
await page.mouse.down()
for (let i = 1; i <= 12; i++) await page.mouse.move(plan.x, plan.y + (plan.dy * i) / 12)
// Hold still before letting go, so the drag ends without a fling.
await page.waitForTimeout(400)
await page.mouse.up()
await finishMapPan(page)
}
/** Hold the loop's last frame a moment, on the state the gesture left. */
async function holdResult(page: Page, frame: () => Promise<void>): Promise<void> {
await settle(page)
@@ -283,6 +342,14 @@ async function holdResult(page: Page, frame: () => Promise<void>): Promise<void>
await frame()
}
/**
* On the stop's name, the handle a reader grabs: the item's centre can be its drive
* band, whose Other ways tooltip would lie over the picture.
*/
async function hoverShrineName(page: Page): Promise<void> {
await stopRow(page, 'Hakone Shrine').hover({ position: { x: 70, y: 12 } })
}
// ── Day 4 as the fixtures left it, for the guide that moves its stops ─────────
let day4Order: number[] = []
@@ -386,6 +453,18 @@ async function restorePlace(page: Page, name: string, data: Record<string, unkno
if (place) await page.request.put(`/api/trips/${tripId}/places/${place.id}`, { data })
}
/** Every visit of the place back on the place's own stay, the hour a new place starts with. */
async function clearVisitStays(page: Page, name: string): Promise<void> {
const { tripId, dayIds } = seededTrip()
const placeId = await placeIdOf(page.request, name)
if (placeId === null) return
for (let i = 0; i < dayIds.length; i++) {
for (const visit of (await assignmentsOn(page.request, i)).filter(a => a.place_id === placeId)) {
await page.request.put(`/api/trips/${tripId}/assignments/${visit.id}/stay`, { data: { stay_minutes: null } })
}
}
}
const closeModal = async (page: Page): Promise<void> => {
if (await modal(page).isVisible().catch(() => false)) {
await page.keyboard.press('Escape')
@@ -409,7 +488,15 @@ const SCRIPTS: Record<string, GuideScript> = {
},
only(p => p.getByText('Driving time', { exact: true }).locator('xpath=ancestor::header[1]')),
only(p => dayCard(p, 2).locator('header')),
only(p => dayCard(p, 2).getByRole('list').first()),
{
target: p => dayCard(p, 2).getByRole('list').first(),
// In the list's top corner: its centre is the drive band, whose Other ways
// tooltip would cover the next stop's name.
hover: async p => {
const box = await dayCard(p, 2).getByRole('list').first().boundingBox()
if (box) await p.mouse.move(box.x + 12, box.y + 8)
},
},
{
// Day 2, like the two steps above: the rail leaves out a day with
// nothing to drive, and day 1 is one of them.
@@ -473,7 +560,7 @@ const SCRIPTS: Record<string, GuideScript> = {
// Hakone Shrine, not a seeded stop: every seeded visit has an end time
// from the day plan, and a stop with one opens the read-only "until"
// version of the dialog, which has no slider and no Save. The drive's
// own fixture places carry no times, so the badge is the plus of Add a stay.
// own fixture places carry no times, only the hour a new place starts with.
target: p => stopItem(p, 'Hakone Shrine').getByRole('button', { name: /^(Time at this stop|Add a stay)/ }),
act: async p => {
await stopItem(p, 'Hakone Shrine').getByRole('button', { name: /^(Time at this stop|Add a stay)/ }).click()
@@ -484,21 +571,63 @@ const SCRIPTS: Record<string, GuideScript> = {
{
target: dialog,
act: async p => {
await modal(p).getByRole('button', { name: '1 h', exact: true }).click()
await expect(modal(p).getByRole('slider', { name: 'Minutes' })).toHaveValue('60')
// Not 1 h: a new place starts with an hour, so that preset would change nothing.
await modal(p).getByRole('button', { name: '45 min', exact: true }).click()
await expect(modal(p).getByRole('slider', { name: 'Minutes' })).toHaveValue('45')
await modal(p).getByRole('button', { name: 'Save', exact: true }).click()
await expect(modal(p)).toHaveCount(0)
await expect(stopItem(p, 'Hakone Shrine')).toContainText('1 h', { timeout: 20_000 })
await expect(stopItem(p, 'Hakone Shrine')).toContainText('45 min', { timeout: 20_000 })
await settle(p)
},
},
],
cleanup: async p => {
// Zero, not null: the update folds a null into "leave it alone".
await restorePlace(p, 'Hakone Shrine', { duration_minutes: 0 })
// The stay lands on the visit (#3092); null hands it back to the place, which has none.
await clearVisitStays(p, 'Hakone Shrine')
await restorePlace(p, 'Meiji Jingu', { stop_type: null })
},
},
'roadtrip-stop-photo': {
guide: guide('roadtrip-stop-photo'),
start: async p => {
await ensurePhotoStop(p.request)
await openRoadtrip(p)
},
steps: [
{
target: p => stopRow(p, PHOTO_STOP),
act: async p => {
await stopRow(p, PHOTO_STOP).click({ position: { x: 70, y: 12 } })
await expect(placeCardHead(p, PHOTO_STOP)).toBeVisible({ timeout: 15_000 })
await finishMapPan(p)
},
},
{
// Edit is the primary action at the right end of the card's footer.
target: cardEdit,
act: async p => {
await cardEdit(p).click()
await expect(stopDialogPhoto(p)).toBeVisible({ timeout: 15_000 })
await expect(stopDialogPhoto(p).locator('img')).toHaveJSProperty('complete', true)
await settle(p)
},
},
{
target: stopDialogPhoto,
act: async p => {
await stopDialogPhoto(p).click()
await expect(lightbox(p)).toBeVisible({ timeout: 15_000 })
await expect(lightbox(p).locator('img').first()).toBeVisible({ timeout: 15_000 })
await settle(p)
},
},
],
cleanup: async p => {
if (await lightbox(p).isVisible().catch(() => false)) await p.keyboard.press('Escape')
await closeModal(p)
await removePhotoStop(p.request)
},
},
'roadtrip-reorder': {
guide: guide('roadtrip-reorder'),
start: async p => {
@@ -510,6 +639,7 @@ const SCRIPTS: Record<string, GuideScript> = {
// Hakone Shrine onto Shinjuku Gyoen: the shrine moves up beside
// Owakudani, and the day stops driving to Tokyo and back.
target: p => stopItem(p, 'Hakone Shrine'),
hover: hoverShrineName,
dropTo: p => stopItem(p, 'Shinjuku Gyoen'),
clip: async (p, frame) => {
await dragLoop(p, stopItem(p, 'Hakone Shrine'), stopItem(p, 'Shinjuku Gyoen'), frame)
@@ -525,6 +655,7 @@ const SCRIPTS: Record<string, GuideScript> = {
// head of day 4 between them day 2 then lies above the rail's window, so
// the pointer let go off the rail and nothing moved.
target: p => stopItem(p, 'Hakone Shrine'),
hover: hoverShrineName,
dropTo: p => stopItem(p, 'Hakone Open-Air Museum'),
clip: async (p, frame) => {
await dragLoop(p, stopItem(p, 'Hakone Shrine'), stopItem(p, 'Hakone Open-Air Museum'), frame)
@@ -538,6 +669,7 @@ const SCRIPTS: Record<string, GuideScript> = {
// Day 4 is Owakudani and Shinjuku Gyoen now; Alt and up puts the garden
// first, and the day drives out of Tokyo to the valley.
target: p => stopRow(p, 'Shinjuku Gyoen'),
hover: async p => { await stopRow(p, 'Shinjuku Gyoen').hover({ position: { x: 70, y: 12 } }) },
act: async p => {
await stopRow(p, 'Shinjuku Gyoen').focus()
await p.keyboard.press('Alt+ArrowUp')
@@ -879,6 +1011,11 @@ const SCRIPTS: Record<string, GuideScript> = {
await settle(p)
},
target: p => modal(p).getByRole('group', { name: 'Daily travel times' }),
// In the group's corner: its centre carries the note's tooltip over Day end time.
hover: async p => {
const box = await modal(p).getByRole('group', { name: 'Daily travel times' }).boundingBox()
if (box) await p.mouse.move(box.x + 6, box.y + 6)
},
},
{
target: p => modal(p).getByRole('textbox', { name: 'Day start time' }),
@@ -939,7 +1076,14 @@ const SCRIPTS: Record<string, GuideScript> = {
await settle(p)
},
},
only(p => dryBand(p).getByRole('list').first()),
{
target: p => dryBand(p).getByRole('list').first(),
// In the list's corner: a badge under its centre would lay its tooltip over a name.
hover: async p => {
const box = await dryBand(p).getByRole('list').first().boundingBox()
if (box) await p.mouse.move(box.x + 6, box.y + 6)
},
},
{
prepare: async p => {
const label = (await addFuelStop(p).getAttribute('aria-label')) ?? ''
@@ -1161,6 +1305,7 @@ const SCRIPTS: Record<string, GuideScript> = {
// that stop (the way the via guide brings its leg into view) puts the
// area in the middle of the map at the same zoom, outline and all.
await frameOnStop(p, 'Hakone Shrine')
await lowerHazardArea(p)
await aimAtHazard(p)
},
},
@@ -1170,7 +1315,9 @@ const SCRIPTS: Record<string, GuideScript> = {
act: async p => {
await p.mouse.click(hazardAt.x, hazardAt.y)
await expect(hazardPopup(p)).toContainText(HAZARD_TITLE, { timeout: 15_000 })
await settle(p)
// The popup pans the map to fit itself, on Leaflet's clock: let that pan land,
// or its title stays under the map's category pills.
await finishMapPan(p)
},
},
],
+33
View File
@@ -218,6 +218,39 @@ const SCRIPTS: Record<string, GuideScript> = {
],
},
'tour-route-in-app': {
guide: guide('tour-route-in-app'),
// The hut trek: a hike, so the map apps follow it on foot.
start: async (p) => {
await openTourTrip(p, { day: null });
await toursTab(p).click();
await expect(row(p, TOUR_NAMES.hutToHut)).toBeVisible({ timeout: 30_000 });
await settle(p);
},
steps: [
{
target: (p) => row(p, TOUR_NAMES.hutToHut),
act: async (p) => {
await row(p, TOUR_NAMES.hutToHut).click();
await expect(head(p).getByRole('heading', { name: TOUR_NAMES.hutToHut, exact: true })).toBeVisible({
timeout: 30_000,
});
await settle(p);
},
},
{
target: (p) => footer(p).getByTestId('tour-route-apps'),
act: async (p) => {
await footer(p).getByTestId('tour-route-apps').click();
await expect(p.getByRole('menu')).toBeVisible();
await settle(p);
},
},
// No click: each entry hands the route to another app in a new tab.
only((p) => p.getByRole('menu')),
],
},
'tour-copy-keep': {
guide: guide('tour-copy-keep'),
start: async (p) => {
+6 -1
View File
@@ -180,7 +180,12 @@ const SCRIPTS: Record<string, GuideScript> = {
await openTours(p);
},
steps: [
{ target: (p) => tourRow(p, RECORDED_NAME), act: viewRecorded },
{
target: (p) => tourRow(p, RECORDED_NAME),
// On the name: the centre of the row is its time badge, whose tooltip would cover the next row.
hover: (p) => tourRow(p, RECORDED_NAME).getByText(RECORDED_NAME, { exact: true }).hover(),
act: viewRecorded,
},
{ target: (p) => railCard(p, RECORDED_NAME, 'Tour summary') },
{
target: (p) => importRail(p, RECORDED_NAME).getByRole('button', { name: 'Back to Tours' }),
+2
View File
@@ -35,6 +35,7 @@ import {
reliefSlider,
restartButton,
seamarksToggle,
searchAgainWhileUnavailable,
searchAlong,
speedGroup,
terrainToggle,
@@ -158,6 +159,7 @@ const SCRIPTS: Record<string, GuideScript> = {
act: async (p) => {
await alongSearch(p).click();
await expect(alongSearch(p)).toHaveText(/Search again/, { timeout: 90_000 });
await searchAgainWhileUnavailable(p);
await settle(p);
},
},
+41 -2
View File
@@ -145,8 +145,39 @@ async function searchTheHut(page: Page): Promise<void> {
const local = options.filter({
hasText: /Santa Cristina|Gardena|Gröden|Bolzano|Bozen|Südtirol|Alto Adige|Trentino/i,
});
await ((await local.count()) ? local.first() : options.first()).click();
const hut = local.filter({ hasText: /Regensburger|Firenze/i });
await ((await hut.count()) ? hut.first() : (await local.count()) ? local.first() : options.first()).click();
await landMap(page);
await fitTheDrawing(page);
}
/**
* The search lands on whatever the place search answers for the hut, and as
* close in as that answer is small: an area mapped as a building lands so far
* in that the spots of the drawing are off the screen. Out with the wheel, on
* the middle of the map, until the first and the last spot are both in sight.
*/
async function fitTheDrawing(page: Page): Promise<void> {
const g = await line(page);
const ends = [DRAWN_OFFSETS[0], DRAWN_OFFSETS[DRAWN_OFFSETS.length - 1]];
const inSight = async () => {
for (const offset of ends) {
if (
!(await screenOf(page, spotAt(g, offset)).then(
() => true,
() => false
))
)
return false;
}
return true;
};
for (let i = 0; i < 6 && !(await inSight()); i++) {
await page.mouse.move(VIEWPORT.width / 2, VIEWPORT.height / 2 + 40);
await page.mouse.wheel(0, 120);
await landMap(page);
}
expect(await inSight(), 'the drawing does not fit on the map after the search').toBe(true);
}
/** Click spot `i` of the drawing onto the map and wait for its row. */
@@ -230,12 +261,16 @@ const SCRIPTS: Record<string, GuideScript> = {
await p.getByTestId('tour-rail-add').click();
}
await expect(p.getByRole('group', { name: 'Add tour', exact: true })).toHaveCount(0);
// The plus keeps the focus, and with it its tooltip, into the pictures after it.
await p.evaluate(() => (document.activeElement as HTMLElement | null)?.blur());
},
},
{ target: mapSearch },
{ target: layerPill },
{
target: (p) => tourRow(p, TOUR_NAMES.recorded),
// On the name: the centre of the row is its time badge, whose tooltip would cover the next row.
hover: (p) => tourRow(p, TOUR_NAMES.recorded).getByText(TOUR_NAMES.recorded, { exact: true }).hover(),
act: async (p) => {
await tourRow(p, TOUR_NAMES.recorded).click();
await expect(p.getByRole('heading', { name: 'GPX tour', exact: true })).toBeVisible({ timeout: 30_000 });
@@ -562,12 +597,16 @@ const SCRIPTS: Record<string, GuideScript> = {
target: breaks,
act: async (p) => {
await typeInto(p, breaks(p), '0:45');
await breaks(p).press('Tab');
// Blurred rather than tabbed away from: Tab would focus Planned, whose
// tooltip then covers the field the next step is about.
await breaks(p).blur();
await settle(p);
},
},
{
target: planned,
// Not on the field itself: its tooltip would cover the time the step is about.
hover: (p) => p.getByText('Breaks', { exact: true }).first().hover(),
act: async (p) => {
await typeInto(p, planned(p), '3:30');
await planned(p).press('Enter');
+24
View File
@@ -505,8 +505,32 @@ const SCRIPTS: Record<string, GuideScript> = {
await tourRow(p, /Vallunga cross-country/).click();
await expect(p.getByTestId('ski-track-card')).toBeVisible({ timeout: 30_000 });
await settle(p);
// The card lies below the fold of its panel while the panel still grows; the picture
// was taken of the empty space below the window. Wait until the button sits inside it.
const change = p.getByTestId('ski-track-card').getByRole('button', { name: 'Change' });
await expect
.poll(
async () => {
await change.evaluate((el) => el.scrollIntoView({ block: 'center', inline: 'nearest' }));
await p.evaluate(() => window.scrollTo(0, 0));
const box = await change.boundingBox();
const vp = p.viewportSize();
return !!box && !!vp && box.y > 0 && box.y + box.height < vp.height && box.x > 0;
},
{ timeout: 20_000 }
)
.toBe(true);
await p.waitForTimeout(800);
await settle(p);
},
target: (p) => p.getByTestId('ski-track-card').getByRole('button', { name: 'Change' }),
hover: async (p) => {
const change = p.getByTestId('ski-track-card').getByRole('button', { name: 'Change' });
// A throwaway full screenshot first: the one render that came out right had one here, and
// the clipped shot alone has come out as an empty, shifted frame without the ring.
await p.screenshot();
await change.hover();
},
act: async (p) => {
await p.getByTestId('ski-track-card').getByRole('button', { name: 'Change' }).click();
await expect(classifyDialog(p)).toBeVisible();
+12 -1
View File
@@ -184,6 +184,12 @@ const SCRIPTS: Record<string, GuideScript> = {
// The hut trek has three stages, so the day it is given asks how next.
prepare: async (p) => {
await hoverRow(p, TOUR_NAMES.hutToHut);
// The second menu opens at the Add to day button, which only shows while the row is
// hovered or focused. Choosing the day moves both away, so the button would have no box
// and the menu would open in the window's top left corner; kept in sight, it anchors there.
await tourRow(p, TOUR_NAMES.hutToHut)
.getByTestId('tour-action-row')
.evaluate((el) => ((el as HTMLElement).style.display = 'flex'));
await tourRow(p, TOUR_NAMES.hutToHut).getByRole('button', { name: 'Add to day', exact: true }).click();
await expect(dayMenu(p)).toBeVisible();
await dayMenu(p)
@@ -196,7 +202,12 @@ const SCRIPTS: Record<string, GuideScript> = {
},
target: dayMenu,
// Nothing chosen: the hut trek keeps its days 4 to 6.
act: closeMenu,
act: async (p) => {
await closeMenu(p);
await tourRow(p, TOUR_NAMES.hutToHut)
.getByTestId('tour-action-row')
.evaluate((el) => (el as HTMLElement).style.removeProperty('display'));
},
},
],
cleanup: noDayTours,
+117 -3
View File
@@ -1,10 +1,11 @@
import { test, expect, type Locator, type Page } from '@playwright/test'
import { captureGuide, captureHero, beat, typeInto, settle, VIEWPORT, type GuideScript } from './guide'
import { seededTrip, ensureTransportFixtures, TRANSIT_JOURNEY, flightEmlFixture, FLIGHT_EML, FLIGHT_TO_IMPORT } from './fixtures'
import { openTrip, openTripOnDay, selectDay, modal, dialog, portalDialog, importSteps, importTask, dismissImportTask, deleteTripFiles } from './trip-shared'
import { openTrip, openTripOnDay, selectDay, closeDayDetails, modal, dialog, portalDialog, importSteps, importTask, dismissImportTask, deleteTripFiles } from './trip-shared'
import { ensureAirtrailConnection, disconnectAirtrail, AIRTRAIL_FLIGHTS, requireExtractor, allowEmlUploads } from './external'
import { tripTransportsContext, tripTransportsGuides } from '../../src/help/contexts/tripTransports'
import type { HelpGuide } from '../../src/help/types'
import { at, day } from '../dates'
/**
* Actions for the Transports tab of a trip, keyed by the ids in
@@ -200,6 +201,67 @@ const joinToggle = (page: Page) =>
const connectionGroup = (page: Page) => joinToggle(page).locator('xpath=..')
const importCta = (page: Page) => airtrailPicker(page).getByRole('button', { name: /^Import \d+$/ })
/**
* The flight home on the trip's last day, the picture day, for flight-live-status.
* Departure 15:20 in Tokyo (06:20 UTC) and arrival 21:25 in Frankfurt (20:25
* UTC), so at the pinned 09:00 UTC it has been in the air for two and a half
* hours: 15 minutes late off the ground and 25 minutes late on the estimate.
*/
const LIVE = {
title: 'NH223 HND → FRA',
code: 'NH7QF2',
flightNumber: 'NH223',
from: { code: 'HND', name: 'Tokyo Haneda', lat: 35.5494, lng: 139.7798, timezone: 'Asia/Tokyo' },
to: { code: 'FRA', name: 'Frankfurt', lat: 50.0379, lng: 8.5622, timezone: 'Europe/Berlin' },
}
/** Creates the flight home and answers its id. */
async function createLiveFlight(page: Page): Promise<number> {
const { tripId, dayIds } = seededTrip()
const res = await page.request.post(`/api/trips/${tripId}/reservations`, {
data: {
title: LIVE.title, type: 'flight', status: 'confirmed',
day_id: dayIds[dayIds.length - 1], end_day_id: dayIds[dayIds.length - 1],
reservation_time: at(0, '15:20'), reservation_end_time: at(0, '21:25'),
confirmation_number: LIVE.code, location: LIVE.from.name,
metadata: { airline: 'All Nippon Airways', flight_number: LIVE.flightNumber, departure_airport: 'HND', arrival_airport: 'FRA' },
endpoints: [
{ role: 'from', sequence: 0, name: LIVE.from.name, code: LIVE.from.code, lat: LIVE.from.lat, lng: LIVE.from.lng, timezone: LIVE.from.timezone, local_date: day(0), local_time: '15:20' },
{ role: 'to', sequence: 1, name: LIVE.to.name, code: LIVE.to.code, lat: LIVE.to.lat, lng: LIVE.to.lng, timezone: LIVE.to.timezone, local_date: day(0), local_time: '21:25' },
],
},
})
if (!res.ok()) throw new Error(`could not create the live flight: ${res.status()} ${await res.text()}`)
const body = (await res.json()) as { reservation?: { id: number }; id?: number }
const id = body.reservation?.id ?? body.id
if (!id) throw new Error('the live flight came back without an id')
return id
}
/**
* What the open ADS-B feeds would say about the flight two and a half hours
* after take-off, over north-east China on the great circle to Frankfurt. The
* feed cannot be asked from here (and the real NH223 may be anywhere), so the
* trip's live read answers this leg: the same shape the server sends.
*/
function liveLeg(reservationId: number) {
const utc = (hhmm: string) => `${day(0)}T${hhmm}:00.000Z`
return {
reservation_id: reservationId, leg_index: 0, callsign: 'ANA223', flight_number: 'NH 223', service_date: day(0),
origin: LIVE.from, destination: LIVE.to, phase: 'airborne',
scheduled_departure: utc('06:20'), scheduled_arrival: utc('20:25'),
departed_at: utc('06:35'), landed_at: null, estimated_arrival: utc('20:50'),
departure_delay_min: 15, arrival_delay_min: 25,
progress: 0.17, distance_total_km: 9361, distance_remaining_km: 7770,
position: { lat: 47.66, lng: 129.51, altitude_ft: 37000, ground_speed_kt: 486, track_deg: 304, vertical_rate_fpm: 0, on_ground: false },
aircraft: { registration: 'JA791A', type: 'B77W' },
last_seen_at: utc('08:59'), fetched_at: utc('08:59'), stale: false, source: 'adsb.lol',
}
}
/** The live card in the open booking, named by the flight number and where it stands. */
const liveCard = (page: Page) => bookingDetail(page, LIVE.title).locator('section[aria-label^="NH 223 "]')
/** Give a day's legs back to the day's own mode, whichever stop carries the one that was set. */
async function resetLegModes(page: Page, dayIndex: number): Promise<void> {
const { tripId, dayIds } = seededTrip()
@@ -666,9 +728,9 @@ const SCRIPTS: Record<string, GuideScript> = {
},
},
{
target: p => bookingDetail(p, TRAIN.title).getByRole('button', { name: 'On map', exact: true }),
target: p => bookingDetail(p, TRAIN.title).getByRole('button', { name: 'Map', exact: true }),
act: async p => {
await bookingDetail(p, TRAIN.title).getByRole('button', { name: 'On map', exact: true }).click()
await bookingDetail(p, TRAIN.title).getByRole('button', { name: 'Map', exact: true }).click()
// The Plan opens on day 5 with the train's line switched on.
await expect(transportRowTitled(p, TRAIN.title).getByRole('button', { name: 'Hide booking routes' })).toBeVisible({ timeout: 20_000 })
await settle(p)
@@ -801,6 +863,58 @@ const SCRIPTS: Record<string, GuideScript> = {
await p.evaluate(() => { try { sessionStorage.clear() } catch { /* a locked-down browser keeps its filters */ } })
},
},
'flight-live-status': {
guide: guide('flight-live-status'),
// The server's own poll is switched off for the guide, so no push from the
// real feed lands over the answer the page is given for this flight.
start: async p => {
await p.request.put('/api/auth/app-settings', { data: { flight_live_enabled: false } })
await deleteByTitle(p, LIVE.title)
const id = await createLiveFlight(p)
await p.context().route(/\/api\/trips\/\d+\/flights\/live$/, route =>
route.fulfill({ json: { enabled: true, attribution: 'adsb.lol', flights: [liveLeg(id)] } }))
await openTrip(p, { tab: 'transports' })
await expect(card(p, LIVE.title).getByText(/^In the air, Lands in /)).toBeVisible({ timeout: 20_000 })
await settle(p)
},
steps: [
only(p => card(p, LIVE.title)),
{
prepare: async p => {
await card(p, LIVE.title).click()
await expect(liveCard(p)).toBeVisible({ timeout: 20_000 })
await settle(p)
// The route map under the pass is a vector map; its tiles land after idle.
await p.waitForTimeout(1500)
},
target: p => liveCard(p).locator('> header'),
},
only(p => liveCard(p).locator('> div > div').first()),
only(p => liveCard(p).locator('div.mt-3.grid')),
{
prepare: async p => {
await p.keyboard.press('Escape')
await expect(bookingDetail(p, LIVE.title)).toHaveCount(0)
// The tab is remembered, so the Plan is opened by its tab. It opens on
// today, the trip's last day, where the flight home is.
await p.getByRole('button', { name: 'Plan', exact: true }).click()
await expect(transportRowTitled(p, LIVE.title)).toBeVisible({ timeout: 20_000 })
await closeDayDetails(p)
await transportRowTitled(p, LIVE.title).scrollIntoViewIfNeeded()
await expect(transportRowTitled(p, LIVE.title).getByText(/^In the air, Lands in /)).toBeVisible({ timeout: 20_000 })
await settle(p)
await p.waitForTimeout(1500)
},
target: p => transportRowTitled(p, LIVE.title),
},
],
cleanup: async p => {
await p.context().unroute(/\/api\/trips\/\d+\/flights\/live$/)
await deleteByTitle(p, LIVE.title)
await p.request.put('/api/auth/app-settings', { data: { flight_live_enabled: true } })
await p.evaluate(() => { try { sessionStorage.clear() } catch { /* a locked-down browser keeps its tab */ } })
},
},
'airtrail-import': {
guide: guide('airtrail-import'),
// The connection is made here and taken away in cleanup, so the hero and
+218 -12
View File
@@ -1,14 +1,24 @@
import { test, expect, type Page, type Locator } from '@playwright/test'
import { captureGuide, captureHero, beat, typeInto, settle, VIEWPORT, type GuideScript } from './guide'
import { ensureUsers, seededTrip, ADMIN_USERS, JOURNEY_TITLE } from './fixtures'
import { openTrip, openTripOnDay, modal } from './trip-shared'
import { openTrip, openTripOnDay, modal, confirmDialog } from './trip-shared'
import { mockTripAssistant, resetTripAssistant, QUESTION, SUGGESTED, type AssistantRun } from './fixtures-assistant'
import { tripContext, tripGuides } from '../../src/help/contexts/trip'
import type { HelpGuide } from '../../src/help/types'
/** The round button at the bottom of the planner, not the navbar's twin of the same name. */
const assistantLauncher = (page: Page) => page.locator('button.trek-assistant-pop')
const assistantWindow = (page: Page) => page.getByRole('dialog', { name: 'Assistant', exact: true })
/** The answer's card of changes: the last section inside the window, by its title while it waits. */
const changeCard = (page: Page) =>
assistantWindow(page).locator('section').filter({ has: page.getByText('Suggested changes', { exact: true }) }).last()
/** What the mocked chat made for real, for cleanup. */
let assistantRun: AssistantRun | null = null
/**
* Actions for the trip frame, keyed by the ids in `src/help/contexts/trip.ts`:
* the trip's Settings (people, sharing, the linked journal), the columns and
* the undo. They run on the seeded "Autumn in Japan"; what a guide creates (a
* the trip's Settings (people, sharing, the linked journal, the trip's addons
* and its own form), the columns and the undo. They run on the seeded "Autumn in Japan"; what a guide creates (a
* member, a guest, a link, a linked journal) it leaves for the next one or
* takes away again in `cleanup`.
*/
@@ -28,7 +38,8 @@ const block = (page: Page, opening: RegExp) => modal(page).locator('section').fi
const inviteBlock = (page: Page) => block(page, /^Invite User/)
const accessBlock = (page: Page) => block(page, /^Access\s*\d/)
/** An area in the dialog's list on the left; each carries the area's name as its label. */
const area = (page: Page, name: 'People' | 'Sharing' | 'Journal') => modal(page).getByRole('button', { name, exact: true })
type AreaName = 'People' | 'Sharing' | 'Journal' | 'Addons' | 'Edit Trip'
const area = (page: Page, name: AreaName) => modal(page).getByRole('button', { name, exact: true })
/** The Trip settings pill beside the trip's name. */
const settingsPill = (page: Page) => page.getByRole('button', { name: 'Trip settings', exact: true })
/**
@@ -52,7 +63,7 @@ async function openSettings(page: Page): Promise<void> {
await clickSettings(page)
}
async function pickArea(page: Page, name: 'Sharing' | 'Journal'): Promise<void> {
async function pickArea(page: Page, name: AreaName): Promise<void> {
await area(page, name).click()
await expect(area(page, name)).toHaveAttribute('aria-current', 'page')
await settle(page)
@@ -61,6 +72,8 @@ async function pickArea(page: Page, name: 'Sharing' | 'Journal'): Promise<void>
const closeModal = async (page: Page): Promise<void> => {
await page.keyboard.press('Escape')
await expect(modal(page)).toHaveCount(0)
// The dialog hands the focus back to the pill, whose focus ring would stay in the picture.
await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur())
}
/** Take the journal off the trip again; a trip without one answers that too, which is fine. */
@@ -71,6 +84,49 @@ async function unlinkJournal(page: Page): Promise<void> {
const only = (target: (p: Page) => Locator) => ({ target })
/**
* Wait until the first rows of the places column show their photos. A photo
* that comes back late leaves the category icon in its place for good, so a
* page that does not get them in time is opened again, at most twice.
*/
async function placePhotos(page: Page): Promise<void> {
for (let attempt = 0; attempt < 3; attempt++) {
const loaded = await page
.waitForFunction(
() => {
const rows = [...document.querySelectorAll('[role="option"]')].slice(0, 8)
return rows.length > 0 && rows.every(row => row.querySelector('img')?.complete)
},
null,
{ timeout: 15_000 },
)
.then(() => true)
.catch(() => false)
if (loaded) break
await openTrip(page)
}
await settle(page)
}
/** The addon the trip-addons guide switches; its row in the Addons area is the switch's row. */
const ADDON_ID = 'roadtrip'
const ADDON_NAME = 'Road trip'
const addonSwitch = (page: Page) => modal(page).getByRole('button', { name: ADDON_NAME, exact: true })
/** A row of the Addons area: the switch's parent, with the tile, the name, the badge and the line under it. */
const addonRow = (page: Page) => addonSwitch(page).locator('xpath=..')
/** The list of every trip addon, one row each. */
const addonList = (page: Page) => addonRow(page).locator('xpath=..')
/** Back to whatever the instance says for the addon the guide switched. */
async function resetAddon(page: Page): Promise<void> {
const { tripId } = seededTrip()
await page.request.put(`/api/trips/${tripId}/addons/${ADDON_ID}`, { data: { enabled: null } })
}
/** A panel of the trip's form by its heading: the heading, its CardHead, then the panel. */
const formPanel = (page: Page, heading: string) =>
modal(page).getByRole('heading', { name: heading, exact: true }).locator('xpath=../../..')
const SCRIPTS: Record<string, GuideScript> = {
'add-member': {
guide: guide('add-member'),
@@ -152,7 +208,7 @@ const SCRIPTS: Record<string, GuideScript> = {
act: p => pickArea(p, 'Sharing'),
},
{
// The first row of chips: Map & Plan, Bookings, Packing, Costs, Chat.
// The chips under Options: Map & Plan, Bookings, Packing, Costs, Chat, then the two options.
target: p => modal(p).getByRole('button', { name: 'Map & Plan' }).locator('xpath=..'),
act: async p => {
await modal(p).getByRole('button', { name: 'Packing', exact: true }).click()
@@ -161,11 +217,8 @@ const SCRIPTS: Record<string, GuideScript> = {
},
},
{
// Options with its two chips; the pointer on the first shows what it leaves out.
target: p => modal(p).getByRole('button', { name: 'Travel & stays only' }).locator('xpath=../..'),
hover: async p => {
await modal(p).getByRole('button', { name: 'Travel & stays only' }).hover()
},
// The first of the two options; the pointer on it shows what it leaves out.
target: p => modal(p).getByRole('button', { name: 'Travel & stays only' }),
},
{
target: p => modal(p).getByRole('button', { name: 'Create link', exact: true }),
@@ -243,9 +296,71 @@ const SCRIPTS: Record<string, GuideScript> = {
],
cleanup: unlinkJournal,
},
'trip-addons': {
guide: guide('trip-addons'),
start: async p => {
await resetAddon(p)
await openSettings(p)
},
steps: [
{
target: p => area(p, 'Addons'),
act: async p => {
await pickArea(p, 'Addons')
await expect(addonSwitch(p)).toBeVisible({ timeout: 15_000 })
await settle(p)
},
},
{
target: addonList,
act: async p => {
const before = await addonSwitch(p).getAttribute('aria-pressed')
await addonSwitch(p).click()
await expect(addonSwitch(p)).not.toHaveAttribute('aria-pressed', before ?? '')
await expect(addonRow(p).getByText('This trip only', { exact: true })).toBeVisible({ timeout: 15_000 })
await settle(p)
},
},
{
target: addonRow,
// The result shows the trip with the addon switched.
act: async p => {
await closeModal(p)
await placePhotos(p)
},
},
],
cleanup: resetAddon,
},
'edit-trip-settings': {
guide: guide('edit-trip-settings'),
start: openSettings,
steps: [
{
target: p => area(p, 'Edit Trip'),
act: async p => {
await pickArea(p, 'Edit Trip')
await expect(formPanel(p, 'Name and description')).toBeVisible({ timeout: 15_000 })
await settle(p)
},
},
only(p => formPanel(p, 'Name and description')),
{
target: p => modal(p).getByRole('button', { name: 'Update', exact: true }),
act: async p => {
await modal(p).getByRole('button', { name: 'Update', exact: true }).click()
await expect(modal(p)).toHaveCount(0, { timeout: 15_000 })
await settle(p)
},
},
],
},
'collapse-columns': {
guide: guide('collapse-columns'),
start: p => openTrip(p),
start: async p => {
await openTrip(p)
await placePhotos(p)
},
steps: [
{
target: leftToggle,
@@ -303,6 +418,30 @@ const SCRIPTS: Record<string, GuideScript> = {
// The day has to stay open for that: the + at the end of a row belongs to
// the open day, and closing the day's details panel closes the day with it.
await openTripOnDay(p, 1)
// The picture shows the rows around it, so their photos have to be in
// first; the spare place has none of its own and is left out of the wait.
for (let attempt = 0; attempt < 3; attempt++) {
const loaded = await p
.waitForFunction(
() => {
// A place's avatar is an <img> with the place's name as its alt
// while it has a photo, and the category icon once the photo is
// given up. Day 1's places sit in the day plan and in the places
// column, so each needs two loaded photos.
const names = ['Senso-ji Temple', 'teamLab Planets']
return names.every(name => {
const imgs = [...document.querySelectorAll('img')].filter(img => img.alt === name)
return imgs.length >= 2 && imgs.every(img => img.complete && img.naturalWidth > 0)
})
},
null,
{ timeout: 20_000 },
)
.then(() => true)
.catch(() => false)
if (loaded) break
await openTripOnDay(p, 1)
}
const row = p.getByRole('option', { name: /^Tsukiji Outer Market/ })
await row.hover()
const add = row.getByRole('button', { name: '+ Day' })
@@ -331,6 +470,73 @@ const SCRIPTS: Record<string, GuideScript> = {
}
},
},
'trip-assistant': {
guide: guide('trip-assistant'),
// No provider answers in the run: fixtures-assistant.ts answers for it, and Apply plans the place for real.
start: async p => {
assistantRun = await mockTripAssistant(p)
await openTrip(p)
await expect(assistantLauncher(p)).toBeVisible({ timeout: 20_000 })
await settle(p)
},
steps: [
{
target: p => assistantLauncher(p),
act: async p => {
await assistantLauncher(p).click()
await expect(assistantWindow(p).getByRole('textbox')).toBeVisible({ timeout: 15_000 })
await settle(p)
},
},
{
prepare: async p => {
await typeInto(p, assistantWindow(p).getByRole('textbox'), QUESTION)
await beat(p, 300)
await settle(p)
},
target: p => assistantWindow(p).locator('form').last(),
hover: async p => { await assistantWindow(p).getByRole('button', { name: 'Send', exact: true }).hover() },
act: async p => {
await assistantWindow(p).getByRole('button', { name: 'Send', exact: true }).click()
await expect(changeCard(p)).toBeVisible({ timeout: 20_000 })
await expect(changeCard(p).getByRole('button', { name: 'Apply', exact: true })).toBeEnabled()
await settle(p)
},
},
{
target: p => changeCard(p),
hover: async p => { await changeCard(p).getByRole('button', { name: 'Apply', exact: true }).hover() },
act: async p => {
await changeCard(p).getByRole('button', { name: 'Apply', exact: true }).click()
await expect(assistantWindow(p).getByRole('button', { name: 'Undo', exact: true }).first()).toBeVisible({ timeout: 20_000 })
// The place lands in day 1 of the plan behind the window, through the websocket.
await expect(p.getByText(SUGGESTED.name, { exact: true }).first()).toBeVisible({ timeout: 20_000 })
await settle(p)
},
},
{
target: p => assistantWindow(p).getByRole('button', { name: 'Share in the trip chat' }).last(),
act: async p => {
await assistantWindow(p).getByRole('button', { name: 'Share in the trip chat' }).last().click()
await expect(confirmDialog(p).getByRole('button', { name: 'Share', exact: true })).toBeVisible({ timeout: 10_000 })
await settle(p)
},
},
{
target: p => confirmDialog(p),
hover: async p => { await confirmDialog(p).getByRole('button', { name: 'Share', exact: true }).hover() },
act: async p => {
await confirmDialog(p).getByRole('button', { name: 'Share', exact: true }).click()
await expect(p.getByText('Shared in the trip chat').first()).toBeVisible({ timeout: 15_000 })
await settle(p)
},
},
],
cleanup: async p => {
await resetTripAssistant(p.request, assistantRun)
assistantRun = null
},
},
}
// ── Run ───────────────────────────────────────────────────────────────────────
+66 -4
View File
@@ -4,7 +4,7 @@ import { monthName, monthsAhead, year } from '../dates'
import {
PARTNER, ensureFused, ensureSeparate, clearPartnerDays, requestFusionFromPartner, clearFusionRequest,
shareWithAdmin, unshareWithAdmin, ownColor, setOwnColor, ensurePublicCalendar, calendarColors,
restoreCalendarColors, companyHolidayFraction, setCompanyHoliday,
restoreCalendarColors, companyHolidayFraction, setCompanyHoliday, adminId, asMember,
} from './fixtures-vacay'
import { vacayGuides, vacayContext } from '../../src/help/contexts/vacay'
import type { HelpGuide } from '../../src/help/types'
@@ -218,8 +218,57 @@ const calendarRow = (page: Page): Locator => settings(page).getByPlaceholder('La
/** The Fusion Request dialog, which opens by itself while an invite waits for an answer. */
const fusionDialog = (page: Page): Locator => page.getByRole('dialog', { name: 'Fusion Request' })
/**
* Log the admin's LOG_DAY through the API when it is not logged yet, and say
* whether it did. The colour guide's result shows logged days in the new
* colour; run on its own (a --grep re-render) the plan had none, so the
* result showed only the small dot in Persons changing.
*/
async function ensureOwnDay(page: Page): Promise<boolean> {
const date = nextMonthDate(LOG_DAY)
const res = await page.request.get(`/api/addons/vacay/entries/${YEAR}`)
if (!res.ok()) throw new Error(`could not load the entries: ${res.status()}`)
const me = await adminId(page)
const { entries } = (await res.json()) as { entries: { user_id: number; date: string }[] }
if (entries.some(e => e.user_id === me && e.date === date)) return false
await toggleOwnDay(page, date)
return true
}
async function toggleOwnDay(page: Page, date: string): Promise<void> {
const res = await page.request.post('/api/addons/vacay/entries/toggle', { data: { date, fraction: 1, kind: 'vacation' } })
if (!res.ok()) throw new Error(`could not toggle ${date}: ${res.status()}`)
}
/**
* Days mira has off in her own plan while she shares it with the admin. Without
* them her shared calendar drew nothing on the grid, so the guide about rings
* on the grid showed none.
*/
const SHARED_DAYS = WORKDAYS.slice(6, 8).map(nextMonthDate)
/** Log (`on`) or clear mira's SHARED_DAYS in her own plan, leaving days already as wanted alone. */
async function setPartnerOwnDays(on: boolean): Promise<void> {
const member = await asMember()
try {
const me = (await (await member.get('/api/auth/me')).json()) as { user: { id: number } }
const res = await member.get(`/api/addons/vacay/entries/${YEAR}`)
if (!res.ok()) throw new Error(`could not load ${PARTNER.username}'s entries: ${res.status()}`)
const { entries } = (await res.json()) as { entries: { user_id: number; date: string }[] }
for (const date of SHARED_DAYS) {
const logged = entries.some(e => e.user_id === me.user.id && e.date === date)
if (logged === on) continue
const t = await member.post('/api/addons/vacay/entries/toggle', { data: { date, fraction: 1, kind: 'vacation' } })
if (!t.ok()) throw new Error(`could not toggle ${PARTNER.username}'s ${date}: ${t.status()}`)
}
} finally {
await member.dispose()
}
}
/** What a guide has to put back, read in its start and used in its cleanup. */
let savedColor = ''
let loggedForColor = false
let savedCalendarColors = new Map<number, string>()
let christmasEveBefore: number | null = null
@@ -342,7 +391,12 @@ const SCRIPTS: Record<string, GuideScript> = {
// The chip with its minus showing, rather than the minus alone: the step
// says to hover the chip, and a ring round the tiny minus put its number
// on top of the year it belongs to.
prepare: async p => { await yearChip(p, YEAR + 1).hover() },
// The chip clicked last keeps the focus, and a focused chip shows its
// minus too, so the picture had two minuses; the focus goes first.
prepare: async p => {
await p.evaluate(() => { (document.activeElement as HTMLElement | null)?.blur() })
await yearChip(p, YEAR + 1).hover()
},
target: p => yearChip(p, YEAR + 1),
// With the ring on the chip, this is what still fails the guide when the minus is gone.
act: async p => { await expect(yearChip(p, YEAR + 1).getByRole('button', { name: 'Remove year' })).toBeVisible() },
@@ -552,6 +606,7 @@ const SCRIPTS: Record<string, GuideScript> = {
guide: guide('person-color'),
start: async p => {
savedColor = await ownColor(p)
loggedForColor = await ensureOwnDay(p)
await openVacay(p)
},
steps: [
@@ -569,7 +624,10 @@ const SCRIPTS: Record<string, GuideScript> = {
},
},
],
cleanup: async p => { await setOwnColor(p, savedColor) },
cleanup: async p => {
await setOwnColor(p, savedColor)
if (loggedForColor) await toggleOwnDay(p, nextMonthDate(LOG_DAY))
},
},
invite: {
@@ -725,6 +783,7 @@ const SCRIPTS: Record<string, GuideScript> = {
// so mira shares hers with the admin first. The page learns of it over
// the socket; a reload is the fallback should that message not come.
prepare: async p => {
await setPartnerOwnDays(true)
await shareWithAdmin(p)
const incoming = cardRow(p, 'Shared Calendars', PARTNER.username)
if (!(await incoming.waitFor({ state: 'visible', timeout: 8_000 }).then(() => true, () => false))) await openVacay(p)
@@ -735,7 +794,10 @@ const SCRIPTS: Record<string, GuideScript> = {
hover: async p => { await cardRow(p, 'Shared Calendars', 'jonas').hover() },
},
],
cleanup: unshareWithAdmin,
cleanup: async p => {
await unshareWithAdmin(p)
await setPartnerOwnDays(false)
},
},
}
+22 -3
View File
@@ -18,11 +18,30 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {
TrekSharedFiles.receive(context.url)
}
// Launched by a tap on a widget or a Live Activity: held like a quick action.
// Capacitor still hears of the link, the UI ignores it there (feature appLinks).
for context in connectionOptions.urlContexts {
// Capacitor must not hear of the link as well, or a UI that still follows the
// launch URL (a server before feature appLinks) opens the page twice.
let appLinks = connectionOptions.urlContexts.filter { TrekQuickActions.appLinkPath($0.url) != nil }
for context in appLinks {
if let path = TrekQuickActions.appLinkPath(context.url) { TrekQuickActions.open(path: path) }
}
SceneDelegateProxy.shared.scene(scene, willConnectTo: session, options: connectionOptions)
if appLinks.isEmpty {
SceneDelegateProxy.shared.scene(scene, willConnectTo: session, options: connectionOptions)
} else {
connectWithoutAppLinks(scene, others: connectionOptions.urlContexts.subtracting(appLinks),
activities: connectionOptions.userActivities)
}
}
/// What SceneDelegateProxy does on a launch, for the links it may have: the
/// options cannot be rebuilt without the app links, so they go in here.
private func connectWithoutAppLinks(_ scene: UIScene, others: Set<UIOpenURLContext>, activities: Set<NSUserActivity>) {
NotificationCenter.default.post(name: .capacitorSceneWillConnect, object: scene)
var token: NSObjectProtocol?
token = NotificationCenter.default.addObserver(forName: .capacitorViewDidAppear, object: nil, queue: .main) { _ in
if let token { NotificationCenter.default.removeObserver(token) }
if !others.isEmpty { SceneDelegateProxy.shared.scene(scene, openURLContexts: others) }
for activity in activities { SceneDelegateProxy.shared.scene(scene, continue: activity) }
}
}
// The app switcher takes its snapshot as the scene resigns active, so the
@@ -121,6 +121,9 @@ class TrekBridgeViewController: CAPBridgeViewController {
right: max(0, safe.right - (window.bounds.maxX - frame.maxX))
)
let corner = cornerElement(in: frame, window: window)
if corner != .zero, UIDevice.current.model == "iPhone", cornerWindowSizes.insert(sizeKey(window.bounds.size)).inserted {
setNeedsStatusBarAppearanceUpdate()
}
if !force, insets == publishedSafeArea, corner == publishedCorner { return }
publishedSafeArea = insets
publishedCorner = corner
@@ -139,15 +142,37 @@ class TrekBridgeViewController: CAPBridgeViewController {
private var publishedCorner: UIEdgeInsets?
// MARK: - The status bar beside a corner element
/// The window sizes on which a corner element was seen. On an iPhone Duo
/// that element is the status capsule, so the app hides the status bar
/// there to take the capsule away; whatever still covers the corner stays
/// in the safe area the page keeps clear of. A size stays in the set
/// once seen: with the bar hidden the next measure may find no corner, and
/// showing the bar again would bring the capsule back and start over. The
/// folded and the unfolded display differ in size, so each keeps its own
/// answer, and a device without such an element never hides its bar. Only
/// on an iPhone: an iPad's window controls are such an element as well.
private var cornerWindowSizes = Set<String>()
private func sizeKey(_ size: CGSize) -> String {
"\(Int(size.width.rounded()))x\(Int(size.height.rounded()))"
}
override var prefersStatusBarHidden: Bool {
if super.prefersStatusBarHidden { return true }
guard let size = view.window?.bounds.size else { return false }
return cornerWindowSizes.contains(sizeKey(size))
}
/// An element in a top corner of the screen, such as the status capsule of
/// an iPhone Duo: how far down it reaches (top) and how wide it is on its
/// side (left/right), in the web view's coordinates; zero where there is
/// none. iOS 26 tells a corner apart from a whole edge: the safe area with
/// the corner avoided vertically reaches lower than the one avoiding it
/// horizontally, which in turn is wider on the corner's side. The page puts
/// its top bar beside the element and starts its content below it, using
/// the full width (mobile.css), instead of giving up a strip of the whole
/// height.
/// horizontally, which in turn is wider on the corner's side. The page
/// counts it into its safe area (mobile.css): upright its content starts
/// below the element, on a wide window it leaves the element's side free.
private func cornerElement(in frame: CGRect, window: UIWindow) -> UIEdgeInsets {
guard #available(iOS 26.0, *) else { return .zero }
let vertical = view.edgeInsets(for: .safeArea(cornerAdaptation: .vertical))
@@ -477,9 +502,14 @@ enum TrekServerStore {
/// filled in with that server (previousURL). Raise both together.
private static let serverCheck = 3
private static var rechecked = false
/// Runs before the first bridge is built, so a server picked under an older
/// minimum is not loaded unchecked.
/// minimum is not loaded unchecked. Once per launch: the bridge that
/// restoreForOffline restarts must keep the server it put back.
static func recheckAfterUpdate() {
guard !rechecked else { return }
rechecked = true
let defaults = UserDefaults.standard
guard defaults.integer(forKey: checkedKey) < serverCheck else { return }
defaults.set(serverCheck, forKey: checkedKey)
+21 -2
View File
@@ -686,9 +686,8 @@ extension TrekShellPlugin {
/// know are left out, so the shell offers only what can really be bought.
@objc func storeProducts(_ call: CAPPluginCall) {
let ids = call.getArray("ids", String.self) ?? []
// TestFlight, App Review and Xcode builds buy in the sandbox; their receipt says so.
let sandbox = Bundle.main.appStoreReceiptURL?.lastPathComponent == "sandboxReceipt"
Task {
let sandbox = await Self.buysInSandbox()
guard AppStore.canMakePayments, let products = try? await Product.products(for: ids) else {
call.resolve(["products": [], "sandbox": sandbox])
return
@@ -697,6 +696,26 @@ extension TrekShellPlugin {
}
}
/// Whether this build buys in the App Store sandbox: TestFlight, App Review and
/// Xcode builds do, and while TREK Cloud's orders are closed only they may buy.
/// The signed app transaction names its environment; the receipt's file name,
/// which App Review builds do not always carry, is only the fallback where the
/// app transaction is missing (iOS 15) or cannot be read.
static func buysInSandbox() async -> Bool {
let receiptSaysSandbox = Bundle.main.appStoreReceiptURL?.lastPathComponent == "sandboxReceipt"
guard #available(iOS 16.0, *), let result = try? await AppTransaction.shared else {
return receiptSaysSandbox
}
// An unverified transaction still names the environment it was signed in;
// it only decides whether the button shows, the cloud checks every purchase itself.
let transaction: AppTransaction
switch result {
case .verified(let signed), .unverified(let signed, _):
transaction = signed
}
return transaction.environment != .production || receiptSaysSandbox
}
/// Feature storeKit: runs the App Store purchase sheet. Resolves with `kind`
/// bought (with the signed transaction the control plane verifies), cancelled,
/// pending (Ask to Buy, a payment the bank still has to approve) or failed.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 104 KiB

After

Width:  |  Height:  |  Size: 49 KiB

@@ -165,14 +165,20 @@ enum TrekDate {
guard let iso, iso.count >= 10 else { return nil }
let ymd = iso.prefix(10).split(separator: "-").compactMap { Int($0) }
guard ymd.count == 3 else { return nil }
return Calendar.current.date(from: DateComponents(year: ymd[0], month: ymd[1], day: ymd[2]))
return gregorian().date(from: DateComponents(year: ymd[0], month: ymd[1], day: ymd[2]))
}
static func iso(_ date: Date) -> String {
let parts = Calendar.current.dateComponents([.year, .month, .day], from: date)
let parts = gregorian().dateComponents([.year, .month, .day], from: date)
return String(format: "%04d-%02d-%02d", parts.year ?? 0, parts.month ?? 0, parts.day ?? 0)
}
private static func gregorian() -> Calendar {
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = .current
return calendar
}
/// yyyy-MM-dd and HH:mm as a moment, in `zone` when given, else here; midnight without a time.
static func moment(_ date: String?, _ time: String?, zone: String? = nil) -> Date? {
guard let date, date.count >= 10 else { return nil }
@@ -21,12 +21,14 @@ struct TrekProvider: TimelineProvider {
func getSnapshot(in context: Context, completion: @escaping (TrekEntry) -> Void) {
let stored = WidgetSnapshot.load()
let snapshot: WidgetSnapshot? = (stored?.trip != nil || !context.isPreview) ? stored : WidgetSnapshot.sample(running: false)
completion(TrekEntry(date: Date(), snapshot: snapshot))
let now = Date()
completion(TrekEntry(date: now, snapshot: snapshot?.on(now)))
}
/// An entry every quarter hour for the next six hours, so the now line and
/// the next stop move on without the app; the app reloads the timeline
/// whenever it writes a new snapshot.
/// the next stop move on without the app, each with the trip day of its own
/// date: the one at midnight turns to the next day. The app reloads the
/// timeline whenever it writes a new snapshot, WidgetKit when it runs out.
func getTimeline(in context: Context, completion: @escaping (Timeline<TrekEntry>) -> Void) {
completion(TrekProvider.timeline(WidgetSnapshot.load()))
}
@@ -36,10 +38,11 @@ struct TrekProvider: TimelineProvider {
let calendar = Calendar.current
let minute = calendar.component(.minute, from: now)
let firstStep = calendar.date(byAdding: .minute, value: 15 - minute % 15, to: now) ?? now
var entries = [TrekEntry(date: now, snapshot: snapshot)]
var entries = [TrekEntry(date: now, snapshot: snapshot?.on(now))]
for step in 0..<24 {
if let date = calendar.date(byAdding: .minute, value: step * 15, to: firstStep) {
entries.append(TrekEntry(date: calendar.date(bySetting: .second, value: 0, of: date) ?? date, snapshot: snapshot))
let at = calendar.date(bySetting: .second, value: 0, of: date) ?? date
entries.append(TrekEntry(date: at, snapshot: snapshot?.on(at)))
}
}
return Timeline(entries: entries, policy: .atEnd)
+29 -10
View File
@@ -512,8 +512,8 @@ struct StopList: View {
ForEach(Array(window.enumerated()), id: \.offset) { offset, stop in
let past = (stop.minutes ?? Int.max) < nowMinutes
let isNext = !past && (offset == 0 || (window[offset - 1].minutes ?? Int.max) < nowMinutes)
if isNext && offset > 0, let nowLabel { nowLine(nowLabel) }
row(stop, past: past, isNext: isNext, last: offset == window.count - 1)
if isNext && offset > 0, let nowLabel { nowLine(nowLabel, in: window) }
row(stop, in: window, past: past, isNext: isNext, last: offset == window.count - 1)
}
}
}
@@ -528,13 +528,33 @@ struct StopList: View {
private var ink: Color { onPhoto ? .white : Trek.ink(scheme) }
private func row(_ stop: WidgetSnapshot.Stop, past: Bool, isNext: Bool, last: Bool) -> some View {
/// The time column, as wide as the longest time in the window (and the now
/// marker's label): every row lays all of them over each other, hidden, so
/// "5:45 AM" fits as well as "09:30" and the dots still stand in one line.
private func timeColumn<Label: View>(_ window: [WidgetSnapshot.Stop], @ViewBuilder label: () -> Label) -> some View {
ZStack(alignment: .leading) {
ForEach(Array(window.enumerated()), id: \.offset) { _, stop in
Text(stop.time ?? "–").font(Trek.number(11.5, .heavy)).hidden()
}
if let nowLabel { nowText(nowLabel).hidden() }
label()
}
.lineLimit(1)
.fixedSize(horizontal: true, vertical: false)
.frame(minWidth: 38, alignment: .leading)
}
private func nowText(_ label: String) -> some View {
Text(label.uppercased()).font(.system(size: 8.5, weight: .heavy)).tracking(0.5).foregroundStyle(Trek.danger)
}
private func row(_ stop: WidgetSnapshot.Stop, in window: [WidgetSnapshot.Stop], past: Bool, isNext: Bool, last: Bool) -> some View {
let color = Color(css: stop.color) ?? (onPhoto ? .white : Trek.info)
return HStack(alignment: .top, spacing: 8) {
Text(stop.time ?? "–")
.font(Trek.number(11.5, isNext ? .heavy : .semibold))
.frame(width: 38, alignment: .leading)
.padding(.top, 1)
timeColumn(window) {
Text(stop.time ?? "–").font(Trek.number(11.5, isNext ? .heavy : .semibold))
}
.padding(.top, 1)
VStack(spacing: 0) {
ZStack {
Circle().fill(color).frame(width: isNext ? 11 : 8, height: isNext ? 11 : 8)
@@ -562,10 +582,9 @@ struct StopList: View {
.frame(height: 24, alignment: .top)
}
private func nowLine(_ label: String) -> some View {
private func nowLine(_ label: String, in window: [WidgetSnapshot.Stop]) -> some View {
HStack(spacing: 5) {
Text(label.uppercased()).font(.system(size: 8.5, weight: .heavy)).tracking(0.5).foregroundStyle(Trek.danger)
.frame(width: 38, alignment: .leading)
timeColumn(window) { nowText(label) }
Circle().fill(Trek.danger).frame(width: 5, height: 5).frame(width: 15)
Rectangle().fill(Trek.danger).frame(height: 1.2)
}
+2 -1
View File
@@ -63,7 +63,8 @@ struct TrekTripProvider: AppIntentTimelineProvider {
func snapshot(for configuration: SelectTripIntent, in context: Context) async -> TrekEntry {
let stored = WidgetSnapshot.load(trip: configuration.trip?.id)
let snapshot: WidgetSnapshot? = (stored?.trip != nil || !context.isPreview) ? stored : WidgetSnapshot.sample(running: false)
return TrekEntry(date: Date(), snapshot: snapshot)
let now = Date()
return TrekEntry(date: now, snapshot: snapshot?.on(now))
}
func timeline(for configuration: SelectTripIntent, in context: Context) async -> Timeline<TrekEntry> {
@@ -35,6 +35,8 @@ struct WidgetSnapshot: Codable {
}
struct Today: Codable {
/// The calendar day it is, yyyy-MM-dd (absent from an app that predates `days`).
var date: String?
var dayLabel: String
var stops: [Stop]
/// 1-based position of today in the trip.
@@ -245,6 +247,9 @@ struct WidgetSnapshot: Codable {
var trip: Trip?
var today: Today?
/// The trip's days from the day the app wrote this on, each with its date,
/// so the widget turns to the next day itself (see `on(_:)`).
var days: [Today]?
var weather: Weather?
var bookings: [Booking]?
var todos: Todos?
@@ -306,6 +311,28 @@ struct WidgetSnapshot: Codable {
return days + 1
}
/// The snapshot as it reads on `date`: that date's trip day out of `days`,
/// none before or after the trip, and only the bookings from that date on.
/// The app writes its snapshot only while it runs, so without this a widget
/// showed the day it last ran (TestFlight feedback: "stuck on day 1"). A
/// snapshot from an app without `days` reads as it was written.
func on(_ date: Date) -> WidgetSnapshot {
guard let days, !days.isEmpty else { return self }
let key = WidgetSnapshot.key(date)
var snapshot = self
if today?.date != key { snapshot.today = days.first { $0.date == key } }
snapshot.bookings = bookings?.filter { ($0.date ?? key) >= key }
return snapshot
}
/// A date as the app writes one, yyyy-MM-dd in the device's calendar day.
static func key(_ date: Date) -> String {
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = .current
let parts = calendar.dateComponents([.year, .month, .day], from: date)
return String(format: "%04d-%02d-%02d", parts.year ?? 0, parts.month ?? 0, parts.day ?? 0)
}
static func daysBetween(_ from: Date, _ to: Date) -> Int? {
let calendar = Calendar.current
return calendar.dateComponents([.day], from: calendar.startOfDay(for: from), to: calendar.startOfDay(for: to)).day
+8 -8
View File
@@ -53,7 +53,7 @@
"format:check": "prettier --check \"src/**/*.tsx\" \"src/**/*.css\""
},
"dependencies": {
"@assistant-ui/react": "0.15.36",
"@assistant-ui/react": "0.15.37",
"@capacitor/action-sheet": "^8.1.1",
"@capacitor/android": "^8.6.2",
"@capacitor/app": "^8.1.1",
@@ -112,8 +112,8 @@
"iso-3166-2": "^1.0.0",
"leaflet": "^1.9.4",
"lucide-react": "^0.577.0",
"mapbox-gl": "^3.35.0",
"maplibre-gl": "6.18.0",
"mapbox-gl": "^3.35.2",
"maplibre-gl": "6.19.0",
"modern-screenshot": "4.7.0",
"plyr": "^3.8.5",
"react": "^19.3.1",
@@ -135,10 +135,10 @@
"@eslint/js": "^10.0.1",
"@jscpd/core": "^4.2.5",
"@jscpd/tokenizer": "^4.2.6",
"@playwright/test": "^1.65.0",
"@playwright/test": "^1.65.1",
"@testing-library/jest-dom": "^6.10.0",
"@testing-library/react": "^16.3.3",
"@testing-library/user-event": "^14.6.10",
"@testing-library/user-event": "^14.6.13",
"@trivago/prettier-plugin-sort-imports": "^6.0.2",
"@types/leaflet": "^1.9.22",
"@types/node": "^25.9.8",
@@ -146,16 +146,16 @@
"@types/react-dom": "^19.3.0",
"@vitejs/plugin-react": "^6.2.1",
"@vitest/coverage-v8": "^4.1.12",
"autoprefixer": "^10.6.2",
"autoprefixer": "^10.7.0",
"eslint": "^10.11.0",
"eslint-config-flat-gitignore": "^2.4.0",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.7",
"eslint-plugin-react-refresh": "^0.5.8",
"fake-indexeddb": "^6.2.7",
"jsdom": "^29.1.1",
"msw": "^2.15.0",
"postcss": "^8.5.28",
"postcss": "^8.5.33",
"prettier": "^3.10.1",
"prettier-plugin-organize-imports": "^4.3.0",
"prettier-plugin-tailwindcss": "^0.8.1",
+4 -1
View File
@@ -143,7 +143,10 @@ export default defineConfig({
stderr: 'pipe',
},
{
command: 'npm run dev',
// E2E_WEB_PREVIEW serves the client already built in dist/ (`npm run build`
// first) instead of a dev server compiling it again: several media runs at
// once otherwise spend the machine on Vite and time out on the first page.
command: process.env.E2E_WEB_PREVIEW ? `npx vite preview --port ${WEB_PORT} --strictPort` : 'npm run dev',
port: WEB_PORT,
env: { TREK_DEV_PORT: String(WEB_PORT), TREK_DEV_API: `http://localhost:${API_PORT}` },
reuseExistingServer: !process.env.CI,
Binary file not shown.

Before

Width:  |  Height:  |  Size: 113 KiB

After

Width:  |  Height:  |  Size: 117 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 46 KiB

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 177 KiB

After

Width:  |  Height:  |  Size: 179 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 73 KiB

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 63 KiB

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 97 KiB

After

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 98 KiB

After

Width:  |  Height:  |  Size: 104 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 36 KiB

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 76 KiB

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 35 KiB

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 39 KiB

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 37 KiB

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 51 KiB

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 126 KiB

After

Width:  |  Height:  |  Size: 123 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 37 KiB

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 164 KiB

After

Width:  |  Height:  |  Size: 164 KiB

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