mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-30 08:30:05 +00:00
feat(assistant): a card framework every addon package plugs into
This commit is contained in:
@@ -1,12 +1,13 @@
|
||||
/**
|
||||
* FE-AI-MSG-CARDS-001 to 002
|
||||
* FE-AI-MSG-CARDS-001 to 005
|
||||
*
|
||||
* The places and the weather a step found are stored parts of the answer,
|
||||
* like a change card: they land in the message being written, and a chunk
|
||||
* sent again for the same search step replaces its part instead of adding a
|
||||
* second strip.
|
||||
* second strip. A tool's card lands the same way, except an applied write's,
|
||||
* which joins the change that proposed it.
|
||||
*/
|
||||
import type { AssistantMessage, AssistantPlaces } from '@trek/shared';
|
||||
import type { AssistantMessage, AssistantPlaces, TrekCard } from '@trek/shared';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { applyChunk } from './assistantMessages';
|
||||
|
||||
@@ -69,4 +70,45 @@ describe('assistantMessages: cards in an answer', () => {
|
||||
);
|
||||
expect(messages[0]?.parts.map((p) => p.type)).toEqual(['data-trek-weather']);
|
||||
});
|
||||
|
||||
const ROUTE: TrekCard = { kind: 'tourRoute' };
|
||||
const LIST: TrekCard = { kind: 'tourList' };
|
||||
const cardsOf = (message: AssistantMessage | undefined) =>
|
||||
message?.parts.flatMap((p) => (p.type === 'data-trek-card' ? [p.data] : [])) ?? [];
|
||||
|
||||
it('FE-AI-MSG-CARDS-003: a read card lands in the answer, replaced when sent again; a null card is skipped', () => {
|
||||
let messages = started();
|
||||
messages = applyChunk(messages, { type: 'data-trek-card', data: { toolCallId: 'r1', card: ROUTE } }, NOW);
|
||||
messages = applyChunk(messages, { type: 'data-trek-card', data: { toolCallId: 'r1', card: LIST } }, NOW);
|
||||
messages = applyChunk(messages, { type: 'data-trek-card', data: { toolCallId: 'r2', card: null } }, NOW);
|
||||
expect(cardsOf(messages[0])).toEqual([{ toolCallId: 'r1', card: LIST }]);
|
||||
});
|
||||
|
||||
it('FE-AI-MSG-CARDS-004: in the decisions stream an applied card joins the message that proposed the change', () => {
|
||||
const proposing: AssistantMessage = {
|
||||
id: 'msg-1',
|
||||
role: 'assistant',
|
||||
status: 'awaiting_approval',
|
||||
createdAt: NOW(),
|
||||
parts: [{ type: 'tool-call', toolCallId: 'w1', toolName: 'create_hike', args: {}, approval: { id: 'w1' } }],
|
||||
};
|
||||
let messages = applyChunk([proposing], { type: 'start', messageId: 'msg-2' }, NOW);
|
||||
messages = applyChunk(messages, { type: 'data-trek-card', data: { toolCallId: 'w1', card: ROUTE } }, NOW);
|
||||
expect(cardsOf(messages[0])).toEqual([{ toolCallId: 'w1', card: ROUTE }]);
|
||||
expect(cardsOf(messages[1])).toEqual([]);
|
||||
});
|
||||
|
||||
it('FE-AI-MSG-CARDS-005: a card under a call that holds no change stays in the message being written', () => {
|
||||
const earlier: AssistantMessage = {
|
||||
id: 'msg-1',
|
||||
role: 'assistant',
|
||||
status: 'complete',
|
||||
createdAt: NOW(),
|
||||
parts: [{ type: 'tool-call', toolCallId: 'r1', toolName: 'list_tours', args: {} }],
|
||||
};
|
||||
let messages = applyChunk([earlier], { type: 'start', messageId: 'msg-2' }, NOW);
|
||||
messages = applyChunk(messages, { type: 'data-trek-card', data: { toolCallId: 'r1', card: LIST } }, NOW);
|
||||
expect(cardsOf(messages[0])).toEqual([]);
|
||||
expect(cardsOf(messages[1])).toEqual([{ toolCallId: 'r1', card: LIST }]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type {
|
||||
AssistantApplied,
|
||||
AssistantCard,
|
||||
AssistantDecision,
|
||||
AssistantMessage,
|
||||
AssistantMessagePart,
|
||||
@@ -62,6 +63,8 @@ export function applyChunk(
|
||||
]);
|
||||
case 'data-trek-weather':
|
||||
return withCurrent(messages, now, (parts) => [...parts, { type: 'data-trek-weather', data: chunk.data }]);
|
||||
case 'data-trek-card':
|
||||
return chunk.data.card ? placeCard(messages, now, chunk.data) : messages;
|
||||
case 'finish':
|
||||
return withStatus(messages, (m) =>
|
||||
m.status === 'error' ? m.status : m.parts.some(isAwaitingDecision) ? 'awaiting_approval' : 'complete'
|
||||
@@ -205,6 +208,31 @@ function upsertCall(
|
||||
return withCurrent(messages, now, (parts) => [...parts, edit({ type: 'tool-call', toolCallId, toolName, args: {} })]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts a card where it belongs: an applied write's next to the change that
|
||||
* proposed it (an earlier message, when the decisions stream sends it), a
|
||||
* read's into the message being written. A repeated card for the same call
|
||||
* replaces the one before.
|
||||
*/
|
||||
function placeCard(messages: AssistantMessage[], now: () => string, data: AssistantCard): AssistantMessage[] {
|
||||
const card: AssistantMessagePart = { type: 'data-trek-card', data };
|
||||
const keep = (parts: AssistantMessagePart[]) => [
|
||||
...parts.filter((p) => !(p.type === 'data-trek-card' && p.data.toolCallId === data.toolCallId)),
|
||||
card,
|
||||
];
|
||||
const at = findChange(messages, data.toolCallId);
|
||||
if (at < 0) return withCurrent(messages, now, keep);
|
||||
return messages.map((m, i) => (i === at ? { ...m, parts: keep(m.parts) } : m));
|
||||
}
|
||||
|
||||
/** The message holding the change a call proposed, or -1. */
|
||||
function findChange(messages: readonly AssistantMessage[], toolCallId: string): number {
|
||||
for (let i = messages.length - 1; i >= 0; i--) {
|
||||
if (messages[i]?.parts.some((p) => p.type === 'tool-call' && p.toolCallId === toolCallId && p.approval)) return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/** Puts the receipt of an applied change next to its call, so the card and its receipt stay together. */
|
||||
function placeApplied(messages: AssistantMessage[], now: () => string, data: AssistantApplied): AssistantMessage[] {
|
||||
const receipt: AssistantMessagePart = { type: 'data-trek-applied', data };
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
/**
|
||||
* FE-AI-STORE-CARDS-001 to FE-AI-STORE-CARDS-004
|
||||
*
|
||||
* What the store keeps for the cards: the spot of a route the card and the
|
||||
* map share, a line a card asks the map to draw, the route the phone peeks
|
||||
* at, the way picked per block, all gone when the chat closes or changes;
|
||||
* and "Plan this", which joins the held change to the answer it belongs to.
|
||||
*/
|
||||
import type { AssistantMessage } from '@trek/shared';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { assistantRepo } from '../repo/assistantRepo';
|
||||
import { chatOf, useAssistantStore } from './assistantStore';
|
||||
|
||||
const TRIP = 4;
|
||||
const INITIAL = useAssistantStore.getState();
|
||||
const store = () => useAssistantStore.getState();
|
||||
const focus = { distanceMeters: 1200, elevationMeters: 840, lat: 45.1, lng: 7.2, sampleIndex: 12 };
|
||||
|
||||
const answer = (parts: AssistantMessage['parts']): AssistantMessage => ({
|
||||
id: 'msg-1',
|
||||
role: 'assistant',
|
||||
status: 'complete',
|
||||
createdAt: '2026-10-22T08:00:00.000Z',
|
||||
parts,
|
||||
});
|
||||
|
||||
function seedThread(messages: AssistantMessage[] = []) {
|
||||
useAssistantStore.setState({ byTrip: { [TRIP]: { ...chatOf(store(), TRIP), threadId: 7, messages } } });
|
||||
}
|
||||
|
||||
beforeEach(() => useAssistantStore.setState(INITIAL, true));
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
describe('assistantStore: cards', () => {
|
||||
it('FE-AI-STORE-CARDS-001: a route spot changes only when it moves, and a line only when it is another one', () => {
|
||||
const seen = vi.fn();
|
||||
const stop = useAssistantStore.subscribe(seen);
|
||||
store().setRouteFocus({ tripId: TRIP, ref: 'r1', focus, source: 'card' });
|
||||
store().setRouteFocus({ tripId: TRIP, ref: 'r1', focus: { ...focus }, source: 'card' });
|
||||
expect(seen).toHaveBeenCalledTimes(1);
|
||||
store().setRouteFocus({ tripId: TRIP, ref: 'r1', focus: { ...focus, sampleIndex: 13 }, source: 'map' });
|
||||
expect(store().routeFocus?.source).toBe('map');
|
||||
|
||||
const line = { tripId: TRIP, ref: 'day-2', lines: [[[45, 7] as [number, number]]], color: 'var(--accent)' };
|
||||
store().setRoutePreview(line);
|
||||
store().setRoutePreview({ ...line });
|
||||
store().setRoutePreview(null);
|
||||
store().setRoutePreview(null);
|
||||
expect(seen).toHaveBeenCalledTimes(4);
|
||||
expect(store().routePreview).toBeNull();
|
||||
stop();
|
||||
});
|
||||
|
||||
it('FE-AI-STORE-CARDS-002: the way picked is kept per block of the chat', () => {
|
||||
seedThread();
|
||||
store().pick(TRIP, 'block-1', 'r2');
|
||||
store().pick(TRIP, 'block-2', 'r5');
|
||||
store().pick(TRIP, 'block-1', 'r3');
|
||||
expect(chatOf(store(), TRIP).picks).toEqual({ 'block-1': 'r3', 'block-2': 'r5' });
|
||||
});
|
||||
|
||||
it('FE-AI-STORE-CARDS-003: closing, a new chat and another thread leave the map without the cards', async () => {
|
||||
const fill = () => {
|
||||
store().setRouteFocus({ tripId: TRIP, ref: 'r1', focus, source: 'card' });
|
||||
store().setRoutePreview({ tripId: TRIP, ref: 'day-2', lines: [], color: 'var(--accent)' });
|
||||
store().setRoutePeek({ tripId: TRIP, toolCallId: 'r1' });
|
||||
};
|
||||
const empty = () => ({ focus: store().routeFocus, line: store().routePreview, peek: store().routePeek });
|
||||
const none = { focus: null, line: null, peek: null };
|
||||
fill();
|
||||
expect(store().routePeek).toEqual({ tripId: TRIP, toolCallId: 'r1' });
|
||||
store().close();
|
||||
expect(empty()).toEqual(none);
|
||||
|
||||
fill();
|
||||
store().newThread(TRIP);
|
||||
expect(empty()).toEqual(none);
|
||||
|
||||
fill();
|
||||
vi.spyOn(assistantRepo, 'thread').mockResolvedValueOnce({ messages: [] } as never);
|
||||
const opening = store().openThread(TRIP, 9);
|
||||
expect(empty()).toEqual(none);
|
||||
await opening;
|
||||
});
|
||||
|
||||
it('FE-AI-STORE-CARDS-004: "Plan this" joins the held change to its answer, and says why when it cannot', async () => {
|
||||
seedThread([answer([{ type: 'text', text: 'Three ways up.' }])]);
|
||||
const held = answer([
|
||||
{ type: 'text', text: 'Three ways up.' },
|
||||
{ type: 'tool-call', toolCallId: 'w1', toolName: 'create_hike', args: {}, approval: { id: 'w1' } },
|
||||
]);
|
||||
const take = vi.spyOn(assistantRepo, 'takeProposal').mockResolvedValueOnce({ message: held });
|
||||
await store().takeProposal(TRIP, 'r1');
|
||||
expect(take).toHaveBeenCalledWith(TRIP, 7, expect.objectContaining({ toolCallId: 'r1' }));
|
||||
expect(chatOf(store(), TRIP).messages).toEqual([held]);
|
||||
|
||||
vi.spyOn(assistantRepo, 'takeProposal').mockRejectedValueOnce({ response: { status: 429 } });
|
||||
await store().takeProposal(TRIP, 'r1');
|
||||
expect(chatOf(store(), TRIP).error).toBe('too_many_requests');
|
||||
});
|
||||
});
|
||||
@@ -20,6 +20,7 @@ import { assistantRepo } from '../repo/assistantRepo';
|
||||
import { OnlineOnlyError } from '../repo/onlineOnly';
|
||||
import type { Assignment } from '../types';
|
||||
import { randomId } from '../utils/randomId';
|
||||
import type { RouteProfileFocus } from '../utils/routeGeometry';
|
||||
import {
|
||||
blockDays,
|
||||
blockKeyOf,
|
||||
@@ -74,6 +75,8 @@ interface AssistantTripChat {
|
||||
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. */
|
||||
@@ -122,8 +125,17 @@ interface AssistantState {
|
||||
mapLink: { tripId: number; hoveredId: string | null; source: AssistantMapSource } | null;
|
||||
/** The latest request to move the map; `seq` tells a new one from the same points asked again. */
|
||||
camera: { tripId: number; seq: number; points: LatLng[]; mode: 'fit' | 'pan'; why: 'user' | 'auto' } | null;
|
||||
/** A found place the pointer rests on, drawn on the map until it leaves. */
|
||||
preview: { tripId: number; ref: string; lat: number; lng: number; name: string } | null;
|
||||
/**
|
||||
* A spot a card points at (a found place, a row), drawn on the map until
|
||||
* the pointer leaves; a place of the trip pulses its own pin instead.
|
||||
*/
|
||||
preview: { tripId: number; ref: string; lat: number; lng: number; name: string; placeId?: number } | null;
|
||||
/** The point of a route a card and the map both show, from the card's profile or from the line on the map. */
|
||||
routeFocus: { tripId: number; ref: string; focus: RouteProfileFocus; source: 'card' | 'map' } | null;
|
||||
/** A line a card asks the map to draw while the pointer rests on it (a day of a drive, a saved tour). */
|
||||
routePreview: { tripId: number; ref: string; lines: LatLng[][]; color: string } | null;
|
||||
/** The route card the phone shows over the map. */
|
||||
routePeek: { tripId: number; toolCallId: string } | null;
|
||||
/** Where the floating window sits after its last move or resize, for the map to frame around it. */
|
||||
windowRect: WindowRect | null;
|
||||
/** The part of the planner's map on screen, sent with a question so "here" means it. */
|
||||
@@ -173,6 +185,14 @@ interface AssistantState {
|
||||
setPreviewPin: (preview: AssistantState['preview']) => void;
|
||||
setWindowRect: (rect: WindowRect | null) => void;
|
||||
setMapView: (mapView: AssistantState['mapView']) => void;
|
||||
|
||||
setRouteFocus: (routeFocus: AssistantState['routeFocus']) => void;
|
||||
setRoutePreview: (routePreview: AssistantState['routePreview']) => void;
|
||||
setRoutePeek: (routePeek: AssistantState['routePeek']) => void;
|
||||
/** Picks one of the ways a block of cards offers. */
|
||||
pick: (tripId: number, blockKey: string, toolCallId: string) => void;
|
||||
/** Takes a proposal an answer showed as a card ("Plan this"); the server holds it as a change to decide. */
|
||||
takeProposal: (tripId: number, toolCallId: string) => Promise<void>;
|
||||
}
|
||||
|
||||
const NO_LIVE: AssistantTripChat['live'] = { activity: null };
|
||||
@@ -192,8 +212,12 @@ const EMPTY_CHAT: AssistantTripChat = {
|
||||
undone: {},
|
||||
compare: null,
|
||||
mentions: [],
|
||||
picks: {},
|
||||
};
|
||||
|
||||
/** What the map shows for the cards of a chat, cleared when the chat closes or changes. */
|
||||
const NO_ROUTE = { routeFocus: null, routePreview: null, routePeek: null } as const;
|
||||
|
||||
/** A trip's chat as the store holds it, or the empty one; stable, so a selector can return it. */
|
||||
export function chatOf(state: Pick<AssistantState, 'byTrip'>, tripId: number): AssistantTripChat {
|
||||
return state.byTrip[tripId] ?? EMPTY_CHAT;
|
||||
@@ -462,6 +486,7 @@ function shellActions(ctx: Ctx) {
|
||||
window: { open: false, minimized: false },
|
||||
mapLink: null,
|
||||
preview: null,
|
||||
...NO_ROUTE,
|
||||
byTrip: backToAfter(s.byTrip),
|
||||
})),
|
||||
// Closed or minimized opens it; open closes it.
|
||||
@@ -487,6 +512,7 @@ function threadActions(ctx: Ctx) {
|
||||
|
||||
const openThread = async (tripId: number, threadId: number) => {
|
||||
if (chat(ctx, tripId).isRunning) return;
|
||||
ctx.set(NO_ROUTE);
|
||||
patch(ctx, tripId, { threadId, loading: true, error: null, unsent: null });
|
||||
try {
|
||||
const { messages } = await assistantRepo.thread(tripId, threadId);
|
||||
@@ -510,6 +536,7 @@ function threadActions(ctx: Ctx) {
|
||||
|
||||
const newThread = (tripId: number) => {
|
||||
chat(ctx, tripId).abort?.abort();
|
||||
ctx.set(NO_ROUTE);
|
||||
// The block a comparison belonged to leaves the screen with its thread.
|
||||
patch(ctx, tripId, {
|
||||
threadId: null,
|
||||
@@ -619,25 +646,43 @@ function compareActions(ctx: Ctx) {
|
||||
const points = [...dayPoints(compare.snapshot, days), ...dayPoints(useTripStore.getState().assignments, days)];
|
||||
requestCameraOn(ctx, tripId, points, 'fit', 'user');
|
||||
},
|
||||
addFoundPlace: async (tripId: number, ref: string, dayId: number) => {
|
||||
const threadId = chat(ctx, tripId).threadId;
|
||||
if (chat(ctx, tripId).isRunning || threadId === null) return;
|
||||
try {
|
||||
const { message } = await assistantRepo.addFoundPlace(tripId, threadId, { ...clientContext(), ref, dayId });
|
||||
const c = chat(ctx, tripId);
|
||||
// The thread may have changed while the server answered. The server sends back the whole answer the
|
||||
// card joined, under that answer's id, so it replaces the message it already holds.
|
||||
if (c.threadId !== threadId) return;
|
||||
const known = c.messages.some((m) => m.id === message.id);
|
||||
const messages = known ? c.messages.map((m) => (m.id === message.id ? message : m)) : [...c.messages, message];
|
||||
patch(ctx, tripId, { messages, error: null });
|
||||
} catch (err) {
|
||||
patch(ctx, tripId, { error: errorCodeOf(err) });
|
||||
}
|
||||
},
|
||||
addFoundPlace: (tripId: number, ref: string, dayId: number) =>
|
||||
holdWithoutTurn(ctx, tripId, (threadId) =>
|
||||
assistantRepo.addFoundPlace(tripId, threadId, { ...clientContext(), ref, dayId })
|
||||
),
|
||||
takeProposal: (tripId: number, toolCallId: string) =>
|
||||
holdWithoutTurn(ctx, tripId, (threadId) =>
|
||||
assistantRepo.takeProposal(tripId, threadId, { ...clientContext(), toolCallId })
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A change the server holds without a model turn (a found place for a day, a
|
||||
* proposal a card showed), joined to the answer it belongs to. The server
|
||||
* sends back that whole answer under its id, so it replaces the message the
|
||||
* chat already holds.
|
||||
*/
|
||||
async function holdWithoutTurn(
|
||||
ctx: Ctx,
|
||||
tripId: number,
|
||||
hold: (threadId: number) => Promise<{ message: AssistantMessage }>
|
||||
): Promise<void> {
|
||||
const threadId = chat(ctx, tripId).threadId;
|
||||
if (chat(ctx, tripId).isRunning || threadId === null) return;
|
||||
try {
|
||||
const { message } = await hold(threadId);
|
||||
const c = chat(ctx, tripId);
|
||||
// The thread may have changed while the server answered.
|
||||
if (c.threadId !== threadId) return;
|
||||
const known = c.messages.some((m) => m.id === message.id);
|
||||
const messages = known ? c.messages.map((m) => (m.id === message.id ? message : m)) : [...c.messages, message];
|
||||
patch(ctx, tripId, { messages, error: null });
|
||||
} catch (err) {
|
||||
patch(ctx, tripId, { error: errorCodeOf(err) });
|
||||
}
|
||||
}
|
||||
|
||||
function requestCameraOn(ctx: Ctx, tripId: number, points: LatLng[], mode: 'fit' | 'pan', why: 'user' | 'auto') {
|
||||
if (points.length === 0) return;
|
||||
const seq = (ctx.get().camera?.seq ?? 0) + 1;
|
||||
@@ -665,6 +710,35 @@ function mapActions(ctx: Ctx) {
|
||||
};
|
||||
}
|
||||
|
||||
/** Whether two route focuses point at the same spot of the same route from the same side. */
|
||||
function sameFocus(a: AssistantState['routeFocus'], b: AssistantState['routeFocus']): boolean {
|
||||
if (a === null || b === null) return a === b;
|
||||
return (
|
||||
a.tripId === b.tripId &&
|
||||
a.ref === b.ref &&
|
||||
a.source === b.source &&
|
||||
a.focus.sampleIndex === b.focus.sampleIndex &&
|
||||
a.focus.distanceMeters === b.focus.distanceMeters
|
||||
);
|
||||
}
|
||||
|
||||
function routeActions(ctx: Ctx) {
|
||||
return {
|
||||
// Scrubbing repeats the same spot; only a change reaches the subscribers.
|
||||
setRouteFocus: (routeFocus: AssistantState['routeFocus']) => {
|
||||
if (!sameFocus(ctx.get().routeFocus, routeFocus)) ctx.set({ routeFocus });
|
||||
},
|
||||
setRoutePreview: (routePreview: AssistantState['routePreview']) => {
|
||||
const current = ctx.get().routePreview;
|
||||
if (current?.tripId === routePreview?.tripId && current?.ref === routePreview?.ref) return;
|
||||
ctx.set({ routePreview });
|
||||
},
|
||||
setRoutePeek: (routePeek: AssistantState['routePeek']) => ctx.set({ routePeek }),
|
||||
pick: (tripId: number, blockKey: string, toolCallId: string) =>
|
||||
patch(ctx, tripId, { picks: { ...chat(ctx, tripId).picks, [blockKey]: toolCallId } }),
|
||||
};
|
||||
}
|
||||
|
||||
function turnActions(ctx: Ctx) {
|
||||
const retry = async (tripId: number) => {
|
||||
const c = chat(ctx, tripId);
|
||||
@@ -728,10 +802,12 @@ export const useAssistantStore = create<AssistantState>((set, get) => {
|
||||
preview: null,
|
||||
windowRect: null,
|
||||
mapView: null,
|
||||
...NO_ROUTE,
|
||||
...shellActions(ctx),
|
||||
...threadActions(ctx),
|
||||
...turnActions(ctx),
|
||||
...compareActions(ctx),
|
||||
...mapActions(ctx),
|
||||
...routeActions(ctx),
|
||||
};
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user