Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

fix(collections): all saved reads its lists four at a time and reloads once per burst of updates

Maurice8acc035efa52
diff --git a/client/scripts/eslint-baseline.json b/client/scripts/eslint-baseline.json
index ad35626f0..cd321cfce 100644
--- a/client/scripts/eslint-baseline.json
+++ b/client/scripts/eslint-baseline.json
@@ -5,7 +5,7 @@
"no-console": 88,
"complexity": 231,
"@typescript-eslint/no-explicit-any": 148,
- "trek/no-swallowed-catch": 135,
+ "trek/no-swallowed-catch": 134,
"max-params": 35,
"trek/store-without-selector": 69,
"react-hooks/refs": 561,
@@ -22,7 +22,7 @@
"trek/no-window-globals": 42,
"react-refresh/only-export-components": 46,
"unused-disable-directive": 6,
- "max-depth": 22,
+ "max-depth": 21,
"react-hooks/void-use-memo": 1,
"@typescript-eslint/no-unused-expressions": 2,
"react-hooks/purity": 2,
diff --git a/client/src/components/Collections/CollectionPicker.tsx b/client/src/components/Collections/CollectionPicker.tsx
index 33b03e8b6..4e84c99eb 100644
--- a/client/src/components/Collections/CollectionPicker.tsx
+++ b/client/src/components/Collections/CollectionPicker.tsx
@@ -2,6 +2,7 @@ import React, { useEffect, useId, useMemo, useRef, useState } from 'react'
import { Search, Bookmark, Loader2, ChevronDown, Check, Layers, Plus, SearchX } from 'lucide-react'
import PlaceAvatar from '../shared/PlaceAvatar'
import { collectionsApi } from '../../api/collections'
+import { loadUnionPlaces } from '../../store/collectionUnion'
import { STATUS_META, STATUS_ORDER } from '../../pages/collections/collectionsModel'
import type { CollectionPlace, CollectionStatus } from '@trek/shared'
import type { TranslationFn } from '../../types'
@@ -34,28 +35,6 @@ function distanceTo(p: CollectionPlace, center: { lat: number; lng: number }): n
interface Opt { key: string | number; label: string; icon?: React.ReactNode; count?: number }
-/** Detail requests fired at once while building the union — keeps a user with
- * many lists from opening the modal with a burst of parallel requests. */
-const DETAIL_BATCH = 4
-
-/** Union of every list's places, in list order, without duplicates. */
-async function loadSavedPlaces(ids: number[]): Promise<CollectionPlace[]> {
- const merged: CollectionPlace[] = []
- const seen = new Set<number>()
- for (let i = 0; i < ids.length; i += DETAIL_BATCH) {
- const batch = await Promise.all(ids.slice(i, i + DETAIL_BATCH).map(id => collectionsApi.get(id).catch(() => null)))
- for (const d of batch) {
- if (!d) continue
- for (const p of d.places) {
- if (seen.has(p.id)) continue
- seen.add(p.id)
- merged.push(p)
- }
- }
- }
- return merged
-}
-
/**
* Compact click-away dropdown (Tailwind, this panel lives outside .trek-dash).
*
@@ -143,7 +122,7 @@ export default function CollectionPicker({ bias, onSelect, t }: CollectionPicker
setLoading(true)
collectionsApi.list()
.then(async (res) => {
- const merged = await loadSavedPlaces(res.collections.map(c => c.id))
+ const merged = await loadUnionPlaces(res.collections.map(c => c.id))
if (cancelled) return
setLists(res.collections.map(c => ({ id: c.id, name: c.name, color: c.color ?? null })))
setPlaces(merged)
diff --git a/client/src/pages/collections/useCollections.test.tsx b/client/src/pages/collections/useCollections.test.tsx
index 599a64742..765224390 100644
--- a/client/src/pages/collections/useCollections.test.tsx
+++ b/client/src/pages/collections/useCollections.test.tsx
@@ -1,4 +1,4 @@
-// FE-PAGE-COLL-001 to FE-PAGE-COLL-085
+// FE-PAGE-COLL-001 to FE-PAGE-COLL-093
// The Collections page hook. The collection store is replaced by a fixture so
// every handler/branch can be driven directly; the categories request goes
// through MSW, and the websocket module is already mocked in tests/setup.ts.
@@ -35,6 +35,9 @@ vi.mock('../../components/Collections/collectionFile', () => ({
}))
import { downloadCollectionFile, downloadCollectionGpx } from '../../components/Collections/collectionFile'
+/** How long useCollections lets a run of collections:* events settle before it reloads. */
+const WS_SETTLE_MS = 400
+
// ── Fixtures ─────────────────────────────────────────────────────────────────
function makeStore() {
return {
@@ -164,6 +167,7 @@ beforeEach(() => {
})
afterEach(() => {
+ vi.useRealTimers()
vi.unstubAllGlobals()
vi.restoreAllMocks()
delete window.__addToast
@@ -869,7 +873,9 @@ describe('useCollections — websocket sync', () => {
store.loadAll.mockClear()
// The route sync already activated the union on mount; only the WS effect counts here.
store.setActive.mockClear()
+ vi.useFakeTimers()
act(() => wsHandler()({ type: 'collections:updated', collectionId: 4 }))
+ act(() => { vi.advanceTimersByTime(WS_SETTLE_MS) })
expect(store.loadAll).toHaveBeenCalledTimes(1)
expect(store.loadCollection).toHaveBeenCalledWith(4)
@@ -881,7 +887,9 @@ describe('useCollections — websocket sync', () => {
store.activeId = null
await setup()
store.loadAll.mockClear()
+ vi.useFakeTimers()
act(() => wsHandler()({ type: 'collections:left' }))
+ act(() => { vi.advanceTimersByTime(WS_SETTLE_MS) })
expect(store.loadAll).toHaveBeenCalledTimes(1)
expect(store.loadCollection).not.toHaveBeenCalled()
@@ -891,9 +899,60 @@ describe('useCollections — websocket sync', () => {
it('FE-PAGE-COLL-076: an update on the All-saved union re-unions the lists', async () => {
store.activeId = 'all'
await setup()
+ store.setActive.mockClear()
+ vi.useFakeTimers()
act(() => wsHandler()({ type: 'collections:accepted' }))
+ act(() => { vi.advanceTimersByTime(WS_SETTLE_MS) })
- expect(store.setActive).toHaveBeenCalledWith('all')
+ // A refresh, so the open place and the selection survive the re-union.
+ expect(store.refreshActive).toHaveBeenCalledTimes(1)
+ expect(store.setActive).not.toHaveBeenCalled()
+ expect(store.loadCollection).not.toHaveBeenCalled()
+ })
+
+ it('FE-PAGE-COLL-091: a burst of updates reloads once, after it has settled (#2559)', async () => {
+ store.activeId = 4
+ await setup()
+ store.loadAll.mockClear()
+ vi.useFakeTimers()
+ act(() => {
+ for (let i = 0; i < 20; i++) {
+ wsHandler()({ type: 'collections:updated', collectionId: 4 })
+ vi.advanceTimersByTime(50)
+ }
+ })
+ expect(store.loadAll).not.toHaveBeenCalled()
+ expect(store.loadCollection).not.toHaveBeenCalled()
+
+ act(() => { vi.advanceTimersByTime(WS_SETTLE_MS) })
+ expect(store.loadAll).toHaveBeenCalledTimes(1)
+ expect(store.loadCollection).toHaveBeenCalledTimes(1)
+ expect(store.loadCollection).toHaveBeenCalledWith(4)
+ })
+
+ it('FE-PAGE-COLL-092: the settled reload reads the list that is open by then', async () => {
+ store.activeId = 4
+ const view = await setup()
+ vi.useFakeTimers()
+ act(() => wsHandler()({ type: 'collections:updated', collectionId: 4 }))
+ store.activeId = 'all'
+ view.rerender()
+ act(() => { vi.advanceTimersByTime(WS_SETTLE_MS) })
+
+ expect(store.loadCollection).not.toHaveBeenCalled()
+ expect(store.refreshActive).toHaveBeenCalledTimes(1)
+ })
+
+ it('FE-PAGE-COLL-093: a reload still pending on unmount is dropped', async () => {
+ store.activeId = 4
+ const view = await setup()
+ store.loadAll.mockClear()
+ vi.useFakeTimers()
+ act(() => wsHandler()({ type: 'collections:updated', collectionId: 4 }))
+ view.unmount()
+ act(() => { vi.advanceTimersByTime(WS_SETTLE_MS) })
+
+ expect(store.loadAll).not.toHaveBeenCalled()
expect(store.loadCollection).not.toHaveBeenCalled()
})
})
diff --git a/client/src/pages/collections/useCollections.ts b/client/src/pages/collections/useCollections.ts
index 137b1a4b6..60ffc8bd2 100644
--- a/client/src/pages/collections/useCollections.ts
+++ b/client/src/pages/collections/useCollections.ts
@@ -18,6 +18,9 @@ import type { Category, Place } from '../../types'
import { filterPlaces, sortPlaces, statusCounts, mappablePlaces, presentCategories, presentLabels } from './collectionsModel'
import type { CollectionLabelUpdateRequest } from '@trek/shared'
+/** Quiet time after the last collections:* event before the page reloads. */
+const WS_RELOAD_SETTLE_MS = 400
+
/**
* Collections page logic — owns the page-local UI state (new/edit-list forms,
* mobile rail drawer), pulls the collection store, wires the WebSocket live sync
@@ -145,6 +148,9 @@ export function useCollections() {
// Live sync via WebSocket. collections:deleted / :removed must bounce a member
// off a list that was removed (or that they were kicked from) under them.
+ const wsReloadTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
+ const activeIdRef = useRef(activeId)
+ useEffect(() => { activeIdRef.current = activeId }, [activeId])
const handleWsMessage = useCallback((msg: { type: string; collectionId?: number }) => {
if (!msg.type?.startsWith('collections:')) return
if (msg.type === 'collections:deleted' || msg.type === 'collections:removed') {
@@ -160,15 +166,26 @@ export function useCollections() {
// invite / accepted / declined / cancelled / left / updated → refresh the
// rail, and refresh the active list WITHOUT clearing the current selection or
// select-mode (setActive would reset selectedPlaceId → close the open detail).
- loadAll()
- if (typeof activeId === 'number') loadCollection(activeId)
- else if (activeId === ALL_SAVED) setActive(ALL_SAVED)
+ // An agent saving places one by one over MCP sends one event per place, so
+ // the reload waits until they stop instead of re-reading every list per event
+ // (#2559), and then reads whatever list is open by that time.
+ if (wsReloadTimer.current !== null) clearTimeout(wsReloadTimer.current)
+ wsReloadTimer.current = setTimeout(() => {
+ wsReloadTimer.current = null
+ loadAll()
+ const current = activeIdRef.current
+ if (typeof current === 'number') loadCollection(current)
+ else if (current === ALL_SAVED) refreshActive()
+ }, WS_RELOAD_SETTLE_MS)
}, [activeId])
useEffect(() => {
addListener(handleWsMessage)
return () => removeListener(handleWsMessage)
}, [handleWsMessage])
+ useEffect(() => () => {
+ if (wsReloadTimer.current !== null) clearTimeout(wsReloadTimer.current)
+ }, [])
// ── Derived ─────────────────────────────────────────────────────────
const activeCollection = useMemo(
diff --git a/client/src/store/collectionStore.test.ts b/client/src/store/collectionStore.test.ts
index ec7858780..d95a257c2 100644
--- a/client/src/store/collectionStore.test.ts
+++ b/client/src/store/collectionStore.test.ts
@@ -960,3 +960,99 @@ describe('collectionStore — view state', () => {
expect(store().selectMode).toBe(false)
})
})
+
+describe('collectionStore — "All saved" load pressure (#2559)', () => {
+ /** A get() the test settles by hand, counting how many are open at once. */
+ function deferredGets() {
+ const pending: Array<{ id: number; resolve: (d: CollectionDetailResponse) => void }> = []
+ let open = 0
+ let peak = 0
+ vi.mocked(collectionsApi.get).mockImplementation((id: number) => {
+ open++
+ peak = Math.max(peak, open)
+ return new Promise<CollectionDetailResponse>(resolve => {
+ pending.push({ id, resolve: (d) => { open--; resolve(d) } })
+ })
+ })
+ return {
+ pending,
+ peak: () => peak,
+ /** Answer everything that is open now, each list with one place of its own id. */
+ async flush() {
+ const batch = pending.splice(0)
+ for (const p of batch) p.resolve(detail({ places: [buildPlace({ id: p.id * 100, collection_id: p.id })] }))
+ await Promise.resolve()
+ await new Promise(r => setTimeout(r, 0))
+ },
+ }
+ }
+
+ it('FE-STORE-COLLECTION-064: the union reads at most four lists at a time', async () => {
+ const lists = Array.from({ length: 10 }, (_, i) => ({ id: i + 1, owner_id: 1, name: `L${i + 1}` }))
+ useCollectionStore.setState({ collections: lists })
+ const gets = deferredGets()
+
+ const run = store().setActive(ALL_SAVED)
+ while (gets.pending.length > 0) await gets.flush()
+ await run
+
+ expect(collectionsApi.get).toHaveBeenCalledTimes(10)
+ expect(gets.peak()).toBeLessThanOrEqual(4)
+ expect(store().places.map(p => p.id)).toEqual(lists.map(l => l.id * 100))
+ expect(store().placesLoading).toBe(false)
+ })
+
+ it('FE-STORE-COLLECTION-065: reloads asked for while the union is loading fold into one more pass', async () => {
+ useCollectionStore.setState({ collections: [listA, listB] })
+ const gets = deferredGets()
+
+ const first = store().setActive(ALL_SAVED)
+ await Promise.resolve()
+ const again = [store().refreshActive(), store().refreshActive(), store().setActive(ALL_SAVED)]
+ while (gets.pending.length > 0) await gets.flush()
+ await Promise.all([first, ...again])
+
+ // One pass for the first load and exactly one for the three that came in during it.
+ expect(collectionsApi.get).toHaveBeenCalledTimes(4)
+ expect(store().placesLoading).toBe(false)
+ })
+
+ it('FE-STORE-COLLECTION-066: a union that lands after the user opened a list does not overwrite it', async () => {
+ useCollectionStore.setState({ collections: [listA, listB] })
+ const unionGets: Array<() => void> = []
+ vi.mocked(collectionsApi.get).mockImplementation((id: number) => {
+ if (id === 2) return Promise.resolve(detail({ collection: listB, places: [buildPlace({ id: 77, collection_id: 2 })] }))
+ return new Promise(resolve => unionGets.push(() => resolve(detail({ places: [buildPlace({ id: 10 })] }))))
+ })
+
+ const union = store().setActive(ALL_SAVED)
+ await Promise.resolve()
+ await store().setActive(2)
+ expect(store().places.map(p => p.id)).toEqual([77])
+
+ unionGets.forEach(r => r())
+ await union
+
+ expect(store().activeId).toBe(2)
+ expect(store().places.map(p => p.id)).toEqual([77])
+ })
+
+ it('FE-STORE-COLLECTION-067: a list read that lands after switching to "All saved" does not take over again', async () => {
+ useCollectionStore.setState({ collections: [listA, listB] })
+ const listOneReads: Array<() => void> = []
+ vi.mocked(collectionsApi.get).mockImplementation((id: number) => {
+ if (id === 1) return new Promise(resolve => listOneReads.push(() => resolve(detail({ places: [buildPlace({ id: 10 })] }))))
+ return Promise.resolve(detail({ collection: listB, places: [buildPlace({ id: 20, collection_id: 2 })] }))
+ })
+
+ const list = store().setActive(1)
+ await Promise.resolve()
+ // The union reads list 1 as well, so both reads are answered together.
+ const union = store().setActive(ALL_SAVED)
+ await Promise.resolve()
+ listOneReads.forEach(r => r())
+ await Promise.all([list, union])
+
+ expect(store().activeId).toBe(ALL_SAVED)
+ })
+})
diff --git a/client/src/store/collectionStore.ts b/client/src/store/collectionStore.ts
index 3455be9df..031daf665 100644
--- a/client/src/store/collectionStore.ts
+++ b/client/src/store/collectionStore.ts
@@ -1,5 +1,6 @@
import { create } from 'zustand'
import { collectionsApi } from '../api/collections'
+import { loadUnionPlaces } from './collectionUnion'
import type {
Collection,
CollectionPlace,
@@ -94,6 +95,26 @@ interface CollectionState {
clearSelection: () => void
}
+/**
+ * What the user last asked to look at, and the "All saved" union read that may
+ * be running for it. A list or union read that comes back after the user has
+ * moved on is dropped instead of painting the old places over the new ones, and
+ * reloads of the union asked for while one is running fold into a single further
+ * pass instead of stacking up full reads of every list (#2559).
+ */
+const activeLoad = {
+ /** Bumped by every setActive/refreshActive, so a read can tell it was overtaken. */
+ seq: 0,
+ target: null as ActiveCollectionId,
+ union: null as Promise<void> | null,
+ unionAgain: false,
+}
+
+/** True once a newer setActive has turned away from what a read started at `seq` was for. */
+function overtaken(seq: number, id: ActiveCollectionId): boolean {
+ return activeLoad.seq !== seq && activeLoad.target !== id
+}
+
/**
* Load whatever `id` points at (a list, the "All saved" union, or nothing) into
* the store. Split out of setActive() because switching lists also has to drop
@@ -105,36 +126,48 @@ async function loadActive(
get: () => CollectionState,
id: ActiveCollectionId,
): Promise<void> {
+ activeLoad.seq++
+ activeLoad.target = id
if (id === null) {
set({ activeId: null, places: [], members: [], labels: [] })
return
}
if (id === ALL_SAVED) {
set({ activeId: ALL_SAVED, members: [], labels: [], placesLoading: true })
- try {
+ if (activeLoad.union !== null) {
+ activeLoad.unionAgain = true
+ return activeLoad.union
+ }
+ activeLoad.union = loadUnion(set, get)
+ return activeLoad.union
+ }
+ await get().loadCollection(id)
+}
+
+/** The "All saved" union, read again as long as reloads keep coming in while it runs. */
+async function loadUnion(
+ set: (partial: Partial<CollectionState>) => void,
+ get: () => CollectionState,
+): Promise<void> {
+ try {
+ do {
+ activeLoad.unionAgain = false
// Client-side union of every list the user owns or co-owns (no server change).
// On first load the lists may not be fetched yet (loadAll still in flight),
// which would union nothing — make sure they're loaded first.
let lists = get().collections
if (lists.length === 0) { await get().loadAll(); lists = get().collections }
- const results = await Promise.all(lists.map(l => collectionsApi.get(l.id).catch(() => null)))
- const seen = new Set<number>()
- const merged: CollectionPlace[] = []
- for (const res of results) {
- if (!res) continue
- for (const p of res.places) {
- if (seen.has(p.id)) continue
- seen.add(p.id)
- merged.push(p)
- }
- }
+ const merged = await loadUnionPlaces(lists.map(l => l.id))
+ if (activeLoad.target !== ALL_SAVED) return
set({ places: merged })
- } finally {
- set({ placesLoading: false })
- }
- return
+ } while (activeLoad.unionAgain && activeLoad.target === ALL_SAVED)
+ } finally {
+ // Cleared here and not after the promise settles, so a reload asked for from
+ // now on starts a pass of its own instead of joining one that has ended.
+ activeLoad.union = null
+ // A list opened meanwhile clears the flag when its own read is done.
+ if (typeof activeLoad.target !== 'number') set({ placesLoading: false })
}
- await get().loadCollection(id)
}
export const useCollectionStore = create<CollectionState>((set, get) => ({
@@ -168,9 +201,11 @@ export const useCollectionStore = create<CollectionState>((set, get) => ({
},
loadCollection: async (id: number) => {
+ const seq = activeLoad.seq
set({ placesLoading: true })
try {
const data = await collectionsApi.get(id)
+ if (overtaken(seq, id)) return
set({
activeId: id,
places: data.places,
@@ -182,9 +217,10 @@ export const useCollectionStore = create<CollectionState>((set, get) => ({
// event or the URL sync can re-request an id we just lost access to). Clear
// it instead of leaving an uncaught 403/404 rejection; useCollections drops
// a route id that is no longer one of the lists.
- if (get().activeId === id) set({ activeId: null, places: [], members: [], labels: [] })
+ if (!overtaken(seq, id) && get().activeId === id) set({ activeId: null, places: [], members: [], labels: [] })
} finally {
- set({ placesLoading: false })
+ // Whatever overtook this read owns the flag now; nothing does after setActive(null).
+ if (!overtaken(seq, id) || activeLoad.target === null) set({ placesLoading: false })
}
},
diff --git a/client/src/store/collectionUnion.ts b/client/src/store/collectionUnion.ts
new file mode 100644
index 000000000..58a4b2db9
--- /dev/null
+++ b/client/src/store/collectionUnion.ts
@@ -0,0 +1,28 @@
+import type { CollectionPlace } from '@trek/shared';
+import { collectionsApi } from '../api/collections';
+
+/** Detail requests fired at once while building the union. A user with many
+ * lists would otherwise open "All saved" (or the trip's saved-places picker)
+ * with one full list read per list, all in parallel (#2559). */
+export const DETAIL_BATCH = 4;
+
+/** Union of every list's places, in list order, without duplicates. A list
+ * that cannot be read is skipped. */
+export async function loadUnionPlaces(ids: number[]): Promise<CollectionPlace[]> {
+ const merged: CollectionPlace[] = [];
+ const seen = new Set<number>();
+ for (let i = 0; i < ids.length; i += DETAIL_BATCH) {
+ const batch = await Promise.all(
+ ids.slice(i, i + DETAIL_BATCH).map((id) => collectionsApi.get(id).catch(() => null))
+ );
+ for (const d of batch) {
+ if (!d) continue;
+ for (const p of d.places) {
+ if (seen.has(p.id)) continue;
+ seen.add(p.id);
+ merged.push(p);
+ }
+ }
+ }
+ return merged;
+}