feat(assistant): curated cards and undo for the changes of a journal itself

Starting a journal, changing its settings, linking or unlinking a trip,
bringing back its suggestions, the user's own view of it and deleting it
fell back to the generic card, which names ids and offers no way back.
They now share a journeyHeader card: the journal with its trips, the one
the change links or unlinks marked, what a new journal brings in and what
a deletion or an unlink takes, and each setting old to new in the
journal's own words. A new journal is deleted again while nothing was
written, added or laid out in it, changed settings are written back from
what the tool answered, a linked trip is unlinked by its owner while none
of its suggestions was written up, and the own switch flips back.
This commit is contained in:
Maurice
2026-10-24 21:36:20 +02:00
parent cf35dc7afd
commit 48ff1b3a98
39 changed files with 2044 additions and 11 deletions
@@ -7,16 +7,32 @@ import {
loadJournal,
type JournalLoaded,
} from './journey-change';
import {
JOURNAL_HEADER_DESCRIBERS,
journalHeaderApplied,
journalHeaderCard,
loadJournalHeader,
type JournalHeaderLoaded,
} from './journey-header';
import {
DELETE_CREATED_JOURNEY,
FLIP_JOURNEY_PREFERENCE,
RESTORE_JOURNEY_SETTINGS,
UNLINK_LINKED_TRIP,
} from './journey-header-undo';
import { readCard } from './journey-look';
import { DELETE_CREATED_ENTRY } from './journey-undo';
import type { JourneyEntriesCard } from '@trek/shared';
import type { AssistantChangeVerbKey, JourneyEntriesCard } from '@trek/shared';
/**
* The travel journal in the assistant chat. A read of a journal's entries
* shows them as a card beside the answer; a held write of an entry shows the
* entry it will write, change or delete, and once applied the entry as it
* was stored, its photo and country included. A created entry can be taken
* back while nothing was written to it since.
* back while nothing was written to it since. A change of a journal itself
* (a new one, its settings, its trips, its suggestions, the user's own view
* of it, its deletion) shows the journal with its trips (journey-header.ts),
* and most of them can be taken back (journey-header-undo.ts).
*/
/** The entry a create or a change answered with, else the one a delete named. */
@@ -46,6 +62,29 @@ function journalWrite(tool: string): ToolCards<JournalLoaded> {
};
}
/** The journal a change of the journal itself touched: the one its answer names, else the one it was called on. */
function journalIds(args: ToolArgs, result: unknown): number[] {
const id = idIn(result, 'journey') ?? argId(args, 'journeyId');
return id === null ? [] : [id];
}
/** A change of a journal itself: its verb, its words, its lookups, its card while held and once applied. */
function journalHeader(
tool: keyof typeof JOURNAL_HEADER_DESCRIBERS,
verbKey: AssistantChangeVerbKey,
undo?: NonNullable<ToolCards['undo']>,
): ToolCards<JournalHeaderLoaded> {
return {
write: { verbKey, entity: 'journey' },
describe: JOURNAL_HEADER_DESCRIBERS[tool],
load: (args, read) => loadJournalHeader(tool, args, read),
change: (_ctx, args, loaded) => journalHeaderCard(tool, args, loaded),
applied: ({ result, preview }) => journalHeaderApplied(tool, result, preview),
appliedIds: journalIds,
...(undo ? { undo } : {}),
};
}
export const JOURNEY_CARDS: DomainCards = {
id: 'journey',
tools: {
@@ -76,6 +115,17 @@ export const JOURNEY_CARDS: DomainCards = {
describe: JOURNEY_DESCRIBERS.delete_journey_entry,
...journalWrite('delete_journey_entry'),
},
create_journey: journalHeader('create_journey', 'createJournal', DELETE_CREATED_JOURNEY),
update_journey: journalHeader('update_journey', 'updateJournalSettings', RESTORE_JOURNEY_SETTINGS),
delete_journey: journalHeader('delete_journey', 'deleteJournal'),
add_journey_trip: journalHeader('add_journey_trip', 'linkJournalTrip', UNLINK_LINKED_TRIP),
remove_journey_trip: journalHeader('remove_journey_trip', 'unlinkJournalTrip'),
restore_journey_suggestions: journalHeader('restore_journey_suggestions', 'restoreJournalSuggestions'),
update_journey_preferences: journalHeader(
'update_journey_preferences',
'setJournalPreferences',
FLIP_JOURNEY_PREFERENCE,
),
},
prompt: [
'Journal: get_trip_journal finds the journal this trip shows. To show entries, call list_journey_entries with from/to for the days asked: the app draws them as cards, so do not list them again in your answer.',
@@ -0,0 +1,117 @@
import type { ToolArgs, ToolCards, UndoSnapshot } from '../card-types';
import { argId, idIn, readKey, recordOf, type Row } from '../card-values';
import { rowsOf } from '../undo-snapshot';
import { journeyArgs } from './journey-header';
/**
* The ways back from a change of a journal itself, each checked against the
* journal as `get_journey` reads it now:
* - a new journal is deleted while nothing was written, added or laid out in
* it since (its trips' suggestions are what it was made with);
* - changed settings are written back as they were, while the journal was not
* changed again since;
* - a linked trip is unlinked again, by its owner and while none of the
* trip's suggestions was written up since;
* - the user's own switch is flipped back while it still stands as set.
*/
type Undo = NonNullable<ToolCards['undo']>;
/** The settings `update_journey` takes no null for. */
const NEVER_NULL: ReadonlySet<string> = new Set(['title', 'status']);
function journeyRead(args: ToolArgs) {
return { tool: 'get_journey', args };
}
/** The journal a snapshot read, as `get_journey` answered. */
function journeyIn(snapshot: UndoSnapshot, args: ToolArgs): Row {
const read = journeyRead(args);
return recordOf(recordOf(snapshot.reads.get(readKey(read.tool, read.args))).journey);
}
/** The new journal by the id its answer names; the reads may not depend on it at boot, so they take it as given. */
function createdArgs(result: unknown): ToolArgs {
const journeyId = idIn(result, 'journey');
return journeyId === null ? {} : { journeyId };
}
export const DELETE_CREATED_JOURNEY: Undo = {
tool: 'delete_journey',
args: (_args, result) => {
const journeyId = idIn(result, 'journey');
return journeyId === null ? null : { journeyId };
},
reads: (_args, result) => [journeyRead(createdArgs(result)), { tool: 'get_book', args: createdArgs(result) }],
unchanged: (result, snapshot) => {
const created = recordOf(recordOf(result).journey);
const args = createdArgs(result);
if (args.journeyId === undefined) return false;
const current = journeyIn(snapshot, args);
const book = recordOf(snapshot.reads.get(readKey('get_book', args)));
return (
current.id === created.id &&
current.updated_at !== undefined &&
current.updated_at === created.updated_at &&
rowsOf(current.entries).every((entry) => entry.type === 'skeleton') &&
rowsOf(current.gallery).length === 0 &&
rowsOf(current.contributors).length <= 1 &&
book.exists === false
);
},
};
export const RESTORE_JOURNEY_SETTINGS: Undo = {
tool: 'update_journey',
args: (_args, result) => {
const journeyId = idIn(result, 'journey');
// The name and the status take no null; one stored empty has nothing to write back.
const previous = Object.fromEntries(
Object.entries(recordOf(recordOf(result).previous)).filter(
([key, value]) => value !== null || !NEVER_NULL.has(key),
),
);
return journeyId === null || Object.keys(previous).length === 0 ? null : { journeyId, ...previous };
},
reads: (_args, result) => [journeyRead(createdArgs(result))],
unchanged: (result, snapshot) => {
const changed = recordOf(recordOf(result).journey);
const current = journeyIn(snapshot, createdArgs(result));
return current.id === changed.id && current.updated_at !== undefined && current.updated_at === changed.updated_at;
},
};
export const UNLINK_LINKED_TRIP: Undo = {
tool: 'remove_journey_trip',
args: (args, result, preview) => {
const tripId = argId(args, 'tripId');
if (preview?.undoable === false || tripId === null || recordOf(result).success !== true) return null;
return { ...journeyArgs(args), tripId };
},
reads: (args) => [journeyRead(journeyArgs(args))],
unchanged: (_result, snapshot, call) => {
const tripId = argId(call?.args ?? {}, 'tripId');
if (tripId === null) return false;
const current = journeyIn(snapshot, journeyArgs(call?.args ?? {}));
const stillLinked = rowsOf(current.trips).some((trip) => trip.trip_id === tripId);
const written = rowsOf(current.entries).some(
(entry) => entry.source_trip_id === tripId && entry.type !== 'skeleton',
);
return stillLinked && !written;
},
};
export const FLIP_JOURNEY_PREFERENCE: Undo = {
tool: 'update_journey_preferences',
args: (args, result, preview) => {
if (preview?.undoable === false || !('hide_skeletons' in args) || !('hide_skeletons' in recordOf(result))) {
return null;
}
return { ...journeyArgs(args), hide_skeletons: !args.hide_skeletons };
},
reads: (args) => [journeyRead(journeyArgs(args))],
unchanged: (result, snapshot, call) => {
const current = journeyIn(snapshot, journeyArgs(call?.args ?? {}));
return 'hide_skeletons' in current && !!current.hide_skeletons === !!recordOf(result).hide_skeletons;
},
};
@@ -0,0 +1,327 @@
import type { CardReader, Described, PreviewContext, ToolArgs } from '../card-types';
import { argId, clipped, recordOf, type Row } from '../card-values';
import { Rows, text } from '../preview-format';
import { rowsOf } from '../undo-snapshot';
import {
JOURNEY_HEADER_LIMITS,
type AssistantChangePreview,
type AssistantChangeRow,
type AssistantChangeVerbKey,
type JourneyHeaderCard,
type JourneyHeaderTrip,
} from '@trek/shared';
/**
* The change cards of a journal itself: a new one, its settings changed, a
* trip linked or unlinked, its suggestions brought back, the user's own view
* of it, the whole journal deleted. The rows name what changes, old to new;
* the card under them is the journal with its trips and what the change takes
* along. Everything is read with the user's rights: the journal as
* `get_journey` answers it, the trips it could link as
* `list_journey_available_trips` does.
*/
/** What a held journal change looked up before its card is drawn. */
export interface JournalHeaderLoaded {
/** The journal as `get_journey` answers it; null for a new one or a read that failed. */
journey: Row | null;
/** The user's trips a journal could link. */
available: Row[];
}
/** The tools these cards are for. */
export const JOURNAL_HEADER_TOOLS = [
'create_journey',
'update_journey',
'delete_journey',
'add_journey_trip',
'remove_journey_trip',
'restore_journey_suggestions',
'update_journey_preferences',
] as const;
type HeaderTool = (typeof JOURNAL_HEADER_TOOLS)[number];
/** The journal a call names, or none in a journey's own conversation, where the session pins it. */
export function journeyArgs(args: ToolArgs): ToolArgs {
const journeyId = argId(args, 'journeyId');
return journeyId === null ? {} : { journeyId };
}
/** At most two reads: the journal (all but a new one), the user's trips (a new journal, a trip linked). */
export async function loadJournalHeader(tool: string, args: ToolArgs, read: CardReader): Promise<JournalHeaderLoaded> {
const withTrips = tool === 'create_journey' || tool === 'add_journey_trip';
const available = withTrips ? rowsOf(recordOf(await read('list_journey_available_trips')).trips) : [];
const found = tool === 'create_journey' ? null : recordOf(await read('get_journey', journeyArgs(args))).journey;
return { journey: found ? recordOf(found) : null, available };
}
/** The settings an update can change beyond the name and subtitle, each a `field` row under the tool's own name. */
const SETTING_FIELDS = [
'status',
'status_override',
'show_verdict',
'show_mood',
'show_weather',
'photo_location',
'show_trip_tracks',
'auto_prepare_recordings',
'cover_gradient',
] as const;
const FLAG_FIELDS: ReadonlySet<string> = new Set([
'show_verdict',
'show_mood',
'show_weather',
'photo_location',
'show_trip_tracks',
'auto_prepare_recordings',
'hide_skeletons',
]);
const STATUS_FIELDS: ReadonlySet<string> = new Set(['status', 'status_override']);
/** A setting as its row writes it: a flag (stored 0 or 1, sent as a boolean) as ✓ or ✗, anything else as it is. */
function settingText(field: string, value: unknown): string {
return FLAG_FIELDS.has(field) ? text(value === true || value === 1) : text(value);
}
function fieldRow(field: string, before: string | null, after: string): AssistantChangeRow {
return { op: before === null ? 'add' : 'change', labelKey: 'field', field, before, after };
}
function described(subject: string, rows: Rows, extra: Partial<Described> = {}): Described {
return { subject, rows, dayId: null, placeIds: [], domain: 'journey', ...extra };
}
/** Which verb an update reads as: a new name alone, a new status alone, else the settings. */
function updateVerb(args: ToolArgs): AssistantChangeVerbKey {
const keys = Object.keys(args).filter((key) => key !== 'journeyId');
if (keys.length > 0 && keys.every((key) => key === 'title')) return 'renameJournal';
if (keys.length > 0 && keys.every((key) => STATUS_FIELDS.has(key))) return 'setJournalStatus';
return 'updateJournalSettings';
}
/** The trip a call names, by the user's trips or the journal's own. */
function tripNamed(loaded: JournalHeaderLoaded | null, tripId: number | null): Row | null {
if (tripId === null) return null;
const own = rowsOf(loaded?.journey?.trips).find((trip) => trip.trip_id === tripId);
if (own) return { id: own.trip_id, title: own.title, start_date: own.start_date, end_date: own.end_date };
return loaded?.available.find((trip) => trip.id === tripId) ?? null;
}
function linked(loaded: JournalHeaderLoaded | null, tripId: number | null): boolean {
return tripId !== null && rowsOf(loaded?.journey?.trips).some((trip) => trip.trip_id === tripId);
}
function updateRows(before: Row, args: ToolArgs): Rows {
const rows = new Rows();
if ('title' in args && text(args.title) !== text(before.title))
rows.change('name', text(before.title), text(args.title));
if ('subtitle' in args && text(args.subtitle) !== text(before.subtitle)) {
rows.change('description', text(before.subtitle), text(args.subtitle));
}
for (const field of SETTING_FIELDS) {
if (!(field in args)) continue;
const was = field in before ? settingText(field, before[field]) : null;
const now = settingText(field, args[field]);
if (was !== now) rows.rows.push(fieldRow(field, was, now));
}
return rows;
}
const TRIP_ROW = (verb: 'add' | 'remove', name: string): AssistantChangeRow =>
verb === 'add'
? { op: 'add', labelKey: 'field', field: 'trip', before: null, after: name }
: { op: 'change', labelKey: 'field', field: 'trip', before: name, after: '' };
export const JOURNAL_HEADER_DESCRIBERS: Readonly<
Record<HeaderTool, (ctx: PreviewContext, args: ToolArgs, loaded: JournalHeaderLoaded | null) => Described>
> = {
create_journey: (_ctx, args) =>
described(text(args.title), new Rows().add('name', text(args.title)).add('description', text(args.subtitle))),
update_journey: (_ctx, args, loaded) => {
const before = loaded?.journey ?? {};
return described(text(before.title) || text(args.title), updateRows(before, args), { verbKey: updateVerb(args) });
},
delete_journey: (_ctx, _args, loaded) => described(text(loaded?.journey?.title), new Rows()),
add_journey_trip: (_ctx, args, loaded) => {
const tripId = argId(args, 'tripId');
const rows = new Rows();
rows.rows.push(TRIP_ROW('add', text(tripNamed(loaded, tripId)?.title)));
// Unlinking takes the owner; a trip linked already would be unlinked by a way back that never linked it.
const owner = loaded?.journey?.my_role === 'owner';
return described(text(loaded?.journey?.title), rows, { undoable: owner && !linked(loaded, tripId) });
},
remove_journey_trip: (_ctx, args, loaded) => {
const rows = new Rows();
rows.rows.push(TRIP_ROW('remove', text(tripNamed(loaded, argId(args, 'tripId'))?.title)));
return described(text(loaded?.journey?.title), rows);
},
restore_journey_suggestions: (_ctx, _args, loaded) => {
const rows = new Rows();
const dismissed = Number(loaded?.journey?.dismissed_count);
if (Number.isInteger(dismissed) && dismissed > 0) rows.rows.push(fieldRow('suggestions', null, String(dismissed)));
return described(text(loaded?.journey?.title), rows);
},
update_journey_preferences: (_ctx, args, loaded) => {
const rows = new Rows();
const known = loaded?.journey && 'hide_skeletons' in loaded.journey;
const was = known ? settingText('hide_skeletons', loaded?.journey?.hide_skeletons) : null;
const now = 'hide_skeletons' in args ? settingText('hide_skeletons', args.hide_skeletons) : null;
if (now !== null && now !== was) rows.rows.push(fieldRow('hide_skeletons', was, now));
// A way back that flips the switch is a way back only where the switch was known to change.
return described(text(loaded?.journey?.title), rows, { undoable: was !== null && now !== null && was !== now });
},
};
const DATE = /^\d{4}-\d{2}-\d{2}$/;
function dateOf(value: unknown): string | null {
return typeof value === 'string' && DATE.test(value.slice(0, 10)) ? value.slice(0, 10) : null;
}
function tripLook(row: Row, change: JourneyHeaderTrip['change'], idKey: 'id' | 'trip_id'): JourneyHeaderTrip | null {
const title = clipped(row.title, JOURNEY_HEADER_LIMITS.tripTitle);
if (!title) return null;
const id = argId(row, idKey);
return { id, title, startDate: dateOf(row.start_date), endDate: dateOf(row.end_date), change };
}
function count(value: unknown): number | null {
const n = Number(value);
return Number.isInteger(n) && n >= 0 ? Math.min(n, 1_000_000) : null;
}
/** The journal's own trips, with what the change does to the one it names; that one first, so a cut keeps it. */
function journalTrips(tool: string, args: ToolArgs, loaded: JournalHeaderLoaded): JourneyHeaderTrip[] {
const tripId = argId(args, 'tripId');
const own = rowsOf(loaded.journey?.trips).flatMap((row) => {
const change = tool === 'remove_journey_trip' && row.trip_id === tripId ? 'unlink' : 'kept';
const look = tripLook(row, change, 'trip_id');
return look ? [look] : [];
});
const changedFirst = [
...own.filter((trip) => trip.change !== 'kept'),
...own.filter((trip) => trip.change === 'kept'),
];
if (tool !== 'add_journey_trip' || linked(loaded, tripId)) return changedFirst;
const added = loaded.available.find((row) => row.id === tripId);
const look = added ? tripLook(added, 'link', 'id') : null;
return look ? [look, ...changedFirst] : changedFirst;
}
/** The trips a new journal links, by the user's trips; an id the user's trips do not list is left out. */
function newTrips(args: ToolArgs, loaded: JournalHeaderLoaded): JourneyHeaderTrip[] {
const ids = Array.isArray(args.trip_ids) ? args.trip_ids : [];
return ids.flatMap((id) => {
const row = loaded.available.find((trip) => trip.id === id);
const look = row ? tripLook(row, 'link', 'id') : null;
return look ? [look] : [];
});
}
/** The places of the trips linked by the change, which come in as suggestions. */
function suggestionsOf(trips: readonly JourneyHeaderTrip[], loaded: JournalHeaderLoaded): number | null {
const linking = trips.filter((trip) => trip.change === 'link' && trip.id !== null);
if (linking.length === 0) return null;
const places = linking.map((trip) => count(loaded.available.find((row) => row.id === trip.id)?.place_count) ?? 0);
return places.reduce((sum, n) => sum + n, 0);
}
/** What the journal holds that the change concerns: all of it, or what one unlinked trip leaves behind. */
function heldBy(tool: string, args: ToolArgs, journey: Row): { entries: number | null; photos: number | null } {
const entries = rowsOf(journey.entries).filter((entry) => !entry.dismissed);
if (tool === 'remove_journey_trip') {
const tripId = argId(args, 'tripId');
return {
entries: entries.filter((e) => e.source_trip_id === tripId && e.type !== 'skeleton').length,
photos: null,
};
}
const written = entries.filter((entry) => entry.type !== 'skeleton').length;
return { entries: written, photos: Array.isArray(journey.gallery) ? journey.gallery.length : null };
}
/** The suggestions an unlinked trip takes with it: its places nobody wrote up. */
function unlinkedSuggestions(args: ToolArgs, journey: Row): number {
const tripId = argId(args, 'tripId');
return rowsOf(journey.entries).filter((e) => e.source_trip_id === tripId && e.type === 'skeleton').length;
}
/** The card under a held journal change; null when it has no journal to name. */
export function journalHeaderCard(
tool: string,
args: ToolArgs,
loaded: JournalHeaderLoaded | null,
): JourneyHeaderCard | null {
if (!loaded) return null;
if (tool === 'create_journey') {
const title = clipped(args.title, JOURNEY_HEADER_LIMITS.title);
if (!title) return null;
const trips = newTrips(args, loaded).slice(0, JOURNEY_HEADER_LIMITS.trips);
const subtitle = clipped(args.subtitle, JOURNEY_HEADER_LIMITS.subtitle);
const suggestions = suggestionsOf(trips, loaded);
return {
kind: 'journeyHeader',
journeyId: null,
title,
subtitle,
change: 'new',
trips,
entries: null,
photos: null,
suggestions,
};
}
const journey = loaded.journey;
const title = clipped(journey?.title, JOURNEY_HEADER_LIMITS.title);
if (!journey || !title) return null;
const trips = journalTrips(tool, args, loaded).slice(0, JOURNEY_HEADER_LIMITS.trips);
const held = heldBy(tool, args, journey);
const suggestions =
tool === 'remove_journey_trip' ? unlinkedSuggestions(args, journey) : suggestionsOf(trips, loaded);
return {
kind: 'journeyHeader',
journeyId: argId(journey, 'id'),
title,
subtitle: clipped(journey.subtitle, JOURNEY_HEADER_LIMITS.subtitle),
change: tool === 'delete_journey' ? 'willDelete' : 'changed',
trips,
entries: tool === 'add_journey_trip' ? null : held.entries,
photos: tool === 'delete_journey' ? held.photos : null,
suggestions,
};
}
/**
* The card of an applied journal change: a new journal as the tool answered
* it (its id, its trips), a changed one with its new name and subtitle over
* the card it was held with. Every other change keeps its held card.
*/
export function journalHeaderApplied(
tool: string,
result: unknown,
preview: AssistantChangePreview | null,
): JourneyHeaderCard | null {
const journey = recordOf(recordOf(result).journey);
const held = preview?.card?.kind === 'journeyHeader' ? preview.card : null;
const title = clipped(journey.title, JOURNEY_HEADER_LIMITS.title);
if (!title) return null;
const subtitle = clipped(journey.subtitle, JOURNEY_HEADER_LIMITS.subtitle);
if (tool === 'update_journey') return held ? { ...held, journeyId: argId(journey, 'id'), title, subtitle } : null;
if (tool !== 'create_journey') return null;
const trips = rowsOf(journey.trips).flatMap((row) => {
const look = tripLook(row, 'link', 'trip_id');
return look ? [look] : [];
});
const suggestions = rowsOf(journey.entries).filter((entry) => entry.type === 'skeleton').length;
return {
kind: 'journeyHeader',
journeyId: argId(journey, 'id'),
title,
subtitle,
change: 'new',
trips: trips.slice(0, JOURNEY_HEADER_LIMITS.trips),
entries: null,
photos: null,
suggestions,
};
}
@@ -0,0 +1,350 @@
/**
* ASTCARD-JHD-001 to ASTCARD-JHD-012
*
* A change of a journal itself in the assistant chat: what a held change
* reads first, the words of its row (the verb an update reads as, each
* setting old to new), the journal card under it with its trips and what the
* change brings or takes, the receipt, and the ways back with their checks.
* Every card is checked against the shared union through the registry's guard.
*/
import { buildTripCard } from '../../../../../../src/nest/assistant/assistant-context';
import type { CardReader, PreviewContext, UndoSnapshot } from '../../../../../../src/nest/assistant/cards/card-types';
import { readKey } from '../../../../../../src/nest/assistant/cards/card-values';
import { JOURNEY_CARDS } from '../../../../../../src/nest/assistant/cards/journey';
import {
loadJournalHeader,
type JournalHeaderLoaded,
} from '../../../../../../src/nest/assistant/cards/journey/journey-header';
import {
appliedCardOf,
ASSISTANT_UNDO_MAP,
ASSISTANT_WRITE_TOOLS,
changeCardOf,
undoReadsOf,
} from '../../../../../../src/nest/assistant/cards/registry';
import { appliedChange, describeToolCall } from '../../../../../../src/nest/assistant/tool-call-preview.helpers';
import { journeyHeaderCardSchema, type AssistantChangePreview, type JourneyHeaderCard } from '@trek/shared';
import { describe, expect, it, vi } from 'vitest';
vi.mock('../../../../../../src/nest/audit/audit-log.logger', () => ({
logInfo: vi.fn(),
logError: vi.fn(),
logWarn: vi.fn(),
logDebug: vi.fn(),
}));
const ctx: PreviewContext = {
card: buildTripCard(1, 7, { trip: { title: 'Berlin' } }, null, null),
categories: new Map(),
locale: 'en',
today: '2026-10-24',
airport: () => null,
};
const AVAILABLE = [
{ id: 5, title: 'Tokyo days', start_date: '2026-11-02', end_date: '2026-11-08', place_count: 9 },
{ id: 6, title: 'Kyoto days', start_date: '2026-11-09', end_date: '2026-11-12', place_count: 4 },
];
function journey(over: Record<string, unknown> = {}): Record<string, unknown> {
return {
id: 12,
title: 'Japan 2026',
subtitle: null,
status: 'active',
status_override: null,
show_mood: 1,
show_verdict: 0,
hide_skeletons: 0,
my_role: 'owner',
updated_at: 100,
dismissed_count: 3,
trips: [{ trip_id: 5, title: 'Tokyo days', start_date: '2026-11-02', end_date: '2026-11-08' }],
entries: [
{ id: 1, type: 'entry', source_trip_id: 5, dismissed: false },
{ id: 2, type: 'skeleton', source_trip_id: 5, dismissed: false },
{ id: 3, type: 'skeleton', source_trip_id: 5, dismissed: false },
],
gallery: [{ id: 1 }, { id: 2 }],
contributors: [{ user_id: 7 }],
...over,
};
}
function readerOf(answers: Record<string, unknown>): { read: CardReader; asked: string[] } {
const asked: string[] = [];
const read: CardReader = (tool, args = {}) => {
asked.push(readKey(tool, args));
return Promise.resolve(answers[readKey(tool, args)] ?? answers[tool] ?? null);
};
return { read, asked };
}
const loadedWith = (over: Record<string, unknown> = {}): JournalHeaderLoaded => ({
journey: journey(over),
available: AVAILABLE,
});
function cardOf(value: unknown): JourneyHeaderCard {
return journeyHeaderCardSchema.parse(value);
}
describe('the lookups of a journal change', () => {
it('ASTCARD-JHD-001: a new journal reads the trips it could link, a change the journal it is on', async () => {
const created = readerOf({ list_journey_available_trips: { trips: AVAILABLE } });
expect(await loadJournalHeader('create_journey', { title: 'Japan' }, created.read)).toEqual({
journey: null,
available: AVAILABLE,
});
expect(created.asked).toEqual([readKey('list_journey_available_trips')]);
const named = readerOf({ get_journey: { journey: journey() } });
const loaded = await loadJournalHeader('update_journey', { journeyId: 12, title: 'X' }, named.read);
expect(loaded.journey).toMatchObject({ id: 12 });
expect(named.asked).toEqual([readKey('get_journey', { journeyId: 12 })]);
// A journey's own conversation pins the journal, so the read names none.
const pinned = readerOf({});
expect(await loadJournalHeader('delete_journey', {}, pinned.read)).toEqual({ journey: null, available: [] });
expect(pinned.asked).toEqual([readKey('get_journey', {})]);
const linking = readerOf({});
await loadJournalHeader('add_journey_trip', { journeyId: 12, tripId: 6 }, linking.read);
expect(linking.asked).toHaveLength(2);
});
});
describe('the words of a journal change', () => {
it('ASTCARD-JHD-002: an update reads as a rename, a status change or a change of settings', () => {
const loaded = loadedWith();
const rename = describeToolCall('update_journey', 'c1', { journeyId: 12, title: 'Nippon' }, ctx, loaded);
expect(rename).toMatchObject({ verbKey: 'renameJournal', subject: 'Japan 2026', undoable: true });
expect(rename.rows).toEqual([{ op: 'change', labelKey: 'name', before: 'Japan 2026', after: 'Nippon' }]);
const status = describeToolCall('update_journey', 'c2', { status_override: 'live' }, ctx, loaded);
expect(status.verbKey).toBe('setJournalStatus');
expect(status.rows).toEqual([
{ op: 'change', labelKey: 'field', field: 'status_override', before: '', after: 'live' },
]);
const settings = describeToolCall(
'update_journey',
'c3',
{ show_mood: false, show_verdict: false, subtitle: 'Autumn', show_trip_tracks: true },
ctx,
loaded,
);
expect(settings.verbKey).toBe('updateJournalSettings');
// A setting set to what it holds gets no row; one the journal does not name has no before.
expect(settings.rows).toEqual([
{ op: 'change', labelKey: 'description', before: null, after: 'Autumn' },
{ op: 'change', labelKey: 'field', field: 'show_mood', before: '✓', after: '✗' },
{ op: 'add', labelKey: 'field', field: 'show_trip_tracks', before: null, after: '✓' },
]);
});
it('ASTCARD-JHD-003: a trip linked names it, and is undoable only for the owner and a trip not linked yet', () => {
const add = describeToolCall('add_journey_trip', 'c1', { journeyId: 12, tripId: 6 }, ctx, loadedWith());
expect(add).toMatchObject({ verbKey: 'linkJournalTrip', subject: 'Japan 2026', undoable: true });
expect(add.rows).toEqual([{ op: 'add', labelKey: 'field', field: 'trip', before: null, after: 'Kyoto days' }]);
const again = describeToolCall('add_journey_trip', 'c2', { journeyId: 12, tripId: 5 }, ctx, loadedWith());
expect(again.undoable).toBe(false);
const editor = describeToolCall('add_journey_trip', 'c3', { tripId: 6 }, ctx, loadedWith({ my_role: 'editor' }));
expect(editor.undoable).toBe(false);
});
it('ASTCARD-JHD-004: the other changes name the journal, and a deletion or an unlink has no way back', () => {
const loaded = loadedWith();
expect(describeToolCall('delete_journey', 'c1', { journeyId: 12 }, ctx, loaded)).toMatchObject({
verbKey: 'deleteJournal',
subject: 'Japan 2026',
undoable: false,
});
const unlink = describeToolCall('remove_journey_trip', 'c2', { tripId: 5 }, ctx, loaded);
expect(unlink).toMatchObject({ verbKey: 'unlinkJournalTrip', undoable: false });
expect(unlink.rows).toEqual([{ op: 'change', labelKey: 'field', field: 'trip', before: 'Tokyo days', after: '' }]);
const restore = describeToolCall('restore_journey_suggestions', 'c3', {}, ctx, loaded);
expect(restore).toMatchObject({ verbKey: 'restoreJournalSuggestions', undoable: false });
expect(restore.rows).toEqual([{ op: 'add', labelKey: 'field', field: 'suggestions', before: null, after: '3' }]);
const prefs = describeToolCall('update_journey_preferences', 'c4', { hide_skeletons: true }, ctx, loaded);
expect(prefs).toMatchObject({ verbKey: 'setJournalPreferences', undoable: true });
expect(prefs.rows).toEqual([{ op: 'change', labelKey: 'field', field: 'hide_skeletons', before: '✗', after: '✓' }]);
// Set to what it holds, the switch has no way back that would mean anything.
expect(describeToolCall('update_journey_preferences', 'c5', { hide_skeletons: false }, ctx, loaded).undoable).toBe(
false,
);
expect(describeToolCall('create_journey', 'c6', { title: 'Japan' }, ctx, null)).toMatchObject({
verbKey: 'createJournal',
subject: 'Japan',
undoable: true,
});
});
});
describe('the journal card under a change', () => {
it('ASTCARD-JHD-005: a new journal shows the trips it links and the places that come in as suggestions', () => {
const loaded: JournalHeaderLoaded = { journey: null, available: AVAILABLE };
const card = cardOf(
changeCardOf('create_journey', ctx, { title: 'Japan 2026', subtitle: 'Autumn', trip_ids: [5, 6, 99] }, loaded),
);
expect(card).toMatchObject({ journeyId: null, title: 'Japan 2026', subtitle: 'Autumn', change: 'new' });
expect(card.trips.map((trip) => [trip.id, trip.change])).toEqual([
[5, 'link'],
[6, 'link'],
]);
expect(card.suggestions).toBe(13);
expect(changeCardOf('create_journey', ctx, {}, loaded)).toBeNull();
});
it('ASTCARD-JHD-006: a deletion counts what goes, an unlink what stays and what goes, a link comes first', () => {
const loaded = loadedWith();
const deleting = cardOf(changeCardOf('delete_journey', ctx, {}, loaded));
expect(deleting).toMatchObject({ change: 'willDelete', journeyId: 12, entries: 1, photos: 2 });
const unlinking = cardOf(changeCardOf('remove_journey_trip', ctx, { tripId: 5 }, loaded));
expect(unlinking).toMatchObject({ change: 'changed', entries: 1, suggestions: 2, photos: null });
expect(unlinking.trips).toEqual([
{ id: 5, title: 'Tokyo days', startDate: '2026-11-02', endDate: '2026-11-08', change: 'unlink' },
]);
const linking = cardOf(changeCardOf('add_journey_trip', ctx, { tripId: 6 }, loaded));
expect(linking.trips.map((trip) => [trip.id, trip.change])).toEqual([
[6, 'link'],
[5, 'kept'],
]);
expect(linking).toMatchObject({ suggestions: 4, entries: null });
expect(changeCardOf('update_journey', ctx, { title: 'X' }, { journey: null, available: [] })).toBeNull();
});
it('ASTCARD-JHD-007: the receipt of a new journal names it with its id, a change takes its new name', () => {
const result = { journey: journey({ entries: [{ type: 'skeleton' }, { type: 'skeleton' }] }) };
const created = cardOf(appliedCardOf('create_journey', { args: {}, result, preview: null }));
expect(created).toMatchObject({ journeyId: 12, change: 'new', suggestions: 2 });
expect(created.trips[0]).toMatchObject({ id: 5, change: 'link' });
const held = changeCardOf('update_journey', ctx, { title: 'Nippon' }, loadedWith());
const preview = { card: held } as unknown as AssistantChangePreview;
const renamed = { journey: journey({ title: 'Nippon' }), previous: { title: 'Japan 2026' } };
expect(appliedCardOf('update_journey', { args: {}, result: renamed, preview })).toMatchObject({
title: 'Nippon',
journeyId: 12,
});
expect(appliedCardOf('delete_journey', { args: {}, result: { success: true }, preview })).toBeNull();
expect(appliedChange('create_journey', 'c1', {}, result, null, null)).toMatchObject({
entity: 'journey',
ids: [12],
});
expect(appliedChange('delete_journey', 'c2', { journeyId: 12 }, { success: true }, null, null)?.ids).toEqual([12]);
});
});
function snapshotOf(entries: Array<[string, Record<string, unknown>, unknown]>): UndoSnapshot {
return {
summary: null,
places: null,
reads: new Map(entries.map(([tool, args, value]) => [readKey(tool, args), value])),
};
}
function undoOf(tool: string) {
const undo = JOURNEY_CARDS.tools[tool]?.undo;
if (!undo) throw new Error(`no undo for ${tool}`);
return undo;
}
describe('the ways back from a journal change', () => {
it('ASTCARD-JHD-008: a new journal is deleted while nothing was written, added or laid out in it', () => {
const undo = undoOf('create_journey');
const created = journey({ entries: [{ type: 'skeleton' }], gallery: [] });
const result = { journey: created };
expect(ASSISTANT_UNDO_MAP.create_journey?.tool).toBe('delete_journey');
expect(undo.args({}, result, null)).toEqual({ journeyId: 12 });
expect(undo.args({}, {}, null)).toBeNull();
expect(undoReadsOf('create_journey', {}, result)).toEqual([
{ tool: 'get_journey', args: { journeyId: 12 } },
{ tool: 'get_book', args: { journeyId: 12 } },
]);
const check = (current: Record<string, unknown>, book: unknown = { exists: false }) =>
undo.unchanged(
result,
snapshotOf([
['get_journey', { journeyId: 12 }, { journey: current }],
['get_book', { journeyId: 12 }, book],
]),
);
expect(check(created)).toBe(true);
expect(check({ ...created, updated_at: 101 })).toBe(false);
expect(check({ ...created, entries: [{ type: 'entry' }] })).toBe(false);
expect(check({ ...created, gallery: [{ id: 1 }] })).toBe(false);
expect(check({ ...created, contributors: [{ user_id: 7 }, { user_id: 8 }] })).toBe(false);
expect(check(created, { exists: true })).toBe(false);
expect(check(created, null)).toBe(false);
});
it('ASTCARD-JHD-009: changed settings are written back as they were, while the journal was not changed since', () => {
const undo = undoOf('update_journey');
const result = { journey: journey({ title: 'Nippon' }), previous: { title: 'Japan 2026', show_mood: true } };
expect(undo.args({ title: 'Nippon' }, result, null)).toEqual({
journeyId: 12,
title: 'Japan 2026',
show_mood: true,
});
expect(undo.args({}, { journey: journey(), previous: {} }, null)).toBeNull();
// A name or a status stored empty has nothing the tool could take back.
expect(undo.args({}, { journey: journey(), previous: { title: null, subtitle: null } }, null)).toEqual({
journeyId: 12,
subtitle: null,
});
const at = (updated: number) =>
undo.unchanged(
result,
snapshotOf([['get_journey', { journeyId: 12 }, { journey: journey({ updated_at: updated }) }]]),
);
expect(at(100)).toBe(true);
expect(at(150)).toBe(false);
});
it('ASTCARD-JHD-010: a linked trip is unlinked by its owner while none of its suggestions was written up', () => {
const undo = undoOf('add_journey_trip');
const args = { journeyId: 12, tripId: 6 };
expect(undo.args(args, { success: true }, null)).toEqual({ journeyId: 12, tripId: 6 });
expect(undo.args({ tripId: 6 }, { success: true }, null)).toEqual({ tripId: 6 });
expect(undo.args(args, { success: false }, null)).toBeNull();
const notOwner = { undoable: false } as unknown as AssistantChangePreview;
expect(undo.args(args, { success: true }, notOwner)).toBeNull();
const linked = { trips: [{ trip_id: 6 }], entries: [{ type: 'skeleton', source_trip_id: 6 }] };
const check = (current: Record<string, unknown>) =>
undo.unchanged({ success: true }, snapshotOf([['get_journey', { journeyId: 12 }, { journey: current }]]), {
args,
preview: null,
});
expect(check(linked)).toBe(true);
expect(check({ ...linked, entries: [{ type: 'entry', source_trip_id: 6 }] })).toBe(false);
expect(check({ ...linked, trips: [] })).toBe(false);
expect(undo.unchanged({ success: true }, snapshotOf([]), { args: {}, preview: null })).toBe(false);
});
it('ASTCARD-JHD-011: the own switch flips back while it still stands as set', () => {
const undo = undoOf('update_journey_preferences');
const args = { journeyId: 12, hide_skeletons: true };
expect(undo.args(args, { hide_skeletons: 1 }, null)).toEqual({ journeyId: 12, hide_skeletons: false });
expect(undo.args({ journeyId: 12 }, { hide_skeletons: 1 }, null)).toBeNull();
const same = { undoable: false } as unknown as AssistantChangePreview;
expect(undo.args(args, { hide_skeletons: 1 }, same)).toBeNull();
const check = (stored: unknown) =>
undo.unchanged(
{ hide_skeletons: 1 },
snapshotOf([['get_journey', { journeyId: 12 }, { journey: { hide_skeletons: stored } }]]),
{ args, preview: null },
);
expect(check(1)).toBe(true);
expect(check(0)).toBe(false);
});
it('ASTCARD-JHD-012: the journal changes bring their verbs, the journal as entity, and no way back for a deletion', () => {
expect(ASSISTANT_WRITE_TOOLS.create_journey).toEqual({ verbKey: 'createJournal', entity: 'journey' });
expect(ASSISTANT_WRITE_TOOLS.update_journey?.verbKey).toBe('updateJournalSettings');
expect(ASSISTANT_WRITE_TOOLS.delete_journey?.verbKey).toBe('deleteJournal');
expect(ASSISTANT_WRITE_TOOLS.add_journey_trip?.verbKey).toBe('linkJournalTrip');
expect(ASSISTANT_WRITE_TOOLS.remove_journey_trip?.verbKey).toBe('unlinkJournalTrip');
expect(ASSISTANT_WRITE_TOOLS.restore_journey_suggestions?.verbKey).toBe('restoreJournalSuggestions');
expect(ASSISTANT_WRITE_TOOLS.update_journey_preferences?.verbKey).toBe('setJournalPreferences');
for (const tool of ['delete_journey', 'remove_journey_trip', 'restore_journey_suggestions']) {
expect(ASSISTANT_UNDO_MAP[tool], tool).toBeUndefined();
}
});
});