Compare commits

..

19 Commits

Author SHA1 Message Date
Maurice 87107d7cba fix(atlas): keep the cached regions projection typed as unknown
The offline snapshot may contain any legacy value. Explicitly retain its unknown type throughout the queue projection to pass the strict client type check.
2026-12-06 18:09:21 +01:00
Maurice 4516edfdad fix(ci): repair client checks for the audit fixes
Keep tile substitution compatible with ES2020 and refresh confirmed bulk settings without replacing live values. Make the Atlas cache fallback explicit and check that removing the last region clears its map entry.
2026-12-06 18:01:48 +01:00
Maurice 360bea8bf4 fix(atlas): refresh the open globe after offline region removal
Use the same queued Atlas projection for an open globe and for an offline restart.
2026-12-06 17:24:39 +01:00
Maurice e3922b76d8 fix(atlas): reconcile offline country and region changes together
Keep country and region reads in step with queued writes and with the mark source held by the server. Reconcile a delete already applied elsewhere before removing it from the account queue.
2026-12-06 17:24:10 +01:00
Maurice da0ecc3f88 fix(atlas): keep online actions usable when the cache fails
Return successful server responses even when IndexedDB is unavailable. Keep the offline queue in use whenever it is readable, and do not cache a response after the account changes.
2026-12-06 17:20:39 +01:00
Maurice a796383e3f fix(journey): retry unsent follower digests
Record pending entries per follower alongside the in-app announcement. Retry only unsettled deliveries and recheck current sharing and entry visibility before composing mail.
2026-12-06 17:20:10 +01:00
Maurice 36bf9fb223 fix(offline): keep account credentials out of the settings cache
Keep only offline presentation and map preferences and scrub old cached settings on access. Update the cache from successful writes without retaining preferences the server declined.
2026-12-06 16:04:52 +01:00
Maurice bbaedc5aa9 docs: document Atlas tools and OpenRouter routing
Document the Atlas comparison default, the custom trip tag inputs and the OpenRouter upstream setting.
2026-12-06 16:04:32 +01:00
Maurice dcbabe998b fix(map): use stored basemaps for uncached GL raster hosts
Share the service-worker raster match with prefetch and the offline renderer. Keep an allowed custom host online and switch to the stored basemap offline when its tiles are outside the readable cache.
2026-12-06 16:04:31 +01:00
Maurice f394818f40 fix(mail-ingest): create missing IMAP archive parent on demand 2026-12-05 13:27:17 +01:00
Luffy b15cd49833 fix(mail-ingest): enhance header processing to prioritize X-Forwarded-To for IMAP 2026-12-05 13:27:17 +01:00
Luffy a4bd40cb0a fix(externalNotifications): improve clarity of pending booking notification message 2026-12-05 13:27:16 +01:00
Luffy 7713e37a8d fix(mail-ingest): create IMAP archive folders only when needed 2026-12-05 13:27:16 +01:00
Maurice 543af0cbcb Merge pull request #3319 from liketrek/codex/trip-tags-desktop-polish
Add custom trip tags and refine the desktop interface
2026-12-05 13:26:40 +01:00
Maurice f3bbd1a268 fix(ci): align packing parity and simplify offline sync
Describe bringer input in the shared packing contract and check its trip event against the REST contributor operation. Keep offline map preparation in its own step without changing the order or the sign-out checks.
2026-12-05 12:45:31 +01:00
Maurice 09567d32c4 fix(packing): serialize bringer and privacy updates
Use the shared write transaction for packing item updates and contributor edits. Remove Common bringers when an item becomes restricted and scope contributor broadcasts to the returned item viewers.
2026-12-05 12:35:18 +01:00
Maurice b79d104349 fix(ios): verify the shell before saving offline trips
Recheck cached assets during explicit offline preparation even when the build is marked warm. Keep the existing start page, trip cache, and pin if this check fails. Keep the ordinary launch fast path for warm builds.

Refs #3318
2026-12-05 12:35:18 +01:00
Maurice 06ee5a850b feat(mcp): set bringers for a packing item
Let packing editors replace the bringers on a Common item in one write. Use the existing trip roster, item visibility and packing edit policy, and leave the sharing tier and recipients alone.

Closes #3313
2026-12-05 12:30:17 +01:00
Maurice f7c45a2d85 fix(ios): prepare the app shell before finishing offline downloads
Download the app shell as part of explicit offline preparation on iOS. Refuse to mark a build ready if any asset fetch returns an HTTP error, and invalidate success markers recorded by the old logic.

Refs #3318
2026-12-05 12:24:23 +01:00
63 changed files with 1658 additions and 390 deletions
@@ -33,12 +33,14 @@ describe('offlineBasemap', () => {
expect(leafletWorksOffline('https://tile.openstreetmap.org/{z}/{x}/{y}.png', false)).toBe(false);
});
it('draws a MapLibre raster template offline where Leaflet would keep the same tiles', () => {
it('keeps only MapLibre raster templates supported by the CORS cache', () => {
const own = mapLibreBasemap('trek:template', 'https://tiles.example.com/{z}/{x}/{y}.png', false, [
'tiles.example.com',
]);
const osm = mapLibreBasemap('trek:template', 'https://tile.openstreetmap.org/{z}/{x}/{y}.png', false, []);
expect(glWorksOffline('maplibre-gl', own.style)).toBe(true);
const cached = mapLibreBasemap('trek:template', 'https://tile.openstreetmap.de/{z}/{x}/{y}.png', false, []);
expect(glWorksOffline('maplibre-gl', cached.style)).toBe(true);
expect(glWorksOffline('maplibre-gl', own.style)).toBe(false);
// The OSM tile usage policy forbids storing its tiles, so the stored basemap stands in.
expect(glWorksOffline('maplibre-gl', osm.style)).toBe(false);
expect(glWorksOffline('mapbox-gl', own.style)).toBe(false);
+7 -4
View File
@@ -1,5 +1,6 @@
import { OFM_DARK, OFM_POSITRON } from '../../constants/mapDefaults';
import { isNativeIos } from '../../native/platform';
import { hasGlRasterCache } from '../../sync/glTileCache';
import { isOfflineForbiddenTemplate, isVectorStyle } from '../../utils/tileUrl';
import { isGlRasterStyle, type GlStyle } from './glBasemap';
import { normalizeStyleForProvider, type GlMapProvider } from './glProviders';
@@ -25,13 +26,15 @@ export function offlineStyleFor(dark: boolean): string {
/**
* Whether a GL map can be drawn offline as configured. Only MapLibre can, on
* one of the stored styles (another OpenFreeMap style lacks its sprite and
* glyphs offline) or on a raster template whose tiles the prefetch stored the
* way Leaflet's are; Mapbox has nothing stored to draw from. `style` is what the
* map draws: the slot's value, or the style a keyword resolved to.
* glyphs offline) or on a raster template the worker caches with CORS. Mapbox
* has nothing stored to draw from. `style` is the map's resolved style.
*/
export function glWorksOffline(provider: GlMapProvider, style: GlStyle | null | undefined): boolean {
if (provider !== 'maplibre-gl') return false;
if (isGlRasterStyle(style)) return leafletWorksOffline(style.metadata['trek:template']);
if (isGlRasterStyle(style)) {
const template = style.metadata['trek:template'];
return leafletWorksOffline(template) && hasGlRasterCache(template);
}
return OFFLINE_STYLES.includes(normalizeStyleForProvider('maplibre-gl', style));
}
@@ -264,6 +264,21 @@ describe('useEffectiveMapEngine: the MapLibre keywords', () => {
expect(result.current.pill).toBeNull();
});
it('FE-MAP-EFFENGINE-041: a custom GL raster host swaps offline and returns when online', () => {
settings({ map_provider: 'maplibre-gl', maplibre_style: 'trek:template' });
seedStore(useAuthStore, { mapExtraConnectHosts: ['tiles.example.com'] });
const { result, rerender } = renderHook(() => useEffectiveMapEngine(OWN_RASTER));
expect(result.current).toMatchObject({
engine: 'maplibre-gl',
styleOverride: OFM_POSITRON,
pill: { kind: 'stored' },
});
env.offline = false;
rerender();
expect(styleSource(result.current.styleOverride)?.tiles).toEqual([OWN_RASTER]);
expect(result.current.pill).toBeNull();
});
it('FE-MAP-EFFENGINE-038: OpenStreetMap, never stored, swaps to the stored basemap', () => {
settings({ map_provider: 'maplibre-gl', maplibre_style: 'trek:template' });
const { result } = renderHook(() => useEffectiveMapEngine('https://tile.openstreetmap.org/{z}/{x}/{y}.png'));
@@ -12,6 +12,13 @@ import { deleteCurrentUserDb, offlineDb, reopenAnonymous, reopenForUser } from '
const LIBERTY = 'https://tiles.openfreemap.org/styles/liberty';
const OSM = 'https://tile.openstreetmap.org/{z}/{x}/{y}.png';
const PRIVATE_SETTINGS = {
llm_api_key: 'test-llm-key',
webhook_url: 'https://example.test/test-webhook',
ntfy_token: 'test-ntfy-token',
assistant_memory: { '1': 'test-assistant-memory' },
future_server_preference: 'test-unknown-value',
};
afterEach(async () => {
vi.restoreAllMocks();
@@ -91,4 +98,63 @@ describe('account settings kept offline', () => {
await expect(cacheAccountSettings({ map_provider: 'maplibre-gl' })).resolves.toBeUndefined();
await expect(cacheAccountSettingsPatch({ map_provider: 'maplibre-gl' })).resolves.toBeUndefined();
});
it('FE-DB-ACCOUNTSETTINGS-008: writes only the offline preferences from a server answer', async () => {
await reopenForUser(701);
const preferences = {
language: 'de',
start_page: 'active_trip',
temperature_unit: 'celsius',
mapbox_access_token: 'pk.test-public-map-token',
carto_api_key: 'test-public-tile-key',
} as const;
await cacheAccountSettings({ ...PRIVATE_SETTINGS, ...preferences });
expect(await offlineDb.accountSettings.get('account')).toEqual({ key: 'account', settings: preferences });
});
it('FE-DB-ACCOUNTSETTINGS-009: filters old cached values and the new patch before writing', async () => {
await reopenForUser(701);
await offlineDb.accountSettings.put({
key: 'account',
settings: { ...PRIVATE_SETTINGS, map_provider: 'leaflet', mapbox_access_token: 'pk.test-old-map-token' },
});
await cacheAccountSettingsPatch({
...PRIVATE_SETTINGS,
mapbox_access_token: 'sk.test-private-map-token',
distance_unit: 'imperial',
});
expect(await offlineDb.accountSettings.get('account')).toEqual({
key: 'account',
settings: { map_provider: 'leaflet', distance_unit: 'imperial' },
});
});
it('FE-DB-ACCOUNTSETTINGS-010: reads and replaces a legacy row with just the offline preferences', async () => {
await reopenForUser(701);
await offlineDb.accountSettings.put({
key: 'account',
settings: { ...PRIVATE_SETTINGS, map_tile_url: OSM, mapbox_access_token: 'sk.test-private-map-token' },
});
expect(await cachedAccountSettings()).toEqual({ map_tile_url: OSM });
expect(await offlineDb.accountSettings.get('account')).toEqual({
key: 'account',
settings: { map_tile_url: OSM },
});
});
it('FE-DB-ACCOUNTSETTINGS-011: returns only offline preferences even when the scrub cannot write', async () => {
await reopenForUser(701);
await offlineDb.accountSettings.put({
key: 'account',
settings: { ...PRIVATE_SETTINGS, map_tile_url: OSM },
});
vi.spyOn(offlineDb.accountSettings, 'put').mockRejectedValue(new Error('refused'));
expect(await cachedAccountSettings()).toEqual({ map_tile_url: OSM });
});
});
+94 -9
View File
@@ -10,35 +10,119 @@ import { isAccountDb, offlineDb } from './offlineDb';
*
* The row lives in the signed-in user's own database (offlineDb.ts), so another
* account on the device never reads it, and logout deletes it with the database.
* It holds what the server sent this user, the map keys included: the trip data
* beside it is no less private, and without the CARTO key a stored CARTO
* template could not be drawn offline. Secrets the server masks arrive masked.
* Only the preferences needed by the offline UI go into this row.
*
* Every function here is best effort and never rejects. A device that cannot
* keep the row (IndexedDB refused in a private window) behaves as before: it
* starts on the defaults until the server answers.
*/
const OFFLINE_SETTINGS = new Set<string>([
'appearance',
'dark_mode',
'language',
'place_language',
'start_page',
'start_trip_tab',
'default_currency',
'temperature_unit',
'distance_unit',
'time_format',
'week_start',
'date_format',
'dashboard_fx_from',
'dashboard_fx_to',
'dashboard_timezones',
'map_provider',
'map_tile_url',
'map_base_layer',
'maplibre_style',
'mapbox_style',
'mapbox_3d_enabled',
'mapbox_quality_mode',
'map_hide_basemap_pois',
'map_compact_unplanned',
'map_booking_labels',
'map_place_labels',
'map_poi_pill_enabled',
'map_always_show_routes',
'show_place_description',
'blur_booking_codes',
'day_date_first',
'preferred_nav_app',
'optimize_from_accommodation',
'planner_trip_views',
'roadtrip_vehicle',
'roadtrip_leg_minutes',
'roadtrip_day_minutes',
'roadtrip_day_start',
'roadtrip_day_end',
'roadtrip_day_end_mode',
'roadtrip_range_km',
'roadtrip_avoid',
'roadtrip_connect_days',
'roadtrip_day_colors',
'roadtrip_fill_percent',
'roadtrip_tank_litres',
'roadtrip_litres_per_100',
'roadtrip_battery_kwh',
'roadtrip_kwh_per_100',
'roadtrip_battery_degradation',
// The browser needs this tile key to resolve the same CARTO URL when offline.
'carto_api_key',
] satisfies (keyof Settings)[]);
function offlineSettingsOf(settings: Partial<Settings>): Partial<Settings> {
const entries = Object.entries(settings).filter(([key]) => OFFLINE_SETTINGS.has(key));
const kept: Partial<Settings> = Object.fromEntries(entries);
const token = settings.mapbox_access_token;
// A Mapbox browser token keeps the user's selected engine available offline.
if (typeof token === 'string' && (token === '' || token.startsWith('pk.'))) kept.mapbox_access_token = token;
return kept;
}
/** The settings the server last answered, or null when this device kept none. */
export async function cachedAccountSettings(): Promise<Partial<Settings> | null> {
let settings: Partial<Settings> | null = null;
try {
if (!isAccountDb()) return null;
return (await offlineDb.accountSettings.get('account'))?.settings ?? null;
const table = offlineDb.accountSettings;
await offlineDb.transaction('rw', table, async () => {
const row = await table.get('account');
if (!row) return;
settings = offlineSettingsOf(row.settings);
if (Object.keys(settings).length !== Object.keys(row.settings).length) {
await table.put({ key: 'account', settings });
}
});
} catch {
return null;
/* If the disk update fails, still use the filtered settings from memory. */
}
return settings;
}
/** Keeps the server's answer, replacing the one kept before. */
export async function cacheAccountSettings(settings: Partial<Settings>): Promise<void> {
try {
if (!isAccountDb()) return;
await offlineDb.accountSettings.put({ key: 'account', settings });
await offlineDb.accountSettings.put({ key: 'account', settings: offlineSettingsOf(settings) });
} catch {
/* Nothing kept: the next start without a connection shows the defaults, as it always did. */
}
}
/** Refresh a partial write's result without changing the live settings. */
export async function refreshCachedAccountSettings(load: () => Promise<Partial<Settings>>): Promise<void> {
if (!isAccountDb()) return;
const account = offlineDb.name;
try {
const settings = await load();
if (account === offlineDb.name) await cacheAccountSettings(settings);
} catch {
// Keep the last confirmed settings until the next successful read.
}
}
/**
* Lays settings the server just accepted over the kept answer, so a change made
* online is what the next start without a connection shows.
@@ -46,9 +130,10 @@ export async function cacheAccountSettings(settings: Partial<Settings>): Promise
export async function cacheAccountSettingsPatch(patch: Partial<Settings>): Promise<void> {
try {
if (!isAccountDb()) return;
await offlineDb.transaction('rw', offlineDb.accountSettings, async () => {
const kept = (await offlineDb.accountSettings.get('account'))?.settings;
await offlineDb.accountSettings.put({ key: 'account', settings: { ...kept, ...patch } });
const table = offlineDb.accountSettings;
await offlineDb.transaction('rw', table, async () => {
const kept = (await table.get('account'))?.settings;
await table.put({ key: 'account', settings: offlineSettingsOf({ ...kept, ...patch }) });
});
} catch {
/* The kept answer stays as it was; the next server answer replaces it anyway. */
+3 -3
View File
@@ -52,7 +52,7 @@ beforeEach(() => {
vi.mocked(isNativeIos).mockReturnValue(false);
vi.mocked(isNativeAndroid).mockReturnValue(false);
vi.mocked(isEffectivelyOffline).mockReturnValue(false);
vi.mocked(keepOfflineShellFresh).mockResolvedValue();
vi.mocked(keepOfflineShellFresh).mockResolvedValue(true);
vi.mocked(hasNativeFeature).mockReturnValue(false);
document.documentElement.classList.remove('dark');
document.documentElement.removeAttribute('data-native-app');
@@ -154,14 +154,14 @@ describe('startNativeApp', () => {
startNativeApp();
expect(keepOfflineShellFresh).not.toHaveBeenCalled();
vi.advanceTimersByTime(15_000);
expect(vi.mocked(keepOfflineShellFresh).mock.calls[0]?.[2]).toBe(false);
expect(vi.mocked(keepOfflineShellFresh).mock.calls[0]?.[2]).toEqual({ nativeStore: false });
});
it('refreshes it on Android too, into the store of the app', () => {
vi.mocked(isNativeAndroid).mockReturnValue(true);
startNativeApp();
vi.advanceTimersByTime(15_000);
expect(vi.mocked(keepOfflineShellFresh).mock.calls[0]?.[2]).toBe(true);
expect(vi.mocked(keepOfflineShellFresh).mock.calls[0]?.[2]).toEqual({ nativeStore: true });
});
it('skips the refresh while offline', () => {
+5 -5
View File
@@ -96,11 +96,11 @@ export function startNativeApp(): void {
if (isEffectivelyOffline()) return;
// Not refreshed this time is no harm: the next launch tries again. An app
// older than the offline copy has no such method, which is no failure.
keepOfflineShellFresh(fetch, useSettingsStore.getState().settings.language, isNativeAndroid()).catch(
(err: unknown) => {
if (!isUnimplemented(err)) reportNativeFailure(err);
}
);
keepOfflineShellFresh(fetch, useSettingsStore.getState().settings.language, {
nativeStore: isNativeAndroid(),
}).catch((err: unknown) => {
if (!isUnimplemented(err)) reportNativeFailure(err);
});
}, OFFLINE_SHELL_DELAY_MS);
}
+47 -7
View File
@@ -38,7 +38,7 @@ describe('manifestFiles', () => {
});
describe('keepOfflineShellFresh', () => {
it('refreshes the stored start page and fetches every file of the build', async () => {
it('tries every asset even when one fails and does not replace the stored start page', async () => {
const fetched: string[] = [];
const fetchImpl = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const url = String(input);
@@ -53,7 +53,7 @@ describe('keepOfflineShellFresh', () => {
await keepOfflineShellFresh(fetchImpl);
expect(TrekShell.refreshOfflineCopy).toHaveBeenCalled();
expect(TrekShell.refreshOfflineCopy).not.toHaveBeenCalled();
expect(fetched.sort()).toEqual([
'/assets/AtlasPage-99887766.js',
'/assets/index-a1b2c3d4.js',
@@ -63,10 +63,11 @@ describe('keepOfflineShellFresh', () => {
]);
});
it('stops after the start page when the build has no manifest', async () => {
it('keeps the previous start page when the build has no manifest', async () => {
const fetchImpl = vi.fn(async () => new Response('', { status: 404 })) as unknown as typeof fetch;
await keepOfflineShellFresh(fetchImpl);
expect(fetchImpl).toHaveBeenCalledTimes(1);
expect(TrekShell.refreshOfflineCopy).not.toHaveBeenCalled();
});
it('fetches at low priority, only the own language, and once per build', async () => {
@@ -100,6 +101,45 @@ describe('keepOfflineShellFresh', () => {
expect(fetched).toContain('/assets/fr-bbbb2222.js');
});
it('retries the iOS warm-up when a route chunk returned an HTTP error', async () => {
const fetchImpl = vi.fn(async (input: RequestInfo | URL) => {
if (String(input) === '/asset-manifest.json') return new Response(JSON.stringify(manifest));
if (String(input) === '/assets/AtlasPage-99887766.js') return new Response(null, { status: 503 });
return new Response('asset');
});
await keepOfflineShellFresh(fetchImpl);
expect(fetchImpl).toHaveBeenCalledWith('/assets/AtlasPage-99887766.js', { priority: 'low' });
fetchImpl.mockClear();
await keepOfflineShellFresh(fetchImpl);
expect(fetchImpl).toHaveBeenCalledWith('/assets/AtlasPage-99887766.js', { priority: 'low' });
});
it('rechecks the marked iOS shell on demand and keeps the previous start page if an asset is missing', async () => {
const chunk = '/assets/AtlasPage-99887766.js';
let chunkAvailable = true;
const fetchImpl = vi.fn(async (input: RequestInfo | URL) => {
if (String(input) === '/asset-manifest.json') return new Response(JSON.stringify(manifest));
if (String(input) === chunk && !chunkAvailable) return new Response(null, { status: 503 });
return new Response('asset');
});
expect(await keepOfflineShellFresh(fetchImpl)).toBe(true);
expect(await keepOfflineShellFresh(fetchImpl)).toBe(true);
expect(fetchImpl.mock.calls.filter(([url]) => url === chunk)).toHaveLength(1);
vi.mocked(TrekShell.refreshOfflineCopy).mockClear();
chunkAvailable = false;
expect(await keepOfflineShellFresh(fetchImpl, 'en', { verifyAssets: true })).toBe(false);
expect(fetchImpl.mock.calls.filter(([url]) => url === chunk)).toHaveLength(2);
expect(TrekShell.refreshOfflineCopy).not.toHaveBeenCalled();
chunkAvailable = true;
expect(await keepOfflineShellFresh(fetchImpl)).toBe(true);
expect(fetchImpl.mock.calls.filter(([url]) => url === chunk)).toHaveLength(3);
expect(TrekShell.refreshOfflineCopy).toHaveBeenCalledOnce();
});
it('on Android hands the list to the native store instead of fetching it here', async () => {
vi.mocked(TrekShell.refreshOfflineCopy).mockResolvedValue({ saved: true, complete: true });
const fetchImpl = vi.fn(async (input: RequestInfo | URL) => {
@@ -107,7 +147,7 @@ describe('keepOfflineShellFresh', () => {
throw new Error('the native side fetches the files');
}) as unknown as typeof fetch;
await keepOfflineShellFresh(fetchImpl, 'en', true);
await keepOfflineShellFresh(fetchImpl, 'en', { nativeStore: true });
expect(fetchImpl).toHaveBeenCalledTimes(1);
expect(TrekShell.refreshOfflineCopy).toHaveBeenCalledTimes(1);
@@ -128,7 +168,7 @@ describe('keepOfflineShellFresh', () => {
const fetchImpl = vi.fn(async () => new Response(JSON.stringify(manifest))) as unknown as typeof fetch;
try {
await keepOfflineShellFresh(fetchImpl, 'en', true);
await keepOfflineShellFresh(fetchImpl, 'en', { nativeStore: true });
} finally {
document.head.innerHTML = '';
}
@@ -144,8 +184,8 @@ describe('keepOfflineShellFresh', () => {
vi.mocked(TrekShell.refreshOfflineCopy).mockResolvedValue({ saved: true, complete: false });
const fetchImpl = vi.fn(async () => new Response(JSON.stringify(manifest))) as unknown as typeof fetch;
await keepOfflineShellFresh(fetchImpl, 'en', true);
await keepOfflineShellFresh(fetchImpl, 'en', true);
await keepOfflineShellFresh(fetchImpl, 'en', { nativeStore: true });
await keepOfflineShellFresh(fetchImpl, 'en', { nativeStore: true });
expect(TrekShell.refreshOfflineCopy).toHaveBeenCalledTimes(2);
});
+32 -14
View File
@@ -22,7 +22,8 @@ const MANIFEST_URL = '/asset-manifest.json';
*/
const CONCURRENCY = 2;
/** The build whose files are all in the cache; a launch on the same build skips the walk. */
const WARMED_KEY = 'trek.offlineShellBuild';
// Older iOS builds counted an HTTP error page as a cached asset. Warm those builds once more.
const WARMED_KEY = 'trek.offlineShellBuild.v2';
const LOCALE_KEY = /\/i18n\/([^/]+)\/index\.[cm]?js$/;
interface ManifestChunk {
@@ -93,9 +94,10 @@ function warmedBuild(): string | null {
}
}
function rememberWarmed(build: string): void {
function recordWarmedBuild(build: string | null): void {
try {
window.localStorage.setItem(WARMED_KEY, build);
if (build === null) window.localStorage.removeItem(WARMED_KEY);
else window.localStorage.setItem(WARMED_KEY, build);
} catch {
// Not remembered: the next launch walks the files again, from the cache.
}
@@ -104,23 +106,39 @@ function rememberWarmed(build: string): void {
export async function keepOfflineShellFresh(
fetchImpl: typeof fetch = fetch,
language?: string,
nativeStore = false
): Promise<void> {
if (!nativeStore) await TrekShell.refreshOfflineCopy();
{ nativeStore = false, verifyAssets = false }: { nativeStore?: boolean; verifyAssets?: boolean } = {}
): Promise<boolean> {
const response = await fetchImpl(MANIFEST_URL, { cache: 'no-store' });
if (!response.ok) return;
if (!response.ok) return false;
const files = manifestFiles(await response.json(), language);
if (!files.length) return false;
// The build and the language together: a new language needs its own chunk.
const build = `${[...files].sort((a, b) => a.localeCompare(b)).find((f) => /index-[^/]+\.js$/.test(f)) ?? files.length}:${language ?? 'en'}`;
if (nativeStore) {
// The native side fetches only what its store lacks, and keeps the start page fresh each time.
const { complete } = await TrekShell.refreshOfflineCopy({ files: [...new Set([...files, ...pageScripts()])] });
if (complete) rememberWarmed(build);
return;
if (complete) recordWarmedBuild(build);
return complete === true;
}
if (warmedBuild() === build) return;
const complete = await warmCache(files, (path) =>
fetchImpl(path, { priority: 'low' } as RequestInit).then((r) => r.blob())
);
if (complete) rememberWarmed(build);
const marked = warmedBuild() === build;
if (marked && !verifyAssets) return (await TrekShell.refreshOfflineCopy()).saved;
// WebKit can evict an asset independently of localStorage. An explicit
// download visits every file again, reusing cached responses and filling misses.
const assets = verifyAssets ? [...new Set([...files, ...pageScripts()])] : files;
const request = { priority: 'low', ...(verifyAssets ? { cache: 'force-cache' } : {}) } as RequestInit;
const complete = await warmCache(assets, async (path) => {
const asset = await fetchImpl(path, request);
if (!asset.ok) throw new Error(`Could not cache ${path}: HTTP ${asset.status}`);
await asset.blob();
});
if (!complete) {
if (marked) recordWarmedBuild(null);
return false;
}
// Keep the previous start page until all assets of the current build are available.
const { saved } = await TrekShell.refreshOfflineCopy();
if (saved) recordWarmedBuild(build);
return saved;
}
@@ -1,4 +1,4 @@
// FE-PAGE-ATLASACTIONS-001 to FE-PAGE-ATLASACTIONS-015: the country / region popup logic
// FE-PAGE-ATLASACTIONS-001 to FE-PAGE-ATLASACTIONS-016: the country / region popup logic
// behind both the desktop dialog and the phone sheet.
import { act, renderHook } from '@testing-library/react';
import { http, HttpResponse } from 'msw';
@@ -7,6 +7,8 @@ import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vite
import { buildAtlasData, buildBucketItem } from '../../../tests/helpers/atlas';
import { server } from '../../../tests/helpers/msw/server';
import { atlasRepo } from '../../repo/atlasRepo';
import { isForcedOffline, setForcedOffline } from '../../sync/networkMode';
import type { AtlasData, BucketItem } from './atlasModel';
import {
bucketMonthTarget,
@@ -205,6 +207,36 @@ describe('useAtlasCountryActions', () => {
expect(result.current.confirmAction).toBeNull();
});
it('FE-PAGE-ATLASACTIONS-016: offline region removal refreshes the open globe from projected stats', async () => {
const alreadyForced = isForcedOffline();
const projected = buildAtlasData({ countries: [] });
const unmark = vi.spyOn(atlasRepo, 'unmarkRegion').mockResolvedValue(undefined);
const stats = vi.spyOn(atlasRepo, 'stats').mockResolvedValue(projected);
const countryDetail = vi.spyOn(atlasRepo, 'countryDetail');
try {
setForcedOffline(true);
const { result } = setup({
confirmAction: { type: 'unmark-region', code: 'ES', name: 'Galicia', regionCode: 'ES-GA' },
data: buildAtlasData({
countries: [{ code: 'ES', tripCount: 0, placeCount: 0, firstVisit: null, lastVisit: null }],
}),
visitedRegions: { ES: [{ code: 'ES-GA', name: 'Galicia', placeCount: 0 }] },
});
await act(() => result.current.actions.unmarkRegion());
expect(unmark).toHaveBeenCalledWith('ES-GA');
expect(stats).toHaveBeenCalledOnce();
expect(countryDetail).not.toHaveBeenCalled();
expect(result.current.data).toBe(projected);
expect(result.current.visitedRegions).toEqual({});
expect(result.current.confirmAction).toBeNull();
} finally {
setForcedOffline(alreadyForced);
unmark.mockRestore();
stats.mockRestore();
countryDetail.mockRestore();
}
});
it('FE-PAGE-ATLASACTIONS-015: a country the server still holds as marked stays when its last region goes (#2597)', async () => {
const init = () => ({
confirmAction: { type: 'unmark-region', code: 'ES', name: 'Galicia', regionCode: 'ES-GA' } as AtlasConfirmAction,
@@ -4,6 +4,7 @@ import { useEffect, useState } from 'react';
import { useToast } from '../../components/shared/Toast';
import { atlasRepo } from '../../repo/atlasRepo';
import { isEffectivelyOffline } from '../../sync/networkMode';
import { getApiErrorMessage, type TranslationFn } from '../../types';
import {
findBucketDuplicate,
@@ -172,7 +173,13 @@ export function useAtlasCountryActions({
try {
await atlasRepo.unmarkRegion(regionCode);
setVisitedRegions((prev) => withRegionUnmarked(prev, countryCode, regionCode));
if (!(await isCountryStillMarked(countryCode))) {
if (isEffectivelyOffline()) {
try {
setData((await atlasRepo.stats()) as AtlasData);
} catch {
// A missing snapshot does not undo the queued write. Keep the current countries until the next load.
}
} else if (!(await isCountryStillMarked(countryCode))) {
setData((prev) => withCountryDroppedAfterRegionUnmark(prev, countryCode, regionCode, visitedRegions));
}
} catch (err) {
+1 -1
View File
@@ -187,7 +187,7 @@ describe('online writes', () => {
await atlasRepo.unmarkCountry('IS');
expect(hits).toEqual(['region', 'country']);
expect((await keptAtlasPart('regions'))?.data).toEqual({ ES: [] });
expect((await keptAtlasPart('regions'))?.data).toEqual({});
expect((await keptAtlasPart('stats'))?.data).toMatchObject({ countries: [], stats: { totalCountries: 0 } });
expect(await offlineDb.userMutationQueue.count()).toBe(0);
});
+76 -1
View File
@@ -77,6 +77,22 @@ describe('atlasRepo reads', () => {
expect((await atlasRepo.flights()).totals.flights).toBe(0);
});
it('FE-REPO-ATLAS-004: returns the server answer if the cache cannot be written', async () => {
serveAtlas();
vi.spyOn(offlineDb.atlasSnapshot, 'put').mockRejectedValue(new Error('QuotaExceededError'));
expect(await atlasRepo.stats()).toEqual(STATS);
});
it('FE-REPO-ATLAS-005: returns the server answer if the queue cannot be opened', async () => {
serveAtlas();
vi.spyOn(offlineDb.userMutationQueue, 'where').mockImplementation(() => {
throw new Error('DatabaseClosedError');
});
expect(await atlasRepo.stats()).toEqual(STATS);
});
it('FE-REPO-ATLAS-002: a request that never reaches the server falls back to the kept answer', async () => {
await readOnline();
server.use(http.get('/api/addons/atlas/stats', () => HttpResponse.error()));
@@ -122,7 +138,7 @@ describe('atlasRepo writes offline', () => {
setOnline(true);
const regions = await atlasRepo.regions();
expect(regions.PT[0]).toMatchObject({ code: 'PT-11', manuallyMarked: false });
expect(regions.PT).toBeUndefined();
expect(regions.ES).toEqual([
{ code: 'ES-CT', name: 'Catalunya', placeCount: 0, status: 'visited', manuallyMarked: true },
]);
@@ -150,6 +166,65 @@ describe('atlasRepo writes online', () => {
expect(stats.countries.some((c) => c.code === 'IS' && c.status === 'visited')).toBe(true);
});
it('FE-REPO-ATLAS-023: sends an online write when the queue cannot be opened', async () => {
vi.spyOn(offlineDb.userMutationQueue, 'where').mockImplementation(() => {
throw new Error('DatabaseClosedError');
});
let sent = 0;
server.use(
http.post('/api/addons/atlas/country/IS/mark', () => {
sent += 1;
return HttpResponse.json({ success: true });
})
);
await expect(atlasRepo.markCountry('IS')).resolves.toBeUndefined();
expect(sent).toBe(1);
});
it('FE-REPO-ATLAS-024: a failed cache update after a save keeps the server result', async () => {
await readOnline();
vi.spyOn(offlineDb.atlasSnapshot, 'put').mockRejectedValue(new Error('QuotaExceededError'));
server.use(
http.post('/api/addons/atlas/country/IS/mark', () => HttpResponse.json({ success: true })),
http.post('/api/addons/atlas/bucket-list', () => HttpResponse.json({ item: { id: 9, name: 'Faro' } }))
);
await expect(atlasRepo.markCountry('IS')).resolves.toBeUndefined();
await expect(atlasRepo.addBucketItem({ name: 'Faro' })).resolves.toEqual({ id: 9, name: 'Faro' });
});
it('FE-REPO-ATLAS-025: a wish removed elsewhere stays gone after the queued delete gets a 404', async () => {
await readOnline();
setOnline(false);
await atlasRepo.deleteBucketItem(7);
server.use(http.delete('/api/addons/atlas/bucket-list/7', () => new HttpResponse(null, { status: 404 })));
setOnline(true);
await mutationQueue.flush();
setOnline(false);
expect(await offlineDb.userMutationQueue.count()).toBe(0);
expect(await atlasRepo.bucketList()).toEqual([{ id: 8, name: 'Madeira' }]);
});
it('FE-REPO-ATLAS-026: replaying a region removal refreshes a legacy country read with unknown provenance', async () => {
await readOnline();
setOnline(false);
await atlasRepo.unmarkRegion('PT-11');
server.use(
http.delete('/api/addons/atlas/region/PT-11/mark', () => HttpResponse.json({ success: true })),
http.get('/api/addons/atlas/stats', () => HttpResponse.json({ countries: [STATS.countries[1]] }))
);
setOnline(true);
await mutationQueue.flush();
setOnline(false);
expect(await atlasRepo.stats()).toEqual({ countries: [STATS.countries[1]] });
expect(await atlasRepo.regions()).toEqual({});
});
it('FE-REPO-ATLAS-021: online behind an older queued write, a write waits in line', async () => {
await readOnline();
setAuthed(false); // the flush stays off, so the line is visible
+36 -10
View File
@@ -1,5 +1,5 @@
import apiClient from '../api/client';
import type { AtlasSnapshotPart } from '../db/offlineDb';
import { offlineDb, type AtlasSnapshotPart } from '../db/offlineDb';
import {
ATLAS_RESOURCE,
keepAtlasPart,
@@ -83,9 +83,16 @@ export const ATLAS_NOT_CACHED = 'The Atlas has not been opened online on this de
async function readThrough<T>(part: AtlasSnapshotPart, fetch: () => Promise<T>): Promise<T> {
return onlineThenCache(
async () => {
const account = offlineDb.name;
const data = await fetch();
await keepAtlasPart(part, data);
return (await withWaitingWrites(part, data)) as T;
if (account !== offlineDb.name) return data;
try {
await keepAtlasPart(part, data);
} catch {
// A full or disabled cache still allows an online read.
}
if (account !== offlineDb.name) return data;
return (await withWaitingWrites(part, data).catch(() => data)) as T;
},
async () => {
const kept = await keptAtlasPart(part);
@@ -114,20 +121,28 @@ interface WriteSpec {
async function write(spec: WriteSpec): Promise<void> {
const id = generateUUID();
const body = spec.body ?? null;
if (!(await userMutationQueue.mustQueue(spec.entity, []))) {
const account = offlineDb.name;
if (!(await userMutationQueue.mustQueue(spec.entity, []).catch(() => false))) {
try {
const res = await apiClient.request({
await apiClient.request({
method: spec.method,
url: spec.url,
data: spec.body,
headers: { 'X-Idempotency-Key': id },
});
await reconcileAtlasWrite({ ...spec, ids: {}, body, createdAt: Date.now(), answer: res.data });
if (account === offlineDb.name) {
try {
await reconcileAtlasWrite({ ...spec, body });
} catch {
// The server accepted the write. A later online read can repair the cached copy.
}
}
return;
} catch (err) {
if (!isNetworkError(err)) throw err;
}
}
if (account !== offlineDb.name) return;
await userMutationQueue.enqueue({
id,
method: spec.method,
@@ -167,12 +182,15 @@ export const atlasRepo = {
},
async stats(): Promise<unknown> {
return readThrough('stats', async () => (await apiClient.get('/addons/atlas/stats')).data as unknown);
return readThrough(
'stats',
async () => (await apiClient.get('/addons/atlas/stats', { params: { offline: 1 } })).data as unknown
);
},
async regions(): Promise<Record<string, AtlasRegionRow[]>> {
return readThrough('regions', async () => {
const res = await apiClient.get('/addons/atlas/regions');
const res = await apiClient.get('/addons/atlas/regions', { params: { offline: 1 } });
return (res.data?.regions ?? {}) as Record<string, AtlasRegionRow[]>;
});
},
@@ -227,9 +245,17 @@ export const atlasRepo = {
/** Online only: the server refuses a wish that is on the list already (409). */
async addBucketItem(data: Record<string, unknown>): Promise<unknown> {
const account = offlineDb.name;
const item = (await apiClient.post('/addons/atlas/bucket-list', data)).data?.item as unknown;
const kept = await keptAtlasPart('bucketList');
if (kept && Array.isArray(kept.data) && item) await keepAtlasPart('bucketList', [item, ...kept.data]);
if (account !== offlineDb.name) return item;
try {
const kept = await keptAtlasPart('bucketList');
if (account === offlineDb.name && kept && Array.isArray(kept.data) && item) {
await keepAtlasPart('bucketList', [item, ...kept.data]);
}
} catch {
// The wish already exists on the server. An online refresh can restore its offline copy.
}
return item;
},
+44 -2
View File
@@ -10,7 +10,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { settingsApi } from '../api/client';
import { cacheAccountSettings, cachedAccountSettings } from '../db/cacheAccountSettings';
import { deleteCurrentUserDb, reopenAnonymous, reopenForUser } from '../db/offlineDb';
import { deleteCurrentUserDb, offlineDb, reopenAnonymous, reopenForUser } from '../db/offlineDb';
import { DEFAULT_SETTINGS, useSettingsStore } from './settingsStore';
vi.mock('../api/client', () => ({
@@ -30,7 +30,9 @@ const settings = () => useSettingsStore.getState().settings;
beforeEach(async () => {
vi.mocked(settingsApi.get).mockReset();
vi.mocked(settingsApi.set).mockReset().mockResolvedValue(undefined);
vi.mocked(settingsApi.setBulk).mockReset().mockResolvedValue(undefined);
vi.mocked(settingsApi.setBulk)
.mockReset()
.mockImplementation(async (patch) => ({ success: true, updated: Object.keys(patch).length }));
vi.spyOn(console, 'error').mockImplementation(() => {});
useSettingsStore.setState(initialState, true);
await reopenForUser(801);
@@ -119,4 +121,44 @@ describe('settings without a connection', () => {
expect(await cachedAccountSettings()).toEqual({ map_provider: 'leaflet' });
});
it('FE-STORE-SETTINGS-OFFLINE-008: saving a provider key keeps the offline preference only', async () => {
const patch = { llm_api_key: 'test-llm-key', language: 'de' };
await useSettingsStore.getState().updateSettings(patch);
expect(settingsApi.setBulk).toHaveBeenCalledWith(patch);
await vi.waitFor(async () =>
expect(await offlineDb.accountSettings.get('account')).toEqual({ key: 'account', settings: { language: 'de' } })
);
});
it('FE-STORE-SETTINGS-OFFLINE-009: successful responses only cache values the server wrote', async () => {
await cacheAccountSettings({ map_provider: 'leaflet', map_tile_url: OSM_DE });
vi.mocked(settingsApi.set).mockResolvedValue({ success: true, key: 'map_provider', unchanged: true });
vi.mocked(settingsApi.setBulk).mockResolvedValue({ success: true, updated: 1, managed_keys: ['map_tile_url'] });
await useSettingsStore.getState().updateSetting('map_provider', 'maplibre-gl');
await useSettingsStore.getState().updateSettings({ map_tile_url: BRIGHT, distance_unit: 'imperial' });
await vi.waitFor(async () =>
expect(await cachedAccountSettings()).toEqual({
map_provider: 'leaflet',
map_tile_url: OSM_DE,
distance_unit: 'imperial',
})
);
});
it('FE-STORE-SETTINGS-OFFLINE-010: a partial bulk write refreshes the cache from the server', async () => {
vi.mocked(settingsApi.setBulk).mockResolvedValue({ success: true, updated: 1 });
vi.mocked(settingsApi.get).mockResolvedValue({ settings: { map_provider: 'leaflet', distance_unit: 'imperial' } });
await useSettingsStore.getState().updateSettings({ map_provider: 'mapbox-gl', distance_unit: 'imperial' });
await vi.waitFor(async () =>
expect(await cachedAccountSettings()).toEqual({ map_provider: 'leaflet', distance_unit: 'imperial' })
);
expect(useSettingsStore.getState().settings.map_provider).toBe('mapbox-gl');
});
});
+25 -6
View File
@@ -1,13 +1,24 @@
import { create } from 'zustand'
import { settingsApi } from '../api/client'
import type { Settings } from '../types'
import { DEFAULT_APPEARANCE, DEFAULT_DATE_FORMAT, DEFAULT_WEEK_START } from '@trek/shared'
import {
DEFAULT_APPEARANCE,
DEFAULT_DATE_FORMAT,
DEFAULT_WEEK_START,
type SettingUpsertResponse,
type SettingsBulkResponse,
} from '@trek/shared'
import { getApiErrorMessage } from '../types'
import { SUPPORTED_LANGUAGE_CODES } from '../i18n/supportedLanguages'
import { detectBrowserLanguage } from '../i18n/detectBrowserLanguage'
import { normalizeTileUrl, stripTileApiKey } from '../utils/tileUrl'
import { clearTileCache } from '../sync/tilePrefetcher'
import { cacheAccountSettings, cacheAccountSettingsPatch, cachedAccountSettings } from '../db/cacheAccountSettings'
import {
cacheAccountSettings,
cacheAccountSettingsPatch,
cachedAccountSettings,
refreshCachedAccountSettings,
} from '../db/cacheAccountSettings'
import { rememberStartDestination, DEFAULT_START_PAGE, DEFAULT_START_TRIP_TAB } from '../utils/startDestination'
import { clearGlEngineFailure } from '../utils/webgl'
@@ -214,8 +225,8 @@ export const useSettingsStore = create<SettingsState>((set, get) => ({
if (key === 'language') localStorage.setItem('app_language', next as string)
rememberStartDestination({ [key]: next } as Partial<Settings>)
try {
await settingsApi.set(key, next)
void cacheAccountSettingsPatch({ [key]: next } as Partial<Settings>)
const saved: SettingUpsertResponse | undefined = await settingsApi.set(key, next)
if (!saved?.managed && !saved?.unchanged) void cacheAccountSettingsPatch({ [key]: next } as Partial<Settings>)
} catch (err: unknown) {
console.error('Failed to save setting:', err)
throw new Error(getApiErrorMessage(err, 'Error saving setting'))
@@ -248,8 +259,16 @@ export const useSettingsStore = create<SettingsState>((set, get) => ({
}))
rememberStartDestination(patch)
try {
await settingsApi.setBulk(patch)
void cacheAccountSettingsPatch(patch)
const saved: SettingsBulkResponse | undefined = await settingsApi.setBulk(patch)
if (typeof saved?.updated !== 'number') return
const managed = new Set(saved.managed_keys)
const accepted = Object.entries(patch).filter(([key]) => !managed.has(key))
// Some no-ops report only a count, so fetch what was actually saved.
if (accepted.length === saved.updated) void cacheAccountSettingsPatch(Object.fromEntries(accepted))
else void refreshCachedAccountSettings(async () => {
const data = await settingsApi.get()
return withNormalizedTileUrl({ ...data.settings } as Partial<Settings>)
})
} catch (err: unknown) {
console.error('Failed to save settings:', err)
throw new Error(getApiErrorMessage(err, 'Error saving settings'))
+54 -12
View File
@@ -45,7 +45,13 @@ const region = (code: string, method: 'POST' | 'DELETE', body: unknown = null) =
});
interface Stats {
countries: Array<{ code: string; status?: string; placeCount?: number; tripCount?: number }>;
countries: Array<{
code: string;
status?: string;
placeCount?: number;
tripCount?: number;
offline?: { directMark: boolean; placeStatus: string | null };
}>;
stats?: Record<string, number | undefined>;
continents?: Record<string, number>;
continentsPlanned?: Record<string, number>;
@@ -107,12 +113,16 @@ describe('countries over the stats read', () => {
it('FE-ATLAS2-DATA-005: marking a country already visited changes nothing, also one without a status', async () => {
await queued(country('PT'));
const data = baseStats();
data.countries[0].offline = { directMark: true, placeStatus: 'visited' };
expect(await withWaitingWrites('stats', data)).toBe(data);
await clearAll();
const noStatus: Stats = { countries: [{ code: 'FR' }], stats: { totalCountries: 1 } };
await queued(country('FR'));
expect(await withWaitingWrites('stats', noStatus)).toEqual(noStatus);
expect(await withWaitingWrites('stats', noStatus)).toEqual({
countries: [{ code: 'FR', offline: { directMark: true, placeStatus: null } }],
stats: { totalCountries: 1 },
});
});
it('FE-ATLAS2-DATA-006: a read without a countries list is not touched', async () => {
@@ -240,6 +250,7 @@ describe('regions', () => {
placeCount: 4,
status: 'visited',
manuallyMarked: true,
placeStatus: 'visited',
});
expect(out.PT).toHaveLength(2);
});
@@ -261,10 +272,10 @@ describe('regions', () => {
expect(await withWaitingWrites('regions', null)).toBeNull();
});
it('FE-ATLAS2-DATA-021: unmarking a region with places keeps it, only the manual flag goes', async () => {
it('FE-ATLAS2-DATA-021: unmarking hides a region even when it has places', async () => {
await queued(region('PT-11', 'DELETE'));
const out = (await withWaitingWrites('regions', regions())) as ReturnType<typeof regions>;
expect(out.PT[0]).toMatchObject({ code: 'PT-11', manuallyMarked: false, placeCount: 4 });
expect(out.PT.map((r) => r.code)).toEqual(['PT-13']);
});
it('FE-ATLAS2-DATA-022: unmarking a region without places drops it', async () => {
@@ -280,11 +291,41 @@ describe('regions', () => {
expect(await withWaitingWrites('regions', null)).toBeNull();
});
it('FE-ATLAS2-DATA-024: a country write or a PUT on a region leaves the regions read alone', async () => {
it('FE-ATLAS2-DATA-024: unmarking a country clears its manual regions but keeps its places', async () => {
await queued(country('PT', 'DELETE'));
await queued({ ...region('PT-11', 'POST', { country_code: 'PT' }), method: 'PUT' });
const data = regions();
expect(await withWaitingWrites('regions', data)).toBe(data);
expect(await withWaitingWrites('regions', data)).toEqual({ PT: [data.PT[0]] });
});
it('FE-ATLAS2-DATA-033: a region added offline also marks its country visited', async () => {
await queued(region('JP-13', 'POST', { country_code: 'JP', name: 'Tokyo' }));
const stats = (await withWaitingWrites('stats', baseStats())) as Stats;
expect(stats.countries.find((c) => c.code === 'JP')).toMatchObject({
status: 'visited',
offline: { directMark: false, placeStatus: null },
});
expect(stats.stats?.totalCountries).toBe(2);
});
it('FE-ATLAS2-DATA-034: a country loses its last region in queue order unless it has its own mark', async () => {
await keepAtlasPart('regions', regions());
await queued(region('PT-11', 'DELETE'));
await queued(region('PT-13', 'DELETE'));
const data = baseStats();
data.countries[0].offline = { directMark: false, placeStatus: 'planned' };
expect(await withWaitingWrites('stats', data)).toMatchObject({
countries: [
{ code: 'PT', status: 'planned' },
{ code: 'ES', status: 'planned' },
],
stats: { totalCountries: 0, totalCountriesPlanned: 2 },
});
data.countries[0].offline.directMark = true;
expect(await withWaitingWrites('stats', data)).toBe(data);
});
});
@@ -320,15 +361,12 @@ describe('a write that went through', () => {
await keepAtlasPart('flights', { routes: [] });
await keepAtlasPart('bucketList', [{ id: 7 }, { id: 9 }]);
await reconcileAtlasWrite({ ...country('JP'), ids: {}, body: null, createdAt: 1 });
await reconcileAtlasWrite({ ...country('JP'), body: null });
await reconcileAtlasWrite({
resource: ATLAS_RESOURCE.bucket,
entity: `${ATLAS_RESOURCE.bucket}:9`,
method: 'DELETE',
ids: {},
body: null,
createdAt: 2,
answer: { success: true },
});
const stats = (await keptAtlasPart('stats'))?.data as Stats;
@@ -339,10 +377,14 @@ describe('a write that went through', () => {
it('FE-ATLAS2-DATA-029: laying the same write in twice changes nothing more', async () => {
await keepAtlasPart('regions', {});
const w = { ...region('ES-CT', 'POST', { name: 'Catalunya', country_code: 'ES' }), ids: {}, createdAt: 1 };
const w = region('ES-CT', 'POST', { name: 'Catalunya', country_code: 'ES' });
await keepAtlasPart('stats', baseStats());
await reconcileAtlasWrite(w);
const once = (await keptAtlasPart('regions'))?.data;
const stats = (await keptAtlasPart('stats'))?.data;
await reconcileAtlasWrite(w);
expect((await keptAtlasPart('stats'))?.data).toEqual(stats);
expect(stats).toMatchObject({ countries: [{ code: 'PT' }, { code: 'ES', status: 'visited' }] });
expect((await keptAtlasPart('regions'))?.data).toEqual(once);
expect(once).toEqual({
ES: [{ code: 'ES-CT', name: 'Catalunya', placeCount: 0, status: 'visited', manuallyMarked: true }],
@@ -350,7 +392,7 @@ describe('a write that went through', () => {
});
it('FE-ATLAS2-DATA-030: with nothing kept there is nothing to change', async () => {
await reconcileAtlasWrite({ ...country('JP'), ids: {}, body: null, createdAt: 1 });
await reconcileAtlasWrite({ ...country('JP'), body: null });
expect(await offlineDb.atlasSnapshot.count()).toBe(0);
});
});
+138 -47
View File
@@ -14,7 +14,8 @@
* Every step here is idempotent: a read that raced a replay may already hold
* the write, and laying it over once more must change nothing.
*/
import { continentForCountry } from '@trek/shared';
import { continentForCountry, type VisitStatus } from '@trek/shared';
import { apiClient } from '../api/client';
import { offlineDb, type AtlasSnapshotPart, type UserQueuedMutation } from '../db/offlineDb';
/** The resources of the Atlas writes in the account queue. */
@@ -24,13 +25,7 @@ export const ATLAS_RESOURCE = {
bucket: 'atlasBucket',
} as const;
/** A write as it is laid over a read: a queued row, or a write that just went through with the server's answer. */
type AtlasWrite = Pick<
UserQueuedMutation,
'resource' | 'method' | 'entity' | 'ids' | 'body' | 'tempId' | 'createdAt'
> & {
answer?: unknown;
};
type AtlasWrite = Pick<UserQueuedMutation, 'resource' | 'method' | 'entity' | 'body'>;
type Fields = Record<string, unknown>;
@@ -51,7 +46,8 @@ function keyOf(w: AtlasWrite): string {
interface StatsCountry {
code: string;
status?: string;
status?: VisitStatus;
offline?: { directMark: boolean; placeStatus?: VisitStatus | null };
placeCount?: number;
tripCount?: number;
}
@@ -75,49 +71,75 @@ function total(s: StatsShape, key: string, by: number): Record<string, number |
return { ...s.stats, [key]: Math.max(0, (s.stats?.[key] ?? 0) + by) };
}
/** A manual "I have been here": a country planned before moves over to the visited tally. */
function markCountry(data: unknown, code: string): unknown {
function placeStatusOf(country: StatsCountry | undefined): VisitStatus | null | undefined {
if (country?.offline) return country.offline.placeStatus;
if (!country || !(country.placeCount || country.tripCount)) return null;
return country.status === 'visited' ? undefined : country.status;
}
/** Add a visit without losing a direct mark, or the status left by the country's places. */
function markCountry(data: unknown, code: string, directMark: boolean): unknown {
const s = asStats(data);
if (!s) return data;
const known = s.countries.find((c) => c.code === code);
const status = known?.status ?? (known ? 'visited' : null);
if (status === 'visited') return data;
const offline = { directMark: directMark || !!known?.offline?.directMark, placeStatus: placeStatusOf(known) };
if (status === 'visited') {
// An older read cannot tell what marked the country. A regional mark cannot settle that.
if (!directMark || known?.offline?.directMark) return data;
return { ...s, countries: s.countries.map((c) => (c.code === code ? { ...c, offline } : c)) };
}
const continent = continentForCountry(code);
const visited: StatsCountry & Fields = {
code,
tripCount: 0,
placeCount: 0,
const visited = {
...(known ?? { code, tripCount: 0, placeCount: 0 }),
firstVisit: null,
lastVisit: null,
status: 'visited',
status: 'visited' as const,
offline,
};
const next: StatsShape = {
...s,
countries: known
? s.countries.map((c) => (c.code === code ? { ...c, status: 'visited' } : c))
: [...s.countries, visited],
countries: known ? s.countries.map((c) => (c.code === code ? visited : c)) : [...s.countries, visited],
stats: total(s, 'totalCountries', 1),
continents: bump(s.continents, continent, 1),
};
if (status === 'idea') return { ...next, stats: total(next, 'totalCountriesIdea', -1) };
if (status !== 'planned') return next;
return {
...next,
stats: { ...next.stats, totalCountriesPlanned: Math.max(0, (s.stats?.totalCountriesPlanned ?? 0) - 1) },
stats: total(next, 'totalCountriesPlanned', -1),
continentsPlanned: bump(s.continentsPlanned, continent, -1),
};
}
/** The manual mark taken back: a country with no trip and no place in it leaves the map. */
/** A direct unmark leaves the country painted by its own places, if any. */
function unmarkCountry(data: unknown, code: string): unknown {
const s = asStats(data);
const known = s?.countries.find((c) => c.code === code);
if (!s || !known || (known.status ?? 'visited') !== 'visited') return data;
if ((known.placeCount ?? 0) > 0 || (known.tripCount ?? 0) > 0) return data;
return {
const placeStatus = placeStatusOf(known);
if (placeStatus === undefined) return data;
const continent = continentForCountry(code);
const next: StatsShape = {
...s,
countries: s.countries.filter((c) => c.code !== code),
countries: placeStatus
? s.countries.map((c) =>
c.code === code ? { ...c, status: placeStatus, offline: { directMark: false, placeStatus } } : c
)
: s.countries.filter((c) => c.code !== code),
stats: total(s, 'totalCountries', -1),
continents: bump(s.continents, continentForCountry(code), -1),
continents: bump(s.continents, continent, -1),
};
if (placeStatus === 'visited') {
return { ...s, countries: next.countries };
}
if (placeStatus === 'idea') return { ...next, stats: total(next, 'totalCountriesIdea', 1) };
if (placeStatus !== 'planned') return next;
return {
...next,
stats: total(next, 'totalCountriesPlanned', 1),
continentsPlanned: bump(s.continentsPlanned, continent, 1),
};
}
@@ -127,7 +149,9 @@ interface RegionRow {
code: string;
name: string;
placeCount: number;
status?: string;
status?: VisitStatus;
/** The status the region's places give it without the mark. */
placeStatus?: VisitStatus;
/** Marked by hand, the server's own name for it. */
manuallyMarked?: boolean;
}
@@ -143,32 +167,77 @@ function markRegion(data: unknown, code: string, name: string, countryCode: stri
if (!regions) return data;
const rows = regions[countryCode] ?? [];
const known = rows.find((r) => r.code === code);
if (known?.status === 'visited' && known.manuallyMarked) return data;
const marked: RegionRow = { ...(known ?? { code, name, placeCount: 0 }), status: 'visited', manuallyMarked: true };
if (known?.status === 'visited' && (known.manuallyMarked || known.placeStatus)) return data;
const placeStatus = known?.placeCount ? (known.placeStatus ?? known.status) : undefined;
const marked: RegionRow = {
...(known ?? { code, name, placeCount: 0 }),
status: 'visited',
manuallyMarked: true,
...(placeStatus ? { placeStatus } : {}),
};
return { ...regions, [countryCode]: known ? rows.map((r) => (r.code === code ? marked : r)) : [...rows, marked] };
}
function countryOfRegion(regions: Regions, code: string): string | undefined {
return Object.keys(regions).find((cc) => (regions[cc] ?? []).some((r) => r.code === code));
}
/** The server hides an explicitly removed region, even if it has places. */
function unmarkRegion(data: unknown, code: string): unknown {
const regions = asRegions(data);
const country = regions && Object.keys(regions).find((cc) => (regions[cc] ?? []).some((r) => r.code === code));
if (!regions || !country) return data;
// A region with places in it stays visited by them; only the manual mark goes.
const rows = regions[country]
.map((r) => (r.code === code ? { ...r, manuallyMarked: false } : r))
.filter((r) => r.code !== code || r.placeCount > 0);
return { ...regions, [country]: rows };
if (!regions) return data;
const country = countryOfRegion(regions, code);
if (!country) return data;
const rows = regions[country].filter((r) => r.code !== code);
if (rows.length) return { ...regions, [country]: rows };
const remaining = { ...regions };
delete remaining[country];
return remaining;
}
function clearCountryRegions(data: unknown, country: string): unknown {
const regions = asRegions(data);
const current = regions?.[country];
if (!regions || !current) return data;
const withPlaces = current
.filter((r) => r.placeCount > 0)
.map((r) => {
const { placeStatus, ...row } = r;
delete row.manuallyMarked;
return placeStatus ? { ...row, status: placeStatus } : row;
});
if (withPlaces.length) return { ...regions, [country]: withPlaces };
const remaining = { ...regions };
delete remaining[country];
return remaining;
}
// ── One write over one read ───────────────────────────────────────────────────
function applyToStats(data: unknown, w: AtlasWrite): unknown {
if (w.resource !== ATLAS_RESOURCE.country) return data;
if (w.method === 'POST') return markCountry(data, keyOf(w));
if (w.method === 'DELETE') return unmarkCountry(data, keyOf(w));
return data;
function lastRegionCountry(data: unknown, w: AtlasWrite): string | undefined {
if (w.resource !== ATLAS_RESOURCE.region || w.method !== 'DELETE') return;
const regions = asRegions(data);
const country = regions && countryOfRegion(regions, keyOf(w));
if (regions && country && regions[country].length === 1) return country;
}
function applyToStats(data: unknown, w: AtlasWrite, regions: unknown): unknown {
if (w.resource === ATLAS_RESOURCE.country) {
if (w.method === 'POST') return markCountry(data, keyOf(w), true);
if (w.method === 'DELETE') return unmarkCountry(data, keyOf(w));
}
if (w.resource === ATLAS_RESOURCE.region && w.method === 'POST') {
const code = text(fields(w.body).country_code);
if (code) return markCountry(data, code, false);
}
const country = lastRegionCountry(regions, w);
if (!country) return data;
const row = asStats(data)?.countries.find((c) => c.code === country);
return row?.offline?.directMark === false ? unmarkCountry(data, country) : data;
}
function applyToRegions(data: unknown, w: AtlasWrite): unknown {
if (w.resource === ATLAS_RESOURCE.country && w.method === 'DELETE') return clearCountryRegions(data, keyOf(w));
if (w.resource !== ATLAS_RESOURCE.region) return data;
const body = fields(w.body);
const country = text(body.country_code);
@@ -178,10 +247,10 @@ function applyToRegions(data: unknown, w: AtlasWrite): unknown {
}
/** What one Atlas read reads as once the write is laid over it. */
function applyAtlasWrite(part: AtlasSnapshotPart, data: unknown, w: AtlasWrite): unknown {
function applyAtlasWrite(part: AtlasSnapshotPart, data: unknown, w: AtlasWrite, regions?: unknown): unknown {
switch (part) {
case 'stats':
return applyToStats(data, w);
return applyToStats(data, w, regions);
case 'regions':
return applyToRegions(data, w);
case 'bucketList': {
@@ -205,7 +274,15 @@ async function waitingWrites(): Promise<UserQueuedMutation[]> {
/** A read with every Atlas write still on its way laid over it, in the order they were made. */
export async function withWaitingWrites(part: AtlasSnapshotPart, data: unknown): Promise<unknown> {
const writes = await waitingWrites();
return writes.reduce((out, w) => applyAtlasWrite(part, out, w), data);
if (part !== 'stats' || !writes.some((w) => w.resource === ATLAS_RESOURCE.region && w.method === 'DELETE')) {
return writes.reduce((out, w) => applyAtlasWrite(part, out, w), data);
}
let regions: unknown = (await keptAtlasPart('regions'))?.data ?? {};
for (const w of writes) {
data = applyToStats(data, w, regions);
regions = applyToRegions(regions, w);
}
return data;
}
/** Keep a read's answer as the server gave it. */
@@ -218,13 +295,27 @@ export async function keptAtlasPart(part: AtlasSnapshotPart): Promise<{ data: un
return offlineDb.atlasSnapshot.get(part);
}
/** A write that went through: its answer is laid into every kept read, so it stays once the device is offline again. */
/** Apply a write the server accepted to the kept reads. */
export async function reconcileAtlasWrite(w: AtlasWrite): Promise<void> {
await offlineDb.transaction('rw', offlineDb.atlasSnapshot, async () => {
const account = offlineDb.name;
const needsStats = await offlineDb.transaction('rw', offlineDb.atlasSnapshot, async () => {
const rows = await offlineDb.atlasSnapshot.toArray();
const regions = rows.find((row) => row.part === 'regions')?.data;
for (const row of rows) {
const next = applyAtlasWrite(row.part, row.data, w);
const next = applyAtlasWrite(row.part, row.data, w, regions);
if (next !== row.data) await offlineDb.atlasSnapshot.put({ part: row.part, data: next });
}
const country = lastRegionCountry(regions, w);
const stats = rows.find((row) => row.part === 'stats')?.data;
const known = country && asStats(stats)?.countries.find((c) => c.code === country);
return !!known && !known.offline;
});
// An old snapshot cannot distinguish a direct mark from a country's last region.
if (!needsStats || account !== offlineDb.name) return;
try {
const { data } = await apiClient.get('/addons/atlas/stats', { params: { offline: 1 } });
if (account === offlineDb.name) await keepAtlasPart('stats', data);
} catch {
// The mutation already synced. The next online read can refresh this snapshot.
}
}
+11 -1
View File
@@ -23,7 +23,7 @@ export const GL_TILE_CACHE = 'map-tiles-gl';
* service worker by its source text, so it must not reach anything outside its
* own body: the host list stays inline.
*/
export function isGlRasterTileRequest({ url, request }: { url: URL; request: Request }): boolean {
export function isGlRasterTileRequest({ url, request }: { url: URL; request: Pick<Request, 'mode'> }): boolean {
if (request.mode !== 'cors' || url.protocol !== 'https:') return false;
const hosts = [
'basemaps.cartocdn.com',
@@ -38,3 +38,13 @@ export function isGlRasterTileRequest({ url, request }: { url: URL; request: Req
const host = url.hostname.toLowerCase();
return hosts.some((entry) => (entry.startsWith('*.') ? host.endsWith(entry.slice(1)) : host === entry));
}
/** Whether prefetch and the service worker can keep readable GL tiles for this template. */
export function hasGlRasterCache(template: string): boolean {
try {
const url = new URL(template.replace(/\{s\}/g, 'a'));
return isGlRasterTileRequest({ url, request: { mode: 'cors' } });
} catch {
return false;
}
}
+2 -9
View File
@@ -33,7 +33,7 @@ import { clearVectorCache, prefetchStyleAssets, prefetchVectorForPlaces } from '
import { isNativeIos } from '../native/platform'
import { isIosDevice } from '../utils/iosDevice'
import { openCacheStorage } from './openCacheStorage'
import { GL_TILE_CACHE, isGlRasterTileRequest } from './glTileCache'
import { GL_TILE_CACHE, hasGlRasterCache } from './glTileCache'
import { useSettingsStore } from '../store/settingsStore'
import { MAPLIBRE_FROM_TEMPLATE } from '@trek/shared'
@@ -308,14 +308,7 @@ async function openTileCache(cacheName: string = TILE_CACHE): Promise<Cache | nu
*/
function fetchedAsGl(template: string): boolean {
const { map_provider: provider, maplibre_style: style } = useSettingsStore.getState().settings
if (provider !== 'maplibre-gl' || style !== MAPLIBRE_FROM_TEMPLATE) return false
try {
const url = new URL(template.replace(/\{s\}/g, 'a'))
// The service worker's own matcher, asked about a CORS request for this host.
return isGlRasterTileRequest({ url, request: { mode: 'cors' } as Request })
} catch {
return false
}
return provider === 'maplibre-gl' && style === MAPLIBRE_FROM_TEMPLATE && hasGlRasterCache(template)
}
/**
@@ -8,12 +8,20 @@ import { server } from '../../tests/helpers/msw/server'
import { tripSyncManager, type PrepareProgress } from './tripSyncManager'
import { prefetchTilesForTrip } from './tilePrefetcher'
import { setAuthed } from './authGate'
import { setCacheTiles, setTripOfflineEnabled, _resetOfflinePrefs } from './offlinePrefs'
import { isTripPinned, setCacheTiles, setTripOfflineEnabled, _resetOfflinePrefs } from './offlinePrefs'
import { prefetchPlacesForTrip } from './placePrefetcher'
import { offlineDb, clearAll, upsertTrip } from '../db/offlineDb'
import { buildTrip, buildDay, buildPlace, buildTripFile } from '../../tests/helpers/factories'
import { keepOfflineShellFresh } from '../native/offlineShell'
import { isNativeIos } from '../native/platform'
import type { Trip, TripFile } from '../types'
vi.mock('../native/platform', async (importOriginal) => ({
...(await importOriginal<typeof import('../native/platform')>()),
isNativeIos: vi.fn(() => false),
}))
vi.mock('../native/offlineShell', () => ({ keepOfflineShellFresh: vi.fn() }))
vi.mock('./tilePrefetcher', () => ({
prefetchTilesForTrip: vi.fn(async () => {}),
}))
@@ -77,6 +85,8 @@ beforeEach(async () => {
})
afterEach(() => {
vi.mocked(isNativeIos).mockReset()
vi.mocked(keepOfflineShellFresh).mockReset()
vi.restoreAllMocks()
vi.unstubAllGlobals()
_resetOfflinePrefs()
@@ -142,6 +152,45 @@ describe('tripSyncManager.prepareForOffline — full run', () => {
expect(await offlineDb.tripMembers.where('tripId').equals(602).count()).toBe(1)
})
it('waits for the iOS UI copy before reporting an offline download as ready', async () => {
vi.mocked(isNativeIos).mockReturnValue(true)
let publishCopy: (() => void) | undefined
vi.mocked(keepOfflineShellFresh).mockImplementation(() => new Promise(resolve => {
publishCopy = () => resolve(true)
}))
const trip = buildTrip({ id: 611, end_date: dateOffset(4) })
serveTrips([trip], { 611: bundleFor(trip) })
const progress = vi.fn()
const download = tripSyncManager.prepareForOffline(progress, trip)
try {
await vi.waitFor(() => expect(keepOfflineShellFresh).toHaveBeenCalledOnce())
expect(progress).not.toHaveBeenCalledWith(expect.objectContaining({ phase: 'done' }))
} finally {
publishCopy?.()
await download
}
expect(await download).toEqual({ status: 'done', trips: 1 })
expect(await offlineDb.trips.get(611)).toBeDefined()
const meta = await offlineDb.syncMeta.get(611)
expect(meta?.lastSyncedAt).toBeGreaterThan(0)
expect(isTripPinned(611)).toBe(true)
vi.mocked(keepOfflineShellFresh).mockResolvedValue(false)
progress.mockClear()
await expect(tripSyncManager.prepareForOffline(progress, trip)).rejects.toThrow('The offline app could not be cached')
expect(progress).not.toHaveBeenCalledWith(expect.objectContaining({ phase: 'done' }))
expect(await offlineDb.syncMeta.get(611)).toEqual(meta)
expect(isTripPinned(611)).toBe(true)
const newTrip = buildTrip({ id: 612, end_date: dateOffset(-2) })
serveTrips([newTrip], { 612: bundleFor(newTrip) })
await expect(tripSyncManager.prepareForOffline(progress, newTrip)).rejects.toThrow('The offline app could not be cached')
expect(await offlineDb.syncMeta.get(612)).toBeUndefined()
expect(isTripPinned(612)).toBe(false)
})
it('FE-SYNC-PREP-006: forces the tile prefetch so an already-cached bbox is refreshed', async () => {
const trip = buildTrip({ id: 603, end_date: dateOffset(4) })
serveTrips([trip], { 603: bundleFor(trip) })
+34 -24
View File
@@ -33,6 +33,8 @@ import { prefetchTilesForTrip } from './tilePrefetcher'
import { isAuthed } from './authGate'
import { isEffectivelyOffline } from './networkMode'
import { getOfflinePrefs, isTripOfflineEnabled, isTripPinned, setTripOfflineEnabled, setTripPinned } from './offlinePrefs'
import { keepOfflineShellFresh } from '../native/offlineShell'
import { isNativeIos } from '../native/platform'
import { useSettingsStore } from '../store/settingsStore'
import { useAddonStore } from '../store/addonStore'
import { useTripAddonsStore } from '../store/tripAddonsStore'
@@ -403,6 +405,9 @@ export const tripSyncManager = {
if (skipped) return skipped
_syncing = true
try {
// A trip must not gain a sync timestamp or a pin if its iOS UI is unavailable.
await prepareOfflineUi()
if (!isAuthed()) return { status: 'skipped', reason: 'signed-out' }
const candidates = await offlineTripCandidates(selectedTrip)
const total = candidates.length
const prepared: Trip[] = []
@@ -436,30 +441,7 @@ export const tripSyncManager = {
await cacheFilesForTrip(trip.id, files).catch(console.error)
}
// 3) Map tiles — awaited, and only when the user opted to store them. The
// places go with every run: "prepared" has to mean the offline search
// works, and the tile switch is about tens of megabytes of imagery, not
// about the megabyte a trip's places cost.
{
const wantTiles = getOfflinePrefs().cacheTiles
const tileUrl = useSettingsStore.getState().settings.map_tile_url || undefined
const cartoKey = useSettingsStore.getState().settings.carto_api_key || undefined
i = 0
for (const trip of prepared) {
if (!isAuthed()) return { status: 'skipped', reason: 'signed-out' }
// Reported only when there is a tile phase to report. The place
// prefetch rides along quietly, the way it always did — it is a
// megabyte, not the tens the progress bar exists for.
if (wantTiles) onProgress?.({ phase: 'tiles', current: ++i, total: prepared.length, label: trip.title })
const places = await offlineDb.places.where('trip_id').equals(trip.id).toArray()
if (wantTiles) {
await prefetchTilesForTrip(trip.id, places, tileUrl, true, cartoKey).catch(console.error)
}
await prefetchPlacesForTrip(trip.id, places, true).catch(console.error)
}
}
if (!isAuthed()) return { status: 'skipped', reason: 'signed-out' }
if (!(await prepareOfflineMaps(prepared, onProgress))) return { status: 'skipped', reason: 'signed-out' }
onProgress?.({ phase: 'done', current: prepared.length, total: prepared.length })
return { status: 'done', trips: prepared.length }
} finally {
@@ -473,6 +455,34 @@ export const tripSyncManager = {
},
}
// Download tiles only when requested, but always cache the places needed for offline search.
async function prepareOfflineMaps(trips: Trip[], onProgress?: (p: PrepareProgress) => void): Promise<boolean> {
const wantTiles = getOfflinePrefs().cacheTiles
const tileUrl = useSettingsStore.getState().settings.map_tile_url || undefined
const cartoKey = useSettingsStore.getState().settings.carto_api_key || undefined
let i = 0
for (const trip of trips) {
if (!isAuthed()) return false
// Reported only when there is a tile phase to report. The place
// prefetch rides along quietly, the way it always did — it is a
// megabyte, not the tens the progress bar exists for.
if (wantTiles) onProgress?.({ phase: 'tiles', current: ++i, total: trips.length, label: trip.title })
const places = await offlineDb.places.where('trip_id').equals(trip.id).toArray()
if (wantTiles) {
await prefetchTilesForTrip(trip.id, places, tileUrl, true, cartoKey).catch(console.error)
}
await prefetchPlacesForTrip(trip.id, places, true).catch(console.error)
}
return isAuthed()
}
async function prepareOfflineUi(): Promise<void> {
// The trip bundle is unusable on iOS if WebKit cannot load the planner itself.
if (!isAuthed() || !isNativeIos()) return
const ready = await keepOfflineShellFresh(fetch, useSettingsStore.getState().settings.language, { verifyAssets: true })
if (!ready) throw new Error('The offline app could not be cached')
}
async function offlineTripCandidates(selectedTrip?: Trip) {
if (selectedTrip) return [selectedTrip]
const [{ trips }, archived] = await Promise.all([tripsApi.list() as Promise<{ trips: Trip[] }>, archivedTrips()])
+8 -2
View File
@@ -97,6 +97,9 @@ async function settle(row: UserQueuedMutation, err: unknown): Promise<Outcome> {
const status = (err as { response?: { status?: number } } | null)?.response?.status;
// A delete of something the server no longer has did what it set out to do.
if (status === 404 && row.method === 'DELETE') {
const account = offlineDb.name;
if (row.resource.startsWith('atlas')) await reconcileAtlasWrite(row);
if (account !== offlineDb.name) return 'stop';
await offlineDb.userMutationQueue.delete(row.id);
return 'done';
}
@@ -119,6 +122,7 @@ async function settle(row: UserQueuedMutation, err: unknown): Promise<Outcome> {
async function replay(row: UserQueuedMutation, idMap: Map<number, number>): Promise<Outcome> {
const ids = resolveIds(row, idMap);
if (!ids) return park(row, 'unresolved temp id (dependent create did not sync)');
const account = offlineDb.name;
await offlineDb.userMutationQueue.update(row.id, { status: 'syncing', syncingSince: Date.now() });
try {
const response = await apiClient.request({
@@ -127,13 +131,15 @@ async function replay(row: UserQueuedMutation, idMap: Map<number, number>): Prom
data: row.body,
headers: { 'X-Idempotency-Key': row.id },
});
if (account !== offlineDb.name) return 'stop';
const realId = row.tempId === undefined ? undefined : createdId(response.data);
if (row.tempId !== undefined && realId !== undefined) await learnId(row.tempId, realId, idMap);
if (row.resource.startsWith('atlas')) await reconcileAtlasWrite({ ...row, ids, answer: response.data });
if (row.resource.startsWith('atlas')) await reconcileAtlasWrite(row);
if (account !== offlineDb.name) return 'stop';
await offlineDb.userMutationQueue.delete(row.id);
return 'done';
} catch (err: unknown) {
return settle(row, err);
return account === offlineDb.name ? settle(row, err) : 'stop';
}
}
+1 -1
View File
@@ -5,7 +5,7 @@
"src/db/repositories/Reservations.repository.ts": 1538,
"src/db/repositories/Trips.repository.ts": 1101,
"src/db/repositories/Users.repository.ts": 1403,
"src/nest/atlas/atlas.service.ts": 1166,
"src/nest/atlas/atlas.service.ts": 1163,
"src/nest/auth/auth.service.ts": 1114,
"src/nest/budget/budget.service.ts": 1607,
"src/nest/collections/collections.service.ts": 1386,
@@ -15,6 +15,7 @@ export class JourneyShareSubscribers {
unsubscribe_token!: string;
last_notified_at?: string | null;
created_at?: string | null;
pending_digest_entries?: string | null;
}
export const JourneyShareSubscribersSchema = defineEntity({
@@ -36,5 +37,6 @@ export const JourneyShareSubscribersSchema = defineEntity({
unsubscribe_token: p.text(),
last_notified_at: p.type(DbTimestampType).nullable(),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
pending_digest_entries: p.text().nullable(),
},
});
+6
View File
@@ -121,6 +121,12 @@ export const USER_MFA_BACKUP_CODES: JsonColumn<unknown[]> = {
fallback: () => [],
};
export const JOURNEY_PENDING_DIGEST_ENTRIES: JsonColumn<number[]> = {
column: 'journey_share_subscribers.pending_digest_entries',
schema: z.array(z.number().int().positive()),
fallback: () => [],
};
/** A journey entry's tags. */
export const JOURNEY_ENTRY_TAGS: JsonColumn<string[]> = {
column: 'journey_entries.tags',
@@ -12,4 +12,5 @@ export interface JourneyShareSubscribersTable {
unsubscribe_token: string;
last_notified_at: InsertOptional<string | null>;
created_at: InsertOptional<string | null>;
pending_digest_entries: InsertOptional<string | null>;
}
@@ -0,0 +1,13 @@
import { engineDdl } from '../migration-utils';
import { Migration } from '@mikro-orm/migrations';
export class Migration20200101046660_a_journey_keeps_unsent_digests extends Migration {
override name = 'Migration20200101046660_a_journey_keeps_unsent_digests';
override up(): void {
engineDdl(this, {
sqlite: ['ALTER TABLE journey_share_subscribers ADD COLUMN pending_digest_entries TEXT'],
postgres: ['alter table "journey_share_subscribers" add "pending_digest_entries" text null'],
});
}
}
@@ -836,21 +836,29 @@ export class JourneyEntriesRepository extends TrekRepository<JourneyEntries> {
/** The entries of one journey that {@link listJourneysToAnnounce} found, in the journal's order. */
async listToAnnounce(journeyId: number): Promise<JourneyEntryToAnnounce[]> {
return await this.kysely<JourneyEntriesDateSortKyselyDB>()
return await this.announceEntries(journeyId).where('announced', '=', 0).execute();
}
/** Entries are checked again before an email retry, since a draft or deletion takes them off the link. */
async listPendingDigestEntries(journeyId: number, ids: number[]): Promise<JourneyEntryToAnnounce[]> {
if (ids.length === 0) return [];
return await this.announceEntries(journeyId).where('id', 'in', ids).execute();
}
private announceEntries(journeyId: number) {
return this.kysely<JourneyEntriesDateSortKyselyDB>()
.selectFrom('journey_entries')
.select(['id', 'title', 'entry_date', 'location_name', 'author_id'])
.where('journey_id', '=', journeyId)
.where('announced', '=', 0)
.where('type', '!=', 'skeleton')
.where('dismissed', '=', 0)
.where('is_draft', '=', 0)
.orderBy('entry_date', 'asc')
.orderBy('sort_order', 'asc')
.orderBy('id', 'asc')
.execute();
.orderBy('id', 'asc');
}
/** The digest spoke of these entries: never again, even if one goes back to a draft and returns. */
/** The entries were announced to the journey and added to the pending digests. */
async markAnnounced(ids: number[]): Promise<void> {
if (ids.length === 0) return;
await this.kysely<JourneyEntriesDateSortKyselyDB>()
@@ -14,6 +14,7 @@ interface JourneyShareSubscriberRow {
confirmed_at: string | null;
unsubscribe_token: string;
last_notified_at: string | null;
pending_digest_entries: string | null;
created_at: string | null;
}
@@ -108,16 +109,38 @@ export class JourneyShareSubscribersRepository extends TrekRepository<JourneySha
return await this.nativeDelete({ id, shareToken: shareTokenId });
}
/**
* The confirmed addresses of a link that got no digest since `cutoffAt`
* (canonical DATETIME text): at most one mail a day each.
*/
/** Keeps the entry ids an address still has to hear about. */
async setPendingDigest(id: number, entryIds: string | null): Promise<void> {
await this.db()
.updateTable('journey_share_subscribers')
.set({ pending_digest_entries: entryIds })
.where('id', '=', id)
.execute();
}
/** Journeys that have mail waiting for at least one recipient due a digest. */
async listDueJourneyIds(cutoffAt: string): Promise<number[]> {
const rows = await this.db()
.selectFrom('journey_share_subscribers as s')
.innerJoin('journey_share_tokens as t', 't.id', 's.share_token_id')
.select('t.journey_id')
.distinct()
.where('s.confirmed_at', 'is not', null)
.where('s.pending_digest_entries', 'is not', null)
.where((eb) => eb.or([eb('s.last_notified_at', 'is', null), eb('s.last_notified_at', '<', cutoffAt)]))
.orderBy('t.journey_id', 'asc')
.execute();
return rows.map((row) => row.journey_id);
}
/** Confirmed followers of a link who still have mail and are due a digest. */
async listDue(shareTokenId: number, cutoffAt: string): Promise<JourneyShareSubscriberRow[]> {
return await this.db()
.selectFrom('journey_share_subscribers')
.selectAll()
.where('share_token_id', '=', shareTokenId)
.where('confirmed_at', 'is not', null)
.where('pending_digest_entries', 'is not', null)
.where((eb) => eb.or([eb('last_notified_at', 'is', null), eb('last_notified_at', '<', cutoffAt)]))
.orderBy('id', 'asc')
.execute();
@@ -128,7 +151,7 @@ export class JourneyShareSubscribersRepository extends TrekRepository<JourneySha
if (ids.length === 0) return;
await this.db()
.updateTable('journey_share_subscribers')
.set({ last_notified_at: notifiedAt })
.set({ last_notified_at: notifiedAt, pending_digest_entries: null })
.where('id', 'in', ids)
.execute();
}
@@ -23,11 +23,8 @@ type PackingItemContributorsKyselyDB = Pick<DB, 'packing_item_contributors' | 'u
* `Migration20200101022900_three_tier_packing_sharing.ts:23-30`'s own
* `PRIMARY KEY (item_id, user_id)`), the only join table in this cluster
* shaped that way (every sibling uses a surrogate `id` PK + a `uniques`
* array instead). So it gets a normal, entity-backed repository, and its
* writes use the composite-key form of `em.upsert`/`nativeDelete` (the
* conflict/match target is the two-column PK, not a synthetic id) — the
* `ReservationDayPositionsRepository`/`ReservationDayPositions.entity.ts`
* precedent for a genuine composite-PK relation table.
* array instead). Both columns identify a contribution, including when a
* bulk write keeps an existing person's record.
*/
export class PackingItemContributorsRepository extends TrekRepository<PackingItemContributors> {
/**
@@ -52,20 +49,28 @@ export class PackingItemContributorsRepository extends TrekRepository<PackingIte
.execute();
}
/**
* PK20 (`addContributor`) — `INSERT OR IGNORE INTO
* packing_item_contributors (item_id, user_id, status) VALUES (?, ?,
* 'accepted')`. `em.upsert` with the composite-PK conflict target
* (`onConflictFields: ['item', 'user']`, the entity's real `PRIMARY KEY
* (item_id, user_id)` — R5/§16, NOT a synthetic-id workaround), named by
* entity property (the `AssignmentParticipantsRepository.insertIgnore`
* precedent).
*/
/** Keep an existing bringer's record when the same person is selected again. */
async insertIgnore(item_id: number, user_id: number): Promise<void> {
await this.upsert(
{ item: item_id, user: user_id, status: 'accepted' },
{ onConflictFields: ['item', 'user'], onConflictAction: 'ignore' },
);
await this.insertManyIgnore(item_id, [user_id]);
}
async insertManyIgnore(item_id: number, user_ids: number[]): Promise<void> {
if (user_ids.length === 0) return;
await this.kysely<PackingItemContributorsKyselyDB>()
.insertInto('packing_item_contributors')
.values(user_ids.map((user_id) => ({ item_id, user_id, status: 'accepted' })))
.onConflict((conflict) => conflict.columns(['item_id', 'user_id']).doNothing())
.execute();
}
/** Remove former bringers when an editor replaces the whole selection. */
async deleteExcept(item_id: number, user_ids: number[]): Promise<void> {
if (user_ids.length === 0) return this.deleteForItem(item_id);
await this.kysely<PackingItemContributorsKyselyDB>()
.deleteFrom('packing_item_contributors')
.where('item_id', '=', item_id)
.where('user_id', 'not in', user_ids)
.execute();
}
/** PK18 (`setItemSharing`'s leaving-Common cleanup) — `DELETE FROM packing_item_contributors WHERE item_id = ?`. */
@@ -61,20 +61,18 @@ export class VisitedCountriesRepository extends TrekRepository<VisitedCountries>
return rows.map((row) => ({ ...row, source: publicSource(row.source) }));
}
/**
* AT5/AT7/AT43 (`stats`'s no-trip early return, `stats`'s manual-country
* merge, `getTravelStats`'s manual-country merge — three identical-text
* call sites) — `SELECT country_code FROM visited_countries WHERE user_id
* = ?`. Returns the bare code list; every one of the three callers only
* ever reads `.country_code` off the legacy row shape.
*/
/** The user's visited codes (AT5/AT7/AT43). */
async listCodesForUser(userId: number): Promise<string[]> {
const rows = await this.writeDb()
return (await this.listMarksForUser(userId)).map((row) => row.country_code);
}
/** The offline projection needs the stored source to distinguish a country's own mark. */
async listMarksForUser(userId: number): Promise<Pick<VisitedCountryRow, 'country_code' | 'source'>[]> {
return this.writeDb()
.selectFrom('visited_countries')
.select('country_code')
.select(['country_code', 'source'])
.where('user_id', '=', userId)
.execute();
return rows.map((r) => r.country_code);
}
/** AT8/AT9 (`countryPlaces`'s no-trip early return, `countryPlaces`'s mark lookup — identical text) — `SELECT source FROM visited_countries WHERE user_id = ? AND country_code = ?`. */
@@ -0,0 +1,19 @@
import type { VisitStatus } from '@trek/shared';
export interface AtlasRegionRow {
code: string;
name: string;
placeCount: number;
status: VisitStatus;
manuallyMarked?: boolean;
placeStatus?: VisitStatus;
}
/** State the client needs when a mark is removed while offline. */
export function atlasCountryOfflineState(
include: boolean,
source: string | undefined,
placeStatus: VisitStatus | null,
) {
return include ? { offline: { directMark: source !== undefined && source !== 'region', placeStatus } } : {};
}
+4 -4
View File
@@ -83,14 +83,14 @@ export class AtlasController {
}
@Get('stats')
async stats(@CurrentUser() user: User) {
return this.atlas.stats(user.id);
async stats(@CurrentUser() user: User, @Query('offline') offline?: string) {
return offline === '1' ? this.atlas.stats(user.id, true) : this.atlas.stats(user.id);
}
@Get('regions')
@Header('Cache-Control', 'no-cache, no-store')
async regions(@CurrentUser() user: User) {
return this.atlas.visitedRegions(user.id);
async regions(@CurrentUser() user: User, @Query('offline') offline?: string) {
return offline === '1' ? this.atlas.visitedRegions(user.id, true) : this.atlas.visitedRegions(user.id);
}
/**
+26 -30
View File
@@ -37,7 +37,8 @@ import type { RegionInfo } from './atlas-geo';
import { isCountryName } from './known-countries';
import { cityFromAddress } from './city-from-address';
import { transferEndpointIds } from './transfer-endpoints';
import { countryVisitDates } from './visit-dates';
import { countryVisitDates, daysBetween } from './visit-dates';
import { atlasCountryOfflineState, type AtlasRegionRow } from './atlas-offline-state';
import { placeCountryResolver } from './place-countries';
import { haversineKm } from '../common/geo';
import { CountryVisits, latestPerCoordinate } from './atlas-visit-order';
@@ -51,17 +52,6 @@ type CachedRegionRow = LocatedPlace & { country_code: string; region_code: strin
/** How many cached rows the #2527 repair checks before it lets other work run. */
const REPAIR_YIELD_EVERY = 200;
/**
* Whole days from `today` to `isoDate`, both `YYYY-MM-DD` in UTC: the legacy
* `CAST(julianday(start_date) - julianday(date('now')) AS INTEGER)` (#2542),
* truncated toward zero the same way.
*/
function daysBetween(today: string, isoDate: string): number {
const from = Date.parse(`${today.slice(0, 10)}T00:00:00Z`);
const to = Date.parse(`${isoDate.slice(0, 10)}T00:00:00Z`);
return Math.trunc((to - from) / 86_400_000);
}
/**
* A reservation endpoint plus the two booking columns that decide whether it may
* take part in layover pairing at all (see transfer-endpoints.ts). Structurally
@@ -327,16 +317,23 @@ export class AtlasService {
// ── Stats ─────────────────────────────────────────────────────────────────
async stats(userId: number) {
async stats(userId: number, includeOfflineState = false) {
const trips = await this.getUserTrips(userId);
const tripIds = trips.map((t) => t.id);
if (tripIds.length === 0) {
const hiddenOnly = await this.getHiddenCountries(userId);
const manualCountryCodes = await this.visitedCountries.listCodesForUser(userId); // AT5
const countries = manualCountryCodes
.filter((code) => !hiddenOnly.has(code))
.map((code) => ({ code, placeCount: 0, tripCount: 0, firstVisit: null, lastVisit: null }));
const marks = await this.visitedCountries.listMarksForUser(userId); // AT5
const countries = marks
.filter((mark) => !hiddenOnly.has(mark.country_code))
.map((mark) => ({
code: mark.country_code,
placeCount: 0,
tripCount: 0,
firstVisit: null,
lastVisit: null,
...atlasCountryOfflineState(includeOfflineState, mark.source, null),
}));
return {
countries,
trips: [],
@@ -405,8 +402,9 @@ export class AtlasService {
const hidden = await this.getHiddenCountries(userId);
// Merge manually marked countries
const manualCountryCodes = await this.visitedCountries.listCodesForUser(userId); // AT7
for (const code of manualCountryCodes) {
const marks = await this.visitedCountries.listMarksForUser(userId); // AT7
const markSources = new Map(marks.map((mark) => [mark.country_code, mark.source]));
for (const code of markSources.keys()) {
if (hidden.has(code)) continue;
const existing = countries.find((c) => c.code === code);
if (existing) {
@@ -547,7 +545,12 @@ export class AtlasService {
const firstYear = tripYears.size > 0 ? Math.min(...tripYears) : null;
return {
countries,
countries: includeOfflineState
? countries.map((c) => ({
...c,
...atlasCountryOfflineState(true, markSources.get(c.code), countrySet.get(c.code)?.status ?? null),
}))
: countries,
stats: {
totalTrips: trips.length,
totalPlaces: footprint.totalPlaces,
@@ -747,12 +750,7 @@ export class AtlasService {
// ── Visited regions ───────────────────────────────────────────────────────
async visitedRegions(userId: number): Promise<{
regions: Record<
string,
{ code: string; name: string; placeCount: number; status: VisitStatus; manuallyMarked?: boolean }[]
>;
}> {
async visitedRegions(userId: number, includeOfflineState = false): Promise<{ regions: Record<string, AtlasRegionRow[]> }> {
const trips = await this.getUserTrips(userId);
const tripIds = trips.map((t) => t.id);
const places = await this.getPlacesForTrips(tripIds);
@@ -795,10 +793,7 @@ export class AtlasService {
}
}
const result: Record<
string,
{ code: string; name: string; placeCount: number; status: VisitStatus; manuallyMarked?: boolean }[]
> = {};
const result: Record<string, AtlasRegionRow[]> = {};
for (const [country, regions] of Object.entries(regionMap)) {
result[country] = [...regions.values()];
}
@@ -809,6 +804,7 @@ export class AtlasService {
if (!result[r.country_code]) result[r.country_code] = [];
const existing = result[r.country_code].find((x) => x.code === r.region_code);
if (existing) {
if (includeOfflineState) existing.placeStatus = existing.status;
existing.status = 'visited';
} else {
result[r.country_code].push({
+11
View File
@@ -38,3 +38,14 @@ export function countryVisitDates(
}
return { firstVisit, lastVisit };
}
/**
* Whole days from `today` to `isoDate`, both `YYYY-MM-DD` in UTC: the legacy
* `CAST(julianday(start_date) - julianday(date('now')) AS INTEGER)` (#2542),
* truncated toward zero the same way.
*/
export function daysBetween(today: string, isoDate: string): number {
const from = Date.parse(`${today.slice(0, 10)}T00:00:00Z`);
const to = Date.parse(`${isoDate.slice(0, 10)}T00:00:00Z`);
return Math.trunc((to - from) / 86_400_000);
}
+105 -66
View File
@@ -3,14 +3,17 @@ import { JourneyEntries } from '../../db/entities/JourneyEntries.entity';
import { JourneyShareSubscribers } from '../../db/entities/JourneyShareSubscribers.entity';
import { JourneyShareTokens } from '../../db/entities/JourneyShareTokens.entity';
import { Journeys } from '../../db/entities/Journeys.entity';
import { JOURNEY_PENDING_DIGEST_ENTRIES } from '../../db/json-columns';
import type { JourneyEntriesRepository, JourneyEntryToAnnounce } from '../../db/repositories/JourneyEntries.repository';
import type { JourneyShareSubscribersRepository } from '../../db/repositories/JourneyShareSubscribers.repository';
import type { JourneyShareTokensRepository } from '../../db/repositories/JourneyShareTokens.repository';
import type { JourneysRepository } from '../../db/repositories/Journeys.repository';
import { dbNow } from '../../db/types';
import { forEachInOrder } from '../../utils/for-each-in-order';
import { decodeJson, encodeJson } from '../../utils/json-column';
import { AddonsService } from '../addons/addons.service';
import { logError } from '../audit/audit-log.logger';
import { UnitOfWork } from '../database/unit-of-work';
import { MailerService } from '../notifications/mailer/mailer.service';
import { NotificationsService } from '../notifications/notifications.service';
import { shareLinkExpired } from './journey-share-access';
@@ -24,6 +27,13 @@ const DIGEST_MIN_GAP_MS = 20 * 60 * 60 * 1000;
/** How long an address may wait for its confirmation before it is forgotten. */
const UNCONFIRMED_KEEP_MS = 7 * 24 * 60 * 60 * 1000;
function entryBatches(ids: number[]): number[][] {
const size = 500;
return Array.from({ length: Math.ceil(ids.length / size) }, (_, index) =>
ids.slice(index * size, (index + 1) * size),
);
}
/** What one run of the digest did. */
export interface JourneyDigestResult {
journeys: number;
@@ -36,74 +46,77 @@ function message(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}
/**
* The daily digest of what was published in a journey (#1669).
*
* An entry counts once it is something a reader of the share link would see
* (published, not a skeleton, not a dismissed suggestion) and the digest has
* not spoken of it yet (`journey_entries.announced`). Once a day, for every
* journey holding such entries:
*
* - everyone on the journey hears about them in the app and on the channels
* they chose (`journey_entry_published`, their notification settings apply),
* unless every one of them is their own;
* - every confirmed follower of its share link gets one mail naming them, when
* the link allows following, still works, shows its timeline or its map,
* and the instance can send mail; each at most once a day, in the language
* they chose, with the link that stops the mails (a link behind a password
* only says that there is something new, without naming the entries);
* - and the entries are marked as told, so no digest names one twice, also
* when it goes back to a draft and comes out again.
*
* Every run also forgets the addresses that never confirmed within a week.
*/
/** Queues mail per confirmed follower as new entries are announced to the journey. */
@Injectable()
export class JourneyDigestService {
constructor(
private readonly addons: AddonsService,
private readonly notifications: NotificationsService,
private readonly mailer: MailerService,
private readonly uow: UnitOfWork,
@InjectRepository(JourneyEntries) private readonly entriesRepo: JourneyEntriesRepository,
@InjectRepository(Journeys) private readonly journeysRepo: JourneysRepository,
@InjectRepository(JourneyShareTokens) private readonly linksRepo: JourneyShareTokensRepository,
@InjectRepository(JourneyShareSubscribers) private readonly subscribersRepo: JourneyShareSubscribersRepository,
) {}
/**
* One run: every journey with something new, one after the other, so one
* that fails is logged and the others still go out.
*
* @txIndependent each journey is announced on its own, with mail sent between the writes.
*/
/** @txIndependent Pending mail and in-app announcements are recorded before sending. */
async run(now: Date = new Date()): Promise<JourneyDigestResult> {
const result: JourneyDigestResult = { journeys: 0, notified: 0, mailed: 0, purged: 0 };
if (!(await this.addons.isAddonEnabled(ADDON_IDS.JOURNEY))) return result;
const forgetBefore = dbNow(new Date(now.getTime() - UNCONFIRMED_KEEP_MS));
result.purged = await this.subscribersRepo.purgeUnconfirmed(forgetBefore);
const canMail = await this.mailer.isSmtpConfigured();
result.purged = await this.subscribersRepo.purgeUnconfirmed(dbNow(new Date(now.getTime() - UNCONFIRMED_KEEP_MS)));
const journeyIds = await this.entriesRepo.listJourneysToAnnounce();
await forEachInOrder(journeyIds, async (journeyId) => {
try {
const done = await this.announce(journeyId, now, canMail);
result.notified += await this.announce(journeyId, now);
result.journeys += 1;
result.notified += done.notified;
result.mailed += done.mailed;
} catch (err) {
logError(`[journey-digest] journey ${journeyId}: ${message(err)}`);
}
});
if (await this.mailer.isSmtpConfigured()) {
result.mailed = await this.sendPending(now);
}
return result;
}
/** @txIndependent the notifications and mails go out between the reads and the final mark. */
private async announce(journeyId: number, now: Date, canMail: boolean) {
const entries = await this.entriesRepo.listToAnnounce(journeyId);
const journey = await this.journeysRepo.findById(journeyId);
if (entries.length === 0 || !journey) return { notified: 0, mailed: 0 };
const notified = await this.notifyPeople(journeyId, journey.title, entries);
const mailed = canMail ? await this.mailFollowers(journeyId, journey.title, entries, now) : 0;
await this.entriesRepo.markAnnounced(entries.map((e) => e.id));
return { notified, mailed };
private async announce(journeyId: number, now: Date): Promise<number> {
const batch = await this.uow.transactional(async () => {
const entries = await this.entriesRepo.listToAnnounce(journeyId);
const journey = await this.journeysRepo.findById(journeyId);
if (entries.length === 0 || !journey) return null;
const ids = entries.map((entry) => entry.id);
await this.queueForFollowers(journeyId, ids, now);
await forEachInOrder(entryBatches(ids), (chunk) => this.entriesRepo.markAnnounced(chunk));
return { title: journey.title, entries };
});
return batch ? this.notifyPeople(journeyId, batch.title, batch.entries) : 0;
}
private async queueForFollowers(journeyId: number, ids: number[], now: Date): Promise<void> {
const link = await this.deliveryLink(journeyId, now);
if (!link) return;
const followers = await this.subscribersRepo.listForLink(link.id);
await forEachInOrder(followers, async (follower) => {
if (follower.confirmed_at === null) return;
const kept = decodeJson(JOURNEY_PENDING_DIGEST_ENTRIES, follower.pending_digest_entries, String(follower.id));
await this.subscribersRepo.setPendingDigest(
follower.id,
encodeJson(JOURNEY_PENDING_DIGEST_ENTRIES, [...kept, ...ids]),
);
});
}
private async deliveryLink(journeyId: number, now: Date) {
const link = await this.linksRepo.findByJourneyId(journeyId);
if (
!link?.allow_subscriptions ||
shareLinkExpired(link.expires_at, now) ||
(!link.share_timeline && !link.share_map)
) {
return null;
}
return link;
}
/** Everyone on the journey, unless every new entry is their own. */
@@ -128,35 +141,61 @@ export class JourneyDigestService {
return notified;
}
/**
* The confirmed followers of the journey's link that are due, one mail
* each, stamped once they went out.
*/
private async mailFollowers(
journeyId: number,
title: string,
entries: JourneyEntryToAnnounce[],
now: Date,
): Promise<number> {
const link = await this.linksRepo.findByJourneyId(journeyId);
if (!link || !link.allow_subscriptions || shareLinkExpired(link.expires_at, now)) return 0;
if (!link.share_timeline && !link.share_map) return 0;
const due = await this.subscribersRepo.listDue(link.id, dbNow(new Date(now.getTime() - DIGEST_MIN_GAP_MS)));
// A link behind a password names no entry in a mail: a follower keeps the
// mails after the owner changed the password, and a mail is no place for
// what the password guards. They only hear that there is something new.
const named = link.password_hash ? [] : entries;
const mailed: number[] = [];
await forEachInOrder(due, async (follower) => {
const mail = digestMail(follower.locale, title, named, {
private async sendPending(now: Date): Promise<number> {
const cutoff = dbNow(new Date(now.getTime() - DIGEST_MIN_GAP_MS));
const journeyIds = await this.subscribersRepo.listDueJourneyIds(cutoff);
let mailed = 0;
await forEachInOrder(journeyIds, async (journeyId) => {
try {
mailed += await this.mailFollowers(journeyId, cutoff, now);
} catch (err) {
logError(`[journey-digest] sending journey ${journeyId}: ${message(err)}`);
}
});
return mailed;
}
/** @txIndependent SMTP and its acknowledgement are independent for each address. */
private async mailFollowers(journeyId: number, cutoff: string, now: Date): Promise<number> {
const link = await this.deliveryLink(journeyId, now);
const journey = await this.journeysRepo.findById(journeyId);
if (!link || !journey) return 0;
const followers = await this.subscribersRepo.listDue(link.id, cutoff);
const entriesByBatch = new Map<string, JourneyEntryToAnnounce[]>();
let mailed = 0;
await forEachInOrder(followers, async (follower) => {
const pending = follower.pending_digest_entries;
if (pending === null) return;
let entries = entriesByBatch.get(pending);
if (!entries) {
entries = await this.pendingEntries(journeyId, pending);
entriesByBatch.set(pending, entries);
}
if (entries.length === 0) {
await this.subscribersRepo.setPendingDigest(follower.id, null);
return;
}
// A retry also respects a password the owner added after the original announcement.
const named = link.password_hash ? [] : entries;
const mail = digestMail(follower.locale, journey.title, named, {
link: link.token,
unsubscribe: follower.unsubscribe_token,
});
if (await this.mailer.sendStandaloneEmail(follower.email, mail, unsubscribeUrl(follower.unsubscribe_token))) {
mailed.push(follower.id);
await this.subscribersRepo.markNotified([follower.id], dbNow(now));
mailed += 1;
}
});
await this.subscribersRepo.markNotified(mailed, dbNow(now));
return mailed.length;
return mailed;
}
private async pendingEntries(journeyId: number, pending: string): Promise<JourneyEntryToAnnounce[]> {
const ids = decodeJson(JOURNEY_PENDING_DIGEST_ENTRIES, pending, `journey ${journeyId}`);
const entries: JourneyEntryToAnnounce[] = [];
await forEachInOrder(entryBatches(ids), async (chunk) => {
entries.push(...(await this.entriesRepo.listPendingDigestEntries(journeyId, chunk)));
});
return entries.sort((a, b) => a.entry_date.localeCompare(b.entry_date));
}
}
+2
View File
@@ -45,6 +45,7 @@ interface MailEnvelope {
messageId: string | null;
deliveredTo: string | null;
xOriginalTo: string | null;
xForwardedTo: string | null;
listUnsubscribe: string | null;
precedence: string | null;
autoSubmitted: string | null;
@@ -85,6 +86,7 @@ const ENVELOPE_HEADERS: [keyof MailEnvelope, string][] = [
['messageId', 'message-id'],
['deliveredTo', 'delivered-to'],
['xOriginalTo', 'x-original-to'],
['xForwardedTo', 'x-forwarded-to'],
['listUnsubscribe', 'list-unsubscribe'],
['precedence', 'precedence'],
['autoSubmitted', 'auto-submitted'],
@@ -24,6 +24,8 @@ export interface ImapSession {
listAfter(lastUid: number): Promise<ImapMailRef[]>;
/** One mail's raw bytes; null for a uid that is gone. */
source(uid: number): Promise<Buffer | null>;
/** The folder's server path, or null if the folder does not exist. */
findFolder(parts: readonly string[]): Promise<string | null>;
/** Makes the folder (made of these parts, in the server's own delimiter) unless it exists; answers its path. */
ensureFolder(parts: readonly string[]): Promise<string>;
move(uids: readonly number[], folder: string): Promise<void>;
@@ -69,6 +71,8 @@ async function vettedAddress(host: string): Promise<string> {
return verdict.resolvedIp;
}
class ImapFolderError extends Error {}
class ImapFlowSession implements ImapSession {
/** How many mails the open folder holds; an empty one is not asked for a range, which some servers refuse. */
private exists = 0;
@@ -99,9 +103,47 @@ class ImapFlowSession implements ImapSession {
return message && Buffer.isBuffer(message.source) ? message.source : null;
}
async findFolder(parts: readonly string[]): Promise<string | null> {
try {
const status = await this.client.status([...parts], { uidValidity: true });
if (status) return status.path;
} catch (err) {
// ImapFlow uses LIST to confirm that a mailbox refused by STATUS is missing.
if (err instanceof Error && 'code' in err && err.code === 'NotFound') return null;
throw new ImapFolderError(`Could not check IMAP folder ${parts.join('/')}. ${describeImapFailure(err)}`, {
cause: err,
});
}
throw new ImapFolderError(`The IMAP server did not return the status of folder ${parts.join('/')}`);
}
async ensureFolder(parts: readonly string[]): Promise<string> {
const created = await this.client.mailboxCreate([...parts]);
return created.path;
const existing = await this.findFolder(parts);
if (existing !== null) return existing;
try {
return await this.createFolder(parts);
} catch (err) {
// Some servers require the parent to be created separately.
const parent = parts.slice(0, -1);
if (parent.length === 0 || (await this.findFolder(parent)) !== null) throw err;
await this.createFolder(parent);
return this.createFolder(parts);
}
}
private async createFolder(parts: readonly string[]): Promise<string> {
try {
const created = await this.client.mailboxCreate([...parts]);
return created.path;
} catch (err) {
// The folder may have been created between the status check and CREATE.
const appeared = await this.findFolder(parts).catch(() => null);
if (appeared !== null) return appeared;
throw new ImapFolderError(`Could not create IMAP folder ${parts.join('/')}. ${describeImapFailure(err)}`, {
cause: err,
});
}
}
async move(uids: readonly number[], folder: string): Promise<void> {
@@ -128,7 +170,7 @@ function dateOf(value: Date | string | undefined): Date | null {
/** What an admin reads when the box cannot be read: the reason, never the password. */
export function describeImapFailure(err: unknown): string {
if (err instanceof SsrfBlockedError) return err.message;
if (err instanceof SsrfBlockedError || err instanceof ImapFolderError) return err.message;
const failure = (err ?? {}) as {
authenticationFailed?: boolean;
code?: string;
@@ -128,7 +128,9 @@ export class MailIngestImapJob implements OnApplicationBootstrap {
* it waited {@link DEFER_DAYS} already, and is then given up the same way.
*/
private async retryDeferred(session: ImapSession, now: Date): Promise<number> {
await session.open(await session.ensureFolder(DEFERRED_FOLDER));
const folder = await session.findFolder(DEFERRED_FOLDER);
if (folder === null) return 0;
await session.open(folder);
const due = (await session.listAfter(0)).slice(0, DEFERRED_PER_RUN);
if (due.length === 0) return 0;
const outcomes = await this.takeAll(session, due);
@@ -7,6 +7,7 @@ import { dbNow } from '../../db/types';
import { UnitOfWork } from '../database/unit-of-work';
import { MailReadService } from '../llm-parse/mail-read.service';
import type { WalkedMail } from '../llm-parse/mail-read.types';
import { addressOf } from './mail-classify';
import { MailIngestAddressService } from './mail-ingest-address.service';
import { MailIngestSettingsService } from './mail-ingest-settings.service';
import { MAIL_INGEST_LIMITS } from './mail-ingest.constants';
@@ -82,7 +83,7 @@ export class MailIngestIntakeService {
const addresses =
envelopeRecipients.length > 0
? await this.addresses.resolveAll(envelopeRecipients)
: await this.headerAddresses(mail.envelope);
: await this.headerAddresses(mail.envelope, transport === 'imap');
if (addresses.length === 0) return { status: 'refused', reason: 'unknown_address' };
const results = await addresses.reduce<Promise<MailIntakeResult[]>>(async (previous, address) => {
const done = await previous;
@@ -111,10 +112,21 @@ export class MailIngestIntakeService {
* writes, then To. The first that names one decides. A delivery header
* without a token names none: Stalwart writes the box itself there, its
* sub-address dropped, and the token then stands only in To.
*
* Gmail automatic forwarding can put a bare address such as
* trek+{token}@example.com in X-Forwarded-To. IMAP tries the topmost value
* of that header when none of the headers above names a live address.
*/
private async headerAddresses(envelope: WalkedMail['envelope']): Promise<MailIngestAddressRow[]> {
private async headerAddresses(
envelope: WalkedMail['envelope'],
useForwardedTo: boolean,
): Promise<MailIngestAddressRow[]> {
const named = await Promise.all(headerRecipients(envelope).map((list) => this.addresses.resolveAll(list)));
return named.find((addresses) => addresses.length > 0) ?? [];
const matched = named.find((addresses) => addresses.length > 0);
if (matched) return matched;
const forwardedTo = useForwardedTo ? addressOf(envelope.xForwardedTo) : null;
return forwardedTo && /^[^\s@]+@[^\s@]+$/.test(forwardedTo) ? this.addresses.resolveAll([forwardedTo]) : [];
}
private async precheck(raw: Buffer): Promise<MailIntakeRefusal | null> {
@@ -183,6 +183,14 @@ export class PackingWritesService {
return item;
}
async setBringers(tripId: number, itemId: number, userIds: number[], writer: TripWriter) {
await this.gate(tripId, writer);
const item = await this.packing.setBringers(tripId, itemId, userIds, writer.userId);
if (!item) throw itemNotFound();
writer.events.emit('packing:updated', { item } as TrekWsPayload<'packing:updated'>, this.packing.viewersOf(item));
return item;
}
/** The list's new order, for every other tab on both surfaces. */
async reorder(tripId: string | number, orderedIds: number[], writer: TripWriter) {
await this.gate(tripId, writer);
@@ -270,8 +270,7 @@ export class PackingController {
if (!item) {
throw new HttpException({ error: 'Item not found or not a shared list item' }, 404);
}
// Common item — visible to all, so the contributor change broadcasts to the room.
this.packing.broadcast(tripId, 'packing:updated', { item }, socketId);
this.packing.emitToViewers(tripId, 'packing:updated', { item }, item, socketId);
return { item };
}
@@ -298,7 +297,7 @@ export class PackingController {
if (!item) {
throw new HttpException({ error: 'Item not found' }, 404);
}
this.packing.broadcast(tripId, 'packing:updated', { item }, socketId);
this.packing.emitToViewers(tripId, 'packing:updated', { item }, item, socketId);
return { item };
}
+27
View File
@@ -23,6 +23,7 @@ import {
packingCreateBagRequestSchema,
packingCreateItemRequestSchema,
packingListItemsRequestSchema,
packingSetBringersRequestSchema,
packingSetSharingRequestSchema,
packingUpdateBagRequestSchema,
packingUpdateItemRequestSchema,
@@ -292,6 +293,32 @@ export class PackingMcp {
return ok({ item });
}
@Tool({
name: 'set_packing_item_bringers',
description:
'Set who brings a Common packing item. Replaces the full selection, including the original bringer if omitted. Pass an empty list to clear it. To find the current selection, read owner_id and contributors in list_packing_items. Does not change sharing or recipients.',
inputSchema: {
tripId: idSchema,
itemId: idSchema,
...packingSetBringersRequestSchema.shape,
},
annotations: TOOL_ANNOTATIONS_WRITE,
when: packingAddonOn,
access: { group: 'packing', mode: 'write' },
})
async setPackingItemBringers(
{ tripId, itemId, user_ids }: { tripId: number; itemId: number; user_ids: number[] },
ctx: McpContext,
) {
const item = await this.writes.setBringers(
tripId,
itemId,
user_ids,
await this.guards.tripWriter(tripId, ctx.userId),
);
return ok({ item });
}
// --- PACKING ADVANCED ---
@Tool({
+84 -55
View File
@@ -318,48 +318,54 @@ export class PackingService {
ifMatch?: string,
actingUserId?: number,
): Promise<unknown | UpdateConflict | null> {
// Was a trip-scoped lookup, which let any member with packing_edit write to
// another member's restricted item (and read it back off the response).
const item = await this.itemsRepo.findVisibleInTrip(id, tripId, actingUserId);
if (!item) return null;
// Bringer changes and privacy changes share the same write transaction.
return this.uow.transactional(async () => {
// Was a trip-scoped lookup, which let any member with packing_edit write to
// another member's restricted item (and read it back off the response).
const item = await this.itemsRepo.findVisibleInTrip(id, tripId, actingUserId);
if (!item) return null;
// Optimistic concurrency (#1135): reject a stale offline overwrite. Absent
// token => unconditional update (back-compat with older clients).
if (ifMatch !== undefined && item.updated_at != null && String(item.updated_at) !== ifMatch) {
return { conflict: true, server: await this.itemsRepo.findById(id) };
}
// Optimistic concurrency (#1135): reject a stale offline overwrite. Absent
// token => unconditional update (back-compat with older clients).
if (ifMatch !== undefined && item.updated_at != null && String(item.updated_at) !== ifMatch) {
return { conflict: true, server: await this.itemsRepo.findById(id) };
}
// A non-null bag about to be bound must belong to this trip (#2154) — the
// FK alone let any member point an item at another trip's bag.
if (bodyKeys.includes('bag_id') && data.bag_id != null && !(await this.bagInTrip(tripId, data.bag_id))) {
return { invalidBag: true } as const;
}
// A non-null bag about to be bound must belong to this trip (#2154) — the
// FK alone let any member point an item at another trip's bag.
if (bodyKeys.includes('bag_id') && data.bag_id != null && !(await this.bagInTrip(tripId, data.bag_id))) {
return { invalidBag: true } as const;
}
// Privatizing an unowned (legacy) item stamps the acting user as its owner so
// the visibility filter still has someone to match (#858).
const claimOwner = bodyKeys.includes('is_private') && !!data.is_private && item.owner_id == null && actingUserId != null;
// Privatizing an unowned (legacy) item stamps the acting user as its owner so
// the visibility filter still has someone to match (#858).
const claimOwner = bodyKeys.includes('is_private') && !!data.is_private && item.owner_id == null && actingUserId != null;
// The box and the packed count (#2296) are settled together, so a count
// that reaches the quantity ticks the item and a tick clears the count.
const quantity = bodyKeys.includes('quantity') ? Math.max(1, Math.min(999, Number(data.quantity) || 1)) : (item.quantity || 1);
const packed = resolvePackedState(
{ checked: item.checked ? 1 : 0, packed_quantity: item.packed_quantity ?? null },
{ bodyKeys, checked: data.checked, packed_quantity: data.packed_quantity, quantity },
);
// The box and the packed count (#2296) are settled together, so a count
// that reaches the quantity ticks the item and a tick clears the count.
const quantity = bodyKeys.includes('quantity') ? Math.max(1, Math.min(999, Number(data.quantity) || 1)) : (item.quantity || 1);
const packed = resolvePackedState(
{ checked: item.checked ? 1 : 0, packed_quantity: item.packed_quantity ?? null },
{ bodyKeys, checked: data.checked, packed_quantity: data.packed_quantity, quantity },
);
await this.itemsRepo.update(id, {
name: [!!data.name, data.name || null],
checked: [true, packed.checked],
packed_quantity: [true, packed.packed_quantity],
category: [!!data.category, data.category || null],
weight_grams: [bodyKeys.includes('weight_grams'), data.weight_grams ?? null],
bag_id: [bodyKeys.includes('bag_id'), data.bag_id ?? null],
quantity: [true, quantity],
is_private: [bodyKeys.includes('is_private'), data.is_private ? 1 : 0],
owner_id: [claimOwner, actingUserId ?? null],
await this.itemsRepo.update(id, {
name: [!!data.name, data.name || null],
checked: [true, packed.checked],
packed_quantity: [true, packed.packed_quantity],
category: [!!data.category, data.category || null],
weight_grams: [bodyKeys.includes('weight_grams'), data.weight_grams ?? null],
bag_id: [bodyKeys.includes('bag_id'), data.bag_id ?? null],
quantity: [true, quantity],
is_private: [bodyKeys.includes('is_private'), data.is_private ? 1 : 0],
owner_id: [claimOwner, actingUserId ?? null],
});
if (item.is_private === 0 && bodyKeys.includes('is_private') && data.is_private) {
await this.contributorsRepo.deleteForItem(id);
}
return (await this.enrichItems([await this.itemsRepo.findById(id)]))[0];
});
return (await this.enrichItems([await this.itemsRepo.findById(id)]))[0];
}
// ── Three-tier sharing (#858): recipients, contributors, clone ───────────────
@@ -376,12 +382,12 @@ export class PackingService {
visibility: PackingVisibility,
recipientIds: number[],
) {
const item = await this.itemsRepo.findVisibleInTrip(id, tripId, actingUserId);
if (!item) return null;
// The owner controls sharing; an unowned legacy item is claimed by the actor.
if (item.owner_id != null && item.owner_id !== actingUserId) return { forbidden: true as const };
return this.uow.transactional(async () => {
const item = await this.itemsRepo.findVisibleInTrip(id, tripId, actingUserId);
if (!item) return null;
// The owner controls sharing; an unowned legacy item is claimed by the actor.
if (item.owner_id != null && item.owner_id !== actingUserId) return { forbidden: true as const };
await this.uow.transactional(async () => {
// COALESCE(owner_id, ?) at the SQL level kept the existing owner if one was
// set; passing the claim only when the pre-image had none reproduces that
// exactly (nothing else touches owner_id inside this same transaction).
@@ -396,8 +402,8 @@ export class PackingService {
}
// Leaving the Common tier drops any co-contributors (they only apply to Common).
if (visibility !== 'common') await this.contributorsRepo.deleteForItem(id);
return (await this.enrichItems([await this.itemsRepo.findById(id)]))[0];
});
return (await this.enrichItems([await this.itemsRepo.findById(id)]))[0];
}
/**
@@ -407,26 +413,49 @@ export class PackingService {
* with no pre-ORM Express precedent — #858 landed post-migration).
*/
async addContributor(tripId: string | number, id: number, userId: number, actingUserId: number = userId) {
const item = await this.itemsRepo.findVisibleInTrip(id, tripId, actingUserId);
if (!item || item.is_private !== 0) return null; // co-contribution is a Common-list concept
if (item.owner_id === userId) return null; // the bringer is already covering it
// Putting someone else down as a bringer (#3098) only reaches people on the trip.
if (userId !== actingUserId && !(await this.tripRosterIds(tripId)).has(userId)) return null;
await this.contributorsRepo.insertIgnore(id, userId);
return (await this.enrichItems([await this.itemsRepo.findById(id)]))[0];
return this.uow.transactional(async () => {
const item = await this.itemsRepo.findVisibleInTrip(id, tripId, actingUserId);
if (!item || item.is_private !== 0) return null; // co-contribution is a Common-list concept
if (item.owner_id === userId) return null; // the bringer is already covering it
// Putting someone else down as a bringer (#3098) only reaches people on the trip.
if (userId !== actingUserId && !(await this.tripRosterIds(tripId)).has(userId)) return null;
await this.contributorsRepo.insertIgnore(id, userId);
return (await this.enrichItems([await this.itemsRepo.findById(id)]))[0];
});
}
/** `id: number` — same Plan 4 Task 8b (U6) narrowing as {@link addContributor}; `userId` here is the target being removed, not the acting viewer (`PackingController.removeContributor` now parses both `:id`/`:userId` via `toRowId` instead of a bare `Number.parseInt`). */
async removeContributor(tripId: string | number, id: number, userId: number, actingUserId: number = userId) {
const item = await this.itemsRepo.findVisibleInTrip(id, tripId, actingUserId);
if (!item) return null;
// On a Common item the owner is its first bringer, so taking them off the
// item has to clear the owner too; otherwise their avatar stuck for good (#3098).
await this.uow.transactional(async () => {
return this.uow.transactional(async () => {
const item = await this.itemsRepo.findVisibleInTrip(id, tripId, actingUserId);
if (!item) return null;
// On a Common item the owner is its first bringer, so taking them off the
// item has to clear the owner too; otherwise their avatar stuck for good (#3098).
if (item.is_private === 0 && item.owner_id === userId) await this.itemsRepo.clearOwner(id);
await this.contributorsRepo.deleteOne(id, userId);
return (await this.enrichItems([await this.itemsRepo.findById(id)]))[0];
});
}
/** Replace the bringers of a Common item without changing who may see it. */
async setBringers(tripId: string | number, itemId: number, userIds: number[], actingUserId: number) {
return this.uow.transactional(async () => {
const item = await this.itemsRepo.findVisibleInTrip(itemId, tripId, actingUserId);
if (!item || item.is_private !== 0) return null;
const roster = await this.tripRosterIds(tripId);
if (userIds.some((id) => !roster.has(id))) {
throw new DomainError(400, 'Every bringer must be a trip member');
}
// The Common item's owner is its first bringer in the UI. When omitted,
// release them the same way as the single-person removal on REST.
const selected = new Set(userIds);
const contributors = [...selected].filter((id) => id !== item.owner_id);
if (item.owner_id != null && !selected.has(item.owner_id)) await this.itemsRepo.clearOwner(itemId);
await this.contributorsRepo.deleteExcept(itemId, contributors);
await this.contributorsRepo.insertManyIgnore(itemId, contributors);
return (await this.enrichItems([await this.itemsRepo.findById(itemId)]))[0];
});
return (await this.enrichItems([await this.itemsRepo.findById(id)]))[0];
}
/** True when the bag exists AND belongs to the trip — the referenced-id rule
+20
View File
@@ -119,6 +119,26 @@ describe('Atlas e2e (real auth guard + real service + temp SQLite)', () => {
await deleteRows(orm, VisitedCountries, { user: userId });
});
it('returns mark provenance only when requested for offline use', async () => {
await markCountryVisited(orm, userId, 'JP');
await request(server)
.post('/api/addons/atlas/region/DE-BY/mark')
.set('Cookie', sessionCookie(userId))
.send({ name: 'Bayern', country_code: 'DE' })
.expect(200);
const res = await request(server).get('/api/addons/atlas/stats?offline=1').set('Cookie', sessionCookie(userId));
expect(res.status).toBe(200);
expect(res.body.countries).toEqual(
expect.arrayContaining([
expect.objectContaining({ code: 'JP', offline: { directMark: true, placeStatus: null } }),
expect.objectContaining({ code: 'DE', offline: { directMark: false, placeStatus: null } }),
]),
);
await deleteRows(orm, VisitedRegions, { user: userId });
await deleteRows(orm, VisitedCountries, { user: userId });
});
it('200 (not 201) on POST country mark, with upper-cased code written to the db', async () => {
const res = await request(server).post('/api/addons/atlas/country/de/mark').set('Cookie', sessionCookie(userId));
expect(res.status).toBe(200);
+44 -1
View File
@@ -409,7 +409,8 @@ describe('following a link by email', () => {
});
describe('the daily digest', () => {
const runDigest = () => withRequestContext(orm, () => app.get(JourneyDigestService, { strict: false }).run());
const runDigest = (now?: Date) =>
withRequestContext(orm, () => app.get(JourneyDigestService, { strict: false }).run(now));
it('JSOCIAL-E2E-030: the people hear of new entries, followers get one mail, nothing is told twice', async () => {
const send = mailWorks();
const { owner, editor, viewer, journey } = await journeyWithPeople();
@@ -470,4 +471,46 @@ describe('the daily digest', () => {
expect(mail.body).not.toContain('Furnas');
expect(mail.cta.href).toContain(`/public/journey/${token}`);
});
it('JSOCIAL-E2E-032: retries waiting mail without repeating successful or in-app notifications', async () => {
const { owner, editor, viewer, journey } = await journeyWithPeople();
const send = mailWorks();
const token = await share(journey.id, owner.id, { allow_subscriptions: true });
const addresses = ['successful@example.com', 'retry@example.com'];
await forEachInOrder(addresses, async (email) => {
await request(server).post(`/api/public/journey/${token}/subscribe`).send({ email }).expect(200);
const follower = must(await findRow(orm, JourneyShareSubscribers, { email }));
await request(server)
.post('/api/public/journey-subscriptions/confirm')
.send({ token: follower.confirm_token })
.expect(200);
});
send.mockClear();
const config = vi.spyOn(mailer, 'isSmtpConfigured').mockResolvedValue(false);
const entry = await makeJourneyEntry(orm, journey.id, editor.id, { title: 'After the storm' });
expect(await runDigest(new Date('2030-01-01T19:00:00Z'))).toMatchObject({ journeys: 1, notified: 2, mailed: 0 });
expect(send).not.toHaveBeenCalled();
expect((await findRow(orm, JourneyEntries, { id: entry.id }))?.announced).toBe(1);
config.mockResolvedValue(true);
send.mockImplementation(async (to) => to === addresses[0]);
expect(await runDigest(new Date('2030-01-02T19:00:00Z'))).toMatchObject({ journeys: 0, notified: 0, mailed: 1 });
expect(send.mock.calls.map(([to]) => to)).toEqual(addresses);
send.mockClear().mockResolvedValue(true);
expect(await runDigest(new Date('2030-01-03T19:00:00Z'))).toMatchObject({ journeys: 0, notified: 0, mailed: 1 });
expect(send).toHaveBeenCalledTimes(1);
const [to, mail] = must(send.mock.calls[0]);
expect(to).toBe(addresses[1]);
expect(mail.body).toContain('After the storm');
send.mockClear();
expect(await runDigest(new Date('2030-01-04T19:00:00Z'))).toMatchObject({ journeys: 0, notified: 0, mailed: 0 });
expect(send).not.toHaveBeenCalled();
await notifications.settled();
expect(
await countRows(orm, Notifications, { recipient: viewer.id, title_key: 'notif.journey_entry_published.title' }),
).toBe(1);
});
});
@@ -178,6 +178,21 @@ export const money: CaseGroup = {
},
expect: ['packing:deleted', { event: 'packing:created', only: 'viewers' }],
},
{
tool: 'set_packing_item_bringers',
needs: ['packingItem', 'member'],
args: (s) => ({
tripId: s.trip.id,
itemId: s.packingItem.id,
user_ids: s.packingItem.owner_id ? [s.packingItem.owner_id, s.member.id] : [s.member.id],
}),
rest: {
method: 'post',
path: (s) => packing(s, '/' + s.packingItem.id + '/contributors'),
body: (s) => ({ user_id: s.member.id }),
},
expect: ['packing:updated'],
},
{
// The route used to save the order and tell nobody (G14).
tool: 'reorder_packing_items',
@@ -131,6 +131,7 @@ const UNNUMBERED = [
'Migration20200101046630_a_journey_gathers_comments_and_followers',
'Migration20200101046640_bahrain_flights_keep_bahrain_time',
'Migration20200101046650_trips_can_carry_custom_tags',
'Migration20200101046660_a_journey_keeps_unsent_digests',
];
// The last step the positional runner ever had; planLegacyBaseline refuses a
// schema_version past it.
@@ -74,19 +74,26 @@ describe('JourneyShareSubscribersRepository', () => {
expect(await subscribers.findByConfirmToken('nothing-like-it-0000')).toBeUndefined();
});
it('JSUB-REPO-002: only confirmed addresses not mailed since the cutoff are due, and marking them stamps them', async () => {
const { link } = await linkOf();
await makeJourneySubscriber(t, link.id);
it('JSUB-REPO-002: only confirmed addresses with pending entries and no recent mail are due', async () => {
const { journey, link } = await linkOf();
await makeJourneySubscriber(t, link.id, { pending_digest_entries: '[11]' });
await makeJourneySubscriber(t, link.id, { confirmed_at: '2026-11-01 08:00:00' });
const fresh = await makeJourneySubscriber(t, link.id, { confirmed_at: '2026-11-01 08:00:00' });
await subscribers.setPendingDigest(fresh.id, '[11]');
const mailedLong = await makeJourneySubscriber(t, link.id, {
confirmed_at: '2026-11-01 08:00:00',
last_notified_at: '2026-11-28 08:00:00',
pending_digest_entries: '[11]',
});
await makeJourneySubscriber(t, link.id, {
confirmed_at: '2026-11-01 08:00:00',
last_notified_at: '2026-11-30 07:00:00',
pending_digest_entries: '[11]',
});
const other = await linkOf();
await makeJourneySubscriber(t, other.link.id, { confirmed_at: '2026-11-01 08:00:00' });
expect(await subscribers.listDueJourneyIds('2026-11-29 12:00:00')).toEqual([journey.id]);
const due = await subscribers.listDue(link.id, '2026-11-29 12:00:00');
expect(due.map((s) => s.id)).toEqual([fresh.id, mailedLong.id]);
@@ -95,7 +102,9 @@ describe('JourneyShareSubscribersRepository', () => {
t.clear();
expect(await findRow(t, JourneyShareSubscribers, { id: fresh.id })).toMatchObject({
last_notified_at: '2026-11-30 12:00:00',
pending_digest_entries: null,
});
expect((await subscribers.listDue(link.id, '2026-12-02 12:00:00')).map((s) => s.id)).not.toContain(fresh.id);
});
it('JSUB-REPO-003: an unsubscribe link and the owner each remove one address, and only on its own link', async () => {
@@ -134,7 +143,7 @@ describe('JourneyEntriesRepository, the entries a digest speaks of', () => {
const { user, journey } = await linkOf();
const published = await makeJourneyEntry(t, journey.id, user.id, { title: 'Alfama', entry_date: '2026-11-02' });
const earlier = await makeJourneyEntry(t, journey.id, user.id, { title: 'Belém', entry_date: '2026-11-01' });
await makeJourneyEntry(t, journey.id, user.id, { is_draft: 1 });
const draft = await makeJourneyEntry(t, journey.id, user.id, { is_draft: 1 });
await makeJourneyEntry(t, journey.id, user.id, { type: 'skeleton' });
await makeJourneyEntry(t, journey.id, user.id, { dismissed: 1 });
await makeJourneyEntry(t, journey.id, user.id, { announced: 1 });
@@ -146,6 +155,16 @@ describe('JourneyEntriesRepository, the entries a digest speaks of', () => {
await entries.markAnnounced(due.map((e) => e.id));
await entries.markAnnounced([]);
const other = await linkOf();
const unrelated = await makeJourneyEntry(t, other.journey.id, other.user.id, { announced: 1 });
const pending = await entries.listPendingDigestEntries(journey.id, [
published.id,
draft.id,
earlier.id,
unrelated.id,
]);
expect(pending.map((entry) => entry.id)).toEqual([earlier.id, published.id]);
expect(await entries.listPendingDigestEntries(journey.id, [])).toEqual([]);
expect(await entries.listToAnnounce(journey.id)).toEqual([]);
expect(await entries.listJourneysToAnnounce()).toEqual([]);
});
@@ -90,6 +90,7 @@ describe('VisitedCountriesRepository: countries that came in through a region (#
expect((await findRow(t, VisitedCountries, { user: user.id, country_code: 'NO' }))?.source).toBe('region');
expect(await repo.findSource(user.id, 'NO')).toEqual({ source: 'manual' });
expect(await repo.listMarksForUser(user.id)).toEqual([{ country_code: 'NO', source: 'region' }]);
expect((await repo.listForUser(user.id)).map((r) => r.source)).toEqual(['manual']);
expect(await repo.hasOwnMark(user.id, 'NO')).toBe(false);
});
+147 -2
View File
@@ -14,6 +14,7 @@
import { ADDON_IDS } from '../../../src/addons';
import { PackingBags } from '../../../src/db/entities/PackingBags.entity';
import { PackingItems } from '../../../src/db/entities/PackingItems.entity';
import { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import { inContext } from '../../helpers/factories/context';
import {
addPackingBagMembers,
@@ -22,7 +23,7 @@ import {
makePackingItem,
} from '../../helpers/factories/packing';
import { countRows, findRow, insertRow, updateRows } from '../../helpers/factories/rows';
import { setAddonEnabled } from '../../helpers/factories/settings';
import { setAddonEnabled, setAppSetting, setTripAddon } from '../../helpers/factories/settings';
import { addTripMember, makeTrip } from '../../helpers/factories/trips';
import { makeUser } from '../../helpers/factories/users';
import { FakeRealtimeService } from '../../helpers/fake-realtime';
@@ -935,6 +936,149 @@ describe('Tool: list_packing_items', () => {
});
});
describe('Tool: set_packing_item_bringers', () => {
function setBringers(h: McpHarness, tripId: number, itemId: number, userIds: number[]) {
return h.client.callTool({
name: 'set_packing_item_bringers',
arguments: { tripId, itemId, user_ids: userIds },
});
}
it('replaces the full selection and keeps the Common item and its other fields', async () => {
const { user: owner } = await makeUser(orm);
const { user: member } = await makeUser(orm);
const trip = await makeTrip(orm, owner.id);
await addTripMember(orm, trip.id, member.id, owner.id);
const item = await makePackingItem(orm, trip.id, { owner: owner.id, name: 'Tent', quantity: 2 });
await withHarness(member.id, async (h) => {
const both = parseToolResult(await setBringers(h, trip.id, item.id, [owner.id, member.id, member.id]));
expect(both).toMatchObject({
item: { owner_id: owner.id, contributors: [{ user_id: member.id }] },
});
expect(broadcastMock).toHaveBeenLastCalledWith(
trip.id,
'packing:updated',
expect.objectContaining({ item: expect.objectContaining({ id: item.id }) }),
);
const one = parseToolResult(await setBringers(h, trip.id, item.id, [member.id]));
expect(one).toMatchObject({
item: {
name: 'Tent',
quantity: 2,
is_private: 0,
owner_id: null,
contributors: [{ user_id: member.id }],
recipients: [],
},
});
const none = parseToolResult(await setBringers(h, trip.id, item.id, []));
expect(none).toMatchObject({ item: { owner_id: null, contributors: [] } });
});
});
it('serializes competing replacements and removes bringers when the item becomes private', async () => {
const { user: owner } = await makeUser(orm);
const { user: first } = await makeUser(orm);
const { user: second } = await makeUser(orm);
const trip = await makeTrip(orm, owner.id);
await addTripMember(orm, trip.id, first.id, owner.id);
await addTripMember(orm, trip.id, second.id, owner.id);
const item = await makePackingItem(orm, trip.id);
await withHarness(owner.id, async (h) => {
const replacements = await Promise.all([
setBringers(h, trip.id, item.id, [first.id]),
setBringers(h, trip.id, item.id, [second.id]),
]);
for (const result of replacements) expect(result.isError).not.toBe(true);
expect(parseToolResult(replacements[0])).toMatchObject({ item: { contributors: [{ user_id: first.id }] } });
expect(parseToolResult(replacements[1])).toMatchObject({ item: { contributors: [{ user_id: second.id }] } });
const restricted = await h.client.callTool({
name: 'update_packing_item',
arguments: { tripId: trip.id, itemId: item.id, is_private: true },
});
expect(parseToolResult(restricted)).toMatchObject({ item: { is_private: 1, contributors: [] } });
expect(broadcastMock).toHaveBeenLastCalledWith(
trip.id,
'packing:created',
expect.objectContaining({ item: expect.objectContaining({ is_private: 1 }) }),
undefined,
owner.id,
);
});
});
it('validates every bringer before changing the current selection', async () => {
const { user: owner } = await makeUser(orm);
const { user: outsider } = await makeUser(orm);
const trip = await makeTrip(orm, owner.id);
const item = await makePackingItem(orm, trip.id, { owner: owner.id });
await withHarness(owner.id, async (h) => {
const result = await setBringers(h, trip.id, item.id, [outsider.id]);
expect(result.isError).toBe(true);
expect(errorText(result)).toContain('Every bringer must be a trip member');
});
expect((await itemRow(item.id)).owner_id).toBe(owner.id);
expect(broadcastMock).not.toHaveBeenCalled();
});
it('refuses private items and items on a different trip', async () => {
const { user } = await makeUser(orm);
const trip = await makeTrip(orm, user.id);
const other = await makeTrip(orm, user.id);
const personal = await makePackingItem(orm, trip.id, { is_private: 1, owner: user.id });
const outsideTrip = await makePackingItem(orm, other.id, { owner: user.id });
await withHarness(user.id, async (h) => {
expect((await setBringers(h, trip.id, personal.id, [])).isError).toBe(true);
expect((await setBringers(h, trip.id, outsideTrip.id, [])).isError).toBe(true);
});
expect(broadcastMock).not.toHaveBeenCalled();
});
it('requires the configured packing edit permission', async () => {
const { user: owner } = await makeUser(orm);
const { user: member } = await makeUser(orm);
const trip = await makeTrip(orm, owner.id);
await addTripMember(orm, trip.id, member.id, owner.id);
const item = await makePackingItem(orm, trip.id, { owner: owner.id });
const permissions = (await bootTestApp(realtime)).get(PermissionsService);
await setAppSetting(orm, 'perm_packing_edit', 'trip_owner');
await permissions.invalidatePermissionsCache();
try {
await withHarness(member.id, async (h) => {
const result = await setBringers(h, trip.id, item.id, [member.id]);
expect(result.isError).toBe(true);
expect(errorText(result)).toContain('You do not have permission');
});
expect(broadcastMock).not.toHaveBeenCalled();
} finally {
await setAppSetting(orm, 'perm_packing_edit', 'trip_member');
await permissions.invalidatePermissionsCache();
}
});
it('respects the target trip addon switch', async () => {
const { user } = await makeUser(orm);
const trip = await makeTrip(orm, user.id);
const item = await makePackingItem(orm, trip.id, { owner: user.id });
await setTripAddon(orm, trip.id, ADDON_IDS.PACKING, false);
await withHarness(user.id, async (h) => {
const result = await setBringers(h, trip.id, item.id, []);
expect(result.isError).toBe(true);
expect(errorText(result)).toMatch(/Packing addon is not enabled/i);
});
expect(broadcastMock).not.toHaveBeenCalled();
});
});
// ---------------------------------------------------------------------------
// Scope gating (packing read/write, registration-time)
// ---------------------------------------------------------------------------
@@ -962,6 +1106,7 @@ describe('Packing tools — scope gating', () => {
'delete_packing_template',
'bulk_import_packing',
'set_packing_item_sharing',
'set_packing_item_bringers',
];
async function listToolNames(userId: number, scopes: string[] | null): Promise<string[]> {
@@ -973,7 +1118,7 @@ describe('Packing tools — scope gating', () => {
}
}
it('registers all nineteen tools with null scopes (full access)', async () => {
it('registers all packing tools with null scopes (full access)', async () => {
const { user } = await makeUser(orm);
const names = await listToolNames(user.id, null);
for (const tool of [...READ_TOOLS, ...WRITE_TOOLS]) expect(names).toContain(tool);
@@ -72,6 +72,7 @@ describe('walkMail: the envelope and the body', () => {
'Authentication-Results: relay.example; dkim=fail',
'Delivered-To: in+token@trek.example',
'X-Original-To: in+token@trek.example',
'x-forwarded-to: Forwarded Recipient <in+token@trek.example>',
'From: =?utf-8?B?QW5hIE3DvGxsZXI=?= <ana@example.org>',
'To: in+token@trek.example',
'Cc: ben@example.org',
@@ -96,6 +97,7 @@ describe('walkMail: the envelope and the body', () => {
messageId: '<abc@example.org>',
deliveredTo: 'in+token@trek.example',
xOriginalTo: 'in+token@trek.example',
xForwardedTo: 'Forwarded Recipient <in+token@trek.example>',
listUnsubscribe: '<https://airline.example/unsubscribe>',
precedence: 'bulk',
autoSubmitted: 'auto-generated',
@@ -112,6 +114,7 @@ describe('walkMail: the envelope and the body', () => {
const walked = walk(mail('From: a@example.org', 'Content-Type: text/plain', '', 'Hotel', ''));
expect(walked.subject).toBeNull();
expect(walked.envelope.to).toBeNull();
expect(walked.envelope.xForwardedTo).toBeNull();
expect(walked.envelope.authenticationResults).toBeNull();
});
});
@@ -5,7 +5,7 @@
* newest mail IMAP always names, makes the processed folder, moves by uid and
* says goodbye even over a broken connection.
*/
import { MailIngestImapClient } from '../../../../src/nest/mail-ingest/mail-ingest-imap.client';
import { describeImapFailure, MailIngestImapClient } from '../../../../src/nest/mail-ingest/mail-ingest-imap.client';
import { SsrfBlockedError } from '../../../../src/utils/ssrfGuard';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -16,7 +16,8 @@ const { checkSsrf, flow, ImapFlow } = vi.hoisted(() => {
mailboxOpen: vi.fn(async () => ({ uidValidity: 77n, exists: 3 })),
fetch: vi.fn(),
fetchOne: vi.fn(),
mailboxCreate: vi.fn(async () => ({ path: 'TREK.processed', created: false })),
status: vi.fn(async (parts: string[]): Promise<{ path: string } | false> => ({ path: parts.join('.') })),
mailboxCreate: vi.fn(async () => ({ path: 'TREK.processed', created: true })),
messageMove: vi.fn(async () => true),
logout: vi.fn(async () => undefined),
close: vi.fn(),
@@ -43,6 +44,7 @@ const CONFIG = {
} as const;
const ARRIVED = new Date('2030-01-15T10:00:00Z');
const missingFolder = () => Object.assign(new Error('Mailbox does not exist'), { code: 'NotFound' });
async function* messages(...uids: number[]) {
for (const uid of uids) yield { uid, size: uid * 10, internalDate: uid === 42 ? 'not a date' : ARRIVED };
@@ -95,6 +97,7 @@ describe('MailIngestImapClient', () => {
expect(await session.source(41)).toEqual(Buffer.from('raw'));
expect(await session.source(43)).toBeNull();
flow.status.mockRejectedValueOnce(missingFolder());
expect(await session.ensureFolder(['TREK', 'processed'])).toBe('TREK.processed');
expect(flow.mailboxCreate).toHaveBeenCalledWith(['TREK', 'processed']);
await session.move([41, 42], 'TREK.processed');
@@ -103,6 +106,53 @@ describe('MailIngestImapClient', () => {
expect(flow.messageMove).toHaveBeenCalledTimes(1);
});
it('uses the existing server path on consecutive connections without creating the folder', async () => {
flow.status
.mockResolvedValueOnce({ path: 'INBOX.TREK.processed' })
.mockResolvedValueOnce({ path: 'INBOX.TREK.processed' });
const client = new MailIngestImapClient();
const first = await client.connect(CONFIG);
expect(await first.ensureFolder(['TREK', 'processed'])).toBe('INBOX.TREK.processed');
const next = await client.connect(CONFIG);
expect(await next.ensureFolder(['TREK', 'processed'])).toBe('INBOX.TREK.processed');
expect(flow.status).toHaveBeenCalledWith(['TREK', 'processed'], { uidValidity: true });
expect(flow.mailboxCreate).not.toHaveBeenCalled();
});
it('does not create when the server could not check the folder', async () => {
flow.status.mockResolvedValueOnce(false);
const session = await new MailIngestImapClient().connect(CONFIG);
await expect(session.ensureFolder(['TREK', 'processed'])).rejects.toThrow('status of folder TREK/processed');
expect(flow.mailboxCreate).not.toHaveBeenCalled();
});
it('uses the folder if it appeared during CREATE and reports the folder if creation really failed', async () => {
const refused = Object.assign(new Error('Command failed'), { responseText: 'CREATE failed' });
const session = await new MailIngestImapClient().connect(CONFIG);
flow.status.mockRejectedValueOnce(missingFolder());
flow.mailboxCreate.mockRejectedValueOnce(refused);
expect(await session.ensureFolder(['TREK', 'processed'])).toBe('TREK.processed');
flow.status.mockRejectedValueOnce(missingFolder()).mockRejectedValueOnce(missingFolder());
flow.mailboxCreate.mockRejectedValueOnce(refused);
const reason = await session.ensureFolder(['TREK', 'processed']).catch(describeImapFailure);
expect(reason).toBe('Could not create IMAP folder TREK/processed. The IMAP server answered: CREATE failed');
});
it('creates a missing parent when the server refuses to create the child first', async () => {
const session = await new MailIngestImapClient().connect(CONFIG);
flow.status
.mockRejectedValueOnce(missingFolder())
.mockRejectedValueOnce(missingFolder())
.mockRejectedValueOnce(missingFolder());
flow.mailboxCreate
.mockRejectedValueOnce(new Error('CREATE failed'))
.mockResolvedValueOnce({ path: 'TREK', created: true });
await expect(session.ensureFolder(['TREK', 'processed'])).resolves.toBe('TREK.processed');
expect(flow.mailboxCreate.mock.calls).toEqual([[['TREK', 'processed']], [['TREK']], [['TREK', 'processed']]]);
});
it('does not ask an empty folder for a range', async () => {
flow.mailboxOpen.mockResolvedValueOnce({ uidValidity: 5n, exists: 0 });
const session = await new MailIngestImapClient().connect(CONFIG);
@@ -87,6 +87,7 @@ const session = {
open: vi.fn(),
listAfter: vi.fn(),
source: vi.fn(),
findFolder: vi.fn(async (parts: readonly string[]): Promise<string | null> => parts.join('.')),
ensureFolder: vi.fn(async (parts: readonly string[]) => parts.join('.')),
move: vi.fn(async () => undefined),
close: vi.fn(async () => undefined),
@@ -268,7 +269,11 @@ describe('the IMAP run', () => {
});
it('moves nothing with an empty box, and touches nothing unless IMAP is the transport', async () => {
session.findFolder.mockResolvedValueOnce(null);
expect(await job().tick(NOW)).toBe(0);
expect(session.findFolder).toHaveBeenCalledWith(['TREK', 'deferred']);
expect(session.open).toHaveBeenCalledExactlyOnceWith('INBOX');
expect(session.ensureFolder).not.toHaveBeenCalled();
expect(session.move).not.toHaveBeenCalled();
expect(intake.receive).not.toHaveBeenCalled();
expect(processing.runSoon).not.toHaveBeenCalled();
@@ -283,6 +288,26 @@ describe('the IMAP run', () => {
expect(imap.connect).not.toHaveBeenCalled();
});
it('leaves mail and the cursor in place when folder creation fails, and retries on the next tick', async () => {
cursor.findCursor.mockResolvedValue({ uid_validity: 9, last_uid: 40 });
session.listAfter.mockResolvedValueOnce([ref(41)]);
session.ensureFolder.mockRejectedValueOnce(
Object.assign(new Error('Command failed'), { responseText: 'CREATE failed' }),
);
expect(await job().tick(NOW)).toBe(0);
expect(cursor.recordError).toHaveBeenCalledWith('imap', 'INBOX', 'The IMAP server answered: CREATE failed');
expect(cursor.recordOk).not.toHaveBeenCalled();
expect(session.move).not.toHaveBeenCalled();
expect(cursor.releaseLease).toHaveBeenCalled();
boxes([ref(41)]);
intake.receive.mockResolvedValueOnce({ status: 'duplicate' });
expect(await job().tick(NOW)).toBe(0);
expect(session.listAfter).toHaveBeenNthCalledWith(2, 40);
expect(session.move).toHaveBeenCalledExactlyOnceWith([41], 'TREK.processed');
expect(cursor.recordOk).toHaveBeenCalledWith('imap', 'INBOX', expect.any(String), { uidValidity: 9, lastUid: 41 });
});
it('records why a run failed for the status card, and keeps the cursor where it was', async () => {
imap.connect.mockRejectedValueOnce(Object.assign(new Error('Command failed'), { authenticationFailed: true }));
expect(await job().tick(NOW)).toBe(0);
@@ -52,8 +52,8 @@ afterAll(async () => {
});
const tokenIn = (address: string) => /^trek\+([a-z2-7]+)@/.exec(address)?.[1] ?? '';
function mailTo(address: string, id: string): Buffer {
const lines = ['From: mia@example.com', `To: ${address}`, 'Subject: Booking', `Message-ID: <${id}@x>`];
function mailTo(address: string, id: string, headers: readonly string[] = []): Buffer {
const lines = ['From: mia@example.com', `To: ${address}`, 'Subject: Booking', `Message-ID: <${id}@x>`, ...headers];
return Buffer.from(`${lines.join('\r\n')}\r\n\r\nBooking ABC123`);
}
@@ -151,17 +151,17 @@ describe('a mail to several addresses', () => {
expect(await findRow(orm(), MailIngestMessages, { user: noah.id })).toBeNull();
});
it('reads on to To when the delivery header names the box without its token, as Stalwart writes it', async () => {
it('reads on to To without a delivery token and gives To priority over X-Forwarded-To', async () => {
const { user: mia } = await makeUser(orm());
const { user: noah } = await makeUser(orm());
const miaOwn = (await addresses().renewOwn(mia.id))?.address ?? '';
const noahOwn = (await addresses().renewOwn(noah.id))?.address ?? '';
const box = miaOwn.replace(/\+[^@]+@/, '@');
const headers = [`Delivered-To: ${box}`, `To: <${miaOwn}>`, 'From: x@example.com'];
const raw = Buffer.from(
`${headers.join('\r\n')}\r\nSubject: WG: Booking\r\nMessage-ID: <fwd@x>\r\n\r\nBooking ABC123`,
);
const raw = mailTo(`<${miaOwn}>`, 'fwd', [`Delivered-To: ${box}`, `X-Forwarded-To: ${noahOwn}`]);
expect(await t.get(MailIngestIntakeService).receive(raw, 'imap')).toEqual({ status: 'accepted' });
expect(await findRow(orm(), MailIngestMessages, { user: mia.id })).not.toBeNull();
expect(await findRow(orm(), MailIngestMessages, { user: noah.id })).toBeNull();
const nobody = Buffer.from(`Delivered-To: ${box}\r\nTo: ${box}\r\nSubject: Hi\r\nMessage-ID: <none@x>\r\n\r\nHi`);
expect(await t.get(MailIngestIntakeService).receive(nobody, 'imap')).toEqual({
@@ -169,6 +169,57 @@ describe('a mail to several addresses', () => {
reason: 'unknown_address',
});
});
it('routes IMAP mail to the trip in the topmost X-Forwarded-To when earlier headers do not match', async () => {
const { user: owner } = await makeUser(orm());
const { user: other } = await makeUser(orm());
const trip = await makeTrip(orm(), owner.id);
const tripAddress = await addresses().renewTripAddress(owner.id, trip.id);
const otherAddress = await addresses().renewOwn(other.id);
const box = 'trek@mail.example.com';
const raw = mailTo(box, 'forwarded-trip', [
`Delivered-To: ${box}`,
`X-Original-To: ${box}`,
`X-Forwarded-To: Trip <${tripAddress?.address}>`,
`X-Forwarded-To: ${otherAddress?.address}`,
]);
expect(await t.get(MailIngestIntakeService).receive(raw, 'imap')).toEqual({ status: 'accepted' });
expect(await findRow(orm(), MailIngestMessages, { user: owner.id, trip: trip.id })).not.toBeNull();
expect(await findRow(orm(), MailIngestMessages, { user: other.id })).toBeNull();
});
it('refuses empty, malformed and retired X-Forwarded-To values', async () => {
const { user } = await makeUser(orm());
const retired = await addresses().renewOwn(user.id);
const active = await addresses().renewOwn(user.id);
const box = 'trek@mail.example.com';
const intake = t.get(MailIngestIntakeService);
const samples = [
mailTo(box, 'empty', ['X-Forwarded-To:', `X-Forwarded-To: ${active?.address}`]),
mailTo(box, 'malformed', [`X-Forwarded-To: <${active?.address.split('@')[0]}>`]),
mailTo(box, 'retired', [`X-Forwarded-To: ${retired?.address}`]),
];
const results = await Promise.all(samples.map((raw) => intake.receive(raw, 'imap')));
const refused = { status: 'refused', reason: 'unknown_address' };
expect(results).toEqual([refused, refused, refused]);
expect(await countRows(orm(), MailIngestMessages, {})).toBe(0);
});
it('uses X-Forwarded-To only for IMAP without an envelope recipient', async () => {
const { user } = await makeUser(orm());
const own = await addresses().renewOwn(user.id);
const box = 'trek@mail.example.com';
const raw = mailTo(box, 'forwarded-imap-only', [`X-Forwarded-To: ${own?.address}`]);
const intake = t.get(MailIngestIntakeService);
const refused = { status: 'refused', reason: 'unknown_address' };
expect(await intake.receive(raw, 'webhook')).toEqual(refused);
expect(await intake.receive(raw, 'cloud')).toEqual(refused);
expect(await intake.receive(raw, 'imap', [box])).toEqual(refused);
expect(await countRows(orm(), MailIngestMessages, {})).toBe(0);
});
});
describe('a trip address', () => {
@@ -434,6 +434,19 @@ describe('PackingController (parity with the legacy /api/trips/:tripId/packing r
});
describe('sharing, contributors, clone (#858 three-tier)', () => {
it('sends a restricted contributor update only to the item viewers', async () => {
const item = { id: 9, is_private: 1, owner_id: 1, recipients: [{ user_id: 2 }] };
const removeContributor = vi.fn().mockResolvedValue(item);
const broadcast = vi.fn();
const broadcastToViewers = vi.fn();
const svc = makeService({ removeContributor, broadcast, broadcastToViewers });
expect(await new PackingController(svc).removeContributor(user, '5', '9', '1', 'sock')).toEqual({ item });
expect(broadcast).not.toHaveBeenCalled();
expect(broadcastToViewers).toHaveBeenCalledOnce();
expect(broadcastToViewers).toHaveBeenCalledWith('5', 'packing:updated', { item }, [1, 2], 'sock');
});
// The invalid-visibility 400 moved into the ZodValidationPipe
// (packingSetSharingRequestSchema requires the enum) — direct method calls
// bypass parameter pipes, so that path is covered by the e2e suite and the
+1 -1
View File
@@ -111,7 +111,7 @@ const zh: NotificationLocale = {
}),
mail_booking_pending: (p) => ({
title: '待查看的转发预订',
body: `TREK 中等待你处理的转发预订:${p.count}。每一条都说明了为什么没有自动添加。`,
body: `TREK 中共有 ${p.count} 条等待你处理的转发预订。每一条都说明了为什么没有自动添加。`,
}),
mail_ingest_paused: () => ({
title: '邮件导入已暂停',
+4
View File
@@ -128,6 +128,10 @@ export const packingAddContributorRequestSchema = z.object({
});
export type PackingAddContributorRequest = z.infer<typeof packingAddContributorRequestSchema>;
export const packingSetBringersRequestSchema = z.object({
user_ids: z.array(idSchema).describe('User IDs of the trip members who bring this item'),
});
export const packingUpdateItemRequestSchema = z.object({
name: z.string().optional(),
// The legacy route accepted both boolean and 0/1 for checked — both stay valid.
+1 -1
View File
@@ -67,7 +67,7 @@ Each person's token is 24 random characters.
TREK reads one mailbox every two minutes. Point a catch-all, or a mailbox with sub-addressing (`trek+anything@`), at it and use the matching address template. Read mails move to the folder `TREK/processed` and are never deleted, so anyone with access to the mailbox can read them. A mail TREK cannot take for now, because its address took its 50 mails of the day or its person has 200 bookings waiting, moves to `TREK/deferred` and is offered again on every run for three days; after that it moves to `TREK/processed` as well.
TREK files a mail under the address in the topmost `Delivered-To` header, else the topmost `X-Original-To`, which the receiving server adds, else `To`. A header that names the mailbox without its `+` part (Stalwart writes `Delivered-To` that way) names no address, so TREK reads on to the next. A mail addressed to several people's addresses reaches each of them.
TREK checks the topmost `Delivered-To`, then the topmost `X-Original-To`, then `To`, and finally the topmost `X-Forwarded-To`. It uses the first header that names an active TREK address. If `Delivered-To` names the mailbox without its `+` part (as it does on Stalwart), TREK checks the next header. A `To` header that names several active TREK addresses reaches each of them.
| Field | Default |
|---|---|
+3 -2
View File
@@ -318,7 +318,7 @@ randomly generated password that is printed to the server log. Once any user exi
## AI Assistant
The AI Assistant addon has no environment variables for its provider. The AI connection (provider, API key or sign-in) is set up inside TREK, and its secrets are encrypted with `ENCRYPTION_KEY`. `LLM_TIMEOUT_MS` and `LLM_MAX_OUTPUT_TOKENS` under [Booking Import](#booking-import-kde-itinerary) bound the AI calls.
Set up the AI connection (provider, API key or sign-in) inside TREK. Its secrets are encrypted with `ENCRYPTION_KEY`. `OPENROUTER_PROVIDER` optionally fixes the upstream provider for an OpenRouter connection. See [Advanced / Tuning](#advanced--tuning) for the AI call limits.
---
@@ -366,7 +366,7 @@ both come back empty. `LOG_LEVEL=debug` additionally passes the extractor's raw
the Reservations panel is hidden only when **neither** extractor is available — an instance running the AI Parsing
addon still offers it with `bookingImport: false`.
Booking import can also fall back to an AI model for documents KDE Itinerary can't read. That feature (the **AI Parsing** addon) is configured in the UI; the only environment variables it reads are `LLM_TIMEOUT_MS` and `LLM_MAX_OUTPUT_TOKENS` below. See [AI-Booking-Import](AI-Booking-Import).
Booking import can also fall back to an AI model for documents KDE Itinerary can't read. Configure the **AI Parsing** addon in the UI. The limits and the optional OpenRouter provider are listed under [Advanced / Tuning](#advanced--tuning). See [AI-Booking-Import](AI-Booking-Import).
---
@@ -563,6 +563,7 @@ next key rotation or admin reset would quietly switch the file back to WAL.
| `OVERPASS_TIMEOUT_MS` | Per-endpoint timeout (in milliseconds) for Overpass POI requests. Endpoints race in parallel and one that hasn't answered within this window is abandoned so a faster mirror can win. The query itself gives Overpass 20 seconds of work, so a lower value hangs up on answers that were still coming; that is why the default rose from `12000` in 4.3.0. Drop any lower value you set by hand, and raise it only for a slow self-hosted Overpass instance. The Tours search along a tour does not read it: it gives Overpass 10 seconds of work and waits 12, because someone is waiting for the list. Invalid values abort startup. | `25000` |
| `LLM_TIMEOUT_MS` | How long (in milliseconds) one AI-parsing call may take before it is abandoned. One ceiling for every provider, applied to the abort signal and to the underlying HTTP client alike. The default is generous so heavier parsing work fits without a code change; lower it if you use a cloud provider and would rather fail fast. Invalid values abort startup. | `900000` (15 min) |
| `LLM_MAX_OUTPUT_TOKENS` | The longest answer (in tokens) one AI-parsing call may ask the model for, sent to every provider. A document with many bookings needs a long answer; when the model hits the cap the import says so and names this variable. Raise it for such documents, but keep prompt plus cap inside the context your model has, or the server refuses the request. Unset keeps each provider's own cap. A whole number from 256 to 1000000, anything else aborts startup. | `4096` (OpenAI-compatible), `8192` (Anthropic) |
| `OPENROUTER_PROVIDER` | Optional upstream provider slug for OpenRouter assistant chat and booking extraction. Leave unset to keep OpenRouter's routing and fallbacks. | unset |
| `GOOGLE_LIST_DATA_BASE` | HTTP(S) base URL of a list-data service. A pasted URL starting with this base is fetched and parsed directly; the URL's origin must also match the base so a lookalike host cannot bypass the URL guard. A failed direct import reports an error without falling back to Google. Unset or a nonmatching URL uses the original Google flow. | Unset |
> **Routing is mostly not set here.** With the TREK services, their Valhalla calculates every route TREK draws and OSRM takes over a day it cannot answer; `TREK_VALHALLA_URL` only points at another copy of it. Engines of your own are set by an admin under **Admin → User Defaults** as **Routing service**, **Own routing engine** and **Own Valhalla instance**, and they take effect after a restart. `OVERPASS_URL` and `OVERPASS_TIMEOUT_MS` above also apply to the road trip's search along the route.
+5 -1
View File
@@ -16,6 +16,7 @@ Requires `packing:read` or `packing:write` scope. The Packing addon is listed as
| `create_packing_item` | Add an item to the packing checklist with optional category. |
| `update_packing_item` | Rename an item, change its category, or count how many of it are already packed. |
| `set_packing_item_sharing` | Move an item between the three sharing tiers: `common` puts it in the pool the whole trip packs from, `personal` keeps it to its owner, `shared` covers the trip members in `recipient_ids`. Only the item's owner may change this. |
| `set_packing_item_bringers` | Replace who brings a Common packing item with `user_ids`, including the original bringer in that list if they should stay. An empty list clears all bringers. Read the item's `owner_id` and `contributors` with `list_packing_items` for its current bringers. Sharing and recipients stay as they are. |
| `toggle_packing_item` | Check or uncheck a packing item. |
| `delete_packing_item` | Remove a packing item. |
| `reorder_packing_items` | Set the display order of packing items within a trip. |
@@ -54,8 +55,11 @@ Requires `atlas:read` or `atlas:write` scope.
| Tool | Description |
|---|---|
| `mark_country_visited` | Mark a country as visited using its ISO 3166-1 alpha-2 code (e.g. `"FR"`, `"JP"`). The answer's `after` says where the country stands now and how many countries count as visited. |
| `unmark_country_visited` | Remove a country from your visited list. The answer's `after` says where the country stands now (a country your trips put on the map stays) and how many countries count as visited. |
| `unmark_country_visited` | Remove a country from your visited list. The answer's `after` says where the country stands now (the country is hidden even when derived from a trip) and how many countries count as visited. |
| `get_atlas_stats` | Get atlas statistics — visited country counts, region counts, and continent breakdown. |
| `list_atlas_flight_routes` | List your flown routes, with both directions counted together, and airport counts and flight totals. |
| `list_atlas_badges` | List your Atlas badges with tier, progress and the year earned when available. |
| `list_atlas_travellers` | Compare selected users on the same instance by visited countries, region and continent counts, flight distance and earned badges. The comparison is on by default. Users can hide their profiles, and an admin can disable the comparison for the instance. |
| `list_visited_regions` | List all manually visited sub-country regions for the current user. |
| `locate_atlas_region` | Resolve a coordinate to the country and region codes the Atlas map can highlight, which is where the pair `mark_region_visited` expects comes from. A point outside every bundled polygon answers with `null` fields rather than an error. For a postal address use `reverse_geocode` instead. |
| `mark_region_visited` | Mark a sub-country region as visited (e.g. `"US-CA"`). The answer's `after` also counts the visited regions of that country. On all four mark tools `after` is left out when the atlas cannot be read back; the change itself stands. |
+3 -3
View File
@@ -32,9 +32,9 @@ Requires `trips:read` or `trips:write` scope.
| Tool | Description |
|---|---|
| `list_trips` | List all trips you own or are a member of. Supports `include_archived` flag. |
| `create_trip` | Create a trip with title, dates, and currency. Days are auto-generated from the date range. Without a currency the trip takes your display currency (Settings → General, or the admin's User Defaults preset), and EUR when that is left on *Trip currency*; see [Currencies](Currencies). |
| `update_trip` | Update a trip's title, description, dates, or currency, and with `costs_mode` whether Costs splits the expenses between the travelers (`split`) or keeps the totals only (`totals`); the costs mode needs `budget_edit` instead of `trip_edit`. Day plans follow their position, so dates that hold fewer days remove the last days with what is on them, also when only the start moved later. Every day a change removes is listed in `removed_days`, with its id, number and date as they stood before and a reason: `overflow` for a day past the new range, `spare` for an empty day without a date. |
| `list_trips` | List all trips you own or are a member of. Supports `include_archived` and an optional `tag` filter matched case-insensitively. |
| `create_trip` | Create a trip with title, dates, currency and optional custom `tags`. Days are auto-generated from the date range. Without a currency the trip takes your display currency (Settings → General, or the admin's User Defaults preset), and EUR when that is left on *Trip currency*; see [Currencies](Currencies). |
| `update_trip` | Update a trip's title, description, dates, or currency, and with `costs_mode` whether Costs splits the expenses between the travelers (`split`) or keeps the totals only (`totals`); the costs mode needs `budget_edit` instead of `trip_edit`. Day plans follow their position, so dates that hold fewer days remove the last days with what is on them, also when only the start moved later. Every day a change removes is listed in `removed_days`, with its id, number and date as they stood before and a reason: `overflow` for a day past the new range, `spare` for an empty day without a date. Replace custom tags with `tags` (`[]` clears them), or use `add_tags` and `remove_tags` without `tags`. |
| `search_cover_images` | Search Unsplash for candidate cover photos and return their URLs, thumbnails and photographer credits. Nothing is saved; pass the chosen photo's URL to `update_trip` as `cover_image`. |
| `delete_trip` | Delete a trip. Owner only. Requires `trips:delete`. |
| `list_trip_members` | List the owner and all collaborators of a trip. |