Elffuss BraidHub

kikocis/continue public

main · 13.8 KiBRawPermalink
1import type { ChatHistoryItem, ToolStatus } from "core/index.js";
2import { createHistoryItem } from "core/util/messageConversion.js";
3
4import {
5 updateSessionHistory,
6 loadSessionById,
7 createSession,
8} from "../session.js";
9import { logger } from "../util/logger.js";
10
11import { BaseService } from "./BaseService.js";
12
13/**
14 * State managed by the ChatHistoryService
15 */
16export interface ChatHistoryState {
17 history: ChatHistoryItem[];
18 compactionIndex: number | null;
19 sessionId: string;
20 isRemoteMode: boolean;
21}
22
23/**
24 * Service for managing chat history as the single source of truth
25 * Provides immutable updates and automatic React integration via events
26 */
27export class ChatHistoryService extends BaseService<ChatHistoryState> {
28 // Simple undo/redo stacks for history snapshots
29 private past: ChatHistoryItem[][] = [];
30 private future: ChatHistoryItem[][] = [];
31 // Memoized snapshot for referential stability in getState()
32 private _memoSnapshot: {
33 stateRef: ChatHistoryState | null;
34 historyRef: ChatHistoryItem[] | null;
35 snapshot: ChatHistoryState | null;
36 } = { stateRef: null, historyRef: null, snapshot: null };
37
38 constructor() {
39 super("ChatHistoryService", {
40 history: [],
41 compactionIndex: null,
42 sessionId: "",
43 isRemoteMode: false,
44 });
45 this.setMaxListeners(50);
46 }
47
48 private setHistoryInternal(
49 history: ChatHistoryItem[],
50 options: {
51 recordUndo?: boolean;
52 compactionIndex?: number | null;
53 persist?: boolean; // set to false to skip persistence (rare)
54 } = {},
55 ): void {
56 const { recordUndo = true, compactionIndex, persist } = options;
57 const prev = this.currentState.history;
58 if (recordUndo) {
59 this.past.push([...prev]);
60 this.future = [];
61 }
62 this.setState({
63 history: [...history],
64 compactionIndex:
65 compactionIndex === undefined
66 ? this.findCompactionIndex(history)
67 : compactionIndex,
68 });
69
70 if (this.currentState.isRemoteMode) {
71 // Skip persistence in remote mode
72 } else if (persist !== false) {
73 updateSessionHistory(history);
74 }
75 }
76
77 /**
78 * Initialize the service with optional session
79 */
80 async doInitialize(
81 session?: any,
82 isRemoteMode = false,
83 ): Promise<ChatHistoryState> {
84 const activeSession = session || createSession([]);
85
86 logger.debug("Initializing ChatHistoryService", {
87 sessionId: activeSession.sessionId,
88 historyLength: activeSession.history.length,
89 isRemoteMode,
90 });
91
92 return {
93 history: activeSession.history || [],
94 compactionIndex: this.findCompactionIndex(activeSession.history || []),
95 sessionId: activeSession.sessionId,
96 isRemoteMode,
97 };
98 }
99
100 /**
101 * Add a user message to the history
102 */
103 addUserMessage(content: string, contextItems: any[] = []): ChatHistoryItem {
104 const newMessage = createHistoryItem(
105 {
106 role: "user",
107 content,
108 },
109 contextItems,
110 );
111
112 const newHistory = [...this.currentState.history, newMessage];
113 this.setHistoryInternal(newHistory);
114
115 logger.debug("Added user message", {
116 contentLength: content.length,
117 contextItemCount: contextItems.length,
118 newHistoryLength: newHistory.length,
119 });
120
121 return newMessage;
122 }
123
124 /**
125 * Add an assistant message to the history
126 */
127 addAssistantMessage(content: string, toolCalls?: any[]): ChatHistoryItem {
128 const message: any = {
129 role: "assistant",
130 content,
131 };
132
133 if (toolCalls && toolCalls.length > 0) {
134 message.toolCalls = toolCalls;
135 }
136
137 const toolCallStates = toolCalls?.map((tc) => {
138 const id = tc.id;
139 const name = tc.function?.name ?? tc.name;
140 // Prefer explicit string arguments; otherwise stringify object arguments
141 let rawArgStr: string;
142 if (typeof tc.arguments === "string") {
143 rawArgStr = tc.arguments;
144 } else if (typeof tc.function?.arguments === "string") {
145 rawArgStr = tc.function.arguments;
146 } else if (tc.arguments === undefined) {
147 rawArgStr =
148 tc.function?.arguments === undefined
149 ? "{}"
150 : String(tc.function.arguments);
151 } else {
152 rawArgStr = JSON.stringify(tc.arguments);
153 }
154
155 // parsedArgs: prefer object, else parse the string if possible
156 let parsedArgs: any = {};
157 if (tc && typeof tc.arguments === "object" && tc.arguments !== null) {
158 parsedArgs = tc.arguments;
159 } else if (typeof rawArgStr === "string") {
160 try {
161 parsedArgs = JSON.parse(rawArgStr);
162 } catch {
163 parsedArgs = {};
164 }
165 }
166
167 return {
168 toolCallId: id,
169 toolCall: {
170 id,
171 type: "function" as const,
172 function: {
173 name,
174 arguments: rawArgStr,
175 },
176 },
177 status: "generated" as ToolStatus,
178 parsedArgs,
179 };
180 });
181
182 const newMessage = createHistoryItem(message, [], toolCallStates);
183 const newHistory = [...this.currentState.history, newMessage];
184 this.setHistoryInternal(newHistory);
185
186 logger.debug("Added assistant message", {
187 contentLength: content.length,
188 toolCallCount: toolCalls?.length || 0,
189 newHistoryLength: newHistory.length,
190 });
191
192 return newMessage;
193 }
194
195 /**
196 * Add a system message to the history
197 */
198 addSystemMessage(content: string): ChatHistoryItem {
199 const newMessage = createHistoryItem({
200 role: "system",
201 content,
202 });
203
204 const newHistory = [...this.currentState.history, newMessage];
205 this.setHistoryInternal(newHistory);
206
207 logger.debug("Added system message", {
208 contentLength: content.length,
209 newHistoryLength: newHistory.length,
210 });
211
212 return newMessage;
213 }
214
215 /**
216 * Add a generic history item
217 */
218 addHistoryItem(item: ChatHistoryItem): ChatHistoryItem {
219 const newHistory = [...this.currentState.history, item];
220 this.setHistoryInternal(newHistory);
221
222 logger.debug("Added history item", {
223 role: item.message.role,
224 newHistoryLength: newHistory.length,
225 });
226
227 return item;
228 }
229
230 /**
231 * Update a tool call state within a message
232 */
233 updateToolCallState(
234 messageIndex: number,
235 toolCallId: string,
236 updates: Partial<{
237 status: ToolStatus;
238 output: any[];
239 }>,
240 ): void {
241 const newHistory = [...this.currentState.history];
242 const message = newHistory[messageIndex];
243
244 if (!message?.toolCallStates) {
245 logger.warn("No tool call states found at message index", {
246 messageIndex,
247 toolCallId,
248 });
249 return;
250 }
251
252 const toolState = message.toolCallStates.find(
253 (ts) => ts.toolCallId === toolCallId,
254 );
255
256 if (!toolState) {
257 logger.warn("Tool call state not found", {
258 messageIndex,
259 toolCallId,
260 availableIds: message.toolCallStates.map((ts) => ts.toolCallId),
261 });
262 return;
263 }
264
265 // Create a new message with updated tool state (immutable)
266 newHistory[messageIndex] = {
267 ...message,
268 toolCallStates: message.toolCallStates.map((ts) =>
269 ts.toolCallId === toolCallId ? { ...ts, ...updates } : ts,
270 ),
271 };
272
273 this.setHistoryInternal(newHistory);
274
275 logger.debug("Updated tool call state", {
276 messageIndex,
277 toolCallId,
278 updates,
279 });
280 }
281
282 /**
283 * Add a tool result to the history
284 */
285 addToolResult(
286 toolCallId: string,
287 result: string,
288 status: ToolStatus = "done",
289 ): void {
290 // Find the last assistant message with this tool call
291 let targetIndex = -1;
292 for (let i = this.currentState.history.length - 1; i >= 0; i--) {
293 const item = this.currentState.history[i];
294 if (item.message.role === "assistant" && item.toolCallStates) {
295 const hasToolCall = item.toolCallStates.some(
296 (ts) => ts.toolCallId === toolCallId,
297 );
298 if (hasToolCall) {
299 targetIndex = i;
300 break;
301 }
302 }
303 }
304
305 if (targetIndex >= 0) {
306 this.updateToolCallState(targetIndex, toolCallId, {
307 status,
308 output: [
309 {
310 content: result,
311 name: "Tool Result",
312 description: "Tool execution result",
313 },
314 ],
315 });
316 } else {
317 logger.warn("Could not find message for tool result", { toolCallId });
318 }
319 }
320
321 /**
322 * Update a tool's status (e.g., set to "calling" immediately on approval)
323 */
324 updateToolStatus(toolCallId: string, status: ToolStatus): void {
325 // Find the last assistant message with this tool call
326 let targetIndex = -1;
327 for (let i = this.currentState.history.length - 1; i >= 0; i--) {
328 const item = this.currentState.history[i];
329 if (item.message.role === "assistant" && item.toolCallStates) {
330 const hasToolCall = item.toolCallStates.some(
331 (ts) => ts.toolCallId === toolCallId,
332 );
333 if (hasToolCall) {
334 targetIndex = i;
335 break;
336 }
337 }
338 }
339
340 if (targetIndex >= 0) {
341 this.updateToolCallState(targetIndex, toolCallId, { status });
342 } else {
343 logger.warn("Could not find message for tool status update", {
344 toolCallId,
345 status,
346 });
347 }
348 }
349
350 /**
351 * Perform compaction on the history
352 */
353 compact(newHistory: ChatHistoryItem[], compactionIndex: number): void {
354 this.setHistoryInternal(newHistory, { compactionIndex });
355
356 logger.debug("Compacted history", {
357 oldLength: this.currentState.history.length,
358 newLength: newHistory.length,
359 compactionIndex,
360 });
361 }
362
363 /**
364 * Clear the chat history
365 */
366 clear(): void {
367 this.setHistoryInternal([], { compactionIndex: null });
368
369 logger.debug("Cleared chat history");
370 }
371
372 /**
373 * Load a session into the service
374 */
375 async loadSession(sessionId: string): Promise<void> {
376 const session = loadSessionById(sessionId);
377 if (session) {
378 // Load new history without recording undo; set sessionId separately
379 this.setHistoryInternal(session.history, { recordUndo: false });
380 this.setState({ sessionId: session.sessionId });
381
382 logger.debug("Loaded session", {
383 sessionId,
384 historyLength: session.history.length,
385 });
386 } else {
387 logger.warn("Session not found", { sessionId });
388 }
389 }
390
391 /**
392 * Get an immutable copy of the current history
393 */
394 getHistory(): ChatHistoryItem[] {
395 return [...this.currentState.history];
396 }
397
398 /**
399 * Get history for LLM (considering compaction)
400 */
401 getHistoryForLLM(compactionIndex?: number | null): ChatHistoryItem[] {
402 const index = compactionIndex ?? this.currentState.compactionIndex;
403 const full = this.currentState.history;
404 if (index === null || index === undefined || index >= full.length) {
405 return this.getHistory();
406 }
407 const systemMessage = full[0]?.message?.role === "system" ? full[0] : null;
408 const messagesFromCompaction = full.slice(index);
409 return systemMessage && index > 0
410 ? [systemMessage, ...messagesFromCompaction]
411 : messagesFromCompaction;
412 }
413
414 /**
415 * Set the entire history (for remote mode or special cases)
416 */
417 setHistory(history: ChatHistoryItem[]): void {
418 this.setHistoryInternal(history);
419 logger.debug("Set entire history", {
420 historyLength: history.length,
421 });
422 }
423
424 /**
425 * Update compaction index
426 */
427 setCompactionIndex(index: number | null): void {
428 this.setState({
429 compactionIndex: index,
430 });
431
432 logger.debug("Updated compaction index", { index });
433 }
434
435 /**
436 * Find compaction index in history
437 */
438 private findCompactionIndex(history: ChatHistoryItem[]): number | null {
439 const idx = history.findIndex(
440 (item) => item.conversationSummary !== undefined,
441 );
442 return idx === -1 ? null : idx;
443 }
444
445 // Undo/Redo API
446 canUndo(): boolean {
447 return this.past.length > 0;
448 }
449
450 canRedo(): boolean {
451 return this.future.length > 0;
452 }
453
454 undo(): void {
455 if (!this.canUndo()) return;
456 const prev = this.past.pop()!;
457 this.future.push([...this.currentState.history]);
458 this.setHistoryInternal(prev, { recordUndo: false });
459 }
460
461 redo(): void {
462 if (!this.canRedo()) return;
463 const next = this.future.pop()!;
464 this.past.push([...this.currentState.history]);
465 this.setHistoryInternal(next, { recordUndo: false });
466 }
467
468 /**
469 * Get current session ID
470 */
471 getSessionId(): string {
472 return this.currentState.sessionId;
473 }
474
475 /**
476 * Check if in remote mode
477 */
478 isRemoteMode(): boolean {
479 return this.currentState.isRemoteMode;
480 }
481
482 /**
483 * Set remote mode
484 */
485 setRemoteMode(isRemote: boolean): void {
486 this.setState({
487 isRemoteMode: isRemote,
488 });
489 }
490
491 /**
492 * Override getState to ensure deep immutability for history array
493 */
494 getState(): ChatHistoryState {
495 const stateRef = this.currentState;
496 const historyRef = stateRef.history;
497
498 // If neither the state object nor the history reference changed,
499 // return the same memoized snapshot to preserve referential stability
500 if (
501 this._memoSnapshot.snapshot &&
502 this._memoSnapshot.stateRef === stateRef &&
503 this._memoSnapshot.historyRef === historyRef
504 ) {
505 return this._memoSnapshot.snapshot;
506 }
507
508 // Build a memoized snapshot object with getters to:
509 // - keep the outer object reference stable when unchanged
510 // - return a fresh copy of history on each access to prevent external mutation
511 const snapshot = {} as ChatHistoryState;
512 Object.defineProperties(snapshot, {
513 history: {
514 enumerable: true,
515 get: () => [...stateRef.history],
516 },
517 compactionIndex: {
518 enumerable: true,
519 get: () => stateRef.compactionIndex,
520 },
521 sessionId: {
522 enumerable: true,
523 get: () => stateRef.sessionId,
524 },
525 isRemoteMode: {
526 enumerable: true,
527 get: () => stateRef.isRemoteMode,
528 },
529 });
530
531 this._memoSnapshot = { stateRef, historyRef, snapshot };
532 return snapshot;
533 }
534}