mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 01:28:55 +00:00
fix(assistant): improve trip proposals and approvals
This commit is contained in:
@@ -640,7 +640,6 @@
|
||||
"src/components/Planner/PlaceFormModal.helpers.test.ts",
|
||||
"src/components/Planner/PlaceFormModal.helpers.ts",
|
||||
"src/components/Planner/PlaceFormModal.test.tsx",
|
||||
"src/components/Planner/PlaceFormModal.tsx",
|
||||
"src/components/Planner/PlaceInspector.test.tsx",
|
||||
"src/components/Planner/PlaceInspector.tsx",
|
||||
"src/components/Planner/PlacesBulkCategoryModal.test.tsx",
|
||||
|
||||
@@ -11,12 +11,13 @@
|
||||
import type { AssistantApplied, AssistantChangeEffect, AssistantChangePreview } from '@trek/shared';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { buildAssignment, buildDay, buildPlace, buildTrip } from '../../../tests/helpers/factories';
|
||||
import { act, fireEvent, render, screen } from '../../../tests/helpers/render';
|
||||
import { buildAssignment, buildCategory, buildDay, buildPlace, buildTrip } from '../../../tests/helpers/factories';
|
||||
import { act, fireEvent, render, screen, within } from '../../../tests/helpers/render';
|
||||
import { chatOf, useAssistantStore } from '../../store/assistantStore';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
import AssistantChangeCard from './AssistantChangeCard';
|
||||
import AssistantCompareSwitch from './AssistantCompareSwitch';
|
||||
import AssistantDayPreview from './AssistantDayPreview';
|
||||
import type { ChangeItem } from './assistantParts';
|
||||
import { type AssistantView, AssistantViewContext } from './assistantViewContext';
|
||||
|
||||
@@ -168,6 +169,106 @@ describe('AssistantChangeCard: deciding', () => {
|
||||
expect(screen.getByRole('button', { name: 'Apply' })).toBeDisabled();
|
||||
expect(screen.getByRole('button', { name: 'Discard' })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('edits a place proposal in the full place form and previews edits before applying', async () => {
|
||||
plannerHere();
|
||||
const change = {
|
||||
...preview('c1', 'Kinkaku-ji'),
|
||||
verbKey: 'addPlaceToDay' as const,
|
||||
effect: { ...PANTHEON, place: { name: 'Kinkaku-ji', lat: 48, lng: 2, categoryId: 31 } },
|
||||
};
|
||||
const other = { ...change, toolCallId: 'c2', subject: 'Tea house', effect: null };
|
||||
useTripStore.setState({
|
||||
categories: [
|
||||
buildCategory({ id: 31, name: 'Temple', color: '#334455' }),
|
||||
buildCategory({ id: 32, name: 'Garden', color: '#667788' }),
|
||||
],
|
||||
});
|
||||
patchChat({
|
||||
messages: [
|
||||
{
|
||||
id: 'm1',
|
||||
role: 'assistant',
|
||||
status: 'complete',
|
||||
createdAt: new Date().toISOString(),
|
||||
parts: [
|
||||
{
|
||||
type: 'tool-call',
|
||||
toolCallId: 'c1',
|
||||
toolName: 'create_and_assign_place',
|
||||
args: {},
|
||||
approval: { id: 'c1' },
|
||||
},
|
||||
{ type: 'data-trek-change', data: change },
|
||||
{
|
||||
type: 'tool-call',
|
||||
toolCallId: 'c2',
|
||||
toolName: 'create_and_assign_place',
|
||||
args: {},
|
||||
approval: { id: 'c2' },
|
||||
},
|
||||
{ type: 'data-trek-change', data: other },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
render(<AssistantDayPreview tripId={TRIP} dayId={3} />);
|
||||
renderCard([
|
||||
{ ...pending('c1', 'Kinkaku-ji'), preview: change },
|
||||
{ ...pending('c2', 'Tea house'), preview: other },
|
||||
]);
|
||||
const day = screen.getByRole('list', { name: 'Suggested by the assistant' });
|
||||
|
||||
const [edit] = screen.getAllByRole('button', { name: 'Edit' });
|
||||
fireEvent.click(edit);
|
||||
const dialog = within(await screen.findByRole('dialog', { name: 'Edit Place' }));
|
||||
expect(dialog.getByRole('textbox', { name: /^Name/ })).toHaveValue('Kinkaku-ji');
|
||||
expect(dialog.getByRole('textbox', { name: 'Address' })).toBeVisible();
|
||||
fireEvent.change(dialog.getByRole('textbox', { name: 'Start' }), { target: { value: '12:30' } });
|
||||
fireEvent.change(dialog.getByRole('textbox', { name: 'Notes for this day' }), {
|
||||
target: { value: 'Use the side entrance' },
|
||||
});
|
||||
fireEvent.click(dialog.getByRole('button', { name: /^Category:/ }));
|
||||
fireEvent.click(screen.getByRole('button', { name: /^Garden$/ }));
|
||||
expect(day).toHaveTextContent('12:30');
|
||||
expect(day).toHaveTextContent('Use the side entrance');
|
||||
expect(within(day).getByText('Garden').parentElement).toHaveStyle({ backgroundColor: '#667788' });
|
||||
expect(decide).not.toHaveBeenCalled();
|
||||
fireEvent.click(dialog.getByRole('button', { name: 'Cancel' }));
|
||||
expect(day).toHaveTextContent('10:30');
|
||||
expect(day).toHaveTextContent('Temple');
|
||||
expect(day).not.toHaveTextContent('Use the side entrance');
|
||||
|
||||
fireEvent.click(edit);
|
||||
const reopened = within(await screen.findByRole('dialog', { name: 'Edit Place' }));
|
||||
const time = reopened.getByRole('textbox', { name: 'Start' });
|
||||
expect(time).toHaveValue('10:30');
|
||||
fireEvent.change(time, { target: { value: '11:45' } });
|
||||
fireEvent.change(reopened.getByRole('textbox', { name: /^Name/ }), { target: { value: 'Golden Pavilion' } });
|
||||
fireEvent.change(reopened.getByRole('textbox', { name: 'Address' }), { target: { value: 'Kyoto, Japan' } });
|
||||
expect(day).toHaveTextContent('Golden Pavilion');
|
||||
fireEvent.click(reopened.getByRole('button', { name: 'Save' }));
|
||||
expect(day).toHaveTextContent('11:45');
|
||||
expect(decide).not.toHaveBeenCalled();
|
||||
|
||||
const [include] = screen.getAllByRole('button', { name: 'Include this change' });
|
||||
fireEvent.click(include);
|
||||
expect(day).not.toHaveTextContent('Golden Pavilion');
|
||||
expect(day).toHaveTextContent('Tea house');
|
||||
fireEvent.click(include);
|
||||
expect(day).toHaveTextContent('Golden Pavilion');
|
||||
expect(day).toHaveTextContent('11:45');
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Apply 2' }));
|
||||
expect(decide).toHaveBeenCalledWith(TRIP, [
|
||||
{
|
||||
toolCallId: 'c1',
|
||||
approved: true,
|
||||
planEdits: { startTime: '11:45', place: { name: 'Golden Pavilion', address: 'Kyoto, Japan' } },
|
||||
},
|
||||
{ toolCallId: 'c2', approved: true },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('AssistantChangeCard: the receipt', () => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Check, CheckCheck, ListChecks, LoaderCircle, MapPin, Undo2 } from 'lucide-react';
|
||||
import { Check, CheckCheck, ChevronDown, ListChecks, LoaderCircle, MapPin, Undo2 } from 'lucide-react';
|
||||
import { type ReactNode, useEffect, useMemo, useState } from 'react';
|
||||
|
||||
import { useTranslation } from '../../i18n';
|
||||
@@ -78,13 +78,21 @@ function dayChangesOf(items: readonly ChangeItem[], excluded: ReadonlySet<string
|
||||
/** The change card's band: tinted green once everything in it is decided, what it holds and its actions. */
|
||||
function CardHead({ open, count, actions }: { open: boolean; count: number; actions?: ReactNode }) {
|
||||
const { t } = useTranslation();
|
||||
const Icon = open ? ListChecks : CheckCheck;
|
||||
return (
|
||||
<CardHeader
|
||||
icon={open ? ListChecks : CheckCheck}
|
||||
icon={Icon}
|
||||
tone={open ? 'info' : 'success'}
|
||||
tint={open ? NEUTRAL_TINT : DONE_TINT}
|
||||
title={t(open ? 'assistant.change.title' : 'assistant.change.doneTitle')}
|
||||
count={count}
|
||||
tile={
|
||||
<span className="relative grid h-8 w-8 shrink-0 place-items-center rounded-[10px] bg-surface-card shadow-sm">
|
||||
<Icon size={15} strokeWidth={2} className={open ? 'text-info' : 'text-success'} aria-hidden="true" />
|
||||
<span className="absolute -end-1 -top-1 inline-flex h-4 min-w-4 items-center justify-center rounded-full bg-surface-card px-1 font-geist text-caption font-bold tabular-nums leading-none text-content-secondary shadow-sm ring-1 ring-edge">
|
||||
{count}
|
||||
</span>
|
||||
</span>
|
||||
}
|
||||
actions={actions}
|
||||
/>
|
||||
);
|
||||
@@ -186,11 +194,23 @@ export default function AssistantChangeCard({ items }: { items: ChangeItem[] })
|
||||
const undone = useAssistantStore((s) => chatOf(s, tripId).undone);
|
||||
const decide = useAssistantStore((s) => s.decide);
|
||||
const undo = useAssistantStore((s) => s.undo);
|
||||
const [excluded, setExcluded] = useChangeExclusions(items);
|
||||
const choices = useAssistantStore((s) => chatOf(s, tripId).changeChoices);
|
||||
const choosePlanChanges = useAssistantStore((s) => s.choosePlanChanges);
|
||||
const excluded = useChangeExclusions(items, choices);
|
||||
const planEdits = useAssistantStore((s) => chatOf(s, tripId).planEdits);
|
||||
const savePlanEdit = useAssistantStore((s) => s.savePlanEdit);
|
||||
const now = useUndoClock(items);
|
||||
|
||||
const pending = items.filter((i) => i.state === 'pending');
|
||||
const chosen = pending.filter((i) => !excluded.has(i.toolCallId)).length;
|
||||
const invalid = pending.some((i) => !excluded.has(i.toolCallId) && planEdits[i.toolCallId]?.noteTitle?.trim() === '');
|
||||
const planDayId = pending[0]?.preview?.dayId;
|
||||
const planDay = useTripStore((s) => (s.trip?.id === tripId ? s.days.find((day) => day.id === planDayId) : undefined));
|
||||
const groupedDay =
|
||||
pending.length > 1 &&
|
||||
pending.length === items.length &&
|
||||
!!planDay &&
|
||||
pending.every((i) => i.preview?.dayId === planDayId);
|
||||
const changes = useMemo(() => dayChangesOf(items, excluded), [items, excluded]);
|
||||
const undoable = items.filter((i) => undoableNow(i, undone, now)).map((i) => i.toolCallId);
|
||||
|
||||
@@ -199,27 +219,17 @@ export default function AssistantChangeCard({ items }: { items: ChangeItem[] })
|
||||
// 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);
|
||||
if (!next.delete(toolCallId)) next.add(toolCallId);
|
||||
return next;
|
||||
});
|
||||
const toggleDay = (ids: readonly string[], include: boolean) => choosePlanChanges(tripId, ids, include);
|
||||
const toggle = (toolCallId: string) => toggleDay([toolCallId], excluded.has(toolCallId));
|
||||
|
||||
const submit = (applyChosen: boolean) =>
|
||||
decide(
|
||||
tripId,
|
||||
pending.map((i) => ({ toolCallId: i.toolCallId, approved: applyChosen && !excluded.has(i.toolCallId) }))
|
||||
pending.map((i) => {
|
||||
const approved = applyChosen && !excluded.has(i.toolCallId);
|
||||
const edits = approved ? planEdits[i.toolCallId] : undefined;
|
||||
return { toolCallId: i.toolCallId, approved, ...(edits ? { planEdits: edits } : {}) };
|
||||
})
|
||||
);
|
||||
|
||||
// An undone change reads as undone from the store; only what stays needs a word.
|
||||
@@ -230,6 +240,21 @@ export default function AssistantChangeCard({ items }: { items: ChangeItem[] })
|
||||
};
|
||||
|
||||
const open = pending.length > 0;
|
||||
const rows = (
|
||||
<ChangeRows
|
||||
items={items}
|
||||
folded={folded}
|
||||
excluded={excluded}
|
||||
disabled={isRunning}
|
||||
undone={undone}
|
||||
undoable={undoable}
|
||||
onToggle={toggle}
|
||||
onUndo={(toolCallId) => void runUndo(toolCallId)}
|
||||
groupedDay={groupedDay}
|
||||
planEdits={planEdits}
|
||||
onEdit={(id, patch) => savePlanEdit(tripId, id, patch)}
|
||||
/>
|
||||
);
|
||||
return (
|
||||
<section className="trek-popover-enter overflow-hidden rounded-[16px] border border-edge-faint bg-surface-card px-3.5 pb-3 pt-3 shadow-card">
|
||||
<CardHead
|
||||
@@ -249,16 +274,31 @@ export default function AssistantChangeCard({ items }: { items: ChangeItem[] })
|
||||
{t('assistant.week.showAll', { count: pending.length })}
|
||||
</button>
|
||||
)}
|
||||
<ChangeRows
|
||||
items={items}
|
||||
folded={folded}
|
||||
excluded={excluded}
|
||||
disabled={isRunning}
|
||||
undone={undone}
|
||||
undoable={undoable}
|
||||
onToggle={toggle}
|
||||
onUndo={(toolCallId) => void runUndo(toolCallId)}
|
||||
/>
|
||||
{!folded && groupedDay && planDay ? (
|
||||
<details open className="group/day mt-1">
|
||||
<summary className="-mx-1.5 flex min-w-0 cursor-pointer list-none items-center gap-2.5 rounded-xl bg-surface-tertiary py-2 pe-3.5 ps-1.5 text-start hover:bg-surface-hover focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent [&::-webkit-details-marker]:hidden">
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="grid h-8 w-8 shrink-0 place-items-center rounded-[10px] bg-surface-card font-geist text-caption font-bold tabular-nums text-content-muted shadow-sm"
|
||||
>
|
||||
{planDay.day_number}
|
||||
</span>
|
||||
<span className="shrink-0 text-body font-bold text-content">
|
||||
{t('assistant.week.day')} {planDay.day_number}
|
||||
</span>
|
||||
{planDay.title && <bdi className="min-w-0 truncate text-caption text-content-muted">{planDay.title}</bdi>}
|
||||
<ChevronDown
|
||||
size={15}
|
||||
strokeWidth={2}
|
||||
aria-hidden="true"
|
||||
className="ms-auto shrink-0 -rotate-90 text-content-muted group-open/day:rotate-0"
|
||||
/>
|
||||
</summary>
|
||||
{rows}
|
||||
</details>
|
||||
) : (
|
||||
rows
|
||||
)}
|
||||
{open && (
|
||||
<>
|
||||
<p className="sr-only" role="status">
|
||||
@@ -270,7 +310,7 @@ export default function AssistantChangeCard({ items }: { items: ChangeItem[] })
|
||||
</DialogButton>
|
||||
<DialogButton
|
||||
variant="primary"
|
||||
disabled={isRunning || chosen === 0}
|
||||
disabled={isRunning || chosen === 0 || invalid}
|
||||
onClick={() => void submit(true)}
|
||||
icon={<Check size={14} aria-hidden="true" />}
|
||||
>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { AssistantChangeLabelKey, AssistantChangeRow } from '@trek/shared';
|
||||
import type { AssistantChangeLabelKey, AssistantChangeRow, AssistantPlanEdits } from '@trek/shared';
|
||||
import {
|
||||
CalendarClock,
|
||||
CalendarDays,
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
} from 'lucide-react';
|
||||
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
import { FactChange } from './cards/parts/CardFacts';
|
||||
|
||||
/**
|
||||
@@ -45,10 +46,42 @@ function shown(row: AssistantChangeRow, value: string | null | undefined, dayWor
|
||||
return value ?? '';
|
||||
}
|
||||
|
||||
export default function AssistantChangeFields({ rows }: { rows: AssistantChangeRow[] }) {
|
||||
export default function AssistantChangeFields({
|
||||
rows,
|
||||
visit = false,
|
||||
edits,
|
||||
}: {
|
||||
rows: AssistantChangeRow[];
|
||||
visit?: boolean;
|
||||
edits?: AssistantPlanEdits;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const categoryName = useTripStore((s) =>
|
||||
edits?.categoryId == null ? undefined : s.categories.find((category) => category.id === edits.categoryId)?.name
|
||||
);
|
||||
const dayWord = t('assistant.week.day');
|
||||
const facts = rows
|
||||
let editedRows = rows;
|
||||
if (visit && edits) {
|
||||
const fields = [
|
||||
['time', edits.startTime],
|
||||
['endTime', edits.endTime],
|
||||
['category', edits.categoryId === null ? null : categoryName],
|
||||
] as const;
|
||||
for (const [labelKey, after] of fields) {
|
||||
if (after === undefined) continue;
|
||||
editedRows = editedRows.filter((row) => row.labelKey !== labelKey);
|
||||
if (after) editedRows.push({ op: 'add', labelKey, before: null, after });
|
||||
}
|
||||
}
|
||||
const end = visit ? editedRows.find((row) => row.labelKey === 'endTime')?.after : undefined;
|
||||
const start = visit ? editedRows.find((row) => row.labelKey === 'time') : undefined;
|
||||
const visible =
|
||||
start?.after && end
|
||||
? editedRows
|
||||
.filter((row) => row.labelKey !== 'endTime')
|
||||
.map((row) => (row === start ? { ...row, after: `${row.after} – ${end}` } : row))
|
||||
: editedRows;
|
||||
const facts = visible
|
||||
.filter((row) => row.labelKey in KEY_FIELDS && row.after)
|
||||
.sort((a, b) => KEY_ORDER.indexOf(a.labelKey) - KEY_ORDER.indexOf(b.labelKey))
|
||||
.slice(0, MAX_FACTS);
|
||||
|
||||
@@ -1,18 +1,28 @@
|
||||
import type { AssistantChangeEffect, AssistantMessage } from '@trek/shared';
|
||||
import { ArrowRightLeft, Minus, Sparkles } from 'lucide-react';
|
||||
import type { AssistantChangePreview, AssistantMessage, AssistantPlanEdits } from '@trek/shared';
|
||||
import { ArrowRightLeft, FileText, MapPin, Minus, type LucideIcon } 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 { useSettingsStore } from '../../store/settingsStore';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
import type { Place } from '../../types';
|
||||
import { formatTime } from '../../utils/formatters';
|
||||
import { TimePill } from '../Planner/planParts';
|
||||
import { getCategoryIcon } from '../shared/categoryIcons';
|
||||
import { isDayNoteProposal, isVisitProposal, planField, proposalNote } from './AssistantPlanFields';
|
||||
|
||||
/** What a waiting change does to one day, as a row of the preview. */
|
||||
interface PreviewRow {
|
||||
toolCallId: string;
|
||||
kind: 'add' | 'in' | 'remove' | 'out';
|
||||
kind: 'add' | 'in' | 'remove' | 'out' | 'note';
|
||||
name: string;
|
||||
categoryId: number | null;
|
||||
categoryName?: string;
|
||||
start?: string;
|
||||
end?: string;
|
||||
detail?: string;
|
||||
}
|
||||
|
||||
/** The changes no one has decided on yet, by their call. */
|
||||
@@ -29,25 +39,48 @@ function waitingCalls(messages: readonly AssistantMessage[]): Set<string> {
|
||||
}
|
||||
|
||||
function rowOf(
|
||||
toolCallId: string,
|
||||
effect: AssistantChangeEffect,
|
||||
preview: AssistantChangePreview,
|
||||
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;
|
||||
places: readonly Place[],
|
||||
edits: AssistantPlanEdits | undefined
|
||||
): PreviewRow | null {
|
||||
const { toolCallId, effect, subject } = preview;
|
||||
if (preview.dayId === dayId && isDayNoteProposal(preview)) {
|
||||
return {
|
||||
toolCallId,
|
||||
kind: 'note',
|
||||
name: edits?.noteTitle || planField(preview, 'title') || subject,
|
||||
categoryId: null,
|
||||
detail: proposalNote(preview, edits) ?? undefined,
|
||||
};
|
||||
}
|
||||
if (effect.kind === 'move' && effect.fromDayId === dayId)
|
||||
return { toolCallId, kind: 'out', name } satisfies PreviewRow;
|
||||
const place = places.find((p) => p.id === effect?.placeId);
|
||||
const row = {
|
||||
toolCallId,
|
||||
name: edits?.place?.name ?? effect?.place?.name ?? place?.name ?? subject,
|
||||
categoryId:
|
||||
edits?.categoryId === undefined ? (effect?.place?.categoryId ?? place?.category_id ?? null) : edits.categoryId,
|
||||
categoryName: edits?.categoryId === undefined ? planField(preview, 'category') : undefined,
|
||||
start: edits?.startTime === undefined ? planField(preview, 'time') : (edits.startTime ?? undefined),
|
||||
end: edits?.endTime === undefined ? planField(preview, 'endTime') : (edits.endTime ?? undefined),
|
||||
detail:
|
||||
(edits?.notes === undefined ? planField(preview, 'notes') : edits.notes) ||
|
||||
(edits?.place?.description === undefined ? planField(preview, 'description') : edits.place.description) ||
|
||||
place?.description ||
|
||||
(edits?.place?.address === undefined ? planField(preview, 'address') : edits.place.address) ||
|
||||
place?.address ||
|
||||
undefined,
|
||||
};
|
||||
if (!effect) return preview.dayId === dayId && isVisitProposal(preview) ? { ...row, kind: 'add' } : null;
|
||||
if (effect.dayId === dayId)
|
||||
return { ...row, kind: effect.kind === 'remove' ? 'remove' : effect.kind === 'move' ? 'in' : 'add' };
|
||||
if (effect.kind === 'move' && effect.fromDayId === dayId) return { ...row, kind: 'out' };
|
||||
return null;
|
||||
}
|
||||
|
||||
const LOOK: Record<PreviewRow['kind'], { icon: typeof Sparkles; row: string; name: string; badgeKey: string }> = {
|
||||
const LOOK: Record<PreviewRow['kind'], { icon: LucideIcon; row: string; name: string; badgeKey: string }> = {
|
||||
add: {
|
||||
icon: Sparkles,
|
||||
icon: MapPin,
|
||||
row: 'border-dashed border-accent bg-accent-subtle',
|
||||
name: 'text-content',
|
||||
badgeKey: 'assistant.preview.suggested',
|
||||
@@ -70,6 +103,12 @@ const LOOK: Record<PreviewRow['kind'], { icon: typeof Sparkles; row: string; nam
|
||||
name: 'text-content-faint line-through',
|
||||
badgeKey: 'assistant.preview.movedAway',
|
||||
},
|
||||
note: {
|
||||
icon: FileText,
|
||||
row: 'border-dashed border-accent bg-accent-subtle',
|
||||
name: 'text-content',
|
||||
badgeKey: 'assistant.preview.suggested',
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -80,31 +119,45 @@ const LOOK: Record<PreviewRow['kind'], { icon: typeof Sparkles; row: string; nam
|
||||
* 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 { t, locale } = useTranslation();
|
||||
const timeFormat = useSettingsStore((s) => s.settings.time_format) || '24h';
|
||||
const messages = useAssistantStore((s) => chatOf(s, tripId).messages);
|
||||
const savedEdits = useAssistantStore((s) => chatOf(s, tripId).planEdits);
|
||||
const liveEdit = useAssistantStore((s) => chatOf(s, tripId).planEditPreview);
|
||||
const choices = useAssistantStore((s) => chatOf(s, tripId).changeChoices);
|
||||
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 categories = useTripStore((s) => s.categories);
|
||||
|
||||
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]);
|
||||
return messages.flatMap((message) =>
|
||||
message.parts.flatMap((part) => {
|
||||
if (part.type !== 'data-trek-change' || !waiting.delete(part.data.toolCallId)) return [];
|
||||
const id = part.data.toolCallId;
|
||||
if (choices[id] === false) return [];
|
||||
const edits = liveEdit?.toolCallId === id ? liveEdit.edits : savedEdits[id];
|
||||
const row = rowOf(part.data, dayId, places, edits);
|
||||
return row ? [row] : [];
|
||||
})
|
||||
);
|
||||
}, [messages, places, dayId, savedEdits, liveEdit, choices]);
|
||||
|
||||
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 category = categories.find((entry) =>
|
||||
row.categoryId ? entry.id === row.categoryId : entry.name === row.categoryName
|
||||
);
|
||||
const Icon = category ? getCategoryIcon(category.icon) : look.icon;
|
||||
const time = [row.start, row.end]
|
||||
.filter((value): value is string => !!value)
|
||||
.map((value) => formatTime(value, locale, timeFormat))
|
||||
.join(' – ');
|
||||
const lit = hovered === row.toolCallId;
|
||||
return (
|
||||
<li
|
||||
@@ -121,11 +174,29 @@ export default function AssistantDayPreview({ tripId, dayId }: { tripId: number;
|
||||
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
|
||||
className="grid h-8 w-8 flex-shrink-0 place-items-center rounded-full bg-surface-card text-content-muted shadow-sm"
|
||||
style={category?.color ? { backgroundColor: category.color, color: 'white' } : undefined}
|
||||
>
|
||||
<Icon size={14} aria-hidden="true" />
|
||||
{(category?.name || row.categoryName) && (
|
||||
<span className="sr-only">{category?.name ?? row.categoryName}</span>
|
||||
)}
|
||||
</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">
|
||||
<span className="min-w-0 flex-1">
|
||||
<bdi className={`block truncate text-body font-medium ${look.name}`}>{row.name}</bdi>
|
||||
{time && (
|
||||
<span className="mt-0.5 flex">
|
||||
<TimePill quiet>{time}</TimePill>
|
||||
</span>
|
||||
)}
|
||||
{row.detail && (
|
||||
<bdi className="mt-0.5 line-clamp-2 break-words text-caption text-content-muted">{row.detail}</bdi>
|
||||
)}
|
||||
</span>
|
||||
<span
|
||||
className={row.kind === 'add' || row.kind === 'note' ? 'sr-only' : 'flex-shrink-0 text-content-muted'}
|
||||
>
|
||||
{t(look.badgeKey)}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
@@ -4,10 +4,11 @@
|
||||
* The error line: one sentence, at most one thing to do, and that thing
|
||||
* does what it says.
|
||||
*/
|
||||
import type { AiStatusResponse, AssistantErrorCode } from '@trek/shared';
|
||||
import type { AiStatusResponse, AssistantErrorCode, AssistantMessage } from '@trek/shared';
|
||||
import { Route, Routes } from 'react-router';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { HIKE } from '../../../tests/helpers/assistantTour';
|
||||
import { fireEvent, render, screen } from '../../../tests/helpers/render';
|
||||
import { chatOf, useAssistantStore } from '../../store/assistantStore';
|
||||
import { setForcedOffline } from '../../sync/networkMode';
|
||||
@@ -33,13 +34,17 @@ const retry = vi.fn(async () => {});
|
||||
const continueHere = vi.fn(async () => {});
|
||||
const send = vi.fn(async () => {});
|
||||
|
||||
function withError(error: AssistantErrorCode | null, status: AiStatusResponse = STATUS) {
|
||||
function withError(
|
||||
error: AssistantErrorCode | null,
|
||||
status: AiStatusResponse = STATUS,
|
||||
messages: AssistantMessage[] = []
|
||||
) {
|
||||
useAssistantStore.setState({
|
||||
status,
|
||||
retry,
|
||||
continueHere,
|
||||
send,
|
||||
byTrip: { [TRIP]: { ...chatOf(useAssistantStore.getState(), TRIP), error } },
|
||||
byTrip: { [TRIP]: { ...chatOf(useAssistantStore.getState(), TRIP), error, messages } },
|
||||
});
|
||||
}
|
||||
|
||||
@@ -119,6 +124,25 @@ describe('AssistantError', () => {
|
||||
expect(screen.queryByRole('button')).toBeNull();
|
||||
});
|
||||
|
||||
it('keeps a calculated route distinct from the rate-limited reply', () => {
|
||||
const when = '2026-10-21T08:00:00.000Z';
|
||||
const question: AssistantMessage = { id: 'm1', role: 'user', status: 'complete', parts: [], createdAt: when };
|
||||
const answer: AssistantMessage = {
|
||||
id: 'm2',
|
||||
role: 'assistant',
|
||||
status: 'error',
|
||||
createdAt: when,
|
||||
parts: [{ type: 'data-trek-card', data: { toolCallId: 'hike', card: HIKE } }],
|
||||
};
|
||||
withError('rate_limited', STATUS, [question, answer]);
|
||||
const { unmount } = renderLine();
|
||||
expect(screen.getByRole('status')).toHaveTextContent('The route preview is still available.');
|
||||
unmount();
|
||||
withError('rate_limited', STATUS, [question, answer, { ...question, id: 'm3' }]);
|
||||
renderLine();
|
||||
expect(screen.getByRole('status')).toHaveTextContent('Limit reached at Anthropic. Try again later.');
|
||||
});
|
||||
|
||||
it('FE-AI-ERR-008: waiting changes ask for a decision before a place can be suggested', () => {
|
||||
withError('decide_first');
|
||||
renderLine();
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useNavigate } from 'react-router';
|
||||
import { useNetworkMode } from '../../hooks/useNetworkMode';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { chatOf, useAssistantStore } from '../../store/assistantStore';
|
||||
import { type AssistantErrorActionKind, connectionErrorOf, errorView } from './assistantModel';
|
||||
import { type AssistantErrorActionKind, connectionErrorOf, errorView, hasCurrentTourProposal } from './assistantModel';
|
||||
import { AI_SETTINGS_PATH } from './assistantParts';
|
||||
import { CHATGPT_USAGE_URL, providerLabel } from './providerCatalog';
|
||||
|
||||
@@ -18,6 +18,10 @@ export default function AssistantError({ tripId }: { tripId: number }) {
|
||||
const navigate = useNavigate();
|
||||
const { offline } = useNetworkMode();
|
||||
const error = useAssistantStore((s) => chatOf(s, tripId).error);
|
||||
const hasTourProposal = useAssistantStore((s) => {
|
||||
const chat = chatOf(s, tripId);
|
||||
return chat.error === 'rate_limited' && hasCurrentTourProposal(chat.messages);
|
||||
});
|
||||
const status = useAssistantStore((s) => s.status);
|
||||
const retry = useAssistantStore((s) => s.retry);
|
||||
const continueHere = useAssistantStore((s) => s.continueHere);
|
||||
@@ -28,7 +32,7 @@ export default function AssistantError({ tripId }: { tripId: number }) {
|
||||
|
||||
const effective = status?.effective;
|
||||
const provider = effective ? providerLabel(effective.kind, effective.host) : '';
|
||||
const view = errorView(code, { canConnectOwn: status?.canConnectOwn ?? false, provider });
|
||||
const view = errorView(code, { canConnectOwn: status?.canConnectOwn ?? false, provider, hasTourProposal });
|
||||
|
||||
const run = (kind: AssistantErrorActionKind) => {
|
||||
if (kind === 'retry') void retry(tripId);
|
||||
|
||||
@@ -139,7 +139,8 @@ function Answer({ message }: { message: StoredMessage }) {
|
||||
});
|
||||
const blocks = useMemo(() => messageBlocks(message, writing), [message, writing]);
|
||||
const share = useAssistantShare(tripId, message, writing);
|
||||
const last = blocks[blocks.length - 1];
|
||||
const end = blocks[blocks.length - 1];
|
||||
const last = end?.kind === 'sources' ? blocks[blocks.length - 2] : end;
|
||||
const hasText = blocks.some((b) => b.kind === 'text');
|
||||
const tail = tailStart(blocks);
|
||||
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
import type { AssistantChangePreview, AssistantPlanEdits } from '@trek/shared';
|
||||
import { assistantPlanEditsSchema, parsePlaceHours, placeOpeningHoursSchema } from '@trek/shared';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { useIsPhone } from '../../mobile/useIsPhone';
|
||||
import { useAssistantStore } from '../../store/assistantStore';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
import PlaceFormModal from '../Planner/PlaceFormModal';
|
||||
import { DEFAULT_FORM, formPin, type PlaceFormData } from '../Planner/PlaceFormModal.helpers';
|
||||
import { planField } from './AssistantPlanFields';
|
||||
import { useAssistantView } from './assistantViewContext';
|
||||
|
||||
type PlacePatch = NonNullable<AssistantPlanEdits['place']>;
|
||||
|
||||
function originalForm(preview: AssistantChangePreview, rawArgs: unknown, categoryId: number | null): PlaceFormData {
|
||||
const args = rawArgs && typeof rawArgs === 'object' ? (rawArgs as Record<string, unknown>) : {};
|
||||
const value = (key: string) => (typeof args[key] === 'string' ? args[key] : '');
|
||||
const point = preview.effect?.place;
|
||||
const hours = placeOpeningHoursSchema.safeParse(args.opening_hours);
|
||||
return {
|
||||
...DEFAULT_FORM,
|
||||
name: value('name') || point?.name || preview.subject,
|
||||
address: value('address') || planField(preview, 'address') || '',
|
||||
description: value('description') || planField(preview, 'description') || '',
|
||||
lat: String(typeof args.lat === 'number' ? args.lat : (point?.lat ?? '')),
|
||||
lng: String(typeof args.lng === 'number' ? args.lng : (point?.lng ?? '')),
|
||||
category_id: String(categoryId ?? ''),
|
||||
place_time: planField(preview, 'time') ?? '',
|
||||
end_time: planField(preview, 'endTime') ?? '',
|
||||
assignment_notes: planField(preview, 'notes') ?? '',
|
||||
notes: value('place_notes'),
|
||||
google_place_id: value('google_place_id'),
|
||||
google_ftid: value('google_ftid'),
|
||||
osm_id: value('osm_id'),
|
||||
amap_poi_id: value('amap_poi_id'),
|
||||
website: value('website'),
|
||||
phone: value('phone'),
|
||||
email: value('email'),
|
||||
opening_hours: hours.success ? JSON.stringify(hours.data) : '',
|
||||
image_url: value('image_url') || null,
|
||||
tags: Array.isArray(args.tags) ? args.tags.filter((tag): tag is number => Number.isInteger(tag)) : [],
|
||||
};
|
||||
}
|
||||
|
||||
function restoreDraft(form: PlaceFormData, edits: AssistantPlanEdits | undefined): PlaceFormData {
|
||||
const { lat, lng, place_notes, opening_hours, ...place } = edits?.place ?? {};
|
||||
const restored = Object.fromEntries(Object.entries(place).map(([field, value]) => [field, value ?? '']));
|
||||
return {
|
||||
...form,
|
||||
...restored,
|
||||
...(lat === undefined ? {} : { lat: String(lat ?? '') }),
|
||||
...(lng === undefined ? {} : { lng: String(lng ?? '') }),
|
||||
...(place_notes === undefined ? {} : { notes: place_notes ?? '' }),
|
||||
...(opening_hours === undefined ? {} : { opening_hours: opening_hours ? JSON.stringify(opening_hours) : '' }),
|
||||
...(edits?.startTime === undefined ? {} : { place_time: edits.startTime ?? '' }),
|
||||
...(edits?.endTime === undefined ? {} : { end_time: edits.endTime ?? '' }),
|
||||
...(edits?.notes === undefined ? {} : { assignment_notes: edits.notes ?? '' }),
|
||||
...(edits?.categoryId === undefined ? {} : { category_id: String(edits.categoryId ?? '') }),
|
||||
};
|
||||
}
|
||||
|
||||
function placeValues(form: PlaceFormData): PlacePatch {
|
||||
const position = formPin(form);
|
||||
return {
|
||||
name: form.name.trim(),
|
||||
description: form.description || null,
|
||||
address: form.address || null,
|
||||
lat: position?.lat ?? null,
|
||||
lng: position?.lng ?? null,
|
||||
google_place_id: form.google_place_id || null,
|
||||
google_ftid: form.google_ftid || null,
|
||||
osm_id: form.osm_id || null,
|
||||
amap_poi_id: form.amap_poi_id || null,
|
||||
place_notes: form.notes || null,
|
||||
website: form.website.trim() || null,
|
||||
phone: form.phone?.trim() || null,
|
||||
email: form.email?.trim() || null,
|
||||
opening_hours: parsePlaceHours(form.opening_hours),
|
||||
image_url: form.image_url || null,
|
||||
tags: form.tags ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
function changesOf(form: PlaceFormData, original: PlaceFormData, existing: boolean): AssistantPlanEdits {
|
||||
const edits: AssistantPlanEdits = {};
|
||||
if (form.place_time !== original.place_time) edits.startTime = form.place_time || null;
|
||||
if (form.end_time !== original.end_time) edits.endTime = form.end_time || null;
|
||||
if (form.assignment_notes !== original.assignment_notes) edits.notes = form.assignment_notes || null;
|
||||
if (!existing) {
|
||||
if (form.category_id !== original.category_id)
|
||||
edits.categoryId = form.category_id ? Number(form.category_id) : null;
|
||||
const previous = placeValues(original);
|
||||
const changed = Object.entries(placeValues(form)).filter(
|
||||
([field, value]) => JSON.stringify(previous[field as keyof PlacePatch]) !== JSON.stringify(value)
|
||||
);
|
||||
if (changed.length) edits.place = Object.fromEntries(changed);
|
||||
}
|
||||
return edits;
|
||||
}
|
||||
|
||||
export default function AssistantPlaceProposal({
|
||||
preview,
|
||||
args,
|
||||
edits,
|
||||
disabled,
|
||||
onEdit,
|
||||
onClose,
|
||||
}: {
|
||||
preview: AssistantChangePreview;
|
||||
args: unknown;
|
||||
edits: AssistantPlanEdits | undefined;
|
||||
disabled: boolean;
|
||||
onEdit: (edits: AssistantPlanEdits) => void;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const { tripId, variant } = useAssistantView();
|
||||
const phone = useIsPhone();
|
||||
const previewEdit = useAssistantStore((s) => s.previewPlanEdit);
|
||||
const categories = useTripStore((s) => s.categories);
|
||||
const dayAssignments = useTripStore((s) => (preview.dayId == null ? undefined : s.assignments[preview.dayId]));
|
||||
const currentPlace = useTripStore((s) => s.places.find((place) => place.id === preview.effect?.placeId));
|
||||
const existing = preview.verbKey === 'assignPlace';
|
||||
const [original] = useState(() => {
|
||||
const categoryId =
|
||||
preview.effect?.place?.categoryId ??
|
||||
currentPlace?.category_id ??
|
||||
categories.find((category) => category.name === planField(preview, 'category'))?.id ??
|
||||
null;
|
||||
const form = originalForm(preview, args, categoryId);
|
||||
return existing && currentPlace ? { ...form, name: currentPlace.name, address: currentPlace.address ?? '' } : form;
|
||||
});
|
||||
const [initialForm] = useState(() => restoreDraft(original, edits));
|
||||
const { toolCallId } = preview;
|
||||
const onPreview = useCallback(
|
||||
(form: PlaceFormData) => {
|
||||
if (!existing && (form.lat || form.lng) && !formPin(form)) return;
|
||||
const parsed = assistantPlanEditsSchema.safeParse(changesOf(form, original, existing));
|
||||
if (parsed.success) previewEdit(tripId, toolCallId, parsed.data);
|
||||
},
|
||||
[existing, original, previewEdit, toolCallId, tripId]
|
||||
);
|
||||
useEffect(() => () => previewEdit(tripId, toolCallId, null), [previewEdit, toolCallId, tripId]);
|
||||
const onSave = (form: PlaceFormData) => {
|
||||
if (!existing && (form.lat || form.lng) && !formPin(form)) throw new Error(t('places.saveError'));
|
||||
const parsed = assistantPlanEditsSchema.safeParse(changesOf(form, original, existing));
|
||||
if (!parsed.success) throw new Error(t('places.saveError'));
|
||||
onEdit(parsed.data);
|
||||
};
|
||||
|
||||
return (
|
||||
<PlaceFormModal
|
||||
isOpen
|
||||
onClose={onClose}
|
||||
place={null}
|
||||
tripId={tripId}
|
||||
categories={categories}
|
||||
assignmentId={null}
|
||||
dayAssignments={dayAssignments}
|
||||
isMobile={phone || variant === 'fullscreen'}
|
||||
proposal={{ initialForm, existing, dayId: preview.dayId, disabled, onPreview, onSave }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
import type { AssistantChangeLabelKey, AssistantChangePreview, AssistantPlanEdits } from '@trek/shared';
|
||||
import { Check, Pencil } from 'lucide-react';
|
||||
import { lazy, Suspense, useEffect, useId, useState } from 'react';
|
||||
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { useAssistantStore } from '../../store/assistantStore';
|
||||
import { EditorField, PANEL, TEXTAREA } from '../shared/dialogParts';
|
||||
import {
|
||||
DialogButton,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogShell,
|
||||
DialogTile,
|
||||
FooterSpacer,
|
||||
NEUTRAL_TINT,
|
||||
} from '../shared/DialogShell';
|
||||
import { Tooltip } from '../shared/Tooltip';
|
||||
import { useAssistantView } from './assistantViewContext';
|
||||
|
||||
const AssistantPlaceProposal = lazy(() => import('./AssistantPlaceProposal'));
|
||||
|
||||
export function isVisitProposal(preview: AssistantChangePreview | null | undefined) {
|
||||
return preview?.verbKey === 'addPlaceToDay' || preview?.verbKey === 'assignPlace';
|
||||
}
|
||||
|
||||
export function isDayNoteProposal(preview: AssistantChangePreview | null | undefined) {
|
||||
return preview?.verbKey === 'addDayNote' || preview?.verbKey === 'updateDayNote';
|
||||
}
|
||||
|
||||
export function planField(preview: AssistantChangePreview, field: AssistantChangeLabelKey) {
|
||||
return preview.rows.find((row) => row.labelKey === field)?.after;
|
||||
}
|
||||
|
||||
export function dayNoteBody(preview: AssistantChangePreview) {
|
||||
return planField(preview, 'content') ?? (preview.verbKey === 'addDayNote' ? planField(preview, 'time') : undefined);
|
||||
}
|
||||
|
||||
export function proposalNote(preview: AssistantChangePreview, edits: AssistantPlanEdits | undefined) {
|
||||
return isVisitProposal(preview)
|
||||
? edits?.notes === undefined
|
||||
? planField(preview, 'notes')
|
||||
: edits.notes
|
||||
: edits?.noteBody === undefined
|
||||
? dayNoteBody(preview)
|
||||
: edits.noteBody;
|
||||
}
|
||||
|
||||
interface ProposalEditProps {
|
||||
preview: AssistantChangePreview;
|
||||
args?: unknown;
|
||||
edits: AssistantPlanEdits | undefined;
|
||||
disabled: boolean;
|
||||
onEdit: (patch: AssistantPlanEdits) => void;
|
||||
}
|
||||
|
||||
export default function AssistantPlanFields({ preview, args, edits, disabled, onEdit }: ProposalEditProps) {
|
||||
const { t } = useTranslation();
|
||||
const [open, setOpen] = useState(false);
|
||||
return (
|
||||
<>
|
||||
<Tooltip label={t('common.edit')} disabled={disabled}>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('common.edit')}
|
||||
aria-haspopup="dialog"
|
||||
disabled={disabled}
|
||||
onClick={() => setOpen(true)}
|
||||
className="relative grid h-8 w-8 shrink-0 place-items-center self-start rounded-lg text-content-muted transition-colors focus-visible:ring-2 focus-visible:ring-accent enabled:hover:bg-accent enabled:hover:text-accent-text disabled:opacity-50 [@media(pointer:coarse)]:before:absolute [@media(pointer:coarse)]:before:-inset-1.5"
|
||||
>
|
||||
<Pencil size={14} aria-hidden="true" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
{open &&
|
||||
(isVisitProposal(preview) ? (
|
||||
<Suspense fallback={null}>
|
||||
<AssistantPlaceProposal
|
||||
preview={preview}
|
||||
args={args}
|
||||
edits={edits}
|
||||
disabled={disabled}
|
||||
onEdit={onEdit}
|
||||
onClose={() => setOpen(false)}
|
||||
/>
|
||||
</Suspense>
|
||||
) : (
|
||||
<DayNoteEditDialog
|
||||
preview={preview}
|
||||
edits={edits}
|
||||
disabled={disabled}
|
||||
onEdit={onEdit}
|
||||
onClose={() => setOpen(false)}
|
||||
/>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function DayNoteEditDialog({ preview, edits, disabled, onEdit, onClose }: ProposalEditProps & { onClose: () => void }) {
|
||||
const { t } = useTranslation();
|
||||
const { tripId } = useAssistantView();
|
||||
const { toolCallId } = preview;
|
||||
const previewPlanEdit = useAssistantStore((s) => s.previewPlanEdit);
|
||||
const id = useId();
|
||||
const [draft, setDraft] = useState<AssistantPlanEdits>(() => edits ?? {});
|
||||
const change = (patch: AssistantPlanEdits) => setDraft((current) => ({ ...current, ...patch }));
|
||||
const note = proposalNote(preview, draft);
|
||||
const noteTitle = draft.noteTitle ?? planField(preview, 'title') ?? preview.subject;
|
||||
useEffect(() => previewPlanEdit(tripId, toolCallId, draft), [draft, previewPlanEdit, toolCallId, tripId]);
|
||||
useEffect(() => () => previewPlanEdit(tripId, toolCallId, null), [previewPlanEdit, toolCallId, tripId]);
|
||||
const noteLabel = t('assistant.change.label.content');
|
||||
const save = () => {
|
||||
if (Object.keys(draft).length > 0) onEdit(draft);
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<DialogShell
|
||||
labelledBy={id}
|
||||
width="narrow"
|
||||
onClose={onClose}
|
||||
header={
|
||||
<DialogHeader
|
||||
labelId={id}
|
||||
tint={NEUTRAL_TINT}
|
||||
tile={
|
||||
<DialogTile>
|
||||
<Pencil size={19} aria-hidden="true" />
|
||||
</DialogTile>
|
||||
}
|
||||
eyebrow={t('common.edit')}
|
||||
titleInput={{
|
||||
label: t('assistant.change.label.title'),
|
||||
value: noteTitle,
|
||||
required: true,
|
||||
maxLength: 500,
|
||||
readOnly: disabled,
|
||||
onChange: (noteTitle) => change({ noteTitle }),
|
||||
}}
|
||||
onClose={onClose}
|
||||
/>
|
||||
}
|
||||
footer={
|
||||
<DialogFooter>
|
||||
<FooterSpacer />
|
||||
<DialogButton onClick={onClose}>{t('common.cancel')}</DialogButton>
|
||||
<DialogButton
|
||||
variant="primary"
|
||||
icon={<Check size={15} aria-hidden="true" />}
|
||||
onClick={save}
|
||||
disabled={disabled || !noteTitle.trim()}
|
||||
>
|
||||
{t('common.save')}
|
||||
</DialogButton>
|
||||
</DialogFooter>
|
||||
}
|
||||
>
|
||||
<fieldset disabled={disabled} className={`${PANEL} m-0 min-w-0`}>
|
||||
<EditorField label={noteLabel} htmlFor={`${id}-note`}>
|
||||
<textarea
|
||||
id={`${id}-note`}
|
||||
className={TEXTAREA}
|
||||
rows={4}
|
||||
maxLength={2000}
|
||||
value={note ?? ''}
|
||||
onChange={(e) => change({ noteBody: e.target.value || null })}
|
||||
/>
|
||||
</EditorField>
|
||||
</fieldset>
|
||||
</DialogShell>
|
||||
);
|
||||
}
|
||||
@@ -7,7 +7,7 @@
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { render, screen } from '../../../tests/helpers/render';
|
||||
import { fireEvent, render, screen } from '../../../tests/helpers/render';
|
||||
import AssistantSources from './AssistantSources';
|
||||
import { messageBlocks } from './assistantParts';
|
||||
|
||||
@@ -31,7 +31,8 @@ describe('AssistantSources', () => {
|
||||
expect(screen.getByRole('link', { name: 'example.org' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-AI-SOURCES-002: an answer keeps its sources as a block of their own after its text', () => {
|
||||
it('FE-AI-SOURCES-002: bundles citations from multiple steps below the changes and keeps links with JSON titles', () => {
|
||||
const exa = 'https://exa.ai/library/places?example=test';
|
||||
const blocks = messageBlocks(
|
||||
{
|
||||
id: 'm1',
|
||||
@@ -40,12 +41,46 @@ describe('AssistantSources', () => {
|
||||
createdAt: '2026-10-23T10:00:00.000Z',
|
||||
parts: [
|
||||
{ type: 'tool-call', toolCallId: 'web-1', toolName: 'web_search', args: { query: 'x' }, result: 'searched' },
|
||||
{
|
||||
type: 'data-trek-sources',
|
||||
data: {
|
||||
sources: [
|
||||
{ url: 'https://a.example', title: 'https://a.example' },
|
||||
{ url: exa, title: '{"places":[{"id":"truncated' },
|
||||
],
|
||||
},
|
||||
},
|
||||
{ type: 'text', text: 'Eat at the harbour.' },
|
||||
{ type: 'data-trek-sources', data: { sources: [{ url: 'https://a.example', title: 'A' }] } },
|
||||
{ type: 'tool-call', toolCallId: 'w1', toolName: 'create_todo', args: {}, approval: { id: 'w1' } },
|
||||
{ type: 'data-trek-sources', data: { sources: [{ url: 'https://a.example', title: 'Harbour guide' }] } },
|
||||
],
|
||||
},
|
||||
false
|
||||
);
|
||||
expect(blocks.map((block) => block.kind)).toEqual(['steps', 'text', 'sources']);
|
||||
expect(blocks.map((block) => block.kind)).toEqual(['steps', 'text', 'change', 'sources']);
|
||||
const sources = blocks.find((block) => block.kind === 'sources')?.sources;
|
||||
expect(sources).toEqual([
|
||||
{ url: 'https://a.example', title: 'Harbour guide' },
|
||||
{ url: exa, title: '' },
|
||||
]);
|
||||
render(<AssistantSources sources={sources ?? []} />);
|
||||
expect(screen.getByRole('link', { name: 'exa.ai' })).toHaveAttribute('href', exa);
|
||||
});
|
||||
|
||||
it('shows three links by default and lets the reader expand and collapse the list', () => {
|
||||
render(
|
||||
<AssistantSources
|
||||
sources={['One', 'Two', 'Three', 'Four'].map((title) => ({ title, url: `https://example.org/${title}` }))}
|
||||
/>
|
||||
);
|
||||
expect(screen.getAllByRole('link')).toHaveLength(3);
|
||||
const more = screen.getByRole('button', { name: 'More sources' });
|
||||
expect(more).toHaveAttribute('aria-expanded', 'false');
|
||||
fireEvent.click(more);
|
||||
expect(screen.getAllByRole('link')).toHaveLength(4);
|
||||
const less = screen.getByRole('button', { name: 'Show less' });
|
||||
expect(less).toHaveAttribute('aria-expanded', 'true');
|
||||
fireEvent.click(less);
|
||||
expect(screen.getAllByRole('link')).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import type { AssistantSources as Sources } from '@trek/shared';
|
||||
import { Globe } from 'lucide-react';
|
||||
import { ChevronDown, Globe } from 'lucide-react';
|
||||
import { useId, useState } from 'react';
|
||||
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { Tooltip } from '../shared/Tooltip';
|
||||
|
||||
const INITIAL_COUNT = 3;
|
||||
|
||||
/** A page's host without "www.", as the chip names it; the whole address where it does not read as one. */
|
||||
function hostOf(url: string): string {
|
||||
@@ -19,30 +23,48 @@ function hostOf(url: string): string {
|
||||
*/
|
||||
export default function AssistantSources({ sources }: { sources: Sources['sources'] }) {
|
||||
const { t } = useTranslation();
|
||||
const id = useId();
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const visible = expanded ? sources : sources.slice(0, INITIAL_COUNT);
|
||||
return (
|
||||
<nav aria-label={t('assistant.sources.title')} className="flex flex-col gap-1.5">
|
||||
<span className="font-geist text-caption font-bold uppercase tracking-[.08em] text-content-faint">
|
||||
{t('assistant.sources.title')}
|
||||
</span>
|
||||
<ul className="m-0 flex list-none flex-wrap gap-1.5 p-0">
|
||||
{sources.map((source) => (
|
||||
<li key={source.url} className="min-w-0 max-w-full">
|
||||
<a
|
||||
href={source.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer nofollow"
|
||||
title={source.title}
|
||||
className="flex min-w-0 max-w-[16rem] items-center gap-1.5 rounded-full border border-edge-faint bg-surface-secondary px-2.5 py-1 text-caption text-content-secondary no-underline transition-colors hover:bg-surface-hover hover:text-content"
|
||||
>
|
||||
<Globe size={11} strokeWidth={2.2} aria-hidden="true" className="flex-none text-content-faint" />
|
||||
<span className="flex-none font-medium">{hostOf(source.url)}</span>
|
||||
{source.title && source.title !== source.url && (
|
||||
<bdi className="min-w-0 truncate text-content-muted">{source.title}</bdi>
|
||||
)}
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
<ul id={id} className="m-0 flex list-none flex-wrap gap-1.5 p-0">
|
||||
{visible.map(({ url, title }) => {
|
||||
const host = hostOf(url);
|
||||
const label = title && title !== url ? title : host;
|
||||
return (
|
||||
<li key={url} className="min-w-0 max-w-full">
|
||||
<Tooltip label={label} placement="top">
|
||||
<a
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer nofollow"
|
||||
className="flex min-w-0 max-w-[18rem] items-center gap-1.5 rounded-full border border-edge-faint bg-surface-secondary px-2.5 py-1 text-caption no-underline transition-colors hover:bg-surface-hover focus-visible:ring-2 focus-visible:ring-accent"
|
||||
>
|
||||
<Globe size={11} strokeWidth={2.2} aria-hidden="true" className="flex-none text-content-faint" />
|
||||
<bdi className="min-w-0 truncate font-semibold text-content">{label}</bdi>
|
||||
{label !== host && <bdi className="max-w-[35%] shrink-0 truncate text-content-muted">{host}</bdi>}
|
||||
</a>
|
||||
</Tooltip>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
{sources.length > INITIAL_COUNT && (
|
||||
<button
|
||||
type="button"
|
||||
aria-expanded={expanded}
|
||||
aria-controls={id}
|
||||
onClick={() => setExpanded(!expanded)}
|
||||
className="inline-flex min-h-7 items-center gap-1 self-start rounded-md px-1.5 text-caption font-medium text-content-muted transition-colors hover:bg-surface-hover hover:text-content focus-visible:ring-2 focus-visible:ring-accent"
|
||||
>
|
||||
{t(expanded ? 'common.showLess' : 'assistant.sources.more')}
|
||||
<ChevronDown size={13} aria-hidden="true" className={expanded ? 'rotate-180' : ''} />
|
||||
</button>
|
||||
)}
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,8 +2,9 @@ import { ChevronRight } from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { POI_CATEGORIES } from '../Map/poiCategories';
|
||||
import AssistantLiveStep from './AssistantLiveStep';
|
||||
import { toolStepKey } from './assistantModel';
|
||||
import { liveStepText } from './assistantModel';
|
||||
import type { ToolStep } from './assistantParts';
|
||||
|
||||
/**
|
||||
@@ -37,9 +38,20 @@ export default function AssistantToolSteps({ steps }: { steps: ToolStep[] }) {
|
||||
</button>
|
||||
{open && (
|
||||
<ul className="m-0 mt-1 list-none space-y-0.5 border-s border-edge-faint ps-3">
|
||||
{steps.map((step) => (
|
||||
<li key={step.toolCallId}>{t(toolStepKey(step.toolName))}</li>
|
||||
))}
|
||||
{steps.map((step) => {
|
||||
const labels = step.categories?.flatMap((key) => {
|
||||
const category = POI_CATEGORIES.find((entry) => entry.key === key);
|
||||
return category ? [t(category.labelKey)] : [];
|
||||
});
|
||||
const { key, params } = labels?.length
|
||||
? { key: 'assistant.step.searchingFor', params: { query: labels.join(', ') } }
|
||||
: liveStepText(step.toolName, step.query ?? null);
|
||||
return (
|
||||
<li key={step.toolCallId} dir="auto" className="break-words">
|
||||
{t(key, params)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -170,12 +170,18 @@ describe('AssistantWindow', () => {
|
||||
|
||||
it('FE-AI-WIN-014: minimized outside a trip, the round button brings the home chat back', () => {
|
||||
seed({ open: true, minimized: true });
|
||||
render(<AssistantWindow trip={null} />);
|
||||
render(<AssistantWindow trip={null} />, { initialEntries: ['/atlas'] });
|
||||
expect(screen.getByText('chat 0 Your travels')).not.toBeVisible();
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Assistant' }));
|
||||
expect(useAssistantStore.getState().window.minimized).toBe(false);
|
||||
});
|
||||
|
||||
it('hides the minimized launcher on the dashboard', () => {
|
||||
seed({ open: true, minimized: true });
|
||||
render(<AssistantWindow trip={null} />);
|
||||
expect(screen.queryByRole('button', { name: 'Assistant' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-AI-WIN-005: closed while writing, the chat stays mounted and the round button breathes until it is opened', () => {
|
||||
seed({ open: true, minimized: true }, true);
|
||||
render(<AssistantWindow trip={TRIP} />);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import './assistant.css';
|
||||
|
||||
import { type CSSProperties, type KeyboardEvent, useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useNavigate } from 'react-router';
|
||||
import { useMatch, useNavigate } from 'react-router';
|
||||
|
||||
import type { WindowRect } from '../../hooks/useDragResize';
|
||||
import { useTranslation } from '../../i18n';
|
||||
@@ -200,6 +200,7 @@ function windowChat(
|
||||
|
||||
export default function AssistantWindow({ trip, onOpen, onFocusDay, onRevealMap }: AssistantWindowProps) {
|
||||
const navigate = useNavigate();
|
||||
const onDashboard = useMatch('/') !== null;
|
||||
const available = useAssistantStore((s) => s.status?.available === true);
|
||||
const open = useAssistantStore((s) => s.window.open);
|
||||
const minimized = useAssistantStore((s) => s.window.minimized);
|
||||
@@ -267,8 +268,9 @@ export default function AssistantWindow({ trip, onOpen, onFocusDay, onRevealMap
|
||||
onOpenTripChat={atHome ? home.openTripChat : undefined}
|
||||
tripSwitch={tripSwitch}
|
||||
/>
|
||||
{/* Hidden while an answer may still come in: the round button brings it back, on any page. */}
|
||||
{minimized && <AssistantLauncher variant="floating" tripId={launcherTrip} focusOnMount />}
|
||||
{minimized && (!onDashboard || !!routeChat) && (
|
||||
<AssistantLauncher variant="floating" tripId={launcherTrip} focusOnMount />
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -118,6 +118,20 @@ const ERRORS: Record<AssistantErrorCode, AssistantErrorView> = {
|
||||
/** The limits a provider sets; the line names the provider instead of guessing at its plan. */
|
||||
const PROVIDER_LIMITS: ReadonlySet<AssistantErrorCode> = new Set(['rate_limited', 'usage_limit']);
|
||||
|
||||
/** A route produced for the latest question can still be inspected after an interrupted answer. */
|
||||
export function hasCurrentTourProposal(messages: readonly AssistantMessage[]): boolean {
|
||||
for (let index = messages.length - 1; index >= 0; index--) {
|
||||
const message = messages[index];
|
||||
if (!message || message.role === 'user') break;
|
||||
const hasRoute = message.parts.some((part) => {
|
||||
const card = part.type === 'data-trek-card' ? part.data.card : null;
|
||||
return card?.kind === 'tourRoute' && card.source === 'proposal' && card.routed;
|
||||
});
|
||||
if (hasRoute) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* The line an error shows and its one action. The daily limit only offers
|
||||
* connecting an own provider where the policy allows one. A provider's limit
|
||||
@@ -126,10 +140,13 @@ const PROVIDER_LIMITS: ReadonlySet<AssistantErrorCode> = new Set(['rate_limited'
|
||||
*/
|
||||
export function errorView(
|
||||
code: AssistantErrorCode,
|
||||
opts: { canConnectOwn: boolean; provider?: string }
|
||||
opts: { canConnectOwn: boolean; provider?: string; hasTourProposal?: boolean }
|
||||
): AssistantErrorView {
|
||||
const view = ERRORS[code];
|
||||
if (code === 'daily_limit' && !opts.canConnectOwn) return { ...view, action: null };
|
||||
if (code === 'rate_limited' && opts.provider && opts.hasTourProposal) {
|
||||
return { ...view, messageKey: 'assistant.error.providerLimitAfterRoute' };
|
||||
}
|
||||
if (PROVIDER_LIMITS.has(code) && opts.provider) return { ...view, messageKey: 'assistant.error.providerLimit' };
|
||||
return view;
|
||||
}
|
||||
|
||||
@@ -98,6 +98,27 @@ describe('messageBlocks', () => {
|
||||
expect(messageBlocks(message(parts), false)[0]).toMatchObject({ steps: [{ running: false }] });
|
||||
});
|
||||
|
||||
it('keeps the query and categories of completed searches for their step labels', () => {
|
||||
const searches = [
|
||||
{ toolCallId: 'r1', toolName: 'search_place', args: { query: ' Hachikō\n statue ' } },
|
||||
{ toolCallId: 'r2', toolName: 'search_places_via_plugins', args: { query: 'Shibuya Sky' } },
|
||||
{ toolCallId: 'r3', toolName: 'search_pois', args: { category: ['restaurant', 'cafe'] } },
|
||||
];
|
||||
const parts = searches.map((search): AssistantMessagePart => ({
|
||||
...search,
|
||||
type: 'tool-call',
|
||||
result: 'searched',
|
||||
}));
|
||||
expect(messageBlocks(message(parts), false)[0]).toMatchObject({
|
||||
kind: 'steps',
|
||||
steps: [
|
||||
{ toolCallId: 'r1', query: 'Hachikō statue', running: false },
|
||||
{ toolCallId: 'r2', query: 'Shibuya Sky', running: false },
|
||||
{ toolCallId: 'r3', categories: ['restaurant', 'cafe'], running: false },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it('FE-AI-PARTS-003: the changes of one step share a card, each with its preview, wherever the preview sits', () => {
|
||||
const blocks = messageBlocks(
|
||||
message([
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
ASSISTANT_FOLLOW_UPS_TOOL,
|
||||
assistantSourceTitle,
|
||||
type AssistantApplied,
|
||||
type AssistantChangeEffect,
|
||||
type AssistantChangeLabelKey,
|
||||
@@ -39,6 +40,8 @@ export interface ToolStep {
|
||||
toolName: string;
|
||||
/** Still waiting for its result while the answer is being written. */
|
||||
running: boolean;
|
||||
query?: string;
|
||||
categories?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -50,6 +53,7 @@ export type ChangeState = 'pending' | 'applying' | 'applied' | 'failed' | 'disca
|
||||
|
||||
export interface ChangeItem {
|
||||
toolCallId: string;
|
||||
args?: unknown;
|
||||
/** What the card says about it; null until the preview arrived. */
|
||||
preview: AssistantChangePreview | null;
|
||||
/** The receipt of an applied change. */
|
||||
@@ -269,6 +273,7 @@ function changeItemOf(
|
||||
const applied = receipts.get(part.toolCallId) ?? null;
|
||||
return {
|
||||
toolCallId: part.toolCallId,
|
||||
...(preview?.verbKey === 'addPlaceToDay' || preview?.verbKey === 'assignPlace' ? { args: part.args } : {}),
|
||||
preview,
|
||||
applied,
|
||||
state: changeState(part, applied),
|
||||
@@ -295,8 +300,8 @@ function changeState(part: ToolCallPart, applied: AssistantApplied | null): Chan
|
||||
* The places of all its searches join into one strip where the newest search
|
||||
* sat, each place once, without the ones a change the model proposed in the
|
||||
* answer already holds; the weather of all steps joins
|
||||
* into one row where the first look sat. A strip does not split the steps
|
||||
* around it: a step after it joins the row of steps before it.
|
||||
* into one row where the first look sat. The sources of all steps sit together
|
||||
* at the end of the answer.
|
||||
*
|
||||
* A reading tool's card joins the cards block of its group (by `rules`, the
|
||||
* kinds' looks unless a test hands others) when only steps lie between them;
|
||||
@@ -311,6 +316,7 @@ export function messageBlocks(
|
||||
const previews = new Map<string, AssistantChangePreview>();
|
||||
const receipts = new Map<string, AssistantApplied>();
|
||||
const cards = new Map<string, TrekCard>();
|
||||
const sources = new Map<string, AssistantSources['sources'][number]>();
|
||||
const changeIds = new Set<string>();
|
||||
const effects: AssistantChangeEffect[] = [];
|
||||
// A place the user suggested from the strip stays on it, marked as suggested.
|
||||
@@ -324,6 +330,11 @@ export function messageBlocks(
|
||||
previews.set(part.data.toolCallId, part.data);
|
||||
if (part.data.effect && !fromStrip.has(part.data.toolCallId)) effects.push(part.data.effect);
|
||||
changeIds.add(part.data.toolCallId);
|
||||
} else if (part.type === 'data-trek-sources') {
|
||||
for (const { url, title } of part.data.sources) {
|
||||
const previous = sources.get(url);
|
||||
if (!previous?.title || previous.title === url) sources.set(url, { url, title: assistantSourceTitle(title) });
|
||||
}
|
||||
} else if (part.type === 'data-trek-applied') receipts.set(part.data.toolCallId, part.data);
|
||||
else if (part.type === 'data-trek-places') lastPlaces = index;
|
||||
else if (part.type === 'data-trek-weather' && firstWeather < 0) firstWeather = index;
|
||||
@@ -335,6 +346,9 @@ export function messageBlocks(
|
||||
const changeCards = message.parts.flatMap((p) => (p.type === 'data-trek-change' && p.data.card ? [p.data.card] : []));
|
||||
const placesHidden =
|
||||
[...cards.values(), ...changeCards].some((card) => rules.hidesFoundPlaces?.(card) === true) ||
|
||||
[...previews.values()].some(
|
||||
(preview) => preview.verbKey === 'addPlaceToDay' || preview.verbKey === 'assignPlace'
|
||||
) ||
|
||||
message.parts.some((p) => p.type === 'tool-call' && TOUR_PLANNING_TOOLS.has(p.toolName));
|
||||
const blocks: MessageBlock[] = [];
|
||||
message.parts.forEach((part, index) => {
|
||||
@@ -347,10 +361,6 @@ export function messageBlocks(
|
||||
if (strip) blocks.push(strip);
|
||||
return;
|
||||
}
|
||||
if (part.type === 'data-trek-sources') {
|
||||
blocks.push({ kind: 'sources', key: `sources-${index}`, sources: part.data.sources });
|
||||
return;
|
||||
}
|
||||
if (part.type === 'data-trek-weather' && index === firstWeather) {
|
||||
blocks.push({ kind: 'weather', key: `weather-${index}`, days: weatherDays(message.parts) });
|
||||
return;
|
||||
@@ -373,18 +383,35 @@ export function messageBlocks(
|
||||
blocks.push({ kind: 'remembered', key: `remembered-${part.toolCallId}`, note });
|
||||
return;
|
||||
}
|
||||
const step: ToolStep = {
|
||||
toolCallId: part.toolCallId,
|
||||
toolName: part.toolName,
|
||||
running: writing && part.result === undefined,
|
||||
};
|
||||
const step = toolStep(part, writing);
|
||||
const steps = openSteps(blocks);
|
||||
if (steps) steps.steps.push(step);
|
||||
else blocks.push({ kind: 'steps', key: `steps-${part.toolCallId}`, steps: [step] });
|
||||
});
|
||||
if (sources.size > 0) blocks.push({ kind: 'sources', key: 'sources', sources: [...sources.values()] });
|
||||
return withoutYielded(blocks, rules);
|
||||
}
|
||||
|
||||
function toolStep(part: ToolCallPart, writing: boolean): ToolStep {
|
||||
const { toolCallId, toolName, args } = part;
|
||||
const step = { toolCallId, toolName, running: writing && part.result === undefined };
|
||||
if (!args || typeof args !== 'object') return step;
|
||||
if (toolName === 'search_place' || toolName === 'search_places_via_plugins' || toolName === 'web_search') {
|
||||
const { query } = args as { query?: unknown };
|
||||
if (typeof query === 'string' && query.trim()) {
|
||||
return { ...step, query: query.trim().replace(/\s+/g, ' ').slice(0, 200) };
|
||||
}
|
||||
}
|
||||
if (toolName === 'search_pois') {
|
||||
const { category } = args as { category?: unknown };
|
||||
const categories = (Array.isArray(category) ? category : [category])
|
||||
.filter((entry): entry is string => typeof entry === 'string')
|
||||
.slice(0, 8);
|
||||
if (categories.length) return { ...step, categories };
|
||||
}
|
||||
return step;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether "+ Day" was already pressed on this found place in the answer: a
|
||||
* suggestion from the strip names the trip's place by its id, a new one by
|
||||
@@ -477,6 +504,10 @@ export const CHANGE_LABELS: Record<AssistantChangeLabelKey, { labelKey: string }
|
||||
*/
|
||||
export function tailStart(blocks: MessageBlock[]): number {
|
||||
let i = blocks.length;
|
||||
while (i > 0 && (blocks[i - 1].kind === 'text' || blocks[i - 1].kind === 'change')) i -= 1;
|
||||
while (
|
||||
i > 0 &&
|
||||
(blocks[i - 1].kind === 'text' || blocks[i - 1].kind === 'change' || blocks[i - 1].kind === 'sources')
|
||||
)
|
||||
i -= 1;
|
||||
return i;
|
||||
}
|
||||
|
||||
@@ -1,13 +1,20 @@
|
||||
import type { AssistantChangePreview, TrekCardKind } from '@trek/shared';
|
||||
import { Check, Undo2 } from 'lucide-react';
|
||||
import type { AssistantChangePreview, AssistantPlanEdits, TrekCardKind } from '@trek/shared';
|
||||
import { Check, Paperclip, Undo2 } from 'lucide-react';
|
||||
import { Fragment, type ReactNode } from 'react';
|
||||
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import { Tooltip } from '../../shared/Tooltip';
|
||||
import AssistantChangeFields from '../AssistantChangeFields';
|
||||
import type { ChangeItem } from '../assistantParts';
|
||||
import AssistantPlanFields, {
|
||||
isDayNoteProposal,
|
||||
isVisitProposal,
|
||||
planField,
|
||||
proposalNote,
|
||||
} from '../AssistantPlanFields';
|
||||
import { useAssistantView } from '../assistantViewContext';
|
||||
import { useChangeHover } from '../useChangeHover';
|
||||
import { isSingleBookingDraft } from './booking/bookingCardModel';
|
||||
import { TOOL_LABELS, verbLookOf } from './cardLooks';
|
||||
import type { CardView } from './cardTypes';
|
||||
import { viewOf } from './cardViews';
|
||||
@@ -140,6 +147,11 @@ function BodySlot({ item, settled }: { item: ChangeItem; settled: boolean }) {
|
||||
);
|
||||
}
|
||||
|
||||
function inlineBookingCard(item: ChangeItem): boolean {
|
||||
const card = item.card;
|
||||
return card?.kind === 'booking' && isSingleBookingDraft(card);
|
||||
}
|
||||
|
||||
/** A decided change that no longer stands: discarded, expired or taken back. */
|
||||
const settledOf = (item: ChangeItem, undone: boolean) =>
|
||||
item.state === 'discarded' || item.state === 'expired' || undone;
|
||||
@@ -164,11 +176,21 @@ function Receipt({
|
||||
const settled = settledOf(item, undone);
|
||||
const statusLabel = t(undone ? 'assistant.change.undone' : receipt.labelKey);
|
||||
const view = item.card ? viewOf(item.card) : null;
|
||||
const inlineBooking = inlineBookingCard(item);
|
||||
return (
|
||||
<div className="trek-assistant-enter flex items-center gap-2.5 py-1.5">
|
||||
<Lead item={item} view={view} dimmed={settled} />
|
||||
{!inlineBooking && <Lead item={item} view={view} dimmed={settled} />}
|
||||
<div className={`min-w-0 flex-1 ${settled ? 'opacity-60' : ''}`}>
|
||||
<ChangeHead item={item} view={view} struck={settled} />
|
||||
{inlineBooking ? (
|
||||
<Slot
|
||||
name="Body"
|
||||
item={item}
|
||||
view={view}
|
||||
fallback={<ChangeHead item={item} view={view} struck={settled} />}
|
||||
/>
|
||||
) : (
|
||||
<ChangeHead item={item} view={view} struck={settled} />
|
||||
)}
|
||||
</div>
|
||||
{applied && <EntityActions applied={applied} card={item.card} />}
|
||||
{canUndo && (
|
||||
@@ -203,63 +225,111 @@ function PendingRow({
|
||||
withChoice,
|
||||
disabled,
|
||||
onToggle,
|
||||
edits,
|
||||
onEdit,
|
||||
groupedDay,
|
||||
}: {
|
||||
item: ChangeItem;
|
||||
excluded: boolean;
|
||||
withChoice: boolean;
|
||||
disabled: boolean;
|
||||
onToggle: () => void;
|
||||
edits: AssistantPlanEdits | undefined;
|
||||
onEdit: (patch: AssistantPlanEdits) => void;
|
||||
groupedDay: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const { tripId } = useAssistantView();
|
||||
const { litFromMap, handlers } = useChangeHover(tripId, item.preview?.effect ? item.toolCallId : null);
|
||||
const preview = item.preview;
|
||||
const view = item.card ? viewOf(item.card) : null;
|
||||
const inlineBooking = inlineBookingCard(item);
|
||||
const aside = <Slot item={item} view={view} name="Aside" />;
|
||||
const visit = isVisitProposal(preview);
|
||||
const dayNote = isDayNoteProposal(preview);
|
||||
const editable = preview && (visit || dayNote);
|
||||
const note = editable ? proposalNote(preview, edits) : null;
|
||||
const receipt = preview?.verbKey === 'importBooking' ? planField(preview, 'attachedTo') : undefined;
|
||||
const rows = preview?.rows.filter(
|
||||
(row) => !(groupedDay && row.labelKey === 'day') && !(dayNote && row.labelKey === 'time')
|
||||
);
|
||||
return (
|
||||
<div
|
||||
{...handlers}
|
||||
className={`-mx-1.5 flex items-center gap-2.5 rounded-[12px] px-1.5 py-2 transition-[opacity,background-color] ${
|
||||
className={`-mx-1.5 flex ${inlineBooking ? 'items-start' : 'items-center'} gap-2.5 rounded-[12px] px-1.5 py-2 transition-[opacity,background-color] ${
|
||||
excluded ? 'opacity-50' : ''
|
||||
} ${litFromMap ? 'bg-surface-hover' : 'hover:bg-surface-hover'}`}
|
||||
>
|
||||
{withChoice && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onToggle}
|
||||
disabled={disabled}
|
||||
aria-pressed={!excluded}
|
||||
aria-label={t('assistant.change.include')}
|
||||
className={`grid h-[18px] w-[18px] flex-none place-items-center rounded-full outline-none transition-colors focus-visible:ring-2 focus-visible:ring-accent disabled:opacity-50 ${
|
||||
excluded ? 'border-[1.5px] border-edge bg-surface-card' : 'bg-accent'
|
||||
}`}
|
||||
>
|
||||
{!excluded && <Check size={11} strokeWidth={3} aria-hidden="true" className="text-accent-text" />}
|
||||
</button>
|
||||
{withChoice ? (
|
||||
<Tooltip label={t('assistant.change.include')}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onToggle}
|
||||
disabled={disabled}
|
||||
aria-pressed={!excluded}
|
||||
aria-label={t('assistant.change.include')}
|
||||
className="relative grid h-8 w-8 flex-none place-items-center rounded-lg outline-none ring-edge transition-shadow before:absolute before:-inset-1.5 before:rounded-xl hover:ring-1 focus-visible:ring-2 focus-visible:ring-accent disabled:cursor-default"
|
||||
>
|
||||
<Lead item={item} view={view} dimmed={excluded} />
|
||||
{!excluded && (
|
||||
<span className="pointer-events-none absolute -bottom-0.5 -end-0.5 grid h-3.5 w-3.5 place-items-center rounded-full bg-accent text-accent-text ring-2 ring-surface-card">
|
||||
<Check size={9} strokeWidth={3} aria-hidden="true" />
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
</Tooltip>
|
||||
) : (
|
||||
!inlineBooking && <Lead item={item} view={view} dimmed={excluded} />
|
||||
)}
|
||||
<Lead item={item} view={view} dimmed={excluded} />
|
||||
<div className="min-w-0 flex-1">
|
||||
{preview ? (
|
||||
{inlineBooking ? (
|
||||
<Slot name="Body" item={item} view={view} fallback={<ChangeHead item={item} view={view} struck={false} />} />
|
||||
) : preview ? (
|
||||
<>
|
||||
{view?.ownsSubject ? (
|
||||
aside
|
||||
) : (
|
||||
<SubjectLine subject={preview.subject} struck={false} aside={view?.Aside && aside} block />
|
||||
<SubjectLine
|
||||
subject={edits?.place?.name ?? edits?.noteTitle ?? preview.subject}
|
||||
struck={false}
|
||||
aside={view?.Aside && aside}
|
||||
block
|
||||
/>
|
||||
)}
|
||||
<span className="mt-1 flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1 text-caption text-content-faint">
|
||||
<span className="me-0.5 min-w-0 truncate">{verbLabel(preview, t)}</span>
|
||||
{!visit && <span className="me-0.5 min-w-0 truncate">{verbLabel(preview, t)}</span>}
|
||||
<DomainChip domain={preview.domain} />
|
||||
{view?.Facts ? (
|
||||
<Slot item={item} view={view} name="Facts" fallback={<AssistantChangeFields rows={preview.rows} />} />
|
||||
) : (
|
||||
<AssistantChangeFields rows={preview.rows} />
|
||||
<AssistantChangeFields rows={rows ?? preview.rows} visit={visit} edits={edits} />
|
||||
)}
|
||||
</span>
|
||||
{receipt && (
|
||||
<div
|
||||
className="mt-1 flex min-w-0 items-center gap-1.5 text-caption text-content-muted"
|
||||
title={t('assistant.attach.chip.keepWithBooking')}
|
||||
>
|
||||
<Paperclip size={13} className="flex-none" aria-hidden="true" />
|
||||
<span className="sr-only">{t('assistant.attach.chip.keepWithBooking')}</span>
|
||||
<bdi className="truncate">{receipt}</bdi>
|
||||
</div>
|
||||
)}
|
||||
{note && <bdi className="mt-1 block truncate text-caption text-content-muted">{note}</bdi>}
|
||||
</>
|
||||
) : (
|
||||
<span className="trek-skeleton inline-block h-4 w-40" aria-hidden="true" />
|
||||
)}
|
||||
</div>
|
||||
{editable && (
|
||||
<AssistantPlanFields
|
||||
preview={preview}
|
||||
args={item.args}
|
||||
edits={edits}
|
||||
disabled={disabled || excluded}
|
||||
onEdit={onEdit}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -274,6 +344,9 @@ interface RowsProps {
|
||||
undoable: readonly string[];
|
||||
onToggle: (toolCallId: string) => void;
|
||||
onUndo: (toolCallId: string) => void;
|
||||
planEdits: Readonly<Record<string, AssistantPlanEdits>>;
|
||||
onEdit: (toolCallId: string, patch: AssistantPlanEdits) => void;
|
||||
groupedDay: boolean;
|
||||
}
|
||||
|
||||
/** Consecutive changes of one kind of card; a change without a card stands alone. */
|
||||
@@ -299,7 +372,19 @@ function runnable(item: ChangeItem, view: View | null): boolean {
|
||||
* `Group` before and after it, and two or more waiting rows its view can
|
||||
* take together are drawn as one `Run` instead.
|
||||
*/
|
||||
export function ChangeRows({ items, folded, excluded, disabled, undone, undoable, onToggle, onUndo }: RowsProps) {
|
||||
export function ChangeRows({
|
||||
items,
|
||||
folded,
|
||||
excluded,
|
||||
disabled,
|
||||
undone,
|
||||
undoable,
|
||||
onToggle,
|
||||
onUndo,
|
||||
planEdits,
|
||||
onEdit,
|
||||
groupedDay,
|
||||
}: RowsProps) {
|
||||
const pendingCount = items.filter((i) => i.state === 'pending').length;
|
||||
// The body stands beside the row, in the same place whether the change waits or is decided, so a body that holds
|
||||
// what the user chose (the pages of a book design) keeps it, and draws on, as the change starts to apply.
|
||||
@@ -316,6 +401,9 @@ export function ChangeRows({ items, folded, excluded, disabled, undone, undoable
|
||||
withChoice={pendingCount > 1}
|
||||
disabled={disabled}
|
||||
onToggle={() => onToggle(item.toolCallId)}
|
||||
edits={planEdits[item.toolCallId]}
|
||||
onEdit={(patch) => onEdit(item.toolCallId, patch)}
|
||||
groupedDay={groupedDay}
|
||||
/>
|
||||
) : (
|
||||
<Receipt
|
||||
@@ -325,7 +413,9 @@ export function ChangeRows({ items, folded, excluded, disabled, undone, undoable
|
||||
onUndo={() => onUndo(item.toolCallId)}
|
||||
/>
|
||||
)}
|
||||
<BodySlot item={item} settled={waiting ? excluded.has(item.toolCallId) : settledOf(item, isUndone)} />
|
||||
{!inlineBookingCard(item) && (
|
||||
<BodySlot item={item} settled={waiting ? excluded.has(item.toolCallId) : settledOf(item, isUndone)} />
|
||||
)}
|
||||
</Fragment>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -25,6 +25,7 @@ import { useAuthStore } from '../../../../store/authStore';
|
||||
import { useSettingsStore } from '../../../../store/settingsStore';
|
||||
import type { ChangeItem } from '../../assistantParts';
|
||||
import { type AssistantView, AssistantViewContext } from '../../assistantViewContext';
|
||||
import { ChangeRows } from '../ChangeCardSlots';
|
||||
import BookingBlock from './BookingBlock';
|
||||
import { BookingChangeBody, BookingChangeFacts } from './BookingChangeSlots';
|
||||
|
||||
@@ -412,4 +413,44 @@ describe('booking cards', () => {
|
||||
expect(screen.queryByRole('button', { name: 'Open the booking' })).not.toBeInTheDocument();
|
||||
expect(screen.getByText('Frankfurt to New York')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it.each(['pending', 'failed'] as const)(
|
||||
'shows a single %s booking as one card with its structured reference',
|
||||
(state) => {
|
||||
const card = cardOf([{ ...DINNER, reservationId: null, status: 'confirmed', hasReference: true }], 'create');
|
||||
const item = changeItem(card);
|
||||
item.state = state;
|
||||
if (!item.preview) throw new Error('Booking preview fixture is missing');
|
||||
item.preview.verbKey = 'addReservation';
|
||||
item.preview.rows = [
|
||||
{ op: 'add', labelKey: 'confirmation', before: null, after: 'ABC-12345' },
|
||||
{ op: 'add', labelKey: 'notes', before: null, after: 'Use the side entrance. Booking code: ABC-12345.' },
|
||||
];
|
||||
inView(
|
||||
<ChangeRows
|
||||
items={[item]}
|
||||
folded={false}
|
||||
excluded={new Set()}
|
||||
disabled={false}
|
||||
undone={{}}
|
||||
undoable={[]}
|
||||
onToggle={vi.fn()}
|
||||
onUndo={vi.fn()}
|
||||
planEdits={{}}
|
||||
onEdit={vi.fn()}
|
||||
groupedDay={false}
|
||||
/>,
|
||||
{ variant: 'fullscreen', density: 'compact' }
|
||||
);
|
||||
const booking = within(screen.getByRole('region', { name: DINNER.title }));
|
||||
expect(booking.getByText('Add booking')).toHaveClass('uppercase');
|
||||
expect(screen.getAllByText('Add booking')).toHaveLength(1);
|
||||
expect(booking.getByText('Start time').closest('dt')?.nextElementSibling).toHaveTextContent('19:00');
|
||||
expect(booking.getByText('End time').closest('dt')?.nextElementSibling).toHaveTextContent('21:30');
|
||||
expect(booking.getByText('Confirmed')).toBeInTheDocument();
|
||||
expect(booking.getByText('Booking Code').closest('dt')?.nextElementSibling).toHaveTextContent('ABC-12345');
|
||||
expect(booking.getByText('Use the side entrance.')).toBeInTheDocument();
|
||||
expect(booking.queryByText(/Booking code: ABC-12345/)).toBeNull();
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
@@ -5,7 +5,16 @@ import { useTranslation } from '../../../../i18n';
|
||||
import { Tooltip } from '../../../shared/Tooltip';
|
||||
import { useAssistantView } from '../../assistantViewContext';
|
||||
import type { EntityTarget } from '../cardTypes';
|
||||
import { BookingFooter, BookingHead, StayBody, TicketBody, VenueBody } from './bookingCardParts';
|
||||
import {
|
||||
BookingFooter,
|
||||
BookingHead,
|
||||
BookingProposalFooter,
|
||||
StayBody,
|
||||
StayProposalBody,
|
||||
TicketBody,
|
||||
VenueBody,
|
||||
VenueProposalBody,
|
||||
} from './bookingCardParts';
|
||||
import { bookingSpotOf, bookingTarget } from './bookingLook';
|
||||
|
||||
/**
|
||||
@@ -88,11 +97,13 @@ export default function BookingCard({
|
||||
item,
|
||||
card,
|
||||
actions = true,
|
||||
proposal,
|
||||
}: {
|
||||
item: BookingItem;
|
||||
card: Card;
|
||||
/** Off inside a change card, whose row has its own ways to the booking. */
|
||||
actions?: boolean;
|
||||
proposal?: { label: string; notes?: string; reference?: string; receipt?: string };
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const body = item.body;
|
||||
@@ -101,17 +112,33 @@ export default function BookingCard({
|
||||
aria-label={item.title}
|
||||
className={`trek-assistant-enter group overflow-hidden rounded-xl border bg-surface-card shadow-card ${FRAME[card.change]}`}
|
||||
>
|
||||
<BookingHead item={item} card={card} actions={actions ? <CardActions item={item} /> : null} />
|
||||
<div className="px-3 pb-2.5 pt-2">
|
||||
<BookingHead
|
||||
item={item}
|
||||
card={card}
|
||||
actionLabel={proposal?.label}
|
||||
actions={actions ? <CardActions item={item} /> : null}
|
||||
/>
|
||||
<div className={proposal ? 'flex flex-col gap-3 bg-surface-secondary p-3' : 'px-3 pb-2.5 pt-2'}>
|
||||
{item.tripTitle && (
|
||||
<p className="m-0 mb-1 text-caption text-content-muted">
|
||||
{t('assistant.card.booking.inTrip', { trip: item.tripTitle })}
|
||||
</p>
|
||||
)}
|
||||
{body.shape === 'ticket' && <TicketBody item={item} body={body} card={card} />}
|
||||
{body.shape === 'stay' && <StayBody item={item} body={body} card={card} />}
|
||||
{body.shape === 'venue' && <VenueBody item={item} body={body} card={card} />}
|
||||
<BookingFooter item={item} card={card} />
|
||||
{body.shape === 'stay' &&
|
||||
(proposal ? <StayProposalBody body={body} /> : <StayBody item={item} body={body} card={card} />)}
|
||||
{body.shape === 'venue' &&
|
||||
(proposal ? <VenueProposalBody body={body} /> : <VenueBody item={item} body={body} card={card} />)}
|
||||
{proposal ? (
|
||||
<BookingProposalFooter
|
||||
item={item}
|
||||
notes={proposal.notes}
|
||||
reference={proposal.reference}
|
||||
receipt={proposal.receipt}
|
||||
/>
|
||||
) : (
|
||||
<BookingFooter item={item} card={card} />
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
import type { TrekCardOf } from '@trek/shared';
|
||||
import { withoutRepeatedBookingReference, type TrekCardOf } from '@trek/shared';
|
||||
|
||||
import { useTranslation } from '../../../../i18n';
|
||||
import AssistantChangeFields from '../../AssistantChangeFields';
|
||||
import type { ChangeItem } from '../../assistantParts';
|
||||
import { verbLookOf } from '../cardLooks';
|
||||
import { BookingList } from './BookingBlock';
|
||||
import BookingCard from './BookingCard';
|
||||
import { isSingleBookingDraft } from './bookingCardModel';
|
||||
|
||||
/**
|
||||
* The booking card inside a change row. The row keeps its choice, its tile
|
||||
@@ -17,8 +21,28 @@ interface SlotProps {
|
||||
item: ChangeItem;
|
||||
}
|
||||
|
||||
/** The card under the row; the row itself leads to the booking once it is saved. */
|
||||
export function BookingChangeBody({ card }: SlotProps) {
|
||||
/** New single bookings carry their action in the card head. */
|
||||
export function BookingChangeBody({ card, item }: SlotProps) {
|
||||
const { t } = useTranslation();
|
||||
const booking = card.items[0];
|
||||
if (booking && isSingleBookingDraft(card)) {
|
||||
const preview = item.preview;
|
||||
const reference = preview?.rows.find((row) => row.labelKey === 'confirmation')?.after.trim() || undefined;
|
||||
const notes = preview?.rows.find((row) => row.labelKey === 'notes')?.after ?? '';
|
||||
return (
|
||||
<BookingCard
|
||||
item={booking}
|
||||
card={card}
|
||||
actions={false}
|
||||
proposal={{
|
||||
label: t(verbLookOf(preview?.verbKey ?? 'addReservation').labelKey),
|
||||
notes: withoutRepeatedBookingReference(notes, reference),
|
||||
reference,
|
||||
receipt: preview?.rows.find((row) => row.labelKey === 'attachedTo')?.after,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return <BookingList items={card.items} more={card.more} card={card} actions={false} />;
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,10 @@ import type { CardEntry } from '../cardTypes';
|
||||
/** A status a booking card names in words. */
|
||||
type BookingStatus = NonNullable<BookingItem['status']>;
|
||||
|
||||
export function isSingleBookingDraft(card: BookingCard): boolean {
|
||||
return card.change === 'create' && card.items.length === 1 && card.more === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* The planner's tone of a booking (its `toneOf`): a transit hop in the info
|
||||
* tone, a confirmed booking green, any other (pending, cancelled) amber; none
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
LogOut,
|
||||
MapPin,
|
||||
Moon,
|
||||
Paperclip,
|
||||
Route,
|
||||
Ticket,
|
||||
Wallet,
|
||||
@@ -23,7 +24,16 @@ import {
|
||||
import { useRef, type ReactNode } from 'react';
|
||||
|
||||
import { useTranslation } from '../../../../i18n';
|
||||
import { ReviewPill, toneColor, toneTint, TypeTile } from '../../../Planner/bookings/bookingParts';
|
||||
import {
|
||||
Block,
|
||||
BOX,
|
||||
Eyebrow,
|
||||
fs,
|
||||
ReviewPill,
|
||||
toneColor,
|
||||
toneTint,
|
||||
TypeTile,
|
||||
} from '../../../Planner/bookings/bookingParts';
|
||||
import { typeInfo } from '../../../Planner/bookings/bookingsModel';
|
||||
import { SoftPill, TimePill, type PillTone } from '../../../Planner/planParts';
|
||||
import { Tooltip } from '../../../shared/Tooltip';
|
||||
@@ -101,13 +111,13 @@ function StayPhoto({ item, body, size, tile }: { item: BookingItem; body: Bookin
|
||||
}
|
||||
|
||||
/** The lead of the head band: a stay's photo (56, 44 when compact), else the type tile. */
|
||||
function HeadLead({ item }: { item: BookingItem }) {
|
||||
function HeadLead({ item, proposal }: { item: BookingItem; proposal: boolean }) {
|
||||
const { density } = useAssistantView();
|
||||
const compact = density === 'compact';
|
||||
if (item.body.shape === 'stay') {
|
||||
return <StayPhoto item={item} body={item.body} size={compact ? 44 : 56} tile={compact ? 32 : 40} />;
|
||||
}
|
||||
return <TypeTile type={item.type} size={compact ? 24 : 28} />;
|
||||
return <TypeTile type={item.type} size={proposal ? 34 : compact ? 24 : 28} />;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -115,22 +125,39 @@ function HeadLead({ item }: { item: BookingItem }) {
|
||||
* title), the title, the review mark, the status dot and the card's actions,
|
||||
* on the tint of the status as on the planner's booking cards.
|
||||
*/
|
||||
export function BookingHead({ item, card, actions }: { item: BookingItem; card: Card; actions?: ReactNode }) {
|
||||
export function BookingHead({
|
||||
item,
|
||||
card,
|
||||
actions,
|
||||
actionLabel,
|
||||
}: {
|
||||
item: BookingItem;
|
||||
card: Card;
|
||||
actions?: ReactNode;
|
||||
actionLabel?: string;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const tone = toneOfItem(item);
|
||||
const removed = card.change === 'remove';
|
||||
const address = item.body.shape === 'stay' ? item.body.address : null;
|
||||
const proposal = !!actionLabel;
|
||||
const address =
|
||||
item.body.shape === 'stay'
|
||||
? item.body.address
|
||||
: proposal && item.body.shape === 'venue'
|
||||
? item.body.location
|
||||
: null;
|
||||
return (
|
||||
<div
|
||||
className="flex items-center gap-2 border-b border-edge-faint px-3 py-2"
|
||||
className={`flex items-center gap-2.5 border-b border-edge-faint px-3 ${actionLabel ? 'py-3' : 'py-2'}`}
|
||||
style={{ background: tone ? toneTint(tone) : undefined }}
|
||||
>
|
||||
<HeadLead item={item} />
|
||||
<span className="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<HeadLead item={item} proposal={proposal} />
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
{actionLabel && <Eyebrow>{actionLabel}</Eyebrow>}
|
||||
<span className="flex min-w-0 items-center gap-1.5">
|
||||
<bdi
|
||||
title={item.title}
|
||||
className={`line-clamp-2 text-body font-semibold leading-tight text-content ${removed ? 'line-through' : ''}`}
|
||||
className={`line-clamp-2 text-body leading-tight text-content ${proposal ? 'font-bold' : 'font-semibold'} ${removed ? 'line-through' : ''}`}
|
||||
>
|
||||
{item.title}
|
||||
</bdi>
|
||||
@@ -138,19 +165,192 @@ export function BookingHead({ item, card, actions }: { item: BookingItem; card:
|
||||
{isChanged(card, item, 'title') && <ChangedDot />}
|
||||
{removed && <span className="sr-only">{t('assistant.card.common.willDelete')}</span>}
|
||||
</span>
|
||||
{address && (
|
||||
<bdi title={address} className="line-clamp-2 text-caption text-content-muted">
|
||||
{address}
|
||||
</bdi>
|
||||
)}
|
||||
</span>
|
||||
<StatusMark item={item} />
|
||||
{address &&
|
||||
(proposal ? (
|
||||
<span className="mt-0.5 flex items-start gap-1.5 text-caption text-content-muted">
|
||||
<MapPin size={12} className="mt-0.5 flex-none" aria-hidden="true" />
|
||||
<bdi title={address} className="line-clamp-2 break-words">
|
||||
{address}
|
||||
</bdi>
|
||||
</span>
|
||||
) : (
|
||||
<bdi title={address} className="line-clamp-2 text-caption text-content-muted">
|
||||
{address}
|
||||
</bdi>
|
||||
))}
|
||||
</div>
|
||||
{!actionLabel && <StatusMark item={item} />}
|
||||
{isChanged(card, item, 'status') && <ChangedDot />}
|
||||
{actions}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** A proposal shows the facts in the same order as the booking editor. */
|
||||
const PROPOSAL_FACTS = 'm-0 grid grid-cols-[repeat(auto-fit,minmax(min(100%,8.5rem),1fr))] gap-2';
|
||||
const PROPOSAL_FIELD_TEXT = fs(12.5, 'body');
|
||||
|
||||
function ProposalFact({ label, children }: { label: string; children: ReactNode }) {
|
||||
return (
|
||||
<div className="min-w-0">
|
||||
<dt className="mb-[3px]">
|
||||
<Eyebrow>{label}</Eyebrow>
|
||||
</dt>
|
||||
<dd
|
||||
className={`${BOX} m-0 flex min-h-9 flex-wrap items-center gap-x-1.5 gap-y-0.5 break-words px-2.5 py-[7px] font-semibold tabular-nums text-content`}
|
||||
style={PROPOSAL_FIELD_TEXT}
|
||||
>
|
||||
{children}
|
||||
</dd>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function VenueProposalBody({ body }: { body: BookingVenue }) {
|
||||
const { t } = useTranslation();
|
||||
const format = useBookingFormat();
|
||||
const day = format.day(body.day);
|
||||
const dayNumber = format.dayNumber(body.day);
|
||||
return (
|
||||
(day || body.starts || body.ends) && (
|
||||
<dl className={PROPOSAL_FACTS}>
|
||||
{day && (
|
||||
<ProposalFact label={t(body.day?.date ? 'reservations.date' : 'reservations.timeline.day')}>
|
||||
<bdi>{day}</bdi>
|
||||
{dayNumber && <span className="text-caption font-normal text-content-muted">{dayNumber}</span>}
|
||||
</ProposalFact>
|
||||
)}
|
||||
{body.starts && (
|
||||
<ProposalFact label={t('reservations.startTime')}>
|
||||
<bdi>{format.clock(body.starts)}</bdi>
|
||||
</ProposalFact>
|
||||
)}
|
||||
{body.ends && (
|
||||
<ProposalFact label={t('reservations.endTime')}>
|
||||
<bdi>{format.clock(body.ends)}</bdi>
|
||||
</ProposalFact>
|
||||
)}
|
||||
</dl>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export function StayProposalBody({ body }: { body: BookingStay }) {
|
||||
const { t } = useTranslation();
|
||||
const format = useBookingFormat();
|
||||
const checkIn = body.checkIn;
|
||||
const checkOut = body.checkOut;
|
||||
return (
|
||||
<>
|
||||
{(checkIn || checkOut) && (
|
||||
<dl className={PROPOSAL_FACTS}>
|
||||
{checkIn && (
|
||||
<ProposalFact label={t('assistant.change.label.checkIn')}>
|
||||
<bdi>{format.day(checkIn.day)}</bdi>
|
||||
{checkIn.from && (
|
||||
<bdi className="text-caption">
|
||||
{format.clock(checkIn.from)}
|
||||
{checkIn.until ? ` – ${format.clock(checkIn.until)}` : ''}
|
||||
</bdi>
|
||||
)}
|
||||
</ProposalFact>
|
||||
)}
|
||||
{checkOut && (
|
||||
<ProposalFact label={t('assistant.change.label.checkOut')}>
|
||||
<bdi>{format.day(checkOut.day)}</bdi>
|
||||
{checkOut.by && <bdi className="text-caption">{format.clock(checkOut.by)}</bdi>}
|
||||
</ProposalFact>
|
||||
)}
|
||||
</dl>
|
||||
)}
|
||||
{!!body.nights && (
|
||||
<p className="m-0 flex items-center gap-1.5 text-body text-content-secondary">
|
||||
<Moon size={14} aria-hidden="true" />
|
||||
{t('assistant.card.booking.nights', { count: body.nights })}
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function BookingProposalFooter({
|
||||
item,
|
||||
notes,
|
||||
reference,
|
||||
receipt,
|
||||
}: {
|
||||
item: BookingItem;
|
||||
notes?: string;
|
||||
reference?: string;
|
||||
receipt?: string;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const format = useBookingFormat();
|
||||
const tone = toneOfItem(item);
|
||||
return (
|
||||
<>
|
||||
{reference && (
|
||||
<dl className="m-0">
|
||||
<ProposalFact label={t('reservations.confirmationCode')}>
|
||||
<bdi dir="ltr" className="min-w-0 break-all font-geist">
|
||||
{reference}
|
||||
</bdi>
|
||||
</ProposalFact>
|
||||
</dl>
|
||||
)}
|
||||
{notes && (
|
||||
<Block label={t('assistant.change.label.notes')}>
|
||||
<p
|
||||
className={`${BOX} m-0 whitespace-pre-wrap break-words px-2.5 py-[7px] text-content-secondary`}
|
||||
style={PROPOSAL_FIELD_TEXT}
|
||||
>
|
||||
<bdi>{notes}</bdi>
|
||||
</p>
|
||||
</Block>
|
||||
)}
|
||||
{receipt && (
|
||||
<Block label={t('assistant.change.label.attachedTo')}>
|
||||
<span
|
||||
className={`${BOX} flex min-w-0 items-center gap-1.5 px-2.5 py-[7px] text-content-secondary`}
|
||||
style={PROPOSAL_FIELD_TEXT}
|
||||
>
|
||||
<Paperclip size={14} aria-hidden="true" className="flex-none" />
|
||||
<bdi className="min-w-0 break-words">{receipt}</bdi>
|
||||
</span>
|
||||
</Block>
|
||||
)}
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-2 border-t border-edge-faint pt-2.5 text-caption text-content-secondary">
|
||||
<span className="font-semibold">{t(typeInfo(item.type).labelKey)}</span>
|
||||
{item.status && tone && (
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
<span
|
||||
className="h-2 w-2 flex-none rounded-full"
|
||||
style={{ background: toneColor(tone) }}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
{t(STATUS_LABEL[item.status].labelKey)}
|
||||
</span>
|
||||
)}
|
||||
{item.hasReference && !reference && (
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
<BadgeCheck size={14} aria-hidden="true" className="flex-none text-success" />
|
||||
{t('reservations.confirmationCode')}
|
||||
</span>
|
||||
)}
|
||||
{item.price && (
|
||||
<bdi className="ms-auto font-semibold tabular-nums text-content">{format.money(item.price)}</bdi>
|
||||
)}
|
||||
{item.travelers.length > 0 && (
|
||||
<span className="flex flex-none items-center gap-1">
|
||||
<PeopleStack people={item.travelers} />
|
||||
{item.moreTravelers > 0 && <span className="font-semibold tabular-nums">+{item.moreTravelers}</span>}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** A fact as a white soft pill with its glyph, the accent dot when an update changes it. */
|
||||
function Pill({
|
||||
icon: Icon,
|
||||
|
||||
@@ -142,6 +142,10 @@ export const STEP_LOOKS: Readonly<Partial<Record<string, StepLook>>> = {
|
||||
stepKey: 'assistant.step.searching',
|
||||
live: { liveKey: 'assistant.step.searchingFor', param: 'query' },
|
||||
},
|
||||
search_places_via_plugins: {
|
||||
stepKey: 'assistant.step.searching',
|
||||
live: { liveKey: 'assistant.step.searchingFor', param: 'query' },
|
||||
},
|
||||
search_pois: { stepKey: 'assistant.step.searching', live: { liveKey: 'assistant.step.nearbyAt', param: 'place' } },
|
||||
get_place_details: { stepKey: 'assistant.step.details' },
|
||||
search_nearby_places: {
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
import type { TourRouteCard } from '@trek/shared';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { GENTLE, HIKE, SAVED } from '../../../../../tests/helpers/assistantTour';
|
||||
import { GENTLE, HIKE, SAVED, tourStop } from '../../../../../tests/helpers/assistantTour';
|
||||
import { buildTrip, buildUser } from '../../../../../tests/helpers/factories';
|
||||
import { act, fireEvent, render, screen } from '../../../../../tests/helpers/render';
|
||||
import { chatOf, useAssistantStore } from '../../../../store/assistantStore';
|
||||
@@ -81,6 +81,34 @@ describe('TourRouteBlock', () => {
|
||||
expect(document.querySelector('[data-profile-compare="call_1"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('preselects the calculated way and keeps the failed way available for diagnosis', () => {
|
||||
const failed: TourRouteCard = {
|
||||
...HIKE,
|
||||
routed: false,
|
||||
distanceM: null,
|
||||
problem: { why: 'point_off_the_way', position: 2, snappedM: 494 },
|
||||
};
|
||||
renderBlock([{ toolCallId: 'call_1', card: failed }, WAYS[1]]);
|
||||
const first = screen.getByRole('radio', { name: 'Way A' });
|
||||
expect(first).toHaveTextContent('not routed');
|
||||
expect(first).not.toHaveTextContent('0 m');
|
||||
expect(screen.getByRole('radio', { name: 'Long and gentle' })).toHaveAttribute('aria-checked', 'true');
|
||||
expect(screen.getByRole('button', { name: 'Plan way B' })).toBeEnabled();
|
||||
expect(screen.queryByTestId('leg-variant-delta')).not.toBeInTheDocument();
|
||||
|
||||
fireEvent.click(first);
|
||||
expect(screen.getByText('Point 2 is too far from any path')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Plan way A' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('warns about a long detour on an open hike while keeping the route available', () => {
|
||||
const start = tourStop({ role: 'start', lat: 35.3969, lng: 138.7345 });
|
||||
const end = tourStop({ role: 'end', lat: 35.3606, lng: 138.7274, atM: 35_856 });
|
||||
renderBlock([{ toolCallId: 'detour', card: { ...HIKE, distanceM: 35_856, stops: [start, end] } }]);
|
||||
expect(screen.getByText(/takes a long detour/)).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'On map' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-AI-TOUR-031: the ways stand side by side in a roomy window and stay rows on the phone', () => {
|
||||
renderBlock(WAYS, { density: 'roomy' });
|
||||
expect(screen.getByRole('radiogroup')).toHaveClass('grid-cols-2');
|
||||
|
||||
@@ -10,7 +10,7 @@ import TourRouteActions from './TourRouteActions';
|
||||
import TourRouteDay from './TourRouteDay';
|
||||
import TourRouteHead, { TourRouteFields } from './TourRouteHead';
|
||||
import { profileSamples } from './tourRouteModel';
|
||||
import { TourRouteProblem, TourRouteWarnings } from './TourRouteNotes';
|
||||
import { TourRouteDetour, TourRouteProblem, TourRouteWarnings } from './TourRouteNotes';
|
||||
import TourRouteProfile from './TourRouteProfile';
|
||||
import TourRouteStops from './TourRouteStops';
|
||||
import { routeName } from './tourRouteWords';
|
||||
@@ -45,6 +45,7 @@ export function TourRouteBody({
|
||||
return (
|
||||
<>
|
||||
<TourRouteFields card={card} />
|
||||
<TourRouteDetour card={card} />
|
||||
{/* A way drawn straight has neither heights nor the line to say so under: no section at all. */}
|
||||
{(samples.length >= 2 || card.routed) && (
|
||||
<CardSection label={t('tours.planner.inspector.elevation')}>
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useTranslation } from '../../../../i18n';
|
||||
import { SoftPill } from '../../../Planner/planParts';
|
||||
import { TourNotice } from '../../../Tours/tourParts';
|
||||
import { useCardFormat } from '../parts/useCardFormat';
|
||||
import { hasLongHikeDetour } from './tourRouteModel';
|
||||
import { PROBLEM_LOOK, WARNING_LOOK } from './tourRouteWords';
|
||||
|
||||
/**
|
||||
@@ -53,3 +54,15 @@ export function TourRouteProblem({ card }: { card: TourRouteCard }) {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function TourRouteDetour({ card }: { card: TourRouteCard }) {
|
||||
const { t } = useTranslation();
|
||||
if (!hasLongHikeDetour(card)) return null;
|
||||
return (
|
||||
<div className="mt-2">
|
||||
<TourNotice tone="warning" icon={<AlertTriangle size={12} strokeWidth={2} aria-hidden="true" />}>
|
||||
{t('assistant.card.tour.longDetour')}
|
||||
</TourNotice>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Route as RouteIcon } from 'lucide-react';
|
||||
import { useMemo } from 'react';
|
||||
|
||||
import { useTranslation } from '../../../../i18n';
|
||||
import { preferredRouteEntry } from '../../../../store/assistantRouteModel';
|
||||
import { chatOf, useAssistantStore } from '../../../../store/assistantStore';
|
||||
import { useSettingsStore } from '../../../../store/settingsStore';
|
||||
import type { DistanceUnit } from '../../../../types';
|
||||
@@ -79,7 +80,7 @@ function WayOption({
|
||||
entry: RouteEntry;
|
||||
index: number;
|
||||
chosen: boolean;
|
||||
chosenWay: LegVariant;
|
||||
chosenWay: LegVariant | null;
|
||||
chosenLetter: string;
|
||||
unit: DistanceUnit;
|
||||
onSelect: () => void;
|
||||
@@ -118,8 +119,14 @@ function WayOption({
|
||||
{/* Ways of a ride or a run may differ by profile: each says its own. */}
|
||||
{entry.card.routingProfile && <TourGrade card={entry.card} />}
|
||||
</span>
|
||||
<WayFigures way={way} unit={unit} />
|
||||
{!chosen && <WayDelta way={way} chosen={chosenWay} letter={chosenLetter} unit={unit} />}
|
||||
{entry.card.routed ? (
|
||||
<WayFigures way={way} unit={unit} />
|
||||
) : (
|
||||
<span className="text-caption text-warning">{t('map.overview.notRouted')}</span>
|
||||
)}
|
||||
{!chosen && entry.card.routed && chosenWay && (
|
||||
<WayDelta way={way} chosen={chosenWay} letter={chosenLetter} unit={unit} />
|
||||
)}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
@@ -156,7 +163,7 @@ function WaysCard({
|
||||
[entries, chosenIndex]
|
||||
);
|
||||
|
||||
const chosenWay = legVariantOf(chosen.card, chosenKey);
|
||||
const chosenWay = chosen.card.routed ? legVariantOf(chosen.card, chosenKey) : null;
|
||||
// Side by side where the window is roomy; on the phone the ways stay rows, so a finger scrubs the profile freely.
|
||||
let columns = '';
|
||||
if (density === 'roomy' && variant !== 'fullscreen') columns = entries.length >= 3 ? 'grid-cols-3' : 'grid-cols-2';
|
||||
@@ -216,10 +223,8 @@ function WaysCard({
|
||||
export default function TourWays({ entries }: { entries: readonly RouteEntry[] }) {
|
||||
const { tripId } = useAssistantView();
|
||||
const blockKey = `tour:${entries[0]?.toolCallId ?? ''}`;
|
||||
const picked = useAssistantStore((s) => chatOf(s, tripId).picks[blockKey] ?? null);
|
||||
const index = entries.findIndex((entry) => entry.toolCallId === picked);
|
||||
const chosenIndex = index < 0 ? 0 : index;
|
||||
const chosen = entries[chosenIndex];
|
||||
const picked = useAssistantStore((s) => chatOf(s, tripId).picks[blockKey]);
|
||||
const chosen = preferredRouteEntry(entries, picked);
|
||||
if (!chosen) return null;
|
||||
return <WaysCard entries={entries} chosen={chosen} chosenIndex={chosenIndex} blockKey={blockKey} />;
|
||||
return <WaysCard entries={entries} chosen={chosen} chosenIndex={entries.indexOf(chosen)} blockKey={blockKey} />;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { cumulativeMetres, type TourRouteCard, type TourRouteStop } from '@trek/shared';
|
||||
import { cumulativeMetres, haversineMetres, type TourRouteCard, type TourRouteStop } from '@trek/shared';
|
||||
|
||||
import type { DistanceIndexedProfileSample } from '../../../../utils/routeGeometry';
|
||||
import { hikePaintCss } from '../../../Tours/hike/hikePaint';
|
||||
@@ -84,6 +84,17 @@ export function profileSamples(card: TourRouteCard): DistanceIndexedProfileSampl
|
||||
}));
|
||||
}
|
||||
|
||||
/** Flag a long detour on an open hike without intermediate waypoints. */
|
||||
export function hasLongHikeDetour(card: TourRouteCard): boolean {
|
||||
if (!card.routed || card.source !== 'proposal' || card.activity !== 'hike' || card.distanceM === null) return false;
|
||||
const waypoints = card.stops.filter((stop) => stop.role !== 'along');
|
||||
const [start, end] = waypoints;
|
||||
if (waypoints.length !== 2 || start?.role !== 'start' || end?.role !== 'end') return false;
|
||||
const directM = haversineMetres(start.lat, start.lng, end.lat, end.lng);
|
||||
// Loops and short switchbacks are expected to cover much more than their direct distance.
|
||||
return directM >= 1_000 && card.distanceM >= Math.max(4 * directM, directM + 10_000);
|
||||
}
|
||||
|
||||
/** A stretch to tint behind the profile, in metres along the route. */
|
||||
interface ProfileBand {
|
||||
fromM: number;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type Dispatch, type SetStateAction, useState } from 'react';
|
||||
import { useMemo, useState } from 'react';
|
||||
|
||||
import type { ChangeItem } from '../assistantParts';
|
||||
import { viewOf } from './cardViews';
|
||||
@@ -21,8 +21,9 @@ const arrived = (items: readonly ChangeItem[]) => items.flatMap((item) => (item.
|
||||
* its preview arrives; after that only the user switches it.
|
||||
*/
|
||||
export function useChangeExclusions(
|
||||
items: readonly ChangeItem[]
|
||||
): [ReadonlySet<string>, Dispatch<SetStateAction<ReadonlySet<string>>>] {
|
||||
items: readonly ChangeItem[],
|
||||
choices: Readonly<Record<string, boolean>>
|
||||
): ReadonlySet<string> {
|
||||
const [excluded, setExcluded] = useState<ReadonlySet<string>>(() => new Set(startingOff(items, new Set())));
|
||||
const [seen, setSeen] = useState<ReadonlySet<string>>(() => new Set(arrived(items)));
|
||||
const fresh = arrived(items).filter((id) => !seen.has(id));
|
||||
@@ -31,5 +32,11 @@ export function useChangeExclusions(
|
||||
setSeen(new Set([...seen, ...fresh]));
|
||||
if (off.length > 0) setExcluded((prev) => new Set([...prev, ...off]));
|
||||
}
|
||||
return [excluded, setExcluded];
|
||||
return useMemo(
|
||||
() =>
|
||||
new Set(
|
||||
items.flatMap(({ toolCallId }) => ((choices[toolCallId] ?? !excluded.has(toolCallId)) ? [] : [toolCallId]))
|
||||
),
|
||||
[items, choices, excluded]
|
||||
);
|
||||
}
|
||||
|
||||
@@ -48,7 +48,7 @@ export function HeaderPills({
|
||||
categories: Category[] | null;
|
||||
categoryId: string;
|
||||
onCategory: (id: string) => void;
|
||||
newCategory: NewCategoryRow;
|
||||
newCategory?: NewCategoryRow;
|
||||
pickedSource: string | null;
|
||||
busy: boolean;
|
||||
/** The place as the form holds it, once it has a position: opens it in a map app (#2178). */
|
||||
@@ -61,14 +61,15 @@ export function HeaderPills({
|
||||
// goes with it, and the focus would drop out of the dialog. It comes back to
|
||||
// the + that opened the field, as a picker's focus comes back to its pill.
|
||||
const plusRef = useRef<HTMLButtonElement | null>(null);
|
||||
const wasOpen = useRef(newCategory.open);
|
||||
const categoryEditorOpen = newCategory?.open ?? false;
|
||||
const wasOpen = useRef(categoryEditorOpen);
|
||||
useEffect(() => {
|
||||
const closed = wasOpen.current && !newCategory.open;
|
||||
wasOpen.current = newCategory.open;
|
||||
const closed = wasOpen.current && !categoryEditorOpen;
|
||||
wasOpen.current = categoryEditorOpen;
|
||||
if (!closed) return;
|
||||
const active = document.activeElement;
|
||||
if (!active || active === document.body || !active.isConnected) plusRef.current?.focus();
|
||||
}, [newCategory.open]);
|
||||
}, [categoryEditorOpen]);
|
||||
|
||||
const noCategory = {
|
||||
label: t('places.noCategory'),
|
||||
@@ -96,7 +97,7 @@ export function HeaderPills({
|
||||
{t(kind.labelKey)}
|
||||
</span>
|
||||
);
|
||||
} else if (newCategory.open) {
|
||||
} else if (newCategory?.open) {
|
||||
lead = <NewCategoryField {...newCategory} t={t} />;
|
||||
} else {
|
||||
lead = (
|
||||
@@ -108,17 +109,19 @@ export function HeaderPills({
|
||||
options={options}
|
||||
fallback={noCategory}
|
||||
/>
|
||||
<Tooltip label={t('places.newCategory')}>
|
||||
<button
|
||||
ref={plusRef}
|
||||
type="button"
|
||||
onClick={() => newCategory.setOpen(true)}
|
||||
aria-label={t('places.newCategory')}
|
||||
className={ROUND_PILL_BUTTON}
|
||||
>
|
||||
<Plus size={13} strokeWidth={2.4} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
{newCategory && (
|
||||
<Tooltip label={t('places.newCategory')}>
|
||||
<button
|
||||
ref={plusRef}
|
||||
type="button"
|
||||
onClick={() => newCategory.setOpen(true)}
|
||||
aria-label={t('places.newCategory')}
|
||||
className={ROUND_PILL_BUTTON}
|
||||
>
|
||||
<Plus size={13} strokeWidth={2.4} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -148,7 +148,9 @@ export type PlacePrefill = {
|
||||
phone?: string
|
||||
osm_id?: string
|
||||
/** A place Google knows, such as one the assistant found: the details column reads it by this id. */
|
||||
google_place_id?: string
|
||||
google_place_id?: string;
|
||||
google_ftid?: string;
|
||||
amap_poi_id?: string;
|
||||
}
|
||||
|
||||
/** A blank form at a prefilled position, with what the POI already knew. */
|
||||
@@ -163,6 +165,8 @@ export function prefillForm(prefill: PlacePrefill, extra: Partial<PlaceFormData>
|
||||
phone: prefill.phone || '',
|
||||
osm_id: prefill.osm_id,
|
||||
google_place_id: prefill.google_place_id,
|
||||
google_ftid: prefill.google_ftid,
|
||||
amap_poi_id: prefill.amap_poi_id,
|
||||
...extra,
|
||||
}
|
||||
}
|
||||
@@ -184,7 +188,9 @@ export function openingDetailsSelection(
|
||||
}
|
||||
}
|
||||
if (prefill) {
|
||||
return { placeId: prefill.google_place_id || prefill.osm_id || undefined, lat: prefill.lat, lng: prefill.lng, name: prefill.name || '' }
|
||||
return {
|
||||
placeId: prefill.google_place_id || prefill.amap_poi_id || prefill.osm_id || undefined,
|
||||
lat: prefill.lat, lng: prefill.lng, name: prefill.name || '' }
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -198,11 +204,7 @@ export function openingDetailsSelection(
|
||||
*/
|
||||
export function openingAutoFilled(place: unknown, prefill: PlacePrefill | null | undefined): Set<ResultField> {
|
||||
return new Set(
|
||||
!place && prefill
|
||||
? (['name', 'address', 'lat', 'lng', 'website', 'phone', 'osm_id'] as ResultField[]).filter(
|
||||
(field) => !!prefill[field as keyof PlacePrefill],
|
||||
)
|
||||
: [],
|
||||
!place && prefill ? RESULT_FIELDS.filter((field) => prefill[field] !== undefined && prefill[field] !== '') : []
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -36,7 +36,7 @@ const tint = (color: string, percent: number) => `color-mix(in srgb, ${color} ${
|
||||
* field after them adds a new tag, in a colour picked the same way and shown on
|
||||
* the field as it is typed. The state is usePlaceTags'; this is its markup.
|
||||
*/
|
||||
export function PlaceFormTags({ tags, t }: { tags: PlaceTagsField; t: Translate }) {
|
||||
export function PlaceFormTags({ tags, t, manage = true }: { tags: PlaceTagsField; t: Translate; manage?: boolean }) {
|
||||
// Which palette is open: a tag's id, 'new' for the new tag's colour, or none.
|
||||
const [palette, setPalette] = useState<number | 'new' | null>(null);
|
||||
// The colour a tag shows while its custom colour is being dragged, before it is kept.
|
||||
@@ -46,6 +46,7 @@ export function PlaceFormTags({ tags, t }: { tags: PlaceTagsField; t: Translate
|
||||
setPalette(null);
|
||||
setPreview(null);
|
||||
};
|
||||
if (!manage && tags.options.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div className={PANEL}>
|
||||
@@ -59,15 +60,19 @@ export function PlaceFormTags({ tags, t }: { tags: PlaceTagsField; t: Translate
|
||||
className={`${PILL} ${tag.on ? '' : PILL_OFF}`}
|
||||
style={tag.on ? { background: tint(color, 18), borderColor: tint(color, 55) } : undefined}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('places.tagColor', { name: tag.name })}
|
||||
aria-expanded={palette === tag.id}
|
||||
onClick={() => (palette === tag.id ? closePalette() : setPalette(tag.id))}
|
||||
className={DOT_BUTTON}
|
||||
>
|
||||
<span aria-hidden="true" className={DOT} style={{ background: color }} />
|
||||
</button>
|
||||
{manage ? (
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('places.tagColor', { name: tag.name })}
|
||||
aria-expanded={palette === tag.id}
|
||||
onClick={() => (palette === tag.id ? closePalette() : setPalette(tag.id))}
|
||||
className={DOT_BUTTON}
|
||||
>
|
||||
<span aria-hidden="true" className={DOT} style={{ background: color }} />
|
||||
</button>
|
||||
) : (
|
||||
<span aria-hidden="true" className={`${DOT} ms-2`} style={{ background: color }} />
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
aria-pressed={tag.on}
|
||||
@@ -95,55 +100,57 @@ export function PlaceFormTags({ tags, t }: { tags: PlaceTagsField; t: Translate
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
<span
|
||||
className={NEW_TAG}
|
||||
style={{
|
||||
background: tint(tags.newColor, typing ? 14 : 6),
|
||||
borderColor: tint(tags.newColor, typing ? 60 : 35),
|
||||
borderStyle: typing ? 'solid' : 'dashed',
|
||||
}}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('places.newTagColor')}
|
||||
aria-expanded={palette === 'new'}
|
||||
onClick={() => (palette === 'new' ? closePalette() : setPalette('new'))}
|
||||
className={DOT_BUTTON}
|
||||
{manage && (
|
||||
<span
|
||||
className={NEW_TAG}
|
||||
style={{
|
||||
background: tint(tags.newColor, typing ? 14 : 6),
|
||||
borderColor: tint(tags.newColor, typing ? 60 : 35),
|
||||
borderStyle: typing ? 'solid' : 'dashed',
|
||||
}}
|
||||
>
|
||||
<span aria-hidden="true" className={DOT} style={{ background: tags.newColor }} />
|
||||
</button>
|
||||
<input
|
||||
type="text"
|
||||
value={tags.name}
|
||||
onChange={(e) => tags.setName(e.target.value)}
|
||||
onKeyDown={tags.handleNameKey}
|
||||
maxLength={TRIP_TAG_NAME_MAX}
|
||||
aria-label={t('places.newTag')}
|
||||
placeholder={t('places.newTag')}
|
||||
className={NEW_TAG_INPUT}
|
||||
style={fs(12, 'body')}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void tags.addNew()}
|
||||
disabled={!tags.canAdd}
|
||||
aria-label={t('places.addTag')}
|
||||
className={ADD_BUTTON}
|
||||
style={tags.canAdd ? { background: tags.newColor, color: 'var(--bg-card)' } : undefined}
|
||||
>
|
||||
<Plus size={13} strokeWidth={2.8} />
|
||||
</button>
|
||||
{palette === 'new' && (
|
||||
<TagColorPopover
|
||||
label={t('places.newTagColor')}
|
||||
value={tags.newColor}
|
||||
onPick={tags.setNewColor}
|
||||
onPreview={tags.setNewColor}
|
||||
onClose={closePalette}
|
||||
t={t}
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('places.newTagColor')}
|
||||
aria-expanded={palette === 'new'}
|
||||
onClick={() => (palette === 'new' ? closePalette() : setPalette('new'))}
|
||||
className={DOT_BUTTON}
|
||||
>
|
||||
<span aria-hidden="true" className={DOT} style={{ background: tags.newColor }} />
|
||||
</button>
|
||||
<input
|
||||
type="text"
|
||||
value={tags.name}
|
||||
onChange={(e) => tags.setName(e.target.value)}
|
||||
onKeyDown={tags.handleNameKey}
|
||||
maxLength={TRIP_TAG_NAME_MAX}
|
||||
aria-label={t('places.newTag')}
|
||||
placeholder={t('places.newTag')}
|
||||
className={NEW_TAG_INPUT}
|
||||
style={fs(12, 'body')}
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void tags.addNew()}
|
||||
disabled={!tags.canAdd}
|
||||
aria-label={t('places.addTag')}
|
||||
className={ADD_BUTTON}
|
||||
style={tags.canAdd ? { background: tags.newColor, color: 'var(--bg-card)' } : undefined}
|
||||
>
|
||||
<Plus size={13} strokeWidth={2.8} />
|
||||
</button>
|
||||
{palette === 'new' && (
|
||||
<TagColorPopover
|
||||
label={t('places.newTagColor')}
|
||||
value={tags.newColor}
|
||||
onPick={tags.setNewColor}
|
||||
onPreview={tags.setNewColor}
|
||||
onClose={closePalette}
|
||||
t={t}
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</DialogSection>
|
||||
</div>
|
||||
|
||||
@@ -36,6 +36,7 @@ export function PlaceFormTexts({
|
||||
notes,
|
||||
dayNotes,
|
||||
dayNumber = null,
|
||||
initialTab,
|
||||
onChange,
|
||||
t,
|
||||
}: {
|
||||
@@ -46,10 +47,11 @@ export function PlaceFormTexts({
|
||||
dayNotes: string | null;
|
||||
/** The day that visit is on, to name the tab after it ("Only day 3"). */
|
||||
dayNumber?: number | null;
|
||||
initialTab?: PlaceTextField;
|
||||
onChange: (field: PlaceTextField, value: string) => void;
|
||||
t: Translate;
|
||||
}) {
|
||||
const { tabs, shown, setActive } = usePlaceTextTabs({ description, notes, dayNotes, dayNumber, t });
|
||||
const { tabs, shown, setActive } = usePlaceTextTabs({ description, notes, dayNotes, dayNumber, t, initialTab });
|
||||
const refs = {
|
||||
description: useRef<HTMLTextAreaElement | null>(null),
|
||||
notes: useRef<HTMLTextAreaElement | null>(null),
|
||||
@@ -102,7 +104,7 @@ export function PlaceFormTexts({
|
||||
value={tab.value}
|
||||
onChange={(e) => onChange(tab.field, e.target.value)}
|
||||
rows={3}
|
||||
maxLength={tab.maxLength}
|
||||
maxLength={initialTab && tab.field === 'assignment_notes' ? 500 : tab.maxLength}
|
||||
className={BARE_TEXTAREA}
|
||||
/>
|
||||
{tab.markdown && (
|
||||
|
||||
@@ -32,6 +32,7 @@ type Toast = ReturnType<typeof useToast>;
|
||||
export interface PlaceFormOptions {
|
||||
t: Translate;
|
||||
toast: Toast;
|
||||
initialForm?: PlaceFormData;
|
||||
/** Files and pictures pasted into the form become attachments only for a member who may upload. */
|
||||
canUploadFiles: boolean;
|
||||
}
|
||||
@@ -43,8 +44,8 @@ export interface PlaceFormOptions {
|
||||
* wrote (see mergeResult), the files chosen before the place exists, what the details
|
||||
* column describes, and the duplicate warning a first save of a new place may raise.
|
||||
*/
|
||||
export function usePlaceForm({ t, toast, canUploadFiles }: PlaceFormOptions) {
|
||||
const [form, setForm] = useState<PlaceFormData>(DEFAULT_FORM);
|
||||
export function usePlaceForm({ t, toast, canUploadFiles, initialForm = DEFAULT_FORM }: PlaceFormOptions) {
|
||||
const [form, setForm] = useState<PlaceFormData>(initialForm);
|
||||
// Which fields the last picked search result wrote. Anything in here belongs
|
||||
// to that place and goes when another is picked; anything outside it is the
|
||||
// user's and survives. See mergeResult.
|
||||
|
||||
@@ -0,0 +1,573 @@
|
||||
import type { PlaceClientOrigin, PlaceOpeningHours, RoadtripStopType, TourListItem } from '@trek/shared';
|
||||
import { guessCategoryId } from '@trek/shared';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useLocationBias } from '../../hooks/useLocationBias';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { useAddonStore } from '../../store/addonStore';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { useCanDo } from '../../store/permissionsStore';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import { useTripAddonEnabled } from '../../store/tripAddonsStore';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
import type { Assignment, BudgetItem, Category, Place } from '../../types';
|
||||
import { DEFAULT_SERVICE_KIND, serviceStopChoice, type ServiceStopMode } from '../Roadtrip/manualStop';
|
||||
import { STOP_KIND_BY_KEY } from '../Roadtrip/stopKinds';
|
||||
import { useToast } from '../shared/Toast';
|
||||
import type { BookingExpenseRequest } from './BookingCostsSection.types';
|
||||
import {
|
||||
DEFAULT_FORM,
|
||||
endsBeforeStart,
|
||||
findDuplicatePlace,
|
||||
formPin,
|
||||
mergeResult,
|
||||
placeEditForm,
|
||||
placeFormPayload,
|
||||
prefillForm,
|
||||
savedCategoryId,
|
||||
type PlaceFormData,
|
||||
type PlacePrefill,
|
||||
} from './PlaceFormModal.helpers';
|
||||
import { useNewCategory, usePlaceForm } from './usePlaceForm';
|
||||
import { usePlaceImageField } from './usePlaceImageField';
|
||||
import { usePlaceRefresh } from './usePlaceRefresh';
|
||||
import { usePlaceSearch } from './usePlaceSearch';
|
||||
import { usePlaceTags } from './usePlaceTags';
|
||||
|
||||
// The submit payload mirrors the form, but lat/lng are parsed to numbers and
|
||||
// category_id is normalised, plus any files chosen before the place existed.
|
||||
export interface PlaceSubmitData extends Omit<PlaceFormData, 'lat' | 'lng' | 'category_id'> {
|
||||
lat: number | null;
|
||||
lng: number | null;
|
||||
category_id: string | null;
|
||||
_pendingFiles?: File[];
|
||||
/**
|
||||
* Where a road-trip service stop belongs on the drive, worked out from the
|
||||
* coordinates being saved. Travels the same way `_pendingFiles` does: the planner
|
||||
* reads it, strips it, and assigns the new place at that position.
|
||||
*/
|
||||
_serviceStop?: { dayId: number; position: number; offRouteKm: number } | null;
|
||||
}
|
||||
|
||||
interface PlaceProposal {
|
||||
initialForm: PlaceFormData;
|
||||
existing: boolean;
|
||||
dayId: number | null;
|
||||
disabled: boolean;
|
||||
onPreview: (form: PlaceFormData) => void;
|
||||
onSave: (form: PlaceFormData) => void;
|
||||
}
|
||||
|
||||
interface PlaceFormModalBaseProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
place: Place | null;
|
||||
prefillCoords?:
|
||||
(PlacePrefill & { stop_type?: RoadtripStopType | null; duration_minutes?: number; category?: string }) | null;
|
||||
tripId: number;
|
||||
categories: Category[];
|
||||
onCategoryCreated?: (category: { name: string; color?: string; icon?: string }) => Promise<Category> | undefined;
|
||||
assignmentId: number | null;
|
||||
dayAssignments?: Assignment[];
|
||||
/** Mobile keeps the untouched single-column form; desktop adds the saved-place
|
||||
* picker column when the Collections addon is enabled. Sourced from the trip
|
||||
* planner's useIsPhone(). */
|
||||
isMobile?: boolean;
|
||||
/** Opens the Costs editor for this place's linked expense (#1298) — the same
|
||||
* seam the booking and transport modals use. */
|
||||
onOpenExpense?: (req: BookingExpenseRequest) => void;
|
||||
/**
|
||||
* Turns this into the form a road trip's service stop is added on: the category
|
||||
* control becomes the kind of stop, the costs section goes, and a row asks which leg
|
||||
* of the drive it belongs on. Absent, nothing about the form changes.
|
||||
*/
|
||||
serviceStop?: ServiceStopMode | null;
|
||||
/** Road trip mode is on, where a visit's End is when the drive leaves it. */
|
||||
roadtripActive?: boolean;
|
||||
/** TIME-02: the tour this place is, whose end the time fields work out from its start; absent for a plain place. */
|
||||
tour?: TourListItem | null;
|
||||
}
|
||||
|
||||
export type PlaceFormModalProps = PlaceFormModalBaseProps &
|
||||
(
|
||||
| { proposal: PlaceProposal; onSave?: never }
|
||||
| { proposal?: never; onSave: (data: PlaceSubmitData, files?: File[]) => Promise<{ id: number } | void> | void }
|
||||
);
|
||||
|
||||
/** Place create/edit form state: maps search + Google-URL resolve + autocomplete,
|
||||
* category creation, file attachments and submit. Keeps PlaceFormModal a thin
|
||||
* render over the form fields. */
|
||||
export function usePlaceFormModal(props: PlaceFormModalProps) {
|
||||
const {
|
||||
isOpen,
|
||||
onClose,
|
||||
onSave,
|
||||
place,
|
||||
prefillCoords,
|
||||
tripId,
|
||||
categories,
|
||||
onCategoryCreated,
|
||||
assignmentId,
|
||||
dayAssignments = [],
|
||||
isMobile = false,
|
||||
onOpenExpense,
|
||||
serviceStop = null,
|
||||
proposal,
|
||||
} = props;
|
||||
// Hidden while the addon is off, because the kinds only mean anything to the road trip
|
||||
// rail: on an instance without it they would be six labels that change nothing.
|
||||
const distanceUnit = useSettingsStore((s) => s.settings.distance_unit) || 'metric';
|
||||
const toast = useToast();
|
||||
const { t, locale } = useTranslation();
|
||||
const { placesEnrichEnabled } = useAuthStore();
|
||||
const can = useCanDo();
|
||||
const timeFormat = useSettingsStore((s) => s.settings.time_format) || '24h';
|
||||
const tripObj = useTripStore((s) => s.trip);
|
||||
const canUploadFiles = !proposal && can('file_upload', tripObj);
|
||||
const collectionsEnabled = useAddonStore((s) => s.isEnabled('collections'));
|
||||
const isBudgetEnabled = useTripAddonEnabled(tripId, 'budget');
|
||||
const deleteBudgetItem = useTripStore((s) => s.deleteBudgetItem);
|
||||
const {
|
||||
form,
|
||||
setForm,
|
||||
autoFilledRef,
|
||||
pendingFiles,
|
||||
addFilesFromInput,
|
||||
removeFile,
|
||||
handlePaste,
|
||||
isSaving,
|
||||
setIsSaving,
|
||||
duplicateWarning,
|
||||
detailsSelection,
|
||||
setDetailsSelection,
|
||||
openForm,
|
||||
handleChange: changeField,
|
||||
pickImage,
|
||||
adoptDescription,
|
||||
warnIfDuplicate,
|
||||
pendingImage,
|
||||
stageUpload,
|
||||
stageAttached,
|
||||
removeImage,
|
||||
} = usePlaceForm({ t, toast, canUploadFiles, initialForm: proposal?.initialForm });
|
||||
const image = usePlaceImageField({
|
||||
place,
|
||||
imageUrl: form.image_url,
|
||||
pendingImage,
|
||||
canUploadFiles,
|
||||
stageUpload,
|
||||
stageAttached,
|
||||
removeImage,
|
||||
});
|
||||
const tagField = usePlaceTags({ tripId, place, tags: form.tags, setForm, t, toast });
|
||||
// The index the picked place came from, as its row named it, shown as a pill
|
||||
// in the head band. Null for a place typed by hand or taken from the saved list.
|
||||
const [pickedSource, setPickedSource] = useState<string | null>(null);
|
||||
// Whether the category was preselected from a search result rather than chosen, so
|
||||
// the next pick may replace it and a hand choice is never overwritten (#2282).
|
||||
const categoryGuessedRef = useRef(false);
|
||||
const guessedCategory = (result: Record<string, unknown>): string => {
|
||||
const saved = savedCategoryId(result, categories || []); // a collection's place keeps its own (#3074)
|
||||
const id = saved ? null : guessCategoryId(result, categories || []);
|
||||
categoryGuessedRef.current = id != null;
|
||||
return saved ?? (id != null ? String(id) : '');
|
||||
};
|
||||
// The hours the details column looked up, as a week the contact block can take over (#2472).
|
||||
const [detailsHours, setDetailsHours] = useState<PlaceOpeningHours | null>(null);
|
||||
/**
|
||||
* The leg of the drive the traveller picked, or empty while the projection's own
|
||||
* answer stands. Empty rather than seeded, because there is nothing to project onto
|
||||
* until a place has been chosen and the answer has to follow the coordinates.
|
||||
*/
|
||||
const [serviceStopLeg, setServiceStopLeg] = useState('');
|
||||
const fileRef = useRef(null);
|
||||
// Set right before submit when the user clicked create/edit expense — the
|
||||
// place has to exist before an expense can point at it (see ReservationModal).
|
||||
const expenseIntentRef = useRef<{ editItem?: BudgetItem; create?: boolean } | null>(null);
|
||||
const newCategory = useNewCategory({
|
||||
variant: 'dialog',
|
||||
create: (category) => onCategoryCreated?.(category),
|
||||
onCreated: (categoryId) => setForm((prev) => ({ ...prev, category_id: categoryId })),
|
||||
t,
|
||||
toast,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
categoryGuessedRef.current = false;
|
||||
let next: PlaceFormData;
|
||||
if (proposal) {
|
||||
const { initialForm } = proposal;
|
||||
const pin = formPin(initialForm);
|
||||
const details = pin && {
|
||||
...pin,
|
||||
name: initialForm.name,
|
||||
address: initialForm.address,
|
||||
website: initialForm.website,
|
||||
phone: initialForm.phone,
|
||||
osm_id: initialForm.osm_id,
|
||||
google_place_id: initialForm.google_place_id,
|
||||
google_ftid: initialForm.google_ftid,
|
||||
amap_poi_id: initialForm.amap_poi_id,
|
||||
};
|
||||
openForm(initialForm, null, details);
|
||||
return;
|
||||
} else if (place) {
|
||||
const assignment = assignmentId ? dayAssignments.find((a) => a.id === assignmentId) : null;
|
||||
next = placeEditForm(place, assignment, {
|
||||
// Shown in the contact block now (#2472), so an edit carries what is there.
|
||||
phone: place.phone || '',
|
||||
email: place.email || '',
|
||||
opening_hours: place.opening_hours || '',
|
||||
// Carried through every edit. Without it, opening a fuel stop to fix a typo
|
||||
// submits an empty kind and turns it back into a numbered destination.
|
||||
// duration_minutes deliberately stays out: how long a stay takes belongs to the
|
||||
// rail's own dialog, and sending it from here would overwrite what was set there.
|
||||
stop_type: place.stop_type ?? null,
|
||||
});
|
||||
} else if (prefillCoords) {
|
||||
next = prefillForm(prefillCoords, {
|
||||
category_id: guessedCategory(prefillCoords),
|
||||
stop_type: prefillCoords.stop_type ?? null,
|
||||
duration_minutes: prefillCoords.duration_minutes,
|
||||
});
|
||||
} else if (serviceStop) {
|
||||
// A stop on a drive is a kind and a dwell before it is anything else, so the form
|
||||
// opens on one rather than on nothing: a service stop left without a kind is a
|
||||
// numbered destination that counts in every total, which is the very thing this
|
||||
// path exists to avoid. Read out of the closure rather than watched, because the
|
||||
// mode is fixed for the life of one opening and a rebuilt drive must not reset a
|
||||
// half-filled form.
|
||||
// What the corridor panel was looking for when the button was pressed, because
|
||||
// that is the traveller's own answer to what they are adding; only a panel with
|
||||
// nothing selected falls back to the constant. The dwell follows the kind, the
|
||||
// same way picking one by hand moves it.
|
||||
const kind = serviceStop.defaultKind ?? DEFAULT_SERVICE_KIND;
|
||||
next = {
|
||||
...DEFAULT_FORM,
|
||||
stop_type: kind,
|
||||
duration_minutes: STOP_KIND_BY_KEY[kind].defaultMinutes,
|
||||
};
|
||||
} else {
|
||||
next = DEFAULT_FORM;
|
||||
}
|
||||
// The column follows whatever the dialog was opened with, not only a search
|
||||
// pick: a POI tapped on the map and a right-click place arrive as
|
||||
// prefillCoords, and editing an existing place arrives as `place`.
|
||||
openForm(next, place, prefillCoords);
|
||||
setServiceStopLeg('');
|
||||
setPickedSource(null);
|
||||
// A fresh dialog owns no intention either. The ref is armed by a click on the Costs
|
||||
// section and spent by the save that follows it; a save that never happened leaves it
|
||||
// armed, and the next opening would consume it for a place nobody linked an expense
|
||||
// to. In service-stop mode that opening has no Costs section at all, so the editor
|
||||
// would arrive out of nowhere, on a petrol stop, filed as an activity.
|
||||
expenseIntentRef.current = null;
|
||||
// dayAssignments is a fresh array each render; read it at open-time only and
|
||||
// re-run on identity changes (place/assignmentId/open), not on every render.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [place, prefillCoords, isOpen, assignmentId]);
|
||||
|
||||
const places = useTripStore((s) => s.places);
|
||||
const tripDays = useTripStore((s) => s.days);
|
||||
// Where the trip is happening — the hint that tells the search which of a
|
||||
// thousand identically named places is meant. Autocomplete wants a box, the
|
||||
// search wants a point; both are derived from the same places.
|
||||
const { box: locationBias } = useLocationBias();
|
||||
|
||||
/**
|
||||
* The one point every pick flows through, so the detail column hangs here: a
|
||||
* search row, a suggestion's place, or a place from the saved-place picker.
|
||||
* `label` is the name the picked row's badge carried; a saved place names none.
|
||||
*/
|
||||
const applyPickedPlace = (result: Record<string, unknown>, label: string | null) => {
|
||||
setForm((prev) => {
|
||||
const merged = mergeResult(prev, result, autoFilledRef.current);
|
||||
if (prev.category_id && !categoryGuessedRef.current) return merged;
|
||||
return { ...merged, category_id: guessedCategory(result) };
|
||||
});
|
||||
setPickedSource(label);
|
||||
// A new pick drops whatever hero image belonged to the previous place.
|
||||
const lat = Number(result.lat);
|
||||
const lng = Number(result.lng);
|
||||
if (Number.isFinite(lat) && Number.isFinite(lng)) {
|
||||
setDetailsSelection({
|
||||
placeId: (result.google_place_id || result.amap_poi_id || result.osm_id || undefined) as string | undefined,
|
||||
lat,
|
||||
lng,
|
||||
name: (result.name as string) || '',
|
||||
// Hand the record along: the server needs the same OSM tags, and
|
||||
// looking them up again costs an Overpass round trip it can skip.
|
||||
details: result,
|
||||
});
|
||||
setForm((prev) => ({ ...prev, image_url: undefined }));
|
||||
}
|
||||
};
|
||||
|
||||
const search = usePlaceSearch({
|
||||
variant: 'dialog',
|
||||
locationBias,
|
||||
t,
|
||||
toast,
|
||||
// The planner keeps this dialog mounted while it is closed (the shell only
|
||||
// stops drawing it), so the search block is reset when it closes, apart from
|
||||
// the opening effect above: that one also reruns while the dialog is open, when
|
||||
// a right-click's reverse lookup fills prefillCoords, and must not wipe a
|
||||
// search the user has started since.
|
||||
open: isOpen,
|
||||
onPlace: applyPickedPlace,
|
||||
onSuggestionName: (name) => setForm((prev) => ({ ...prev, name })),
|
||||
onMapLink: (resolved) => {
|
||||
setForm((prev) => ({
|
||||
...prev,
|
||||
name: resolved.name || prev.name,
|
||||
address: resolved.address || prev.address,
|
||||
lat: String(resolved.lat),
|
||||
lng: String(resolved.lng),
|
||||
google_ftid: resolved.google_ftid || prev.google_ftid,
|
||||
}));
|
||||
// The fields are the link's now, not the last picked result's.
|
||||
setPickedSource(null);
|
||||
},
|
||||
});
|
||||
const refresh = usePlaceRefresh({ place, form, language: search.language });
|
||||
|
||||
/**
|
||||
* What a stop on a drive might be a second copy of, said while the form is being filled.
|
||||
*
|
||||
* By the map record and by where it stands, never by its name: two Arals on one
|
||||
* motorway are two petrol stations, and a check that called them one refused the save
|
||||
* the first time it was pressed. This one refuses nothing: it is a note beside the
|
||||
* name, and the reader decides.
|
||||
*/
|
||||
const serviceStopDuplicate = useMemo(() => {
|
||||
if (!serviceStop || place) return null;
|
||||
return findDuplicatePlace(form, places, { byName: false, byOsmId: true })?.name ?? null;
|
||||
}, [serviceStop, place, form, places]);
|
||||
|
||||
const handleChange = (field: string, value: string, origin?: PlaceClientOrigin) => {
|
||||
if (field === 'category_id') categoryGuessedRef.current = false;
|
||||
changeField(field, value, origin);
|
||||
};
|
||||
|
||||
// What is around the pin the form holds (#976).
|
||||
const pin = formPin(form);
|
||||
const handleNearby = () => search.searchNearby(pin);
|
||||
|
||||
/**
|
||||
* The kind of stop, and with it how long that kind usually takes.
|
||||
*
|
||||
* Picking a kind is also picking a dwell, until the user says otherwise: a charge is
|
||||
* not a fuel stop. Only ever called for a kind that is not already on, so a dwell set
|
||||
* by hand survives a second click on the same pill.
|
||||
*/
|
||||
const handleStopKind = useCallback(
|
||||
(kind: RoadtripStopType) => {
|
||||
setForm((prev) => ({ ...prev, stop_type: kind, duration_minutes: STOP_KIND_BY_KEY[kind].defaultMinutes }));
|
||||
},
|
||||
[setForm]
|
||||
);
|
||||
|
||||
const handleStopMinutes = useCallback(
|
||||
(minutes: number) => {
|
||||
setForm((prev) => ({ ...prev, duration_minutes: minutes }));
|
||||
},
|
||||
[setForm]
|
||||
);
|
||||
|
||||
const hasTimeError = !!(place || proposal) && endsBeforeStart(form.place_time, form.end_time);
|
||||
const previewDraft = proposal?.onPreview;
|
||||
useEffect(() => {
|
||||
if (isOpen) previewDraft?.(form);
|
||||
}, [form, isOpen, previewDraft]);
|
||||
|
||||
const handleSubmit = async (e?: { preventDefault?: () => void }) => {
|
||||
e?.preventDefault?.();
|
||||
if (!form.name.trim()) {
|
||||
// Nothing was saved, so an expense intent from a previous click is stale —
|
||||
// otherwise the next plain Save would open a Costs editor out of nowhere.
|
||||
expenseIntentRef.current = null;
|
||||
toast.error(t('places.nameRequired'));
|
||||
return;
|
||||
}
|
||||
if (proposal) {
|
||||
if (proposal.disabled || hasTimeError) return;
|
||||
try {
|
||||
proposal.onSave(form);
|
||||
onClose();
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : t('places.saveError'));
|
||||
}
|
||||
return;
|
||||
}
|
||||
// #1152: only for new places, and only on the first attempt — a second click
|
||||
// (with the warning already showing) is the explicit "add anyway" confirmation.
|
||||
//
|
||||
// Never for a stop on a drive. Most of what that check catches is a repeated name,
|
||||
// and on a motorway a repeated name is the normal case: the second Aral is four
|
||||
// hundred kilometres from the first and is a different petrol station. The popup this
|
||||
// path replaced compared the OSM object for exactly that reason and never gated the
|
||||
// save on it, only noted it. So the note is shown beside the name while the form is
|
||||
// being filled (see serviceStopDuplicate), which is the earlier word anyway, and the
|
||||
// press that saves is the press that saves.
|
||||
if (!place && !serviceStop && !duplicateWarning && warnIfDuplicate(places)) {
|
||||
// Nothing was saved, so an expense intent from a previous click is stale, and
|
||||
// the next plain Save would otherwise open a Costs editor out of nowhere.
|
||||
expenseIntentRef.current = null;
|
||||
return;
|
||||
}
|
||||
setIsSaving(true);
|
||||
try {
|
||||
const ctxAssignment = assignmentId ? dayAssignments.find((a) => a.id === assignmentId) : null;
|
||||
const payload = placeFormPayload(
|
||||
form,
|
||||
pendingFiles,
|
||||
ctxAssignment,
|
||||
(lat, lng) => ({
|
||||
// An explicit null is how a stop stops being a fuel stop; the service reads it
|
||||
// that way rather than as "leave alone", which is what a missing key means.
|
||||
stop_type: form.stop_type || null,
|
||||
// Only on the way in, and only with a kind: it is the popup's suggestion for how
|
||||
// long that kind of pause takes. On an edit it is left out entirely, because the
|
||||
// stay belongs to the rail's dialog and sending it here would overwrite it.
|
||||
...(!place && form.stop_type && form.duration_minutes ? { duration_minutes: form.duration_minutes } : {}),
|
||||
// Where on the drive it goes, worked out HERE and not when the dialog opened: a
|
||||
// stop added by hand has no coordinates at all until a place has been chosen in
|
||||
// it, so the answer has to follow what is actually being saved.
|
||||
...(serviceStop ? { _serviceStop: serviceStopChoice(serviceStop, lat, lng, serviceStopLeg).placement } : {}),
|
||||
}),
|
||||
pendingImage
|
||||
);
|
||||
const saved = await onSave?.(payload);
|
||||
// Open the Costs editor for the saved place when the user asked to
|
||||
// create/edit its linked expense — gated on an id, so a create that the
|
||||
// server refused never opens an editor pointing at nothing (#1298).
|
||||
const intent = expenseIntentRef.current;
|
||||
expenseIntentRef.current = null;
|
||||
const savedId = (saved && 'id' in saved ? saved.id : null) ?? place?.id ?? null;
|
||||
if (intent && onOpenExpense && savedId) {
|
||||
if (intent.editItem) onOpenExpense({ editItem: intent.editItem });
|
||||
else onOpenExpense({ prefill: { placeId: savedId, name: form.name.trim(), category: 'activities' } });
|
||||
}
|
||||
onClose();
|
||||
} catch (err: unknown) {
|
||||
// The save did not happen, so the intent behind it cannot be honoured: the place
|
||||
// the expense would point at does not exist. Left armed it would ride along to
|
||||
// whatever the next press saves.
|
||||
expenseIntentRef.current = null;
|
||||
toast.error(err instanceof Error ? err.message : t('places.saveError'));
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCreateExpense = () => {
|
||||
expenseIntentRef.current = { create: true };
|
||||
void handleSubmit();
|
||||
};
|
||||
const handleEditExpense = (item: BudgetItem) => {
|
||||
expenseIntentRef.current = { editItem: item };
|
||||
void handleSubmit();
|
||||
};
|
||||
const handleRemoveExpense = async (item: BudgetItem) => {
|
||||
try {
|
||||
await deleteBudgetItem(Number(tripId), item.id);
|
||||
} catch {
|
||||
toast.error(t('common.unknownError'));
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
isOpen,
|
||||
onClose,
|
||||
place,
|
||||
prefillCoords,
|
||||
categories,
|
||||
assignmentId,
|
||||
dayAssignments,
|
||||
dayNumber: proposal
|
||||
? (tripDays.find((day) => day.id === proposal.dayId)?.day_number ?? null)
|
||||
: dayNumberOf(assignmentId, dayAssignments, tripDays),
|
||||
isMobile,
|
||||
collectionsEnabled,
|
||||
form,
|
||||
mapsSearch: search.query,
|
||||
setMapsSearch: search.setQuery,
|
||||
mapsResults: search.results,
|
||||
isSearchingMaps: search.searching,
|
||||
newCategoryName: newCategory.name,
|
||||
setNewCategoryName: newCategory.setName,
|
||||
showNewCategory: newCategory.open,
|
||||
setShowNewCategory: newCategory.setOpen,
|
||||
isSaving,
|
||||
pendingFiles,
|
||||
emptySearch: search.emptySearch,
|
||||
setEmptySearch: search.setEmptySearch,
|
||||
detailsHours,
|
||||
setDetailsHours,
|
||||
fileRef,
|
||||
acSuggestions: search.suggestions,
|
||||
setAcSuggestions: search.setSuggestions,
|
||||
acSource: search.acSource,
|
||||
searchSource: search.searchSource,
|
||||
acHighlight: search.highlight,
|
||||
setAcHighlight: search.setHighlight,
|
||||
t,
|
||||
language: search.language,
|
||||
locale,
|
||||
refresh,
|
||||
timeFormat,
|
||||
googleAnswers: search.googleAnswers,
|
||||
placesEnrichEnabled,
|
||||
canUploadFiles,
|
||||
locationBias,
|
||||
fetchSuggestions: search.fetchSuggestions,
|
||||
sourceLabel: search.sourceLabel,
|
||||
handleChange,
|
||||
handleMapsSearch: search.runSearch,
|
||||
handleNearby,
|
||||
pin,
|
||||
nearbyList: search.nearbyList,
|
||||
distanceUnit,
|
||||
handleSelectMapsResult: search.pickPlace,
|
||||
handleSelectSuggestion: search.selectSuggestion,
|
||||
handleSearchKeyDown: search.handleKeyDown,
|
||||
handleCreateCategory: newCategory.submit,
|
||||
handleFileAdd: addFilesFromInput,
|
||||
handleRemoveFile: removeFile,
|
||||
handlePaste,
|
||||
pickImage,
|
||||
image,
|
||||
tagField,
|
||||
adoptDescription,
|
||||
hasTimeError,
|
||||
handleSubmit,
|
||||
duplicateWarning,
|
||||
pickedSource,
|
||||
detailsSelection,
|
||||
isBudgetEnabled,
|
||||
handleCreateExpense,
|
||||
handleEditExpense,
|
||||
handleRemoveExpense,
|
||||
serviceStop,
|
||||
serviceStopDuplicate,
|
||||
serviceStopLeg,
|
||||
setServiceStopLeg,
|
||||
handleStopKind,
|
||||
handleStopMinutes,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Detail column, form and saved places side by side, inside the scrolling body
|
||||
* rather than as it: a row that scrolled itself would stretch the side columns
|
||||
* to the visible height only, and they would end halfway down the form.
|
||||
*/
|
||||
/** The number of the day the edited visit is on, for the day note's tab; null when it is not known. */
|
||||
function dayNumberOf(
|
||||
assignmentId: number | null,
|
||||
visits: Assignment[],
|
||||
days: { id: number; day_number?: number | null }[]
|
||||
): number | null {
|
||||
if (!assignmentId) return null;
|
||||
const dayId = visits.find((visit) => visit.id === assignmentId)?.day_id;
|
||||
return days.find((day) => day.id === dayId)?.day_number ?? null;
|
||||
}
|
||||
@@ -25,6 +25,7 @@ interface PlaceTextTabsOptions {
|
||||
dayNotes: string | null;
|
||||
/** The day that visit is on, to name the tab after it ("Only day 3"). */
|
||||
dayNumber?: number | null;
|
||||
initialTab?: PlaceTextField;
|
||||
t: Translate;
|
||||
}
|
||||
|
||||
@@ -34,8 +35,15 @@ interface PlaceTextTabsOptions {
|
||||
* The one logic path behind the desktop card and the phone sheet; each draws its
|
||||
* own tabs and field over it.
|
||||
*/
|
||||
export function usePlaceTextTabs({ description, notes, dayNotes, dayNumber = null, t }: PlaceTextTabsOptions) {
|
||||
const [active, setActive] = useState<PlaceTextField>('description');
|
||||
export function usePlaceTextTabs({
|
||||
description,
|
||||
notes,
|
||||
dayNotes,
|
||||
dayNumber = null,
|
||||
t,
|
||||
initialTab = 'description',
|
||||
}: PlaceTextTabsOptions) {
|
||||
const [active, setActive] = useState<PlaceTextField>(initialTab);
|
||||
const tabs: PlaceTextTab[] = [
|
||||
{
|
||||
field: 'description',
|
||||
|
||||
@@ -157,7 +157,10 @@ export function useAssistantMapLink(options: MapLinkOptions): AssistantMapProps
|
||||
* on every frame, does not render the whole planner each time.
|
||||
*/
|
||||
function useGhostCandidates(tripId: number): GhostCandidate[] {
|
||||
const signature = useAssistantStore((s) => JSON.stringify(ghostCandidates(chatOf(s, tripId).messages)));
|
||||
const signature = useAssistantStore((s) => {
|
||||
const { messages, planEdits, planEditPreview } = chatOf(s, tripId);
|
||||
return JSON.stringify(ghostCandidates(messages, planEdits, planEditPreview));
|
||||
});
|
||||
return useMemo(() => JSON.parse(signature) as GhostCandidate[], [signature]);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import type {
|
||||
AssistantActivity,
|
||||
AssistantErrorCode,
|
||||
AssistantFocus,
|
||||
AssistantMention,
|
||||
AssistantMessage,
|
||||
AssistantPlanEdits,
|
||||
AssistantThreadSummary,
|
||||
} from '@trek/shared';
|
||||
import type { Assignment } from '../types';
|
||||
|
||||
export interface AssistantTripChat {
|
||||
/** The open thread; null for a new one the first message creates. */
|
||||
threadId: number | null;
|
||||
/** The user's latest threads in this trip; null until loaded. */
|
||||
threads: AssistantThreadSummary[] | null;
|
||||
messages: AssistantMessage[];
|
||||
isRunning: boolean;
|
||||
/** A thread is being loaded. */
|
||||
loading: boolean;
|
||||
error: AssistantErrorCode | null;
|
||||
/** What the next message is about: a place the user asked from, or the selected day. */
|
||||
focus: AssistantFocus | null;
|
||||
/** What is typed but not sent, kept while the phone screen hops to the map. */
|
||||
draft: string;
|
||||
/** The text of a message the server refused before answering, sent again by retry(). */
|
||||
unsent: string | null;
|
||||
/** Ends the running stream. */
|
||||
abort: AbortController | null;
|
||||
/** What the running step is doing (the place it searches near, the area); streamed only, never stored. */
|
||||
live: { activity: AssistantActivity | null };
|
||||
/** The applied changes taken back in this session, by call. */
|
||||
undone: Record<string, true>;
|
||||
/** "Before" and "after" of the last block of changes applied here; null when there is none to compare. */
|
||||
compare: AssistantCompare | null;
|
||||
/** The days, places and bookings named with @ in the draft. */
|
||||
mentions: AssistantMentionItem[];
|
||||
/** The way picked among the ways a block of cards offers, by block. */
|
||||
picks: Record<string, string>;
|
||||
/** Edits saved in a proposal's dialog, waiting for the batch decision. */
|
||||
planEdits: Readonly<Record<string, AssistantPlanEdits>>;
|
||||
/** The open editor's temporary edits, shown only in the planner preview. */
|
||||
planEditPreview: { toolCallId: string; edits: AssistantPlanEdits } | null;
|
||||
/** Which proposals the user explicitly switched on or off. */
|
||||
changeChoices: Readonly<Record<string, boolean>>;
|
||||
}
|
||||
|
||||
/** A mention as the composer picked it, with the label it wrote into the text. */
|
||||
export type AssistantMentionItem = AssistantMention & { label: string };
|
||||
|
||||
/**
|
||||
* The plan of the days one applied block of changes touched, as it was just
|
||||
* before, so the map can show either side. Lives only in this session.
|
||||
*/
|
||||
export interface AssistantCompare {
|
||||
/** The block it belongs to, `blockKeyOf` its calls. */
|
||||
blockKey: string;
|
||||
mode: 'before' | 'after';
|
||||
/** The affected days' stops before the block ran, by day. */
|
||||
snapshot: Record<number, Assignment[]>;
|
||||
/** The calls of the block that make a new place. */
|
||||
newPlaceCalls: string[];
|
||||
/** The places those calls made, hidden while "before" is on. */
|
||||
addedPlaceIds: number[];
|
||||
}
|
||||
@@ -1,4 +1,11 @@
|
||||
import type { AssistantActivityArea, AssistantApplied, AssistantChangeEffect, AssistantMessage } from '@trek/shared';
|
||||
import {
|
||||
editedPlaceEffect,
|
||||
type AssistantActivityArea,
|
||||
type AssistantApplied,
|
||||
type AssistantChangeEffect,
|
||||
type AssistantMessage,
|
||||
type AssistantPlanEdits,
|
||||
} from '@trek/shared';
|
||||
import type { Assignment, AssignmentsMap } from '../types';
|
||||
|
||||
/**
|
||||
@@ -22,11 +29,18 @@ export function blockKeyOf(toolCallIds: readonly string[]): string {
|
||||
}
|
||||
|
||||
/** The effect each change of the thread has on the day plan, by its call. */
|
||||
export function changeEffects(messages: readonly AssistantMessage[]): Map<string, AssistantChangeEffect> {
|
||||
export function changeEffects(
|
||||
messages: readonly AssistantMessage[],
|
||||
edits: Readonly<Record<string, AssistantPlanEdits>> = {},
|
||||
live?: { toolCallId: string; edits: AssistantPlanEdits } | null
|
||||
): Map<string, AssistantChangeEffect> {
|
||||
const effects = new Map<string, AssistantChangeEffect>();
|
||||
for (const m of messages) {
|
||||
for (const p of m.parts) {
|
||||
if (p.type === 'data-trek-change' && p.data.effect) effects.set(p.data.toolCallId, p.data.effect);
|
||||
if (p.type !== 'data-trek-change') continue;
|
||||
const { toolCallId } = p.data;
|
||||
const effect = editedPlaceEffect(p.data, live?.toolCallId === toolCallId ? live.edits : edits[toolCallId]);
|
||||
if (effect) effects.set(toolCallId, effect);
|
||||
}
|
||||
}
|
||||
return effects;
|
||||
@@ -58,8 +72,9 @@ export interface GhostCandidate {
|
||||
* order of the chat. Discarded, expired and failed changes are not, and
|
||||
* neither is a removal: what goes is already on the map.
|
||||
*/
|
||||
export function ghostCandidates(messages: readonly AssistantMessage[]): GhostCandidate[] {
|
||||
const effects = changeEffects(messages);
|
||||
export function ghostCandidates(...args: Parameters<typeof changeEffects>): GhostCandidate[] {
|
||||
const [messages] = args;
|
||||
const effects = changeEffects(...args);
|
||||
if (effects.size === 0) return [];
|
||||
const receipts = receiptsOf(messages);
|
||||
const candidates: GhostCandidate[] = [];
|
||||
|
||||
@@ -141,6 +141,21 @@ describe('assistantRouteModel', () => {
|
||||
expect(discarded.map((ref) => ref.toolCallId)).toEqual(['call_1', 'call_2']);
|
||||
});
|
||||
|
||||
it('highlights a calculated alternative by default and respects a manual selection', () => {
|
||||
const unplanned = { ...HIKE, routed: false, distanceM: null };
|
||||
const latest = message([...read('a', unplanned), ...read('b', GENTLE)]);
|
||||
const selection = (picks: Readonly<Record<string, string>>) =>
|
||||
routeRefs([latest], picks, NOBODY, LOOK, AS_WAYS).map((ref) => [ref.way, ref.picked]);
|
||||
expect(selection({})).toEqual([
|
||||
['a', false],
|
||||
['b', true],
|
||||
]);
|
||||
expect(selection({ 'tour:a': 'a' })).toEqual([
|
||||
['a', true],
|
||||
['b', false],
|
||||
]);
|
||||
});
|
||||
|
||||
it("FE-AI-ROUTE-003: lines lie in order (replaced way, others, the chosen way, the lit one) in their ways' colours", () => {
|
||||
const previous = { line: flat(HIKE), distanceM: 8000, ascentM: null, minutes: null };
|
||||
const messages = [
|
||||
|
||||
@@ -19,6 +19,15 @@ export interface RouteCardEntry {
|
||||
card: TrekCard;
|
||||
}
|
||||
|
||||
/** Use the first calculated route unless the user chose a particular way. */
|
||||
export function preferredRouteEntry<T extends RouteCardEntry>(entries: readonly T[], picked?: string): T | undefined {
|
||||
return (
|
||||
entries.find((entry) => entry.toolCallId === picked) ??
|
||||
entries.find(({ card }) => card.kind === 'tourRoute' && card.routed) ??
|
||||
entries[0]
|
||||
);
|
||||
}
|
||||
|
||||
/** The letters the ways of one answer go by, in the order the answer gave them. */
|
||||
type RouteWayKey = 'a' | 'b' | 'c';
|
||||
const WAY_KEYS: readonly RouteWayKey[] = ['a', 'b', 'c'];
|
||||
@@ -101,7 +110,7 @@ function standsOnMap(part: ToolCallPart, receipt: AssistantApplied | undefined,
|
||||
/**
|
||||
* The cards of the latest answer that draws any, laid out as the chat lays
|
||||
* them out: a group of several is a choice of ways, each with its letter, the
|
||||
* chosen one (by `picks`, else the first) picked. Older answers drop, and so
|
||||
* chosen one (by `picks`, else the first calculated route) picked. Older answers drop, and so
|
||||
* do the ways of a group once one of them was taken into the trip.
|
||||
*/
|
||||
function lookRefs(
|
||||
@@ -111,7 +120,6 @@ function lookRefs(
|
||||
look: CardMapLook,
|
||||
layout: AnswerLayout
|
||||
): RouteRef[] {
|
||||
const chosenIds = new Set(Object.values(picks));
|
||||
const taken = takenProposals(messages);
|
||||
for (let index = messages.length - 1; index >= 0; index--) {
|
||||
const answers = (messages[index]?.parts ?? []).flatMap((part): RouteCardEntry[] =>
|
||||
@@ -125,7 +133,7 @@ function lookRefs(
|
||||
return layout(answers).flatMap((group) => {
|
||||
if (group.some((entry) => taken.has(entry.toolCallId))) return [];
|
||||
const ways = group.length >= 2;
|
||||
const chosen = group.find((entry) => chosenIds.has(entry.toolCallId)) ?? group[0];
|
||||
const chosen = preferredRouteEntry(group, picks[`tour:${group[0]?.toolCallId ?? ''}`]);
|
||||
return group.flatMap((entry, position): RouteRef[] => {
|
||||
if (!drawn.has(entry.toolCallId)) return [];
|
||||
const way = ways ? (WAY_KEYS[position] ?? null) : null;
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import {
|
||||
ASSISTANT_ERROR_CODES,
|
||||
type AiStatusResponse,
|
||||
type AssistantActivity,
|
||||
type AssistantApplied,
|
||||
type AssistantDecision,
|
||||
type AssistantErrorCode,
|
||||
@@ -9,10 +8,10 @@ import {
|
||||
type AssistantFoundPlace,
|
||||
type AssistantJourneySurface,
|
||||
type AssistantMapView,
|
||||
type AssistantMention,
|
||||
type AssistantMessage,
|
||||
type AssistantMessagePart,
|
||||
type AssistantPageRender,
|
||||
type AssistantPlanEdits,
|
||||
type AssistantThreadSummary,
|
||||
type UiStreamChunk,
|
||||
} from '@trek/shared';
|
||||
@@ -21,12 +20,12 @@ import { AssistantRequestError } from '../api/assistant';
|
||||
import { aiConnectionsRepo } from '../repo/aiConnectionsRepo';
|
||||
import { assistantRepo } from '../repo/assistantRepo';
|
||||
import { OnlineOnlyError } from '../repo/onlineOnly';
|
||||
import type { Assignment } from '../types';
|
||||
import { browserTimeZone } from '../utils/localDate';
|
||||
import { randomId } from '../utils/randomId';
|
||||
import type { RouteProfileFocus } from '../utils/routeGeometry';
|
||||
import { useAddonStore } from './addonStore';
|
||||
import { assistantScopeOf, assistantTargetOf, type AssistantChatKey } from './assistantChatKey';
|
||||
import type { AssistantCompare, AssistantMentionItem, AssistantTripChat } from './assistantChatState';
|
||||
import {
|
||||
blockDays,
|
||||
blockKeyOf,
|
||||
@@ -41,6 +40,8 @@ import { useAuthStore } from './authStore';
|
||||
import { useSettingsStore } from './settingsStore';
|
||||
import { useTripStore } from './tripStore';
|
||||
|
||||
export type { AssistantMentionItem } from './assistantChatState';
|
||||
|
||||
/**
|
||||
* The assistant: whether it can run, whether its window is open, and one
|
||||
* conversation per trip and one per journey (the chat in TREK Studio), each
|
||||
@@ -60,55 +61,6 @@ import { useTripStore } from './tripStore';
|
||||
* thread.
|
||||
*/
|
||||
|
||||
interface AssistantTripChat {
|
||||
/** The open thread; null for a new one the first message creates. */
|
||||
threadId: number | null;
|
||||
/** The user's latest threads in this trip; null until loaded. */
|
||||
threads: AssistantThreadSummary[] | null;
|
||||
messages: AssistantMessage[];
|
||||
isRunning: boolean;
|
||||
/** A thread is being loaded. */
|
||||
loading: boolean;
|
||||
error: AssistantErrorCode | null;
|
||||
/** What the next message is about: a place the user asked from, or the selected day. */
|
||||
focus: AssistantFocus | null;
|
||||
/** What is typed but not sent, kept while the phone screen hops to the map. */
|
||||
draft: string;
|
||||
/** The text of a message the server refused before answering, sent again by retry(). */
|
||||
unsent: string | null;
|
||||
/** Ends the running stream. */
|
||||
abort: AbortController | null;
|
||||
/** What the running step is doing (the place it searches near, the area); streamed only, never stored. */
|
||||
live: { activity: AssistantActivity | null };
|
||||
/** The applied changes taken back in this session, by call. */
|
||||
undone: Record<string, true>;
|
||||
/** "Before" and "after" of the last block of changes applied here; null when there is none to compare. */
|
||||
compare: AssistantCompare | null;
|
||||
/** The days, places and bookings named with @ in the draft. */
|
||||
mentions: AssistantMentionItem[];
|
||||
/** The way picked among the ways a block of cards offers, by block. */
|
||||
picks: Record<string, string>;
|
||||
}
|
||||
|
||||
/** A mention as the composer picked it, with the label it wrote into the text. */
|
||||
export type AssistantMentionItem = AssistantMention & { label: string };
|
||||
|
||||
/**
|
||||
* The plan of the days one applied block of changes touched, as it was just
|
||||
* before, so the map can show either side. Lives only in this session.
|
||||
*/
|
||||
interface AssistantCompare {
|
||||
/** The block it belongs to, `blockKeyOf` its calls. */
|
||||
blockKey: string;
|
||||
mode: 'before' | 'after';
|
||||
/** The affected days' stops before the block ran, by day. */
|
||||
snapshot: Record<number, Assignment[]>;
|
||||
/** The calls of the block that make a new place. */
|
||||
newPlaceCalls: string[];
|
||||
/** The places those calls made, hidden while "before" is on. */
|
||||
addedPlaceIds: number[];
|
||||
}
|
||||
|
||||
/** Where a hover on a change came from: its row in the card, its pin on the map, a found place in the strip. */
|
||||
type AssistantMapSource = 'card' | 'map' | 'strip';
|
||||
|
||||
@@ -199,6 +151,9 @@ interface AssistantState {
|
||||
/** Hands a booking file to a trip's chat, which proposes what it finds in it; does nothing under a journey key. */
|
||||
attach: (key: AssistantChatKey, file: File) => Promise<void>;
|
||||
decide: (key: AssistantChatKey, decisions: AssistantDecision[]) => Promise<void>;
|
||||
savePlanEdit: (key: AssistantChatKey, toolCallId: string, edits: AssistantPlanEdits) => void;
|
||||
previewPlanEdit: (key: AssistantChatKey, toolCallId: string, edits: AssistantPlanEdits | null) => void;
|
||||
choosePlanChanges: (key: AssistantChatKey, toolCallIds: readonly string[], include: boolean) => void;
|
||||
undo: (key: AssistantChatKey, toolCallId: string) => Promise<UndoOutcome>;
|
||||
cancel: (key: AssistantChatKey) => void;
|
||||
/** Sends the last question again: the refused message, or the one whose answer broke off. */
|
||||
@@ -311,6 +266,9 @@ const EMPTY_CHAT: AssistantTripChat = {
|
||||
compare: null,
|
||||
mentions: [],
|
||||
picks: {},
|
||||
planEdits: {},
|
||||
planEditPreview: null,
|
||||
changeChoices: {},
|
||||
};
|
||||
|
||||
/** What the map shows for the cards of a chat, cleared when the chat closes or changes. */
|
||||
@@ -659,9 +617,18 @@ function threadActions(ctx: Ctx) {
|
||||
};
|
||||
|
||||
const openThread = async (tripId: number, threadId: number) => {
|
||||
if (chat(ctx, tripId).isRunning) return;
|
||||
const current = chat(ctx, tripId);
|
||||
if (current.isRunning) return;
|
||||
ctx.set(NO_ROUTE);
|
||||
patch(ctx, tripId, { threadId, loading: true, error: null, unsent: null });
|
||||
patch(ctx, tripId, {
|
||||
threadId,
|
||||
loading: true,
|
||||
error: null,
|
||||
unsent: null,
|
||||
planEdits: current.threadId === threadId ? current.planEdits : {},
|
||||
planEditPreview: null,
|
||||
changeChoices: current.threadId === threadId ? current.changeChoices : {},
|
||||
});
|
||||
try {
|
||||
const { messages } = await assistantRepo.thread(assistantTargetOf(tripId), threadId);
|
||||
// Another thread may have been opened while this one loaded.
|
||||
@@ -695,6 +662,9 @@ function threadActions(ctx: Ctx) {
|
||||
abort: null,
|
||||
live: NO_LIVE,
|
||||
compare: null,
|
||||
planEdits: {},
|
||||
planEditPreview: null,
|
||||
changeChoices: {},
|
||||
});
|
||||
};
|
||||
|
||||
@@ -921,6 +891,17 @@ function turnActions(ctx: Ctx) {
|
||||
return {
|
||||
send: (tripId: number, text: string) => sendMessage(ctx, tripId, text),
|
||||
attach: (tripId: number, file: File) => attachFile(ctx, tripId, file),
|
||||
savePlanEdit: (tripId: number, toolCallId: string, edits: AssistantPlanEdits) =>
|
||||
patch(ctx, tripId, { planEdits: { ...chat(ctx, tripId).planEdits, [toolCallId]: edits } }),
|
||||
previewPlanEdit: (tripId: number, toolCallId: string, edits: AssistantPlanEdits | null) => {
|
||||
if (edits === null && chat(ctx, tripId).planEditPreview?.toolCallId !== toolCallId) return;
|
||||
patch(ctx, tripId, { planEditPreview: edits === null ? null : { toolCallId, edits } });
|
||||
},
|
||||
choosePlanChanges: (tripId: number, toolCallIds: readonly string[], include: boolean) => {
|
||||
const changeChoices = { ...chat(ctx, tripId).changeChoices };
|
||||
for (const id of toolCallIds) changeChoices[id] = include;
|
||||
patch(ctx, tripId, { changeChoices });
|
||||
},
|
||||
decide: async (tripId: number, decisions: AssistantDecision[]) => {
|
||||
const c = chat(ctx, tripId);
|
||||
const threadId = c.threadId;
|
||||
@@ -941,7 +922,20 @@ function turnActions(ctx: Ctx) {
|
||||
},
|
||||
});
|
||||
// Refused before anything ran: there is no "after" to compare with.
|
||||
if (chat(ctx, tripId).error) patch(ctx, tripId, { compare: null });
|
||||
const current = chat(ctx, tripId);
|
||||
if (current.threadId !== threadId) return;
|
||||
if (current.error) {
|
||||
patch(ctx, tripId, { compare: null });
|
||||
return;
|
||||
}
|
||||
if (current.messages === c.messages) return;
|
||||
const planEdits = { ...current.planEdits };
|
||||
const changeChoices = { ...current.changeChoices };
|
||||
for (const { toolCallId } of decisions) {
|
||||
delete planEdits[toolCallId];
|
||||
delete changeChoices[toolCallId];
|
||||
}
|
||||
patch(ctx, tripId, { planEdits, changeChoices });
|
||||
},
|
||||
undo: (tripId: number, toolCallId: string) => undoOne(ctx, tripId, toolCallId),
|
||||
cancel: (tripId: number) => chat(ctx, tripId).abort?.abort(),
|
||||
|
||||
Reference in New Issue
Block a user