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..566ebe5aa --- /dev/null +++ b/extensions/cli/CHAT_HISTORY_SERVICE_MIGRATION_PLAN.md @@ -0,0 +1,434 @@ +# 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 + +Status: Completed + +- Remote mode now reads/writes chat history via ChatHistoryService; `/state` reflects the service’s history. +- Stream callbacks avoid duplicating tool entries; service is single source of truth. +- Added undo/redo to ChatHistoryService with tests (`canUndo/canRedo/undo/redo`). + +Notes: Further optimizations (batching/memoization) can be added if performance profiling indicates need with very large histories. + +### 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 + +- Removed direct history mutations in serve/stream paths where service is present; retained minimal fallbacks. +- Updated imports/types; removed unused `updateSessionHistory` in serve mode and pruned unused types. +- Verified service methods own persistence; remote mode disables persistence by design. + +#### 6.3 Migration Verification Checklist + +- [x] No direct array mutations remain where service is available (fallbacks kept for resilience) +- [x] All tests passing +- [x] Service handles all chat operations (user, assistant, tools, system, compaction) +- [x] React components update via service events +- [x] Session management integrated with service persistence +- [x] Remote mode reading/writing via service +- [x] Performance acceptable in tests; no regressions +- [x] No new console errors/warnings introduced + +## 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 +``` diff --git a/extensions/cli/package-lock.json b/extensions/cli/package-lock.json index b6154c67b..d52b3f219 100644 --- a/extensions/cli/package-lock.json +++ b/extensions/cli/package-lock.json @@ -58,6 +58,7 @@ "@vitest/ui": "^3.2.4", "@workos-inc/node": "^7.45.0", "chalk": "^5.4.1", + "clipboardy": "^4.0.0", "commander": "^14.0.0", "conventional-changelog-conventionalcommits": "^9.1.0", "core": "file:../../core", @@ -7211,6 +7212,155 @@ "url": "https://github.com/chalk/slice-ansi?sponsor=1" } }, + "node_modules/clipboardy": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/clipboardy/-/clipboardy-4.0.0.tgz", + "integrity": "sha512-5mOlNS0mhX0707P2I0aZ2V/cmHUEO/fL7VFLqszkhUsxt7RwnmrInf/eEQKlf5GzvYeHIjT+Ov1HRfNmymlG0w==", + "dev": true, + "license": "MIT", + "dependencies": { + "execa": "^8.0.1", + "is-wsl": "^3.1.0", + "is64bit": "^2.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/clipboardy/node_modules/execa": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/execa/-/execa-8.0.1.tgz", + "integrity": "sha512-VyhnebXciFV2DESc+p6B+y0LjSm0krU4OgJN44qFAhBY0TJ+1V61tYD2+wHusZ6F9n5K+vl8k0sTy7PEfV4qpg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cross-spawn": "^7.0.3", + "get-stream": "^8.0.1", + "human-signals": "^5.0.0", + "is-stream": "^3.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^5.1.0", + "onetime": "^6.0.0", + "signal-exit": "^4.1.0", + "strip-final-newline": "^3.0.0" + }, + "engines": { + "node": ">=16.17" + }, + "funding": { + "url": "https://github.com/sindresorhus/execa?sponsor=1" + } + }, + "node_modules/clipboardy/node_modules/get-stream": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-8.0.1.tgz", + "integrity": "sha512-VaUJspBffn/LMCJVoMvSAdmscJyS1auj5Zulnn5UoYcY531UWmdwhRWkcGKnGU93m5HSXP9LP2usOryrBtQowA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/clipboardy/node_modules/human-signals": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-5.0.0.tgz", + "integrity": "sha512-AXcZb6vzzrFAUE61HnN4mpLqd/cSIwNQjtNWR0euPm6y0iqx3G4gOXaIDdtdDwZmhwe82LA6+zinmW4UBWVePQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=16.17.0" + } + }, + "node_modules/clipboardy/node_modules/is-stream": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-3.0.0.tgz", + "integrity": "sha512-LnQR4bZ9IADDRSkvpqMGvt/tEJWclzklNgSw48V5EAaAeDd6qGvN8ei6k5p0tvxSR171VmGyHuTiAOfxAbr8kA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/clipboardy/node_modules/mimic-fn": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-4.0.0.tgz", + "integrity": "sha512-vqiC06CuhBTUdZH+RYl8sFrL096vA45Ok5ISO6sE/Mr1jRbGH4Csnhi8f3wKVl7x8mO4Au7Ir9D3Oyv1VYMFJw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/clipboardy/node_modules/npm-run-path": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-5.3.0.tgz", + "integrity": "sha512-ppwTtiJZq0O/ai0z7yfudtBpWIoxM8yE6nHi1X47eFR2EWORqfbu6CnPlNsjeN683eT0qG6H/Pyf9fCcvjnnnQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^4.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/clipboardy/node_modules/onetime": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-6.0.0.tgz", + "integrity": "sha512-1FlR+gjXK7X+AsAHso35MnyN5KqGwJRi/31ft6x0M194ht7S+rWAvd7PHss9xSKMzE0asv1pyIHaJYq+BbacAQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "mimic-fn": "^4.0.0" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/clipboardy/node_modules/path-key": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-4.0.0.tgz", + "integrity": "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/clipboardy/node_modules/strip-final-newline": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-3.0.0.tgz", + "integrity": "sha512-dOESqjYr96iWYylGObzd39EuNTa5VJxyvVAEm5Jnh7KGo75V43Hk1odPQkNDyXNmUR6k+gEiDVXnjB8HJ3crXw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/cliui": { "version": "8.0.1", "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", @@ -11267,6 +11417,22 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/is64bit": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is64bit/-/is64bit-2.0.0.tgz", + "integrity": "sha512-jv+8jaWCl0g2lSBkNSVXdzfBA0npK1HGC2KtWM9FumFRoGS94g3NbCCLVnCYHLjp4GrW2KZeeSTMo5ddtznmGw==", + "dev": true, + "license": "MIT", + "dependencies": { + "system-architecture": "^0.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/isarray": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", @@ -17672,6 +17838,19 @@ "dev": true, "license": "MIT" }, + "node_modules/system-architecture": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/system-architecture/-/system-architecture-0.1.0.tgz", + "integrity": "sha512-ulAk51I9UVUyJgxlv9M6lFot2WP3e7t8Kz9+IS6D4rVba1tR9kON+Ey69f+1R4Q8cd45Lod6a4IcJIxnzGc/zA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/temp-dir": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/temp-dir/-/temp-dir-3.0.0.tgz", diff --git a/extensions/cli/package.json b/extensions/cli/package.json index 68490c7c4..1fefcd973 100644 --- a/extensions/cli/package.json +++ b/extensions/cli/package.json @@ -97,6 +97,7 @@ "eslint-plugin-import": "^2.32.0", "eslint-plugin-unused-imports": "^4.1.4", "execa": "^9.6.0", + "clipboardy": "^4.0.0", "express": "^5.1.0", "glob": "^11.0.3", "gpt-tokenizer": "^3.0.1", diff --git a/extensions/cli/src/args.ts b/extensions/cli/src/args.ts index fca0c86e5..b8a452213 100644 --- a/extensions/cli/src/args.ts +++ b/extensions/cli/src/args.ts @@ -3,6 +3,7 @@ export interface CommandLineArgs { organizationSlug?: string; // Organization slug to use for this session prompt?: string; // Optional prompt argument resume?: boolean; // Resume from last session + fork?: string; // Fork from an existing session ID readonly?: boolean; // Start in plan mode (backward compatibility) rules?: string[]; // Array of rule specifications mcps?: string[]; // Array of MCP server slugs from the hub @@ -71,6 +72,12 @@ export function parseArgs(): CommandLineArgs { result.readonly = true; } + // Parse fork flag + const forkValue = extractSingleFlag(args, "--fork"); + if (forkValue) { + result.fork = forkValue; + } + // Parse single-value flags const formatValue = extractSingleFlag(args, "--format"); if (formatValue === "json") { @@ -124,6 +131,7 @@ export function parseArgs(): CommandLineArgs { "--model", "--prompt", "--format", + "--fork", ]; const nonFlagArgs = args.filter((arg, index) => { if (arg.startsWith("--") || arg === "-p") return false; diff --git a/extensions/cli/src/commands/chat.ts b/extensions/cli/src/commands/chat.ts index c62b656c4..96e74c9ae 100644 --- a/extensions/cli/src/commands/chat.ts +++ b/extensions/cli/src/commands/chat.ts @@ -4,17 +4,13 @@ import type { ChatHistoryItem, Session } from "core/index.js"; import { ChatDescriber } from "core/util/chatDescriber.js"; import * as readlineSync from "readline-sync"; -import { - compactChatHistory, - findCompactionIndex, - getHistoryForLLM, -} from "../compaction.js"; +import { compactChatHistory, findCompactionIndex } from "../compaction.js"; import { processCommandFlags } from "../flags/flagProcessor.js"; import { safeStdout } from "../init.js"; import { configureLogger } from "../logger.js"; import * as logging from "../logging.js"; import { sentryService } from "../sentry.js"; -import { initializeServices } from "../services/index.js"; +import { initializeServices, services } from "../services/index.js"; import { serviceContainer } from "../services/ServiceContainer.js"; import { ModelServiceState, SERVICE_NAMES } from "../services/types.js"; import { @@ -80,6 +76,7 @@ function stripThinkTags(response: string): string { export interface ChatOptions extends ExtendedCommandOptions { headless?: boolean; resume?: boolean; + fork?: string; // Fork from an existing session ID format?: "json"; // Output format for headless mode silent?: boolean; // Strip tags and excess whitespace } @@ -89,6 +86,20 @@ export async function initializeChatHistory( ): Promise { let session: Session | null = null; + // Fork from an existing session if --fork flag is used + if (options.fork) { + const { loadSessionById, startNewSession } = await import("../session.js"); + const sessionToFork = loadSessionById(options.fork); + if (sessionToFork) { + logger.info(chalk.yellow("Forking from existing session...")); + const newSession = startNewSession(sessionToFork.history); + return newSession.history; + } else { + logger.error(chalk.red(`Session with ID "${options.fork}" not found.`)); + process.exit(1); + } + } + // Load previous session if --resume flag is used if (options.resume) { session = loadSession(); @@ -115,21 +126,21 @@ async function handleManualCompaction( } try { - const result = await compactChatHistory(chatHistory, model, llmApi); + const current = services.chatHistory.getHistory(); + const result = await compactChatHistory(current, model, llmApi); - // Replace chat history with compacted version - chatHistory.length = 0; - chatHistory.push(...result.compactedHistory); - - // Save the compacted session - updateSessionHistory(chatHistory); + // Update service-driven history (persistence handled by service) + services.chatHistory.compact( + result.compactedHistory, + result.compactionIndex, + ); if (isHeadless) { safeStdout( JSON.stringify({ status: "success", message: "Chat history compacted", - historyLength: chatHistory.length, + historyLength: services.chatHistory.getHistory().length, }) + "\n", ); } else { @@ -176,7 +187,7 @@ async function handleAutoCompaction( message: "Auto-compacting triggered", contextUsage: calculateContextUsagePercentage( - countChatHistoryTokens(chatHistory), + countChatHistoryTokens(services.chatHistory.getHistory()), model, ) + "%", }) + "\n", @@ -186,11 +197,11 @@ async function handleAutoCompaction( if (!isHeadless) { console.info(chalk.green(message)); } else if (format === "json") { + // Omit history length here; service updates occur after compaction completes safeStdout( JSON.stringify({ status: "success", message: "Auto-compacted successfully", - historyLength: chatHistory.length, }) + "\n", ); } @@ -210,15 +221,19 @@ async function handleAutoCompaction( }, }; - const result = await coreAutoCompaction(chatHistory, model, llmApi, { - isHeadless, - format, - callbacks, - }); + const result = await coreAutoCompaction( + services.chatHistory.getHistory(), + model, + llmApi, + { + isHeadless, + format, + callbacks, + }, + ); - // Update the original array reference for headless mode - chatHistory.length = 0; - chatHistory.push(...result.chatHistory); + // Update service-driven history + services.chatHistory.setHistory(result.chatHistory); return result.compactionIndex; } @@ -286,7 +301,7 @@ async function processMessage( telemetryService.logUserPrompt(userInput.length, userInput); // Check if auto-compacting is needed BEFORE adding user message - if (shouldAutoCompact(chatHistory, model)) { + if (shouldAutoCompact(services.chatHistory.getHistory(), model)) { const newIndex = await handleAutoCompaction( chatHistory, model, @@ -296,17 +311,12 @@ async function processMessage( ); if (newIndex !== null) { compactionIndex = newIndex; - // Replace chatHistory with compacted version - chatHistory.length = 0; - chatHistory.push(...chatHistory); + // Service already updated in handleAutoCompaction via setHistory } } // Add user message to history AFTER potential compaction - chatHistory.push({ - message: { role: "user", content: userInput }, - contextItems: [], - }); + services.chatHistory.addUserMessage(userInput); // Get AI response with potential tool usage if (!isHeadless) { @@ -316,12 +326,12 @@ async function processMessage( try { const abortController = new AbortController(); - // Handle compaction properly - streamChatResponse modifies the array in place + // Service-driven streaming; history updates occur via ChatHistoryService let finalResponse; if (compactionIndex !== null && compactionIndex !== undefined) { - // When using compaction, we need to send a subset but capture the full history - const historyForLLM = getHistoryForLLM(chatHistory, compactionIndex); - const originalLength = historyForLLM.length; + // Use service to compute history for LLM + const historyForLLM = + services.chatHistory.getHistoryForLLM(compactionIndex); finalResponse = await streamChatResponse( historyForLLM, @@ -329,19 +339,14 @@ async function processMessage( llmApi, abortController, ); - - // Append any new messages (assistant/tool) that were added by streamChatResponse - const newMessages = historyForLLM.slice(originalLength); - chatHistory.push(...newMessages); } else { - // No compaction - just pass the full history directly + // No compaction - get full history from service finalResponse = await streamChatResponse( - chatHistory, + services.chatHistory.getHistory(), model, llmApi, abortController, ); - // No need to sync back - streamChatResponse modifies chatHistory in place } // Generate session title after first assistant response @@ -368,7 +373,7 @@ async function processMessage( } // Save session after each successful response - updateSessionHistory(chatHistory); + updateSessionHistory(services.chatHistory.getHistory()); } catch (e: any) { const error = e instanceof Error ? e : new Error(String(e)); @@ -381,11 +386,17 @@ async function processMessage( sentryService.captureException(error, { context: "chat_response", isHeadless, - chatHistoryLength: chatHistory.length, + chatHistoryLength: services.chatHistory.getHistory().length, }); if (!isHeadless) { logger.info( - chalk.dim(`Chat history:\n${JSON.stringify(chatHistory, null, 2)}`), + chalk.dim( + `Chat history:\n${JSON.stringify( + services.chatHistory.getHistory(), + null, + 2, + )}`, + ), ); } } @@ -414,12 +425,11 @@ async function runHeadlessMode( throw new Error("No models were found."); } - // Initialize chat history + // Initialize service-driven history (resume if requested) const chatHistory = await initializeChatHistory(options); - - // Track compaction index if resuming with compacted history let compactionIndex: number | null = null; - if (options.resume) { + if (options.resume || options.fork) { + services.chatHistory.setHistory(chatHistory); compactionIndex = findCompactionIndex(chatHistory); } @@ -502,6 +512,7 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { const tuiOptions: any = { initialPrompt: prompt, resume: options.resume, + fork: options.fork, config: options.config, org: options.org, rule: options.rule, diff --git a/extensions/cli/src/commands/commands.ts b/extensions/cli/src/commands/commands.ts index d1e6325e9..419241100 100644 --- a/extensions/cli/src/commands/commands.ts +++ b/extensions/cli/src/commands/commands.ts @@ -76,6 +76,11 @@ export const SYSTEM_SLASH_COMMANDS: SystemCommand[] = [ description: "Resume a previous chat session", category: "system", }, + { + name: "fork", + description: "Start a forked chat session from the current history", + category: "system", + }, { name: "exit", description: "Exit the chat", diff --git a/extensions/cli/src/commands/serve.helpers.ts b/extensions/cli/src/commands/serve.helpers.ts index 35d67116d..82ca902ea 100644 --- a/extensions/cli/src/commands/serve.helpers.ts +++ b/extensions/cli/src/commands/serve.helpers.ts @@ -1,7 +1,9 @@ -import type { Session, ToolCallState, ToolStatus } from "core/index.js"; +import type { Session, ToolStatus } from "core/index.js"; +import { services } from "../services/index.js"; import { streamChatResponse } from "../stream/streamChatResponse.js"; import { StreamCallbacks } from "../stream/streamChatResponse.types.js"; +import { logger } from "../util/logger.js"; // Modified version of streamChatResponse that supports interruption export async function streamChatResponseWithInterruption( @@ -38,47 +40,11 @@ export async function streamChatResponseWithInterruption( // This callback is just for notification/UI updates // The tool call state is already created and added by handleToolCalls }, - onToolResult: (result: string, toolName: string, status: ToolStatus) => { - // Update only the tool call state status - // The actual result is already added as a separate message by handleToolCalls - for (let i = state.session.history.length - 1; i >= 0; i--) { - const item = state.session.history[i]; - if (item.toolCallStates) { - const toolState = item.toolCallStates.find( - (ts: ToolCallState) => - ts.toolCall.function.name === toolName && - (ts.status === "calling" || ts.status === "generated"), - ); - if (toolState) { - // Only update the status, not the output - toolState.status = status; - break; - } - } - } + onToolResult: (_result: string, _toolName: string, _status: ToolStatus) => { + // No-op when using ChatHistoryService; it updates tool states/results }, - onToolError: (error: string, toolName?: string) => { - // Only update the tool call state to errored status when tool name is provided - // The error message is already added as a separate tool result message - // by handleToolCalls/preprocessStreamedToolCalls/executeStreamedToolCalls - if (toolName) { - // Find and update the corresponding tool call state - for (let i = state.session.history.length - 1; i >= 0; i--) { - const item = state.session.history[i]; - if (item.toolCallStates) { - const toolState = item.toolCallStates.find( - (ts: ToolCallState) => - ts.toolCall.function.name === toolName && - (ts.status === "calling" || ts.status === "generated"), - ); - if (toolState) { - // Only update the status, not the output - toolState.status = "errored"; - break; - } - } - } - } + onToolError: (_error: string, _toolName?: string) => { + // No-op; errors are added to history via handleToolCalls flow }, onToolPermissionRequest: ( toolName: string, @@ -95,25 +61,33 @@ export async function streamChatResponseWithInterruption( toolCallPreview, }; - // Add a system message indicating permission is needed - state.session.history.push({ - message: { - role: "system", - content: `WARNING: Tool ${toolName} requires permission`, - }, - contextItems: [], - }); + // Add a system message indicating permission is needed via service + try { + services.chatHistory.addSystemMessage( + `WARNING: Tool ${toolName} requires permission`, + ); + } catch (err) { + // Do not mutate session history; ChatHistoryService is the source of truth + logger.error( + "Failed to add system message via ChatHistoryService", + err, + { context: "onToolPermissionRequest", toolName, requestId }, + ); + } // Don't wait here - the streamChatResponse will handle waiting }, onSystemMessage: (message: string) => { - state.session.history.push({ - message: { - role: "system", - content: message, - }, - contextItems: [], - }); + try { + services.chatHistory.addSystemMessage(message); + } catch (err) { + // Do not mutate session history; ChatHistoryService is the source of truth + logger.error( + "Failed to add system message via ChatHistoryService", + err, + { context: "onSystemMessage" }, + ); + } }, }; diff --git a/extensions/cli/src/commands/serve.ts b/extensions/cli/src/commands/serve.ts index 8d8e726d5..5be1eda05 100644 --- a/extensions/cli/src/commands/serve.ts +++ b/extensions/cli/src/commands/serve.ts @@ -12,13 +12,14 @@ import { getService, initializeServices, SERVICE_NAMES, + services, } from "../services/index.js"; import { AuthServiceState, ConfigServiceState, ModelServiceState, } from "../services/types.js"; -import { createSession, updateSessionHistory } from "../session.js"; +import { createSession } from "../session.js"; import { constructSystemMessage } from "../systemMessage.js"; import { telemetryService } from "../telemetry/telemetryService.js"; import { formatError } from "../util/formatError.js"; @@ -38,6 +39,7 @@ interface ServeOptions extends ExtendedCommandOptions { port?: string; } +// eslint-disable-next-line max-statements export async function serve(prompt?: string, options: ServeOptions = {}) { // Check if prompt should come from stdin instead of parameter let actualPrompt = prompt; @@ -122,6 +124,13 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { const session = createSession(initialHistory); + // Align ChatHistoryService with server session and enable remote mode + try { + await services.chatHistory.initialize(session, false); + } catch { + // Fallback: continue even if service init fails; stream will still work with arrays + } + // Initialize server state const state: ServerState = { session, @@ -146,6 +155,14 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { // GET /state - Return the current state app.get("/state", (_req: Request, res: Response) => { state.lastActivity = Date.now(); + // Ensure session history reflects ChatHistoryService state + try { + state.session.history = services.chatHistory.getHistory(); + } catch (e) { + logger.debug( + `Failed to sync session history from ChatHistoryService: ${formatError(e)}`, + ); + } res.json({ session: state.session, // Return session directly instead of converting isProcessing: state.isProcessing, @@ -328,6 +345,27 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { }); // Process messages from the queue + function removePartialAssistantMessage(state: ServerState) { + try { + const svcHistory = services.chatHistory.getHistory(); + const last = svcHistory[svcHistory.length - 1]; + if (last && last.message.role === "assistant" && !last.message.content) { + const trimmed = svcHistory.slice(0, -1); + services.chatHistory.setHistory(trimmed); + } + } catch { + const lastMessage = + state.session.history[state.session.history.length - 1]; + if ( + lastMessage && + lastMessage.message.role === "assistant" && + !lastMessage.message.content + ) { + state.session.history.pop(); + } + } + } + async function processMessages(state: ServerState, llmApi: any) { while (state.messageQueue.length > 0 && state.serverRunning) { const userMessage = state.messageQueue.shift()!; @@ -335,11 +373,16 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { state.shouldInterrupt = false; state.lastActivity = Date.now(); - // Add user message to history - state.session.history.push({ - message: { role: "user", content: userMessage }, - contextItems: [], - }); + // Add user message via ChatHistoryService (single source of truth) + try { + services.chatHistory.addUserMessage(userMessage); + } catch { + // Fallback to local array if service unavailable + state.session.history.push({ + message: { role: "user", content: userMessage }, + contextItems: [], + }); + } try { // Create new abort controller for this response @@ -353,31 +396,26 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { () => state.shouldInterrupt, ); - // Save session after successful response - updateSessionHistory(state.session.history); + // No direct persistence here; ChatHistoryService handles persistence when appropriate state.lastActivity = Date.now(); } catch (e: any) { if (e.name === "AbortError") { logger.debug("Response interrupted"); - // Remove the partial assistant message if it exists - const lastMessage = - state.session.history[state.session.history.length - 1]; - if ( - lastMessage && - lastMessage.message.role === "assistant" && - !lastMessage.message.content - ) { - state.session.history.pop(); - } + // Remove any partial assistant message + removePartialAssistantMessage(state); } else { logger.error(`Error: ${formatError(e)}`); - // Add error message to chat history and display messages + // Add error message via ChatHistoryService const errorMessage = `Error: ${formatError(e)}`; - state.session.history.push({ - message: { role: "assistant", content: errorMessage }, - contextItems: [], - }); + try { + services.chatHistory.addAssistantMessage(errorMessage); + } catch { + state.session.history.push({ + message: { role: "assistant", content: errorMessage }, + contextItems: [], + }); + } } } finally { state.currentAbortController = null; diff --git a/extensions/cli/src/compaction.ts b/extensions/cli/src/compaction.ts index 3edbe0260..8513b1405 100644 --- a/extensions/cli/src/compaction.ts +++ b/extensions/cli/src/compaction.ts @@ -80,7 +80,7 @@ export async function compactChatHistory( historyForCompaction = [...historyToUse, compactionPrompt]; } - // Stream the compaction response + // Stream the compaction response (service drives updates; this collects content locally) const controller = new AbortController(); let compactionContent = ""; diff --git a/extensions/cli/src/flags/flagValidator.ts b/extensions/cli/src/flags/flagValidator.ts index 60e084a10..fb9b29195 100644 --- a/extensions/cli/src/flags/flagValidator.ts +++ b/extensions/cli/src/flags/flagValidator.ts @@ -16,6 +16,10 @@ export interface ValidationOptions { auto?: boolean; config?: string; + // Session flags + resume?: boolean; + fork?: string; + // Permission flags allow?: string[]; ask?: string[]; @@ -101,6 +105,29 @@ function validateModeFlags(options: ValidationOptions): ValidationError[] { return errors; } +/** + * Validate session flags + */ +function validateSessionFlags(options: ValidationOptions): ValidationError[] { + const errors: ValidationError[] = []; + + if (options.resume && options.fork) { + errors.push({ + code: "CONFLICTING_SESSION_FLAGS", + message: "Error: Cannot use both --resume and --fork flags together", + }); + } + + if (options.fork !== undefined && (!options.fork || !options.fork.trim())) { + errors.push({ + code: "FORK_REQUIRES_SESSION_ID", + message: "Error: --fork requires a session ID (e.g., --fork abc123)", + }); + } + + return errors; +} + /** * Validate config path exists (basic check) */ @@ -164,6 +191,7 @@ export function validateFlags(options: ValidationOptions): ValidationResult { validateSilentFlag, validateFormatValue, validateModeFlags, + validateSessionFlags, validateConfigPath, validatePermissionFlags, ]; diff --git a/extensions/cli/src/index.ts b/extensions/cli/src/index.ts index 1d2da1cb9..91b5a6c78 100644 --- a/extensions/cli/src/index.ts +++ b/extensions/cli/src/index.ts @@ -64,6 +64,7 @@ addCommonOptions(program) "Strip tags and excess whitespace from output. Only works with -p/--print flag.", ) .option("--resume", "Resume from last session") + .option("--fork ", "Fork from an existing session ID") .action(async (prompt, options) => { // Handle piped input - detect it early and decide on mode let stdinInput = null; @@ -100,6 +101,8 @@ addCommonOptions(program) readonly: options.readonly, auto: options.auto, config: options.config, + resume: options.resume, + fork: options.fork, allow: options.allow, ask: options.ask, exclude: options.exclude, diff --git a/extensions/cli/src/services/ChatHistoryService.test.ts b/extensions/cli/src/services/ChatHistoryService.test.ts new file mode 100644 index 000000000..e5edef8ba --- /dev/null +++ b/extensions/cli/src/services/ChatHistoryService.test.ts @@ -0,0 +1,548 @@ +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: "assistant", content: "Summary here" }, + contextItems: [], + conversationSummary: "Summary here", + }, + { + 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: "assistant", content: "old summary" }, + contextItems: [], + conversationSummary: "old summary", + }, + { + message: { role: "user", content: "Recent message" }, + contextItems: [], + }, + ]; + + service.setHistory(historyWithCompaction); + + const state = service.getState(); + expect(state.compactionIndex).toBe(0); + }); + }); + + describe("undo/redo", () => { + beforeEach(async () => { + await service.initialize(); + }); + + it("should undo last change and redo it", () => { + service.addUserMessage("A"); + service.addAssistantMessage("B"); + + expect(service.getState().history.map((m) => m.message.content)).toEqual([ + "A", + "B", + ]); + + expect(service.canUndo()).toBe(true); + service.undo(); + expect(service.getState().history.map((m) => m.message.content)).toEqual([ + "A", + ]); + + expect(service.canRedo()).toBe(true); + service.redo(); + expect(service.getState().history.map((m) => m.message.content)).toEqual([ + "A", + "B", + ]); + }); + + it("should support undoing tool state updates", () => { + service.addAssistantMessage("Using tool", [ + { id: "t1", name: "Read", arguments: { path: "file" } }, + ]); + const before = service.getHistory(); + service.addToolResult("t1", "ok", "done"); + const after = service.getHistory(); + + expect(after[0].toolCallStates?.[0].status).toBe("done"); + service.undo(); + const undone = service.getHistory(); + expect(undone[0].toolCallStates?.[0].status).toBe( + before[0].toolCallStates?.[0].status, + ); + }); + }); + + 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: [], + }), + ); + }); + }); +}); diff --git a/extensions/cli/src/services/ChatHistoryService.ts b/extensions/cli/src/services/ChatHistoryService.ts new file mode 100644 index 000000000..0ebc9de50 --- /dev/null +++ b/extensions/cli/src/services/ChatHistoryService.ts @@ -0,0 +1,534 @@ +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 { + // Simple undo/redo stacks for history snapshots + private past: ChatHistoryItem[][] = []; + private future: ChatHistoryItem[][] = []; + // Memoized snapshot for referential stability in getState() + private _memoSnapshot: { + stateRef: ChatHistoryState | null; + historyRef: ChatHistoryItem[] | null; + snapshot: ChatHistoryState | null; + } = { stateRef: null, historyRef: null, snapshot: null }; + + constructor() { + super("ChatHistoryService", { + history: [], + compactionIndex: null, + sessionId: "", + isRemoteMode: false, + }); + this.setMaxListeners(50); + } + + private setHistoryInternal( + history: ChatHistoryItem[], + options: { + recordUndo?: boolean; + compactionIndex?: number | null; + persist?: boolean; // set to false to skip persistence (rare) + } = {}, + ): void { + const { recordUndo = true, compactionIndex, persist } = options; + const prev = this.currentState.history; + if (recordUndo) { + this.past.push([...prev]); + this.future = []; + } + this.setState({ + history: [...history], + compactionIndex: + compactionIndex === undefined + ? this.findCompactionIndex(history) + : compactionIndex, + }); + + if (this.currentState.isRemoteMode) { + // Skip persistence in remote mode + } else if (persist !== false) { + updateSessionHistory(history); + } + } + + /** + * 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.setHistoryInternal(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) => { + const id = tc.id; + const name = tc.function?.name ?? tc.name; + // Prefer explicit string arguments; otherwise stringify object arguments + let rawArgStr: string; + if (typeof tc.arguments === "string") { + rawArgStr = tc.arguments; + } else if (typeof tc.function?.arguments === "string") { + rawArgStr = tc.function.arguments; + } else if (tc.arguments === undefined) { + rawArgStr = + tc.function?.arguments === undefined + ? "{}" + : String(tc.function.arguments); + } else { + rawArgStr = JSON.stringify(tc.arguments); + } + + // parsedArgs: prefer object, else parse the string if possible + let parsedArgs: any = {}; + if (tc && typeof tc.arguments === "object" && tc.arguments !== null) { + parsedArgs = tc.arguments; + } else if (typeof rawArgStr === "string") { + try { + parsedArgs = JSON.parse(rawArgStr); + } catch { + parsedArgs = {}; + } + } + + return { + toolCallId: id, + toolCall: { + id, + type: "function" as const, + function: { + name, + arguments: rawArgStr, + }, + }, + status: "generated" as ToolStatus, + parsedArgs, + }; + }); + + const newMessage = createHistoryItem(message, [], toolCallStates); + const newHistory = [...this.currentState.history, newMessage]; + this.setHistoryInternal(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.setHistoryInternal(newHistory); + + logger.debug("Added system message", { + contentLength: content.length, + newHistoryLength: newHistory.length, + }); + + return newMessage; + } + + /** + * Add a generic history item + */ + addHistoryItem(item: ChatHistoryItem): ChatHistoryItem { + const newHistory = [...this.currentState.history, item]; + this.setHistoryInternal(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.setHistoryInternal(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 }); + } + } + + /** + * Update a tool's status (e.g., set to "calling" immediately on approval) + */ + updateToolStatus(toolCallId: string, status: ToolStatus): 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 }); + } else { + logger.warn("Could not find message for tool status update", { + toolCallId, + status, + }); + } + } + + /** + * Perform compaction on the history + */ + compact(newHistory: ChatHistoryItem[], compactionIndex: number): void { + this.setHistoryInternal(newHistory, { compactionIndex }); + + logger.debug("Compacted history", { + oldLength: this.currentState.history.length, + newLength: newHistory.length, + compactionIndex, + }); + } + + /** + * Clear the chat history + */ + clear(): void { + this.setHistoryInternal([], { compactionIndex: null }); + + logger.debug("Cleared chat history"); + } + + /** + * Load a session into the service + */ + async loadSession(sessionId: string): Promise { + const session = loadSessionById(sessionId); + if (session) { + // Load new history without recording undo; set sessionId separately + this.setHistoryInternal(session.history, { recordUndo: false }); + this.setState({ sessionId: session.sessionId }); + + 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; + const full = this.currentState.history; + if (index === null || index === undefined || index >= full.length) { + return this.getHistory(); + } + const systemMessage = full[0]?.message?.role === "system" ? full[0] : null; + const messagesFromCompaction = full.slice(index); + return systemMessage && index > 0 + ? [systemMessage, ...messagesFromCompaction] + : messagesFromCompaction; + } + + /** + * Set the entire history (for remote mode or special cases) + */ + setHistory(history: ChatHistoryItem[]): void { + this.setHistoryInternal(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 { + const idx = history.findIndex( + (item) => item.conversationSummary !== undefined, + ); + return idx === -1 ? null : idx; + } + + // Undo/Redo API + canUndo(): boolean { + return this.past.length > 0; + } + + canRedo(): boolean { + return this.future.length > 0; + } + + undo(): void { + if (!this.canUndo()) return; + const prev = this.past.pop()!; + this.future.push([...this.currentState.history]); + this.setHistoryInternal(prev, { recordUndo: false }); + } + + redo(): void { + if (!this.canRedo()) return; + const next = this.future.pop()!; + this.past.push([...this.currentState.history]); + this.setHistoryInternal(next, { recordUndo: false }); + } + + /** + * 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 { + const stateRef = this.currentState; + const historyRef = stateRef.history; + + // If neither the state object nor the history reference changed, + // return the same memoized snapshot to preserve referential stability + if ( + this._memoSnapshot.snapshot && + this._memoSnapshot.stateRef === stateRef && + this._memoSnapshot.historyRef === historyRef + ) { + return this._memoSnapshot.snapshot; + } + + // Build a memoized snapshot object with getters to: + // - keep the outer object reference stable when unchanged + // - return a fresh copy of history on each access to prevent external mutation + const snapshot = {} as ChatHistoryState; + Object.defineProperties(snapshot, { + history: { + enumerable: true, + get: () => [...stateRef.history], + }, + compactionIndex: { + enumerable: true, + get: () => stateRef.compactionIndex, + }, + sessionId: { + enumerable: true, + get: () => stateRef.sessionId, + }, + isRemoteMode: { + enumerable: true, + get: () => stateRef.isRemoteMode, + }, + }); + + this._memoSnapshot = { stateRef, historyRef, snapshot }; + return snapshot; + } +} 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/extensions/cli/src/slashCommands.ts b/extensions/cli/src/slashCommands.ts index 9c8b172a8..b5dc3d9aa 100644 --- a/extensions/cli/src/slashCommands.ts +++ b/extensions/cli/src/slashCommands.ts @@ -199,6 +199,34 @@ async function handleInfo() { }; } +async function handleFork() { + posthogService.capture("useSlashCommand", { name: "fork" }); + + try { + const currentSession = getCurrentSession(); + const forkCommand = `cn --fork ${currentSession.sessionId}`; + // Try to copy to clipboard dynamically to avoid hard dependency in tests + try { + const clipboardy = await import("clipboardy"); + await clipboardy.default.write(forkCommand); + return { + exit: false, + output: chalk.gray(`${forkCommand} (copied to clipboard)`), + }; + } catch { + return { + exit: false, + output: chalk.gray(`${forkCommand}`), + }; + } + } catch (error: any) { + return { + exit: false, + output: chalk.red(`Failed to create fork command: ${error.message}`), + }; + } +} + const commandHandlers: Record = { help: handleHelp, clear: () => { @@ -230,6 +258,7 @@ const commandHandlers: Record = { posthogService.capture("useSlashCommand", { name: "resume" }); return { openSessionSelector: true }; }, + fork: handleFork, }; export async function handleSlashCommands( diff --git a/extensions/cli/src/stream/handleToolCalls.ts b/extensions/cli/src/stream/handleToolCalls.ts index aa37a25d7..d5b7b09a7 100644 --- a/extensions/cli/src/stream/handleToolCalls.ts +++ b/extensions/cli/src/stream/handleToolCalls.ts @@ -9,6 +9,7 @@ import { MCPServiceState, MCPTool, SERVICE_NAMES, + services, } from "../services/index.js"; import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js"; import { getAllBuiltinTools, ToolCall } from "../tools/index.js"; @@ -27,14 +28,23 @@ export async function handleToolCalls( callbacks: StreamCallbacks | undefined, isHeadless: boolean, ): Promise { + const chatHistorySvc = services.chatHistory; + const useService = + typeof chatHistorySvc?.isReady === "function" && chatHistorySvc.isReady(); if (toolCalls.length === 0) { if (content) { - chatHistory.push( - createHistoryItem({ - role: "assistant", - content, - }), - ); + if (useService) { + // Service-driven: write assistant message via service + chatHistorySvc.addAssistantMessage(content); + } else { + // Fallback only when service is unavailable + chatHistory.push( + createHistoryItem({ + role: "assistant", + content, + }), + ); + } } return false; } @@ -68,7 +78,16 @@ export async function handleToolCalls( })), }; - chatHistory.push(createHistoryItem(assistantMessage, [], toolCallStates)); + if (useService) { + // Important: pass ChatCompletion-style toolCalls, not internal ToolCall[] + chatHistorySvc.addAssistantMessage( + assistantMessage.content || "", + assistantMessage.toolCalls, + ); + } else { + // Fallback only when service is unavailable + chatHistory.push(createHistoryItem(assistantMessage, [], toolCallStates)); + } // First preprocess the tool calls const { preprocessedCalls, errorChatEntries } = @@ -77,13 +96,17 @@ export async function handleToolCalls( // Add any preprocessing errors to chat history // Convert error entries from OpenAI format to ChatHistoryItem format errorChatEntries.forEach((errorEntry) => { - chatHistory.push( - createHistoryItem({ - role: "tool", - content: stripImages(errorEntry.content) || "", - toolCallId: errorEntry.tool_call_id, - }), - ); + const item = createHistoryItem({ + role: "tool", + content: stripImages(errorEntry.content) || "", + toolCallId: errorEntry.tool_call_id, + }); + if (useService) { + chatHistorySvc.addHistoryItem(item); + } else { + // Fallback only when service is unavailable + chatHistory.push(item); + } }); // Execute the valid preprocessed tool calls @@ -97,32 +120,55 @@ export async function handleToolCalls( return true; // Signal early return needed } - // Convert tool results from OpenAI format to ChatHistoryItem format - // and add them to the chat history + // Convert tool results and add them to the chat history with per-result status toolResults.forEach((toolResult) => { - // Find the corresponding tool call state to update - const lastAssistantIndex = chatHistory.findLastIndex( - (item) => item.message.role === "assistant" && item.toolCallStates, - ); + const resultContent = + typeof toolResult.content === "string" ? toolResult.content : ""; + // Derive per-result status instead of applying batch-wide hasRejection + let status: ToolStatus = "done"; + const lower = resultContent.toLowerCase(); if ( - lastAssistantIndex >= 0 && - chatHistory[lastAssistantIndex].toolCallStates + lower.includes("permission denied by user") || + lower.includes("cancelled due to previous tool rejection") || + lower.includes("canceled due to previous tool rejection") ) { - const toolState = chatHistory[lastAssistantIndex].toolCallStates.find( - (ts) => ts.toolCallId === toolResult.tool_call_id, - ); + status = "canceled"; + } else if ( + lower.startsWith("error executing tool") || + lower.startsWith("error:") + ) { + status = "errored" as ToolStatus; + } - if (toolState) { - toolState.status = hasRejection ? "canceled" : "done"; - toolState.output = [ - { - content: - typeof toolResult.content === "string" ? toolResult.content : "", - name: `Tool Result`, - description: "Tool execution result", - }, - ]; + if (useService) { + chatHistorySvc.addToolResult( + toolResult.tool_call_id, + resultContent, + status, + ); + } else { + // Fallback only when service is unavailable: update local tool state + const lastAssistantIndex = chatHistory.findLastIndex( + (item) => item.message.role === "assistant" && item.toolCallStates, + ); + if ( + lastAssistantIndex >= 0 && + chatHistory[lastAssistantIndex].toolCallStates + ) { + const toolState = chatHistory[lastAssistantIndex].toolCallStates.find( + (ts) => ts.toolCallId === toolResult.tool_call_id, + ); + if (toolState) { + toolState.status = status; + toolState.output = [ + { + content: resultContent, + name: `Tool Result`, + description: "Tool execution result", + }, + ]; + } } } }); diff --git a/extensions/cli/src/stream/streamChatResponse.helpers.ts b/extensions/cli/src/stream/streamChatResponse.helpers.ts index 4ac0a9e88..69bace2ea 100644 --- a/extensions/cli/src/stream/streamChatResponse.helpers.ts +++ b/extensions/cli/src/stream/streamChatResponse.helpers.ts @@ -5,6 +5,7 @@ import { ChatCompletionToolMessageParam } from "openai/resources/chat/completion import { checkToolPermission } from "../permissions/permissionChecker.js"; import { toolPermissionManager } from "../permissions/permissionManager.js"; import { ToolCallRequest } from "../permissions/types.js"; +import { services } from "../services/index.js"; import { telemetryService } from "../telemetry/telemetryService.js"; import { calculateTokenCost } from "../telemetry/utils.js"; import { @@ -373,81 +374,151 @@ export async function executeStreamedToolCalls( hasRejection: boolean; chatHistoryEntries: ChatCompletionToolMessageParam[]; }> { - const chatHistoryEntries: ChatCompletionToolMessageParam[] = []; + // Strategy: queue permissions (preserve order), then run approved tools in parallel. + // If any permission is rejected, cancel the remaining tools in this batch. + + type IndexedCall = { index: number; call: PreprocessedToolCall }; + const indexedCalls: IndexedCall[] = preprocessedCalls.map((call, index) => ({ + index, + call, + })); + + const entriesByIndex = new Map(); + const execPromises: Promise[] = []; + let hasRejection = false; - // Execute each preprocessed tool call - for (const toolCall of preprocessedCalls) { - if (hasRejection) { - const cancelledMessage = `Cancelled due to previous tool rejection`; - chatHistoryEntries.push({ - role: "tool", - tool_call_id: toolCall.id, - content: cancelledMessage, - }); + // Permission phase (sequential) + for (const { index, call } of indexedCalls) { + // Do not cancel subsequent tools after a rejection; handle each independently - callbacks?.onToolResult?.(cancelledMessage, toolCall.name, "canceled"); - continue; - } - - // Handle remaining tool calls in this batch to maintain chat history consistency try { logger.debug("Checking tool permissions", { - name: toolCall.name, - arguments: toolCall.arguments, + name: call.name, + arguments: call.arguments, }); - // Notify tool start - before permission check - // This ensures the UI shows the tool call even if it's rejected - callbacks?.onToolStart?.(toolCall.name, toolCall.arguments); + // Notify tool start before permission check to display in UI fallbacks + callbacks?.onToolStart?.(call.name, call.arguments); - // Check tool permissions using helper const approved = await checkToolPermissionApproval( - toolCall, + call, callbacks, isHeadless, ); if (!approved) { - handlePermissionDenied(toolCall, chatHistoryEntries, callbacks); + // Permission denied: record and mark rejection + const deniedEntry: ChatCompletionToolMessageParam = { + role: "tool", + tool_call_id: call.id, + content: `Permission denied by user`, + }; + entriesByIndex.set(index, deniedEntry); + callbacks?.onToolResult?.( + String(deniedEntry.content), + call.name, + "canceled", + ); + // Immediate service update for UI feedback + try { + services.chatHistory.addToolResult( + call.id, + String(deniedEntry.content), + "canceled", + ); + } catch {} hasRejection = true; + // Remaining items will be auto-cancelled in subsequent iterations continue; } - logger.debug("Executing tool", { - name: toolCall.name, - arguments: toolCall.arguments, - }); + // Immediately mark as calling for instant UI feedback + try { + services.chatHistory.updateToolStatus(call.id, "calling"); + } catch {} - const toolResult = await executeToolCall(toolCall); - - chatHistoryEntries.push({ - role: "tool", - tool_call_id: toolCall.id, - content: toolResult, - }); - - callbacks?.onToolResult?.(toolResult, toolCall.name, "done"); + // Start execution immediately for approved calls + execPromises.push( + (async () => { + try { + logger.debug("Executing tool", { + name: call.name, + arguments: call.arguments, + }); + const toolResult = await executeToolCall(call); + const entry: ChatCompletionToolMessageParam = { + role: "tool", + tool_call_id: call.id, + content: toolResult, + }; + entriesByIndex.set(index, entry); + callbacks?.onToolResult?.(toolResult, call.name, "done"); + // Immediate service update for UI feedback + try { + services.chatHistory.addToolResult( + call.id, + String(toolResult), + "done", + ); + } catch {} + } catch (error) { + const errorMessage = `Error executing tool ${call.name}: ${ + error instanceof Error ? error.message : String(error) + }`; + logger.error("Tool execution failed", { + name: call.name, + error: errorMessage, + }); + entriesByIndex.set(index, { + role: "tool", + tool_call_id: call.id, + content: errorMessage, + }); + callbacks?.onToolError?.(errorMessage, call.name); + // Immediate service update for UI feedback + try { + services.chatHistory.addToolResult( + call.id, + errorMessage as string, + "errored", + ); + } catch {} + } + })(), + ); } catch (error) { - const errorMessage = `Error executing tool ${toolCall.name}: ${ + const errorMessage = `Error checking permissions for ${call.name}: ${ error instanceof Error ? error.message : String(error) }`; - - logger.error("Tool execution failed", { - name: toolCall.name, + logger.error("Permission check failed", { + name: call.name, error: errorMessage, }); - - chatHistoryEntries.push({ + entriesByIndex.set(index, { role: "tool", - tool_call_id: toolCall.id, + tool_call_id: call.id, content: errorMessage, }); - - callbacks?.onToolError?.(errorMessage, toolCall.name); + callbacks?.onToolError?.(errorMessage, call.name); + // Treat permission errors like execution errors but do not stop the batch + try { + services.chatHistory.addToolResult( + call.id, + errorMessage as string, + "errored", + ); + } catch {} } } + await Promise.all(execPromises); + + // Assemble final entries in original order + const chatHistoryEntries: ChatCompletionToolMessageParam[] = preprocessedCalls + .map((_, index) => entriesByIndex.get(index)) + .filter((e): e is ChatCompletionToolMessageParam => !!e); + return { hasRejection, chatHistoryEntries, diff --git a/extensions/cli/src/stream/streamChatResponse.ts b/extensions/cli/src/stream/streamChatResponse.ts index 300ea5b24..95316e975 100644 --- a/extensions/cli/src/stream/streamChatResponse.ts +++ b/extensions/cli/src/stream/streamChatResponse.ts @@ -8,7 +8,7 @@ import type { ChatCompletionTool, } from "openai/resources.mjs"; -import { getServiceSync, SERVICE_NAMES } from "../services/index.js"; +import { getServiceSync, SERVICE_NAMES, services } from "../services/index.js"; import { systemMessageService } from "../services/SystemMessageService.js"; import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js"; import { telemetryService } from "../telemetry/telemetryService.js"; @@ -298,6 +298,7 @@ export async function processStreamingResponse( } // Main function that handles the conversation loop +// eslint-disable-next-line complexity export async function streamChatResponse( chatHistory: ChatHistoryItem[], model: ModelConfig, @@ -320,6 +321,16 @@ export async function streamChatResponse( let finalResponse = ""; while (true) { + // If ChatHistoryService is available, refresh local chatHistory view + const chatHistorySvc = services.chatHistory; + if ( + typeof chatHistorySvc?.isReady === "function" && + chatHistorySvc.isReady() + ) { + try { + chatHistory = chatHistorySvc.getHistory(); + } catch {} + } logger.debug("Starting conversation iteration"); // Recompute tools on each iteration to handle mode changes during streaming @@ -359,7 +370,7 @@ export async function streamChatResponse( // Handle content display handleContentDisplay(content, callbacks, isHeadless); - // Handle tool calls and check for early return + // Handle tool calls and check for early return. This updates history via ChatHistoryService. const shouldReturn = await handleToolCalls( toolCalls, chatHistory, @@ -385,7 +396,18 @@ export async function streamChatResponse( // Only update chat history if compaction actually occurred if (wasCompacted) { - chatHistory = [...updatedChatHistory]; + // Always prefer service; local copy is for temporary reads only + const chatHistorySvc2 = services.chatHistory; + if ( + typeof chatHistorySvc2?.isReady === "function" && + chatHistorySvc2.isReady() + ) { + chatHistorySvc2.setHistory(updatedChatHistory); + chatHistory = chatHistorySvc2.getHistory(); + } else { + // Fallback only when service is unavailable + chatHistory = [...updatedChatHistory]; + } } } diff --git a/extensions/cli/src/test-helpers/ui-test-context.ts b/extensions/cli/src/test-helpers/ui-test-context.ts index a8eae59f3..443420b27 100644 --- a/extensions/cli/src/test-helpers/ui-test-context.ts +++ b/extensions/cli/src/test-helpers/ui-test-context.ts @@ -8,6 +8,21 @@ export interface UITestContext { cleanup: () => void; } +// Export a mock LLM API for testing +export const mockLlmApi = { + chatCompletionNonStream: vi.fn(), + chatCompletionStream: vi.fn(), + completionNonStream: vi.fn(), + completionStream: vi.fn(), + embed: vi.fn(), + rerank: vi.fn(), + fimStream: vi.fn(), + listModels: vi.fn(), + completions: vi.fn(), + stream: vi.fn(), + abort: vi.fn(), +} as any; + /** * Creates a test context with common UI mocks for TUI components */ diff --git a/extensions/cli/src/ui/AppRoot.tsx b/extensions/cli/src/ui/AppRoot.tsx index f6cef3c20..856e2d002 100644 --- a/extensions/cli/src/ui/AppRoot.tsx +++ b/extensions/cli/src/ui/AppRoot.tsx @@ -8,6 +8,7 @@ interface AppRootProps { configPath?: string; initialPrompt?: string; resume?: boolean; + fork?: string; additionalRules?: string[]; additionalPrompts?: string[]; } diff --git a/extensions/cli/src/ui/TUIChat.tsx b/extensions/cli/src/ui/TUIChat.tsx index 2b6ce883a..98c0480b7 100644 --- a/extensions/cli/src/ui/TUIChat.tsx +++ b/extensions/cli/src/ui/TUIChat.tsx @@ -43,6 +43,7 @@ interface TUIChatProps { configPath?: string; initialPrompt?: string; resume?: boolean; + fork?: string; additionalRules?: string[]; additionalPrompts?: string[]; } @@ -138,6 +139,7 @@ const TUIChat: React.FC = ({ configPath, initialPrompt, resume, + fork, additionalRules, additionalPrompts, }) => { @@ -200,6 +202,7 @@ const TUIChat: React.FC = ({ llmApi: services.model?.llmApi || undefined, initialPrompt, resume, + fork, additionalRules, additionalPrompts, onShowConfigSelector: () => navigateTo("config"), diff --git a/extensions/cli/src/ui/__tests__/TUIChat.fileSearch.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.fileSearch.test.tsx index 7f3c405c1..6dd14d1eb 100644 --- a/extensions/cli/src/ui/__tests__/TUIChat.fileSearch.test.tsx +++ b/extensions/cli/src/ui/__tests__/TUIChat.fileSearch.test.tsx @@ -1,8 +1,8 @@ -import { testBothModes, renderInMode } from "./TUIChat.dualModeHelper.js"; +import { testSingleMode, renderInMode } from "./TUIChat.dualModeHelper.js"; describe("TUIChat - @ File Search Tests", () => { - testBothModes("shows @ character when user types @", async (mode) => { - const { lastFrame, stdin } = renderInMode(mode); + testSingleMode("shows @ character when user types @", "local", async () => { + const { lastFrame, stdin } = renderInMode("local"); // Wait a bit for initial render await new Promise((resolve) => setTimeout(resolve, 50)); @@ -16,52 +16,43 @@ describe("TUIChat - @ File Search Tests", () => { const frame = lastFrame()!; // Should show @ character in input or show file search UI - // The @ might be in the input line or in a file search UI const hasAtSymbol = frame.includes("@") || frame.includes("◉ @"); expect(hasAtSymbol).toBe(true); - // Mode-specific UI - if (mode === "remote") { - expect(frame).toContain("Remote Mode"); - } else { - expect(frame).not.toContain("Remote Mode"); - expect(frame).toContain("Continue CLI"); - } + // Local mode specific UI expectations + expect(frame).not.toContain("Remote Mode"); + expect(frame).toContain("Continue CLI"); }); - testBothModes("shows search text when user types after @", async (mode) => { - const { lastFrame, stdin } = renderInMode(mode); + testSingleMode( + "shows search text when user types after @", + "local", + async () => { + const { lastFrame, stdin } = renderInMode("local"); - // Type @ followed by text to filter files - stdin.write("@READ"); + // Type @ followed by text to filter files + stdin.write("@READ"); - // Wait for file search to filter and display results - await new Promise((resolve) => setTimeout(resolve, 100)); + // Wait for file search to filter and display results + await new Promise((resolve) => setTimeout(resolve, 100)); - const frame = lastFrame()!; + const frame = lastFrame()!; - // Should show the typed text - expect(frame).toContain("@READ"); + // Should show the typed text + expect(frame).toContain("@READ"); - // In local mode, should show either navigation hints or files - if (mode === "local") { // Should show either navigation hints or at least indicate file search is working const hasNavigationHints = frame.includes("↑/↓ to navigate"); - const hasFileSearch = - frame.includes("@READ") && !frame.includes("Remote Mode"); + const hasFileSearch = frame.includes("@READ"); expect(hasNavigationHints || hasFileSearch).toBe(true); - } - // Mode-specific checks - if (mode === "remote") { - expect(frame).toContain("Remote Mode"); - } else { + // Local mode specific UI expectations expect(frame).not.toContain("Remote Mode"); - } - }); + }, + ); - testBothModes("handles multiple @ characters", async (mode) => { - const { lastFrame, stdin } = renderInMode(mode); + testSingleMode("handles multiple @ characters", "local", async () => { + const { lastFrame, stdin } = renderInMode("local"); // Type multiple @ characters stdin.write("@@test"); @@ -75,36 +66,32 @@ describe("TUIChat - @ File Search Tests", () => { expect(frame).toBeDefined(); expect(frame).toContain("@@test"); - // Mode-specific UI elements - if (mode === "remote") { - expect(frame).toContain("Remote Mode"); - } else { - expect(frame).toContain("Continue CLI"); - } + // Local mode specific UI elements + expect(frame).toContain("Continue CLI"); }); - testBothModes("handles @ character input without crashing", async (mode) => { - const { lastFrame, stdin } = renderInMode(mode); + testSingleMode( + "handles @ character input without crashing", + "local", + async () => { + const { lastFrame, stdin } = renderInMode("local"); - // Type @ to trigger file search - stdin.write("@"); + // Type @ to trigger file search + stdin.write("@"); - // Wait for potential async operations - await new Promise((resolve) => setTimeout(resolve, 50)); + // Wait for potential async operations + await new Promise((resolve) => setTimeout(resolve, 50)); - const frame = lastFrame()!; + const frame = lastFrame()!; - // Should not crash and show something - expect(frame).toBeDefined(); - expect(frame.length).toBeGreaterThan(0); + // Should not crash and show something + expect(frame).toBeDefined(); + expect(frame.length).toBeGreaterThan(0); - // In local mode, should show either navigation hints or file search UI - if (mode === "local") { // Should show either navigation hints or at least the @ character in file search const hasNavigationHints = frame.includes("↑/↓ to navigate"); - const hasFileSearchUI = - frame.includes("@") && !frame.includes("Remote Mode"); + const hasFileSearchUI = frame.includes("@"); expect(hasNavigationHints || hasFileSearchUI).toBe(true); - } - }); + }, + ); }); diff --git a/extensions/cli/src/ui/__tests__/TUIChat.slashCommands.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.slashCommands.test.tsx index b7c2d6b27..9bb1f0ee6 100644 --- a/extensions/cli/src/ui/__tests__/TUIChat.slashCommands.test.tsx +++ b/extensions/cli/src/ui/__tests__/TUIChat.slashCommands.test.tsx @@ -30,8 +30,10 @@ describe("TUIChat - Slash Commands Tests", () => { // Type /log to trigger slash command filtering stdin.write("/log"); - // Wait a bit for the UI to update - await new Promise((resolve) => setTimeout(resolve, 50)); + // Wait a bit for the UI to update (allow extra time in both modes) + await new Promise((resolve) => + setTimeout(resolve, mode === "remote" ? 200 : 150), + ); const frame = lastFrame(); @@ -81,7 +83,9 @@ describe("TUIChat - Slash Commands Tests", () => { // Type just / stdin.write("/"); - await new Promise((resolve) => setTimeout(resolve, 50)); + await new Promise((resolve) => + setTimeout(resolve, mode === "remote" ? 120 : 50), + ); const frame = lastFrame(); diff --git a/extensions/cli/src/ui/components/MemoizedMessage.tsx b/extensions/cli/src/ui/components/MemoizedMessage.tsx index 1b29a459d..ebec26450 100644 --- a/extensions/cli/src/ui/components/MemoizedMessage.tsx +++ b/extensions/cli/src/ui/components/MemoizedMessage.tsx @@ -117,7 +117,15 @@ export const MemoizedMessage = memo( > {isCompleted || isErrored ? "●" : "○"} diff --git a/extensions/cli/src/ui/hooks/useChat.helpers.ts b/extensions/cli/src/ui/hooks/useChat.helpers.ts index f6d947d1c..17aa450fb 100644 --- a/extensions/cli/src/ui/hooks/useChat.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.helpers.ts @@ -221,7 +221,6 @@ interface HandleSpecialCommandsOptions { remoteUrl?: string; onShowConfigSelector: () => void; exit: () => void; - setChatHistory: React.Dispatch>; } /** @@ -233,7 +232,6 @@ export async function handleSpecialCommands({ remoteUrl, onShowConfigSelector, exit, - setChatHistory, }: HandleSpecialCommandsOptions): Promise { const trimmedMessage = message.trim(); @@ -246,7 +244,7 @@ export async function handleSpecialCommands({ // Handle /exit command in remote mode if (isRemoteMode && remoteUrl && trimmedMessage === "/exit") { const { handleRemoteExit } = await import("./useChat.remote.helpers.js"); - await handleRemoteExit(remoteUrl, setChatHistory, exit); + await handleRemoteExit(remoteUrl, exit); return true; } diff --git a/extensions/cli/src/ui/hooks/useChat.remote.helpers.ts b/extensions/cli/src/ui/hooks/useChat.remote.helpers.ts index 75beb23ff..c173d3ae3 100644 --- a/extensions/cli/src/ui/hooks/useChat.remote.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.remote.helpers.ts @@ -1,10 +1,19 @@ import type { ChatHistoryItem } from "core/index.js"; +import { services } from "../../services/index.js"; import { posthogService } from "../../telemetry/posthogService.js"; import { logger } from "../../util/logger.js"; import { RemoteServerState } from "./useChat.types.js"; +function historiesEqual(a: ChatHistoryItem[], b: ChatHistoryItem[]): boolean { + if (a.length !== b.length) return false; + for (let i = 0; i < a.length; i++) { + if (JSON.stringify(a[i]) !== JSON.stringify(b[i])) return false; + } + return true; +} + /** * Poll remote server for state updates */ @@ -25,7 +34,6 @@ async function pollRemoteServerState( interface SetupRemotePollingOptions { remoteUrl: string; - setChatHistory: React.Dispatch>; setIsWaitingForResponse: React.Dispatch>; responseStartTime: number | null; setResponseStartTime: React.Dispatch>; @@ -36,7 +44,6 @@ interface SetupRemotePollingOptions { */ export function setupRemotePolling({ remoteUrl, - setChatHistory, setIsWaitingForResponse, responseStartTime, setResponseStartTime, @@ -54,7 +61,6 @@ export function setupRemotePolling({ if (state && isMounted) { updateStateFromRemote({ state, - setChatHistory, setIsWaitingForResponse, responseStartTime, setResponseStartTime, @@ -81,7 +87,6 @@ export function setupRemotePolling({ interface UpdateStateFromRemoteOptions { state: RemoteServerState; - setChatHistory: React.Dispatch>; setIsWaitingForResponse: React.Dispatch>; responseStartTime: number | null; setResponseStartTime: React.Dispatch>; @@ -92,37 +97,26 @@ interface UpdateStateFromRemoteOptions { */ function updateStateFromRemote({ state, - setChatHistory, setIsWaitingForResponse, responseStartTime, setResponseStartTime, }: UpdateStateFromRemoteOptions): void { // Update chat history from server - now using session.history directly if (state.session && state.session.history) { - setChatHistory((prevHistory) => { - // Use session history directly - it already has the correct type - const newHistory = state.session.history; - - // Quick length check first - if (prevHistory.length !== newHistory.length) { - return newHistory; - } - - // Deep comparison - check if content actually changed - const hasChanged = newHistory.some((item, index) => { - const prevItem = prevHistory[index]; - return ( - !prevItem || - prevItem.message.role !== item.message.role || - prevItem.message.content !== item.message.content || - JSON.stringify(prevItem.toolCallStates) !== - JSON.stringify(item.toolCallStates) - ); - }); - - // Only update if there are actual changes - return hasChanged ? newHistory : prevHistory; - }); + const newHistory = state.session.history as ChatHistoryItem[]; + // Let ChatHistoryService own the history and emit updates to UI + if (!services.chatHistory.isRemoteMode()) { + services.chatHistory.setRemoteMode(true); + } + // Avoid redundant updates: only set when history actually changed + try { + const current = services.chatHistory.getHistory(); + const changed = !historiesEqual(current, newHistory); + if (changed) services.chatHistory.setHistory(newHistory); + } catch { + // As a fallback, attempt to set history (service may handle no-op) + services.chatHistory.setHistory(newHistory); + } } // Update processing state @@ -139,7 +133,6 @@ function updateStateFromRemote({ */ export async function handleRemoteExit( remoteUrl: string, - setChatHistory: React.Dispatch>, exit: () => void, ): Promise { posthogService.capture("useSlashCommand", { @@ -152,50 +145,36 @@ export async function handleRemoteExit( }); if (response.ok) { - setChatHistory((prev) => [ - ...prev, - { - message: { - role: "system", - content: "Remote environment is shutting down...", - }, - contextItems: [], - }, - ]); + try { + services.chatHistory.addSystemMessage( + "Remote environment is shutting down...", + ); + } catch (err) { + logger.error("Failed to add system message", err); + } setTimeout(() => exit(), 1000); } else { const text = await response.text(); logger.error("Remote shutdown failed:", text); - setChatHistory((prev) => [ - ...prev, - { - message: { - role: "system", - content: "Failed to shutdown remote environment", - }, - contextItems: [], - }, - ]); + try { + services.chatHistory.addSystemMessage( + "Failed to shutdown remote environment", + ); + } catch {} } } catch (error) { logger.error("Failed to send exit request to remote server:", error); - setChatHistory((prev) => [ - ...prev, - { - message: { - role: "system", - content: "Error: Failed to connect to remote server for shutdown", - }, - contextItems: [], - }, - ]); + try { + services.chatHistory.addSystemMessage( + "Error: Failed to connect to remote server for shutdown", + ); + } catch {} } } interface HandleRemoteMessageOptions { remoteUrl: string; messageContent: string; - setChatHistory: React.Dispatch>; } /** @@ -204,7 +183,6 @@ interface HandleRemoteMessageOptions { export async function handleRemoteMessage({ remoteUrl, messageContent, - setChatHistory, }: HandleRemoteMessageOptions): Promise { try { const response = await fetch(`${remoteUrl}/message`, { @@ -217,29 +195,19 @@ export async function handleRemoteMessage({ if (!response.ok) { const error = await response.json(); - setChatHistory((prev) => [ - ...prev, - { - message: { - role: "system", - content: `Error: ${error.error || "Failed to send message"}`, - }, - contextItems: [], - }, - ]); + try { + services.chatHistory.addSystemMessage( + `Error: ${error.error || "Failed to send message"}`, + ); + } catch {} } // State will be updated by polling } catch (error) { logger.error("Failed to send message to remote server:", error); - setChatHistory((prev) => [ - ...prev, - { - message: { - role: "system", - content: `Error: Failed to connect to remote server`, - }, - contextItems: [], - }, - ]); + try { + services.chatHistory.addSystemMessage( + "Error: Failed to connect to remote server", + ); + } catch {} } } diff --git a/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts b/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts index aa2c19579..213c0212f 100644 --- a/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts @@ -1,5 +1,8 @@ import type { ChatHistoryItem, ToolCallState, ToolStatus } from "core/index.js"; +import { logger } from "src/util/logger.js"; + +import { services } from "../../services/index.js"; import { getCurrentSession, updateSessionTitle } from "../../session.js"; import { generateSessionTitle } from "./useChat.helpers.js"; @@ -23,18 +26,27 @@ export function createStreamCallbacks( onContent: (_: string) => {}, onContentComplete: async (content: string) => { - setChatHistory((prev) => [ - ...prev, - { - contextItems: [], - message: { - role: "assistant", - content: content, - isStreaming: false, - }, - }, - ]); - + // Do not add assistant messages via service; handleToolCalls is the single writer + // For environments where the service isn't ready (unit tests), update local state only + try { + const svc = services.chatHistory; + const useService = typeof svc?.isReady === "function" && svc.isReady(); + if (!useService && content) { + setChatHistory((prev) => [ + ...prev, + { + contextItems: [], + message: { + role: "assistant", + content: content, + isStreaming: false, + }, + }, + ]); + } + } catch (error) { + logger.error("Failed to update chat history", { error }); + } // Generate session title after first assistant response if (content && llmApi && model) { const currentSession = getCurrentSession(); @@ -52,10 +64,15 @@ export function createStreamCallbacks( }, onToolStart: (toolName: string, toolArgs?: any) => { + // When ChatHistoryService is ready, let handleToolCalls add entries + const svc = services.chatHistory; + const useService = typeof svc?.isReady === "function" && svc.isReady(); + if (useService) return; + + // Fallback (service not ready): create a local assistant message representing the tool call setChatHistory((prev) => { const newHistory = [...prev]; - // Always create a new assistant message for each tool call const toolCallId = `tool_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`; const toolCallState: ToolCallState = { toolCallId: toolCallId, @@ -95,17 +112,22 @@ export function createStreamCallbacks( }, onToolResult: (result: string, toolName: string, status: ToolStatus) => { + // When service is ready, it updates tool results; avoid duplicate local updates + const svc = services.chatHistory; + const useService = typeof svc?.isReady === "function" && svc.isReady(); + if (useService) return; + + // Fallback (service not ready): update local UI-only state setChatHistory((prev) => { const newHistory = [...prev]; - // Find the tool call state and update it for (let i = newHistory.length - 1; i >= 0; i--) { const item = newHistory[i]; if (item.toolCallStates) { const toolState = item.toolCallStates.find( (ts) => ts.toolCall.function.name === toolName && - ts.status === "calling", + (ts.status === "calling" || ts.status === "generated"), ); if (toolState) { @@ -127,10 +149,14 @@ export function createStreamCallbacks( }, onToolError: (error: string, toolName?: string) => { + // When service is ready, handleToolCalls adds error entries; avoid duplicate local updates + const svc = services.chatHistory; + const useService = typeof svc?.isReady === "function" && svc.isReady(); + if (useService) return; + setChatHistory((prev) => { const newHistory = [...prev]; - // Find the tool call state and mark it as errored if (toolName) { for (let i = newHistory.length - 1; i >= 0; i--) { const item = newHistory[i]; @@ -138,7 +164,7 @@ export function createStreamCallbacks( const toolState = item.toolCallStates.find( (ts) => ts.toolCall.function.name === toolName && - ts.status === "calling", + (ts.status === "calling" || ts.status === "generated"), ); if (toolState) { @@ -184,6 +210,14 @@ export function createStreamCallbacks( }, onSystemMessage: (message: string) => { + try { + const svc = services.chatHistory; + if (typeof svc?.isReady === "function" && svc.isReady()) { + svc.addSystemMessage(message); + return; + } + } catch {} + // Fallback to local state if service unavailable setChatHistory((prev) => [ ...prev, { @@ -241,8 +275,7 @@ export async function executeStreaming({ streamCallbacks, ); - // streamChatResponse modifies the array in place - // The new messages are already in historyForLLM + // Service-driven streaming; history updates occur via ChatHistoryService } else { await streamChatResponse( chatHistory, diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index 479fab094..c62854ed4 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -1,6 +1,6 @@ import type { ChatHistoryItem, Session } from "core/index.js"; import { useApp } from "ink"; -import { useEffect, useState } from "react"; +import { useEffect, useRef, useState } from "react"; import { findCompactionIndex } from "../../compaction.js"; import { toolPermissionManager } from "../../permissions/permissionManager.js"; @@ -46,6 +46,7 @@ export function useChat({ llmApi, initialPrompt, resume, + fork, additionalRules, additionalPrompts, onShowConfigSelector, @@ -59,6 +60,9 @@ export function useChat({ }: UseChatProps) { const { exit } = useApp(); + // Track service subscription + const serviceListenerCleanupRef = useRef void)>(null); + // Store the current session const [currentSession, setCurrentSession] = useState(() => { // In remote mode, start with empty session (will be populated by polling) @@ -66,6 +70,17 @@ export function useChat({ return createSession([]); } + // Fork from an existing session if fork flag is used + if (fork) { + const { loadSessionById, startNewSession } = require("../../session.js"); + const sessionToFork = loadSessionById(fork); + if (sessionToFork) { + return startNewSession(sessionToFork.history); + } + // If session not found, create a new empty session + return createSession([]); + } + // Load previous session if resume flag is used if (resume) { const savedSession = loadSession(); @@ -78,9 +93,45 @@ export function useChat({ return createSession([]); }); - const [chatHistory, setChatHistory] = useState( - () => currentSession.history, + // Local view of history driven solely by ChatHistoryService + const [chatHistory, setChatHistoryView] = useState(() => + services.chatHistory?.isReady() + ? services.chatHistory.getHistory() + : currentSession.history, ); + // Proxy setter: apply changes to ChatHistoryService (single source of truth) + const setChatHistory: React.Dispatch< + React.SetStateAction + > = (value) => { + const svc = services.chatHistory; + const current = svc.getHistory(); + const next = typeof value === "function" ? (value as any)(current) : value; + svc.setHistory(next); + }; + + // Initialize ChatHistoryService and subscribe to updates + useEffect(() => { + const svc = services.chatHistory; + svc + .initialize(currentSession, isRemoteMode) + .then(() => { + setChatHistoryView(svc.getHistory()); + const listener = () => { + setChatHistoryView(svc.getHistory()); + }; + svc.on("stateChanged", listener); + serviceListenerCleanupRef.current = () => + svc.off("stateChanged", listener); + }) + .catch((error) => { + logger.error("Failed to initialize ChatHistoryService", { error }); + }); + + return () => { + serviceListenerCleanupRef.current?.(); + serviceListenerCleanupRef.current = null; + }; + }, []); const [isWaitingForResponse, setIsWaitingForResponse] = useState(false); const [responseStartTime, setResponseStartTime] = useState( @@ -91,8 +142,11 @@ export function useChat({ useState(null); const [isChatHistoryInitialized, setIsChatHistoryInitialized] = useState( // If we're resuming and found a saved session, we're already initialized + // If we're forking and found a session to fork from, we're already initialized // If we're in remote mode, we're initialized (will be populated by polling) - isRemoteMode || (resume && currentSession.history.length > 0), + isRemoteMode || + (resume && currentSession.history.length > 0) || + (fork && currentSession.history.length > 0), ); // Capture initial rules to prevent re-initialization when rules change @@ -101,8 +155,8 @@ export function useChat({ const [activePermissionRequest, setActivePermissionRequest] = useState(null); const [compactionIndex, setCompactionIndex] = useState(() => { - // When resuming, check for compaction markers in the loaded history - if (resume && currentSession.history.length > 0) { + // When resuming or forking, check for compaction markers in the loaded history + if ((resume || fork) && currentSession.history.length > 0) { return findCompactionIndex(currentSession.history); } return null; @@ -126,7 +180,6 @@ export function useChat({ return setupRemotePolling({ remoteUrl, - setChatHistory, setIsWaitingForResponse, responseStartTime, setResponseStartTime, @@ -204,7 +257,7 @@ export function useChat({ try { const streamCallbacks = createStreamCallbacks({ - setChatHistory, + setChatHistory: setChatHistory, setActivePermissionRequest, llmApi, model, @@ -366,7 +419,6 @@ export function useChat({ remoteUrl, onShowConfigSelector, exit, - setChatHistory, }); if (handled) return; @@ -406,7 +458,6 @@ export function useChat({ await handleRemoteMessage({ remoteUrl, messageContent: messageContentString, - setChatHistory, }); return; } @@ -418,7 +469,7 @@ export function useChat({ model, llmApi, compactionIndex, - setChatHistory, + setChatHistory: setChatHistory, setCompactionIndex, }); @@ -549,7 +600,7 @@ export function useChat({ return { chatHistory, - setChatHistory, + setChatHistory: setChatHistory, isWaitingForResponse, responseStartTime, inputMode, diff --git a/extensions/cli/src/ui/hooks/useChat.types.ts b/extensions/cli/src/ui/hooks/useChat.types.ts index c34ebacac..a9a840184 100644 --- a/extensions/cli/src/ui/hooks/useChat.types.ts +++ b/extensions/cli/src/ui/hooks/useChat.types.ts @@ -10,6 +10,7 @@ export interface UseChatProps { llmApi?: BaseLlmApi; initialPrompt?: string; resume?: boolean; + fork?: string; additionalRules?: string[]; additionalPrompts?: string[]; onShowConfigSelector: () => void; diff --git a/extensions/cli/src/ui/hooks/useUserInput.ts b/extensions/cli/src/ui/hooks/useUserInput.ts index 558df58d6..aa99c421e 100644 --- a/extensions/cli/src/ui/hooks/useUserInput.ts +++ b/extensions/cli/src/ui/hooks/useUserInput.ts @@ -194,7 +194,7 @@ interface TextBufferStateOptions { export function updateTextBufferState(options: TextBufferStateOptions) { const { - handled, + handled: _handled, textBuffer, setInputText, setCursorPosition, @@ -204,7 +204,7 @@ export function updateTextBufferState(options: TextBufferStateOptions) { } = options; // Skip state updates during rapid input mode to avoid conflicts with timer-based updates - if (handled && !textBuffer.isInRapidInputMode()) { + if (!textBuffer.isInRapidInputMode()) { const newText = textBuffer.text; const newCursor = textBuffer.cursor; setInputText(newText); diff --git a/extensions/cli/src/ui/index.ts b/extensions/cli/src/ui/index.ts index d0225b8de..3b4edece4 100644 --- a/extensions/cli/src/ui/index.ts +++ b/extensions/cli/src/ui/index.ts @@ -12,6 +12,7 @@ export { MarkdownRenderer } from "./MarkdownRenderer.js"; interface StartTUIChatOptions { initialPrompt?: string; resume?: boolean; + fork?: string; config?: string; org?: string; rule?: string[]; @@ -31,6 +32,7 @@ export async function startTUIChat( const { initialPrompt, resume, + fork, config, org, rule, @@ -63,6 +65,7 @@ export async function startTUIChat( configPath: config, initialPrompt, resume, + fork, additionalRules: rule, additionalPrompts: prompt, }), diff --git a/extensions/cli/src/ui/types.ts b/extensions/cli/src/ui/types.ts deleted file mode 100644 index a18e4a9b2..000000000 --- a/extensions/cli/src/ui/types.ts +++ /dev/null @@ -1,2 +0,0 @@ -// This file has been intentionally left empty after migration to ChatHistoryItem -// All types have been migrated to use @continuedev/core types 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"