/** * Pure message-list mutators powering the chat surface's destructive * operations (delete, truncate-and-rerun). Kept free of React, of the * concrete `ChatMessage` shape, and of any side effects so we can test * the rules in isolation under vitest's existing node environment. * * Consumers thread their own `ChatMessage` (or a structural subtype) — we * only need `id` and `role`. */ export interface MinimalMsg { id: string; role: "user" | "assistant" | "system"; content?: string; } /** Identity-preserving slice: returns the input array unchanged when the * anchor isn't present, so React reference equality keeps memoised * consumers from re-rendering on a no-op. */ export function truncateUpToAndIncluding( list: T[], anchorId: string, ): T[] { const idx = list.findIndex((m) => m.id === anchorId); if (idx < 0) return list; return list.slice(0, idx + 1); } /** Drops the anchor and everything after it. */ export function truncateBefore( list: T[], anchorId: string, ): T[] { const idx = list.findIndex((m) => m.id === anchorId); if (idx < 0) return list; return list.slice(0, idx); } /** Remove a single message by id. */ export function removeAt(list: T[], id: string): T[] { const idx = list.findIndex((m) => m.id === id); if (idx < 0) return list; const next = list.slice(); next.splice(idx, 1); return next; } /** * Remove a user message AND the immediately-following assistant message * (the "paired delete" semantic). When the next slot isn't an assistant — * either because it's another user message or because the user message is * at the tail — only the user message is removed. */ export function removePair( list: T[], userId: string, ): T[] { const idx = list.findIndex((m) => m.id === userId); if (idx < 0) return list; const next = list.slice(); const removeCount = list[idx + 1] && list[idx + 1].role === "assistant" ? 2 : 1; next.splice(idx, removeCount); return next; } /** Walk backwards from the given assistant message and return the nearest * user message above it. Returns null when none exists or the target id * isn't in the list. */ export function findUserAnchorAbove( list: T[], fromId: string, ): T | null { const idx = list.findIndex((m) => m.id === fromId); if (idx < 0) return null; for (let i = idx - 1; i >= 0; i -= 1) { if (list[i].role === "user") return list[i]; } return null; }