feat(tours): let a background check hint at changes of your own wanderer trails

Settings, Integrations, wanderer gains an optional background check of the
trails you imported, off until you switch it on. While on, TREK reads the
short record of each such trail at most once a day (never its GPX file) and
leaves a hint when the trail may have moved on: "may have changed" when only
wanderer's change time moved, "changed" when its name or description proves
it, and "not checkable" when the trail is gone, no longer yours or carries no
change time. Nothing is ever said to be unchanged. A new hint arrives as a
notification that opens the tour (a new ?place= link in the planner); the
tour's provenance shows it with the source check right beside it, and the
card lists all open hints in a dialog, each leading to its tour. The check
reads the source in full as before and spends the hint; taking a change in
stays the confirmed reimport. No tour is ever changed or deleted.

The check only asks through your own connection, only about trails your
account imported into trips you can still open, and stops when you switch it
off, remove the connection, wanderer refuses the token (until a test passes
or a new token is saved) or the admin switches wanderer off; hints and
snapshots stay. A run asks at most 25 connections for at most 10 records
each, one after another, and an instance that fails (an outage, a rate
limit) is left alone for an hour, doubling up to two days.

Server: migration 046120 adds the switch and the run bookkeeping to
wanderer_connections and the tour_source_hints table (one row per snapshot,
for its importer, gone with it). WandererWatchService and an hourly
wanderer-watch job on the CronRegistrar live in the tours domain and read
through WandererService; GET and PUT /api/integrations/wanderer/watch and GET
/api/trips/:tripId/tours/wanderer/sources/:placeId/hint (place_edit, like the
check) answer with @trek/shared contracts. A new user notification event,
wanderer_source_hint, can be muted per channel. Saving a new token now clears
what the last check said about the old one. There is no MCP tool, as for the
rest of the personal wanderer connection. All 27 locales carry the strings,
and the admin wiki page says what the check does.
This commit is contained in:
Maurice
2026-10-20 14:40:50 +02:00
parent aacc7f2c8d
commit 2e1dca9fe9
202 changed files with 4791 additions and 57 deletions
@@ -16,11 +16,14 @@ import {
} from './settingsKit';
import ToggleSwitch from './ToggleSwitch';
import { useWandererConnection } from './useWandererConnection';
import WandererWatchRow from './WandererWatchRow';
/**
* Settings → Integrations → wanderer: the reader's own trail database, from
* which the Tours workspace imports trails. Laid out like the Dawarich and
* AirTrail cards beside it; the behaviour is in `useWandererConnection`.
* Under the form, the optional background check of the imported trails
* (WAN-02), which switches on its own and needs no save.
*/
export default function WandererConnectionSection(): React.ReactElement {
const { t } = useTranslation();
@@ -136,6 +139,8 @@ export default function WandererConnectionSection(): React.ReactElement {
)}
</div>
)}
<WandererWatchRow connected={S.connected} />
</Section>
);
}
@@ -0,0 +1,101 @@
import userEvent from '@testing-library/user-event';
import type { WandererSourceHintItem, WandererWatch } from '@trek/shared';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { render, screen, waitFor, within } from '../../../tests/helpers/render';
import WandererWatchRow from './WandererWatchRow';
const repo = vi.hoisted(() => ({ getWatch: vi.fn(), setWatch: vi.fn() }));
const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() }));
const navigate = vi.hoisted(() => vi.fn());
vi.mock('../../repo/wandererRepo', () => ({ wandererRepo: repo }));
vi.mock('../shared/Toast', () => ({ useToast: () => toast }));
vi.mock('react-router', async () => ({
...(await vi.importActual<typeof import('react-router')>('react-router')),
useNavigate: () => navigate,
}));
const off: WandererWatch = {
enabled: false,
connected: true,
lastRunAt: null,
pausedUntil: null,
blocked: false,
hints: [],
};
const hints: WandererSourceHintItem[] = [
{
placeId: 7,
tripId: 3,
tripTitle: 'Alps',
tourName: 'Ridge',
state: 'changed',
changes: ['name'],
reason: null,
externalUpdated: '2026-10-14',
checkedAt: '2026-10-20T10:00:00Z',
},
{
placeId: 8,
tripId: 3,
tripTitle: 'Alps',
tourName: 'Gorge',
state: 'unverifiable',
changes: [],
reason: 'unavailable',
externalUpdated: null,
checkedAt: '2026-10-19T10:00:00Z',
},
];
beforeEach(() => {
vi.clearAllMocks();
});
describe('WandererWatchRow (WAN-02)', () => {
it('is off by default and dimmed, not hidden, without a connection', async () => {
repo.getWatch.mockResolvedValue({ ...off, connected: false });
render(<WandererWatchRow connected={false} />);
await waitFor(() => expect(repo.getWatch).toHaveBeenCalled());
const toggle = await screen.findByRole('button', { name: 'Check my trails for changes', pressed: false });
expect(toggle).toHaveAttribute('aria-pressed', 'false');
expect(toggle.closest('[aria-disabled="true"]')).not.toBeNull();
expect(screen.queryByTestId('wanderer-watch-status')).toBeNull();
});
it('switches on at once and then says when it last looked', async () => {
repo.getWatch.mockResolvedValue(off);
repo.setWatch.mockResolvedValue({ ...off, enabled: true });
render(<WandererWatchRow connected />);
const toggle = await screen.findByRole('button', { name: 'Check my trails for changes', pressed: false });
await waitFor(() => expect(toggle.closest('[aria-disabled="true"]')).toBeNull());
await userEvent.click(toggle);
expect(repo.setWatch).toHaveBeenCalledWith(true);
expect(await screen.findByText('Not looked yet')).toBeInTheDocument();
expect(screen.getByRole('button', { name: /Hints/ })).toBeDisabled();
});
it('counts the open hints on the button and opens each tour from the dialog', async () => {
repo.getWatch.mockResolvedValue({ ...off, enabled: true, lastRunAt: '2026-10-20T10:00:00Z', hints });
render(<WandererWatchRow connected />);
expect(await screen.findByTestId('wanderer-hint-count')).toHaveTextContent('2');
await userEvent.click(screen.getByRole('button', { name: /Hints/ }));
const dialog = await screen.findByRole('dialog');
expect(within(dialog).getByText('Hints on your trails')).toBeInTheDocument();
expect(within(dialog).getByText('2 open hints')).toBeInTheDocument();
const ridge = within(dialog).getByTestId('wanderer-hint-7');
expect(within(ridge).getByText('Changed')).toBeInTheDocument();
expect(within(ridge).getByText('Name')).toBeInTheDocument();
expect(within(within(dialog).getByTestId('wanderer-hint-8')).getByText('Trail out of reach')).toBeInTheDocument();
await userEvent.click(ridge);
expect(navigate).toHaveBeenCalledWith('/trips/3?tab=plan&place=7');
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
});
it('names a refused token instead of a last look', async () => {
repo.getWatch.mockResolvedValue({ ...off, enabled: true, blocked: true });
render(<WandererWatchRow connected />);
expect(await screen.findByText('Token refused')).toBeInTheDocument();
});
});
@@ -0,0 +1,97 @@
import { BellRing } from 'lucide-react';
import React from 'react';
import { useTranslation } from '../../i18n';
import { fs } from '../shared/DialogShell';
import { Tooltip } from '../shared/Tooltip';
import { InfoDot } from '../Tours/tourParts';
import WandererHintsDialog from '../Tours/wanderer/WandererHintsDialog';
import { SETTINGS_BUTTON, SettingRow, SettingRows, StatusPill } from './settingsKit';
import ToggleSwitch from './ToggleSwitch';
import { useWandererWatch, type WandererWatchController } from './useWandererWatch';
/** The switch, dimmed with a word on why while there is no connection to watch with. */
function WatchSwitch({ W }: { W: WandererWatchController }) {
const { t } = useTranslation();
const toggle = (
<ToggleSwitch on={W.enabled} onToggle={() => void W.toggle()} label={t('wanderer.watch.label')} />
);
if (W.available) return toggle;
return (
<Tooltip label={t('wanderer.watch.notConnected')}>
<span className="inline-flex opacity-50" aria-disabled="true">
<span className="pointer-events-none inline-flex">{toggle}</span>
</span>
</Tooltip>
);
}
/** The open hints behind a button, their number as a badge on its corner; dimmed while there are none. */
function HintsButton({ W }: { W: WandererWatchController }) {
const { t } = useTranslation();
const count = W.hints.length;
return (
<Tooltip label={count ? t('wanderer.watch.hintsCount', { count }) : t('wanderer.watch.empty')}>
<span className="inline-flex">
<button
type="button"
onClick={W.openHints}
disabled={count === 0}
className={`${SETTINGS_BUTTON} relative`}
style={fs(12.5, 'body')}
>
<BellRing size={13} strokeWidth={2.2} />
{t('wanderer.watch.hints')}
{count > 0 && (
<span
aria-label={t('wanderer.watch.hintsCount', { count })}
data-testid="wanderer-hint-count"
className="absolute -end-1.5 -top-1.5 grid h-[18px] min-w-[18px] place-items-center rounded-full bg-accent px-1 font-geist font-semibold tabular-nums text-accent-text ring-2 ring-[color:var(--bg-card)]"
style={fs(10)}
>
{count}
</span>
)}
</button>
</span>
</Tooltip>
);
}
/**
* WAN-02 in the wanderer card: the optional background check of the user's
* own imported trails. Off until switched on; while on, what it last did and
* its open hints, which open in a dialog that leads to each tour.
*/
export default function WandererWatchRow({ connected }: { connected: boolean }): React.ReactElement {
const { t } = useTranslation();
const W = useWandererWatch(connected);
return (
<SettingRows>
<SettingRow
label={
<span className="inline-flex items-center gap-1.5">
{t('wanderer.watch.label')}
<InfoDot label={t('wanderer.watch.label')} description={t('wanderer.watch.info')} />
</span>
}
hint={t('wanderer.watch.hint')}
dimmed={W.saving}
control={<WatchSwitch W={W} />}
>
{W.status && (
<div className="flex flex-wrap items-center gap-2" data-testid="wanderer-watch-status">
<Tooltip label={W.status.why ?? ''} disabled={!W.status.why}>
<span className="inline-flex">
<StatusPill tone={W.status.tone}>{W.status.text}</StatusPill>
</span>
</Tooltip>
<span className="ms-auto">
<HintsButton W={W} />
</span>
</div>
)}
</SettingRow>
<WandererHintsDialog open={W.hintsOpen} hints={W.hints} onClose={W.closeHints} onOpenTour={W.openTour} />
</SettingRows>
);
}
@@ -27,6 +27,7 @@ export const EVENT_LABEL_KEYS: Record<string, string> = {
photos_shared: 'settings.notifyPhotosShared',
collab_message: 'settings.notifyCollabMessage',
packing_tagged: 'settings.notifyPackingTagged',
wanderer_source_hint: 'settings.notifyWandererSourceHint',
version_available: 'settings.notifyVersionAvailable',
}
@@ -0,0 +1,134 @@
import { act, renderHook, waitFor } from '@testing-library/react';
import type { WandererSourceHintItem, WandererWatch } from '@trek/shared';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { useWandererWatch, watchStatusOf } from './useWandererWatch';
const repo = vi.hoisted(() => ({ getWatch: vi.fn(), setWatch: vi.fn() }));
const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() }));
const navigate = vi.hoisted(() => vi.fn());
vi.mock('../../repo/wandererRepo', () => ({ wandererRepo: repo }));
vi.mock('../shared/Toast', () => ({ useToast: () => toast }));
vi.mock('../../i18n', () => ({
useTranslation: () => ({
t: (key: string, params?: Record<string, unknown>) => (params ? `${key} ${JSON.stringify(params)}` : key),
locale: 'en',
}),
}));
vi.mock('react-router', async () => ({
...(await vi.importActual<typeof import('react-router')>('react-router')),
useNavigate: () => navigate,
}));
const t = (key: string) => key;
const off: WandererWatch = {
enabled: false,
connected: true,
lastRunAt: null,
pausedUntil: null,
blocked: false,
hints: [],
};
const hint: WandererSourceHintItem = {
placeId: 7,
tripId: 3,
tripTitle: 'Alps',
tourName: 'Ridge',
state: 'possible_change',
changes: [],
reason: null,
externalUpdated: '2026-10-14',
checkedAt: '2026-10-20T10:00:00Z',
};
beforeEach(() => {
vi.clearAllMocks();
repo.getWatch.mockResolvedValue(off);
repo.setWatch.mockImplementation(async (enabled: boolean) => ({ ...off, enabled }));
});
describe('watchStatusOf (WAN-02)', () => {
const now = Date.parse('2026-10-20T12:00:00Z');
it('says nothing while the watch is off', () => {
expect(watchStatusOf(null, t, 'en', now)).toBeNull();
expect(watchStatusOf(off, t, 'en', now)).toBeNull();
});
it('names a refused token first, then a pause still running, then the last look', () => {
const on = { ...off, enabled: true };
expect(watchStatusOf({ ...on, blocked: true, pausedUntil: '2026-10-21T00:00:00Z' }, t, 'en', now)).toEqual({
tone: 'danger',
text: 'wanderer.watch.blocked',
why: 'wanderer.watch.blockedHint',
});
expect(watchStatusOf({ ...on, pausedUntil: '2026-10-20T14:00:00Z' }, t, 'en', now)).toMatchObject({
tone: 'warning',
text: 'wanderer.watch.paused',
why: 'wanderer.watch.pausedHint',
});
expect(
watchStatusOf({ ...on, pausedUntil: '2026-10-20T11:00:00Z', lastRunAt: '2026-10-20T10:00:00Z' }, t, 'en', now)
).toEqual({ tone: 'neutral', text: 'wanderer.watch.lastRun', why: null });
expect(watchStatusOf(on, t, 'en', now)).toEqual({ tone: 'neutral', text: 'wanderer.watch.neverRun', why: null });
});
});
describe('useWandererWatch (WAN-02)', () => {
it('loads with the card and again when the connection comes or goes', async () => {
const { result, rerender } = renderHook(({ connected }) => useWandererWatch(connected), {
initialProps: { connected: true },
});
await waitFor(() => expect(result.current.available).toBe(true));
expect(result.current.enabled).toBe(false);
expect(result.current.status).toBeNull();
rerender({ connected: false });
await waitFor(() => expect(repo.getWatch).toHaveBeenCalledTimes(2));
});
it('switches at once, and says so either way', async () => {
const { result } = renderHook(() => useWandererWatch(true));
await waitFor(() => expect(result.current.available).toBe(true));
await act(async () => {
await result.current.toggle();
});
expect(repo.setWatch).toHaveBeenCalledWith(true);
expect(result.current.enabled).toBe(true);
expect(toast.success).toHaveBeenCalledWith('wanderer.watch.on');
repo.setWatch.mockRejectedValueOnce(new Error('down'));
await act(async () => {
await result.current.toggle();
});
expect(toast.error).toHaveBeenCalledWith('wanderer.watch.failed');
expect(result.current.enabled).toBe(true);
});
it('leaves the switch alone without a connection, or when the watch could not be read', async () => {
repo.getWatch.mockResolvedValueOnce({ ...off, connected: false });
const { result } = renderHook(() => useWandererWatch(false));
await waitFor(() => expect(repo.getWatch).toHaveBeenCalled());
await act(async () => {
await result.current.toggle();
});
expect(repo.setWatch).not.toHaveBeenCalled();
repo.getWatch.mockRejectedValueOnce(new Error('offline'));
const failed = renderHook(() => useWandererWatch(true));
await waitFor(() => expect(repo.getWatch).toHaveBeenCalledTimes(2));
expect(failed.result.current.available).toBe(false);
});
it('lists the hints and opens the tour one is about', async () => {
repo.getWatch.mockResolvedValue({ ...off, enabled: true, hints: [hint] });
const { result } = renderHook(() => useWandererWatch(true));
await waitFor(() => expect(result.current.hints).toEqual([hint]));
act(() => result.current.openHints());
expect(result.current.hintsOpen).toBe(true);
act(() => result.current.openTour(hint));
expect(navigate).toHaveBeenCalledWith('/trips/3?tab=plan&place=7');
expect(result.current.hintsOpen).toBe(false);
act(() => result.current.openHints());
act(() => result.current.closeHints());
expect(result.current.hintsOpen).toBe(false);
});
});
@@ -0,0 +1,113 @@
import type { WandererSourceHintItem, WandererWatch } from '@trek/shared';
import { useCallback, useEffect, useState } from 'react';
import { useNavigate } from 'react-router';
import { useTranslation } from '../../i18n';
import { wandererRepo } from '../../repo/wandererRepo';
import { useToast } from '../shared/Toast';
import { hintWhen } from '../Tours/wanderer/sourceHintParts';
type Translate = (key: string, params?: Record<string, unknown>) => string;
/** What the watch last did, as one pill: refused, waiting after errors, last looked, or not yet. */
interface WandererWatchStatus {
tone: 'neutral' | 'warning' | 'danger';
text: string;
/** Why, for the tooltip; null where the text says it all. */
why: string | null;
}
/** The pill for a switched-on watch; null while it is off, since then nothing runs to report on. */
export function watchStatusOf(
watch: WandererWatch | null,
t: Translate,
locale: string,
now = Date.now()
): WandererWatchStatus | null {
if (!watch?.enabled) return null;
if (watch.blocked) return { tone: 'danger', text: t('wanderer.watch.blocked'), why: t('wanderer.watch.blockedHint') };
const pausedUntil = watch.pausedUntil ? new Date(watch.pausedUntil).getTime() : Number.NaN;
if (pausedUntil > now) {
return {
tone: 'warning',
text: t('wanderer.watch.paused', { time: hintWhen(watch.pausedUntil, locale) }),
why: t('wanderer.watch.pausedHint'),
};
}
const lastRun = hintWhen(watch.lastRunAt, locale);
return {
tone: 'neutral',
text: lastRun ? t('wanderer.watch.lastRun', { date: lastRun }) : t('wanderer.watch.neverRun'),
why: null,
};
}
/**
* WAN-02: the background watch in the wanderer card. It loads with the card
* and again whenever the connection comes or goes, switches on and off at
* once (there is nothing to save with the form), and opens the tour a hint is
* about. Online-only like the rest of the connection: the watch runs on the
* server and its hints are read from there.
*/
export function useWandererWatch(connected: boolean) {
const { t, locale } = useTranslation();
const toast = useToast();
const navigate = useNavigate();
const [watch, setWatch] = useState<WandererWatch | null>(null);
const [saving, setSaving] = useState(false);
const [hintsOpen, setHintsOpen] = useState(false);
useEffect(() => {
let cancelled = false;
wandererRepo.getWatch().then(
(next) => {
if (!cancelled) setWatch(next);
},
() => {
// The card above already says when the connection cannot be read; without
// an answer the switch simply stays dimmed.
if (!cancelled) setWatch(null);
}
);
return () => {
cancelled = true;
};
}, [connected]);
const toggle = useCallback(async () => {
if (!watch?.connected || saving) return;
setSaving(true);
try {
const next = await wandererRepo.setWatch(!watch.enabled);
setWatch(next);
toast.success(next.enabled ? t('wanderer.watch.on') : t('wanderer.watch.off'));
} catch {
toast.error(t('wanderer.watch.failed'));
} finally {
setSaving(false);
}
}, [saving, t, toast, watch]);
const openTour = useCallback(
(hint: WandererSourceHintItem) => {
setHintsOpen(false);
navigate(`/trips/${hint.tripId}?tab=plan&place=${hint.placeId}`);
},
[navigate]
);
return {
/** The switch can act: the server knows a connection to watch with. */
available: !!watch?.connected,
enabled: !!watch?.enabled,
saving,
status: watchStatusOf(watch, t, locale),
hints: watch?.hints ?? [],
hintsOpen,
openHints: useCallback(() => setHintsOpen(true), []),
closeHints: useCallback(() => setHintsOpen(false), []),
openTour,
toggle,
};
}
export type WandererWatchController = ReturnType<typeof useWandererWatch>;
@@ -1,5 +1,5 @@
import { fireEvent, render, screen } from '@testing-library/react';
import type { TourProvenance, TourSourceCheckResponse } from '@trek/shared';
import type { TourProvenance, TourSourceCheckResponse, TourSourceHint } from '@trek/shared';
import { describe, expect, it, vi } from 'vitest';
import TourProvenanceSection from './TourProvenanceSection';
import type { SourceCheck } from './useSourceCheck';
@@ -158,4 +158,51 @@ describe('TourProvenanceSection (P2C-02, MF-03)', () => {
expect(screen.getByText('tours.provenance.body.unavailable')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: /tours.provenance.reimport/ })).toBeNull();
});
it('shows the background hint with its own check button until the source answered (WAN-02)', () => {
const onCheck = vi.fn();
const wanderer: TourProvenance = {
...base,
origin: 'wanderer',
source: {
kind: 'wanderer',
instance: 'https://t.example',
externalId: 't1',
externalUrl: null,
externalUpdated: null,
importedAt: null,
},
};
const hint: TourSourceHint = {
state: 'changed',
changes: ['description'],
reason: null,
externalUpdated: '2026-10-14',
checkedAt: '2026-10-20T10:00:00Z',
};
const { rerender } = render(
<TourProvenanceSection provenance={wanderer} check={check({ check: onCheck })} hint={hint} />
);
const notice = screen.getByTestId('tour-source-hint');
expect(notice).toHaveTextContent('wanderer.watch.noticeLabel');
expect(screen.getByTestId('source-hint-state')).toHaveAttribute('data-state', 'changed');
expect(screen.getByText('tours.provenance.change.description')).toBeInTheDocument();
const buttons = screen.getAllByRole('button', { name: /tours.provenance.check$/ });
expect(buttons).toHaveLength(1);
fireEvent.click(buttons[0]);
expect(onCheck).toHaveBeenCalledTimes(1);
rerender(
<TourProvenanceSection
provenance={wanderer}
check={check({ answered: true })}
hint={{ ...hint, state: 'unverifiable', changes: [], reason: 'unavailable' }}
/>
);
expect(screen.queryByTestId('tour-source-hint')).toBeNull();
expect(screen.getAllByRole('button', { name: /tours.provenance.check$/ })).toHaveLength(1);
rerender(<TourProvenanceSection provenance={wanderer} hint={hint} />);
expect(screen.queryByTestId('tour-source-hint')).toBeNull();
});
});
@@ -1,4 +1,4 @@
import type { TourListItem, TourProvenance, TourSourceCheckResponse } from '@trek/shared';
import type { TourListItem, TourProvenance, TourSourceCheckResponse, TourSourceHint } from '@trek/shared';
import { CopyPlus, Download, ExternalLink, FileDown, Loader2, PenLine, RefreshCw } from 'lucide-react';
import type { ReactNode } from 'react';
import { useTranslation } from '../../../i18n';
@@ -9,8 +9,10 @@ import ConfirmDialog from '../../shared/ConfirmDialog';
import { DialogSection, fs } from '../../shared/DialogShell';
import { Tooltip } from '../../shared/Tooltip';
import { CardAction, InfoDot } from '../tourParts';
import { hintWhen, SourceHintPills, SourceHintTile } from '../wanderer/sourceHintParts';
import WandererMark from '../wanderer/WandererMark';
import { type SourceCheck, useSourceCheck } from './useSourceCheck';
import { useSourceHint } from './useSourceHint';
import { useTourProvenance } from './useTourProvenance';
type Translate = (key: string, params?: Record<string, unknown>) => string;
@@ -177,10 +179,73 @@ function CheckResult({ check, locale, t }: { check: SourceCheck; locale: string;
);
}
/** The check button, in the head of the section or on the hint it answers. */
function CheckButton({ check, t }: { check: SourceCheck; t: Translate }) {
return (
<Tooltip label={t('tours.provenance.checkHint')}>
<span className="inline-flex">
<CardAction
icon={
check.checking ? <Loader2 size={12} className="animate-spin" /> : <RefreshCw size={12} strokeWidth={2.2} />
}
onClick={() => void check.check()}
disabled={check.checking}
>
{t('tours.provenance.check')}
</CardAction>
</span>
</Tooltip>
);
}
/**
* WAN-02: what the reader's background watch found about this snapshot's
* source. A hint, never the answer: it leads to the check, which reads the
* source in full and from which a change can be taken in.
*/
function HintNotice({
hint,
check,
locale,
t,
}: {
hint: TourSourceHint;
check: SourceCheck;
locale: string;
t: Translate;
}) {
const when = hintWhen(hint.checkedAt, locale);
return (
<div
role="status"
data-testid="tour-source-hint"
className="flex items-center gap-2.5 border-t border-edge-faint px-3 py-2.5"
>
<SourceHintTile state={hint.state} />
<div className="flex min-w-0 flex-1 flex-col gap-1">
<span className="text-content-faint" style={fs(11)}>
{t('wanderer.watch.noticeLabel')}
</span>
<div className="flex flex-wrap items-center gap-1.5">
<SourceHintPills hint={hint} />
{when && (
<span className="text-content-faint" style={fs(11)}>
{t('wanderer.watch.checkedAt', { date: when })}
</span>
)}
</div>
</div>
<CheckButton check={check} t={t} />
</div>
);
}
interface TourProvenanceSectionProps {
provenance: TourProvenance;
/** Given for a wanderer snapshot the user may change: the check of its source and the reimport. */
check?: SourceCheck;
/** WAN-02: the reader's own background hint on the source, shown until the check answers. */
hint?: TourSourceHint | null;
}
/**
@@ -189,13 +254,15 @@ interface TourProvenanceSectionProps {
* came in. For a wanderer snapshot, MF-03: the check of its source, on purpose
* and read only, and from a change the confirmed reimport as a new snapshot.
*/
export default function TourProvenanceSection({ provenance, check }: TourProvenanceSectionProps) {
export default function TourProvenanceSection({ provenance, check, hint }: TourProvenanceSectionProps) {
const { t, locale } = useTranslation();
const { source } = provenance;
const imported = source.kind !== 'trek';
const importedAt = dayOf((source.kind === 'wanderer' ? source.importedAt : null) ?? provenance.createdAt, locale);
const externalUpdated = source.kind === 'wanderer' ? dayOf(source.externalUpdated, locale) : null;
const local = <LocalState provenance={provenance} t={t} />;
// The hint carries the check button until the source answered a check, which spends it.
const openHint = check && hint && !check.answered ? hint : null;
const sourceIcon =
source.kind === 'gpx' ? (
<FileDown size={13} strokeWidth={2} />
@@ -209,27 +276,7 @@ export default function TourProvenanceSection({ provenance, check }: TourProvena
<DialogSection
className="flex-none"
label={t('tours.provenance.label')}
action={
check && (
<Tooltip label={t('tours.provenance.checkHint')}>
<span className="inline-flex">
<CardAction
icon={
check.checking ? (
<Loader2 size={12} className="animate-spin" />
) : (
<RefreshCw size={12} strokeWidth={2.2} />
)
}
onClick={() => void check.check()}
disabled={check.checking}
>
{t('tours.provenance.check')}
</CardAction>
</span>
</Tooltip>
)
}
action={check && !openHint && <CheckButton check={check} t={t} />}
>
<div className={`${BOX} divide-y divide-edge-faint`}>
<ProvenanceRow icon={sourceIcon} label={t('tours.provenance.source')}>
@@ -267,6 +314,7 @@ export default function TourProvenanceSection({ provenance, check }: TourProvena
{local}
</ProvenanceRow>
)}
{check && openHint && <HintNotice hint={openHint} check={check} locale={locale} t={t} />}
{check && <CheckResult check={check} locale={locale} t={t} />}
</div>
{check && (
@@ -287,7 +335,8 @@ export default function TourProvenanceSection({ provenance, check }: TourProvena
/**
* The section as the tour's detail places it: reads the provenance with the
* detail, and offers the source check only on a wanderer snapshot the user
* may change, where a reimport has somewhere to go.
* may change, where a reimport has somewhere to go, with the reader's own
* background hint on it (WAN-02).
*/
export function TourProvenanceBlock({
tripId,
@@ -302,7 +351,15 @@ export function TourProvenanceBlock({
}) {
const provenance = useTourProvenance(tripId, tour);
const check = useSourceCheck({ tripId, placeId: tour.place_id, onReimported });
const fromWanderer = (provenance?.origin ?? tour.origin) === 'wanderer';
const hint = useSourceHint({ tripId, placeId: tour.place_id, enabled: canCheck && fromWanderer });
if (!provenance) return null;
const checkable = canCheck && provenance.origin === 'wanderer';
return <TourProvenanceSection provenance={provenance} check={checkable ? check : undefined} />;
return (
<TourProvenanceSection
provenance={provenance}
check={checkable ? check : undefined}
hint={checkable ? hint : null}
/>
);
}
@@ -100,4 +100,33 @@ describe('useSourceCheck (MF-03)', () => {
rerender({ placeId: 8 });
expect(result.current.result).toBeNull();
});
it('remembers that the source answered for this tour, through a reimport, and not for another (WAN-02)', async () => {
const onReimported = vi.fn();
const { result, rerender } = renderHook(({ placeId }) => useSourceCheck({ tripId: 1, placeId, onReimported }), {
initialProps: { placeId: 7 },
});
expect(result.current.answered).toBe(false);
repo.checkSource.mockRejectedValueOnce({ code: 'unreachable' });
await act(async () => {
await result.current.check();
});
expect(result.current.answered).toBe(false);
await act(async () => {
await result.current.check();
});
expect(result.current.answered).toBe(true);
act(() => result.current.askReimport());
await act(async () => {
await result.current.reimport();
});
expect(result.current.result).toBeNull();
expect(result.current.answered).toBe(true);
rerender({ placeId: 8 });
expect(result.current.answered).toBe(false);
act(() => result.current.askReimport());
expect(result.current.answered).toBe(false);
});
});
@@ -25,19 +25,35 @@ export function useSourceCheck({ tripId, placeId, onReimported }: SourceCheckOpt
const [reimporting, setReimporting] = useState(false);
// The answer and the question belong to the tour they were asked for:
// another tour shown in the same dialog starts unchecked.
const [state, setState] = useState<{ placeId: number; result: TourSourceCheckResponse | null; confirming: boolean }>({
placeId,
result: null,
confirming: false,
});
// `answered` stays once the source answered for this tour, through a reimport
// too: the server then holds no background hint on it any more (WAN-02).
const [state, setState] = useState<{
placeId: number;
result: TourSourceCheckResponse | null;
confirming: boolean;
answered: boolean;
}>({ placeId, result: null, confirming: false, answered: false });
const result = state.placeId === placeId ? state.result : null;
const confirming = state.placeId === placeId && state.confirming;
const answered = state.placeId === placeId && state.answered;
const setResult = useCallback(
(next: TourSourceCheckResponse | null) => setState({ placeId, result: next, confirming: false }),
(next: TourSourceCheckResponse | null) =>
setState((current) => ({
placeId,
result: next,
confirming: false,
answered: (current.placeId === placeId && current.answered) || next !== null,
})),
[placeId]
);
const setConfirming = useCallback(
(next: boolean) => setState((current) => ({ ...current, placeId, confirming: next })),
(next: boolean) =>
setState((current) => ({
...current,
placeId,
confirming: next,
answered: current.placeId === placeId && current.answered,
})),
[placeId]
);
@@ -76,6 +92,8 @@ export function useSourceCheck({ tripId, placeId, onReimported }: SourceCheckOpt
checking,
result,
check,
/** The source answered a check of this tour; a background hint on it is spent. */
answered,
/** A reimport can be offered: the trail was read and differs, and someone takes the new snapshot in. */
canReimport: !!result?.reimport && !!onReimported,
confirming,
@@ -0,0 +1,47 @@
import { renderHook, waitFor } from '@testing-library/react';
import type { TourSourceHint } from '@trek/shared';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { useSourceHint } from './useSourceHint';
const repo = vi.hoisted(() => ({ sourceHint: vi.fn() }));
vi.mock('../../../repo/wandererRepo', () => ({ wandererRepo: repo }));
const hint: TourSourceHint = {
state: 'possible_change',
changes: [],
reason: null,
externalUpdated: '2026-10-14',
checkedAt: '2026-10-20T10:00:00Z',
};
beforeEach(() => {
vi.clearAllMocks();
repo.sourceHint.mockResolvedValue(hint);
});
describe('useSourceHint (WAN-02)', () => {
it('reads the hint of the tour it is asked for, and asks again for another tour', async () => {
const { result, rerender } = renderHook(({ placeId }) => useSourceHint({ tripId: 1, placeId, enabled: true }), {
initialProps: { placeId: 7 },
});
expect(result.current).toBeNull();
await waitFor(() => expect(result.current).toEqual(hint));
expect(repo.sourceHint).toHaveBeenCalledWith(1, 7, expect.any(AbortSignal));
repo.sourceHint.mockResolvedValue(null);
rerender({ placeId: 8 });
expect(result.current).toBeNull();
await waitFor(() => expect(repo.sourceHint).toHaveBeenCalledWith(1, 8, expect.any(AbortSignal)));
});
it('asks nothing where the hint could lead nowhere, and shows none after a failed read', async () => {
const off = renderHook(() => useSourceHint({ tripId: 1, placeId: 7, enabled: false }));
expect(off.result.current).toBeNull();
expect(repo.sourceHint).not.toHaveBeenCalled();
repo.sourceHint.mockRejectedValue(new Error('down'));
const failed = renderHook(() => useSourceHint({ tripId: 1, placeId: 7, enabled: true }));
await waitFor(() => expect(repo.sourceHint).toHaveBeenCalled());
expect(failed.result.current).toBeNull();
});
});
@@ -0,0 +1,39 @@
import type { TourSourceHint } from '@trek/shared';
import { useEffect, useState } from 'react';
import { wandererRepo } from '../../../repo/wandererRepo';
/**
* WAN-02: the reader's own background hint on a wanderer snapshot, read with
* the tour's detail when it can lead anywhere (a snapshot the reader may
* check). Null while it loads, offline, on a failed read and when the watch
* left none: a missing hint only means there is nothing to point at, never
* that the trail is unchanged.
*/
export function useSourceHint({
tripId,
placeId,
enabled,
}: {
tripId: number;
placeId: number;
enabled: boolean;
}): TourSourceHint | null {
const [state, setState] = useState<{ key: string; hint: TourSourceHint | null } | null>(null);
const key = `${tripId}|${placeId}`;
useEffect(() => {
if (!enabled) return;
const controller = new AbortController();
wandererRepo.sourceHint(tripId, placeId, controller.signal).then(
(hint) => {
if (!controller.signal.aborted) setState({ key, hint });
},
() => {
if (!controller.signal.aborted) setState({ key, hint: null });
}
);
return () => controller.abort();
}, [enabled, key, tripId, placeId]);
return enabled && state?.key === key ? state.hint : null;
}
@@ -0,0 +1,119 @@
import type { WandererSourceHintItem } from '@trek/shared';
import { ChevronRight } from 'lucide-react';
import { useId } from 'react';
import { useTranslation } from '../../../i18n';
import {
DialogButton,
DialogFooter,
DialogHeader,
DialogShell,
DialogTile,
FooterSpacer,
fs,
NEUTRAL_TINT,
} from '../../shared/DialogShell';
import { hintWhen, SourceHintPills, SourceHintTile } from './sourceHintParts';
import WandererMark from './WandererMark';
/** One hint: the tour and its trip, what the watch found, when, and the way to the tour. */
function HintRow({ hint, onOpen }: { hint: WandererSourceHintItem; onOpen: (hint: WandererSourceHintItem) => void }) {
const { t, locale } = useTranslation();
const when = hintWhen(hint.checkedAt, locale);
return (
<li>
<button
type="button"
onClick={() => onOpen(hint)}
data-testid={`wanderer-hint-${hint.placeId}`}
className="group flex w-full items-center gap-3 rounded-[14px] border border-edge-faint bg-surface-card px-3 py-2.5 text-start transition-colors hover:bg-surface-hover focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent"
>
<SourceHintTile state={hint.state} />
<span className="flex min-w-0 flex-1 flex-col gap-1">
<span className="flex min-w-0 items-baseline gap-2">
<span className="min-w-0 truncate font-semibold text-content" style={fs(13, 'body')}>
{hint.tourName}
</span>
<span className="min-w-0 truncate text-content-faint" style={fs(11.5)}>
{hint.tripTitle}
</span>
</span>
<span className="flex flex-wrap items-center gap-1.5">
<SourceHintPills hint={hint} />
{when && (
<span className="text-content-faint" style={fs(11)}>
{t('wanderer.watch.checkedAt', { date: when })}
</span>
)}
</span>
</span>
<span className="sr-only">{t('wanderer.watch.openTour')}</span>
<ChevronRight
size={15}
strokeWidth={2.2}
aria-hidden="true"
className="flex-none text-content-faint transition-transform group-hover:translate-x-0.5 rtl:rotate-180 rtl:group-hover:-translate-x-0.5"
/>
</button>
</li>
);
}
/**
* WAN-02: the open hints of the user's wanderer watch, each leading to its
* tour, where the source check shows what really changed. Reading only: the
* dialog changes nothing, and a hint goes once its source was checked.
*/
export default function WandererHintsDialog({
open,
hints,
onClose,
onOpenTour,
}: {
open: boolean;
hints: readonly WandererSourceHintItem[];
onClose: () => void;
onOpenTour: (hint: WandererSourceHintItem) => void;
}) {
const { t } = useTranslation();
const labelId = useId();
return (
<DialogShell
open={open}
onClose={onClose}
labelledBy={labelId}
width="detail"
header={
<DialogHeader
tile={
<DialogTile>
<WandererMark size={22} />
</DialogTile>
}
tint={NEUTRAL_TINT}
labelId={labelId}
onClose={onClose}
title={t('wanderer.watch.dialogTitle')}
sub={t('wanderer.watch.hintsCount', { count: hints.length })}
/>
}
footer={
<DialogFooter>
<FooterSpacer />
<DialogButton onClick={onClose}>{t('common.close')}</DialogButton>
</DialogFooter>
}
>
{hints.length === 0 ? (
<p className="m-0 text-center text-content-muted" style={fs(12.5, 'body')}>
{t('wanderer.watch.empty')}
</p>
) : (
<ul className="m-0 flex list-none flex-col gap-2 p-0">
{hints.map((hint) => (
<HintRow key={hint.placeId} hint={hint} onOpen={onOpenTour} />
))}
</ul>
)}
</DialogShell>
);
}
@@ -0,0 +1,24 @@
import { render, screen } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import { hintWhen, SourceHintPills, SourceHintTile } from './sourceHintParts';
// Rendered without the translation provider: every text reads as its key.
describe('sourceHintParts (WAN-02)', () => {
it('names a possible change apart from a proven one, with the reason a source could not be judged', () => {
const { rerender } = render(<SourceHintPills hint={{ state: 'possible_change', changes: [], reason: null }} />);
expect(screen.getByTestId('source-hint-state')).toHaveAttribute('data-state', 'possible_change');
expect(screen.getByText('wanderer.watch.state.possible_change')).toBeInTheDocument();
rerender(<SourceHintPills hint={{ state: 'unverifiable', changes: [], reason: 'no_change_time' }} />);
expect(screen.getByText('wanderer.watch.state.unverifiable')).toBeInTheDocument();
expect(screen.getByText('wanderer.watch.reason.no_change_time')).toBeInTheDocument();
});
it('marks the tile with the state, and reads a stored instant or nothing', () => {
const { container } = render(<SourceHintTile state="changed" />);
expect(container.querySelector('.text-warning')).not.toBeNull();
expect(hintWhen(null, 'en')).toBeNull();
expect(hintWhen('not a time', 'en')).toBeNull();
expect(hintWhen('2026-10-20T10:00:00Z', 'en')).toEqual(expect.stringContaining('Oct'));
});
});
@@ -0,0 +1,63 @@
import type { TourSourceHint, TourSourceHintState } from '@trek/shared';
import { HelpCircle, History, PenLine, type LucideIcon } from 'lucide-react';
import { useTranslation } from '../../../i18n';
import { SoftPill } from '../../Planner/planParts';
import { Tooltip } from '../../shared/Tooltip';
import WandererMark from './WandererMark';
/**
* WAN-02: how a hint of the wanderer watch looks wherever it shows (the
* settings list, a tour's provenance): one tone and one icon per state, so a
* possible change never reads like a proven one.
*/
const HINT_LOOK: Record<TourSourceHintState, { tone: 'info' | 'warning' | 'neutral'; text: string; Icon: LucideIcon }> =
{
possible_change: { tone: 'info', text: 'text-info', Icon: History },
changed: { tone: 'warning', text: 'text-warning', Icon: PenLine },
unverifiable: { tone: 'neutral', text: 'text-content-muted', Icon: HelpCircle },
};
/** The state as a pill with its meaning in the tooltip, then what the record proves changed or why it could not judge. */
export function SourceHintPills({ hint }: { hint: Pick<TourSourceHint, 'state' | 'changes' | 'reason'> }) {
const { t } = useTranslation();
const look = HINT_LOOK[hint.state];
return (
<>
<Tooltip label={t(`wanderer.watch.stateHint.${hint.state}`)}>
<span className="inline-flex" data-testid="source-hint-state" data-state={hint.state}>
<SoftPill tone={look.tone} icon={<look.Icon size={10} strokeWidth={2.4} />}>
{t(`wanderer.watch.state.${hint.state}`)}
</SoftPill>
</span>
</Tooltip>
{hint.changes.map((part) => (
<SoftPill key={part}>{t(`tours.provenance.change.${part}`)}</SoftPill>
))}
{hint.reason && <SoftPill>{t(`wanderer.watch.reason.${hint.reason}`)}</SoftPill>}
</>
);
}
/** The wanderer emblem on a raised round tile, with the state's icon as a badge on its corner. */
export function SourceHintTile({ state }: { state: TourSourceHintState }) {
const look = HINT_LOOK[state];
return (
<span className="relative grid h-9 w-9 flex-none place-items-center rounded-full bg-surface-card text-content-secondary shadow-sm ring-1 ring-inset ring-edge-faint">
<WandererMark size={17} />
<span
aria-hidden="true"
className={`absolute -bottom-1 -end-1 grid h-4 w-4 place-items-center rounded-full bg-surface-card shadow-sm ring-2 ring-[color:var(--bg-card)] ${look.text}`}
>
<look.Icon size={9} strokeWidth={2.6} />
</span>
</span>
);
}
/** A stored instant as the reader's day and time; the hints say when the watch last looked. */
export function hintWhen(iso: string | null, locale: string): string | null {
if (!iso) return null;
const date = new Date(iso);
if (Number.isNaN(date.getTime())) return null;
return date.toLocaleString(locale, { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' });
}