diff --git a/extensions/cli/CHAT_HISTORY_SERVICE_MIGRATION_PLAN.md b/extensions/cli/CHAT_HISTORY_SERVICE_MIGRATION_PLAN.md new file mode 100644 index 000000000..a580ff7a9 --- /dev/null +++ b/extensions/cli/CHAT_HISTORY_SERVICE_MIGRATION_PLAN.md @@ -0,0 +1,381 @@ +# ChatHistoryService Migration Plan + +## Overview + +This document outlines a gradual migration plan to move from the current mixed state management approach (React state + direct mutations) to a centralized `ChatHistoryService` that acts as the single source of truth for chat history. + +## Current State Analysis + +### Problems +- **Duplicate state**: Chat history exists in both React state (`useState`) and is directly mutated in arrays +- **Direct mutations**: `handleToolCalls.ts` uses `chatHistory.push()` bypassing React +- **Inconsistent updates**: Mix of `setChatHistory` callbacks and direct array modifications +- **Testing difficulties**: Hard to test and mock due to mixed patterns +- **Race conditions**: Potential for state inconsistencies + +### Affected Files +- `src/ui/hooks/useChat.ts` - Main hook with React state +- `src/stream/handleToolCalls.ts` - Direct array mutations +- `src/stream/streamChatResponse.ts` - Mixed patterns +- `src/commands/serve.ts` - Direct mutations in remote mode +- `src/session.ts` - Session management + +## Migration Strategy + +### Phase 1: Create ChatHistoryService (Day 1) +**Goal**: Establish the service foundation without breaking existing code + +#### 1.1 Create Service Implementation +```typescript +// src/services/ChatHistoryService.ts +export interface ChatHistoryState { + history: ChatHistoryItem[]; + compactionIndex: number | null; + sessionId: string; + isRemoteMode: boolean; +} + +export class ChatHistoryService extends BaseService { + // Implementation details below +} +``` + +#### 1.2 Service Methods to Implement +- `addUserMessage(content, contextItems)` +- `addAssistantMessage(content, toolCalls?)` +- `addSystemMessage(content)` +- `updateToolCallState(messageIndex, toolCallId, updates)` +- `addToolResult(toolCallId, result, status)` +- `compact(newHistory, compactionIndex)` +- `clear()` +- `loadSession(sessionId)` +- `getHistory()` - Returns immutable copy +- `getHistoryForLLM(compactionIndex?)` - For streaming + +#### 1.3 Register Service +- Add to `src/services/index.ts` +- Add to ServiceContainer initialization +- Ensure proper initialization order + +#### 1.4 Write Unit Tests +- Test all service methods +- Test event emissions +- Test immutability guarantees +- Test session integration + +**Deliverable**: Working service with tests, no integration yet + +### Phase 2: Wrapper Integration (Day 1-2) +**Goal**: Wrap existing code to use service without changing behavior + +#### 2.1 Create Compatibility Layer +```typescript +// src/services/ChatHistoryCompatibility.ts +export function createChatHistoryProxy(service: ChatHistoryService) { + return new Proxy([], { + get(target, prop) { + if (prop === 'push') { + return (item) => service.addHistoryItem(item); + } + // Delegate reads to service.getHistory() + const history = service.getHistory(); + return history[prop]; + } + }); +} +``` + +#### 2.2 Update useChat Hook +- Initialize ChatHistoryService in useChat +- Keep existing `setChatHistory` for now +- Sync service changes to React state: +```typescript +// In useChat.ts +const chatHistoryService = useService('chatHistory'); + +useEffect(() => { + if (chatHistoryService.state === 'ready') { + setChatHistory(chatHistoryService.value.history); + } +}, [chatHistoryService]); +``` + +#### 2.3 Add Service Methods to Mirror State Updates +- Wherever `setChatHistory` is called, also update service +- This creates temporary duplication but maintains compatibility + +**Deliverable**: Service running in parallel with existing state + +### Phase 3: Migrate Stream Processing (Day 2) +**Goal**: Update streaming functions to use service + +#### 3.1 Update handleToolCalls.ts +- Replace `chatHistory.push()` with service methods: +```typescript +// Before: +chatHistory.push(createHistoryItem(...)); + +// After: +await chatHistoryService.addHistoryItem(createHistoryItem(...)); +``` + +#### 3.2 Update streamChatResponse.ts +- Pass service instance instead of arrays +- Use service methods for all updates +- Remove direct array access + +#### 3.3 Update Stream Callbacks +- Modify `createStreamCallbacks` in `useChat.stream.helpers.ts` +- Use service methods instead of `setChatHistory` +- Ensure proper event handling + +#### 3.4 Test Streaming +- Test tool execution flow +- Test interruption handling +- Test auto-compaction +- Verify no direct mutations remain + +**Deliverable**: All streaming using service, no direct mutations + +### Phase 4: Remove React State Duplication (Day 2-3) +**Goal**: Remove `useState` and rely solely on service + +#### 4.1 Update useChat to Use Service Directly +```typescript +// Remove: +const [chatHistory, setChatHistory] = useState(...); + +// Replace with: +const { value: chatHistoryState, state } = useService('chatHistory'); +const chatHistory = chatHistoryState?.history || []; +``` + +#### 4.2 Update All Components +- Update components that receive `chatHistory` prop +- Ensure they handle potential undefined/loading states +- Update any direct `setChatHistory` calls + +#### 4.3 Remove Compatibility Layer +- Remove the proxy wrapper +- Remove temporary sync code +- Clean up unused imports + +**Deliverable**: Single source of truth established + +### Phase 5: Optimize and Enhance (Day 3) +**Goal**: Add optimizations and missing features + +#### 5.1 Performance Optimizations +- Implement efficient diffing for large histories +- Add memoization where needed +- Optimize re-render triggers + +#### 5.2 Add Advanced Features +- Implement undo/redo capability +- Add history branching for explorations +- Improve session management integration +- Add persistence strategies + +#### 5.3 Remote Mode Integration +- Update `serve.ts` to use service +- Ensure remote sync works with service +- Test remote mode thoroughly + +#### 5.4 Update Documentation +- Update code comments +- Update AGENTS.md with new patterns +- Create service usage examples + +**Deliverable**: Optimized service with full feature set + +### Phase 6: Validation and Cleanup (Day 3-4) +**Goal**: Ensure migration is complete and stable + +#### 6.1 Comprehensive Testing +- Run all existing tests +- Add integration tests for service +- Test all user flows (TUI, headless, remote) +- Performance testing with large histories + +#### 6.2 Code Cleanup +- Remove all deprecated code +- Update imports and types +- Run linting and formatting +- Update type definitions + +#### 6.3 Migration Verification Checklist +- [ ] No direct array mutations remain +- [ ] All tests passing +- [ ] Service handles all chat operations +- [ ] React components update properly +- [ ] Session management integrated +- [ ] Remote mode working +- [ ] Performance acceptable +- [ ] No console errors/warnings + +## Rollback Plan + +If issues arise during migration: + +1. **Phase 1-2**: No impact, service runs in parallel +2. **Phase 3**: Revert stream processing changes, keep service +3. **Phase 4**: Revert to dual state temporarily +4. **Phase 5-6**: Feature flags for new capabilities + +## Testing Strategy + +### Unit Tests +- Service methods individually +- Event emissions +- State immutability +- Error handling + +### Integration Tests +- Service + React hooks +- Service + streaming +- Service + sessions +- Service + remote mode + +### E2E Tests +- Full chat flows +- Tool execution +- Mode switching +- Session resume +- Interruption handling + +## Success Metrics + +1. **No regressions**: All existing functionality works +2. **Performance**: No noticeable slowdown +3. **Maintainability**: Cleaner, more testable code +4. **Reliability**: No state inconsistencies +5. **Developer experience**: Easier to understand and modify + +## Risk Mitigation + +### High Risk Areas +1. **Streaming integration**: Most complex change + - Mitigation: Extensive testing, gradual rollout + +2. **Remote mode**: Different state management + - Mitigation: Test thoroughly, maintain compatibility + +3. **Performance**: Large histories might cause issues + - Mitigation: Profiling, optimization, lazy loading + +### Monitoring +- Add logging for state transitions +- Monitor performance metrics +- Track error rates +- User feedback collection + +## Timeline + +- **Day 1**: Phase 1-2 (Service creation, wrapper) +- **Day 2**: Phase 3-4 (Stream migration, remove duplication) +- **Day 3**: Phase 5 (Optimization, features) +- **Day 4**: Phase 6 (Validation, cleanup) + +Total: 4 days with buffer for issues + +## Implementation Checklist + +### Pre-Migration +- [ ] Current state documented +- [ ] All stakeholders informed +- [ ] Test environment ready +- [ ] Rollback plan confirmed + +### Phase 1 +- [ ] ChatHistoryService created +- [ ] Unit tests written +- [ ] Service registered +- [ ] No breaking changes + +### Phase 2 +- [ ] Compatibility layer working +- [ ] useChat integrated +- [ ] Parallel operation verified +- [ ] No regressions + +### Phase 3 +- [ ] Stream processing migrated +- [ ] No direct mutations +- [ ] Tool handling updated +- [ ] Tests passing + +### Phase 4 +- [ ] React state removed +- [ ] Service-only operation +- [ ] Components updated +- [ ] Performance acceptable + +### Phase 5 +- [ ] Optimizations implemented +- [ ] Features added +- [ ] Remote mode working +- [ ] Documentation updated + +### Phase 6 +- [ ] All tests passing +- [ ] Code cleaned up +- [ ] Migration complete +- [ ] Team sign-off + +## Post-Migration + +1. Monitor for issues for 1 week +2. Gather performance metrics +3. Document lessons learned +4. Plan future enhancements +5. Knowledge transfer to team + +## Appendix: Code Examples + +### Service Method Example +```typescript +class ChatHistoryService extends BaseService { + addUserMessage(content: string, contextItems: any[] = []) { + const newMessage: ChatHistoryItem = { + message: { role: 'user', content }, + contextItems + }; + + const newHistory = [...this.currentState.history, newMessage]; + this.setState({ + ...this.currentState, + history: newHistory + }); + + // Auto-save to session + updateSessionHistory(newHistory); + + return newMessage; + } +} +``` + +### React Integration Example +```typescript +function ChatComponent() { + const { value: chatState, state } = useService('chatHistory'); + + if (state === 'loading') return ; + if (state === 'error') return ; + + const history = chatState?.history || []; + + return ; +} +``` + +### Migration Pattern Example +```typescript +// Before: +chatHistory.push(newMessage); +setChatHistory([...chatHistory]); + +// After: +chatHistoryService.addMessage(newMessage); +// React auto-updates via useService hook +``` \ No newline at end of file diff --git a/extensions/cli/src/services/ChatHistoryService.test.ts b/extensions/cli/src/services/ChatHistoryService.test.ts new file mode 100644 index 000000000..43567fb39 --- /dev/null +++ b/extensions/cli/src/services/ChatHistoryService.test.ts @@ -0,0 +1,487 @@ +import type { ChatHistoryItem } from "core/index.js"; +import { describe, it, expect, beforeEach, vi } from "vitest"; + +import { ChatHistoryService } from "./ChatHistoryService.js"; + +// Mock the dependencies +vi.mock("../session.js", () => ({ + updateSessionHistory: vi.fn(), + loadSession: vi.fn(), + createSession: vi.fn((history) => ({ + sessionId: "test-session-id", + history: history || [], + title: "Test Session", + workspaceDirectory: "/test", + })), +})); + +vi.mock("../util/logger.js", () => ({ + logger: { + debug: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + }, +})); + +describe("ChatHistoryService", () => { + let service: ChatHistoryService; + + beforeEach(() => { + service = new ChatHistoryService(); + vi.clearAllMocks(); + }); + + describe("initialization", () => { + it("should initialize with empty state", async () => { + const state = await service.initialize(); + + expect(state.history).toEqual([]); + expect(state.compactionIndex).toBeNull(); + expect(state.sessionId).toBe("test-session-id"); + expect(state.isRemoteMode).toBe(false); + }); + + it("should initialize with provided session", async () => { + const mockHistory: ChatHistoryItem[] = [ + { + message: { role: "user", content: "Hello" }, + contextItems: [], + }, + ]; + + const mockSession = { + sessionId: "custom-session", + history: mockHistory, + title: "Custom Session", + workspaceDirectory: "/custom", + }; + + const state = await service.initialize(mockSession); + + expect(state.history).toEqual(mockHistory); + expect(state.sessionId).toBe("custom-session"); + }); + + it("should detect compaction index on initialization", async () => { + const mockHistory: ChatHistoryItem[] = [ + { + message: { role: "user", content: "First message" }, + contextItems: [], + }, + { + message: { role: "system", content: "[Compacted] Summary of conversation" }, + contextItems: [], + }, + { + message: { role: "user", content: "After compaction" }, + contextItems: [], + }, + ]; + + const mockSession = { + sessionId: "session-with-compaction", + history: mockHistory, + title: "Compacted Session", + workspaceDirectory: "/compacted", + }; + + const state = await service.initialize(mockSession); + + expect(state.compactionIndex).toBe(1); + }); + + it("should set remote mode on initialization", async () => { + const state = await service.initialize(undefined, true); + + expect(state.isRemoteMode).toBe(true); + }); + }); + + describe("addUserMessage", () => { + beforeEach(async () => { + await service.initialize(); + }); + + it("should add a user message to history", () => { + const message = service.addUserMessage("Hello, world!"); + + expect(message.message.role).toBe("user"); + expect(message.message.content).toBe("Hello, world!"); + + const state = service.getState(); + expect(state.history).toHaveLength(1); + expect(state.history[0]).toBe(message); + }); + + it("should include context items", () => { + const contextItems = [ + { content: "file.txt", name: "File", description: "A text file" }, + ]; + + const message = service.addUserMessage("Check this file", contextItems); + + expect(message.contextItems).toEqual(contextItems); + }); + + it("should emit state change event", () => { + const listener = vi.fn(); + service.on("stateChanged", listener); + + service.addUserMessage("Test message"); + + expect(listener).toHaveBeenCalledTimes(1); + expect(listener).toHaveBeenCalledWith( + expect.objectContaining({ + history: expect.arrayContaining([ + expect.objectContaining({ + message: expect.objectContaining({ + role: "user", + content: "Test message", + }), + }), + ]), + }), + expect.any(Object) + ); + }); + + it("should not save to session in remote mode", async () => { + const { updateSessionHistory } = await import("../session.js"); + + await service.initialize(undefined, true); + service.addUserMessage("Remote message"); + + expect(updateSessionHistory).not.toHaveBeenCalled(); + }); + }); + + describe("addAssistantMessage", () => { + beforeEach(async () => { + await service.initialize(); + }); + + it("should add an assistant message without tool calls", () => { + const message = service.addAssistantMessage("I can help with that"); + + expect(message.message.role).toBe("assistant"); + expect(message.message.content).toBe("I can help with that"); + expect(message.toolCallStates).toBeUndefined(); + }); + + it("should add an assistant message with tool calls", () => { + const toolCalls = [ + { + id: "tool-123", + name: "readFile", + arguments: { path: "test.txt" }, + }, + ]; + + const message = service.addAssistantMessage("Let me read that file", toolCalls); + + expect(message.message.role).toBe("assistant"); + expect(message.toolCallStates).toHaveLength(1); + expect(message.toolCallStates![0].toolCallId).toBe("tool-123"); + expect(message.toolCallStates![0].status).toBe("generated"); + }); + }); + + describe("addSystemMessage", () => { + beforeEach(async () => { + await service.initialize(); + }); + + it("should add a system message", () => { + const message = service.addSystemMessage("System notification"); + + expect(message.message.role).toBe("system"); + expect(message.message.content).toBe("System notification"); + }); + }); + + describe("updateToolCallState", () => { + beforeEach(async () => { + await service.initialize(); + }); + + it("should update tool call state", () => { + // Add assistant message with tool call + const toolCalls = [ + { + id: "tool-456", + name: "writeFile", + arguments: { path: "output.txt", content: "data" }, + }, + ]; + + service.addAssistantMessage("Writing file", toolCalls); + + // Update the tool call state + service.updateToolCallState(0, "tool-456", { + status: "done", + output: [{ content: "File written successfully", name: "Result", description: "" }], + }); + + const state = service.getState(); + const toolState = state.history[0].toolCallStates![0]; + + expect(toolState.status).toBe("done"); + expect(toolState.output).toHaveLength(1); + expect(toolState.output![0].content).toBe("File written successfully"); + }); + + it("should handle missing tool call gracefully", () => { + service.addAssistantMessage("No tools here"); + + // Should not throw + service.updateToolCallState(0, "non-existent", { + status: "done", + }); + + // State should remain unchanged + const state = service.getState(); + expect(state.history[0].toolCallStates).toBeUndefined(); + }); + }); + + describe("addToolResult", () => { + beforeEach(async () => { + await service.initialize(); + }); + + it("should add tool result to the correct message", () => { + // Add messages with tool calls + service.addUserMessage("Do something"); + service.addAssistantMessage("Using tool", [ + { id: "tool-789", name: "search", arguments: { query: "test" } }, + ]); + + // Add tool result + service.addToolResult("tool-789", "Search results: found 5 items"); + + const state = service.getState(); + const assistantMessage = state.history[1]; + const toolState = assistantMessage.toolCallStates![0]; + + expect(toolState.status).toBe("done"); + expect(toolState.output![0].content).toBe("Search results: found 5 items"); + }); + }); + + describe("compact", () => { + beforeEach(async () => { + await service.initialize(); + }); + + it("should compact history and update index", () => { + // Add initial messages + service.addUserMessage("Message 1"); + service.addAssistantMessage("Response 1"); + service.addUserMessage("Message 2"); + service.addAssistantMessage("Response 2"); + + // Create compacted history + const compactedHistory: ChatHistoryItem[] = [ + { + message: { role: "system", content: "[Compacted] Summary of messages 1-2" }, + contextItems: [], + }, + { + message: { role: "user", content: "Message 3" }, + contextItems: [], + }, + ]; + + service.compact(compactedHistory, 0); + + const state = service.getState(); + expect(state.history).toEqual(compactedHistory); + expect(state.compactionIndex).toBe(0); + }); + }); + + describe("clear", () => { + beforeEach(async () => { + await service.initialize(); + }); + + it("should clear all history", () => { + service.addUserMessage("Message"); + service.addAssistantMessage("Response"); + + service.clear(); + + const state = service.getState(); + expect(state.history).toEqual([]); + expect(state.compactionIndex).toBeNull(); + }); + }); + + describe("getHistory and getHistoryForLLM", () => { + beforeEach(async () => { + await service.initialize(); + }); + + it("should return immutable copy of history", () => { + service.addUserMessage("Test"); + + const history1 = service.getHistory(); + const history2 = service.getHistory(); + + expect(history1).not.toBe(history2); // Different arrays + expect(history1).toEqual(history2); // Same content + }); + + it("should return full history when no compaction", () => { + service.addUserMessage("Message 1"); + service.addAssistantMessage("Response 1"); + + const historyForLLM = service.getHistoryForLLM(); + const fullHistory = service.getHistory(); + + expect(historyForLLM).toEqual(fullHistory); + }); + + it("should return history after compaction index", () => { + const history: ChatHistoryItem[] = [ + { + message: { role: "user", content: "Old message" }, + contextItems: [], + }, + { + message: { role: "system", content: "[Compacted] Summary" }, + contextItems: [], + }, + { + message: { role: "user", content: "New message" }, + contextItems: [], + }, + ]; + + service.setHistory(history); + service.setCompactionIndex(1); + + const historyForLLM = service.getHistoryForLLM(); + + expect(historyForLLM).toHaveLength(2); // Compacted message + new message + expect(historyForLLM[0].message.content).toBe("[Compacted] Summary"); + expect(historyForLLM[1].message.content).toBe("New message"); + }); + }); + + describe("setHistory", () => { + beforeEach(async () => { + await service.initialize(); + }); + + it("should set entire history", () => { + const newHistory: ChatHistoryItem[] = [ + { + message: { role: "user", content: "Imported message" }, + contextItems: [], + }, + ]; + + service.setHistory(newHistory); + + const state = service.getState(); + expect(state.history).toEqual(newHistory); + }); + + it("should detect compaction index when setting history", () => { + const historyWithCompaction: ChatHistoryItem[] = [ + { + message: { role: "system", content: "[Compacted] Old stuff" }, + contextItems: [], + }, + { + message: { role: "user", content: "Recent message" }, + contextItems: [], + }, + ]; + + service.setHistory(historyWithCompaction); + + const state = service.getState(); + expect(state.compactionIndex).toBe(0); + }); + }); + + describe("immutability", () => { + beforeEach(async () => { + await service.initialize(); + }); + + it("should not allow external mutation of state", () => { + service.addUserMessage("Test"); + + const state = service.getState(); + const originalLength = state.history.length; + + // Try to mutate + state.history.push({ + message: { role: "user", content: "Hacked!" }, + contextItems: [], + }); + + // Check that internal state wasn't affected + const newState = service.getState(); + expect(newState.history).toHaveLength(originalLength); + }); + + it("should not allow mutation through getHistory", () => { + service.addUserMessage("Test"); + + const history = service.getHistory(); + const originalLength = history.length; + + // Try to mutate + history.push({ + message: { role: "user", content: "Hacked!" }, + contextItems: [], + }); + + // Check that internal state wasn't affected + const newHistory = service.getHistory(); + expect(newHistory).toHaveLength(originalLength); + }); + }); + + describe("event emissions", () => { + beforeEach(async () => { + await service.initialize(); + }); + + it("should emit stateChanged on every update", () => { + const listener = vi.fn(); + service.on("stateChanged", listener); + + service.addUserMessage("Message 1"); + service.addAssistantMessage("Response 1"); + service.addSystemMessage("System"); + service.clear(); + + expect(listener).toHaveBeenCalledTimes(4); + }); + + it("should provide old and new state in event", () => { + const listener = vi.fn(); + service.on("stateChanged", listener); + + service.addUserMessage("Test"); + + expect(listener).toHaveBeenCalledWith( + expect.objectContaining({ + history: expect.arrayContaining([ + expect.objectContaining({ + message: expect.objectContaining({ content: "Test" }), + }), + ]), + }), + expect.objectContaining({ + history: [], + }) + ); + }); + }); +}); \ No newline at end of file diff --git a/extensions/cli/src/services/ChatHistoryService.ts b/extensions/cli/src/services/ChatHistoryService.ts new file mode 100644 index 000000000..ed0813e9a --- /dev/null +++ b/extensions/cli/src/services/ChatHistoryService.ts @@ -0,0 +1,429 @@ +import type { ChatHistoryItem, ToolStatus } from "core/index.js"; +import { createHistoryItem } from "core/util/messageConversion.js"; + +import { updateSessionHistory, loadSessionById, createSession } from "../session.js"; +import { logger } from "../util/logger.js"; + +import { BaseService } from "./BaseService.js"; + +/** + * State managed by the ChatHistoryService + */ +export interface ChatHistoryState { + history: ChatHistoryItem[]; + compactionIndex: number | null; + sessionId: string; + isRemoteMode: boolean; +} + +/** + * Service for managing chat history as the single source of truth + * Provides immutable updates and automatic React integration via events + */ +export class ChatHistoryService extends BaseService { + constructor() { + super("ChatHistoryService", { + history: [], + compactionIndex: null, + sessionId: "", + isRemoteMode: false, + }); + } + + /** + * Initialize the service with optional session + */ + async doInitialize(session?: any, isRemoteMode = false): Promise { + const activeSession = session || createSession([]); + + logger.debug("Initializing ChatHistoryService", { + sessionId: activeSession.sessionId, + historyLength: activeSession.history.length, + isRemoteMode, + }); + + return { + history: activeSession.history || [], + compactionIndex: this.findCompactionIndex(activeSession.history || []), + sessionId: activeSession.sessionId, + isRemoteMode, + }; + } + + /** + * Add a user message to the history + */ + addUserMessage(content: string, contextItems: any[] = []): ChatHistoryItem { + const newMessage = createHistoryItem({ + role: "user", + content, + }, contextItems); + + const newHistory = [...this.currentState.history, newMessage]; + this.setState({ + history: newHistory, + }); + + // Auto-save to session if not in remote mode + if (!this.currentState.isRemoteMode) { + updateSessionHistory(newHistory); + } + + logger.debug("Added user message", { + contentLength: content.length, + contextItemCount: contextItems.length, + newHistoryLength: newHistory.length, + }); + + return newMessage; + } + + /** + * Add an assistant message to the history + */ + addAssistantMessage(content: string, toolCalls?: any[]): ChatHistoryItem { + const message: any = { + role: "assistant", + content, + }; + + if (toolCalls && toolCalls.length > 0) { + message.toolCalls = toolCalls; + } + + const toolCallStates = toolCalls?.map((tc) => ({ + toolCallId: tc.id, + toolCall: { + id: tc.id, + type: "function" as const, + function: { + name: tc.name || tc.function?.name, + arguments: typeof tc.arguments === "string" + ? tc.arguments + : JSON.stringify(tc.arguments || tc.function?.arguments || {}), + }, + }, + status: "generated" as ToolStatus, + parsedArgs: typeof tc.arguments === "object" ? tc.arguments : {}, + })); + + const newMessage = createHistoryItem(message, [], toolCallStates); + const newHistory = [...this.currentState.history, newMessage]; + + this.setState({ + history: newHistory, + }); + + if (!this.currentState.isRemoteMode) { + updateSessionHistory(newHistory); + } + + logger.debug("Added assistant message", { + contentLength: content.length, + toolCallCount: toolCalls?.length || 0, + newHistoryLength: newHistory.length, + }); + + return newMessage; + } + + /** + * Add a system message to the history + */ + addSystemMessage(content: string): ChatHistoryItem { + const newMessage = createHistoryItem({ + role: "system", + content, + }); + + const newHistory = [...this.currentState.history, newMessage]; + this.setState({ + history: newHistory, + }); + + if (!this.currentState.isRemoteMode) { + updateSessionHistory(newHistory); + } + + logger.debug("Added system message", { + contentLength: content.length, + newHistoryLength: newHistory.length, + }); + + return newMessage; + } + + /** + * Add a generic history item (for compatibility during migration) + */ + addHistoryItem(item: ChatHistoryItem): ChatHistoryItem { + const newHistory = [...this.currentState.history, item]; + this.setState({ + history: newHistory, + }); + + if (!this.currentState.isRemoteMode) { + updateSessionHistory(newHistory); + } + + logger.debug("Added history item", { + role: item.message.role, + newHistoryLength: newHistory.length, + }); + + return item; + } + + /** + * Update a tool call state within a message + */ + updateToolCallState( + messageIndex: number, + toolCallId: string, + updates: Partial<{ + status: ToolStatus; + output: any[]; + }> + ): void { + const newHistory = [...this.currentState.history]; + const message = newHistory[messageIndex]; + + if (!message?.toolCallStates) { + logger.warn("No tool call states found at message index", { + messageIndex, + toolCallId, + }); + return; + } + + const toolState = message.toolCallStates.find( + (ts) => ts.toolCallId === toolCallId + ); + + if (!toolState) { + logger.warn("Tool call state not found", { + messageIndex, + toolCallId, + availableIds: message.toolCallStates.map((ts) => ts.toolCallId), + }); + return; + } + + // Create a new message with updated tool state (immutable) + newHistory[messageIndex] = { + ...message, + toolCallStates: message.toolCallStates.map((ts) => + ts.toolCallId === toolCallId + ? { ...ts, ...updates } + : ts + ), + }; + + this.setState({ + history: newHistory, + }); + + if (!this.currentState.isRemoteMode) { + updateSessionHistory(newHistory); + } + + logger.debug("Updated tool call state", { + messageIndex, + toolCallId, + updates, + }); + } + + /** + * Add a tool result to the history + */ + addToolResult(toolCallId: string, result: string, status: ToolStatus = "done"): void { + // Find the last assistant message with this tool call + let targetIndex = -1; + for (let i = this.currentState.history.length - 1; i >= 0; i--) { + const item = this.currentState.history[i]; + if (item.message.role === "assistant" && item.toolCallStates) { + const hasToolCall = item.toolCallStates.some( + (ts) => ts.toolCallId === toolCallId + ); + if (hasToolCall) { + targetIndex = i; + break; + } + } + } + + if (targetIndex >= 0) { + this.updateToolCallState(targetIndex, toolCallId, { + status, + output: [{ + content: result, + name: "Tool Result", + description: "Tool execution result", + }], + }); + } else { + logger.warn("Could not find message for tool result", { toolCallId }); + } + } + + /** + * Perform compaction on the history + */ + compact(newHistory: ChatHistoryItem[], compactionIndex: number): void { + this.setState({ + history: newHistory, + compactionIndex, + }); + + if (!this.currentState.isRemoteMode) { + updateSessionHistory(newHistory); + } + + logger.debug("Compacted history", { + oldLength: this.currentState.history.length, + newLength: newHistory.length, + compactionIndex, + }); + } + + /** + * Clear the chat history + */ + clear(): void { + this.setState({ + history: [], + compactionIndex: null, + }); + + if (!this.currentState.isRemoteMode) { + updateSessionHistory([]); + } + + logger.debug("Cleared chat history"); + } + + /** + * Load a session into the service + */ + async loadSession(sessionId: string): Promise { + const session = loadSessionById(sessionId); + if (session) { + this.setState({ + history: session.history, + sessionId: session.sessionId, + compactionIndex: this.findCompactionIndex(session.history), + }); + + logger.debug("Loaded session", { + sessionId, + historyLength: session.history.length, + }); + } else { + logger.warn("Session not found", { sessionId }); + } + } + + /** + * Get an immutable copy of the current history + */ + getHistory(): ChatHistoryItem[] { + return [...this.currentState.history]; + } + + /** + * Get history for LLM (considering compaction) + */ + getHistoryForLLM(compactionIndex?: number | null): ChatHistoryItem[] { + const index = compactionIndex ?? this.currentState.compactionIndex; + + if (index !== null && index !== undefined && index < this.currentState.history.length) { + // Return only messages after compaction, plus the compacted summary + return this.currentState.history.slice(index); + } + + return this.getHistory(); + } + + /** + * Set the entire history (for remote mode or special cases) + */ + setHistory(history: ChatHistoryItem[]): void { + this.setState({ + history: [...history], + compactionIndex: this.findCompactionIndex(history), + }); + + if (!this.currentState.isRemoteMode) { + updateSessionHistory(history); + } + + logger.debug("Set entire history", { + historyLength: history.length, + }); + } + + /** + * Update compaction index + */ + setCompactionIndex(index: number | null): void { + this.setState({ + compactionIndex: index, + }); + + logger.debug("Updated compaction index", { index }); + } + + /** + * Find compaction index in history + */ + private findCompactionIndex(history: ChatHistoryItem[]): number | null { + for (let i = history.length - 1; i >= 0; i--) { + const message = history[i].message; + if (message.role === "system") { + // Handle both string and MessagePart array content + const content = message.content; + if (typeof content === "string" && content.includes("[Compacted]")) { + return i; + } + } + } + return null; + } + + /** + * Get current session ID + */ + getSessionId(): string { + return this.currentState.sessionId; + } + + /** + * Check if in remote mode + */ + isRemoteMode(): boolean { + return this.currentState.isRemoteMode; + } + + /** + * Set remote mode + */ + setRemoteMode(isRemote: boolean): void { + this.setState({ + isRemoteMode: isRemote, + }); + } + + /** + * Override getState to ensure deep immutability for history array + */ + getState(): ChatHistoryState { + return { + ...this.currentState, + history: [...this.currentState.history], + }; + } +} + +// Export singleton instance for migration compatibility +export const chatHistoryService = new ChatHistoryService(); \ No newline at end of file diff --git a/extensions/cli/src/services/index.ts b/extensions/cli/src/services/index.ts index e9409c722..ae53965ab 100644 --- a/extensions/cli/src/services/index.ts +++ b/extensions/cli/src/services/index.ts @@ -4,6 +4,7 @@ import { logger } from "../util/logger.js"; import { ApiClientService } from "./ApiClientService.js"; import { AuthService } from "./AuthService.js"; +import { ChatHistoryService } from "./ChatHistoryService.js"; import { ConfigService } from "./ConfigService.js"; import { FileIndexService } from "./FileIndexService.js"; import { MCPService } from "./MCPService.js"; @@ -29,6 +30,7 @@ const apiClientService = new ApiClientService(); const mcpService = new MCPService(); const fileIndexService = new FileIndexService(); const resourceMonitoringService = new ResourceMonitoringService(); +const chatHistoryService = new ChatHistoryService(); /** * Initialize all services and register them with the service container @@ -241,6 +243,12 @@ export async function initializeServices( [], ); + serviceContainer.register( + SERVICE_NAMES.CHAT_HISTORY, + () => chatHistoryService.initialize(undefined, initOptions.headless), + [], // No dependencies for now, but could depend on SESSION in future + ); + // Eagerly initialize all services to ensure they're ready when needed // This avoids race conditions and "service not ready" errors await serviceContainer.initializeAll(); @@ -284,6 +292,7 @@ export function areServicesReady(): boolean { SERVICE_NAMES.MCP, SERVICE_NAMES.FILE_INDEX, SERVICE_NAMES.RESOURCE_MONITORING, + SERVICE_NAMES.CHAT_HISTORY, ].every((name) => serviceContainer.isReady(name)); } @@ -307,6 +316,7 @@ export const services = { mode: modeService, resourceMonitoring: resourceMonitoringService, systemMessage: systemMessageService, + chatHistory: chatHistoryService, } as const; // Export the service container for advanced usage diff --git a/extensions/cli/src/services/types.ts b/extensions/cli/src/services/types.ts index 75470d958..18fb2cbae 100644 --- a/extensions/cli/src/services/types.ts +++ b/extensions/cli/src/services/types.ts @@ -93,6 +93,7 @@ export interface ToolPermissionServiceState { } export type { FileIndexServiceState } from "./FileIndexService.js"; +export type { ChatHistoryState } from "./ChatHistoryService.js"; /** * Service names as constants to prevent typos @@ -107,6 +108,7 @@ export const SERVICE_NAMES = { FILE_INDEX: "fileIndex", RESOURCE_MONITORING: "resourceMonitoring", SYSTEM_MESSAGE: "systemMessage", + CHAT_HISTORY: "chatHistory", } as const; /** diff --git a/packages/openai-adapters/package-lock.json b/packages/openai-adapters/package-lock.json index 046b1dc37..806a98f2a 100644 --- a/packages/openai-adapters/package-lock.json +++ b/packages/openai-adapters/package-lock.json @@ -12528,6 +12528,7 @@ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.5.4.tgz", "integrity": "sha512-Mtq29sKDAEYP7aljRgtPOpTvOfbwRWlS6dPRzwjdE+C0R4brX/GUyhHSecbHMFLNBLcJIPt9nl9yG5TZ1weH+Q==", "dev": true, + "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver"