feat(assistant): one AI tile for assistant, parsing and MCP, a planner-aware chat

The three AI addons share one tile in the integration column; a dialog holds
the connection, the assistant's limits and AI parsing, which now reads with
the assistant's connection unless an install keeps its own. Existing parsing
configs stay where they are and keep winning.

The chat sees the map on screen, offers next questions under an answer,
shows its live step in the window head, previews waiting changes inside the
day list, checks whether a day still works, folds a multi-day plan into a
week grid, keeps per-trip notes and can estimate costs. An empty or cut-off
answer gets one push instead of ending silently, and the assistant's own
step and size limits are raised.
This commit is contained in:
Maurice
2026-10-21 20:55:06 +02:00
parent b64da26651
commit 123e27643d
142 changed files with 5456 additions and 1572 deletions
@@ -226,10 +226,13 @@ describe('AssistantChangeCard: on the map', () => {
expect(row).toHaveClass('bg-surface-hover');
});
it('FE-AI-CARD-009: the days a waiting card touches read as a band, with the schedule folded away', () => {
it('FE-AI-CARD-009: the days a waiting card touches read as named stops, with the schedule folded away', () => {
plannerHere();
renderCard([onTheMap('c1', 'Pantheon')]);
expect(screen.getByText('Rome')).toBeInTheDocument();
// Folded, each stop is a chip with its name, not a blank block behind a tooltip.
expect(screen.getByText('Louvre')).toBeInTheDocument();
expect(screen.getAllByText('Pantheon')).toHaveLength(2);
expect(screen.queryByText('New')).toBeNull();
fireEvent.click(screen.getByRole('button', { name: 'Show schedule' }));
@@ -25,14 +25,16 @@ import { blockKeyOf } from '../../store/assistantMapModel';
import { chatOf, useAssistantStore } from '../../store/assistantStore';
import { useTripStore } from '../../store/tripStore';
import ToggleSwitch from '../Settings/ToggleSwitch';
import { Tooltip } from '../shared/Tooltip';
import { useToast } from '../shared/Toast';
import { Tooltip } from '../shared/Tooltip';
import AssistantCompareSwitch from './AssistantCompareSwitch';
import AssistantDayBand from './AssistantDayBand';
import AssistantWeekOverview from './AssistantWeekOverview';
import { CHANGE_LABELS, type ChangeItem, type ChangeState, undoLeftMs } from './assistantParts';
import { useAssistantView } from './assistantViewContext';
import { changePoints, type DayChange } from './dayAfterModel';
import { useChangeHover } from './useChangeHover';
import { useWeekDays } from './useWeekDays';
/**
* The changes the assistant proposes in one go, as one card in plain words:
@@ -235,7 +237,11 @@ function Receipt({
</Tooltip>
)}
<Tooltip label={statusLabel} placement="top">
<span role="img" aria-label={statusLabel} className={`flex h-7 w-5 items-center justify-center ${receipt.tone}`}>
<span
role="img"
aria-label={statusLabel}
className={`flex h-7 w-5 items-center justify-center ${receipt.tone}`}
>
<Icon size={15} strokeWidth={2.4} className={item.state === 'applying' ? 'animate-spin' : ''} />
</span>
</Tooltip>
@@ -392,6 +398,21 @@ export default function AssistantChangeCard({ items }: { items: ChangeItem[] })
const changes = useMemo(() => dayChangesOf(items, excluded), [items, excluded]);
const undoable = items.filter((i) => undoableNow(i, undone, now)).map((i) => i.toolCallId);
const week = useWeekDays(pending);
const [showAll, setShowAll] = useState(false);
// A plan over a week reads from its grid; the single changes wait behind one line.
const folded = week.length > 0 && !showAll;
const toggleDay = (ids: readonly string[], include: boolean) =>
setExcluded((prev) => {
const next = new Set(prev);
for (const id of ids) {
if (include) next.delete(id);
else next.add(id);
}
return next;
});
const toggle = (toolCallId: string) =>
setExcluded((prev) => {
const next = new Set(prev);
@@ -420,18 +441,32 @@ export default function AssistantChangeCard({ items }: { items: ChangeItem[] })
count={items.length}
actions={<HeadActions open={open} items={items} changes={changes} undoable={undoable} />}
/>
{open && <AssistantDayBand changes={changes} />}
{open && week.length > 0 && (
<AssistantWeekOverview days={week} excluded={excluded} disabled={isRunning} onToggleDay={toggleDay} />
)}
{open && !folded && <AssistantDayBand changes={changes} />}
{folded && (
<button
type="button"
onClick={() => setShowAll(true)}
className="mb-1 w-full rounded-lg px-2 py-1.5 text-center text-caption font-medium text-content-muted transition-colors hover:bg-surface-hover hover:text-content"
>
{t('assistant.week.showAll', { count: pending.length })}
</button>
)}
<div className={open ? 'divide-y divide-edge-faint' : ''}>
{items.map((item) =>
item.state === 'pending' ? (
<PendingRow
key={item.toolCallId}
item={item}
excluded={excluded.has(item.toolCallId)}
withSwitch={pending.length > 1}
disabled={isRunning}
onToggle={() => toggle(item.toolCallId)}
/>
folded ? null : (
<PendingRow
key={item.toolCallId}
item={item}
excluded={excluded.has(item.toolCallId)}
withSwitch={pending.length > 1}
disabled={isRunning}
onToggle={() => toggle(item.toolCallId)}
/>
)
) : (
<Receipt
key={item.toolCallId}
@@ -111,7 +111,7 @@ export default function AssistantComposer({ tripId, tripTitle }: { tripId: numbe
onPaste={(e) => {
if (e.clipboardData.files.length > 0 && take(e.clipboardData.files)) e.preventDefault();
}}
className="max-h-48 min-h-[36px] flex-1 resize-none bg-transparent px-1.5 py-1.5 text-body text-content outline-none placeholder:text-content-faint disabled:cursor-not-allowed"
className="max-h-48 min-h-[36px] flex-1 resize-none bg-transparent px-1.5 py-1.5 text-body text-content outline-none placeholder:text-content-faint disabled:cursor-not-allowed dark:bg-transparent"
/>
<AuiIf condition={(s) => s.thread.isRunning}>
<ComposerPrimitive.Cancel
@@ -1,4 +1,4 @@
import { ChevronDown, TriangleAlert } from 'lucide-react';
import { ChevronDown, CircleCheck, TriangleAlert } from 'lucide-react';
import { useMemo, useState } from 'react';
import { useShallow } from 'zustand/react/shallow';
@@ -7,38 +7,49 @@ import { useTripStore } from '../../store/tripStore';
import { dayLabel } from '../../utils/dayLabel';
import { Tooltip } from '../shared/Tooltip';
import { useAssistantView } from './assistantViewContext';
import { buildDayAfter, changedDays, type DayAfter, type DayChange, type TimelineStop } from './dayAfterModel';
import {
buildDayAfter,
changedDays,
type DayAfter,
type DayChange,
dayIssues,
stopIssue,
type TimelineStop,
} from './dayAfterModel';
import { useChangeHover } from './useChangeHover';
/**
* The days a waiting card touches, as they would read once it ran: one thin
* band per day with a block per stop, so a glance shows where the suggestion
* lands among the rest. The details (times, the way between stops, free time,
* a clash) stay folded away until asked for. Two days at most; the rest are
* counted. Shown only while the planner holds this trip, since the day plans
* come from it.
* The days a waiting card touches, as they would read once it ran: per day its
* date and its stops in order as small named chips, so a glance shows where the
* suggestion lands among the rest. The details (times, the way between stops,
* free time, a clash) stay folded away until asked for. Two days at most; the
* rest are counted. Shown only while the planner holds this trip, since the day
* plans come from it.
*/
/** Days drawn as a band; the rest are counted. */
/** Days shown; the rest are counted. */
const MAX_DAYS = 2;
/** Stops shown as chips on a day; the rest are counted. */
const MAX_CHIPS = 6;
const SEGMENT: Record<TimelineStop['status'], string> = {
kept: 'bg-surface-secondary',
new: 'border border-dashed border-success bg-success-soft',
removed: 'border border-edge-faint opacity-50',
const CHIP: Record<TimelineStop['status'], string> = {
kept: 'border-transparent bg-surface-secondary text-content-muted',
new: 'border-dashed border-success bg-success-soft text-content',
removed: 'border-transparent text-content-faint line-through',
};
function Segment({ stop }: { stop: TimelineStop }) {
/** One stop of the day, named; the change it belongs to lights up with it. */
function StopChip({ stop }: { stop: TimelineStop }) {
const { tripId } = useAssistantView();
const { lit, handlers } = useChangeHover(tripId, stop.toolCallId);
const clash = stop.lead?.overlapsWith ? 'ring-1 ring-inset ring-danger' : '';
const clash = stop.lead?.overlapsWith ? 'border-danger' : stopIssue(stop) ? 'border-warning' : '';
return (
<Tooltip label={stop.name} placement="top">
<span
{...(stop.toolCallId ? handlers : {})}
className={`h-full min-w-[6px] flex-1 rounded-sm transition-shadow ${SEGMENT[stop.status]} ${clash} ${lit ? 'ring-2 ring-inset ring-accent' : ''}`}
/>
</Tooltip>
<span
{...(stop.toolCallId ? handlers : {})}
className={`inline-flex max-w-[11rem] items-center rounded-full border px-2 py-0.5 text-caption transition-colors ${CHIP[stop.status]} ${clash} ${lit ? 'bg-surface-hover' : ''}`}
>
<bdi className="truncate">{stop.name}</bdi>
</span>
);
}
@@ -47,13 +58,19 @@ function Lead({ stop, timed }: { stop: TimelineStop; timed: boolean }) {
const lead = stop.lead;
if (!lead) return null;
const travel = lead.travelMinutes !== null && lead.travelMinutes > 0;
if (!travel && lead.freeMinutes === null && !lead.overlapsWith) return null;
if (!travel && lead.freeMinutes === null && !lead.overlapsWith && lead.shortBy === null) return null;
return (
<li
className={`flex flex-wrap items-center gap-x-2 text-caption text-content-faint ${timed ? 'ps-[3.25rem]' : 'ps-1'}`}
>
{travel && <span>{t('assistant.change.timeline.travel', { count: lead.travelMinutes ?? 0 })}</span>}
{lead.freeMinutes !== null && <span>{t('assistant.change.timeline.gap', { count: lead.freeMinutes })}</span>}
{lead.shortBy !== null && (
<span className="inline-flex items-center gap-1 font-medium text-warning">
<TriangleAlert size={11} aria-hidden="true" className="flex-shrink-0" />
{t('assistant.change.timeline.tight', { count: lead.shortBy })}
</span>
)}
{lead.overlapsWith && (
<span className="inline-flex items-center gap-1 text-content-muted">
<TriangleAlert size={11} aria-hidden="true" className="flex-shrink-0 text-danger" />
@@ -91,16 +108,20 @@ function StopLine({ stop, timed }: { stop: TimelineStop; timed: boolean }) {
function DayRow({ day, label, open }: { day: DayAfter; label: string; open: boolean }) {
const timed = day.stops.some((s) => s.time !== null);
const chips = day.stops.slice(0, MAX_CHIPS);
return (
<div>
<div className="flex items-center gap-2">
<bdi className="w-16 flex-shrink-0 truncate text-caption text-content-muted">{label}</bdi>
<div className="flex h-6 min-w-0 flex-1 gap-0.5 overflow-hidden" aria-hidden="true">
{day.stops.map((stop) => (
<Segment key={stop.key} stop={stop} />
<bdi className="block truncate text-caption font-medium text-content-muted">{label}</bdi>
{!open && (
<div className="mt-1 flex min-w-0 flex-wrap items-center gap-1">
{chips.map((stop) => (
<StopChip key={stop.key} stop={stop} />
))}
{day.stops.length > MAX_CHIPS && (
<span className="text-caption tabular-nums text-content-faint">+{day.stops.length - MAX_CHIPS}</span>
)}
</div>
</div>
)}
{open && (
<ol className="trek-assistant-enter mt-1 space-y-0.5" aria-label={label}>
{day.stops.map((stop) => (
@@ -153,6 +174,8 @@ export default function AssistantDayBand({ changes }: { changes: readonly DayCha
if (rows.length === 0) return null;
const shown = rows.slice(0, MAX_DAYS);
const issues = rows.reduce((sum, row) => sum + dayIssues(row.after), 0);
const measured = rows.some((row) => row.after.stops.some((stop) => stop.lead?.travelMinutes != null));
const toggleLabel = t(open ? 'assistant.change.timeline.hide' : 'assistant.change.timeline.show');
return (
<div className="mb-1 flex gap-1.5">
@@ -161,18 +184,31 @@ export default function AssistantDayBand({ changes }: { changes: readonly DayCha
<DayRow key={after.dayId} day={after} label={label} open={open} />
))}
{rows.length > MAX_DAYS && (
<p className="ps-[4.5rem] text-caption text-content-faint">
<p className="text-caption text-content-faint">
{t('assistant.change.timeline.moreDays', { count: rows.length - MAX_DAYS })}
</p>
)}
</div>
{(issues > 0 || measured) && (
// What the check found, at a glance; a tap opens the schedule that says where.
<button
type="button"
onClick={() => setOpen(true)}
className={`inline-flex h-6 flex-shrink-0 items-center gap-1 self-start rounded-full px-2 text-caption font-medium transition-colors ${
issues > 0 ? 'bg-warning-soft text-warning hover:brightness-95' : 'bg-success-soft text-success'
}`}
>
{issues > 0 ? <TriangleAlert size={12} aria-hidden="true" /> : <CircleCheck size={12} aria-hidden="true" />}
{issues > 0 ? t('assistant.check.issues', { count: issues }) : t('assistant.check.ok')}
</button>
)}
<Tooltip label={toggleLabel} placement="top">
<button
type="button"
onClick={() => setOpen((v) => !v)}
aria-expanded={open}
aria-label={toggleLabel}
className="flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-md text-content-muted transition-colors hover:bg-surface-hover hover:text-content"
className="flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-full text-content-muted outline-none transition-colors hover:bg-surface-hover hover:text-content focus-visible:ring-2 focus-visible:ring-accent"
>
<ChevronDown
size={14}
@@ -0,0 +1,137 @@
import type { AssistantChangeEffect, AssistantMessage } from '@trek/shared';
import { ArrowRightLeft, Minus, Sparkles } from 'lucide-react';
import { useMemo } from 'react';
import { useShallow } from 'zustand/react/shallow';
import { useTranslation } from '../../i18n';
import { changeEffects } from '../../store/assistantMapModel';
import { chatOf, useAssistantStore } from '../../store/assistantStore';
import { useTripStore } from '../../store/tripStore';
/** What a waiting change does to one day, as a row of the preview. */
interface PreviewRow {
toolCallId: string;
kind: 'add' | 'in' | 'remove' | 'out';
name: string;
}
/** The changes no one has decided on yet, by their call. */
function waitingCalls(messages: readonly AssistantMessage[]): Set<string> {
const ids = new Set<string>();
for (const m of messages) {
for (const p of m.parts) {
if (p.type === 'tool-call' && p.approval && !p.approval.resolution && p.approval.approved === undefined) {
ids.add(p.toolCallId);
}
}
}
return ids;
}
function rowOf(
toolCallId: string,
effect: AssistantChangeEffect,
dayId: number,
nameOf: (id: number | null) => string | null
) {
const name = effect.place?.name ?? nameOf(effect.placeId);
if (!name) return null;
if (effect.dayId === dayId) {
const kind = effect.kind === 'remove' ? 'remove' : effect.kind === 'move' ? 'in' : 'add';
return { toolCallId, kind, name } satisfies PreviewRow;
}
if (effect.kind === 'move' && effect.fromDayId === dayId)
return { toolCallId, kind: 'out', name } satisfies PreviewRow;
return null;
}
const LOOK: Record<PreviewRow['kind'], { icon: typeof Sparkles; row: string; name: string; badgeKey: string }> = {
add: {
icon: Sparkles,
row: 'border-dashed border-accent bg-accent-subtle',
name: 'text-content',
badgeKey: 'assistant.preview.suggested',
},
in: {
icon: ArrowRightLeft,
row: 'border-dashed border-accent bg-accent-subtle',
name: 'text-content',
badgeKey: 'assistant.preview.movedHere',
},
remove: {
icon: Minus,
row: 'border-dashed border-edge',
name: 'text-content-faint line-through',
badgeKey: 'assistant.preview.removed',
},
out: {
icon: ArrowRightLeft,
row: 'border-dashed border-edge',
name: 'text-content-faint line-through',
badgeKey: 'assistant.preview.movedAway',
},
};
/**
* The assistant's waiting changes inside the day they touch, in the planner's
* own day list: a place it would add as a dashed row, one it would take off
* struck through, a move on both of its days. Resting on a row lights the
* change's pin and card; a click brings the chat forward to decide. Nothing
* here writes; the change card stays the one place a change is applied.
*/
export default function AssistantDayPreview({ tripId, dayId }: { tripId: number; dayId: number }) {
const { t } = useTranslation();
const messages = useAssistantStore((s) => chatOf(s, tripId).messages);
const hovered = useAssistantStore((s) => (s.mapLink?.tripId === tripId ? s.mapLink.hoveredId : null));
const { setMapHover, open } = useAssistantStore(useShallow((s) => ({ setMapHover: s.setMapHover, open: s.open })));
const places = useTripStore((s) => s.places);
const rows = useMemo(() => {
const waiting = waitingCalls(messages);
if (waiting.size === 0) return [];
const nameOf = (id: number | null) => (id === null ? null : (places.find((p) => p.id === id)?.name ?? null));
const out: PreviewRow[] = [];
for (const [toolCallId, effect] of changeEffects(messages)) {
if (!waiting.has(toolCallId)) continue;
const row = rowOf(toolCallId, effect, dayId, nameOf);
if (row) out.push(row);
}
return out;
}, [messages, places, dayId]);
if (rows.length === 0) return null;
return (
<ul className="m-0 flex list-none flex-col gap-1 px-3 pb-2 pt-1" aria-label={t('assistant.preview.title')}>
{rows.map((row, i) => {
const look = LOOK[row.kind];
const Icon = look.icon;
const lit = hovered === row.toolCallId;
return (
<li
key={`${row.toolCallId}-${row.kind}`}
className="trek-assistant-enter"
style={{ animationDelay: `${i * 50}ms` }}
>
<button
type="button"
onClick={open}
onMouseEnter={() => setMapHover(tripId, row.toolCallId, 'card')}
onMouseLeave={() => setMapHover(tripId, null, 'card')}
className={`flex w-full items-center gap-2 rounded-xl border px-2.5 py-1.5 text-start transition-all ${look.row} ${
lit ? 'shadow-md ring-2 ring-accent' : 'hover:shadow-sm'
}`}
>
<span className="grid h-6 w-6 flex-shrink-0 place-items-center rounded-lg bg-surface-card text-content-muted shadow-sm">
<Icon size={12} aria-hidden="true" />
</span>
<bdi className={`min-w-0 flex-1 truncate text-caption font-medium ${look.name}`}>{row.name}</bdi>
<span className="flex-shrink-0 rounded-full bg-surface-card px-2 py-0.5 text-caption text-content-muted shadow-sm">
{t(look.badgeKey)}
</span>
</button>
</li>
);
})}
</ul>
);
}
@@ -0,0 +1,58 @@
import type { AssistantMessage } from '@trek/shared';
import { CornerDownRight } from 'lucide-react';
import { useTranslation } from '../../i18n';
import { chatOf, useAssistantStore } from '../../store/assistantStore';
import { useCanDo } from '../../store/permissionsStore';
import { useTripStore } from '../../store/tripStore';
import { followUpsFor } from './assistantFollowUpRules';
import { hasUndecided } from './assistantParts';
import { useAssistantView } from './assistantViewContext';
/** Each chip comes in a moment after the one before it. */
const STAGGER_MS = 60;
/**
* The next questions under the latest answer, one tap each. Only under the
* last answer, once it is written, and not while changes wait for a decision:
* then the cards are what to answer.
*/
export default function AssistantFollowUps({ message }: { message: AssistantMessage }) {
const { t } = useTranslation();
const { tripId } = useAssistantView();
const can = useCanDo();
const trip = useTripStore((s) => (s.trip?.id === tripId ? s.trip : null));
const send = useAssistantStore((s) => s.send);
const shown = useAssistantStore((s) => {
const chat = chatOf(s, tripId);
const last = chat.messages[chat.messages.length - 1];
return !chat.isRunning && !chat.error && last?.id === message.id && !hasUndecided(chat.messages);
});
if (!shown) return null;
const chips = followUpsFor(message, !!trip && can('place_edit', trip));
if (chips.length === 0) return null;
return (
<div role="group" aria-label={t('assistant.followUp.title')} className="flex flex-wrap gap-1.5 pt-0.5">
{chips.map((chip, i) => {
const text = t(chip.labelKey);
return (
<button
key={chip.id}
type="button"
onClick={() => void send(tripId, text)}
className="trek-assistant-enter group/chip inline-flex max-w-full items-center gap-1.5 rounded-full bg-surface-card px-3 py-1.5 text-caption font-medium text-content-secondary shadow-sm ring-1 ring-edge-faint transition-all hover:-translate-y-px hover:text-content hover:shadow-md hover:ring-edge active:translate-y-0"
style={{ animationDelay: `${i * STAGGER_MS}ms` }}
>
<CornerDownRight
size={12}
aria-hidden="true"
className="flex-shrink-0 text-content-faint transition-colors group-hover/chip:text-content rtl:-scale-x-100"
/>
<span className="truncate">{text}</span>
</button>
);
})}
</div>
);
}
@@ -1,24 +1,28 @@
import { Ellipsis, History, Lightbulb, LightbulbOff, Plus, Settings, Trash2, X } from 'lucide-react';
import { Ellipsis, History, Lightbulb, LightbulbOff, NotebookPen, Plus, Settings, Trash2, X } from 'lucide-react';
import { type HTMLAttributes, type MouseEvent, useState } from 'react';
import { useNavigate } from 'react-router';
import { useTranslation } from '../../i18n';
import { PopoverItem } from '../Packing/PackingPopover';
import ConfirmDialog from '../shared/ConfirmDialog';
import { NEUTRAL_TINT } from '../shared/DialogShell';
import { ContextMenu, useContextMenu } from '../shared/ContextMenu';
import { NEUTRAL_TINT } from '../shared/DialogShell';
import Tooltip from '../shared/Tooltip';
import { PopoverListPanel } from '../shared/dialogParts';
import { usePopoverList } from '../shared/usePopoverList';
import AssistantMemoryDialog from './AssistantMemoryDialog';
import { AI_SETTINGS_PATH } from './assistantParts';
import { useAssistantHintsSetting } from './useAssistantHints';
import { useAssistantLiveStep } from './useAssistantLiveStep';
import type { useAssistantThread } from './useAssistantThread';
import { useTripMemory } from './useTripMemory';
// The round, raised buttons of TREK's dialog heads.
const ICON_BUTTON =
'grid h-7 w-7 place-items-center rounded-full bg-surface-card text-content-muted shadow-sm transition-colors hover:text-content';
interface AssistantHeaderProps {
tripId: number;
thread: ReturnType<typeof useAssistantThread>;
tripTitle: string;
onClose: () => void;
@@ -34,8 +38,11 @@ interface AssistantHeaderProps {
* keeps the conversation, and an answer being written goes on. The model is not picked here;
* that lives in the settings.
*/
export default function AssistantHeader({ thread, tripTitle, onClose, dragProps }: AssistantHeaderProps) {
export default function AssistantHeader({ tripId, thread, tripTitle, onClose, dragProps }: AssistantHeaderProps) {
const { t, locale } = useTranslation();
const live = useAssistantLiveStep(tripId);
const memory = useTripMemory(tripId);
const [memoryOpen, setMemoryOpen] = useState(false);
const navigate = useNavigate();
const menu = useContextMenu();
const [confirming, setConfirming] = useState(false);
@@ -90,9 +97,20 @@ export default function AssistantHeader({ thread, tripTitle, onClose, dragProps
className="flex min-w-0 flex-1 cursor-grab touch-none select-none items-center active:cursor-grabbing"
>
<div className="min-w-0 flex-1">
<p className="m-0 truncate font-geist text-caption font-bold uppercase tracking-[.08em] text-content-muted">
{t('assistant.launcher.tooltip')}
</p>
{thread.isRunning ? (
// While it works, the line over the title says what it does right now.
<p role="status" className="m-0 flex min-w-0 items-center gap-1.5 text-caption font-medium">
<span
aria-hidden="true"
className="trek-assistant-pulse h-1.5 w-1.5 flex-shrink-0 rounded-full bg-accent"
/>
<span className="trek-assistant-shimmer truncate">{live?.text ?? t('assistant.step.working')}</span>
</p>
) : (
<p className="m-0 truncate font-geist text-caption font-bold uppercase tracking-[.08em] text-content-muted">
{t('assistant.launcher.tooltip')}
</p>
)}
<h2 className="m-0 truncate text-body font-bold tracking-[-0.01em] text-content">
<bdi>{thread.title ?? tripTitle}</bdi>
</h2>
@@ -104,6 +122,22 @@ export default function AssistantHeader({ thread, tripTitle, onClose, dragProps
onPointerDown={(e) => e.stopPropagation()}
onDoubleClick={(e) => e.stopPropagation()}
>
<Tooltip label={t(memory.has ? 'assistant.memory.edit' : 'assistant.memory.title')}>
<button
type="button"
onClick={() => setMemoryOpen(true)}
aria-label={t('assistant.memory.title')}
className={`relative ${ICON_BUTTON}`}
>
<NotebookPen size={13} aria-hidden="true" />
{memory.has && (
<span
aria-hidden="true"
className="absolute -end-0.5 -top-0.5 h-2 w-2 rounded-full bg-accent ring-2 ring-[color:var(--bg-elevated)]"
/>
)}
</button>
</Tooltip>
<Tooltip label={t('assistant.history.open')}>
<button
ref={history.triggerRef}
@@ -167,6 +201,7 @@ export default function AssistantHeader({ thread, tripTitle, onClose, dragProps
</PopoverListPanel>
<ContextMenu menu={menu.menu} onClose={menu.close} />
{memoryOpen && <AssistantMemoryDialog tripId={tripId} onClose={() => setMemoryOpen(false)} />}
<ConfirmDialog
isOpen={confirming}
onClose={() => setConfirming(false)}
@@ -0,0 +1,112 @@
import { NotebookPen, Plus } from 'lucide-react';
import { useId, useState } from 'react';
import { useTranslation } from '../../i18n';
import {
DialogButton,
DialogFooter,
DialogHeader,
DialogSection,
DialogShell,
DialogTile,
FooterSpacer,
NEUTRAL_TINT,
} from '../shared/DialogShell';
import { TEXTAREA } from '../shared/dialogParts';
import { MAX_MEMORY_CHARS, useTripMemory } from './useTripMemory';
/** What travellers most often want minded, one tap to add each. */
const QUICK = ['vegetarian', 'kids', 'budget', 'slow', 'accessible', 'noMuseums'] as const;
/**
* The trip's notes for the assistant: a few lines it follows in every
* suggestion on this trip, written once instead of in every question. The
* common ones are a tap away; the rest is free text.
*/
export default function AssistantMemoryDialog({ tripId, onClose }: { tripId: number; onClose: () => void }) {
const { t } = useTranslation();
const labelId = useId();
const memory = useTripMemory(tripId);
const [draft, setDraft] = useState(memory.text);
const [saving, setSaving] = useState(false);
const add = (line: string) =>
setDraft((prev) => (prev.includes(line) ? prev : `${prev.trimEnd()}${prev.trim() ? '\n' : ''}${line}`));
const save = async () => {
setSaving(true);
const done = await memory.save(draft);
setSaving(false);
if (done) onClose();
};
return (
<DialogShell
onClose={onClose}
labelledBy={labelId}
width="narrow"
discardGuard={draft}
header={
<DialogHeader
tile={
<DialogTile>
<NotebookPen size={20} strokeWidth={2} />
</DialogTile>
}
tint={NEUTRAL_TINT}
labelId={labelId}
eyebrow={t('assistant.launcher.tooltip')}
title={t('assistant.memory.title')}
sub={t('assistant.memory.sub')}
subWraps
onClose={onClose}
/>
}
footer={
<DialogFooter>
<span className="text-caption tabular-nums text-content-faint">
{draft.length}/{MAX_MEMORY_CHARS}
</span>
<FooterSpacer />
<DialogButton onClick={onClose}>{t('common.cancel')}</DialogButton>
<DialogButton variant="primary" disabled={saving} onClick={() => void save()}>
{t(saving ? 'common.saving' : 'common.save')}
</DialogButton>
</DialogFooter>
}
>
<DialogSection label={t('assistant.memory.quick')}>
<div className="flex flex-wrap gap-1.5">
{QUICK.map((key, i) => {
const line = t(`assistant.memory.quick.${key}`);
const taken = draft.includes(line);
return (
<button
key={key}
type="button"
disabled={taken}
onClick={() => add(line)}
className="trek-assistant-enter inline-flex items-center gap-1 rounded-full bg-surface-card px-2.5 py-1 text-caption font-medium text-content-secondary shadow-sm ring-1 ring-edge-faint transition-all hover:-translate-y-px hover:text-content hover:shadow-md disabled:translate-y-0 disabled:opacity-40 disabled:shadow-none"
style={{ animationDelay: `${i * 40}ms` }}
>
<Plus size={11} aria-hidden="true" />
{line}
</button>
);
})}
</div>
</DialogSection>
<DialogSection label={t('assistant.memory.notes')}>
<textarea
aria-label={t('assistant.memory.notes')}
rows={6}
maxLength={MAX_MEMORY_CHARS}
value={draft}
onChange={(e) => setDraft(e.target.value)}
placeholder={t('assistant.memory.placeholder')}
className={TEXTAREA}
/>
</DialogSection>
</DialogShell>
);
}
@@ -7,6 +7,7 @@ import { useTranslation } from '../../i18n';
import { chatOf, useAssistantStore } from '../../store/assistantStore';
import { Tooltip } from '../shared/Tooltip';
import AssistantChangeCard from './AssistantChangeCard';
import AssistantFollowUps from './AssistantFollowUps';
import AssistantMarkdown from './AssistantMarkdown';
import AssistantMentionText from './AssistantMentionText';
import AssistantPlaceStrip from './AssistantPlaceStrip';
@@ -74,7 +75,9 @@ function AttachmentChip({ name, size }: { name: string; size: number }) {
</span>
<span className="flex min-w-0 flex-col">
<bdi className="truncate text-body font-medium text-content">{name}</bdi>
<span className="text-caption tabular-nums text-content-muted">{kb >= 1024 ? `${(kb / 1024).toFixed(1)} MB` : `${kb} KB`}</span>
<span className="text-caption tabular-nums text-content-muted">
{kb >= 1024 ? `${(kb / 1024).toFixed(1)} MB` : `${kb} KB`}
</span>
</span>
</span>
);
@@ -149,6 +152,7 @@ function Answer({ message }: { message: StoredMessage }) {
</div>
)}
{share.canShare && <AssistantShareDialog share={share} />}
<AssistantFollowUps message={message} />
</MessagePrimitive.Root>
);
}
@@ -1,9 +1,8 @@
import type { AssistantFoundPlace } from '@trek/shared';
import { Check, ChevronDown, LoaderCircle, MapPin, Plus } from 'lucide-react';
import { Check, ChevronDown, LoaderCircle, MapPin, Plus, Star } from 'lucide-react';
import { type ReactNode, useRef } from 'react';
import { useTranslation } from '../../i18n';
import { PopoverItem } from '../Packing/PackingPopover';
import { getCategoryIcon } from '../shared/categoryIcons';
import { PopoverListPanel } from '../shared/dialogParts';
import { Tooltip } from '../shared/Tooltip';
@@ -22,7 +21,7 @@ function SuggestButton({ place, strip, tall }: { place: AssistantFoundPlace; str
const { t } = useTranslation();
const { days, focusDay, disabled, blockedKey, adding } = strip;
const list = usePopoverList(focusDay ? days.findIndex((d) => d.id === focusDay.id) : 0, {
estimatedHeight: Math.min(320, days.length * 34 + 8),
estimatedHeight: Math.ceil(days.length / 7) * 44 + 16,
});
const height = tall ? 'h-10' : 'h-7';
const busy = adding === place.ref;
@@ -91,26 +90,44 @@ function SuggestButton({ place, strip, tall }: { place: AssistantFoundPlace; str
) : (
buttons
)}
<PopoverListPanel list={list} label={t('assistant.place.pickDay')} className="max-w-[16rem]">
{days.map((day) => (
<PopoverItem
key={day.id}
icon={null}
label={day.label}
active={day.id === focusDay?.id}
onClick={() => pick(day.id)}
/>
))}
{/* A grid of day tiles, not a list: a month-long trip still fits in a few rows. */}
<PopoverListPanel list={list} label={t('assistant.place.pickDay')} className="w-[15.5rem] p-2">
<div className="grid grid-cols-7 gap-1">
{days.map((day) => {
const current = day.id === focusDay?.id;
return (
<Tooltip key={day.id} label={day.label} placement="top">
<button
type="button"
onClick={() => pick(day.id)}
aria-label={day.label}
aria-pressed={current}
className={`flex h-10 flex-col items-center justify-center rounded-lg leading-none outline-none transition-colors focus-visible:ring-2 focus-visible:ring-accent ${
current ? 'bg-accent text-accent-text' : 'text-content hover:bg-surface-hover'
}`}
>
<span className="text-body font-semibold tabular-nums">{day.n}</span>
{day.weekday && (
<span className={`mt-0.5 text-caption ${current ? 'text-accent-text' : 'text-content-faint'}`}>
{day.weekday}
</span>
)}
</button>
</Tooltip>
);
})}
</div>
</PopoverListPanel>
</>
);
}
/**
* One place a search found, as a small card: its picture from TREK's photo
* proxy (or its category's icon), its name, the category it most likely
* belongs in, whether it is open now while the trip runs, how far it is from
* the last stop of the day in focus, and one way on: "+ Day 3" for a new
* One place a search found, as a card: its picture from TREK's photo proxy
* with the category it most likely belongs in on it (or that category's icon
* on its colour), its name, address and rating, whether it is open now while
* the trip runs, how far it is from the last stop of the day in focus, and one
* way on: "+ Day 3" for a new
* place, "On map" for one the trip has. A click on the card shows it on the
* map, and resting the pointer on it pins it there for a moment.
*/
@@ -156,8 +173,8 @@ export default function AssistantPlaceCard({
return (
<li
ref={ref}
className={`flex flex-shrink-0 snap-start flex-col overflow-hidden rounded-xl border border-edge-faint bg-surface-card ${
density === 'compact' ? 'w-[168px]' : 'w-[200px]'
className={`group/card flex flex-shrink-0 snap-start flex-col overflow-hidden rounded-2xl border border-edge-faint bg-surface-card shadow-sm transition-shadow hover:shadow-md ${
density === 'compact' ? 'w-[188px]' : 'w-[220px]'
}`}
onMouseEnter={() => strip.hover(place)}
onMouseLeave={() => strip.hover(null)}
@@ -169,36 +186,62 @@ export default function AssistantPlaceCard({
onBlur={() => strip.hover(null)}
className="flex flex-col text-start outline-none focus-visible:bg-surface-hover"
>
<span className="flex h-[72px] w-full items-center justify-center overflow-hidden bg-surface-secondary">
<span
className="relative block h-24 w-full overflow-hidden bg-surface-secondary"
// Without a picture the category's own colour washes the space, data from the trip.
style={
photo || !category
? undefined
: { background: `color-mix(in srgb, ${category.color} 16%, var(--bg-secondary))` }
}
>
{photo ? (
<img src={photo} alt="" decoding="async" loading="lazy" className="h-full w-full object-cover" />
<img
src={photo}
alt=""
decoding="async"
loading="lazy"
className="h-full w-full object-cover transition-transform duration-300 group-hover/card:scale-[1.04]"
/>
) : (
// The category's own colour, data from the trip; only the small icon wears it.
<Icon size={20} aria-hidden="true" style={{ color: category?.color ?? 'var(--text-faint)' }} />
)}
</span>
<span className="flex min-w-0 flex-col gap-0.5 px-2.5 pt-2">
<bdi className="truncate text-body font-semibold text-content">{place.name}</bdi>
{(category || place.openNow !== null) && (
<span className="flex min-w-0 items-center gap-2 text-caption text-content-muted">
{category && <bdi className="min-w-0 truncate">{category.name}</bdi>}
{place.openNow === true && (
<span className="inline-flex flex-shrink-0 items-center gap-1">
<span aria-hidden="true" className="h-1.5 w-1.5 rounded-full bg-success" />
{t('assistant.place.openNow')}
</span>
)}
{place.openNow === false && <span className="flex-shrink-0">{t('assistant.place.closed')}</span>}
<span className="grid h-full w-full place-items-center">
<Icon size={30} aria-hidden="true" style={{ color: category?.color ?? 'var(--text-faint)' }} />
</span>
)}
{distance && (
<span className="truncate text-caption text-content-faint">
{t('assistant.place.fromPrev', { distance })}
{category && photo && (
<span className="absolute start-2 top-2 inline-flex max-w-[75%] items-center gap-1 rounded-full bg-surface-card px-2 py-0.5 text-caption font-medium text-content shadow-sm">
<Icon size={11} aria-hidden="true" className="flex-shrink-0" style={{ color: category.color }} />
<bdi className="truncate">{category.name}</bdi>
</span>
)}
{place.openNow !== null && (
<span className="absolute bottom-2 end-2 inline-flex items-center gap-1 rounded-full bg-surface-card px-2 py-0.5 text-caption font-medium text-content-muted shadow-sm">
<span
aria-hidden="true"
className={`h-1.5 w-1.5 rounded-full ${place.openNow ? 'bg-success' : 'bg-[color:var(--text-faint)]'}`}
/>
{t(place.openNow ? 'assistant.place.openNow' : 'assistant.place.closed')}
</span>
)}
</span>
<span className="flex min-w-0 flex-col gap-1 px-3 pt-2.5">
<bdi className="line-clamp-2 text-body font-semibold leading-snug text-content">{place.name}</bdi>
{category && !photo && <bdi className="truncate text-caption text-content-muted">{category.name}</bdi>}
{place.address && <bdi className="truncate text-caption text-content-muted">{place.address}</bdi>}
{(place.rating !== null || distance) && (
<span className="flex min-w-0 items-center gap-2 text-caption text-content-faint">
{place.rating !== null && (
<span className="inline-flex flex-shrink-0 items-center gap-0.5 font-medium text-content-muted">
<Star size={11} aria-hidden="true" className="fill-current text-warning" />
{place.rating.toFixed(1)}
</span>
)}
{distance && <span className="truncate">{t('assistant.place.fromPrev', { distance })}</span>}
</span>
)}
</span>
</button>
<div className="mt-auto flex min-w-0 px-2.5 pb-2.5 pt-2">{action}</div>
<div className="mt-auto flex min-w-0 px-3 pb-3 pt-2.5">{action}</div>
</li>
);
}
@@ -8,7 +8,6 @@
import type { AssistantFoundPlace, AssistantMessage, AssistantPlaces } from '@trek/shared';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen, waitFor } from '../../../tests/helpers/render';
import {
buildAssignment,
buildCategory,
@@ -17,6 +16,7 @@ import {
buildTrip,
buildUser,
} from '../../../tests/helpers/factories';
import { fireEvent, render, screen, waitFor } from '../../../tests/helpers/render';
import { fetchPhoto } from '../../services/photoService';
import { chatOf, useAssistantStore } from '../../store/assistantStore';
import { useAuthStore } from '../../store/authStore';
@@ -119,12 +119,18 @@ describe('AssistantPlaceStrip', () => {
expect(screen.getByText('1.2 km from the previous stop')).toBeInTheDocument();
});
it('FE-AI-PLACES-002: shows six cards and counts the rest on a tile', () => {
it('FE-AI-PLACES-002: shows every card it was sent and counts what the server left out on a tile', () => {
seed();
const list = Array.from({ length: 8 }, (_, i) => place(`s1:${i}`));
renderStrip({ toolCallId: 's1', places: list, more: 4 });
expect(screen.getAllByRole('button', { name: /^Add to/ })).toHaveLength(6);
expect(screen.getByText('6 more')).toBeInTheDocument();
expect(screen.getAllByRole('button', { name: /^Add to/ })).toHaveLength(8);
expect(screen.getByText('4 more')).toBeInTheDocument();
});
it('FE-AI-PLACES-009: a place known only by its position shows its category, never a photo of the area', () => {
seed();
renderStrip({ toolCallId: 's1', places: [place('s1:0', { photoKey: 'coords:41.889000,12.470000' })], more: 0 });
expect(fetchPhoto).not.toHaveBeenCalled();
});
it('FE-AI-PLACES-003: a picture only ever comes from the photo proxy', async () => {
@@ -3,16 +3,18 @@ import { ChevronLeft, ChevronRight } from 'lucide-react';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from '../../i18n';
import { prefersReducedMotion } from '../../utils/reducedMotion';
import AssistantPlaceCard from './AssistantPlaceCard';
import { suggestedFromStrip } from './assistantParts';
import { useAssistantView } from './assistantViewContext';
import { useAssistantPlaceStrip } from './useAssistantPlaceStrip';
/** Cards the strip shows; the rest are counted on the tile at its end. */
const SHOWN = 6;
/** Cards the strip shows, every one the server sends; what it left out is counted on the tile at its end. */
const SHOWN = 20;
// In the strip's head, never over a card: a press that ends a pixel off still lands on the arrow.
const ARROW =
'absolute top-[52px] z-10 hidden h-7 w-7 -translate-y-1/2 items-center justify-center rounded-full border border-edge-faint bg-surface-card text-content-secondary shadow-dropdown hover:text-content group-hover:flex';
'grid h-7 w-7 place-items-center rounded-full bg-surface-card text-content-secondary shadow-sm ring-1 ring-edge-faint transition-colors hover:text-content disabled:cursor-default disabled:opacity-40 disabled:hover:text-content-secondary';
/** How far the strip has scrolled from either end, with the reading direction in mind. */
function edgesOf(el: HTMLElement): { start: boolean; end: boolean } {
@@ -24,8 +26,9 @@ function edgesOf(el: HTMLElement): { start: boolean; end: boolean } {
/**
* The places a search found, as one row of cards to swipe or scroll through:
* the next card peeks in, so the row says it goes on, and the edges fade
* where there is more. On the desktop two arrows show on hover while the row
* overflows. At most six cards, then a tile counting the rest.
* where there is more. On the desktop a head over the row names it and holds
* two arrows that move it by whole cards, off while that way is the end. Every card the step found, then a
* tile counting what the server left out.
*/
export default function AssistantPlaceStrip({ found, message }: { found: AssistantPlaces; message: AssistantMessage }) {
const { t } = useTranslation();
@@ -55,22 +58,63 @@ export default function AssistantPlaceStrip({ found, message }: { found: Assista
const { hover } = strip;
useEffect(() => () => hover(null), [hover]);
/** Scrolls by most of a view towards the start (-1) or the end (1) of the row. */
/**
* Scrolls by as many whole cards as the view holds, towards the start (-1)
* or the end (1), so the row lands on a card edge instead of fighting its
* snap points half way; smoothly, unless motion is turned down.
*/
const page = (towards: -1 | 1) => {
const el = listRef.current;
if (!el) return;
const card = el?.firstElementChild as HTMLElement | null;
if (!el || !card) return;
const gap = Number.parseFloat(getComputedStyle(el).columnGap) || 0;
const step = card.offsetWidth + gap;
const cards = Math.max(1, Math.floor((el.clientWidth - 32) / step));
const rtl = getComputedStyle(el).direction === 'rtl';
el.scrollBy((rtl ? -towards : towards) * el.clientWidth * 0.8, 0);
el.scrollBy({
left: (rtl ? -towards : towards) * cards * step,
behavior: prefersReducedMotion() ? 'auto' : 'smooth',
});
};
const total = found.places.length + found.more;
return (
<section aria-label={t('assistant.place.strip')} className="group relative -mx-4">
<section aria-label={t('assistant.place.strip')} className="-mx-4">
{variant === 'window' && (fade.start || fade.end) && (
// The cards are reachable by Tab; the arrows are for the pointer only.
<div className="mb-1.5 flex items-center gap-2 px-4">
<span className="min-w-0 flex-1 truncate text-caption font-medium text-content-muted">
{t('assistant.place.strip')}
<span className="ms-1.5 tabular-nums text-content-faint">{total}</span>
</span>
<button
type="button"
tabIndex={-1}
aria-hidden="true"
disabled={!fade.start}
onClick={() => page(-1)}
className={ARROW}
>
<ChevronLeft size={15} className="rtl:-scale-x-100" />
</button>
<button
type="button"
tabIndex={-1}
aria-hidden="true"
disabled={!fade.end}
onClick={() => page(1)}
className={ARROW}
>
<ChevronRight size={15} className="rtl:-scale-x-100" />
</button>
</div>
)}
<ul
ref={listRef}
onScroll={measure}
data-fade-start={fade.start || undefined}
data-fade-end={fade.end || undefined}
className="trek-assistant-strip flex snap-x snap-mandatory scroll-px-4 gap-2 overflow-x-auto px-4 pb-1"
className="trek-assistant-strip flex snap-x snap-mandatory scroll-px-4 gap-2.5 overflow-x-auto overscroll-x-contain px-4 pb-2 pt-0.5"
>
{found.places.slice(0, SHOWN).map((place) => (
<AssistantPlaceCard
@@ -81,32 +125,11 @@ export default function AssistantPlaceStrip({ found, message }: { found: Assista
/>
))}
{rest > 0 && (
<li className="flex w-24 flex-shrink-0 snap-start items-center justify-center rounded-xl border border-dashed border-edge-faint px-2 text-center text-caption text-content-muted">
<li className="flex w-24 flex-shrink-0 snap-start items-center justify-center rounded-2xl border border-dashed border-edge-faint px-2 text-center text-caption text-content-muted">
{t('assistant.place.more', { count: rest })}
</li>
)}
</ul>
{variant === 'window' && (
// The cards are reachable by Tab; the arrows are for the pointer only.
<>
{fade.start && (
<button
type="button"
tabIndex={-1}
aria-hidden="true"
onClick={() => page(-1)}
className={`${ARROW} start-2`}
>
<ChevronLeft size={15} className="rtl:-scale-x-100" />
</button>
)}
{fade.end && (
<button type="button" tabIndex={-1} aria-hidden="true" onClick={() => page(1)} className={`${ARROW} end-2`}>
<ChevronRight size={15} className="rtl:-scale-x-100" />
</button>
)}
</>
)}
</section>
);
}
@@ -0,0 +1,257 @@
/**
* FE-AI-POWER-001 to FE-AI-POWER-010
*
* The parts that tie the chat into the planner: the next questions under an
* answer, the waiting changes inside the day list, the week grid of a plan
* over several days, the context menu rows, the trip notes and the part of the
* map a question carries.
*/
import { act, renderHook } from '@testing-library/react';
import type { AssistantChangePreview, AssistantMessage } from '@trek/shared';
import type { ReactNode } from 'react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { buildDay, buildPlace, buildTrip, buildUser } from '../../../tests/helpers/factories';
import { fireEvent, render, screen } from '../../../tests/helpers/render';
import { chatOf, useAssistantStore } from '../../store/assistantStore';
import { useAuthStore } from '../../store/authStore';
import { useSettingsStore } from '../../store/settingsStore';
import { useTripStore } from '../../store/tripStore';
import { mapViewOf } from '../Map/assistantViewport';
import AssistantDayPreview from './AssistantDayPreview';
import { followUpsFor } from './assistantFollowUpRules';
import AssistantFollowUps from './AssistantFollowUps';
import type { ChangeItem } from './assistantParts';
import { type AssistantView, AssistantViewContext } from './assistantViewContext';
import AssistantWeekOverview from './AssistantWeekOverview';
import { useAssistantMenu } from './useAssistantMenu';
import { useTripMemory } from './useTripMemory';
import { useWeekDays } from './useWeekDays';
const TRIP = 9;
const ASSISTANT = useAssistantStore.getState();
const TRIPS = useTripStore.getState();
const SETTINGS = useSettingsStore.getState();
const AUTH = useAuthStore.getState();
afterEach(() => {
useAssistantStore.setState(ASSISTANT, true);
useTripStore.setState(TRIPS, true);
useSettingsStore.setState(SETTINGS, true);
useAuthStore.setState(AUTH, true);
});
const view: AssistantView = { tripId: TRIP, variant: 'window' };
const inView = (node: ReactNode) => <AssistantViewContext.Provider value={view}>{node}</AssistantViewContext.Provider>;
function answer(parts: AssistantMessage['parts'], id = 'a1'): AssistantMessage {
return { id, role: 'assistant', status: 'complete', createdAt: '2026-10-21T08:00:00.000Z', parts };
}
function preview(
toolCallId: string,
dayId: number,
over: Partial<AssistantChangePreview> = {}
): AssistantChangePreview {
return {
toolCallId,
verbKey: 'addPlace',
subject: 'Place',
rows: [],
dayId,
placeIds: [],
undoable: true,
effect: { kind: 'add', dayId, fromDayId: null, placeId: null, assignmentId: null, place: null },
...over,
};
}
function waiting(toolCallId: string, data: AssistantChangePreview): AssistantMessage['parts'] {
return [
{ type: 'tool-call', toolCallId, toolName: 'create_place', args: {}, approval: { id: toolCallId } },
{ type: 'data-trek-change', data },
];
}
function seedChat(messages: AssistantMessage[], extra: Record<string, unknown> = {}) {
useAssistantStore.setState({
byTrip: { [TRIP]: { ...chatOf(useAssistantStore.getState(), TRIP), messages, ...extra } },
});
}
describe('the next questions', () => {
it('FE-AI-POWER-001: an answer offers what fits what it holds, changes only to someone who may make them', () => {
const ids = (parts: AssistantMessage['parts'], canEdit = true) =>
followUpsFor(answer(parts), canEdit).map((f) => f.id);
expect(ids([{ type: 'data-trek-places', data: { toolCallId: 's', places: [], more: 0 } }])).toContain('cheaper');
expect(ids([{ type: 'data-trek-change', data: preview('c', 1) }])).toContain('nextDay');
expect(ids([{ type: 'data-trek-change', data: preview('c', 1) }], false)).toEqual([]);
expect(ids([{ type: 'text', text: 'Hi' }])).toEqual(['more', 'next']);
expect(ids([])).toEqual([]);
});
it('FE-AI-POWER-002: under the last finished answer a tap sends the question; not while it runs', () => {
const send = vi.fn(async () => {});
const last = answer([{ type: 'text', text: 'Done.' }]);
seedChat([last]);
useAssistantStore.setState({ send });
const { rerender } = render(inView(<AssistantFollowUps message={last} />));
fireEvent.click(screen.getByRole('button', { name: 'Tell me more' }));
expect(send).toHaveBeenCalledWith(TRIP, 'Tell me more');
seedChat([last], { isRunning: true });
rerender(inView(<AssistantFollowUps message={last} />));
expect(screen.queryByRole('button', { name: 'Tell me more' })).toBeNull();
});
});
describe('the day list preview', () => {
it('FE-AI-POWER-003: a waiting add shows dashed on its day, a removal struck, and resting on it lights the change', () => {
useTripStore.setState({ places: [buildPlace({ id: 5, name: 'Louvre' })] });
const add = preview('c1', 3, {
effect: {
kind: 'add',
dayId: 3,
fromDayId: null,
placeId: null,
assignmentId: null,
place: { name: 'Pantheon', lat: 1, lng: 2, categoryId: null },
},
});
const remove = preview('c2', 3, {
effect: { kind: 'remove', dayId: 3, fromDayId: null, placeId: 5, assignmentId: 50, place: null },
});
seedChat([answer([...waiting('c1', add), ...waiting('c2', remove)])]);
render(<AssistantDayPreview tripId={TRIP} dayId={3} />);
expect(screen.getByText('Pantheon')).toBeInTheDocument();
expect(screen.getByText('Louvre')).toHaveClass('line-through');
fireEvent.mouseEnter(screen.getByText('Pantheon'));
expect(useAssistantStore.getState().mapLink?.hoveredId).toBe('c1');
});
it('FE-AI-POWER-004: nothing shows on another day, or once the change was decided', () => {
const add = preview('c1', 3, {
effect: {
kind: 'add',
dayId: 3,
fromDayId: null,
placeId: null,
assignmentId: null,
place: { name: 'Pantheon', lat: 1, lng: 2, categoryId: null },
},
});
seedChat([answer(waiting('c1', add))]);
const { container } = render(<AssistantDayPreview tripId={TRIP} dayId={4} />);
expect(container).toBeEmptyDOMElement();
});
});
describe('the week grid', () => {
const item = (id: string, dayId: number): ChangeItem => ({
toolCallId: id,
preview: preview(id, dayId),
applied: null,
state: 'pending',
});
it('FE-AI-POWER-005: from three days on the changes group by day, in trip order', () => {
useTripStore.setState({
trip: buildTrip({ id: TRIP }),
days: [
buildDay({ id: 1, date: '2026-11-02' }),
buildDay({ id: 2, date: '2026-11-03' }),
buildDay({ id: 3, date: '2026-11-04' }),
],
});
const wrapper = ({ children }: { children: ReactNode }) => inView(children);
const three = renderHook(() => useWeekDays([item('a', 3), item('b', 1), item('c', 2), item('d', 1)]), { wrapper });
expect(three.result.current.map((d) => [d.n, d.ids])).toEqual([
[1, ['b', 'd']],
[2, ['c']],
[3, ['a']],
]);
const two = renderHook(() => useWeekDays([item('a', 1), item('b', 2)]), { wrapper });
expect(two.result.current).toEqual([]);
});
it('FE-AI-POWER-006: a tap leaves a whole day out or takes it back in', () => {
const onToggleDay = vi.fn();
const days = [
{ id: 1, n: 1, weekday: 'Mon', ids: ['a', 'b'] },
{ id: 2, n: 2, weekday: 'Tue', ids: ['c'] },
];
render(<AssistantWeekOverview days={days} excluded={new Set(['c'])} disabled={false} onToggleDay={onToggleDay} />);
const [mon, tue] = screen.getAllByRole('button');
expect(mon).toHaveAttribute('aria-pressed', 'true');
expect(tue).toHaveAttribute('aria-pressed', 'false');
fireEvent.click(mon);
expect(onToggleDay).toHaveBeenCalledWith(['a', 'b'], false);
fireEvent.click(tue);
expect(onToggleDay).toHaveBeenLastCalledWith(['c'], true);
});
});
describe('the context menu rows', () => {
it('FE-AI-POWER-007: none while the assistant cannot run; else they open the chat on the place and ask', () => {
const send = vi.fn(async () => {});
const openWith = vi.fn();
useAssistantStore.setState({ status: null, send, openWith });
const louvre = buildPlace({ id: 5, name: 'Louvre' });
const off = renderHook(() => useAssistantMenu(TRIP));
expect(off.result.current.place(louvre)).toEqual([]);
useAssistantStore.setState({ status: { available: true } as never });
const on = renderHook(() => useAssistantMenu(TRIP));
const rows = on.result.current.place(louvre);
const alternative = rows.find((r) => 'label' in r && r.label === 'Find an alternative');
act(() => (alternative && 'onClick' in alternative ? alternative.onClick() : undefined));
expect(openWith).toHaveBeenCalledWith(TRIP, { placeIds: [5] });
expect(send).toHaveBeenCalledWith(TRIP, expect.stringContaining('Louvre'));
expect(on.result.current.day(3).length).toBeGreaterThan(1);
});
});
describe('the trip notes', () => {
it('FE-AI-POWER-008: notes are kept per trip, and saving empty ones drops the entry', async () => {
useAuthStore.setState({ user: buildUser({ id: 1 }) });
const updateSetting = vi.fn(async () => {});
useSettingsStore.setState({
settings: { ...SETTINGS.settings, assistant_memory: { '2': 'Other' } },
updateSetting,
});
const { result } = renderHook(() => useTripMemory(TRIP));
expect(result.current.has).toBe(false);
await act(async () => void (await result.current.save(' Vegetarian ')));
expect(updateSetting).toHaveBeenCalledWith('assistant_memory', { '2': 'Other', [TRIP]: 'Vegetarian' });
await act(async () => void (await result.current.save(' ')));
expect(updateSetting).toHaveBeenLastCalledWith('assistant_memory', { '2': 'Other' });
});
});
describe('the map a question carries', () => {
it('FE-AI-POWER-009: edges stay on the globe and are rounded to about ten metres', () => {
expect(mapViewOf({ south: 35.123456, west: -190, north: 35.2, east: 139.987654 })).toEqual({
south: 35.1235,
west: -180,
north: 35.2,
east: 139.9877,
});
});
it('FE-AI-POWER-010: a question goes out with the map of its own trip in its focus', async () => {
const send = vi.fn();
useAssistantStore.setState({ mapView: { tripId: TRIP, view: { south: 1, west: 2, north: 3, east: 4 } } });
seedChat([]);
// The request body is built inside the store; read it from the repo call.
const { assistantRepo } = await import('../../repo/assistantRepo');
const spy = vi.spyOn(assistantRepo, 'send').mockImplementation(async (_trip, body) => {
send(body);
throw new Error('stop');
});
await useAssistantStore.getState().send(TRIP, 'What is here?');
expect(send).toHaveBeenCalledWith(
expect.objectContaining({ focus: { view: { south: 1, west: 2, north: 3, east: 4 } } })
);
spy.mockRestore();
});
});
@@ -0,0 +1,65 @@
import { Check, Minus } from 'lucide-react';
import { useTranslation } from '../../i18n';
import type { WeekDay } from './useWeekDays';
/**
* A plan over several days as one grid: a tile per day with how many changes
* it gets, taken in or left out as a whole with one tap. The single changes
* stay below it, folded away until asked for.
*/
export default function AssistantWeekOverview({
days,
excluded,
disabled,
onToggleDay,
}: {
days: readonly WeekDay[];
excluded: ReadonlySet<string>;
disabled: boolean;
onToggleDay: (ids: readonly string[], include: boolean) => void;
}) {
const { t } = useTranslation();
return (
<div
role="group"
aria-label={t('assistant.week.title')}
className="mb-2 grid gap-1.5"
style={{ gridTemplateColumns: `repeat(${Math.min(days.length, 7)}, minmax(0, 1fr))` }}
>
{days.map((day, i) => {
const on = day.ids.filter((id) => !excluded.has(id)).length;
const taken = on > 0;
return (
<button
key={day.id}
type="button"
disabled={disabled}
aria-pressed={taken}
onClick={() => onToggleDay(day.ids, !taken)}
className={`trek-assistant-enter group/day relative flex min-w-0 flex-col items-center gap-0.5 rounded-xl border px-1 py-2 transition-all disabled:cursor-default ${
taken
? 'border-accent bg-accent-subtle text-content shadow-sm hover:-translate-y-px hover:shadow-md'
: 'border-dashed border-edge text-content-faint hover:border-edge-secondary'
}`}
style={{ animationDelay: `${i * 40}ms` }}
>
<span
aria-hidden="true"
className={`absolute end-1 top-1 grid h-3.5 w-3.5 place-items-center rounded-full ${
taken ? 'bg-accent text-accent-text' : 'bg-surface-tertiary text-content-faint'
}`}
>
{taken ? <Check size={9} strokeWidth={3} /> : <Minus size={9} strokeWidth={3} />}
</span>
<span className="text-caption text-content-muted">{day.weekday ?? t('assistant.week.day')}</span>
<span className="text-subtitle font-bold tabular-nums leading-none">{day.n}</span>
<span className={`text-caption tabular-nums ${taken ? 'text-content-secondary' : ''}`}>
{t('assistant.week.changes', { count: taken ? on : day.ids.length })}
</span>
</button>
);
})}
</div>
);
}
@@ -196,6 +196,7 @@ function ChatWindow({
))}
<div className="flex min-h-0 flex-1 flex-col overflow-hidden rounded-xl">
<AssistantHeader
tripId={trip.id}
thread={thread}
tripTitle={trip.title}
dragProps={frame.handleProps}
+18 -2
View File
@@ -168,6 +168,20 @@
animation: trek-assistant-busy 1.8s ease-in-out infinite;
}
/* The dot beside what the assistant does right now: a soft beat, a halo going out. */
@keyframes trek-assistant-pulse {
0% {
box-shadow: 0 0 0 0 color-mix(in srgb, var(--accent) 45%, transparent);
}
70%,
100% {
box-shadow: 0 0 0 6px transparent;
}
}
.trek-assistant-pulse {
animation: trek-assistant-pulse 1.4s ease-out infinite;
}
@media (prefers-reduced-motion: reduce) {
.trek-assistant-pop,
.trek-assistant-enter {
@@ -176,7 +190,8 @@
.trek-assistant-settle {
transition: none;
}
.trek-assistant-busy {
.trek-assistant-busy,
.trek-assistant-pulse {
animation: none;
}
.trek-assistant-shimmer {
@@ -196,7 +211,8 @@
[data-reduce-motion] .trek-assistant-settle {
transition: none;
}
[data-reduce-motion] .trek-assistant-busy {
[data-reduce-motion] .trek-assistant-busy,
[data-reduce-motion] .trek-assistant-pulse {
animation: none;
}
[data-reduce-motion] .trek-assistant-shimmer {
@@ -0,0 +1,44 @@
import type { AssistantMessage } from '@trek/shared';
/**
* The next questions an answer suggests, as one tap each: read from what the
* answer holds, not asked from the model, so they cost nothing and come at
* once. Places found ask to narrow them, a plan asks to go on, a forecast asks
* for the other weather. Three at most; the first kind the answer holds wins.
*/
export interface FollowUp {
id: string;
labelKey: string;
}
const PLACES: readonly FollowUp[] = [
{ id: 'cheaper', labelKey: 'assistant.followUp.cheaper' },
{ id: 'closer', labelKey: 'assistant.followUp.closer' },
{ id: 'openNow', labelKey: 'assistant.followUp.openNow' },
];
const PLAN: readonly FollowUp[] = [
{ id: 'nextDay', labelKey: 'assistant.followUp.nextDay' },
{ id: 'relaxed', labelKey: 'assistant.followUp.relaxed' },
{ id: 'dinners', labelKey: 'assistant.followUp.dinners' },
];
const WEATHER: readonly FollowUp[] = [
{ id: 'rain', labelKey: 'assistant.followUp.rain' },
{ id: 'sun', labelKey: 'assistant.followUp.sun' },
];
const GENERAL: readonly FollowUp[] = [
{ id: 'more', labelKey: 'assistant.followUp.more' },
{ id: 'next', labelKey: 'assistant.followUp.next' },
];
/** What an answer offers to ask next; changes are offered only to someone who may make them. */
export function followUpsFor(message: AssistantMessage, canEdit: boolean): readonly FollowUp[] {
const types = new Set(message.parts.map((part) => part.type));
if (canEdit && (types.has('data-trek-change') || types.has('data-trek-applied'))) return PLAN;
if (types.has('data-trek-places')) return PLACES;
if (types.has('data-trek-weather')) return WEATHER;
return types.has('text') ? GENERAL : [];
}
@@ -92,6 +92,10 @@ const ERRORS: Record<AssistantErrorCode, AssistantErrorView> = {
messageKey: 'assistant.error.maxSteps',
action: { kind: 'continue', labelKey: 'assistant.errorAction.continue' },
},
empty_answer: {
messageKey: 'assistant.error.emptyAnswer',
action: { kind: 'continue', labelKey: 'assistant.errorAction.continue' },
},
offline: { messageKey: 'assistant.error.offline', action: null },
decide_first: { messageKey: 'assistant.error.decideFirst', action: null },
too_many_requests: { messageKey: 'assistant.error.rateLimited', action: null },
@@ -1,5 +1,5 @@
/**
* FE-AI-DAYAFTER-001 to FE-AI-DAYAFTER-008
* FE-AI-DAYAFTER-001 to FE-AI-DAYAFTER-009
*
* A day as it would read once a card's waiting changes ran, without React: who
* stays, who joins at the end and who leaves, the way between two stops as a
@@ -10,7 +10,15 @@ import { describe, expect, it } from 'vitest';
import { buildAssignment, buildPlace } from '../../../tests/helpers/factories';
import type { AssignmentsMap } from '../../types';
import { buildDayAfter, changedDays, changePoints, type DayChange, minutesOf } from './dayAfterModel';
import {
buildDayAfter,
changedDays,
changePoints,
type DayChange,
dayIssues,
minutesOf,
stopIssue,
} from './dayAfterModel';
// 0.01° of latitude is 1.112 km: with the detour factor that is 19 minutes on foot, 6 by bike.
const louvre = buildPlace({ id: 10, name: 'Louvre', lat: 48.0, lng: 2.0, duration_minutes: 60 });
@@ -51,7 +59,7 @@ describe('dayAfterModel', () => {
]);
expect(stops[0]?.lead).toBeNull();
// 09:00 plus an hour, 19 minutes on foot, so 161 minutes are left before 13:00.
expect(stops[1]?.lead).toEqual({ travelMinutes: 19, freeMinutes: 161, overlapsWith: null });
expect(stops[1]?.lead).toEqual({ travelMinutes: 19, freeMinutes: 161, overlapsWith: null, shortBy: null });
});
it('FE-AI-DAYAFTER-002: a new place joins at the end, named and placed by the change', () => {
@@ -59,7 +67,7 @@ describe('dayAfterModel', () => {
const { stops } = day(3, [change('c1', pantheon)]);
const last = stops[stops.length - 1];
expect(last).toMatchObject({ key: 'new:c1', name: 'Pantheon', status: 'new', toolCallId: 'c1', time: null });
expect(last?.lead).toEqual({ travelMinutes: 19, freeMinutes: null, overlapsWith: null });
expect(last?.lead).toEqual({ travelMinutes: 19, freeMinutes: null, overlapsWith: null, shortBy: null });
});
it('FE-AI-DAYAFTER-003: a planned place joins by its id; a change with nothing to name it by is left out', () => {
@@ -139,4 +147,15 @@ describe('dayAfterModel', () => {
[48.02, 2.0],
]);
});
it('FE-AI-DAYAFTER-009: a way longer than the time between two stops is too tight, and counts as an issue', () => {
// Louvre until 10:00, then 19 minutes on foot to Orsay, which starts at 10:10: nine minutes short.
const tight = plan();
tight[3] = (tight[3] ?? []).map((a) => (a.id === 101 ? { ...a, assignment_time: '10:10' } : a));
const after = day(3, [], tight);
expect(after.stops[1]?.lead).toMatchObject({ travelMinutes: 19, shortBy: 9 });
expect(after.stops.map(stopIssue)).toEqual([false, true]);
expect(dayIssues(after)).toBe(1);
expect(dayIssues(day(3, []))).toBe(0);
});
});
@@ -35,6 +35,8 @@ interface StopLead {
freeMinutes: number | null;
/** The stop before, when the two take the same time. */
overlapsWith: string | null;
/** Minutes the way there is longer than the time between the two; null when it fits or the times do not say. */
shortBy: number | null;
}
export interface TimelineStop {
@@ -152,10 +154,12 @@ function leadOf(prev: Draft, cur: Draft, defaultMode: string): StopLead {
60
)
: null;
if (cur.start === null || prev.end === null) return { travelMinutes, freeMinutes: null, overlapsWith: null };
if (cur.start < prev.end) return { travelMinutes, freeMinutes: null, overlapsWith: prev.stop.name };
const none = { freeMinutes: null, overlapsWith: null, shortBy: null };
if (cur.start === null || prev.end === null) return { travelMinutes, ...none };
if (cur.start < prev.end) return { travelMinutes, ...none, overlapsWith: prev.stop.name };
const free = cur.start - prev.end - (travelMinutes ?? 0);
return { travelMinutes, freeMinutes: free >= GAP_MIN_MINUTES ? free : null, overlapsWith: null };
if (free < 0) return { travelMinutes, ...none, shortBy: -free };
return { travelMinutes, ...none, freeMinutes: free >= GAP_MIN_MINUTES ? free : null };
}
/**
@@ -230,3 +234,27 @@ export function changedDays(changes: readonly DayChange[]): number[] {
}
return days;
}
/** A leg this long without a time says the day asks a lot of travel. */
const FAR_MINUTES = 60;
/**
* Whether a day still works once the changes ran: stops that take the same
* time, a way there longer than the time between two stops, and legs over an
* hour. Counted over the stops that stay on the day.
*/
export function dayIssues(day: DayAfter): number {
return day.stops.reduce((sum, stop) => {
const lead = stop.lead;
if (stop.status === 'removed' || !lead) return sum;
const far = lead.travelMinutes !== null && lead.travelMinutes >= FAR_MINUTES;
return sum + (lead.overlapsWith || lead.shortBy !== null || far ? 1 : 0);
}, 0);
}
/** Whether a stop is one of those `dayIssues` counts. */
export function stopIssue(stop: TimelineStop): boolean {
const lead = stop.lead;
if (stop.status === 'removed' || !lead) return false;
return !!lead.overlapsWith || lead.shortBy !== null || (lead.travelMinutes ?? 0) >= FAR_MINUTES;
}
@@ -2,20 +2,19 @@ import { useTranslation } from '../../i18n';
import { useSettingsStore } from '../../store/settingsStore';
import { useToast } from '../shared/Toast';
/**
* Whether the trip map follows the assistant: pans to where it searches and
* frames the places it suggests. On unless switched off. Behind the switch in
* both AI settings shells, the desktop section and the phone card.
*/
export function useAssistantMapFollow(): { on: boolean; set: (on: boolean) => Promise<void> } {
const on = useSettingsStore((s) => s.settings.assistant_map_follow) !== false;
/** The assistant's own on/off settings; each reads as on unless switched off. */
type AssistantFlag = 'assistant_map_follow' | 'assistant_cost_estimates';
/** One of the assistant's switches, read and saved through the user's settings. */
function useAssistantFlag(key: AssistantFlag): { on: boolean; set: (on: boolean) => Promise<void> } {
const on = useSettingsStore((s) => s.settings[key]) !== false;
const updateSetting = useSettingsStore((s) => s.updateSetting);
const { t } = useTranslation();
const toast = useToast();
const set = async (next: boolean) => {
try {
await updateSetting('assistant_map_follow', next);
await updateSetting(key, next);
} catch (e: unknown) {
toast.error(e instanceof Error ? e.message : t('common.error'));
}
@@ -23,3 +22,21 @@ export function useAssistantMapFollow(): { on: boolean; set: (on: boolean) => Pr
return { on, set };
}
/**
* Whether the trip map follows the assistant: pans to where it searches and
* frames the places it suggests. On unless switched off. Behind the switch in
* both AI settings shells, the desktop section and the phone card.
*/
export function useAssistantMapFollow() {
return useAssistantFlag('assistant_map_follow');
}
/**
* Whether the assistant proposes an estimated budget item along with a place
* that costs money, as one more change card to apply or leave. On unless
* switched off; the server reads the same setting.
*/
export function useAssistantCostEstimates() {
return useAssistantFlag('assistant_cost_estimates');
}
@@ -0,0 +1,70 @@
import type { AssistantFocus } from '@trek/shared';
import { CalendarCheck, CloudRain, type LucideIcon, Shuffle, Sparkles, UtensilsCrossed } from 'lucide-react';
import { useTranslation } from '../../i18n';
import { useAssistantStore } from '../../store/assistantStore';
import type { Place } from '../../types';
/** One row of a context menu, or the line before the assistant's rows. */
type AssistantMenuEntry = { label: string; icon: LucideIcon; onClick: () => void } | { divider: true };
/**
* The assistant's rows in the planner's context menus, so a question starts
* where the user already is: a right click on a place asks about it, finds
* something else in its place, or a restaurant near it; one on a day plans it
* or makes a plan for rain. Each opens the chat with the place or day as its
* focus and sends the question at once. Empty while the assistant cannot run
* for this user, so the menus look as they always did.
*/
export function useAssistantMenu(tripId: number | null) {
const { t } = useTranslation();
const available = useAssistantStore((s) => s.status?.available === true);
const openWith = useAssistantStore((s) => s.openWith);
const send = useAssistantStore((s) => s.send);
const on = available && tripId !== null;
const ask = (focus: AssistantFocus, text?: string) => {
if (tripId === null) return;
openWith(tripId, focus);
if (text) void send(tripId, text);
};
const place = (target: Place): AssistantMenuEntry[] => {
if (!on) return [];
const focus = { placeIds: [target.id] };
return [
{ divider: true },
{ label: t('assistant.context.ask'), icon: Sparkles, onClick: () => ask(focus) },
{
label: t('assistant.menu.alternative'),
icon: Shuffle,
onClick: () => ask(focus, t('assistant.menu.alternativeAsk', { place: target.name })),
},
{
label: t('assistant.menu.foodNearby'),
icon: UtensilsCrossed,
onClick: () => ask(focus, t('assistant.menu.foodNearbyAsk', { place: target.name })),
},
];
};
const day = (dayId: number): AssistantMenuEntry[] => {
if (!on) return [];
const focus = { dayId };
return [
{ divider: true },
{
label: t('assistant.menu.planDay'),
icon: CalendarCheck,
onClick: () => ask(focus, t('assistant.menu.planDayAsk')),
},
{
label: t('assistant.menu.rainPlan'),
icon: CloudRain,
onClick: () => ask(focus, t('assistant.menu.rainPlanAsk')),
},
];
};
return { place, day };
}
@@ -22,6 +22,14 @@ interface StripDay {
/** Its place in the trip, 1 for the first day: "+ Day 3". */
n: number;
label: string;
/** Its weekday, short ("Sat"), for the day grid; null for a day without a date. */
weekday: string | null;
}
/** The short weekday of a `YYYY-MM-DD` date, read as that calendar day wherever the reader is. */
function weekdayOf(date: string | null | undefined, locale: string): string | null {
if (!date || !/^\d{4}-\d{2}-\d{2}$/.test(date)) return null;
return new Intl.DateTimeFormat(locale, { weekday: 'short', timeZone: 'UTC' }).format(new Date(`${date}T00:00:00Z`));
}
/** The trip category a found place most likely belongs in, for its line and its icon. */
@@ -89,7 +97,12 @@ export function useAssistantPlaceStrip() {
const stripDays = useMemo(
(): StripDay[] =>
(days ?? []).map((day, index) => ({ id: day.id, n: index + 1, label: dayLabel(day, index, t, locale) })),
(days ?? []).map((day, index) => ({
id: day.id,
n: index + 1,
label: dayLabel(day, index, t, locale),
weekday: weekdayOf(day.date, locale),
})),
[days, t, locale]
);
const focusDay = stripDays.find((d) => d.id === focusDayId) ?? null;
@@ -7,6 +7,16 @@ import { useAuthStore } from '../../store/authStore';
/** The only pictures a found place shows: TREK's own photo proxy, never an address from the search. */
const PROXY_PREFIX = '/api/maps/place-photo/';
/**
* A key the proxy can find this very place's photo by. A place known only by
* its position (`coords:`, what a search of the open map data finds) would get
* a picture of its surroundings, the same street scene for every restaurant
* in a district; such a card shows its category instead.
*/
function photoKeyOf(place: AssistantFoundPlace): string | null {
return place.photoKey && !place.photoKey.startsWith('coords:') ? place.photoKey : null;
}
/** A picture TREK's proxy serves, or null for anything else. */
function proxiedPhoto(url: string | null | undefined): string | null {
return url?.startsWith(PROXY_PREFIX) ? url : null;
@@ -18,11 +28,12 @@ function proxiedPhoto(url: string | null | undefined): string | null {
* provider, and a strip holds several. The answer goes through the shared
* photo cache and its limit on parallel requests, so a place the planner shows
* too is fetched once. Null while it loads, when there is none, when photos
* are off, and for any answer that is not the proxy's own address.
* are off, for a place known only by its position, and for any answer that is
* not the proxy's own address.
*/
export function useFoundPlacePhoto(place: AssistantFoundPlace, ref: RefObject<Element | null>): string | null {
const enabled = useAuthStore((s) => s.placesPhotosEnabled);
const key = place.photoKey;
const key = photoKeyOf(place);
const [src, setSrc] = useState<string | null>(() => (key ? proxiedPhoto(getCached(key)?.photoUrl) : null));
const [visible, setVisible] = useState(false);
@@ -0,0 +1,38 @@
import { useTranslation } from '../../i18n';
import { useSettingsStore } from '../../store/settingsStore';
import { useToast } from '../shared/Toast';
/** As long as the server reads a trip's notes; more is cut there. */
export const MAX_MEMORY_CHARS = 2_000;
/**
* What the user keeps for the assistant to mind on one trip ("vegetarian, no
* museums"): read from and saved to their settings, one entry per trip, so it
* follows them to every device. Every question on the trip carries it. The
* same for the window and the phone.
*/
export function useTripMemory(tripId: number) {
const { t } = useTranslation();
const toast = useToast();
const all = useSettingsStore((s) => s.settings.assistant_memory);
const updateSetting = useSettingsStore((s) => s.updateSetting);
const text = all?.[String(tripId)] ?? '';
/** Saves the notes; empty ones are dropped rather than kept as a blank entry. */
const save = async (next: string): Promise<boolean> => {
const trimmed = next.trim().slice(0, MAX_MEMORY_CHARS);
const rest = { ...(all ?? {}) };
if (trimmed) rest[String(tripId)] = trimmed;
else delete rest[String(tripId)];
try {
await updateSetting('assistant_memory', rest);
toast.success(t('assistant.memory.saved'));
return true;
} catch (e: unknown) {
toast.error(e instanceof Error ? e.message : t('common.error'));
return false;
}
};
return { text, has: text.trim().length > 0, save };
}
@@ -0,0 +1,48 @@
import { useMemo } from 'react';
import { useTranslation } from '../../i18n';
import { useTripStore } from '../../store/tripStore';
import type { ChangeItem } from './assistantParts';
import { useAssistantView } from './assistantViewContext';
/** The day a waiting change lands on: where its effect puts it, else the day its card names. */
function dayOf(item: ChangeItem): number | null {
return item.preview?.effect?.dayId ?? item.preview?.dayId ?? null;
}
export interface WeekDay {
id: number;
n: number;
weekday: string | null;
ids: string[];
}
/** A plan this wide reads as a week: the overview shows from three days on. */
const WEEK_FROM_DAYS = 3;
/**
* The days a card's waiting changes land on, in trip order, each with its
* changes; empty for a plan narrower than a week view.
*/
export function useWeekDays(pending: readonly ChangeItem[]): WeekDay[] {
const { locale } = useTranslation();
const { tripId } = useAssistantView();
const days = useTripStore((s) => (s.trip?.id === tripId ? s.days : null));
return useMemo(() => {
if (!days) return [];
const byDay = new Map<number, string[]>();
for (const item of pending) {
const id = dayOf(item);
if (id !== null) byDay.set(id, [...(byDay.get(id) ?? []), item.toolCallId]);
}
if (byDay.size < WEEK_FROM_DAYS) return [];
const weekdayOf = (date: string | null | undefined) =>
date && /^\d{4}-\d{2}-\d{2}$/.test(date)
? new Intl.DateTimeFormat(locale, { weekday: 'short', timeZone: 'UTC' }).format(new Date(`${date}T00:00:00Z`))
: null;
return days.flatMap((day, index) => {
const ids = byDay.get(day.id);
return ids ? [{ id: day.id, n: index + 1, weekday: weekdayOf(day.date), ids }] : [];
});
}, [days, pending, locale]);
}