feat(assistant): hike, walk and route cards with their lines on the map, and "Plan this"

This commit is contained in:
Maurice
2026-10-22 15:50:47 +02:00
parent 8547006742
commit 59313dfaff
135 changed files with 12185 additions and 234 deletions
+2 -1
View File
@@ -32,7 +32,8 @@ export function changeEffects(messages: readonly AssistantMessage[]): Map<string
return effects;
}
function receiptsOf(messages: readonly AssistantMessage[]): Map<string, AssistantApplied> {
/** The receipt of every applied change of the thread, by its call. */
export function receiptsOf(messages: readonly AssistantMessage[]): Map<string, AssistantApplied> {
const receipts = new Map<string, AssistantApplied>();
for (const m of messages) {
for (const p of m.parts) if (p.type === 'data-trek-applied') receipts.set(p.data.toolCallId, p.data);
@@ -0,0 +1,183 @@
/**
* FE-AI-ROUTE-001 to FE-AI-ROUTE-005
*
* Which routes of the chat's cards the plan's map draws, and how: changes
* that still stand on the map with the way they replace, the cards of the
* latest answer that draws any (its ways each with a letter, the chosen one
* solid), the order lines lie in, and the spots the waiting changes mark.
* The looks are a stand-in here: the model reads cards only through them.
*/
import type { AssistantApplied, AssistantMessage, AssistantMessagePart, TourRouteCard, TrekCard } from '@trek/shared';
import { describe, expect, it } from 'vitest';
import { GENTLE, HIKE, SAVED } from '../../tests/helpers/assistantTour';
import type { CardMapLook, RouteLineSpec } from '../types/assistantMap';
import {
type AnswerLayout,
cardGhosts,
cardHiddenGhosts,
lookPoints,
routeLines,
routeRefs,
} from './assistantRouteModel';
const flat = (card: TourRouteCard): [number, number][] => card.line.map(([lat, lng]): [number, number] => [lat, lng]);
/** A look that draws a route card's line (rimmed), the way it replaces, and one spot for a held route. */
const LOOK: CardMapLook = {
lines: (card: TrekCard, use): RouteLineSpec[] => {
if (card.kind !== 'tourRoute') return [];
if (use === 'before') {
return card.previous ? [{ id: 'previous', lines: [card.previous.line], color: 'var(--faint)', dim: true }] : [];
}
if (card.line.length < 2) return [];
const tints = [{ line: flat(card).slice(3, 6), color: 'var(--t3)' }];
const route = { id: 'route', lines: [flat(card)], color: 'var(--route)', casing: 'var(--rim)' };
return [{ ...route, dashed: !card.routed, tints }];
},
ghosts: (card) =>
card.kind === 'tourRoute' ? [{ id: 'start', lat: 47.77, lng: 12.59, name: 'Bergen', variant: 'pin' }] : [],
hidesEffectGhost: (card) => card.kind === 'tourRoute' && card.routed,
};
/** All an answer's cards as one group, as the chat lays out proposals of one activity. */
const AS_WAYS: AnswerLayout = (entries) => [entries];
function message(parts: AssistantMessagePart[], id = 'msg-1'): AssistantMessage {
return { id, role: 'assistant', parts, status: 'complete', createdAt: '2026-10-21T08:00:00.000Z' };
}
function read(toolCallId: string, card: TourRouteCard): AssistantMessagePart[] {
return [
{ type: 'tool-call', toolCallId, toolName: 'propose_hike', args: {}, result: {} },
{ type: 'data-trek-card', data: { toolCallId, card } },
];
}
type Approval = { approved?: boolean; resolution?: 'expired' };
function held(toolCallId: string, card: TourRouteCard, approval: Approval = {}, extra: object = {}) {
return [
{
type: 'tool-call',
toolCallId,
toolName: 'create_hike',
args: {},
approval: { id: toolCallId, ...approval },
...extra,
},
{
type: 'data-trek-change',
data: { toolCallId, verbKey: 'addTour', subject: 'x', rows: [], dayId: null, placeIds: [], undoable: true, card },
},
] as AssistantMessagePart[];
}
function receipt(toolCallId: string, entity: AssistantApplied['entity'], ids: number[]): AssistantMessagePart {
return { type: 'data-trek-applied', data: { toolCallId, entity, ids, dayId: null, undoUntil: null } };
}
const PENDING: TourRouteCard = { ...HIKE, source: 'pending' };
const NOBODY = new Set<number>();
describe('assistantRouteModel', () => {
it('FE-AI-ROUTE-001: a change stands on the map while undecided or running, and once applied until its place arrives', () => {
const messages = [
message([
...held('wait', PENDING),
...held('run', PENDING, { approved: true }),
...held('done', PENDING, { approved: true }, { result: {} }),
receipt('done', 'tour', [41]),
...held('note', PENDING, { approved: true }, { result: {} }),
receipt('note', 'day_note', [5]),
...held('no', PENDING, { approved: false }),
...held('late', PENDING, { resolution: 'expired' }),
...held('broke', PENDING, { approved: true }, { result: {}, isError: true }),
]),
];
const standing = routeRefs(messages, {}, NOBODY, LOOK).map((ref) => `${ref.toolCallId}:${ref.use}`);
const all = ['wait:before', 'wait:pending', 'run:before', 'run:pending', 'done:before', 'done:pending'];
expect(standing).toEqual(all);
const arrived = routeRefs(messages, {}, new Set([41]), LOOK).map((ref) => ref.toolCallId);
expect(arrived).not.toContain('done');
});
it('FE-AI-ROUTE-002: the latest answer that draws routes is drawn, its ways lettered and the chosen one picked', () => {
const older = message(read('old', SAVED), 'msg-0');
const latest = message([...read('call_1', HIKE), ...read('call_2', GENTLE)], 'msg-1');
const quiet = message([{ type: 'text', text: 'Both are fine.' }], 'msg-2');
const first = routeRefs([older, latest, quiet], {}, NOBODY, LOOK, AS_WAYS);
expect(first.map((ref) => [ref.toolCallId, ref.use, ref.way, ref.picked])).toEqual([
['call_1', 'look', 'a', true],
['call_2', 'look', 'b', false],
]);
const chosen = routeRefs([older, latest], { 'tour:call_1': 'call_2' }, NOBODY, LOOK, AS_WAYS);
expect(chosen.map((ref) => ref.picked)).toEqual([false, true]);
// Laid out one by one, the cards are routes of their own: no letters.
expect(routeRefs([latest], {}, NOBODY, LOOK).map((ref) => ref.way)).toEqual([null, null]);
// A card under a change's call is that change's, never an answer's.
const applied: AssistantMessagePart = { type: 'data-trek-card', data: { toolCallId: 'c9', card: SAVED } };
const change = message([...held('c9', PENDING), applied]);
const refs = routeRefs([change], {}, NOBODY, LOOK);
expect(refs.map((ref) => ref.use)).toEqual(['before', 'pending']);
expect(refs[1]?.card).toBe(SAVED);
});
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 = [
message([...held('upd', { ...PENDING, previous })], 'msg-0'),
message([...read('call_1', HIKE), ...read('call_2', GENTLE)], 'msg-1'),
];
const refs = routeRefs(messages, { 'tour:call_1': 'call_2' }, NOBODY, LOOK, AS_WAYS);
const calm = routeLines(refs, LOOK, null);
expect(calm.map((line) => line.id)).toEqual([
'upd:before:previous',
'upd:pending:route',
'call_1:look:route',
'call_2:look:route',
]);
const [replaced, pending, wayA, wayB] = calm;
expect(replaced).toMatchObject({ ref: 'upd', dim: true, casing: 'var(--bg-card)' });
expect(replaced?.ends).toBeUndefined();
expect(pending).toMatchObject({ color: 'var(--route)', casing: 'var(--rim)' });
// The hike is a loop: one disc at its start, no ring at its end.
expect(pending?.ends).toEqual({ start: [47.77, 12.59], end: null });
expect(wayA).toMatchObject({ color: 'var(--hike-variant-a)', dashed: true });
expect(wayA?.tints).toBeUndefined();
expect(wayB).toMatchObject({ color: 'var(--hike-variant-b)' });
expect(wayB?.dashed).toBeUndefined();
expect(wayB?.tints).toHaveLength(1);
const lit = routeLines(refs, LOOK, 'call_1');
expect(lit[lit.length - 1]).toMatchObject({ id: 'call_1:look:route', hot: true });
expect(lit[lit.length - 1]?.dashed).toBeUndefined();
});
it('FE-AI-ROUTE-004: a route joined straight stays dashed even when lit, and an open route has a ring at its end', () => {
const straight: TourRouteCard = { ...HIKE, routed: false, line: HIKE.line.slice(0, 5) };
const refs = routeRefs([message(read('s', straight))], {}, NOBODY, LOOK);
const [line] = routeLines(refs, LOOK, 's');
expect(line).toMatchObject({ dashed: true, hot: true });
expect(line?.ends).toEqual({ start: [47.77, 12.59], end: [47.79, 12.62] });
});
it('FE-AI-ROUTE-005: waiting changes mark their spots under their call, hide the pin their line replaces, and answers frame', () => {
const messages = [
message([...held('wait', PENDING), ...held('flat', { ...PENDING, routed: false })], 'msg-0'),
message(read('call_1', HIKE), 'msg-1'),
];
const refs = routeRefs(messages, {}, NOBODY, LOOK);
expect(cardGhosts(refs, LOOK)).toEqual([
{ id: 'wait:start', ref: 'wait', lat: 47.77, lng: 12.59, name: 'Bergen', variant: 'pin' },
{ id: 'flat:start', ref: 'flat', lat: 47.77, lng: 12.59, name: 'Bergen', variant: 'pin' },
]);
expect([...cardHiddenGhosts(refs, LOOK)]).toEqual(['wait']);
expect(lookPoints(refs, LOOK)).toEqual(flat(HIKE));
});
});
+259
View File
@@ -0,0 +1,259 @@
import { type AssistantApplied, type AssistantMessage, haversineMetres, type TrekCard } from '@trek/shared';
import type { AssistantRouteLine, CardMapLook, GhostPoint, RouteLineSpec, RouteUse } from '../types/assistantMap';
import { receiptsOf } from './assistantMapModel';
/**
* Which routes of the chat's cards the plan's map draws, and how. Three
* kinds of card stand on the map: a change still to be decided (or applied,
* until the trip holds what it made), with the way it replaces faint beside
* it; and the cards of the latest answer that drew any, the ways of one
* proposal each in its letter's colour, the chosen one solid. Pure and
* React-free: the store holds the chat, the planner hands in the cards'
* map looks (`CardMapLook`), and the tests need neither.
*/
/** A card of the chat under the call it came from. */
export interface RouteCardEntry {
toolCallId: string;
card: TrekCard;
}
/** 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'];
/** The colour each way is drawn in, the planner's own for the ways of a section (styles/hike.css). */
const WAY_PAINT: Readonly<Record<RouteWayKey, string>> = {
a: 'var(--hike-variant-a)',
b: 'var(--hike-variant-b)',
c: 'var(--hike-variant-c)',
};
/** The rim a line gets when its card names none. */
const DEFAULT_CASING = 'var(--bg-card)';
/** A line whose ends lie closer than this is a loop: one disc at its start, no ring at its end. */
const LOOP_M = 60;
/**
* A card the map draws, in the part it plays: `pending` a change, `before`
* the way that change replaces, `look` a card of an answer. `way` is its
* letter among the ways of one answer, `picked` whether it is the chosen one.
*/
export interface RouteRef {
toolCallId: string;
card: TrekCard;
use: RouteUse;
way: RouteWayKey | null;
picked: boolean;
}
/**
* How an answer lays out its cards, as the chat does: the groups that show
* as one card. A group of several is a choice between ways.
*/
export type AnswerLayout = (entries: readonly RouteCardEntry[]) => readonly (readonly RouteCardEntry[])[];
/** Every card on its own, for a planner that knows no groups. */
const ALONE: AnswerLayout = (entries) => entries.map((entry) => [entry]);
type ToolCallPart = Extract<AssistantMessage['parts'][number], { type: 'tool-call' }>;
/** What an applied change made that becomes a place of the trip, and so arrives on the map by itself. */
const BECOMES_A_PLACE: ReadonlySet<AssistantApplied['entity']> = new Set(['tour', 'place']);
/** The card of each change of the thread (its applied card once there, else its preview's), and every change's call. */
function changeCards(messages: readonly AssistantMessage[]): { cards: Map<string, TrekCard>; changeIds: Set<string> } {
const previews = new Map<string, TrekCard>();
const posted = new Map<string, TrekCard>();
const changeIds = new Set<string>();
for (const message of messages) {
for (const part of message.parts) {
if (part.type === 'data-trek-change') {
changeIds.add(part.data.toolCallId);
if (part.data.card) previews.set(part.data.toolCallId, part.data.card);
} else if (part.type === 'tool-call' && part.approval) changeIds.add(part.toolCallId);
else if (part.type === 'data-trek-card' && part.data.card) posted.set(part.data.toolCallId, part.data.card);
}
}
const cards = new Map(previews);
for (const [toolCallId, card] of posted) if (changeIds.has(toolCallId)) cards.set(toolCallId, card);
return { cards, changeIds };
}
/**
* Whether a change still stands on the map: undecided, or applied and not
* answered yet, or applied with a place the trip does not hold yet (the
* place comes with the broadcast, and its real line takes over then). A
* change that was discarded, expired or failed does not.
*/
function standsOnMap(part: ToolCallPart, receipt: AssistantApplied | undefined, known: ReadonlySet<number>): boolean {
const approval = part.approval;
if (!approval || approval.resolution || approval.approved === false) return false;
if (approval.approved === undefined) return true;
if (part.isError) return false;
if (!receipt) return part.result === undefined;
const placeId = receipt.ids[0];
return BECOMES_A_PLACE.has(receipt.entity) && placeId !== undefined && !known.has(placeId);
}
/**
* 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.
*/
function lookRefs(
messages: readonly AssistantMessage[],
changeIds: ReadonlySet<string>,
picks: Readonly<Record<string, string>>,
look: CardMapLook,
layout: AnswerLayout
): RouteRef[] {
const chosenIds = new Set(Object.values(picks));
for (let index = messages.length - 1; index >= 0; index--) {
const answers = (messages[index]?.parts ?? []).flatMap((part): RouteCardEntry[] =>
part.type === 'data-trek-card' && part.data.card && !changeIds.has(part.data.toolCallId)
? [{ toolCallId: part.data.toolCallId, card: part.data.card }]
: []
);
const lined = answers.filter((entry) => look.lines(entry.card, 'look').length > 0);
const drawn = new Set(lined.map((entry) => entry.toolCallId));
if (drawn.size === 0) continue;
return layout(answers).flatMap((group) => {
const ways = group.length >= 2;
const chosen = group.find((entry) => chosenIds.has(entry.toolCallId)) ?? group[0];
return group.flatMap((entry, position): RouteRef[] => {
if (!drawn.has(entry.toolCallId)) return [];
const way = ways ? (WAY_KEYS[position] ?? null) : null;
return [{ ...entry, use: 'look', way, picked: ways && entry === chosen }];
});
});
}
return [];
}
/**
* Every card of the chat the map draws now, in the part it plays: the
* changes that still stand on the map (each with the way it replaces), then
* the cards of the latest answer that draws any.
*/
export function routeRefs(
messages: readonly AssistantMessage[],
picks: Readonly<Record<string, string>>,
knownPlaceIds: ReadonlySet<number>,
look: CardMapLook,
layout: AnswerLayout = ALONE
): RouteRef[] {
const { cards, changeIds } = changeCards(messages);
const receipts = receiptsOf(messages);
const refs: RouteRef[] = [];
for (const message of messages) {
for (const part of message.parts) {
if (part.type !== 'tool-call') continue;
const card = cards.get(part.toolCallId);
if (!card || !standsOnMap(part, receipts.get(part.toolCallId), knownPlaceIds)) continue;
refs.push({ toolCallId: part.toolCallId, card, use: 'before', way: null, picked: false });
refs.push({ toolCallId: part.toolCallId, card, use: 'pending', way: null, picked: false });
}
}
return [...refs, ...lookRefs(messages, changeIds, picks, look, layout)];
}
/** Where a route starts and ends; a loop has no end of its own. */
function endsOf(lines: readonly [number, number][][]): AssistantRouteLine['ends'] | null {
const first = lines[0]?.[0];
const lastLine = lines[lines.length - 1];
const last = lastLine?.[lastLine.length - 1];
if (!first || !last) return null;
const loop = haversineMetres(first[0], first[1], last[0], last[1]) <= LOOP_M;
return { start: first, end: loop ? null : last };
}
/**
* One spec of a card as the map draws it. A way not chosen is dashed until
* it is pointed at; a line straight between its stops stays dashed. Only a
* route the card gives a rim to has ends (a via's move is a hint, not a
* route), and only a faint line leaves them out.
*/
function lineOf(
ref: RouteRef,
spec: RouteLineSpec,
hoveredId: string | null
): { line: AssistantRouteLine; rank: number } {
const hot = ref.toolCallId === hoveredId;
const unchosen = ref.way !== null && !ref.picked;
const line: AssistantRouteLine = {
id: `${ref.toolCallId}:${ref.use}:${spec.id}`,
ref: ref.toolCallId,
lines: spec.lines,
color: ref.way ? WAY_PAINT[ref.way] : spec.color,
casing: spec.casing ?? DEFAULT_CASING,
...extrasOf(spec, unchosen),
};
if (spec.dashed || (unchosen && !hot)) line.dashed = true;
if (spec.dim) line.dim = true;
if (hot) line.hot = true;
return { line, rank: rankOf(ref, hot) };
}
/** A route's ends, named stops and hard grades, as far as its spec has them; a way not chosen shows no grades. */
function extrasOf(spec: RouteLineSpec, unchosen: boolean): Pick<AssistantRouteLine, 'ends' | 'stops' | 'tints'> {
const extras: Pick<AssistantRouteLine, 'ends' | 'stops' | 'tints'> = {};
const ends = spec.casing && !spec.dim ? endsOf(spec.lines) : null;
if (ends) extras.ends = ends;
if (spec.stops && spec.stops.length > 0) extras.stops = spec.stops;
if (spec.tints && spec.tints.length > 0 && !unchosen) extras.tints = spec.tints;
return extras;
}
/** Where a line lies among the others: the replaced way at the bottom, the chosen way high, the lit one on top. */
function rankOf(ref: RouteRef, hot: boolean): number {
if (hot) return 3;
if (ref.use === 'before') return 0;
return ref.picked ? 2 : 1;
}
/**
* The lines to draw, bottom first: the ways changes replace, then the
* others, the chosen way, and last the one under the pointer, so it lies on
* top where lines share a path.
*/
export function routeLines(
refs: readonly RouteRef[],
look: CardMapLook,
hoveredId: string | null
): AssistantRouteLine[] {
const drawn = refs.flatMap((ref) => look.lines(ref.card, ref.use).map((spec) => lineOf(ref, spec, hoveredId)));
return drawn
.map((entry, order) => ({ ...entry, order }))
.sort((a, b) => a.rank - b.rank || a.order - b.order)
.map((entry) => entry.line);
}
/** A spot a waiting change marks on the map, lit with its row by the change's call (`ref`). */
interface CardGhost extends GhostPoint {
ref: string;
}
/** The spots the waiting changes' cards mark (a road trip's new stops and vias), each under its own id. */
export function cardGhosts(refs: readonly RouteRef[], look: CardMapLook): CardGhost[] {
return refs.flatMap((ref) =>
ref.use === 'pending'
? look.ghosts(ref.card).map((ghost) => ({ ...ghost, id: `${ref.toolCallId}:${ghost.id}`, ref: ref.toolCallId }))
: []
);
}
/** The changes whose card draws them itself, so the pin of the place they add would only cover its start. */
export function cardHiddenGhosts(refs: readonly RouteRef[], look: CardMapLook): Set<string> {
const hiding = refs.filter((ref) => ref.use === 'pending' && look.hidesEffectGhost(ref.card));
return new Set(hiding.map((ref) => ref.toolCallId));
}
/** The points of every line an answer draws, to frame the map on them. */
export function lookPoints(refs: readonly RouteRef[], look: CardMapLook): [number, number][] {
return refs.flatMap((ref) =>
ref.use === 'look' ? look.lines(ref.card, 'look').flatMap((spec) => spec.lines.flat()) : []
);
}
+18 -3
View File
@@ -1,5 +1,5 @@
/**
* FE-AI-STORE-CARDS-001 to FE-AI-STORE-CARDS-004
* FE-AI-STORE-CARDS-001 to FE-AI-STORE-CARDS-005
*
* 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
@@ -91,12 +91,27 @@ describe('assistantStore: cards', () => {
{ 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');
await expect(store().takeProposal(TRIP, 'r1')).resolves.toBe('held');
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');
await expect(store().takeProposal(TRIP, 'r1')).resolves.toBe('refused');
expect(chatOf(store(), TRIP).error).toBe('too_many_requests');
});
it('FE-AI-STORE-CARDS-005: "Plan this" says it held nothing while a turn runs or after the thread changed under it', async () => {
seedThread([answer([{ type: 'text', text: 'Three ways up.' }])]);
const held = answer([{ type: 'text', text: 'Three ways up.' }]);
const take = vi.spyOn(assistantRepo, 'takeProposal').mockImplementationOnce(async () => {
useAssistantStore.setState({ byTrip: { [TRIP]: { ...chatOf(store(), TRIP), threadId: 8 } } });
return { message: held };
});
await expect(store().takeProposal(TRIP, 'r1')).resolves.toBe('skipped');
expect(take).toHaveBeenCalledTimes(1);
useAssistantStore.setState({ byTrip: { [TRIP]: { ...chatOf(store(), TRIP), isRunning: true } } });
await expect(store().takeProposal(TRIP, 'r1')).resolves.toBe('skipped');
expect(take).toHaveBeenCalledTimes(1);
});
});
+18 -8
View File
@@ -191,10 +191,17 @@ interface AssistantState {
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>;
/**
* Takes a proposal an answer showed as a card ("Plan this"); the server holds it as a change to decide.
* Says what came of it: held, refused (the chat's error says why), or skipped while a turn ran or the
* thread changed under it.
*/
takeProposal: (tripId: number, toolCallId: string) => Promise<HoldOutcome>;
}
/** What came of a change the server was asked to hold without a model turn. */
export type HoldOutcome = 'held' | 'refused' | 'skipped';
const NO_LIVE: AssistantTripChat['live'] = { activity: null };
const EMPTY_CHAT: AssistantTripChat = {
@@ -646,10 +653,11 @@ function compareActions(ctx: Ctx) {
const points = [...dayPoints(compare.snapshot, days), ...dayPoints(useTripStore.getState().assignments, days)];
requestCameraOn(ctx, tripId, points, 'fit', 'user');
},
addFoundPlace: (tripId: number, ref: string, dayId: number) =>
holdWithoutTurn(ctx, tripId, (threadId) =>
addFoundPlace: async (tripId: number, ref: string, dayId: number) => {
await 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 })
@@ -667,19 +675,21 @@ async function holdWithoutTurn(
ctx: Ctx,
tripId: number,
hold: (threadId: number) => Promise<{ message: AssistantMessage }>
): Promise<void> {
): Promise<HoldOutcome> {
const threadId = chat(ctx, tripId).threadId;
if (chat(ctx, tripId).isRunning || threadId === null) return;
if (chat(ctx, tripId).isRunning || threadId === null) return 'skipped';
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;
if (c.threadId !== threadId) return 'skipped';
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 });
return 'held';
} catch (err) {
patch(ctx, tripId, { error: errorCodeOf(err) });
return 'refused';
}
}