char-fork/llama.cpp

git clone https://git.t4t.associates/char-fork/llama.cpp

Aleksander Grygierui: Improve Chat Messages rendering performance (#28460)0afb805b1

char/aliceai-t5-moe
7.5 KiB269 linesraw
1/**
2 * Message branching utilities for conversation tree navigation.
3 *
4 * Conversation branching allows users to edit messages and create alternate paths
5 * while preserving the original conversation flow. Each message has parent/children
6 * relationships forming a tree structure.
7 *
8 * Example tree:
9 * root
10 *  ├── message 1 (user)
11 *  │      └── message 2 (assistant)
12 *  │             ├── message 3 (user)
13 *  │             └── message 6 (user) ← new branch
14 *  └── message 4 (user)
15 *        └── message 5 (assistant)
16 */
17
18import { MessageRole } from '$lib/enums';
19
20/**
21 * Finds a message by its ID in the given messages array.
22 */
23export function findMessageById(
24	messages: readonly DatabaseMessage[],
25	id: string | null | undefined
26): DatabaseMessage | undefined {
27	if (!id) return undefined;
28
29	return messages.find((m) => m.id === id);
30}
31
32/**
33 * Filters messages to get the conversation path from root to a specific leaf node.
34 * If the leafNodeId doesn't exist, returns the path with the latest timestamp.
35 *
36 * @param messages - All messages in the conversation
37 * @param leafNodeId - The target leaf node ID to trace back from
38 * @param includeRoot - Whether to include root messages in the result
39 * @returns Array of messages from root to leaf, sorted by timestamp
40 */
41export function filterByLeafNodeId(
42	messages: readonly DatabaseMessage[],
43	leafNodeId: string,
44	includeRoot: boolean = false
45): readonly DatabaseMessage[] {
46	const result: DatabaseMessage[] = [];
47	const nodeMap = new Map<string, DatabaseMessage>();
48
49	// Build node map for quick lookups
50	for (const msg of messages) {
51		nodeMap.set(msg.id, msg);
52	}
53
54	// Find the starting node (leaf node or latest if not found)
55	let startNode: DatabaseMessage | undefined = nodeMap.get(leafNodeId);
56
57	if (!startNode) {
58		// If leaf node not found, use the message with latest timestamp
59		let latestTime = -1;
60
61		for (const msg of messages) {
62			if (msg.timestamp > latestTime) {
63				startNode = msg;
64				latestTime = msg.timestamp;
65			}
66		}
67	}
68
69	// Traverse from leaf to root, collecting messages
70	let currentNode: DatabaseMessage | undefined = startNode;
71
72	while (currentNode) {
73		// Include message if it's not root, or if we want to include root
74		if (currentNode.type !== 'root' || includeRoot) {
75			result.push(currentNode);
76		}
77
78		// Stop traversal if parent is null (reached root)
79		if (currentNode.parent === null) {
80			break;
81		}
82
83		currentNode = nodeMap.get(currentNode.parent);
84	}
85
86	// Sort: system messages first, then by timestamp
87	result.sort((a, b) => {
88		if (a.role === MessageRole.SYSTEM && b.role !== MessageRole.SYSTEM) return -1;
89
90		if (a.role !== MessageRole.SYSTEM && b.role === MessageRole.SYSTEM) return 1;
91
92		return a.timestamp - b.timestamp;
93	});
94
95	return result;
96}
97
98/**
99 * Finds the leaf node (message with no children) for a given message branch.
100 * Traverses down the tree following the last child until reaching a leaf.
101 *
102 * @param nodeMap - Map of messages keyed by ID
103 * @param messageId - Starting message ID to find leaf for
104 * @returns The leaf node ID, or the original messageId if no children
105 */
106function findLeafNodeInMap(
107	nodeMap: ReadonlyMap<string, DatabaseMessage>,
108	messageId: string,
109	leafCache?: Map<string, string>
110): string {
111	const path: string[] = [];
112
113	let currentNode: DatabaseMessage | undefined = nodeMap.get(messageId);
114
115	while (currentNode && currentNode.children.length > 0) {
116		// Follow the last child (most recent branch)
117		const cached = leafCache?.get(currentNode.id);
118
119		if (cached !== undefined) {
120			for (const id of path) leafCache?.set(id, cached);
121
122			return cached;
123		}
124
125		path.push(currentNode.id);
126		const lastChildId = currentNode.children[currentNode.children.length - 1];
127
128		currentNode = nodeMap.get(lastChildId);
129	}
130
131	const leafId = currentNode?.id ?? messageId;
132
133	for (const id of path) leafCache?.set(id, leafId);
134
135	return leafId;
136}
137
138/**
139 * Convenience wrapper around {@link findLeafNodeInMap} for callers that have a flat message array.
140 */
141export function findLeafNode(messages: readonly DatabaseMessage[], messageId: string): string {
142	const nodeMap = new Map(messages.map((msg) => [msg.id, msg] as const));
143
144	return findLeafNodeInMap(nodeMap, messageId);
145}
146
147/**
148 * Finds all descendant messages (children, grandchildren, etc.) of a given message.
149 * This is used for cascading deletion to remove all messages in a branch.
150 *
151 * @param messages - All messages in the conversation
152 * @param messageId - The root message ID to find descendants for
153 * @returns Array of all descendant message IDs
154 */
155export function findDescendantMessages(
156	messages: readonly DatabaseMessage[],
157	messageId: string
158): string[] {
159	const nodeMap = new Map<string, DatabaseMessage>();
160
161	// Build node map for quick lookups
162	for (const msg of messages) {
163		nodeMap.set(msg.id, msg);
164	}
165
166	const descendants: string[] = [];
167	const queue: string[] = [messageId];
168
169	while (queue.length > 0) {
170		const currentId = queue.shift()!;
171		const currentNode = nodeMap.get(currentId);
172
173		if (currentNode) {
174			// Add all children to the queue and descendants list
175			for (const childId of currentNode.children) {
176				descendants.push(childId);
177				queue.push(childId);
178			}
179		}
180	}
181
182	return descendants;
183}
184
185/**
186 * Gets sibling information for a message, including all sibling IDs and current position.
187 * Siblings are messages that share the same parent.
188 *
189 * @param nodeMap - Map of messages keyed by ID
190 * @param messageId - The message to get sibling info for
191 * @returns Sibling information including leaf node IDs for navigation
192 */
193export function getMessageSiblings(
194	nodeMap: ReadonlyMap<string, DatabaseMessage>,
195	messageId: string,
196	leafCache?: Map<string, string>
197): ChatMessageSiblingInfo | null {
198	const message = nodeMap.get(messageId);
199
200	if (!message) {
201		return null;
202	}
203
204	// Handle null parent (root message) case
205	if (message.parent === null) {
206		// No parent means this is likely a root node with no siblings
207		return {
208			currentIndex: 0,
209			message,
210			siblingIds: [messageId],
211			totalSiblings: 1
212		};
213	}
214
215	const parentNode = nodeMap.get(message.parent);
216
217	if (!parentNode) {
218		// Parent not found - treat as single message
219		return {
220			currentIndex: 0,
221			message,
222			siblingIds: [messageId],
223			totalSiblings: 1
224		};
225	}
226
227	// Get all sibling IDs (including self)
228	const siblingIds = parentNode.children;
229	// Convert sibling message IDs to their corresponding leaf node IDs
230	// This allows navigation between different conversation branches
231	const siblingLeafIds = siblingIds.map((siblingId: string) =>
232		findLeafNodeInMap(nodeMap, siblingId, leafCache)
233	);
234	// Find current message's position among siblings
235	const currentIndex = siblingIds.indexOf(messageId);
236
237	return {
238		currentIndex,
239		message,
240		siblingIds: siblingLeafIds,
241		totalSiblings: siblingIds.length
242	};
243}
244
245/**
246 * Builds sibling information for every message in a conversation.
247 *
248 * @param messages - All messages in the conversation
249 * @returns Map of message ID to its sibling information
250 */
251export function buildSiblingInfoMap(
252	messages: readonly DatabaseMessage[]
253): Map<string, ChatMessageSiblingInfo> {
254	const nodeMap = new Map(messages.map((msg) => [msg.id, msg] as const));
255	const siblingMap = new Map<string, ChatMessageSiblingInfo>();
256	// Leaf walks repeat along the same child chains for every message; memoize
257	// them per build so each edge is walked once instead of O(messages^2)
258	const leafCache = new Map<string, string>();
259
260	for (const msg of messages) {
261		const info = getMessageSiblings(nodeMap, msg.id, leafCache);
262
263		if (info) {
264			siblingMap.set(msg.id, info);
265		}
266	}
267
268	return siblingMap;
269}