| 1 | import type { ChatHistoryItem } from "core/index.js"; |
| 2 | import { describe, it, expect, beforeEach, vi } from "vitest"; |
| 3 | |
| 4 | import { ChatHistoryService } from "./ChatHistoryService.js"; |
| 5 | |
| 6 | // Mock the dependencies |
| 7 | vi.mock("../session.js", () => ({ |
| 8 | updateSessionHistory: vi.fn(), |
| 9 | loadSession: vi.fn(), |
| 10 | createSession: vi.fn((history) => ({ |
| 11 | sessionId: "test-session-id", |
| 12 | history: history || [], |
| 13 | title: "Test Session", |
| 14 | workspaceDirectory: "/test", |
| 15 | })), |
| 16 | })); |
| 17 | |
| 18 | vi.mock("../util/logger.js", () => ({ |
| 19 | logger: { |
| 20 | debug: vi.fn(), |
| 21 | warn: vi.fn(), |
| 22 | error: vi.fn(), |
| 23 | }, |
| 24 | })); |
| 25 | |
| 26 | describe("ChatHistoryService", () => { |
| 27 | let service: ChatHistoryService; |
| 28 | |
| 29 | beforeEach(() => { |
| 30 | service = new ChatHistoryService(); |
| 31 | vi.clearAllMocks(); |
| 32 | }); |
| 33 | |
| 34 | describe("initialization", () => { |
| 35 | it("should initialize with empty state", async () => { |
| 36 | const state = await service.initialize(); |
| 37 | |
| 38 | expect(state.history).toEqual([]); |
| 39 | expect(state.compactionIndex).toBeNull(); |
| 40 | expect(state.sessionId).toBe("test-session-id"); |
| 41 | expect(state.isRemoteMode).toBe(false); |
| 42 | }); |
| 43 | |
| 44 | it("should initialize with provided session", async () => { |
| 45 | const mockHistory: ChatHistoryItem[] = [ |
| 46 | { |
| 47 | message: { role: "user", content: "Hello" }, |
| 48 | contextItems: [], |
| 49 | }, |
| 50 | ]; |
| 51 | |
| 52 | const mockSession = { |
| 53 | sessionId: "custom-session", |
| 54 | history: mockHistory, |
| 55 | title: "Custom Session", |
| 56 | workspaceDirectory: "/custom", |
| 57 | }; |
| 58 | |
| 59 | const state = await service.initialize(mockSession); |
| 60 | |
| 61 | expect(state.history).toEqual(mockHistory); |
| 62 | expect(state.sessionId).toBe("custom-session"); |
| 63 | }); |
| 64 | |
| 65 | it("should detect compaction index on initialization", async () => { |
| 66 | const mockHistory: ChatHistoryItem[] = [ |
| 67 | { |
| 68 | message: { role: "user", content: "First message" }, |
| 69 | contextItems: [], |
| 70 | }, |
| 71 | { |
| 72 | message: { role: "assistant", content: "Summary here" }, |
| 73 | contextItems: [], |
| 74 | conversationSummary: "Summary here", |
| 75 | }, |
| 76 | { |
| 77 | message: { role: "user", content: "After compaction" }, |
| 78 | contextItems: [], |
| 79 | }, |
| 80 | ]; |
| 81 | |
| 82 | const mockSession = { |
| 83 | sessionId: "session-with-compaction", |
| 84 | history: mockHistory, |
| 85 | title: "Compacted Session", |
| 86 | workspaceDirectory: "/compacted", |
| 87 | }; |
| 88 | |
| 89 | const state = await service.initialize(mockSession); |
| 90 | |
| 91 | expect(state.compactionIndex).toBe(1); |
| 92 | }); |
| 93 | |
| 94 | it("should set remote mode on initialization", async () => { |
| 95 | const state = await service.initialize(undefined, true); |
| 96 | |
| 97 | expect(state.isRemoteMode).toBe(true); |
| 98 | }); |
| 99 | }); |
| 100 | |
| 101 | describe("addUserMessage", () => { |
| 102 | beforeEach(async () => { |
| 103 | await service.initialize(); |
| 104 | }); |
| 105 | |
| 106 | it("should add a user message to history", () => { |
| 107 | const message = service.addUserMessage("Hello, world!"); |
| 108 | |
| 109 | expect(message.message.role).toBe("user"); |
| 110 | expect(message.message.content).toBe("Hello, world!"); |
| 111 | |
| 112 | const state = service.getState(); |
| 113 | expect(state.history).toHaveLength(1); |
| 114 | expect(state.history[0]).toBe(message); |
| 115 | }); |
| 116 | |
| 117 | it("should include context items", () => { |
| 118 | const contextItems = [ |
| 119 | { content: "file.txt", name: "File", description: "A text file" }, |
| 120 | ]; |
| 121 | |
| 122 | const message = service.addUserMessage("Check this file", contextItems); |
| 123 | |
| 124 | expect(message.contextItems).toEqual(contextItems); |
| 125 | }); |
| 126 | |
| 127 | it("should emit state change event", () => { |
| 128 | const listener = vi.fn(); |
| 129 | service.on("stateChanged", listener); |
| 130 | |
| 131 | service.addUserMessage("Test message"); |
| 132 | |
| 133 | expect(listener).toHaveBeenCalledTimes(1); |
| 134 | expect(listener).toHaveBeenCalledWith( |
| 135 | expect.objectContaining({ |
| 136 | history: expect.arrayContaining([ |
| 137 | expect.objectContaining({ |
| 138 | message: expect.objectContaining({ |
| 139 | role: "user", |
| 140 | content: "Test message", |
| 141 | }), |
| 142 | }), |
| 143 | ]), |
| 144 | }), |
| 145 | expect.any(Object), |
| 146 | ); |
| 147 | }); |
| 148 | |
| 149 | it("should not save to session in remote mode", async () => { |
| 150 | const { updateSessionHistory } = await import("../session.js"); |
| 151 | |
| 152 | await service.initialize(undefined, true); |
| 153 | service.addUserMessage("Remote message"); |
| 154 | |
| 155 | expect(updateSessionHistory).not.toHaveBeenCalled(); |
| 156 | }); |
| 157 | }); |
| 158 | |
| 159 | describe("addAssistantMessage", () => { |
| 160 | beforeEach(async () => { |
| 161 | await service.initialize(); |
| 162 | }); |
| 163 | |
| 164 | it("should add an assistant message without tool calls", () => { |
| 165 | const message = service.addAssistantMessage("I can help with that"); |
| 166 | |
| 167 | expect(message.message.role).toBe("assistant"); |
| 168 | expect(message.message.content).toBe("I can help with that"); |
| 169 | expect(message.toolCallStates).toBeUndefined(); |
| 170 | }); |
| 171 | |
| 172 | it("should add an assistant message with tool calls", () => { |
| 173 | const toolCalls = [ |
| 174 | { |
| 175 | id: "tool-123", |
| 176 | name: "readFile", |
| 177 | arguments: { path: "test.txt" }, |
| 178 | }, |
| 179 | ]; |
| 180 | |
| 181 | const message = service.addAssistantMessage( |
| 182 | "Let me read that file", |
| 183 | toolCalls, |
| 184 | ); |
| 185 | |
| 186 | expect(message.message.role).toBe("assistant"); |
| 187 | expect(message.toolCallStates).toHaveLength(1); |
| 188 | expect(message.toolCallStates![0].toolCallId).toBe("tool-123"); |
| 189 | expect(message.toolCallStates![0].status).toBe("generated"); |
| 190 | }); |
| 191 | }); |
| 192 | |
| 193 | describe("addSystemMessage", () => { |
| 194 | beforeEach(async () => { |
| 195 | await service.initialize(); |
| 196 | }); |
| 197 | |
| 198 | it("should add a system message", () => { |
| 199 | const message = service.addSystemMessage("System notification"); |
| 200 | |
| 201 | expect(message.message.role).toBe("system"); |
| 202 | expect(message.message.content).toBe("System notification"); |
| 203 | }); |
| 204 | }); |
| 205 | |
| 206 | describe("updateToolCallState", () => { |
| 207 | beforeEach(async () => { |
| 208 | await service.initialize(); |
| 209 | }); |
| 210 | |
| 211 | it("should update tool call state", () => { |
| 212 | // Add assistant message with tool call |
| 213 | const toolCalls = [ |
| 214 | { |
| 215 | id: "tool-456", |
| 216 | name: "writeFile", |
| 217 | arguments: { path: "output.txt", content: "data" }, |
| 218 | }, |
| 219 | ]; |
| 220 | |
| 221 | service.addAssistantMessage("Writing file", toolCalls); |
| 222 | |
| 223 | // Update the tool call state |
| 224 | service.updateToolCallState(0, "tool-456", { |
| 225 | status: "done", |
| 226 | output: [ |
| 227 | { |
| 228 | content: "File written successfully", |
| 229 | name: "Result", |
| 230 | description: "", |
| 231 | }, |
| 232 | ], |
| 233 | }); |
| 234 | |
| 235 | const state = service.getState(); |
| 236 | const toolState = state.history[0].toolCallStates![0]; |
| 237 | |
| 238 | expect(toolState.status).toBe("done"); |
| 239 | expect(toolState.output).toHaveLength(1); |
| 240 | expect(toolState.output![0].content).toBe("File written successfully"); |
| 241 | }); |
| 242 | |
| 243 | it("should handle missing tool call gracefully", () => { |
| 244 | service.addAssistantMessage("No tools here"); |
| 245 | |
| 246 | // Should not throw |
| 247 | service.updateToolCallState(0, "non-existent", { |
| 248 | status: "done", |
| 249 | }); |
| 250 | |
| 251 | // State should remain unchanged |
| 252 | const state = service.getState(); |
| 253 | expect(state.history[0].toolCallStates).toBeUndefined(); |
| 254 | }); |
| 255 | }); |
| 256 | |
| 257 | describe("addToolResult", () => { |
| 258 | beforeEach(async () => { |
| 259 | await service.initialize(); |
| 260 | }); |
| 261 | |
| 262 | it("should add tool result to the correct message", () => { |
| 263 | // Add messages with tool calls |
| 264 | service.addUserMessage("Do something"); |
| 265 | service.addAssistantMessage("Using tool", [ |
| 266 | { id: "tool-789", name: "search", arguments: { query: "test" } }, |
| 267 | ]); |
| 268 | |
| 269 | // Add tool result |
| 270 | service.addToolResult("tool-789", "Search results: found 5 items"); |
| 271 | |
| 272 | const state = service.getState(); |
| 273 | const assistantMessage = state.history[1]; |
| 274 | const toolState = assistantMessage.toolCallStates![0]; |
| 275 | |
| 276 | expect(toolState.status).toBe("done"); |
| 277 | expect(toolState.output![0].content).toBe( |
| 278 | "Search results: found 5 items", |
| 279 | ); |
| 280 | }); |
| 281 | }); |
| 282 | |
| 283 | describe("compact", () => { |
| 284 | beforeEach(async () => { |
| 285 | await service.initialize(); |
| 286 | }); |
| 287 | |
| 288 | it("should compact history and update index", () => { |
| 289 | // Add initial messages |
| 290 | service.addUserMessage("Message 1"); |
| 291 | service.addAssistantMessage("Response 1"); |
| 292 | service.addUserMessage("Message 2"); |
| 293 | service.addAssistantMessage("Response 2"); |
| 294 | |
| 295 | // Create compacted history |
| 296 | const compactedHistory: ChatHistoryItem[] = [ |
| 297 | { |
| 298 | message: { |
| 299 | role: "system", |
| 300 | content: "[Compacted] Summary of messages 1-2", |
| 301 | }, |
| 302 | contextItems: [], |
| 303 | }, |
| 304 | { |
| 305 | message: { role: "user", content: "Message 3" }, |
| 306 | contextItems: [], |
| 307 | }, |
| 308 | ]; |
| 309 | |
| 310 | service.compact(compactedHistory, 0); |
| 311 | |
| 312 | const state = service.getState(); |
| 313 | expect(state.history).toEqual(compactedHistory); |
| 314 | expect(state.compactionIndex).toBe(0); |
| 315 | }); |
| 316 | }); |
| 317 | |
| 318 | describe("clear", () => { |
| 319 | beforeEach(async () => { |
| 320 | await service.initialize(); |
| 321 | }); |
| 322 | |
| 323 | it("should clear all history", () => { |
| 324 | service.addUserMessage("Message"); |
| 325 | service.addAssistantMessage("Response"); |
| 326 | |
| 327 | service.clear(); |
| 328 | |
| 329 | const state = service.getState(); |
| 330 | expect(state.history).toEqual([]); |
| 331 | expect(state.compactionIndex).toBeNull(); |
| 332 | }); |
| 333 | }); |
| 334 | |
| 335 | describe("getHistory and getHistoryForLLM", () => { |
| 336 | beforeEach(async () => { |
| 337 | await service.initialize(); |
| 338 | }); |
| 339 | |
| 340 | it("should return immutable copy of history", () => { |
| 341 | service.addUserMessage("Test"); |
| 342 | |
| 343 | const history1 = service.getHistory(); |
| 344 | const history2 = service.getHistory(); |
| 345 | |
| 346 | expect(history1).not.toBe(history2); // Different arrays |
| 347 | expect(history1).toEqual(history2); // Same content |
| 348 | }); |
| 349 | |
| 350 | it("should return full history when no compaction", () => { |
| 351 | service.addUserMessage("Message 1"); |
| 352 | service.addAssistantMessage("Response 1"); |
| 353 | |
| 354 | const historyForLLM = service.getHistoryForLLM(); |
| 355 | const fullHistory = service.getHistory(); |
| 356 | |
| 357 | expect(historyForLLM).toEqual(fullHistory); |
| 358 | }); |
| 359 | |
| 360 | it("should return history after compaction index", () => { |
| 361 | const history: ChatHistoryItem[] = [ |
| 362 | { |
| 363 | message: { role: "user", content: "Old message" }, |
| 364 | contextItems: [], |
| 365 | }, |
| 366 | { |
| 367 | message: { role: "system", content: "[Compacted] Summary" }, |
| 368 | contextItems: [], |
| 369 | }, |
| 370 | { |
| 371 | message: { role: "user", content: "New message" }, |
| 372 | contextItems: [], |
| 373 | }, |
| 374 | ]; |
| 375 | |
| 376 | service.setHistory(history); |
| 377 | service.setCompactionIndex(1); |
| 378 | |
| 379 | const historyForLLM = service.getHistoryForLLM(); |
| 380 | |
| 381 | expect(historyForLLM).toHaveLength(2); // Compacted message + new message |
| 382 | expect(historyForLLM[0].message.content).toBe("[Compacted] Summary"); |
| 383 | expect(historyForLLM[1].message.content).toBe("New message"); |
| 384 | }); |
| 385 | }); |
| 386 | |
| 387 | describe("setHistory", () => { |
| 388 | beforeEach(async () => { |
| 389 | await service.initialize(); |
| 390 | }); |
| 391 | |
| 392 | it("should set entire history", () => { |
| 393 | const newHistory: ChatHistoryItem[] = [ |
| 394 | { |
| 395 | message: { role: "user", content: "Imported message" }, |
| 396 | contextItems: [], |
| 397 | }, |
| 398 | ]; |
| 399 | |
| 400 | service.setHistory(newHistory); |
| 401 | |
| 402 | const state = service.getState(); |
| 403 | expect(state.history).toEqual(newHistory); |
| 404 | }); |
| 405 | |
| 406 | it("should detect compaction index when setting history", () => { |
| 407 | const historyWithCompaction: ChatHistoryItem[] = [ |
| 408 | { |
| 409 | message: { role: "assistant", content: "old summary" }, |
| 410 | contextItems: [], |
| 411 | conversationSummary: "old summary", |
| 412 | }, |
| 413 | { |
| 414 | message: { role: "user", content: "Recent message" }, |
| 415 | contextItems: [], |
| 416 | }, |
| 417 | ]; |
| 418 | |
| 419 | service.setHistory(historyWithCompaction); |
| 420 | |
| 421 | const state = service.getState(); |
| 422 | expect(state.compactionIndex).toBe(0); |
| 423 | }); |
| 424 | }); |
| 425 | |
| 426 | describe("undo/redo", () => { |
| 427 | beforeEach(async () => { |
| 428 | await service.initialize(); |
| 429 | }); |
| 430 | |
| 431 | it("should undo last change and redo it", () => { |
| 432 | service.addUserMessage("A"); |
| 433 | service.addAssistantMessage("B"); |
| 434 | |
| 435 | expect(service.getState().history.map((m) => m.message.content)).toEqual([ |
| 436 | "A", |
| 437 | "B", |
| 438 | ]); |
| 439 | |
| 440 | expect(service.canUndo()).toBe(true); |
| 441 | service.undo(); |
| 442 | expect(service.getState().history.map((m) => m.message.content)).toEqual([ |
| 443 | "A", |
| 444 | ]); |
| 445 | |
| 446 | expect(service.canRedo()).toBe(true); |
| 447 | service.redo(); |
| 448 | expect(service.getState().history.map((m) => m.message.content)).toEqual([ |
| 449 | "A", |
| 450 | "B", |
| 451 | ]); |
| 452 | }); |
| 453 | |
| 454 | it("should support undoing tool state updates", () => { |
| 455 | service.addAssistantMessage("Using tool", [ |
| 456 | { id: "t1", name: "Read", arguments: { path: "file" } }, |
| 457 | ]); |
| 458 | const before = service.getHistory(); |
| 459 | service.addToolResult("t1", "ok", "done"); |
| 460 | const after = service.getHistory(); |
| 461 | |
| 462 | expect(after[0].toolCallStates?.[0].status).toBe("done"); |
| 463 | service.undo(); |
| 464 | const undone = service.getHistory(); |
| 465 | expect(undone[0].toolCallStates?.[0].status).toBe( |
| 466 | before[0].toolCallStates?.[0].status, |
| 467 | ); |
| 468 | }); |
| 469 | }); |
| 470 | |
| 471 | describe("immutability", () => { |
| 472 | beforeEach(async () => { |
| 473 | await service.initialize(); |
| 474 | }); |
| 475 | |
| 476 | it("should not allow external mutation of state", () => { |
| 477 | service.addUserMessage("Test"); |
| 478 | |
| 479 | const state = service.getState(); |
| 480 | const originalLength = state.history.length; |
| 481 | |
| 482 | // Try to mutate |
| 483 | state.history.push({ |
| 484 | message: { role: "user", content: "Hacked!" }, |
| 485 | contextItems: [], |
| 486 | }); |
| 487 | |
| 488 | // Check that internal state wasn't affected |
| 489 | const newState = service.getState(); |
| 490 | expect(newState.history).toHaveLength(originalLength); |
| 491 | }); |
| 492 | |
| 493 | it("should not allow mutation through getHistory", () => { |
| 494 | service.addUserMessage("Test"); |
| 495 | |
| 496 | const history = service.getHistory(); |
| 497 | const originalLength = history.length; |
| 498 | |
| 499 | // Try to mutate |
| 500 | history.push({ |
| 501 | message: { role: "user", content: "Hacked!" }, |
| 502 | contextItems: [], |
| 503 | }); |
| 504 | |
| 505 | // Check that internal state wasn't affected |
| 506 | const newHistory = service.getHistory(); |
| 507 | expect(newHistory).toHaveLength(originalLength); |
| 508 | }); |
| 509 | }); |
| 510 | |
| 511 | describe("event emissions", () => { |
| 512 | beforeEach(async () => { |
| 513 | await service.initialize(); |
| 514 | }); |
| 515 | |
| 516 | it("should emit stateChanged on every update", () => { |
| 517 | const listener = vi.fn(); |
| 518 | service.on("stateChanged", listener); |
| 519 | |
| 520 | service.addUserMessage("Message 1"); |
| 521 | service.addAssistantMessage("Response 1"); |
| 522 | service.addSystemMessage("System"); |
| 523 | service.clear(); |
| 524 | |
| 525 | expect(listener).toHaveBeenCalledTimes(4); |
| 526 | }); |
| 527 | |
| 528 | it("should provide old and new state in event", () => { |
| 529 | const listener = vi.fn(); |
| 530 | service.on("stateChanged", listener); |
| 531 | |
| 532 | service.addUserMessage("Test"); |
| 533 | |
| 534 | expect(listener).toHaveBeenCalledWith( |
| 535 | expect.objectContaining({ |
| 536 | history: expect.arrayContaining([ |
| 537 | expect.objectContaining({ |
| 538 | message: expect.objectContaining({ content: "Test" }), |
| 539 | }), |
| 540 | ]), |
| 541 | }), |
| 542 | expect.objectContaining({ |
| 543 | history: [], |
| 544 | }), |
| 545 | ); |
| 546 | }); |
| 547 | }); |
| 548 | }); |