Changesets · Branches · Tags · Compare
| Changeset | 937b30c7b45d8666fe9b171d9fcebf28f3533f8998cd96c896ea74426ea4084b |
|---|---|
| Author | Nate Sesti <33237525+sestinj@users.noreply.github.com> · 2025-09-01 15:45 -07:00 |
| Committer | GitHub <noreply@github.com> · 2025-09-01 15:45 -07:00 |
| Parents | 4409bbdbfe8e, 6ea18b3a4328 |
34 files changed
added extensions/cli/CHAT_HISTORY_SERVICE_MIGRATION_PLAN.md +434 −0
| @@ -0,0 +1,434 @@ | ||
| 1 | +# ChatHistoryService Migration Plan | |
| 2 | + | |
| 3 | +## Overview | |
| 4 | + | |
| 5 | +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. | |
| 6 | + | |
| 7 | +## Current State Analysis | |
| 8 | + | |
| 9 | +### Problems | |
| 10 | + | |
| 11 | +- **Duplicate state**: Chat history exists in both React state (`useState`) and is directly mutated in arrays | |
| 12 | +- **Direct mutations**: `handleToolCalls.ts` uses `chatHistory.push()` bypassing React | |
| 13 | +- **Inconsistent updates**: Mix of `setChatHistory` callbacks and direct array modifications | |
| 14 | +- **Testing difficulties**: Hard to test and mock due to mixed patterns | |
| 15 | +- **Race conditions**: Potential for state inconsistencies | |
| 16 | + | |
| 17 | +### Affected Files | |
| 18 | + | |
| 19 | +- `src/ui/hooks/useChat.ts` - Main hook with React state | |
| 20 | +- `src/stream/handleToolCalls.ts` - Direct array mutations | |
| 21 | +- `src/stream/streamChatResponse.ts` - Mixed patterns | |
| 22 | +- `src/commands/serve.ts` - Direct mutations in remote mode | |
| 23 | +- `src/session.ts` - Session management | |
| 24 | + | |
| 25 | +## Migration Strategy | |
| 26 | + | |
| 27 | +### Phase 1: Create ChatHistoryService (Day 1) | |
| 28 | + | |
| 29 | +**Goal**: Establish the service foundation without breaking existing code | |
| 30 | + | |
| 31 | +#### 1.1 Create Service Implementation | |
| 32 | + | |
| 33 | +```typescript | |
| 34 | +// src/services/ChatHistoryService.ts | |
| 35 | +export interface ChatHistoryState { | |
| 36 | + history: ChatHistoryItem[]; | |
| 37 | + compactionIndex: number | null; | |
| 38 | + sessionId: string; | |
| 39 | + isRemoteMode: boolean; | |
| 40 | +} | |
| 41 | + | |
| 42 | +export class ChatHistoryService extends BaseService<ChatHistoryState> { | |
| 43 | + // Implementation details below | |
| 44 | +} | |
| 45 | +``` | |
| 46 | + | |
| 47 | +#### 1.2 Service Methods to Implement | |
| 48 | + | |
| 49 | +- `addUserMessage(content, contextItems)` | |
| 50 | +- `addAssistantMessage(content, toolCalls?)` | |
| 51 | +- `addSystemMessage(content)` | |
| 52 | +- `updateToolCallState(messageIndex, toolCallId, updates)` | |
| 53 | +- `addToolResult(toolCallId, result, status)` | |
| 54 | +- `compact(newHistory, compactionIndex)` | |
| 55 | +- `clear()` | |
| 56 | +- `loadSession(sessionId)` | |
| 57 | +- `getHistory()` - Returns immutable copy | |
| 58 | +- `getHistoryForLLM(compactionIndex?)` - For streaming | |
| 59 | + | |
| 60 | +#### 1.3 Register Service | |
| 61 | + | |
| 62 | +- Add to `src/services/index.ts` | |
| 63 | +- Add to ServiceContainer initialization | |
| 64 | +- Ensure proper initialization order | |
| 65 | + | |
| 66 | +#### 1.4 Write Unit Tests | |
| 67 | + | |
| 68 | +- Test all service methods | |
| 69 | +- Test event emissions | |
| 70 | +- Test immutability guarantees | |
| 71 | +- Test session integration | |
| 72 | + | |
| 73 | +**Deliverable**: Working service with tests, no integration yet | |
| 74 | + | |
| 75 | +### Phase 2: Wrapper Integration (Day 1-2) | |
| 76 | + | |
| 77 | +**Goal**: Wrap existing code to use service without changing behavior | |
| 78 | + | |
| 79 | +#### 2.1 Create Compatibility Layer | |
| 80 | + | |
| 81 | +```typescript | |
| 82 | +// src/services/ChatHistoryCompatibility.ts | |
| 83 | +export function createChatHistoryProxy(service: ChatHistoryService) { | |
| 84 | + return new Proxy([], { | |
| 85 | + get(target, prop) { | |
| 86 | + if (prop === "push") { | |
| 87 | + return (item) => service.addHistoryItem(item); | |
| 88 | + } | |
| 89 | + // Delegate reads to service.getHistory() | |
| 90 | + const history = service.getHistory(); | |
| 91 | + return history[prop]; | |
| 92 | + }, | |
| 93 | + }); | |
| 94 | +} | |
| 95 | +``` | |
| 96 | + | |
| 97 | +#### 2.2 Update useChat Hook | |
| 98 | + | |
| 99 | +- Initialize ChatHistoryService in useChat | |
| 100 | +- Keep existing `setChatHistory` for now | |
| 101 | +- Sync service changes to React state: | |
| 102 | + | |
| 103 | +```typescript | |
| 104 | +// In useChat.ts | |
| 105 | +const chatHistoryService = useService<ChatHistoryState>("chatHistory"); | |
| 106 | + | |
| 107 | +useEffect(() => { | |
| 108 | + if (chatHistoryService.state === "ready") { | |
| 109 | + setChatHistory(chatHistoryService.value.history); | |
| 110 | + } | |
| 111 | +}, [chatHistoryService]); | |
| 112 | +``` | |
| 113 | + | |
| 114 | +#### 2.3 Add Service Methods to Mirror State Updates | |
| 115 | + | |
| 116 | +- Wherever `setChatHistory` is called, also update service | |
| 117 | +- This creates temporary duplication but maintains compatibility | |
| 118 | + | |
| 119 | +**Deliverable**: Service running in parallel with existing state | |
| 120 | + | |
| 121 | +### Phase 3: Migrate Stream Processing (Day 2) | |
| 122 | + | |
| 123 | +**Goal**: Update streaming functions to use service | |
| 124 | + | |
| 125 | +#### 3.1 Update handleToolCalls.ts | |
| 126 | + | |
| 127 | +- Replace `chatHistory.push()` with service methods: | |
| 128 | + | |
| 129 | +```typescript | |
| 130 | +// Before: | |
| 131 | +chatHistory.push(createHistoryItem(...)); | |
| 132 | + | |
| 133 | +// After: | |
| 134 | +await chatHistoryService.addHistoryItem(createHistoryItem(...)); | |
| 135 | +``` | |
| 136 | + | |
| 137 | +#### 3.2 Update streamChatResponse.ts | |
| 138 | + | |
| 139 | +- Pass service instance instead of arrays | |
| 140 | +- Use service methods for all updates | |
| 141 | +- Remove direct array access | |
| 142 | + | |
| 143 | +#### 3.3 Update Stream Callbacks | |
| 144 | + | |
| 145 | +- Modify `createStreamCallbacks` in `useChat.stream.helpers.ts` | |
| 146 | +- Use service methods instead of `setChatHistory` | |
| 147 | +- Ensure proper event handling | |
| 148 | + | |
| 149 | +#### 3.4 Test Streaming | |
| 150 | + | |
| 151 | +- Test tool execution flow | |
| 152 | +- Test interruption handling | |
| 153 | +- Test auto-compaction | |
| 154 | +- Verify no direct mutations remain | |
| 155 | + | |
| 156 | +**Deliverable**: All streaming using service, no direct mutations | |
| 157 | + | |
| 158 | +### Phase 4: Remove React State Duplication (Day 2-3) | |
| 159 | + | |
| 160 | +**Goal**: Remove `useState` and rely solely on service | |
| 161 | + | |
| 162 | +#### 4.1 Update useChat to Use Service Directly | |
| 163 | + | |
| 164 | +```typescript | |
| 165 | +// Remove: | |
| 166 | +const [chatHistory, setChatHistory] = useState<ChatHistoryItem[]>(...); | |
| 167 | + | |
| 168 | +// Replace with: | |
| 169 | +const { value: chatHistoryState, state } = useService<ChatHistoryState>('chatHistory'); | |
| 170 | +const chatHistory = chatHistoryState?.history || []; | |
| 171 | +``` | |
| 172 | + | |
| 173 | +#### 4.2 Update All Components | |
| 174 | + | |
| 175 | +- Update components that receive `chatHistory` prop | |
| 176 | +- Ensure they handle potential undefined/loading states | |
| 177 | +- Update any direct `setChatHistory` calls | |
| 178 | + | |
| 179 | +#### 4.3 Remove Compatibility Layer | |
| 180 | + | |
| 181 | +- Remove the proxy wrapper | |
| 182 | +- Remove temporary sync code | |
| 183 | +- Clean up unused imports | |
| 184 | + | |
| 185 | +**Deliverable**: Single source of truth established | |
| 186 | + | |
| 187 | +### Phase 5: Optimize and Enhance (Day 3) | |
| 188 | + | |
| 189 | +**Goal**: Add optimizations and missing features | |
| 190 | + | |
| 191 | +#### 5.1 Performance Optimizations | |
| 192 | + | |
| 193 | +- Implement efficient diffing for large histories | |
| 194 | +- Add memoization where needed | |
| 195 | +- Optimize re-render triggers | |
| 196 | + | |
| 197 | +#### 5.2 Add Advanced Features | |
| 198 | + | |
| 199 | +- Implement undo/redo capability | |
| 200 | +- Add history branching for explorations | |
| 201 | +- Improve session management integration | |
| 202 | +- Add persistence strategies | |
| 203 | + | |
| 204 | +#### 5.3 Remote Mode Integration | |
| 205 | + | |
| 206 | +- Update `serve.ts` to use service | |
| 207 | +- Ensure remote sync works with service | |
| 208 | +- Test remote mode thoroughly | |
| 209 | + | |
| 210 | +#### 5.4 Update Documentation | |
| 211 | + | |
| 212 | +- Update code comments | |
| 213 | +- Update AGENTS.md with new patterns | |
| 214 | +- Create service usage examples | |
| 215 | + | |
| 216 | +**Deliverable**: Optimized service with full feature set | |
| 217 | + | |
| 218 | +Status: Completed | |
| 219 | + | |
| 220 | +- Remote mode now reads/writes chat history via ChatHistoryService; `/state` reflects the service’s history. | |
| 221 | +- Stream callbacks avoid duplicating tool entries; service is single source of truth. | |
| 222 | +- Added undo/redo to ChatHistoryService with tests (`canUndo/canRedo/undo/redo`). | |
| 223 | + | |
| 224 | +Notes: Further optimizations (batching/memoization) can be added if performance profiling indicates need with very large histories. | |
| 225 | + | |
| 226 | +### Phase 6: Validation and Cleanup (Day 3-4) | |
| 227 | + | |
| 228 | +**Goal**: Ensure migration is complete and stable | |
| 229 | + | |
| 230 | +#### 6.1 Comprehensive Testing | |
| 231 | + | |
| 232 | +- Run all existing tests | |
| 233 | +- Add integration tests for service | |
| 234 | +- Test all user flows (TUI, headless, remote) | |
| 235 | +- Performance testing with large histories | |
| 236 | + | |
| 237 | +#### 6.2 Code Cleanup | |
| 238 | + | |
| 239 | +- Removed direct history mutations in serve/stream paths where service is present; retained minimal fallbacks. | |
| 240 | +- Updated imports/types; removed unused `updateSessionHistory` in serve mode and pruned unused types. | |
| 241 | +- Verified service methods own persistence; remote mode disables persistence by design. | |
| 242 | + | |
| 243 | +#### 6.3 Migration Verification Checklist | |
| 244 | + | |
| 245 | +- [x] No direct array mutations remain where service is available (fallbacks kept for resilience) | |
| 246 | +- [x] All tests passing | |
| 247 | +- [x] Service handles all chat operations (user, assistant, tools, system, compaction) | |
| 248 | +- [x] React components update via service events | |
| 249 | +- [x] Session management integrated with service persistence | |
| 250 | +- [x] Remote mode reading/writing via service | |
| 251 | +- [x] Performance acceptable in tests; no regressions | |
| 252 | +- [x] No new console errors/warnings introduced | |
| 253 | + | |
| 254 | +## Rollback Plan | |
| 255 | + | |
| 256 | +If issues arise during migration: | |
| 257 | + | |
| 258 | +1. **Phase 1-2**: No impact, service runs in parallel | |
| 259 | +2. **Phase 3**: Revert stream processing changes, keep service | |
| 260 | +3. **Phase 4**: Revert to dual state temporarily | |
| 261 | +4. **Phase 5-6**: Feature flags for new capabilities | |
| 262 | + | |
| 263 | +## Testing Strategy | |
| 264 | + | |
| 265 | +### Unit Tests | |
| 266 | + | |
| 267 | +- Service methods individually | |
| 268 | +- Event emissions | |
| 269 | +- State immutability | |
| 270 | +- Error handling | |
| 271 | + | |
| 272 | +### Integration Tests | |
| 273 | + | |
| 274 | +- Service + React hooks | |
| 275 | +- Service + streaming | |
| 276 | +- Service + sessions | |
| 277 | +- Service + remote mode | |
| 278 | + | |
| 279 | +### E2E Tests | |
| 280 | + | |
| 281 | +- Full chat flows | |
| 282 | +- Tool execution | |
| 283 | +- Mode switching | |
| 284 | +- Session resume | |
| 285 | +- Interruption handling | |
| 286 | + | |
| 287 | +## Success Metrics | |
| 288 | + | |
| 289 | +1. **No regressions**: All existing functionality works | |
| 290 | +2. **Performance**: No noticeable slowdown | |
| 291 | +3. **Maintainability**: Cleaner, more testable code | |
| 292 | +4. **Reliability**: No state inconsistencies | |
| 293 | +5. **Developer experience**: Easier to understand and modify | |
| 294 | + | |
| 295 | +## Risk Mitigation | |
| 296 | + | |
| 297 | +### High Risk Areas | |
| 298 | + | |
| 299 | +1. **Streaming integration**: Most complex change | |
| 300 | + - Mitigation: Extensive testing, gradual rollout | |
| 301 | +2. **Remote mode**: Different state management | |
| 302 | + | |
| 303 | + - Mitigation: Test thoroughly, maintain compatibility | |
| 304 | + | |
| 305 | +3. **Performance**: Large histories might cause issues | |
| 306 | + - Mitigation: Profiling, optimization, lazy loading | |
| 307 | + | |
| 308 | +### Monitoring | |
| 309 | + | |
| 310 | +- Add logging for state transitions | |
| 311 | +- Monitor performance metrics | |
| 312 | +- Track error rates | |
| 313 | +- User feedback collection | |
| 314 | + | |
| 315 | +## Timeline | |
| 316 | + | |
| 317 | +- **Day 1**: Phase 1-2 (Service creation, wrapper) | |
| 318 | +- **Day 2**: Phase 3-4 (Stream migration, remove duplication) | |
| 319 | +- **Day 3**: Phase 5 (Optimization, features) | |
| 320 | +- **Day 4**: Phase 6 (Validation, cleanup) | |
| 321 | + | |
| 322 | +Total: 4 days with buffer for issues | |
| 323 | + | |
| 324 | +## Implementation Checklist | |
| 325 | + | |
| 326 | +### Pre-Migration | |
| 327 | + | |
| 328 | +- [ ] Current state documented | |
| 329 | +- [ ] All stakeholders informed | |
| 330 | +- [ ] Test environment ready | |
| 331 | +- [ ] Rollback plan confirmed | |
| 332 | + | |
| 333 | +### Phase 1 | |
| 334 | + | |
| 335 | +- [ ] ChatHistoryService created | |
| 336 | +- [ ] Unit tests written | |
| 337 | +- [ ] Service registered | |
| 338 | +- [ ] No breaking changes | |
| 339 | + | |
| 340 | +### Phase 2 | |
| 341 | + | |
| 342 | +- [ ] Compatibility layer working | |
| 343 | +- [ ] useChat integrated | |
| 344 | +- [ ] Parallel operation verified | |
| 345 | +- [ ] No regressions | |
| 346 | + | |
| 347 | +### Phase 3 | |
| 348 | + | |
| 349 | +- [ ] Stream processing migrated | |
| 350 | +- [ ] No direct mutations | |
| 351 | +- [ ] Tool handling updated | |
| 352 | +- [ ] Tests passing | |
| 353 | + | |
| 354 | +### Phase 4 | |
| 355 | + | |
| 356 | +- [ ] React state removed | |
| 357 | +- [ ] Service-only operation | |
| 358 | +- [ ] Components updated | |
| 359 | +- [ ] Performance acceptable | |
| 360 | + | |
| 361 | +### Phase 5 | |
| 362 | + | |
| 363 | +- [ ] Optimizations implemented | |
| 364 | +- [ ] Features added | |
| 365 | +- [ ] Remote mode working | |
| 366 | +- [ ] Documentation updated | |
| 367 | + | |
| 368 | +### Phase 6 | |
| 369 | + | |
| 370 | +- [ ] All tests passing | |
| 371 | +- [ ] Code cleaned up | |
| 372 | +- [ ] Migration complete | |
| 373 | +- [ ] Team sign-off | |
| 374 | + | |
| 375 | +## Post-Migration | |
| 376 | + | |
| 377 | +1. Monitor for issues for 1 week | |
| 378 | +2. Gather performance metrics | |
| 379 | +3. Document lessons learned | |
| 380 | +4. Plan future enhancements | |
| 381 | +5. Knowledge transfer to team | |
| 382 | + | |
| 383 | +## Appendix: Code Examples | |
| 384 | + | |
| 385 | +### Service Method Example | |
| 386 | + | |
| 387 | +```typescript | |
| 388 | +class ChatHistoryService extends BaseService<ChatHistoryState> { | |
| 389 | + addUserMessage(content: string, contextItems: any[] = []) { | |
| 390 | + const newMessage: ChatHistoryItem = { | |
| 391 | + message: { role: "user", content }, | |
| 392 | + contextItems, | |
| 393 | + }; | |
| 394 | + | |
| 395 | + const newHistory = [...this.currentState.history, newMessage]; | |
| 396 | + this.setState({ | |
| 397 | + ...this.currentState, | |
| 398 | + history: newHistory, | |
| 399 | + }); | |
| 400 | + | |
| 401 | + // Auto-save to session | |
| 402 | + updateSessionHistory(newHistory); | |
| 403 | + | |
| 404 | + return newMessage; | |
| 405 | + } | |
| 406 | +} | |
| 407 | +``` | |
| 408 | + | |
| 409 | +### React Integration Example | |
| 410 | + | |
| 411 | +```typescript | |
| 412 | +function ChatComponent() { | |
| 413 | + const { value: chatState, state } = useService<ChatHistoryState>('chatHistory'); | |
| 414 | + | |
| 415 | + if (state === 'loading') return <LoadingSpinner />; | |
| 416 | + if (state === 'error') return <ErrorMessage />; | |
| 417 | + | |
| 418 | + const history = chatState?.history || []; | |
| 419 | + | |
| 420 | + return <ChatMessages history={history} />; | |
| 421 | +} | |
| 422 | +``` | |
| 423 | + | |
| 424 | +### Migration Pattern Example | |
| 425 | + | |
| 426 | +```typescript | |
| 427 | +// Before: | |
| 428 | +chatHistory.push(newMessage); | |
| 429 | +setChatHistory([...chatHistory]); | |
| 430 | + | |
| 431 | +// After: | |
| 432 | +chatHistoryService.addMessage(newMessage); | |
| 433 | +// React auto-updates via useService hook | |
| 434 | +``` |
modified extensions/cli/package-lock.json +0 −0
Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.
modified extensions/cli/package.json +1 −0
| @@ -97,6 +97,7 @@ | ||
| 97 | 97 | "eslint-plugin-import": "^2.32.0", |
| 98 | 98 | "eslint-plugin-unused-imports": "^4.1.4", |
| 99 | 99 | "execa": "^9.6.0", |
| 100 | + "clipboardy": "^4.0.0", | |
| 100 | 101 | "express": "^5.1.0", |
| 101 | 102 | "glob": "^11.0.3", |
| 102 | 103 | "gpt-tokenizer": "^3.0.1", |
modified extensions/cli/src/args.ts +8 −0
| @@ -3,6 +3,7 @@ | ||
| 3 | 3 | organizationSlug?: string; // Organization slug to use for this session |
| 4 | 4 | prompt?: string; // Optional prompt argument |
| 5 | 5 | resume?: boolean; // Resume from last session |
| 6 | + fork?: string; // Fork from an existing session ID | |
| 6 | 7 | readonly?: boolean; // Start in plan mode (backward compatibility) |
| 7 | 8 | rules?: string[]; // Array of rule specifications |
| 8 | 9 | mcps?: string[]; // Array of MCP server slugs from the hub |
| @@ -71,6 +72,12 @@ | ||
| 71 | 72 | result.readonly = true; |
| 72 | 73 | } |
| 73 | 74 | |
| 75 | + // Parse fork flag | |
| 76 | + const forkValue = extractSingleFlag(args, "--fork"); | |
| 77 | + if (forkValue) { | |
| 78 | + result.fork = forkValue; | |
| 79 | + } | |
| 80 | + | |
| 74 | 81 | // Parse single-value flags |
| 75 | 82 | const formatValue = extractSingleFlag(args, "--format"); |
| 76 | 83 | if (formatValue === "json") { |
| @@ -124,6 +131,7 @@ | ||
| 124 | 131 | "--model", |
| 125 | 132 | "--prompt", |
| 126 | 133 | "--format", |
| 134 | + "--fork", | |
| 127 | 135 | ]; |
| 128 | 136 | const nonFlagArgs = args.filter((arg, index) => { |
| 129 | 137 | if (arg.startsWith("--") || arg === "-p") return false; |
modified extensions/cli/src/commands/chat.ts +62 −51
| @@ -4,17 +4,13 @@ | ||
| 4 | 4 | import { ChatDescriber } from "core/util/chatDescriber.js"; |
| 5 | 5 | import * as readlineSync from "readline-sync"; |
| 6 | 6 | |
| 7 | -import { | |
| 8 | - compactChatHistory, | |
| 9 | - findCompactionIndex, | |
| 10 | - getHistoryForLLM, | |
| 11 | -} from "../compaction.js"; | |
| 7 | +import { compactChatHistory, findCompactionIndex } from "../compaction.js"; | |
| 12 | 8 | import { processCommandFlags } from "../flags/flagProcessor.js"; |
| 13 | 9 | import { safeStdout } from "../init.js"; |
| 14 | 10 | import { configureLogger } from "../logger.js"; |
| 15 | 11 | import * as logging from "../logging.js"; |
| 16 | 12 | import { sentryService } from "../sentry.js"; |
| 17 | -import { initializeServices } from "../services/index.js"; | |
| 13 | +import { initializeServices, services } from "../services/index.js"; | |
| 18 | 14 | import { serviceContainer } from "../services/ServiceContainer.js"; |
| 19 | 15 | import { ModelServiceState, SERVICE_NAMES } from "../services/types.js"; |
| 20 | 16 | import { |
| @@ -80,6 +76,7 @@ | ||
| 80 | 76 | export interface ChatOptions extends ExtendedCommandOptions { |
| 81 | 77 | headless?: boolean; |
| 82 | 78 | resume?: boolean; |
| 79 | + fork?: string; // Fork from an existing session ID | |
| 83 | 80 | format?: "json"; // Output format for headless mode |
| 84 | 81 | silent?: boolean; // Strip <think></think> tags and excess whitespace |
| 85 | 82 | } |
| @@ -89,6 +86,20 @@ | ||
| 89 | 86 | ): Promise<ChatHistoryItem[]> { |
| 90 | 87 | let session: Session | null = null; |
| 91 | 88 | |
| 89 | + // Fork from an existing session if --fork flag is used | |
| 90 | + if (options.fork) { | |
| 91 | + const { loadSessionById, startNewSession } = await import("../session.js"); | |
| 92 | + const sessionToFork = loadSessionById(options.fork); | |
| 93 | + if (sessionToFork) { | |
| 94 | + logger.info(chalk.yellow("Forking from existing session...")); | |
| 95 | + const newSession = startNewSession(sessionToFork.history); | |
| 96 | + return newSession.history; | |
| 97 | + } else { | |
| 98 | + logger.error(chalk.red(`Session with ID "${options.fork}" not found.`)); | |
| 99 | + process.exit(1); | |
| 100 | + } | |
| 101 | + } | |
| 102 | + | |
| 92 | 103 | // Load previous session if --resume flag is used |
| 93 | 104 | if (options.resume) { |
| 94 | 105 | session = loadSession(); |
| @@ -115,21 +126,21 @@ | ||
| 115 | 126 | } |
| 116 | 127 | |
| 117 | 128 | try { |
| 118 | - const result = await compactChatHistory(chatHistory, model, llmApi); | |
| 119 | - | |
| 120 | - // Replace chat history with compacted version | |
| 121 | - chatHistory.length = 0; | |
| 122 | - chatHistory.push(...result.compactedHistory); | |
| 123 | - | |
| 124 | - // Save the compacted session | |
| 125 | - updateSessionHistory(chatHistory); | |
| 129 | + const current = services.chatHistory.getHistory(); | |
| 130 | + const result = await compactChatHistory(current, model, llmApi); | |
| 131 | + | |
| 132 | + // Update service-driven history (persistence handled by service) | |
| 133 | + services.chatHistory.compact( | |
| 134 | + result.compactedHistory, | |
| 135 | + result.compactionIndex, | |
| 136 | + ); | |
| 126 | 137 | |
| 127 | 138 | if (isHeadless) { |
| 128 | 139 | safeStdout( |
| 129 | 140 | JSON.stringify({ |
| 130 | 141 | status: "success", |
| 131 | 142 | message: "Chat history compacted", |
| 132 | - historyLength: chatHistory.length, | |
| 143 | + historyLength: services.chatHistory.getHistory().length, | |
| 133 | 144 | }) + "\n", |
| 134 | 145 | ); |
| 135 | 146 | } else { |
| @@ -176,7 +187,7 @@ | ||
| 176 | 187 | message: "Auto-compacting triggered", |
| 177 | 188 | contextUsage: |
| 178 | 189 | calculateContextUsagePercentage( |
| 179 | - countChatHistoryTokens(chatHistory), | |
| 190 | + countChatHistoryTokens(services.chatHistory.getHistory()), | |
| 180 | 191 | model, |
| 181 | 192 | ) + "%", |
| 182 | 193 | }) + "\n", |
| @@ -186,11 +197,11 @@ | ||
| 186 | 197 | if (!isHeadless) { |
| 187 | 198 | console.info(chalk.green(message)); |
| 188 | 199 | } else if (format === "json") { |
| 200 | + // Omit history length here; service updates occur after compaction completes | |
| 189 | 201 | safeStdout( |
| 190 | 202 | JSON.stringify({ |
| 191 | 203 | status: "success", |
| 192 | 204 | message: "Auto-compacted successfully", |
| 193 | - historyLength: chatHistory.length, | |
| 194 | 205 | }) + "\n", |
| 195 | 206 | ); |
| 196 | 207 | } |
| @@ -210,15 +221,19 @@ | ||
| 210 | 221 | }, |
| 211 | 222 | }; |
| 212 | 223 | |
| 213 | - const result = await coreAutoCompaction(chatHistory, model, llmApi, { | |
| 214 | - isHeadless, | |
| 215 | - format, | |
| 216 | - callbacks, | |
| 217 | - }); | |
| 224 | + const result = await coreAutoCompaction( | |
| 225 | + services.chatHistory.getHistory(), | |
| 226 | + model, | |
| 227 | + llmApi, | |
| 228 | + { | |
| 229 | + isHeadless, | |
| 230 | + format, | |
| 231 | + callbacks, | |
| 232 | + }, | |
| 233 | + ); | |
| 218 | 234 | |
| 219 | - // Update the original array reference for headless mode | |
| 220 | - chatHistory.length = 0; | |
| 221 | - chatHistory.push(...result.chatHistory); | |
| 235 | + // Update service-driven history | |
| 236 | + services.chatHistory.setHistory(result.chatHistory); | |
| 222 | 237 | |
| 223 | 238 | return result.compactionIndex; |
| 224 | 239 | } |
| @@ -286,7 +301,7 @@ | ||
| 286 | 301 | telemetryService.logUserPrompt(userInput.length, userInput); |
| 287 | 302 | |
| 288 | 303 | // Check if auto-compacting is needed BEFORE adding user message |
| 289 | - if (shouldAutoCompact(chatHistory, model)) { | |
| 304 | + if (shouldAutoCompact(services.chatHistory.getHistory(), model)) { | |
| 290 | 305 | const newIndex = await handleAutoCompaction( |
| 291 | 306 | chatHistory, |
| 292 | 307 | model, |
| @@ -296,17 +311,12 @@ | ||
| 296 | 311 | ); |
| 297 | 312 | if (newIndex !== null) { |
| 298 | 313 | compactionIndex = newIndex; |
| 299 | - // Replace chatHistory with compacted version | |
| 300 | - chatHistory.length = 0; | |
| 301 | - chatHistory.push(...chatHistory); | |
| 314 | + // Service already updated in handleAutoCompaction via setHistory | |
| 302 | 315 | } |
| 303 | 316 | } |
| 304 | 317 | |
| 305 | 318 | // Add user message to history AFTER potential compaction |
| 306 | - chatHistory.push({ | |
| 307 | - message: { role: "user", content: userInput }, | |
| 308 | - contextItems: [], | |
| 309 | - }); | |
| 319 | + services.chatHistory.addUserMessage(userInput); | |
| 310 | 320 | |
| 311 | 321 | // Get AI response with potential tool usage |
| 312 | 322 | if (!isHeadless) { |
| @@ -316,12 +326,12 @@ | ||
| 316 | 326 | try { |
| 317 | 327 | const abortController = new AbortController(); |
| 318 | 328 | |
| 319 | - // Handle compaction properly - streamChatResponse modifies the array in place | |
| 329 | + // Service-driven streaming; history updates occur via ChatHistoryService | |
| 320 | 330 | let finalResponse; |
| 321 | 331 | if (compactionIndex !== null && compactionIndex !== undefined) { |
| 322 | - // When using compaction, we need to send a subset but capture the full history | |
| 323 | - const historyForLLM = getHistoryForLLM(chatHistory, compactionIndex); | |
| 324 | - const originalLength = historyForLLM.length; | |
| 332 | + // Use service to compute history for LLM | |
| 333 | + const historyForLLM = | |
| 334 | + services.chatHistory.getHistoryForLLM(compactionIndex); | |
| 325 | 335 | |
| 326 | 336 | finalResponse = await streamChatResponse( |
| 327 | 337 | historyForLLM, |
| @@ -329,19 +339,14 @@ | ||
| 329 | 339 | llmApi, |
| 330 | 340 | abortController, |
| 331 | 341 | ); |
| 332 | - | |
| 333 | - // Append any new messages (assistant/tool) that were added by streamChatResponse | |
| 334 | - const newMessages = historyForLLM.slice(originalLength); | |
| 335 | - chatHistory.push(...newMessages); | |
| 336 | 342 | } else { |
| 337 | - // No compaction - just pass the full history directly | |
| 343 | + // No compaction - get full history from service | |
| 338 | 344 | finalResponse = await streamChatResponse( |
| 339 | - chatHistory, | |
| 345 | + services.chatHistory.getHistory(), | |
| 340 | 346 | model, |
| 341 | 347 | llmApi, |
| 342 | 348 | abortController, |
| 343 | 349 | ); |
| 344 | - // No need to sync back - streamChatResponse modifies chatHistory in place | |
| 345 | 350 | } |
| 346 | 351 | |
| 347 | 352 | // Generate session title after first assistant response |
| @@ -368,7 +373,7 @@ | ||
| 368 | 373 | } |
| 369 | 374 | |
| 370 | 375 | // Save session after each successful response |
| 371 | - updateSessionHistory(chatHistory); | |
| 376 | + updateSessionHistory(services.chatHistory.getHistory()); | |
| 372 | 377 | } catch (e: any) { |
| 373 | 378 | const error = e instanceof Error ? e : new Error(String(e)); |
| 374 | 379 | |
| @@ -381,11 +386,17 @@ | ||
| 381 | 386 | sentryService.captureException(error, { |
| 382 | 387 | context: "chat_response", |
| 383 | 388 | isHeadless, |
| 384 | - chatHistoryLength: chatHistory.length, | |
| 389 | + chatHistoryLength: services.chatHistory.getHistory().length, | |
| 385 | 390 | }); |
| 386 | 391 | if (!isHeadless) { |
| 387 | 392 | logger.info( |
| 388 | - chalk.dim(`Chat history:\n${JSON.stringify(chatHistory, null, 2)}`), | |
| 393 | + chalk.dim( | |
| 394 | + `Chat history:\n${JSON.stringify( | |
| 395 | + services.chatHistory.getHistory(), | |
| 396 | + null, | |
| 397 | + 2, | |
| 398 | + )}`, | |
| 399 | + ), | |
| 389 | 400 | ); |
| 390 | 401 | } |
| 391 | 402 | } |
| @@ -414,12 +425,11 @@ | ||
| 414 | 425 | throw new Error("No models were found."); |
| 415 | 426 | } |
| 416 | 427 | |
| 417 | - // Initialize chat history | |
| 428 | + // Initialize service-driven history (resume if requested) | |
| 418 | 429 | const chatHistory = await initializeChatHistory(options); |
| 419 | - | |
| 420 | - // Track compaction index if resuming with compacted history | |
| 421 | 430 | let compactionIndex: number | null = null; |
| 422 | - if (options.resume) { | |
| 431 | + if (options.resume || options.fork) { | |
| 432 | + services.chatHistory.setHistory(chatHistory); | |
| 423 | 433 | compactionIndex = findCompactionIndex(chatHistory); |
| 424 | 434 | } |
| 425 | 435 | |
| @@ -502,6 +512,7 @@ | ||
| 502 | 512 | const tuiOptions: any = { |
| 503 | 513 | initialPrompt: prompt, |
| 504 | 514 | resume: options.resume, |
| 515 | + fork: options.fork, | |
| 505 | 516 | config: options.config, |
| 506 | 517 | org: options.org, |
| 507 | 518 | rule: options.rule, |
modified extensions/cli/src/commands/commands.ts +5 −0
| @@ -76,6 +76,11 @@ | ||
| 76 | 76 | description: "Resume a previous chat session", |
| 77 | 77 | category: "system", |
| 78 | 78 | }, |
| 79 | + { | |
| 80 | + name: "fork", | |
| 81 | + description: "Start a forked chat session from the current history", | |
| 82 | + category: "system", | |
| 83 | + }, | |
| 79 | 84 | { |
| 80 | 85 | name: "exit", |
| 81 | 86 | description: "Exit the chat", |
modified extensions/cli/src/commands/serve.helpers.ts +30 −56
| @@ -1,7 +1,9 @@ | ||
| 1 | -import type { Session, ToolCallState, ToolStatus } from "core/index.js"; | |
| 1 | +import type { Session, ToolStatus } from "core/index.js"; | |
| 2 | 2 | |
| 3 | +import { services } from "../services/index.js"; | |
| 3 | 4 | import { streamChatResponse } from "../stream/streamChatResponse.js"; |
| 4 | 5 | import { StreamCallbacks } from "../stream/streamChatResponse.types.js"; |
| 6 | +import { logger } from "../util/logger.js"; | |
| 5 | 7 | |
| 6 | 8 | // Modified version of streamChatResponse that supports interruption |
| 7 | 9 | export async function streamChatResponseWithInterruption( |
| @@ -38,47 +40,11 @@ | ||
| 38 | 40 | // This callback is just for notification/UI updates |
| 39 | 41 | // The tool call state is already created and added by handleToolCalls |
| 40 | 42 | }, |
| 41 | - onToolResult: (result: string, toolName: string, status: ToolStatus) => { | |
| 42 | - // Update only the tool call state status | |
| 43 | - // The actual result is already added as a separate message by handleToolCalls | |
| 44 | - for (let i = state.session.history.length - 1; i >= 0; i--) { | |
| 45 | - const item = state.session.history[i]; | |
| 46 | - if (item.toolCallStates) { | |
| 47 | - const toolState = item.toolCallStates.find( | |
| 48 | - (ts: ToolCallState) => | |
| 49 | - ts.toolCall.function.name === toolName && | |
| 50 | - (ts.status === "calling" || ts.status === "generated"), | |
| 51 | - ); | |
| 52 | - if (toolState) { | |
| 53 | - // Only update the status, not the output | |
| 54 | - toolState.status = status; | |
| 55 | - break; | |
| 56 | - } | |
| 57 | - } | |
| 58 | - } | |
| 43 | + onToolResult: (_result: string, _toolName: string, _status: ToolStatus) => { | |
| 44 | + // No-op when using ChatHistoryService; it updates tool states/results | |
| 59 | 45 | }, |
| 60 | - onToolError: (error: string, toolName?: string) => { | |
| 61 | - // Only update the tool call state to errored status when tool name is provided | |
| 62 | - // The error message is already added as a separate tool result message | |
| 63 | - // by handleToolCalls/preprocessStreamedToolCalls/executeStreamedToolCalls | |
| 64 | - if (toolName) { | |
| 65 | - // Find and update the corresponding tool call state | |
| 66 | - for (let i = state.session.history.length - 1; i >= 0; i--) { | |
| 67 | - const item = state.session.history[i]; | |
| 68 | - if (item.toolCallStates) { | |
| 69 | - const toolState = item.toolCallStates.find( | |
| 70 | - (ts: ToolCallState) => | |
| 71 | - ts.toolCall.function.name === toolName && | |
| 72 | - (ts.status === "calling" || ts.status === "generated"), | |
| 73 | - ); | |
| 74 | - if (toolState) { | |
| 75 | - // Only update the status, not the output | |
| 76 | - toolState.status = "errored"; | |
| 77 | - break; | |
| 78 | - } | |
| 79 | - } | |
| 80 | - } | |
| 81 | - } | |
| 46 | + onToolError: (_error: string, _toolName?: string) => { | |
| 47 | + // No-op; errors are added to history via handleToolCalls flow | |
| 82 | 48 | }, |
| 83 | 49 | onToolPermissionRequest: ( |
| 84 | 50 | toolName: string, |
| @@ -95,25 +61,33 @@ | ||
| 95 | 61 | toolCallPreview, |
| 96 | 62 | }; |
| 97 | 63 | |
| 98 | - // Add a system message indicating permission is needed | |
| 99 | - state.session.history.push({ | |
| 100 | - message: { | |
| 101 | - role: "system", | |
| 102 | - content: `WARNING: Tool ${toolName} requires permission`, | |
| 103 | - }, | |
| 104 | - contextItems: [], | |
| 105 | - }); | |
| 64 | + // Add a system message indicating permission is needed via service | |
| 65 | + try { | |
| 66 | + services.chatHistory.addSystemMessage( | |
| 67 | + `WARNING: Tool ${toolName} requires permission`, | |
| 68 | + ); | |
| 69 | + } catch (err) { | |
| 70 | + // Do not mutate session history; ChatHistoryService is the source of truth | |
| 71 | + logger.error( | |
| 72 | + "Failed to add system message via ChatHistoryService", | |
| 73 | + err, | |
| 74 | + { context: "onToolPermissionRequest", toolName, requestId }, | |
| 75 | + ); | |
| 76 | + } | |
| 106 | 77 | |
| 107 | 78 | // Don't wait here - the streamChatResponse will handle waiting |
| 108 | 79 | }, |
| 109 | 80 | onSystemMessage: (message: string) => { |
| 110 | - state.session.history.push({ | |
| 111 | - message: { | |
| 112 | - role: "system", | |
| 113 | - content: message, | |
| 114 | - }, | |
| 115 | - contextItems: [], | |
| 116 | - }); | |
| 81 | + try { | |
| 82 | + services.chatHistory.addSystemMessage(message); | |
| 83 | + } catch (err) { | |
| 84 | + // Do not mutate session history; ChatHistoryService is the source of truth | |
| 85 | + logger.error( | |
| 86 | + "Failed to add system message via ChatHistoryService", | |
| 87 | + err, | |
| 88 | + { context: "onSystemMessage" }, | |
| 89 | + ); | |
| 90 | + } | |
| 117 | 91 | }, |
| 118 | 92 | }; |
| 119 | 93 |
modified extensions/cli/src/commands/serve.ts +61 −23
| @@ -12,13 +12,14 @@ | ||
| 12 | 12 | getService, |
| 13 | 13 | initializeServices, |
| 14 | 14 | SERVICE_NAMES, |
| 15 | + services, | |
| 15 | 16 | } from "../services/index.js"; |
| 16 | 17 | import { |
| 17 | 18 | AuthServiceState, |
| 18 | 19 | ConfigServiceState, |
| 19 | 20 | ModelServiceState, |
| 20 | 21 | } from "../services/types.js"; |
| 21 | -import { createSession, updateSessionHistory } from "../session.js"; | |
| 22 | +import { createSession } from "../session.js"; | |
| 22 | 23 | import { constructSystemMessage } from "../systemMessage.js"; |
| 23 | 24 | import { telemetryService } from "../telemetry/telemetryService.js"; |
| 24 | 25 | import { formatError } from "../util/formatError.js"; |
| @@ -38,6 +39,7 @@ | ||
| 38 | 39 | port?: string; |
| 39 | 40 | } |
| 40 | 41 | |
| 42 | +// eslint-disable-next-line max-statements | |
| 41 | 43 | export async function serve(prompt?: string, options: ServeOptions = {}) { |
| 42 | 44 | // Check if prompt should come from stdin instead of parameter |
| 43 | 45 | let actualPrompt = prompt; |
| @@ -122,6 +124,13 @@ | ||
| 122 | 124 | |
| 123 | 125 | const session = createSession(initialHistory); |
| 124 | 126 | |
| 127 | + // Align ChatHistoryService with server session and enable remote mode | |
| 128 | + try { | |
| 129 | + await services.chatHistory.initialize(session, false); | |
| 130 | + } catch { | |
| 131 | + // Fallback: continue even if service init fails; stream will still work with arrays | |
| 132 | + } | |
| 133 | + | |
| 125 | 134 | // Initialize server state |
| 126 | 135 | const state: ServerState = { |
| 127 | 136 | session, |
| @@ -146,6 +155,14 @@ | ||
| 146 | 155 | // GET /state - Return the current state |
| 147 | 156 | app.get("/state", (_req: Request, res: Response) => { |
| 148 | 157 | state.lastActivity = Date.now(); |
| 158 | + // Ensure session history reflects ChatHistoryService state | |
| 159 | + try { | |
| 160 | + state.session.history = services.chatHistory.getHistory(); | |
| 161 | + } catch (e) { | |
| 162 | + logger.debug( | |
| 163 | + `Failed to sync session history from ChatHistoryService: ${formatError(e)}`, | |
| 164 | + ); | |
| 165 | + } | |
| 149 | 166 | res.json({ |
| 150 | 167 | session: state.session, // Return session directly instead of converting |
| 151 | 168 | isProcessing: state.isProcessing, |
| @@ -328,6 +345,27 @@ | ||
| 328 | 345 | }); |
| 329 | 346 | |
| 330 | 347 | // Process messages from the queue |
| 348 | + function removePartialAssistantMessage(state: ServerState) { | |
| 349 | + try { | |
| 350 | + const svcHistory = services.chatHistory.getHistory(); | |
| 351 | + const last = svcHistory[svcHistory.length - 1]; | |
| 352 | + if (last && last.message.role === "assistant" && !last.message.content) { | |
| 353 | + const trimmed = svcHistory.slice(0, -1); | |
| 354 | + services.chatHistory.setHistory(trimmed); | |
| 355 | + } | |
| 356 | + } catch { | |
| 357 | + const lastMessage = | |
| 358 | + state.session.history[state.session.history.length - 1]; | |
| 359 | + if ( | |
| 360 | + lastMessage && | |
| 361 | + lastMessage.message.role === "assistant" && | |
| 362 | + !lastMessage.message.content | |
| 363 | + ) { | |
| 364 | + state.session.history.pop(); | |
| 365 | + } | |
| 366 | + } | |
| 367 | + } | |
| 368 | + | |
| 331 | 369 | async function processMessages(state: ServerState, llmApi: any) { |
| 332 | 370 | while (state.messageQueue.length > 0 && state.serverRunning) { |
| 333 | 371 | const userMessage = state.messageQueue.shift()!; |
| @@ -335,11 +373,16 @@ | ||
| 335 | 373 | state.shouldInterrupt = false; |
| 336 | 374 | state.lastActivity = Date.now(); |
| 337 | 375 | |
| 338 | - // Add user message to history | |
| 339 | - state.session.history.push({ | |
| 340 | - message: { role: "user", content: userMessage }, | |
| 341 | - contextItems: [], | |
| 342 | - }); | |
| 376 | + // Add user message via ChatHistoryService (single source of truth) | |
| 377 | + try { | |
| 378 | + services.chatHistory.addUserMessage(userMessage); | |
| 379 | + } catch { | |
| 380 | + // Fallback to local array if service unavailable | |
| 381 | + state.session.history.push({ | |
| 382 | + message: { role: "user", content: userMessage }, | |
| 383 | + contextItems: [], | |
| 384 | + }); | |
| 385 | + } | |
| 343 | 386 | |
| 344 | 387 | try { |
| 345 | 388 | // Create new abort controller for this response |
| @@ -353,31 +396,26 @@ | ||
| 353 | 396 | () => state.shouldInterrupt, |
| 354 | 397 | ); |
| 355 | 398 | |
| 356 | - // Save session after successful response | |
| 357 | - updateSessionHistory(state.session.history); | |
| 399 | + // No direct persistence here; ChatHistoryService handles persistence when appropriate | |
| 358 | 400 | |
| 359 | 401 | state.lastActivity = Date.now(); |
| 360 | 402 | } catch (e: any) { |
| 361 | 403 | if (e.name === "AbortError") { |
| 362 | 404 | logger.debug("Response interrupted"); |
| 363 | - // Remove the partial assistant message if it exists | |
| 364 | - const lastMessage = | |
| 365 | - state.session.history[state.session.history.length - 1]; | |
| 366 | - if ( | |
| 367 | - lastMessage && | |
| 368 | - lastMessage.message.role === "assistant" && | |
| 369 | - !lastMessage.message.content | |
| 370 | - ) { | |
| 371 | - state.session.history.pop(); | |
| 372 | - } | |
| 405 | + // Remove any partial assistant message | |
| 406 | + removePartialAssistantMessage(state); | |
| 373 | 407 | } else { |
| 374 | 408 | logger.error(`Error: ${formatError(e)}`); |
| 375 | - // Add error message to chat history and display messages | |
| 409 | + // Add error message via ChatHistoryService | |
| 376 | 410 | const errorMessage = `Error: ${formatError(e)}`; |
| 377 | - state.session.history.push({ | |
| 378 | - message: { role: "assistant", content: errorMessage }, | |
| 379 | - contextItems: [], | |
| 380 | - }); | |
| 411 | + try { | |
| 412 | + services.chatHistory.addAssistantMessage(errorMessage); | |
| 413 | + } catch { | |
| 414 | + state.session.history.push({ | |
| 415 | + message: { role: "assistant", content: errorMessage }, | |
| 416 | + contextItems: [], | |
| 417 | + }); | |
| 418 | + } | |
| 381 | 419 | } |
| 382 | 420 | } finally { |
| 383 | 421 | state.currentAbortController = null; |
modified extensions/cli/src/compaction.ts +1 −1
| @@ -80,7 +80,7 @@ | ||
| 80 | 80 | historyForCompaction = [...historyToUse, compactionPrompt]; |
| 81 | 81 | } |
| 82 | 82 | |
| 83 | - // Stream the compaction response | |
| 83 | + // Stream the compaction response (service drives updates; this collects content locally) | |
| 84 | 84 | const controller = new AbortController(); |
| 85 | 85 | |
| 86 | 86 | let compactionContent = ""; |
modified extensions/cli/src/flags/flagValidator.ts +28 −0
| @@ -16,6 +16,10 @@ | ||
| 16 | 16 | auto?: boolean; |
| 17 | 17 | config?: string; |
| 18 | 18 | |
| 19 | + // Session flags | |
| 20 | + resume?: boolean; | |
| 21 | + fork?: string; | |
| 22 | + | |
| 19 | 23 | // Permission flags |
| 20 | 24 | allow?: string[]; |
| 21 | 25 | ask?: string[]; |
| @@ -101,6 +105,29 @@ | ||
| 101 | 105 | return errors; |
| 102 | 106 | } |
| 103 | 107 | |
| 108 | +/** | |
| 109 | + * Validate session flags | |
| 110 | + */ | |
| 111 | +function validateSessionFlags(options: ValidationOptions): ValidationError[] { | |
| 112 | + const errors: ValidationError[] = []; | |
| 113 | + | |
| 114 | + if (options.resume && options.fork) { | |
| 115 | + errors.push({ | |
| 116 | + code: "CONFLICTING_SESSION_FLAGS", | |
| 117 | + message: "Error: Cannot use both --resume and --fork flags together", | |
| 118 | + }); | |
| 119 | + } | |
| 120 | + | |
| 121 | + if (options.fork !== undefined && (!options.fork || !options.fork.trim())) { | |
| 122 | + errors.push({ | |
| 123 | + code: "FORK_REQUIRES_SESSION_ID", | |
| 124 | + message: "Error: --fork requires a session ID (e.g., --fork abc123)", | |
| 125 | + }); | |
| 126 | + } | |
| 127 | + | |
| 128 | + return errors; | |
| 129 | +} | |
| 130 | + | |
| 104 | 131 | /** |
| 105 | 132 | * Validate config path exists (basic check) |
| 106 | 133 | */ |
| @@ -164,6 +191,7 @@ | ||
| 164 | 191 | validateSilentFlag, |
| 165 | 192 | validateFormatValue, |
| 166 | 193 | validateModeFlags, |
| 194 | + validateSessionFlags, | |
| 167 | 195 | validateConfigPath, |
| 168 | 196 | validatePermissionFlags, |
| 169 | 197 | ]; |
modified extensions/cli/src/index.ts +3 −0
| @@ -64,6 +64,7 @@ | ||
| 64 | 64 | "Strip <think></think> tags and excess whitespace from output. Only works with -p/--print flag.", |
| 65 | 65 | ) |
| 66 | 66 | .option("--resume", "Resume from last session") |
| 67 | + .option("--fork <sessionId>", "Fork from an existing session ID") | |
| 67 | 68 | .action(async (prompt, options) => { |
| 68 | 69 | // Handle piped input - detect it early and decide on mode |
| 69 | 70 | let stdinInput = null; |
| @@ -100,6 +101,8 @@ | ||
| 100 | 101 | readonly: options.readonly, |
| 101 | 102 | auto: options.auto, |
| 102 | 103 | config: options.config, |
| 104 | + resume: options.resume, | |
| 105 | + fork: options.fork, | |
| 103 | 106 | allow: options.allow, |
| 104 | 107 | ask: options.ask, |
| 105 | 108 | exclude: options.exclude, |
added extensions/cli/src/services/ChatHistoryService.test.ts +548 −0
| @@ -0,0 +1,548 @@ | ||
| 1 | +import type { ChatHistoryItem } from "core/index.js"; | |
| 2 | +import { describe, it, expect, beforeEach, vi } from "vitest"; | |
| 3 | + | |
| 4 | +import { ChatHistoryService } from "./ChatHistoryService.js"; | |
| 5 | + | |
| 6 | +// Mock the dependencies | |
| 7 | +vi.mock("../session.js", () => ({ | |
| 8 | + updateSessionHistory: vi.fn(), | |
| 9 | + loadSession: vi.fn(), | |
| 10 | + createSession: vi.fn((history) => ({ | |
| 11 | + sessionId: "test-session-id", | |
| 12 | + history: history || [], | |
| 13 | + title: "Test Session", | |
| 14 | + workspaceDirectory: "/test", | |
| 15 | + })), | |
| 16 | +})); | |
| 17 | + | |
| 18 | +vi.mock("../util/logger.js", () => ({ | |
| 19 | + logger: { | |
| 20 | + debug: vi.fn(), | |
| 21 | + warn: vi.fn(), | |
| 22 | + error: vi.fn(), | |
| 23 | + }, | |
| 24 | +})); | |
| 25 | + | |
| 26 | +describe("ChatHistoryService", () => { | |
| 27 | + let service: ChatHistoryService; | |
| 28 | + | |
| 29 | + beforeEach(() => { | |
| 30 | + service = new ChatHistoryService(); | |
| 31 | + vi.clearAllMocks(); | |
| 32 | + }); | |
| 33 | + | |
| 34 | + describe("initialization", () => { | |
| 35 | + it("should initialize with empty state", async () => { | |
| 36 | + const state = await service.initialize(); | |
| 37 | + | |
| 38 | + expect(state.history).toEqual([]); | |
| 39 | + expect(state.compactionIndex).toBeNull(); | |
| 40 | + expect(state.sessionId).toBe("test-session-id"); | |
| 41 | + expect(state.isRemoteMode).toBe(false); | |
| 42 | + }); | |
| 43 | + | |
| 44 | + it("should initialize with provided session", async () => { | |
| 45 | + const mockHistory: ChatHistoryItem[] = [ | |
| 46 | + { | |
| 47 | + message: { role: "user", content: "Hello" }, | |
| 48 | + contextItems: [], | |
| 49 | + }, | |
| 50 | + ]; | |
| 51 | + | |
| 52 | + const mockSession = { | |
| 53 | + sessionId: "custom-session", | |
| 54 | + history: mockHistory, | |
| 55 | + title: "Custom Session", | |
| 56 | + workspaceDirectory: "/custom", | |
| 57 | + }; | |
| 58 | + | |
| 59 | + const state = await service.initialize(mockSession); | |
| 60 | + | |
| 61 | + expect(state.history).toEqual(mockHistory); | |
| 62 | + expect(state.sessionId).toBe("custom-session"); | |
| 63 | + }); | |
| 64 | + | |
| 65 | + it("should detect compaction index on initialization", async () => { | |
| 66 | + const mockHistory: ChatHistoryItem[] = [ | |
| 67 | + { | |
| 68 | + message: { role: "user", content: "First message" }, | |
| 69 | + contextItems: [], | |
| 70 | + }, | |
| 71 | + { | |
| 72 | + message: { role: "assistant", content: "Summary here" }, | |
| 73 | + contextItems: [], | |
| 74 | + conversationSummary: "Summary here", | |
| 75 | + }, | |
| 76 | + { | |
| 77 | + message: { role: "user", content: "After compaction" }, | |
| 78 | + contextItems: [], | |
| 79 | + }, | |
| 80 | + ]; | |
| 81 | + | |
| 82 | + const mockSession = { | |
| 83 | + sessionId: "session-with-compaction", | |
| 84 | + history: mockHistory, | |
| 85 | + title: "Compacted Session", | |
| 86 | + workspaceDirectory: "/compacted", | |
| 87 | + }; | |
| 88 | + | |
| 89 | + const state = await service.initialize(mockSession); | |
| 90 | + | |
| 91 | + expect(state.compactionIndex).toBe(1); | |
| 92 | + }); | |
| 93 | + | |
| 94 | + it("should set remote mode on initialization", async () => { | |
| 95 | + const state = await service.initialize(undefined, true); | |
| 96 | + | |
| 97 | + expect(state.isRemoteMode).toBe(true); | |
| 98 | + }); | |
| 99 | + }); | |
| 100 | + | |
| 101 | + describe("addUserMessage", () => { | |
| 102 | + beforeEach(async () => { | |
| 103 | + await service.initialize(); | |
| 104 | + }); | |
| 105 | + | |
| 106 | + it("should add a user message to history", () => { | |
| 107 | + const message = service.addUserMessage("Hello, world!"); | |
| 108 | + | |
| 109 | + expect(message.message.role).toBe("user"); | |
| 110 | + expect(message.message.content).toBe("Hello, world!"); | |
| 111 | + | |
| 112 | + const state = service.getState(); | |
| 113 | + expect(state.history).toHaveLength(1); | |
| 114 | + expect(state.history[0]).toBe(message); | |
| 115 | + }); | |
| 116 | + | |
| 117 | + it("should include context items", () => { | |
| 118 | + const contextItems = [ | |
| 119 | + { content: "file.txt", name: "File", description: "A text file" }, | |
| 120 | + ]; | |
| 121 | + | |
| 122 | + const message = service.addUserMessage("Check this file", contextItems); | |
| 123 | + | |
| 124 | + expect(message.contextItems).toEqual(contextItems); | |
| 125 | + }); | |
| 126 | + | |
| 127 | + it("should emit state change event", () => { | |
| 128 | + const listener = vi.fn(); | |
| 129 | + service.on("stateChanged", listener); | |
| 130 | + | |
| 131 | + service.addUserMessage("Test message"); | |
| 132 | + | |
| 133 | + expect(listener).toHaveBeenCalledTimes(1); | |
| 134 | + expect(listener).toHaveBeenCalledWith( | |
| 135 | + expect.objectContaining({ | |
| 136 | + history: expect.arrayContaining([ | |
| 137 | + expect.objectContaining({ | |
| 138 | + message: expect.objectContaining({ | |
| 139 | + role: "user", | |
| 140 | + content: "Test message", | |
| 141 | + }), | |
| 142 | + }), | |
| 143 | + ]), | |
| 144 | + }), | |
| 145 | + expect.any(Object), | |
| 146 | + ); | |
| 147 | + }); | |
| 148 | + | |
| 149 | + it("should not save to session in remote mode", async () => { | |
| 150 | + const { updateSessionHistory } = await import("../session.js"); | |
| 151 | + | |
| 152 | + await service.initialize(undefined, true); | |
| 153 | + service.addUserMessage("Remote message"); | |
| 154 | + | |
| 155 | + expect(updateSessionHistory).not.toHaveBeenCalled(); | |
| 156 | + }); | |
| 157 | + }); | |
| 158 | + | |
| 159 | + describe("addAssistantMessage", () => { | |
| 160 | + beforeEach(async () => { | |
| 161 | + await service.initialize(); | |
| 162 | + }); | |
| 163 | + | |
| 164 | + it("should add an assistant message without tool calls", () => { | |
| 165 | + const message = service.addAssistantMessage("I can help with that"); | |
| 166 | + | |
| 167 | + expect(message.message.role).toBe("assistant"); | |
| 168 | + expect(message.message.content).toBe("I can help with that"); | |
| 169 | + expect(message.toolCallStates).toBeUndefined(); | |
| 170 | + }); | |
| 171 | + | |
| 172 | + it("should add an assistant message with tool calls", () => { | |
| 173 | + const toolCalls = [ | |
| 174 | + { | |
| 175 | + id: "tool-123", | |
| 176 | + name: "readFile", | |
| 177 | + arguments: { path: "test.txt" }, | |
| 178 | + }, | |
| 179 | + ]; | |
| 180 | + | |
| 181 | + const message = service.addAssistantMessage( | |
| 182 | + "Let me read that file", | |
| 183 | + toolCalls, | |
| 184 | + ); | |
| 185 | + | |
| 186 | + expect(message.message.role).toBe("assistant"); | |
| 187 | + expect(message.toolCallStates).toHaveLength(1); | |
| 188 | + expect(message.toolCallStates![0].toolCallId).toBe("tool-123"); | |
| 189 | + expect(message.toolCallStates![0].status).toBe("generated"); | |
| 190 | + }); | |
| 191 | + }); | |
| 192 | + | |
| 193 | + describe("addSystemMessage", () => { | |
| 194 | + beforeEach(async () => { | |
| 195 | + await service.initialize(); | |
| 196 | + }); | |
| 197 | + | |
| 198 | + it("should add a system message", () => { | |
| 199 | + const message = service.addSystemMessage("System notification"); | |
| 200 | + | |
| 201 | + expect(message.message.role).toBe("system"); | |
| 202 | + expect(message.message.content).toBe("System notification"); | |
| 203 | + }); | |
| 204 | + }); | |
| 205 | + | |
| 206 | + describe("updateToolCallState", () => { | |
| 207 | + beforeEach(async () => { | |
| 208 | + await service.initialize(); | |
| 209 | + }); | |
| 210 | + | |
| 211 | + it("should update tool call state", () => { | |
| 212 | + // Add assistant message with tool call | |
| 213 | + const toolCalls = [ | |
| 214 | + { | |
| 215 | + id: "tool-456", | |
| 216 | + name: "writeFile", | |
| 217 | + arguments: { path: "output.txt", content: "data" }, | |
| 218 | + }, | |
| 219 | + ]; | |
| 220 | + | |
| 221 | + service.addAssistantMessage("Writing file", toolCalls); | |
| 222 | + | |
| 223 | + // Update the tool call state | |
| 224 | + service.updateToolCallState(0, "tool-456", { | |
| 225 | + status: "done", | |
| 226 | + output: [ | |
| 227 | + { | |
| 228 | + content: "File written successfully", | |
| 229 | + name: "Result", | |
| 230 | + description: "", | |
| 231 | + }, | |
| 232 | + ], | |
| 233 | + }); | |
| 234 | + | |
| 235 | + const state = service.getState(); | |
| 236 | + const toolState = state.history[0].toolCallStates![0]; | |
| 237 | + | |
| 238 | + expect(toolState.status).toBe("done"); | |
| 239 | + expect(toolState.output).toHaveLength(1); | |
| 240 | + expect(toolState.output![0].content).toBe("File written successfully"); | |
| 241 | + }); | |
| 242 | + | |
| 243 | + it("should handle missing tool call gracefully", () => { | |
| 244 | + service.addAssistantMessage("No tools here"); | |
| 245 | + | |
| 246 | + // Should not throw | |
| 247 | + service.updateToolCallState(0, "non-existent", { | |
| 248 | + status: "done", | |
| 249 | + }); | |
| 250 | + | |
| 251 | + // State should remain unchanged | |
| 252 | + const state = service.getState(); | |
| 253 | + expect(state.history[0].toolCallStates).toBeUndefined(); | |
| 254 | + }); | |
| 255 | + }); | |
| 256 | + | |
| 257 | + describe("addToolResult", () => { | |
| 258 | + beforeEach(async () => { | |
| 259 | + await service.initialize(); | |
| 260 | + }); | |
| 261 | + | |
| 262 | + it("should add tool result to the correct message", () => { | |
| 263 | + // Add messages with tool calls | |
| 264 | + service.addUserMessage("Do something"); | |
| 265 | + service.addAssistantMessage("Using tool", [ | |
| 266 | + { id: "tool-789", name: "search", arguments: { query: "test" } }, | |
| 267 | + ]); | |
| 268 | + | |
| 269 | + // Add tool result | |
| 270 | + service.addToolResult("tool-789", "Search results: found 5 items"); | |
| 271 | + | |
| 272 | + const state = service.getState(); | |
| 273 | + const assistantMessage = state.history[1]; | |
| 274 | + const toolState = assistantMessage.toolCallStates![0]; | |
| 275 | + | |
| 276 | + expect(toolState.status).toBe("done"); | |
| 277 | + expect(toolState.output![0].content).toBe( | |
| 278 | + "Search results: found 5 items", | |
| 279 | + ); | |
| 280 | + }); | |
| 281 | + }); | |
| 282 | + | |
| 283 | + describe("compact", () => { | |
| 284 | + beforeEach(async () => { | |
| 285 | + await service.initialize(); | |
| 286 | + }); | |
| 287 | + | |
| 288 | + it("should compact history and update index", () => { | |
| 289 | + // Add initial messages | |
| 290 | + service.addUserMessage("Message 1"); | |
| 291 | + service.addAssistantMessage("Response 1"); | |
| 292 | + service.addUserMessage("Message 2"); | |
| 293 | + service.addAssistantMessage("Response 2"); | |
| 294 | + | |
| 295 | + // Create compacted history | |
| 296 | + const compactedHistory: ChatHistoryItem[] = [ | |
| 297 | + { | |
| 298 | + message: { | |
| 299 | + role: "system", | |
| 300 | + content: "[Compacted] Summary of messages 1-2", | |
| 301 | + }, | |
| 302 | + contextItems: [], | |
| 303 | + }, | |
| 304 | + { | |
| 305 | + message: { role: "user", content: "Message 3" }, | |
| 306 | + contextItems: [], | |
| 307 | + }, | |
| 308 | + ]; | |
| 309 | + | |
| 310 | + service.compact(compactedHistory, 0); | |
| 311 | + | |
| 312 | + const state = service.getState(); | |
| 313 | + expect(state.history).toEqual(compactedHistory); | |
| 314 | + expect(state.compactionIndex).toBe(0); | |
| 315 | + }); | |
| 316 | + }); | |
| 317 | + | |
| 318 | + describe("clear", () => { | |
| 319 | + beforeEach(async () => { | |
| 320 | + await service.initialize(); | |
| 321 | + }); | |
| 322 | + | |
| 323 | + it("should clear all history", () => { | |
| 324 | + service.addUserMessage("Message"); | |
| 325 | + service.addAssistantMessage("Response"); | |
| 326 | + | |
| 327 | + service.clear(); | |
| 328 | + | |
| 329 | + const state = service.getState(); | |
| 330 | + expect(state.history).toEqual([]); | |
| 331 | + expect(state.compactionIndex).toBeNull(); | |
| 332 | + }); | |
| 333 | + }); | |
| 334 | + | |
| 335 | + describe("getHistory and getHistoryForLLM", () => { | |
| 336 | + beforeEach(async () => { | |
| 337 | + await service.initialize(); | |
| 338 | + }); | |
| 339 | + | |
| 340 | + it("should return immutable copy of history", () => { | |
| 341 | + service.addUserMessage("Test"); | |
| 342 | + | |
| 343 | + const history1 = service.getHistory(); | |
| 344 | + const history2 = service.getHistory(); | |
| 345 | + | |
| 346 | + expect(history1).not.toBe(history2); // Different arrays | |
| 347 | + expect(history1).toEqual(history2); // Same content | |
| 348 | + }); | |
| 349 | + | |
| 350 | + it("should return full history when no compaction", () => { | |
| 351 | + service.addUserMessage("Message 1"); | |
| 352 | + service.addAssistantMessage("Response 1"); | |
| 353 | + | |
| 354 | + const historyForLLM = service.getHistoryForLLM(); | |
| 355 | + const fullHistory = service.getHistory(); | |
| 356 | + | |
| 357 | + expect(historyForLLM).toEqual(fullHistory); | |
| 358 | + }); | |
| 359 | + | |
| 360 | + it("should return history after compaction index", () => { | |
| 361 | + const history: ChatHistoryItem[] = [ | |
| 362 | + { | |
| 363 | + message: { role: "user", content: "Old message" }, | |
| 364 | + contextItems: [], | |
| 365 | + }, | |
| 366 | + { | |
| 367 | + message: { role: "system", content: "[Compacted] Summary" }, | |
| 368 | + contextItems: [], | |
| 369 | + }, | |
| 370 | + { | |
| 371 | + message: { role: "user", content: "New message" }, | |
| 372 | + contextItems: [], | |
| 373 | + }, | |
| 374 | + ]; | |
| 375 | + | |
| 376 | + service.setHistory(history); | |
| 377 | + service.setCompactionIndex(1); | |
| 378 | + | |
| 379 | + const historyForLLM = service.getHistoryForLLM(); | |
| 380 | + | |
| 381 | + expect(historyForLLM).toHaveLength(2); // Compacted message + new message | |
| 382 | + expect(historyForLLM[0].message.content).toBe("[Compacted] Summary"); | |
| 383 | + expect(historyForLLM[1].message.content).toBe("New message"); | |
| 384 | + }); | |
| 385 | + }); | |
| 386 | + | |
| 387 | + describe("setHistory", () => { | |
| 388 | + beforeEach(async () => { | |
| 389 | + await service.initialize(); | |
| 390 | + }); | |
| 391 | + | |
| 392 | + it("should set entire history", () => { | |
| 393 | + const newHistory: ChatHistoryItem[] = [ | |
| 394 | + { | |
| 395 | + message: { role: "user", content: "Imported message" }, | |
| 396 | + contextItems: [], | |
| 397 | + }, | |
| 398 | + ]; | |
| 399 | + | |
| 400 | + service.setHistory(newHistory); | |
| 401 | + | |
| 402 | + const state = service.getState(); | |
| 403 | + expect(state.history).toEqual(newHistory); | |
| 404 | + }); | |
| 405 | + | |
| 406 | + it("should detect compaction index when setting history", () => { | |
| 407 | + const historyWithCompaction: ChatHistoryItem[] = [ | |
| 408 | + { | |
| 409 | + message: { role: "assistant", content: "old summary" }, | |
| 410 | + contextItems: [], | |
| 411 | + conversationSummary: "old summary", | |
| 412 | + }, | |
| 413 | + { | |
| 414 | + message: { role: "user", content: "Recent message" }, | |
| 415 | + contextItems: [], | |
| 416 | + }, | |
| 417 | + ]; | |
| 418 | + | |
| 419 | + service.setHistory(historyWithCompaction); | |
| 420 | + | |
| 421 | + const state = service.getState(); | |
| 422 | + expect(state.compactionIndex).toBe(0); | |
| 423 | + }); | |
| 424 | + }); | |
| 425 | + | |
| 426 | + describe("undo/redo", () => { | |
| 427 | + beforeEach(async () => { | |
| 428 | + await service.initialize(); | |
| 429 | + }); | |
| 430 | + | |
| 431 | + it("should undo last change and redo it", () => { | |
| 432 | + service.addUserMessage("A"); | |
| 433 | + service.addAssistantMessage("B"); | |
| 434 | + | |
| 435 | + expect(service.getState().history.map((m) => m.message.content)).toEqual([ | |
| 436 | + "A", | |
| 437 | + "B", | |
| 438 | + ]); | |
| 439 | + | |
| 440 | + expect(service.canUndo()).toBe(true); | |
| 441 | + service.undo(); | |
| 442 | + expect(service.getState().history.map((m) => m.message.content)).toEqual([ | |
| 443 | + "A", | |
| 444 | + ]); | |
| 445 | + | |
| 446 | + expect(service.canRedo()).toBe(true); | |
| 447 | + service.redo(); | |
| 448 | + expect(service.getState().history.map((m) => m.message.content)).toEqual([ | |
| 449 | + "A", | |
| 450 | + "B", | |
| 451 | + ]); | |
| 452 | + }); | |
| 453 | + | |
| 454 | + it("should support undoing tool state updates", () => { | |
| 455 | + service.addAssistantMessage("Using tool", [ | |
| 456 | + { id: "t1", name: "Read", arguments: { path: "file" } }, | |
| 457 | + ]); | |
| 458 | + const before = service.getHistory(); | |
| 459 | + service.addToolResult("t1", "ok", "done"); | |
| 460 | + const after = service.getHistory(); | |
| 461 | + | |
| 462 | + expect(after[0].toolCallStates?.[0].status).toBe("done"); | |
| 463 | + service.undo(); | |
| 464 | + const undone = service.getHistory(); | |
| 465 | + expect(undone[0].toolCallStates?.[0].status).toBe( | |
| 466 | + before[0].toolCallStates?.[0].status, | |
| 467 | + ); | |
| 468 | + }); | |
| 469 | + }); | |
| 470 | + | |
| 471 | + describe("immutability", () => { | |
| 472 | + beforeEach(async () => { | |
| 473 | + await service.initialize(); | |
| 474 | + }); | |
| 475 | + | |
| 476 | + it("should not allow external mutation of state", () => { | |
| 477 | + service.addUserMessage("Test"); | |
| 478 | + | |
| 479 | + const state = service.getState(); | |
| 480 | + const originalLength = state.history.length; | |
| 481 | + | |
| 482 | + // Try to mutate | |
| 483 | + state.history.push({ | |
| 484 | + message: { role: "user", content: "Hacked!" }, | |
| 485 | + contextItems: [], | |
| 486 | + }); | |
| 487 | + | |
| 488 | + // Check that internal state wasn't affected | |
| 489 | + const newState = service.getState(); | |
| 490 | + expect(newState.history).toHaveLength(originalLength); | |
| 491 | + }); | |
| 492 | + | |
| 493 | + it("should not allow mutation through getHistory", () => { | |
| 494 | + service.addUserMessage("Test"); | |
| 495 | + | |
| 496 | + const history = service.getHistory(); | |
| 497 | + const originalLength = history.length; | |
| 498 | + | |
| 499 | + // Try to mutate | |
| 500 | + history.push({ | |
| 501 | + message: { role: "user", content: "Hacked!" }, | |
| 502 | + contextItems: [], | |
| 503 | + }); | |
| 504 | + | |
| 505 | + // Check that internal state wasn't affected | |
| 506 | + const newHistory = service.getHistory(); | |
| 507 | + expect(newHistory).toHaveLength(originalLength); | |
| 508 | + }); | |
| 509 | + }); | |
| 510 | + | |
| 511 | + describe("event emissions", () => { | |
| 512 | + beforeEach(async () => { | |
| 513 | + await service.initialize(); | |
| 514 | + }); | |
| 515 | + | |
| 516 | + it("should emit stateChanged on every update", () => { | |
| 517 | + const listener = vi.fn(); | |
| 518 | + service.on("stateChanged", listener); | |
| 519 | + | |
| 520 | + service.addUserMessage("Message 1"); | |
| 521 | + service.addAssistantMessage("Response 1"); | |
| 522 | + service.addSystemMessage("System"); | |
| 523 | + service.clear(); | |
| 524 | + | |
| 525 | + expect(listener).toHaveBeenCalledTimes(4); | |
| 526 | + }); | |
| 527 | + | |
| 528 | + it("should provide old and new state in event", () => { | |
| 529 | + const listener = vi.fn(); | |
| 530 | + service.on("stateChanged", listener); | |
| 531 | + | |
| 532 | + service.addUserMessage("Test"); | |
| 533 | + | |
| 534 | + expect(listener).toHaveBeenCalledWith( | |
| 535 | + expect.objectContaining({ | |
| 536 | + history: expect.arrayContaining([ | |
| 537 | + expect.objectContaining({ | |
| 538 | + message: expect.objectContaining({ content: "Test" }), | |
| 539 | + }), | |
| 540 | + ]), | |
| 541 | + }), | |
| 542 | + expect.objectContaining({ | |
| 543 | + history: [], | |
| 544 | + }), | |
| 545 | + ); | |
| 546 | + }); | |
| 547 | + }); | |
| 548 | +}); |
added extensions/cli/src/services/ChatHistoryService.ts +534 −0
| @@ -0,0 +1,534 @@ | ||
| 1 | +import type { ChatHistoryItem, ToolStatus } from "core/index.js"; | |
| 2 | +import { createHistoryItem } from "core/util/messageConversion.js"; | |
| 3 | + | |
| 4 | +import { | |
| 5 | + updateSessionHistory, | |
| 6 | + loadSessionById, | |
| 7 | + createSession, | |
| 8 | +} from "../session.js"; | |
| 9 | +import { logger } from "../util/logger.js"; | |
| 10 | + | |
| 11 | +import { BaseService } from "./BaseService.js"; | |
| 12 | + | |
| 13 | +/** | |
| 14 | + * State managed by the ChatHistoryService | |
| 15 | + */ | |
| 16 | +export interface ChatHistoryState { | |
| 17 | + history: ChatHistoryItem[]; | |
| 18 | + compactionIndex: number | null; | |
| 19 | + sessionId: string; | |
| 20 | + isRemoteMode: boolean; | |
| 21 | +} | |
| 22 | + | |
| 23 | +/** | |
| 24 | + * Service for managing chat history as the single source of truth | |
| 25 | + * Provides immutable updates and automatic React integration via events | |
| 26 | + */ | |
| 27 | +export class ChatHistoryService extends BaseService<ChatHistoryState> { | |
| 28 | + // Simple undo/redo stacks for history snapshots | |
| 29 | + private past: ChatHistoryItem[][] = []; | |
| 30 | + private future: ChatHistoryItem[][] = []; | |
| 31 | + // Memoized snapshot for referential stability in getState() | |
| 32 | + private _memoSnapshot: { | |
| 33 | + stateRef: ChatHistoryState | null; | |
| 34 | + historyRef: ChatHistoryItem[] | null; | |
| 35 | + snapshot: ChatHistoryState | null; | |
| 36 | + } = { stateRef: null, historyRef: null, snapshot: null }; | |
| 37 | + | |
| 38 | + constructor() { | |
| 39 | + super("ChatHistoryService", { | |
| 40 | + history: [], | |
| 41 | + compactionIndex: null, | |
| 42 | + sessionId: "", | |
| 43 | + isRemoteMode: false, | |
| 44 | + }); | |
| 45 | + this.setMaxListeners(50); | |
| 46 | + } | |
| 47 | + | |
| 48 | + private setHistoryInternal( | |
| 49 | + history: ChatHistoryItem[], | |
| 50 | + options: { | |
| 51 | + recordUndo?: boolean; | |
| 52 | + compactionIndex?: number | null; | |
| 53 | + persist?: boolean; // set to false to skip persistence (rare) | |
| 54 | + } = {}, | |
| 55 | + ): void { | |
| 56 | + const { recordUndo = true, compactionIndex, persist } = options; | |
| 57 | + const prev = this.currentState.history; | |
| 58 | + if (recordUndo) { | |
| 59 | + this.past.push([...prev]); | |
| 60 | + this.future = []; | |
| 61 | + } | |
| 62 | + this.setState({ | |
| 63 | + history: [...history], | |
| 64 | + compactionIndex: | |
| 65 | + compactionIndex === undefined | |
| 66 | + ? this.findCompactionIndex(history) | |
| 67 | + : compactionIndex, | |
| 68 | + }); | |
| 69 | + | |
| 70 | + if (this.currentState.isRemoteMode) { | |
| 71 | + // Skip persistence in remote mode | |
| 72 | + } else if (persist !== false) { | |
| 73 | + updateSessionHistory(history); | |
| 74 | + } | |
| 75 | + } | |
| 76 | + | |
| 77 | + /** | |
| 78 | + * Initialize the service with optional session | |
| 79 | + */ | |
| 80 | + async doInitialize( | |
| 81 | + session?: any, | |
| 82 | + isRemoteMode = false, | |
| 83 | + ): Promise<ChatHistoryState> { | |
| 84 | + const activeSession = session || createSession([]); | |
| 85 | + | |
| 86 | + logger.debug("Initializing ChatHistoryService", { | |
| 87 | + sessionId: activeSession.sessionId, | |
| 88 | + historyLength: activeSession.history.length, | |
| 89 | + isRemoteMode, | |
| 90 | + }); | |
| 91 | + | |
| 92 | + return { | |
| 93 | + history: activeSession.history || [], | |
| 94 | + compactionIndex: this.findCompactionIndex(activeSession.history || []), | |
| 95 | + sessionId: activeSession.sessionId, | |
| 96 | + isRemoteMode, | |
| 97 | + }; | |
| 98 | + } | |
| 99 | + | |
| 100 | + /** | |
| 101 | + * Add a user message to the history | |
| 102 | + */ | |
| 103 | + addUserMessage(content: string, contextItems: any[] = []): ChatHistoryItem { | |
| 104 | + const newMessage = createHistoryItem( | |
| 105 | + { | |
| 106 | + role: "user", | |
| 107 | + content, | |
| 108 | + }, | |
| 109 | + contextItems, | |
| 110 | + ); | |
| 111 | + | |
| 112 | + const newHistory = [...this.currentState.history, newMessage]; | |
| 113 | + this.setHistoryInternal(newHistory); | |
| 114 | + | |
| 115 | + logger.debug("Added user message", { | |
| 116 | + contentLength: content.length, | |
| 117 | + contextItemCount: contextItems.length, | |
| 118 | + newHistoryLength: newHistory.length, | |
| 119 | + }); | |
| 120 | + | |
| 121 | + return newMessage; | |
| 122 | + } | |
| 123 | + | |
| 124 | + /** | |
| 125 | + * Add an assistant message to the history | |
| 126 | + */ | |
| 127 | + addAssistantMessage(content: string, toolCalls?: any[]): ChatHistoryItem { | |
| 128 | + const message: any = { | |
| 129 | + role: "assistant", | |
| 130 | + content, | |
| 131 | + }; | |
| 132 | + | |
| 133 | + if (toolCalls && toolCalls.length > 0) { | |
| 134 | + message.toolCalls = toolCalls; | |
| 135 | + } | |
| 136 | + | |
| 137 | + const toolCallStates = toolCalls?.map((tc) => { | |
| 138 | + const id = tc.id; | |
| 139 | + const name = tc.function?.name ?? tc.name; | |
| 140 | + // Prefer explicit string arguments; otherwise stringify object arguments | |
| 141 | + let rawArgStr: string; | |
| 142 | + if (typeof tc.arguments === "string") { | |
| 143 | + rawArgStr = tc.arguments; | |
| 144 | + } else if (typeof tc.function?.arguments === "string") { | |
| 145 | + rawArgStr = tc.function.arguments; | |
| 146 | + } else if (tc.arguments === undefined) { | |
| 147 | + rawArgStr = | |
| 148 | + tc.function?.arguments === undefined | |
| 149 | + ? "{}" | |
| 150 | + : String(tc.function.arguments); | |
| 151 | + } else { | |
| 152 | + rawArgStr = JSON.stringify(tc.arguments); | |
| 153 | + } | |
| 154 | + | |
| 155 | + // parsedArgs: prefer object, else parse the string if possible | |
| 156 | + let parsedArgs: any = {}; | |
| 157 | + if (tc && typeof tc.arguments === "object" && tc.arguments !== null) { | |
| 158 | + parsedArgs = tc.arguments; | |
| 159 | + } else if (typeof rawArgStr === "string") { | |
| 160 | + try { | |
| 161 | + parsedArgs = JSON.parse(rawArgStr); | |
| 162 | + } catch { | |
| 163 | + parsedArgs = {}; | |
| 164 | + } | |
| 165 | + } | |
| 166 | + | |
| 167 | + return { | |
| 168 | + toolCallId: id, | |
| 169 | + toolCall: { | |
| 170 | + id, | |
| 171 | + type: "function" as const, | |
| 172 | + function: { | |
| 173 | + name, | |
| 174 | + arguments: rawArgStr, | |
| 175 | + }, | |
| 176 | + }, | |
| 177 | + status: "generated" as ToolStatus, | |
| 178 | + parsedArgs, | |
| 179 | + }; | |
| 180 | + }); | |
| 181 | + | |
| 182 | + const newMessage = createHistoryItem(message, [], toolCallStates); | |
| 183 | + const newHistory = [...this.currentState.history, newMessage]; | |
| 184 | + this.setHistoryInternal(newHistory); | |
| 185 | + | |
| 186 | + logger.debug("Added assistant message", { | |
| 187 | + contentLength: content.length, | |
| 188 | + toolCallCount: toolCalls?.length || 0, | |
| 189 | + newHistoryLength: newHistory.length, | |
| 190 | + }); | |
| 191 | + | |
| 192 | + return newMessage; | |
| 193 | + } | |
| 194 | + | |
| 195 | + /** | |
| 196 | + * Add a system message to the history | |
| 197 | + */ | |
| 198 | + addSystemMessage(content: string): ChatHistoryItem { | |
| 199 | + const newMessage = createHistoryItem({ | |
| 200 | + role: "system", | |
| 201 | + content, | |
| 202 | + }); | |
| 203 | + | |
| 204 | + const newHistory = [...this.currentState.history, newMessage]; | |
| 205 | + this.setHistoryInternal(newHistory); | |
| 206 | + | |
| 207 | + logger.debug("Added system message", { | |
| 208 | + contentLength: content.length, | |
| 209 | + newHistoryLength: newHistory.length, | |
| 210 | + }); | |
| 211 | + | |
| 212 | + return newMessage; | |
| 213 | + } | |
| 214 | + | |
| 215 | + /** | |
| 216 | + * Add a generic history item | |
| 217 | + */ | |
| 218 | + addHistoryItem(item: ChatHistoryItem): ChatHistoryItem { | |
| 219 | + const newHistory = [...this.currentState.history, item]; | |
| 220 | + this.setHistoryInternal(newHistory); | |
| 221 | + | |
| 222 | + logger.debug("Added history item", { | |
| 223 | + role: item.message.role, | |
| 224 | + newHistoryLength: newHistory.length, | |
| 225 | + }); | |
| 226 | + | |
| 227 | + return item; | |
| 228 | + } | |
| 229 | + | |
| 230 | + /** | |
| 231 | + * Update a tool call state within a message | |
| 232 | + */ | |
| 233 | + updateToolCallState( | |
| 234 | + messageIndex: number, | |
| 235 | + toolCallId: string, | |
| 236 | + updates: Partial<{ | |
| 237 | + status: ToolStatus; | |
| 238 | + output: any[]; | |
| 239 | + }>, | |
| 240 | + ): void { | |
| 241 | + const newHistory = [...this.currentState.history]; | |
| 242 | + const message = newHistory[messageIndex]; | |
| 243 | + | |
| 244 | + if (!message?.toolCallStates) { | |
| 245 | + logger.warn("No tool call states found at message index", { | |
| 246 | + messageIndex, | |
| 247 | + toolCallId, | |
| 248 | + }); | |
| 249 | + return; | |
| 250 | + } | |
| 251 | + | |
| 252 | + const toolState = message.toolCallStates.find( | |
| 253 | + (ts) => ts.toolCallId === toolCallId, | |
| 254 | + ); | |
| 255 | + | |
| 256 | + if (!toolState) { | |
| 257 | + logger.warn("Tool call state not found", { | |
| 258 | + messageIndex, | |
| 259 | + toolCallId, | |
| 260 | + availableIds: message.toolCallStates.map((ts) => ts.toolCallId), | |
| 261 | + }); | |
| 262 | + return; | |
| 263 | + } | |
| 264 | + | |
| 265 | + // Create a new message with updated tool state (immutable) | |
| 266 | + newHistory[messageIndex] = { | |
| 267 | + ...message, | |
| 268 | + toolCallStates: message.toolCallStates.map((ts) => | |
| 269 | + ts.toolCallId === toolCallId ? { ...ts, ...updates } : ts, | |
| 270 | + ), | |
| 271 | + }; | |
| 272 | + | |
| 273 | + this.setHistoryInternal(newHistory); | |
| 274 | + | |
| 275 | + logger.debug("Updated tool call state", { | |
| 276 | + messageIndex, | |
| 277 | + toolCallId, | |
| 278 | + updates, | |
| 279 | + }); | |
| 280 | + } | |
| 281 | + | |
| 282 | + /** | |
| 283 | + * Add a tool result to the history | |
| 284 | + */ | |
| 285 | + addToolResult( | |
| 286 | + toolCallId: string, | |
| 287 | + result: string, | |
| 288 | + status: ToolStatus = "done", | |
| 289 | + ): void { | |
| 290 | + // Find the last assistant message with this tool call | |
| 291 | + let targetIndex = -1; | |
| 292 | + for (let i = this.currentState.history.length - 1; i >= 0; i--) { | |
| 293 | + const item = this.currentState.history[i]; | |
| 294 | + if (item.message.role === "assistant" && item.toolCallStates) { | |
| 295 | + const hasToolCall = item.toolCallStates.some( | |
| 296 | + (ts) => ts.toolCallId === toolCallId, | |
| 297 | + ); | |
| 298 | + if (hasToolCall) { | |
| 299 | + targetIndex = i; | |
| 300 | + break; | |
| 301 | + } | |
| 302 | + } | |
| 303 | + } | |
| 304 | + | |
| 305 | + if (targetIndex >= 0) { | |
| 306 | + this.updateToolCallState(targetIndex, toolCallId, { | |
| 307 | + status, | |
| 308 | + output: [ | |
| 309 | + { | |
| 310 | + content: result, | |
| 311 | + name: "Tool Result", | |
| 312 | + description: "Tool execution result", | |
| 313 | + }, | |
| 314 | + ], | |
| 315 | + }); | |
| 316 | + } else { | |
| 317 | + logger.warn("Could not find message for tool result", { toolCallId }); | |
| 318 | + } | |
| 319 | + } | |
| 320 | + | |
| 321 | + /** | |
| 322 | + * Update a tool's status (e.g., set to "calling" immediately on approval) | |
| 323 | + */ | |
| 324 | + updateToolStatus(toolCallId: string, status: ToolStatus): void { | |
| 325 | + // Find the last assistant message with this tool call | |
| 326 | + let targetIndex = -1; | |
| 327 | + for (let i = this.currentState.history.length - 1; i >= 0; i--) { | |
| 328 | + const item = this.currentState.history[i]; | |
| 329 | + if (item.message.role === "assistant" && item.toolCallStates) { | |
| 330 | + const hasToolCall = item.toolCallStates.some( | |
| 331 | + (ts) => ts.toolCallId === toolCallId, | |
| 332 | + ); | |
| 333 | + if (hasToolCall) { | |
| 334 | + targetIndex = i; | |
| 335 | + break; | |
| 336 | + } | |
| 337 | + } | |
| 338 | + } | |
| 339 | + | |
| 340 | + if (targetIndex >= 0) { | |
| 341 | + this.updateToolCallState(targetIndex, toolCallId, { status }); | |
| 342 | + } else { | |
| 343 | + logger.warn("Could not find message for tool status update", { | |
| 344 | + toolCallId, | |
| 345 | + status, | |
| 346 | + }); | |
| 347 | + } | |
| 348 | + } | |
| 349 | + | |
| 350 | + /** | |
| 351 | + * Perform compaction on the history | |
| 352 | + */ | |
| 353 | + compact(newHistory: ChatHistoryItem[], compactionIndex: number): void { | |
| 354 | + this.setHistoryInternal(newHistory, { compactionIndex }); | |
| 355 | + | |
| 356 | + logger.debug("Compacted history", { | |
| 357 | + oldLength: this.currentState.history.length, | |
| 358 | + newLength: newHistory.length, | |
| 359 | + compactionIndex, | |
| 360 | + }); | |
| 361 | + } | |
| 362 | + | |
| 363 | + /** | |
| 364 | + * Clear the chat history | |
| 365 | + */ | |
| 366 | + clear(): void { | |
| 367 | + this.setHistoryInternal([], { compactionIndex: null }); | |
| 368 | + | |
| 369 | + logger.debug("Cleared chat history"); | |
| 370 | + } | |
| 371 | + | |
| 372 | + /** | |
| 373 | + * Load a session into the service | |
| 374 | + */ | |
| 375 | + async loadSession(sessionId: string): Promise<void> { | |
| 376 | + const session = loadSessionById(sessionId); | |
| 377 | + if (session) { | |
| 378 | + // Load new history without recording undo; set sessionId separately | |
| 379 | + this.setHistoryInternal(session.history, { recordUndo: false }); | |
| 380 | + this.setState({ sessionId: session.sessionId }); | |
| 381 | + | |
| 382 | + logger.debug("Loaded session", { | |
| 383 | + sessionId, | |
| 384 | + historyLength: session.history.length, | |
| 385 | + }); | |
| 386 | + } else { | |
| 387 | + logger.warn("Session not found", { sessionId }); | |
| 388 | + } | |
| 389 | + } | |
| 390 | + | |
| 391 | + /** | |
| 392 | + * Get an immutable copy of the current history | |
| 393 | + */ | |
| 394 | + getHistory(): ChatHistoryItem[] { | |
| 395 | + return [...this.currentState.history]; | |
| 396 | + } | |
| 397 | + | |
| 398 | + /** | |
| 399 | + * Get history for LLM (considering compaction) | |
| 400 | + */ | |
| 401 | + getHistoryForLLM(compactionIndex?: number | null): ChatHistoryItem[] { | |
| 402 | + const index = compactionIndex ?? this.currentState.compactionIndex; | |
| 403 | + const full = this.currentState.history; | |
| 404 | + if (index === null || index === undefined || index >= full.length) { | |
| 405 | + return this.getHistory(); | |
| 406 | + } | |
| 407 | + const systemMessage = full[0]?.message?.role === "system" ? full[0] : null; | |
| 408 | + const messagesFromCompaction = full.slice(index); | |
| 409 | + return systemMessage && index > 0 | |
| 410 | + ? [systemMessage, ...messagesFromCompaction] | |
| 411 | + : messagesFromCompaction; | |
| 412 | + } | |
| 413 | + | |
| 414 | + /** | |
| 415 | + * Set the entire history (for remote mode or special cases) | |
| 416 | + */ | |
| 417 | + setHistory(history: ChatHistoryItem[]): void { | |
| 418 | + this.setHistoryInternal(history); | |
| 419 | + logger.debug("Set entire history", { | |
| 420 | + historyLength: history.length, | |
| 421 | + }); | |
| 422 | + } | |
| 423 | + | |
| 424 | + /** | |
| 425 | + * Update compaction index | |
| 426 | + */ | |
| 427 | + setCompactionIndex(index: number | null): void { | |
| 428 | + this.setState({ | |
| 429 | + compactionIndex: index, | |
| 430 | + }); | |
| 431 | + | |
| 432 | + logger.debug("Updated compaction index", { index }); | |
| 433 | + } | |
| 434 | + | |
| 435 | + /** | |
| 436 | + * Find compaction index in history | |
| 437 | + */ | |
| 438 | + private findCompactionIndex(history: ChatHistoryItem[]): number | null { | |
| 439 | + const idx = history.findIndex( | |
| 440 | + (item) => item.conversationSummary !== undefined, | |
| 441 | + ); | |
| 442 | + return idx === -1 ? null : idx; | |
| 443 | + } | |
| 444 | + | |
| 445 | + // Undo/Redo API | |
| 446 | + canUndo(): boolean { | |
| 447 | + return this.past.length > 0; | |
| 448 | + } | |
| 449 | + | |
| 450 | + canRedo(): boolean { | |
| 451 | + return this.future.length > 0; | |
| 452 | + } | |
| 453 | + | |
| 454 | + undo(): void { | |
| 455 | + if (!this.canUndo()) return; | |
| 456 | + const prev = this.past.pop()!; | |
| 457 | + this.future.push([...this.currentState.history]); | |
| 458 | + this.setHistoryInternal(prev, { recordUndo: false }); | |
| 459 | + } | |
| 460 | + | |
| 461 | + redo(): void { | |
| 462 | + if (!this.canRedo()) return; | |
| 463 | + const next = this.future.pop()!; | |
| 464 | + this.past.push([...this.currentState.history]); | |
| 465 | + this.setHistoryInternal(next, { recordUndo: false }); | |
| 466 | + } | |
| 467 | + | |
| 468 | + /** | |
| 469 | + * Get current session ID | |
| 470 | + */ | |
| 471 | + getSessionId(): string { | |
| 472 | + return this.currentState.sessionId; | |
| 473 | + } | |
| 474 | + | |
| 475 | + /** | |
| 476 | + * Check if in remote mode | |
| 477 | + */ | |
| 478 | + isRemoteMode(): boolean { | |
| 479 | + return this.currentState.isRemoteMode; | |
| 480 | + } | |
| 481 | + | |
| 482 | + /** | |
| 483 | + * Set remote mode | |
| 484 | + */ | |
| 485 | + setRemoteMode(isRemote: boolean): void { | |
| 486 | + this.setState({ | |
| 487 | + isRemoteMode: isRemote, | |
| 488 | + }); | |
| 489 | + } | |
| 490 | + | |
| 491 | + /** | |
| 492 | + * Override getState to ensure deep immutability for history array | |
| 493 | + */ | |
| 494 | + getState(): ChatHistoryState { | |
| 495 | + const stateRef = this.currentState; | |
| 496 | + const historyRef = stateRef.history; | |
| 497 | + | |
| 498 | + // If neither the state object nor the history reference changed, | |
| 499 | + // return the same memoized snapshot to preserve referential stability | |
| 500 | + if ( | |
| 501 | + this._memoSnapshot.snapshot && | |
| 502 | + this._memoSnapshot.stateRef === stateRef && | |
| 503 | + this._memoSnapshot.historyRef === historyRef | |
| 504 | + ) { | |
| 505 | + return this._memoSnapshot.snapshot; | |
| 506 | + } | |
| 507 | + | |
| 508 | + // Build a memoized snapshot object with getters to: | |
| 509 | + // - keep the outer object reference stable when unchanged | |
| 510 | + // - return a fresh copy of history on each access to prevent external mutation | |
| 511 | + const snapshot = {} as ChatHistoryState; | |
| 512 | + Object.defineProperties(snapshot, { | |
| 513 | + history: { | |
| 514 | + enumerable: true, | |
| 515 | + get: () => [...stateRef.history], | |
| 516 | + }, | |
| 517 | + compactionIndex: { | |
| 518 | + enumerable: true, | |
| 519 | + get: () => stateRef.compactionIndex, | |
| 520 | + }, | |
| 521 | + sessionId: { | |
| 522 | + enumerable: true, | |
| 523 | + get: () => stateRef.sessionId, | |
| 524 | + }, | |
| 525 | + isRemoteMode: { | |
| 526 | + enumerable: true, | |
| 527 | + get: () => stateRef.isRemoteMode, | |
| 528 | + }, | |
| 529 | + }); | |
| 530 | + | |
| 531 | + this._memoSnapshot = { stateRef, historyRef, snapshot }; | |
| 532 | + return snapshot; | |
| 533 | + } | |
| 534 | +} |
modified extensions/cli/src/services/index.ts +10 −0
| @@ -4,6 +4,7 @@ | ||
| 4 | 4 | |
| 5 | 5 | import { ApiClientService } from "./ApiClientService.js"; |
| 6 | 6 | import { AuthService } from "./AuthService.js"; |
| 7 | +import { ChatHistoryService } from "./ChatHistoryService.js"; | |
| 7 | 8 | import { ConfigService } from "./ConfigService.js"; |
| 8 | 9 | import { FileIndexService } from "./FileIndexService.js"; |
| 9 | 10 | import { MCPService } from "./MCPService.js"; |
| @@ -29,6 +30,7 @@ | ||
| 29 | 30 | const mcpService = new MCPService(); |
| 30 | 31 | const fileIndexService = new FileIndexService(); |
| 31 | 32 | const resourceMonitoringService = new ResourceMonitoringService(); |
| 33 | +const chatHistoryService = new ChatHistoryService(); | |
| 32 | 34 | |
| 33 | 35 | /** |
| 34 | 36 | * Initialize all services and register them with the service container |
| @@ -241,6 +243,12 @@ | ||
| 241 | 243 | [], |
| 242 | 244 | ); |
| 243 | 245 | |
| 246 | + serviceContainer.register( | |
| 247 | + SERVICE_NAMES.CHAT_HISTORY, | |
| 248 | + () => chatHistoryService.initialize(undefined, initOptions.headless), | |
| 249 | + [], // No dependencies for now, but could depend on SESSION in future | |
| 250 | + ); | |
| 251 | + | |
| 244 | 252 | // Eagerly initialize all services to ensure they're ready when needed |
| 245 | 253 | // This avoids race conditions and "service not ready" errors |
| 246 | 254 | await serviceContainer.initializeAll(); |
| @@ -284,6 +292,7 @@ | ||
| 284 | 292 | SERVICE_NAMES.MCP, |
| 285 | 293 | SERVICE_NAMES.FILE_INDEX, |
| 286 | 294 | SERVICE_NAMES.RESOURCE_MONITORING, |
| 295 | + SERVICE_NAMES.CHAT_HISTORY, | |
| 287 | 296 | ].every((name) => serviceContainer.isReady(name)); |
| 288 | 297 | } |
| 289 | 298 | |
| @@ -307,6 +316,7 @@ | ||
| 307 | 316 | mode: modeService, |
| 308 | 317 | resourceMonitoring: resourceMonitoringService, |
| 309 | 318 | systemMessage: systemMessageService, |
| 319 | + chatHistory: chatHistoryService, | |
| 310 | 320 | } as const; |
| 311 | 321 | |
| 312 | 322 | // Export the service container for advanced usage |
modified extensions/cli/src/services/types.ts +2 −0
| @@ -93,6 +93,7 @@ | ||
| 93 | 93 | } |
| 94 | 94 | |
| 95 | 95 | export type { FileIndexServiceState } from "./FileIndexService.js"; |
| 96 | +export type { ChatHistoryState } from "./ChatHistoryService.js"; | |
| 96 | 97 | |
| 97 | 98 | /** |
| 98 | 99 | * Service names as constants to prevent typos |
| @@ -107,6 +108,7 @@ | ||
| 107 | 108 | FILE_INDEX: "fileIndex", |
| 108 | 109 | RESOURCE_MONITORING: "resourceMonitoring", |
| 109 | 110 | SYSTEM_MESSAGE: "systemMessage", |
| 111 | + CHAT_HISTORY: "chatHistory", | |
| 110 | 112 | } as const; |
| 111 | 113 | |
| 112 | 114 | /** |
modified extensions/cli/src/slashCommands.ts +29 −0
| @@ -199,6 +199,34 @@ | ||
| 199 | 199 | }; |
| 200 | 200 | } |
| 201 | 201 | |
| 202 | +async function handleFork() { | |
| 203 | + posthogService.capture("useSlashCommand", { name: "fork" }); | |
| 204 | + | |
| 205 | + try { | |
| 206 | + const currentSession = getCurrentSession(); | |
| 207 | + const forkCommand = `cn --fork ${currentSession.sessionId}`; | |
| 208 | + // Try to copy to clipboard dynamically to avoid hard dependency in tests | |
| 209 | + try { | |
| 210 | + const clipboardy = await import("clipboardy"); | |
| 211 | + await clipboardy.default.write(forkCommand); | |
| 212 | + return { | |
| 213 | + exit: false, | |
| 214 | + output: chalk.gray(`${forkCommand} (copied to clipboard)`), | |
| 215 | + }; | |
| 216 | + } catch { | |
| 217 | + return { | |
| 218 | + exit: false, | |
| 219 | + output: chalk.gray(`${forkCommand}`), | |
| 220 | + }; | |
| 221 | + } | |
| 222 | + } catch (error: any) { | |
| 223 | + return { | |
| 224 | + exit: false, | |
| 225 | + output: chalk.red(`Failed to create fork command: ${error.message}`), | |
| 226 | + }; | |
| 227 | + } | |
| 228 | +} | |
| 229 | + | |
| 202 | 230 | const commandHandlers: Record<string, CommandHandler> = { |
| 203 | 231 | help: handleHelp, |
| 204 | 232 | clear: () => { |
| @@ -230,6 +258,7 @@ | ||
| 230 | 258 | posthogService.capture("useSlashCommand", { name: "resume" }); |
| 231 | 259 | return { openSessionSelector: true }; |
| 232 | 260 | }, |
| 261 | + fork: handleFork, | |
| 233 | 262 | }; |
| 234 | 263 | |
| 235 | 264 | export async function handleSlashCommands( |
modified extensions/cli/src/stream/handleToolCalls.ts +81 −35
| @@ -9,6 +9,7 @@ | ||
| 9 | 9 | MCPServiceState, |
| 10 | 10 | MCPTool, |
| 11 | 11 | SERVICE_NAMES, |
| 12 | + services, | |
| 12 | 13 | } from "../services/index.js"; |
| 13 | 14 | import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js"; |
| 14 | 15 | import { getAllBuiltinTools, ToolCall } from "../tools/index.js"; |
| @@ -27,14 +28,23 @@ | ||
| 27 | 28 | callbacks: StreamCallbacks | undefined, |
| 28 | 29 | isHeadless: boolean, |
| 29 | 30 | ): Promise<boolean> { |
| 31 | + const chatHistorySvc = services.chatHistory; | |
| 32 | + const useService = | |
| 33 | + typeof chatHistorySvc?.isReady === "function" && chatHistorySvc.isReady(); | |
| 30 | 34 | if (toolCalls.length === 0) { |
| 31 | 35 | if (content) { |
| 32 | - chatHistory.push( | |
| 33 | - createHistoryItem({ | |
| 34 | - role: "assistant", | |
| 35 | - content, | |
| 36 | - }), | |
| 37 | - ); | |
| 36 | + if (useService) { | |
| 37 | + // Service-driven: write assistant message via service | |
| 38 | + chatHistorySvc.addAssistantMessage(content); | |
| 39 | + } else { | |
| 40 | + // Fallback only when service is unavailable | |
| 41 | + chatHistory.push( | |
| 42 | + createHistoryItem({ | |
| 43 | + role: "assistant", | |
| 44 | + content, | |
| 45 | + }), | |
| 46 | + ); | |
| 47 | + } | |
| 38 | 48 | } |
| 39 | 49 | return false; |
| 40 | 50 | } |
| @@ -68,7 +78,16 @@ | ||
| 68 | 78 | })), |
| 69 | 79 | }; |
| 70 | 80 | |
| 71 | - chatHistory.push(createHistoryItem(assistantMessage, [], toolCallStates)); | |
| 81 | + if (useService) { | |
| 82 | + // Important: pass ChatCompletion-style toolCalls, not internal ToolCall[] | |
| 83 | + chatHistorySvc.addAssistantMessage( | |
| 84 | + assistantMessage.content || "", | |
| 85 | + assistantMessage.toolCalls, | |
| 86 | + ); | |
| 87 | + } else { | |
| 88 | + // Fallback only when service is unavailable | |
| 89 | + chatHistory.push(createHistoryItem(assistantMessage, [], toolCallStates)); | |
| 90 | + } | |
| 72 | 91 | |
| 73 | 92 | // First preprocess the tool calls |
| 74 | 93 | const { preprocessedCalls, errorChatEntries } = |
| @@ -77,13 +96,17 @@ | ||
| 77 | 96 | // Add any preprocessing errors to chat history |
| 78 | 97 | // Convert error entries from OpenAI format to ChatHistoryItem format |
| 79 | 98 | errorChatEntries.forEach((errorEntry) => { |
| 80 | - chatHistory.push( | |
| 81 | - createHistoryItem({ | |
| 82 | - role: "tool", | |
| 83 | - content: stripImages(errorEntry.content) || "", | |
| 84 | - toolCallId: errorEntry.tool_call_id, | |
| 85 | - }), | |
| 86 | - ); | |
| 99 | + const item = createHistoryItem({ | |
| 100 | + role: "tool", | |
| 101 | + content: stripImages(errorEntry.content) || "", | |
| 102 | + toolCallId: errorEntry.tool_call_id, | |
| 103 | + }); | |
| 104 | + if (useService) { | |
| 105 | + chatHistorySvc.addHistoryItem(item); | |
| 106 | + } else { | |
| 107 | + // Fallback only when service is unavailable | |
| 108 | + chatHistory.push(item); | |
| 109 | + } | |
| 87 | 110 | }); |
| 88 | 111 | |
| 89 | 112 | // Execute the valid preprocessed tool calls |
| @@ -97,32 +120,55 @@ | ||
| 97 | 120 | return true; // Signal early return needed |
| 98 | 121 | } |
| 99 | 122 | |
| 100 | - // Convert tool results from OpenAI format to ChatHistoryItem format | |
| 101 | - // and add them to the chat history | |
| 123 | + // Convert tool results and add them to the chat history with per-result status | |
| 102 | 124 | toolResults.forEach((toolResult) => { |
| 103 | - // Find the corresponding tool call state to update | |
| 104 | - const lastAssistantIndex = chatHistory.findLastIndex( | |
| 105 | - (item) => item.message.role === "assistant" && item.toolCallStates, | |
| 106 | - ); | |
| 125 | + const resultContent = | |
| 126 | + typeof toolResult.content === "string" ? toolResult.content : ""; | |
| 107 | 127 | |
| 128 | + // Derive per-result status instead of applying batch-wide hasRejection | |
| 129 | + let status: ToolStatus = "done"; | |
| 130 | + const lower = resultContent.toLowerCase(); | |
| 108 | 131 | if ( |
| 109 | - lastAssistantIndex >= 0 && | |
| 110 | - chatHistory[lastAssistantIndex].toolCallStates | |
| 132 | + lower.includes("permission denied by user") || | |
| 133 | + lower.includes("cancelled due to previous tool rejection") || | |
| 134 | + lower.includes("canceled due to previous tool rejection") | |
| 111 | 135 | ) { |
| 112 | - const toolState = chatHistory[lastAssistantIndex].toolCallStates.find( | |
| 113 | - (ts) => ts.toolCallId === toolResult.tool_call_id, | |
| 114 | - ); | |
| 136 | + status = "canceled"; | |
| 137 | + } else if ( | |
| 138 | + lower.startsWith("error executing tool") || | |
| 139 | + lower.startsWith("error:") | |
| 140 | + ) { | |
| 141 | + status = "errored" as ToolStatus; | |
| 142 | + } | |
| 115 | 143 | |
| 116 | - if (toolState) { | |
| 117 | - toolState.status = hasRejection ? "canceled" : "done"; | |
| 118 | - toolState.output = [ | |
| 119 | - { | |
| 120 | - content: | |
| 121 | - typeof toolResult.content === "string" ? toolResult.content : "", | |
| 122 | - name: `Tool Result`, | |
| 123 | - description: "Tool execution result", | |
| 124 | - }, | |
| 125 | - ]; | |
| 144 | + if (useService) { | |
| 145 | + chatHistorySvc.addToolResult( | |
| 146 | + toolResult.tool_call_id, | |
| 147 | + resultContent, | |
| 148 | + status, | |
| 149 | + ); | |
| 150 | + } else { | |
| 151 | + // Fallback only when service is unavailable: update local tool state | |
| 152 | + const lastAssistantIndex = chatHistory.findLastIndex( | |
| 153 | + (item) => item.message.role === "assistant" && item.toolCallStates, | |
| 154 | + ); | |
| 155 | + if ( | |
| 156 | + lastAssistantIndex >= 0 && | |
| 157 | + chatHistory[lastAssistantIndex].toolCallStates | |
| 158 | + ) { | |
| 159 | + const toolState = chatHistory[lastAssistantIndex].toolCallStates.find( | |
| 160 | + (ts) => ts.toolCallId === toolResult.tool_call_id, | |
| 161 | + ); | |
| 162 | + if (toolState) { | |
| 163 | + toolState.status = status; | |
| 164 | + toolState.output = [ | |
| 165 | + { | |
| 166 | + content: resultContent, | |
| 167 | + name: `Tool Result`, | |
| 168 | + description: "Tool execution result", | |
| 169 | + }, | |
| 170 | + ]; | |
| 171 | + } | |
| 126 | 172 | } |
| 127 | 173 | } |
| 128 | 174 | }); |
modified extensions/cli/src/stream/streamChatResponse.helpers.ts +117 −46
| @@ -5,6 +5,7 @@ | ||
| 5 | 5 | import { checkToolPermission } from "../permissions/permissionChecker.js"; |
| 6 | 6 | import { toolPermissionManager } from "../permissions/permissionManager.js"; |
| 7 | 7 | import { ToolCallRequest } from "../permissions/types.js"; |
| 8 | +import { services } from "../services/index.js"; | |
| 8 | 9 | import { telemetryService } from "../telemetry/telemetryService.js"; |
| 9 | 10 | import { calculateTokenCost } from "../telemetry/utils.js"; |
| 10 | 11 | import { |
| @@ -373,81 +374,151 @@ | ||
| 373 | 374 | hasRejection: boolean; |
| 374 | 375 | chatHistoryEntries: ChatCompletionToolMessageParam[]; |
| 375 | 376 | }> { |
| 376 | - const chatHistoryEntries: ChatCompletionToolMessageParam[] = []; | |
| 377 | - let hasRejection = false; | |
| 377 | + // Strategy: queue permissions (preserve order), then run approved tools in parallel. | |
| 378 | + // If any permission is rejected, cancel the remaining tools in this batch. | |
| 378 | 379 | |
| 379 | - // Execute each preprocessed tool call | |
| 380 | - for (const toolCall of preprocessedCalls) { | |
| 381 | - if (hasRejection) { | |
| 382 | - const cancelledMessage = `Cancelled due to previous tool rejection`; | |
| 383 | - chatHistoryEntries.push({ | |
| 384 | - role: "tool", | |
| 385 | - tool_call_id: toolCall.id, | |
| 386 | - content: cancelledMessage, | |
| 387 | - }); | |
| 380 | + type IndexedCall = { index: number; call: PreprocessedToolCall }; | |
| 381 | + const indexedCalls: IndexedCall[] = preprocessedCalls.map((call, index) => ({ | |
| 382 | + index, | |
| 383 | + call, | |
| 384 | + })); | |
| 388 | 385 | |
| 389 | - callbacks?.onToolResult?.(cancelledMessage, toolCall.name, "canceled"); | |
| 390 | - continue; | |
| 391 | - } | |
| 386 | + const entriesByIndex = new Map<number, ChatCompletionToolMessageParam>(); | |
| 387 | + const execPromises: Promise<void>[] = []; | |
| 388 | + | |
| 389 | + let hasRejection = false; | |
| 390 | + | |
| 391 | + // Permission phase (sequential) | |
| 392 | + for (const { index, call } of indexedCalls) { | |
| 393 | + // Do not cancel subsequent tools after a rejection; handle each independently | |
| 392 | 394 | |
| 393 | - // Handle remaining tool calls in this batch to maintain chat history consistency | |
| 394 | 395 | try { |
| 395 | 396 | logger.debug("Checking tool permissions", { |
| 396 | - name: toolCall.name, | |
| 397 | - arguments: toolCall.arguments, | |
| 397 | + name: call.name, | |
| 398 | + arguments: call.arguments, | |
| 398 | 399 | }); |
| 399 | 400 | |
| 400 | - // Notify tool start - before permission check | |
| 401 | - // This ensures the UI shows the tool call even if it's rejected | |
| 402 | - callbacks?.onToolStart?.(toolCall.name, toolCall.arguments); | |
| 401 | + // Notify tool start before permission check to display in UI fallbacks | |
| 402 | + callbacks?.onToolStart?.(call.name, call.arguments); | |
| 403 | 403 | |
| 404 | - // Check tool permissions using helper | |
| 405 | 404 | const approved = await checkToolPermissionApproval( |
| 406 | - toolCall, | |
| 405 | + call, | |
| 407 | 406 | callbacks, |
| 408 | 407 | isHeadless, |
| 409 | 408 | ); |
| 410 | 409 | |
| 411 | 410 | if (!approved) { |
| 412 | - handlePermissionDenied(toolCall, chatHistoryEntries, callbacks); | |
| 411 | + // Permission denied: record and mark rejection | |
| 412 | + const deniedEntry: ChatCompletionToolMessageParam = { | |
| 413 | + role: "tool", | |
| 414 | + tool_call_id: call.id, | |
| 415 | + content: `Permission denied by user`, | |
| 416 | + }; | |
| 417 | + entriesByIndex.set(index, deniedEntry); | |
| 418 | + callbacks?.onToolResult?.( | |
| 419 | + String(deniedEntry.content), | |
| 420 | + call.name, | |
| 421 | + "canceled", | |
| 422 | + ); | |
| 423 | + // Immediate service update for UI feedback | |
| 424 | + try { | |
| 425 | + services.chatHistory.addToolResult( | |
| 426 | + call.id, | |
| 427 | + String(deniedEntry.content), | |
| 428 | + "canceled", | |
| 429 | + ); | |
| 430 | + } catch {} | |
| 413 | 431 | hasRejection = true; |
| 432 | + // Remaining items will be auto-cancelled in subsequent iterations | |
| 414 | 433 | continue; |
| 415 | 434 | } |
| 416 | 435 | |
| 417 | - logger.debug("Executing tool", { | |
| 418 | - name: toolCall.name, | |
| 419 | - arguments: toolCall.arguments, | |
| 420 | - }); | |
| 421 | - | |
| 422 | - const toolResult = await executeToolCall(toolCall); | |
| 423 | - | |
| 424 | - chatHistoryEntries.push({ | |
| 425 | - role: "tool", | |
| 426 | - tool_call_id: toolCall.id, | |
| 427 | - content: toolResult, | |
| 428 | - }); | |
| 429 | - | |
| 430 | - callbacks?.onToolResult?.(toolResult, toolCall.name, "done"); | |
| 436 | + // Immediately mark as calling for instant UI feedback | |
| 437 | + try { | |
| 438 | + services.chatHistory.updateToolStatus(call.id, "calling"); | |
| 439 | + } catch {} | |
| 440 | + | |
| 441 | + // Start execution immediately for approved calls | |
| 442 | + execPromises.push( | |
| 443 | + (async () => { | |
| 444 | + try { | |
| 445 | + logger.debug("Executing tool", { | |
| 446 | + name: call.name, | |
| 447 | + arguments: call.arguments, | |
| 448 | + }); | |
| 449 | + const toolResult = await executeToolCall(call); | |
| 450 | + const entry: ChatCompletionToolMessageParam = { | |
| 451 | + role: "tool", | |
| 452 | + tool_call_id: call.id, | |
| 453 | + content: toolResult, | |
| 454 | + }; | |
| 455 | + entriesByIndex.set(index, entry); | |
| 456 | + callbacks?.onToolResult?.(toolResult, call.name, "done"); | |
| 457 | + // Immediate service update for UI feedback | |
| 458 | + try { | |
| 459 | + services.chatHistory.addToolResult( | |
| 460 | + call.id, | |
| 461 | + String(toolResult), | |
| 462 | + "done", | |
| 463 | + ); | |
| 464 | + } catch {} | |
| 465 | + } catch (error) { | |
| 466 | + const errorMessage = `Error executing tool ${call.name}: ${ | |
| 467 | + error instanceof Error ? error.message : String(error) | |
| 468 | + }`; | |
| 469 | + logger.error("Tool execution failed", { | |
| 470 | + name: call.name, | |
| 471 | + error: errorMessage, | |
| 472 | + }); | |
| 473 | + entriesByIndex.set(index, { | |
| 474 | + role: "tool", | |
| 475 | + tool_call_id: call.id, | |
| 476 | + content: errorMessage, | |
| 477 | + }); | |
| 478 | + callbacks?.onToolError?.(errorMessage, call.name); | |
| 479 | + // Immediate service update for UI feedback | |
| 480 | + try { | |
| 481 | + services.chatHistory.addToolResult( | |
| 482 | + call.id, | |
| 483 | + errorMessage as string, | |
| 484 | + "errored", | |
| 485 | + ); | |
| 486 | + } catch {} | |
| 487 | + } | |
| 488 | + })(), | |
| 489 | + ); | |
| 431 | 490 | } catch (error) { |
| 432 | - const errorMessage = `Error executing tool ${toolCall.name}: ${ | |
| 491 | + const errorMessage = `Error checking permissions for ${call.name}: ${ | |
| 433 | 492 | error instanceof Error ? error.message : String(error) |
| 434 | 493 | }`; |
| 435 | - | |
| 436 | - logger.error("Tool execution failed", { | |
| 437 | - name: toolCall.name, | |
| 494 | + logger.error("Permission check failed", { | |
| 495 | + name: call.name, | |
| 438 | 496 | error: errorMessage, |
| 439 | 497 | }); |
| 440 | - | |
| 441 | - chatHistoryEntries.push({ | |
| 498 | + entriesByIndex.set(index, { | |
| 442 | 499 | role: "tool", |
| 443 | - tool_call_id: toolCall.id, | |
| 500 | + tool_call_id: call.id, | |
| 444 | 501 | content: errorMessage, |
| 445 | 502 | }); |
| 446 | - | |
| 447 | - callbacks?.onToolError?.(errorMessage, toolCall.name); | |
| 503 | + callbacks?.onToolError?.(errorMessage, call.name); | |
| 504 | + // Treat permission errors like execution errors but do not stop the batch | |
| 505 | + try { | |
| 506 | + services.chatHistory.addToolResult( | |
| 507 | + call.id, | |
| 508 | + errorMessage as string, | |
| 509 | + "errored", | |
| 510 | + ); | |
| 511 | + } catch {} | |
| 448 | 512 | } |
| 449 | 513 | } |
| 450 | 514 | |
| 515 | + await Promise.all(execPromises); | |
| 516 | + | |
| 517 | + // Assemble final entries in original order | |
| 518 | + const chatHistoryEntries: ChatCompletionToolMessageParam[] = preprocessedCalls | |
| 519 | + .map((_, index) => entriesByIndex.get(index)) | |
| 520 | + .filter((e): e is ChatCompletionToolMessageParam => !!e); | |
| 521 | + | |
| 451 | 522 | return { |
| 452 | 523 | hasRejection, |
| 453 | 524 | chatHistoryEntries, |
modified extensions/cli/src/stream/streamChatResponse.ts +25 −3
| @@ -8,7 +8,7 @@ | ||
| 8 | 8 | ChatCompletionTool, |
| 9 | 9 | } from "openai/resources.mjs"; |
| 10 | 10 | |
| 11 | -import { getServiceSync, SERVICE_NAMES } from "../services/index.js"; | |
| 11 | +import { getServiceSync, SERVICE_NAMES, services } from "../services/index.js"; | |
| 12 | 12 | import { systemMessageService } from "../services/SystemMessageService.js"; |
| 13 | 13 | import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js"; |
| 14 | 14 | import { telemetryService } from "../telemetry/telemetryService.js"; |
| @@ -298,6 +298,7 @@ | ||
| 298 | 298 | } |
| 299 | 299 | |
| 300 | 300 | // Main function that handles the conversation loop |
| 301 | +// eslint-disable-next-line complexity | |
| 301 | 302 | export async function streamChatResponse( |
| 302 | 303 | chatHistory: ChatHistoryItem[], |
| 303 | 304 | model: ModelConfig, |
| @@ -320,6 +321,16 @@ | ||
| 320 | 321 | let finalResponse = ""; |
| 321 | 322 | |
| 322 | 323 | while (true) { |
| 324 | + // If ChatHistoryService is available, refresh local chatHistory view | |
| 325 | + const chatHistorySvc = services.chatHistory; | |
| 326 | + if ( | |
| 327 | + typeof chatHistorySvc?.isReady === "function" && | |
| 328 | + chatHistorySvc.isReady() | |
| 329 | + ) { | |
| 330 | + try { | |
| 331 | + chatHistory = chatHistorySvc.getHistory(); | |
| 332 | + } catch {} | |
| 333 | + } | |
| 323 | 334 | logger.debug("Starting conversation iteration"); |
| 324 | 335 | |
| 325 | 336 | // Recompute tools on each iteration to handle mode changes during streaming |
| @@ -359,7 +370,7 @@ | ||
| 359 | 370 | // Handle content display |
| 360 | 371 | handleContentDisplay(content, callbacks, isHeadless); |
| 361 | 372 | |
| 362 | - // Handle tool calls and check for early return | |
| 373 | + // Handle tool calls and check for early return. This updates history via ChatHistoryService. | |
| 363 | 374 | const shouldReturn = await handleToolCalls( |
| 364 | 375 | toolCalls, |
| 365 | 376 | chatHistory, |
| @@ -385,7 +396,18 @@ | ||
| 385 | 396 | |
| 386 | 397 | // Only update chat history if compaction actually occurred |
| 387 | 398 | if (wasCompacted) { |
| 388 | - chatHistory = [...updatedChatHistory]; | |
| 399 | + // Always prefer service; local copy is for temporary reads only | |
| 400 | + const chatHistorySvc2 = services.chatHistory; | |
| 401 | + if ( | |
| 402 | + typeof chatHistorySvc2?.isReady === "function" && | |
| 403 | + chatHistorySvc2.isReady() | |
| 404 | + ) { | |
| 405 | + chatHistorySvc2.setHistory(updatedChatHistory); | |
| 406 | + chatHistory = chatHistorySvc2.getHistory(); | |
| 407 | + } else { | |
| 408 | + // Fallback only when service is unavailable | |
| 409 | + chatHistory = [...updatedChatHistory]; | |
| 410 | + } | |
| 389 | 411 | } |
| 390 | 412 | } |
| 391 | 413 |
modified extensions/cli/src/test-helpers/ui-test-context.ts +15 −0
| @@ -8,6 +8,21 @@ | ||
| 8 | 8 | cleanup: () => void; |
| 9 | 9 | } |
| 10 | 10 | |
| 11 | +// Export a mock LLM API for testing | |
| 12 | +export const mockLlmApi = { | |
| 13 | + chatCompletionNonStream: vi.fn(), | |
| 14 | + chatCompletionStream: vi.fn(), | |
| 15 | + completionNonStream: vi.fn(), | |
| 16 | + completionStream: vi.fn(), | |
| 17 | + embed: vi.fn(), | |
| 18 | + rerank: vi.fn(), | |
| 19 | + fimStream: vi.fn(), | |
| 20 | + listModels: vi.fn(), | |
| 21 | + completions: vi.fn(), | |
| 22 | + stream: vi.fn(), | |
| 23 | + abort: vi.fn(), | |
| 24 | +} as any; | |
| 25 | + | |
| 11 | 26 | /** |
| 12 | 27 | * Creates a test context with common UI mocks for TUI components |
| 13 | 28 | */ |
modified extensions/cli/src/ui/AppRoot.tsx +1 −0
| @@ -8,6 +8,7 @@ | ||
| 8 | 8 | configPath?: string; |
| 9 | 9 | initialPrompt?: string; |
| 10 | 10 | resume?: boolean; |
| 11 | + fork?: string; | |
| 11 | 12 | additionalRules?: string[]; |
| 12 | 13 | additionalPrompts?: string[]; |
| 13 | 14 | } |
modified extensions/cli/src/ui/TUIChat.tsx +3 −0
| @@ -43,6 +43,7 @@ | ||
| 43 | 43 | configPath?: string; |
| 44 | 44 | initialPrompt?: string; |
| 45 | 45 | resume?: boolean; |
| 46 | + fork?: string; | |
| 46 | 47 | additionalRules?: string[]; |
| 47 | 48 | additionalPrompts?: string[]; |
| 48 | 49 | } |
| @@ -138,6 +139,7 @@ | ||
| 138 | 139 | configPath, |
| 139 | 140 | initialPrompt, |
| 140 | 141 | resume, |
| 142 | + fork, | |
| 141 | 143 | additionalRules, |
| 142 | 144 | additionalPrompts, |
| 143 | 145 | }) => { |
| @@ -200,6 +202,7 @@ | ||
| 200 | 202 | llmApi: services.model?.llmApi || undefined, |
| 201 | 203 | initialPrompt, |
| 202 | 204 | resume, |
| 205 | + fork, | |
| 203 | 206 | additionalRules, |
| 204 | 207 | additionalPrompts, |
| 205 | 208 | onShowConfigSelector: () => navigateTo("config"), |
modified extensions/cli/src/ui/__tests__/TUIChat.fileSearch.test.tsx +43 −56
| @@ -1,8 +1,8 @@ | ||
| 1 | -import { testBothModes, renderInMode } from "./TUIChat.dualModeHelper.js"; | |
| 1 | +import { testSingleMode, renderInMode } from "./TUIChat.dualModeHelper.js"; | |
| 2 | 2 | |
| 3 | 3 | describe("TUIChat - @ File Search Tests", () => { |
| 4 | - testBothModes("shows @ character when user types @", async (mode) => { | |
| 5 | - const { lastFrame, stdin } = renderInMode(mode); | |
| 4 | + testSingleMode("shows @ character when user types @", "local", async () => { | |
| 5 | + const { lastFrame, stdin } = renderInMode("local"); | |
| 6 | 6 | |
| 7 | 7 | // Wait a bit for initial render |
| 8 | 8 | await new Promise((resolve) => setTimeout(resolve, 50)); |
| @@ -16,52 +16,43 @@ | ||
| 16 | 16 | const frame = lastFrame()!; |
| 17 | 17 | |
| 18 | 18 | // Should show @ character in input or show file search UI |
| 19 | - // The @ might be in the input line or in a file search UI | |
| 20 | 19 | const hasAtSymbol = frame.includes("@") || frame.includes("◉ @"); |
| 21 | 20 | expect(hasAtSymbol).toBe(true); |
| 22 | 21 | |
| 23 | - // Mode-specific UI | |
| 24 | - if (mode === "remote") { | |
| 25 | - expect(frame).toContain("Remote Mode"); | |
| 26 | - } else { | |
| 27 | - expect(frame).not.toContain("Remote Mode"); | |
| 28 | - expect(frame).toContain("Continue CLI"); | |
| 29 | - } | |
| 22 | + // Local mode specific UI expectations | |
| 23 | + expect(frame).not.toContain("Remote Mode"); | |
| 24 | + expect(frame).toContain("Continue CLI"); | |
| 30 | 25 | }); |
| 31 | 26 | |
| 32 | - testBothModes("shows search text when user types after @", async (mode) => { | |
| 33 | - const { lastFrame, stdin } = renderInMode(mode); | |
| 27 | + testSingleMode( | |
| 28 | + "shows search text when user types after @", | |
| 29 | + "local", | |
| 30 | + async () => { | |
| 31 | + const { lastFrame, stdin } = renderInMode("local"); | |
| 34 | 32 | |
| 35 | - // Type @ followed by text to filter files | |
| 36 | - stdin.write("@READ"); | |
| 33 | + // Type @ followed by text to filter files | |
| 34 | + stdin.write("@READ"); | |
| 37 | 35 | |
| 38 | - // Wait for file search to filter and display results | |
| 39 | - await new Promise((resolve) => setTimeout(resolve, 100)); | |
| 36 | + // Wait for file search to filter and display results | |
| 37 | + await new Promise((resolve) => setTimeout(resolve, 100)); | |
| 40 | 38 | |
| 41 | - const frame = lastFrame()!; | |
| 39 | + const frame = lastFrame()!; | |
| 42 | 40 | |
| 43 | - // Should show the typed text | |
| 44 | - expect(frame).toContain("@READ"); | |
| 41 | + // Should show the typed text | |
| 42 | + expect(frame).toContain("@READ"); | |
| 45 | 43 | |
| 46 | - // In local mode, should show either navigation hints or files | |
| 47 | - if (mode === "local") { | |
| 48 | 44 | // Should show either navigation hints or at least indicate file search is working |
| 49 | 45 | const hasNavigationHints = frame.includes("↑/↓ to navigate"); |
| 50 | - const hasFileSearch = | |
| 51 | - frame.includes("@READ") && !frame.includes("Remote Mode"); | |
| 46 | + const hasFileSearch = frame.includes("@READ"); | |
| 52 | 47 | expect(hasNavigationHints || hasFileSearch).toBe(true); |
| 53 | - } | |
| 54 | - | |
| 55 | - // Mode-specific checks | |
| 56 | - if (mode === "remote") { | |
| 57 | - expect(frame).toContain("Remote Mode"); | |
| 58 | - } else { | |
| 48 | + | |
| 49 | + // Local mode specific UI expectations | |
| 59 | 50 | expect(frame).not.toContain("Remote Mode"); |
| 60 | - } | |
| 61 | - }); | |
| 51 | + }, | |
| 52 | + ); | |
| 62 | 53 | |
| 63 | - testBothModes("handles multiple @ characters", async (mode) => { | |
| 64 | - const { lastFrame, stdin } = renderInMode(mode); | |
| 54 | + testSingleMode("handles multiple @ characters", "local", async () => { | |
| 55 | + const { lastFrame, stdin } = renderInMode("local"); | |
| 65 | 56 | |
| 66 | 57 | // Type multiple @ characters |
| 67 | 58 | stdin.write("@@test"); |
| @@ -75,36 +66,32 @@ | ||
| 75 | 66 | expect(frame).toBeDefined(); |
| 76 | 67 | expect(frame).toContain("@@test"); |
| 77 | 68 | |
| 78 | - // Mode-specific UI elements | |
| 79 | - if (mode === "remote") { | |
| 80 | - expect(frame).toContain("Remote Mode"); | |
| 81 | - } else { | |
| 82 | - expect(frame).toContain("Continue CLI"); | |
| 83 | - } | |
| 69 | + // Local mode specific UI elements | |
| 70 | + expect(frame).toContain("Continue CLI"); | |
| 84 | 71 | }); |
| 85 | 72 | |
| 86 | - testBothModes("handles @ character input without crashing", async (mode) => { | |
| 87 | - const { lastFrame, stdin } = renderInMode(mode); | |
| 73 | + testSingleMode( | |
| 74 | + "handles @ character input without crashing", | |
| 75 | + "local", | |
| 76 | + async () => { | |
| 77 | + const { lastFrame, stdin } = renderInMode("local"); | |
| 88 | 78 | |
| 89 | - // Type @ to trigger file search | |
| 90 | - stdin.write("@"); | |
| 79 | + // Type @ to trigger file search | |
| 80 | + stdin.write("@"); | |
| 91 | 81 | |
| 92 | - // Wait for potential async operations | |
| 93 | - await new Promise((resolve) => setTimeout(resolve, 50)); | |
| 82 | + // Wait for potential async operations | |
| 83 | + await new Promise((resolve) => setTimeout(resolve, 50)); | |
| 94 | 84 | |
| 95 | - const frame = lastFrame()!; | |
| 85 | + const frame = lastFrame()!; | |
| 96 | 86 | |
| 97 | - // Should not crash and show something | |
| 98 | - expect(frame).toBeDefined(); | |
| 99 | - expect(frame.length).toBeGreaterThan(0); | |
| 87 | + // Should not crash and show something | |
| 88 | + expect(frame).toBeDefined(); | |
| 89 | + expect(frame.length).toBeGreaterThan(0); | |
| 100 | 90 | |
| 101 | - // In local mode, should show either navigation hints or file search UI | |
| 102 | - if (mode === "local") { | |
| 103 | 91 | // Should show either navigation hints or at least the @ character in file search |
| 104 | 92 | const hasNavigationHints = frame.includes("↑/↓ to navigate"); |
| 105 | - const hasFileSearchUI = | |
| 106 | - frame.includes("@") && !frame.includes("Remote Mode"); | |
| 93 | + const hasFileSearchUI = frame.includes("@"); | |
| 107 | 94 | expect(hasNavigationHints || hasFileSearchUI).toBe(true); |
| 108 | - } | |
| 109 | - }); | |
| 95 | + }, | |
| 96 | + ); | |
| 110 | 97 | }); |
modified extensions/cli/src/ui/__tests__/TUIChat.slashCommands.test.tsx +7 −3
| @@ -30,8 +30,10 @@ | ||
| 30 | 30 | // Type /log to trigger slash command filtering |
| 31 | 31 | stdin.write("/log"); |
| 32 | 32 | |
| 33 | - // Wait a bit for the UI to update | |
| 34 | - await new Promise((resolve) => setTimeout(resolve, 50)); | |
| 33 | + // Wait a bit for the UI to update (allow extra time in both modes) | |
| 34 | + await new Promise((resolve) => | |
| 35 | + setTimeout(resolve, mode === "remote" ? 200 : 150), | |
| 36 | + ); | |
| 35 | 37 | |
| 36 | 38 | const frame = lastFrame(); |
| 37 | 39 | |
| @@ -81,7 +83,9 @@ | ||
| 81 | 83 | // Type just / |
| 82 | 84 | stdin.write("/"); |
| 83 | 85 | |
| 84 | - await new Promise((resolve) => setTimeout(resolve, 50)); | |
| 86 | + await new Promise((resolve) => | |
| 87 | + setTimeout(resolve, mode === "remote" ? 120 : 50), | |
| 88 | + ); | |
| 85 | 89 | |
| 86 | 90 | const frame = lastFrame(); |
| 87 | 91 |
modified extensions/cli/src/ui/components/MemoizedMessage.tsx +9 −1
| @@ -117,7 +117,15 @@ | ||
| 117 | 117 | > |
| 118 | 118 | <Box> |
| 119 | 119 | <Text |
| 120 | - color={isErrored ? "red" : isCompleted ? "green" : "white"} | |
| 120 | + color={ | |
| 121 | + isErrored | |
| 122 | + ? "red" | |
| 123 | + : isCompleted | |
| 124 | + ? "green" | |
| 125 | + : toolState.status === "generated" | |
| 126 | + ? "yellow" | |
| 127 | + : "white" | |
| 128 | + } | |
| 121 | 129 | > |
| 122 | 130 | {isCompleted || isErrored ? "●" : "○"} |
| 123 | 131 | </Text> |
modified extensions/cli/src/ui/hooks/useChat.helpers.ts +1 −3
| @@ -221,7 +221,6 @@ | ||
| 221 | 221 | remoteUrl?: string; |
| 222 | 222 | onShowConfigSelector: () => void; |
| 223 | 223 | exit: () => void; |
| 224 | - setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>; | |
| 225 | 224 | } |
| 226 | 225 | |
| 227 | 226 | /** |
| @@ -233,7 +232,6 @@ | ||
| 233 | 232 | remoteUrl, |
| 234 | 233 | onShowConfigSelector, |
| 235 | 234 | exit, |
| 236 | - setChatHistory, | |
| 237 | 235 | }: HandleSpecialCommandsOptions): Promise<boolean> { |
| 238 | 236 | const trimmedMessage = message.trim(); |
| 239 | 237 | |
| @@ -246,7 +244,7 @@ | ||
| 246 | 244 | // Handle /exit command in remote mode |
| 247 | 245 | if (isRemoteMode && remoteUrl && trimmedMessage === "/exit") { |
| 248 | 246 | const { handleRemoteExit } = await import("./useChat.remote.helpers.js"); |
| 249 | - await handleRemoteExit(remoteUrl, setChatHistory, exit); | |
| 247 | + await handleRemoteExit(remoteUrl, exit); | |
| 250 | 248 | return true; |
| 251 | 249 | } |
| 252 | 250 |
modified extensions/cli/src/ui/hooks/useChat.remote.helpers.ts +50 −82
| @@ -1,10 +1,19 @@ | ||
| 1 | 1 | import type { ChatHistoryItem } from "core/index.js"; |
| 2 | 2 | |
| 3 | +import { services } from "../../services/index.js"; | |
| 3 | 4 | import { posthogService } from "../../telemetry/posthogService.js"; |
| 4 | 5 | import { logger } from "../../util/logger.js"; |
| 5 | 6 | |
| 6 | 7 | import { RemoteServerState } from "./useChat.types.js"; |
| 7 | 8 | |
| 9 | +function historiesEqual(a: ChatHistoryItem[], b: ChatHistoryItem[]): boolean { | |
| 10 | + if (a.length !== b.length) return false; | |
| 11 | + for (let i = 0; i < a.length; i++) { | |
| 12 | + if (JSON.stringify(a[i]) !== JSON.stringify(b[i])) return false; | |
| 13 | + } | |
| 14 | + return true; | |
| 15 | +} | |
| 16 | + | |
| 8 | 17 | /** |
| 9 | 18 | * Poll remote server for state updates |
| 10 | 19 | */ |
| @@ -25,7 +34,6 @@ | ||
| 25 | 34 | |
| 26 | 35 | interface SetupRemotePollingOptions { |
| 27 | 36 | remoteUrl: string; |
| 28 | - setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>; | |
| 29 | 37 | setIsWaitingForResponse: React.Dispatch<React.SetStateAction<boolean>>; |
| 30 | 38 | responseStartTime: number | null; |
| 31 | 39 | setResponseStartTime: React.Dispatch<React.SetStateAction<number | null>>; |
| @@ -36,7 +44,6 @@ | ||
| 36 | 44 | */ |
| 37 | 45 | export function setupRemotePolling({ |
| 38 | 46 | remoteUrl, |
| 39 | - setChatHistory, | |
| 40 | 47 | setIsWaitingForResponse, |
| 41 | 48 | responseStartTime, |
| 42 | 49 | setResponseStartTime, |
| @@ -54,7 +61,6 @@ | ||
| 54 | 61 | if (state && isMounted) { |
| 55 | 62 | updateStateFromRemote({ |
| 56 | 63 | state, |
| 57 | - setChatHistory, | |
| 58 | 64 | setIsWaitingForResponse, |
| 59 | 65 | responseStartTime, |
| 60 | 66 | setResponseStartTime, |
| @@ -81,7 +87,6 @@ | ||
| 81 | 87 | |
| 82 | 88 | interface UpdateStateFromRemoteOptions { |
| 83 | 89 | state: RemoteServerState; |
| 84 | - setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>; | |
| 85 | 90 | setIsWaitingForResponse: React.Dispatch<React.SetStateAction<boolean>>; |
| 86 | 91 | responseStartTime: number | null; |
| 87 | 92 | setResponseStartTime: React.Dispatch<React.SetStateAction<number | null>>; |
| @@ -92,37 +97,26 @@ | ||
| 92 | 97 | */ |
| 93 | 98 | function updateStateFromRemote({ |
| 94 | 99 | state, |
| 95 | - setChatHistory, | |
| 96 | 100 | setIsWaitingForResponse, |
| 97 | 101 | responseStartTime, |
| 98 | 102 | setResponseStartTime, |
| 99 | 103 | }: UpdateStateFromRemoteOptions): void { |
| 100 | 104 | // Update chat history from server - now using session.history directly |
| 101 | 105 | if (state.session && state.session.history) { |
| 102 | - setChatHistory((prevHistory) => { | |
| 103 | - // Use session history directly - it already has the correct type | |
| 104 | - const newHistory = state.session.history; | |
| 105 | - | |
| 106 | - // Quick length check first | |
| 107 | - if (prevHistory.length !== newHistory.length) { | |
| 108 | - return newHistory; | |
| 109 | - } | |
| 110 | - | |
| 111 | - // Deep comparison - check if content actually changed | |
| 112 | - const hasChanged = newHistory.some((item, index) => { | |
| 113 | - const prevItem = prevHistory[index]; | |
| 114 | - return ( | |
| 115 | - !prevItem || | |
| 116 | - prevItem.message.role !== item.message.role || | |
| 117 | - prevItem.message.content !== item.message.content || | |
| 118 | - JSON.stringify(prevItem.toolCallStates) !== | |
| 119 | - JSON.stringify(item.toolCallStates) | |
| 120 | - ); | |
| 121 | - }); | |
| 122 | - | |
| 123 | - // Only update if there are actual changes | |
| 124 | - return hasChanged ? newHistory : prevHistory; | |
| 125 | - }); | |
| 106 | + const newHistory = state.session.history as ChatHistoryItem[]; | |
| 107 | + // Let ChatHistoryService own the history and emit updates to UI | |
| 108 | + if (!services.chatHistory.isRemoteMode()) { | |
| 109 | + services.chatHistory.setRemoteMode(true); | |
| 110 | + } | |
| 111 | + // Avoid redundant updates: only set when history actually changed | |
| 112 | + try { | |
| 113 | + const current = services.chatHistory.getHistory(); | |
| 114 | + const changed = !historiesEqual(current, newHistory); | |
| 115 | + if (changed) services.chatHistory.setHistory(newHistory); | |
| 116 | + } catch { | |
| 117 | + // As a fallback, attempt to set history (service may handle no-op) | |
| 118 | + services.chatHistory.setHistory(newHistory); | |
| 119 | + } | |
| 126 | 120 | } |
| 127 | 121 | |
| 128 | 122 | // Update processing state |
| @@ -139,7 +133,6 @@ | ||
| 139 | 133 | */ |
| 140 | 134 | export async function handleRemoteExit( |
| 141 | 135 | remoteUrl: string, |
| 142 | - setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>, | |
| 143 | 136 | exit: () => void, |
| 144 | 137 | ): Promise<void> { |
| 145 | 138 | posthogService.capture("useSlashCommand", { |
| @@ -152,50 +145,36 @@ | ||
| 152 | 145 | }); |
| 153 | 146 | |
| 154 | 147 | if (response.ok) { |
| 155 | - setChatHistory((prev) => [ | |
| 156 | - ...prev, | |
| 157 | - { | |
| 158 | - message: { | |
| 159 | - role: "system", | |
| 160 | - content: "Remote environment is shutting down...", | |
| 161 | - }, | |
| 162 | - contextItems: [], | |
| 163 | - }, | |
| 164 | - ]); | |
| 148 | + try { | |
| 149 | + services.chatHistory.addSystemMessage( | |
| 150 | + "Remote environment is shutting down...", | |
| 151 | + ); | |
| 152 | + } catch (err) { | |
| 153 | + logger.error("Failed to add system message", err); | |
| 154 | + } | |
| 165 | 155 | setTimeout(() => exit(), 1000); |
| 166 | 156 | } else { |
| 167 | 157 | const text = await response.text(); |
| 168 | 158 | logger.error("Remote shutdown failed:", text); |
| 169 | - setChatHistory((prev) => [ | |
| 170 | - ...prev, | |
| 171 | - { | |
| 172 | - message: { | |
| 173 | - role: "system", | |
| 174 | - content: "Failed to shutdown remote environment", | |
| 175 | - }, | |
| 176 | - contextItems: [], | |
| 177 | - }, | |
| 178 | - ]); | |
| 159 | + try { | |
| 160 | + services.chatHistory.addSystemMessage( | |
| 161 | + "Failed to shutdown remote environment", | |
| 162 | + ); | |
| 163 | + } catch {} | |
| 179 | 164 | } |
| 180 | 165 | } catch (error) { |
| 181 | 166 | logger.error("Failed to send exit request to remote server:", error); |
| 182 | - setChatHistory((prev) => [ | |
| 183 | - ...prev, | |
| 184 | - { | |
| 185 | - message: { | |
| 186 | - role: "system", | |
| 187 | - content: "Error: Failed to connect to remote server for shutdown", | |
| 188 | - }, | |
| 189 | - contextItems: [], | |
| 190 | - }, | |
| 191 | - ]); | |
| 167 | + try { | |
| 168 | + services.chatHistory.addSystemMessage( | |
| 169 | + "Error: Failed to connect to remote server for shutdown", | |
| 170 | + ); | |
| 171 | + } catch {} | |
| 192 | 172 | } |
| 193 | 173 | } |
| 194 | 174 | |
| 195 | 175 | interface HandleRemoteMessageOptions { |
| 196 | 176 | remoteUrl: string; |
| 197 | 177 | messageContent: string; |
| 198 | - setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>; | |
| 199 | 178 | } |
| 200 | 179 | |
| 201 | 180 | /** |
| @@ -204,7 +183,6 @@ | ||
| 204 | 183 | export async function handleRemoteMessage({ |
| 205 | 184 | remoteUrl, |
| 206 | 185 | messageContent, |
| 207 | - setChatHistory, | |
| 208 | 186 | }: HandleRemoteMessageOptions): Promise<void> { |
| 209 | 187 | try { |
| 210 | 188 | const response = await fetch(`${remoteUrl}/message`, { |
| @@ -217,29 +195,19 @@ | ||
| 217 | 195 | |
| 218 | 196 | if (!response.ok) { |
| 219 | 197 | const error = await response.json(); |
| 220 | - setChatHistory((prev) => [ | |
| 221 | - ...prev, | |
| 222 | - { | |
| 223 | - message: { | |
| 224 | - role: "system", | |
| 225 | - content: `Error: ${error.error || "Failed to send message"}`, | |
| 226 | - }, | |
| 227 | - contextItems: [], | |
| 228 | - }, | |
| 229 | - ]); | |
| 198 | + try { | |
| 199 | + services.chatHistory.addSystemMessage( | |
| 200 | + `Error: ${error.error || "Failed to send message"}`, | |
| 201 | + ); | |
| 202 | + } catch {} | |
| 230 | 203 | } |
| 231 | 204 | // State will be updated by polling |
| 232 | 205 | } catch (error) { |
| 233 | 206 | logger.error("Failed to send message to remote server:", error); |
| 234 | - setChatHistory((prev) => [ | |
| 235 | - ...prev, | |
| 236 | - { | |
| 237 | - message: { | |
| 238 | - role: "system", | |
| 239 | - content: `Error: Failed to connect to remote server`, | |
| 240 | - }, | |
| 241 | - contextItems: [], | |
| 242 | - }, | |
| 243 | - ]); | |
| 207 | + try { | |
| 208 | + services.chatHistory.addSystemMessage( | |
| 209 | + "Error: Failed to connect to remote server", | |
| 210 | + ); | |
| 211 | + } catch {} | |
| 244 | 212 | } |
| 245 | 213 | } |
modified extensions/cli/src/ui/hooks/useChat.stream.helpers.ts +52 −19
| @@ -1,5 +1,8 @@ | ||
| 1 | 1 | import type { ChatHistoryItem, ToolCallState, ToolStatus } from "core/index.js"; |
| 2 | 2 | |
| 3 | +import { logger } from "src/util/logger.js"; | |
| 4 | + | |
| 5 | +import { services } from "../../services/index.js"; | |
| 3 | 6 | import { getCurrentSession, updateSessionTitle } from "../../session.js"; |
| 4 | 7 | |
| 5 | 8 | import { generateSessionTitle } from "./useChat.helpers.js"; |
| @@ -23,18 +26,27 @@ | ||
| 23 | 26 | onContent: (_: string) => {}, |
| 24 | 27 | |
| 25 | 28 | onContentComplete: async (content: string) => { |
| 26 | - setChatHistory((prev) => [ | |
| 27 | - ...prev, | |
| 28 | - { | |
| 29 | - contextItems: [], | |
| 30 | - message: { | |
| 31 | - role: "assistant", | |
| 32 | - content: content, | |
| 33 | - isStreaming: false, | |
| 34 | - }, | |
| 35 | - }, | |
| 36 | - ]); | |
| 37 | - | |
| 29 | + // Do not add assistant messages via service; handleToolCalls is the single writer | |
| 30 | + // For environments where the service isn't ready (unit tests), update local state only | |
| 31 | + try { | |
| 32 | + const svc = services.chatHistory; | |
| 33 | + const useService = typeof svc?.isReady === "function" && svc.isReady(); | |
| 34 | + if (!useService && content) { | |
| 35 | + setChatHistory((prev) => [ | |
| 36 | + ...prev, | |
| 37 | + { | |
| 38 | + contextItems: [], | |
| 39 | + message: { | |
| 40 | + role: "assistant", | |
| 41 | + content: content, | |
| 42 | + isStreaming: false, | |
| 43 | + }, | |
| 44 | + }, | |
| 45 | + ]); | |
| 46 | + } | |
| 47 | + } catch (error) { | |
| 48 | + logger.error("Failed to update chat history", { error }); | |
| 49 | + } | |
| 38 | 50 | // Generate session title after first assistant response |
| 39 | 51 | if (content && llmApi && model) { |
| 40 | 52 | const currentSession = getCurrentSession(); |
| @@ -52,10 +64,15 @@ | ||
| 52 | 64 | }, |
| 53 | 65 | |
| 54 | 66 | onToolStart: (toolName: string, toolArgs?: any) => { |
| 67 | + // When ChatHistoryService is ready, let handleToolCalls add entries | |
| 68 | + const svc = services.chatHistory; | |
| 69 | + const useService = typeof svc?.isReady === "function" && svc.isReady(); | |
| 70 | + if (useService) return; | |
| 71 | + | |
| 72 | + // Fallback (service not ready): create a local assistant message representing the tool call | |
| 55 | 73 | setChatHistory((prev) => { |
| 56 | 74 | const newHistory = [...prev]; |
| 57 | 75 | |
| 58 | - // Always create a new assistant message for each tool call | |
| 59 | 76 | const toolCallId = `tool_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`; |
| 60 | 77 | const toolCallState: ToolCallState = { |
| 61 | 78 | toolCallId: toolCallId, |
| @@ -95,17 +112,22 @@ | ||
| 95 | 112 | }, |
| 96 | 113 | |
| 97 | 114 | onToolResult: (result: string, toolName: string, status: ToolStatus) => { |
| 115 | + // When service is ready, it updates tool results; avoid duplicate local updates | |
| 116 | + const svc = services.chatHistory; | |
| 117 | + const useService = typeof svc?.isReady === "function" && svc.isReady(); | |
| 118 | + if (useService) return; | |
| 119 | + | |
| 120 | + // Fallback (service not ready): update local UI-only state | |
| 98 | 121 | setChatHistory((prev) => { |
| 99 | 122 | const newHistory = [...prev]; |
| 100 | 123 | |
| 101 | - // Find the tool call state and update it | |
| 102 | 124 | for (let i = newHistory.length - 1; i >= 0; i--) { |
| 103 | 125 | const item = newHistory[i]; |
| 104 | 126 | if (item.toolCallStates) { |
| 105 | 127 | const toolState = item.toolCallStates.find( |
| 106 | 128 | (ts) => |
| 107 | 129 | ts.toolCall.function.name === toolName && |
| 108 | - ts.status === "calling", | |
| 130 | + (ts.status === "calling" || ts.status === "generated"), | |
| 109 | 131 | ); |
| 110 | 132 | |
| 111 | 133 | if (toolState) { |
| @@ -127,10 +149,14 @@ | ||
| 127 | 149 | }, |
| 128 | 150 | |
| 129 | 151 | onToolError: (error: string, toolName?: string) => { |
| 152 | + // When service is ready, handleToolCalls adds error entries; avoid duplicate local updates | |
| 153 | + const svc = services.chatHistory; | |
| 154 | + const useService = typeof svc?.isReady === "function" && svc.isReady(); | |
| 155 | + if (useService) return; | |
| 156 | + | |
| 130 | 157 | setChatHistory((prev) => { |
| 131 | 158 | const newHistory = [...prev]; |
| 132 | 159 | |
| 133 | - // Find the tool call state and mark it as errored | |
| 134 | 160 | if (toolName) { |
| 135 | 161 | for (let i = newHistory.length - 1; i >= 0; i--) { |
| 136 | 162 | const item = newHistory[i]; |
| @@ -138,7 +164,7 @@ | ||
| 138 | 164 | const toolState = item.toolCallStates.find( |
| 139 | 165 | (ts) => |
| 140 | 166 | ts.toolCall.function.name === toolName && |
| 141 | - ts.status === "calling", | |
| 167 | + (ts.status === "calling" || ts.status === "generated"), | |
| 142 | 168 | ); |
| 143 | 169 | |
| 144 | 170 | if (toolState) { |
| @@ -184,6 +210,14 @@ | ||
| 184 | 210 | }, |
| 185 | 211 | |
| 186 | 212 | onSystemMessage: (message: string) => { |
| 213 | + try { | |
| 214 | + const svc = services.chatHistory; | |
| 215 | + if (typeof svc?.isReady === "function" && svc.isReady()) { | |
| 216 | + svc.addSystemMessage(message); | |
| 217 | + return; | |
| 218 | + } | |
| 219 | + } catch {} | |
| 220 | + // Fallback to local state if service unavailable | |
| 187 | 221 | setChatHistory((prev) => [ |
| 188 | 222 | ...prev, |
| 189 | 223 | { |
| @@ -241,8 +275,7 @@ | ||
| 241 | 275 | streamCallbacks, |
| 242 | 276 | ); |
| 243 | 277 | |
| 244 | - // streamChatResponse modifies the array in place | |
| 245 | - // The new messages are already in historyForLLM | |
| 278 | + // Service-driven streaming; history updates occur via ChatHistoryService | |
| 246 | 279 | } else { |
| 247 | 280 | await streamChatResponse( |
| 248 | 281 | chatHistory, |
modified extensions/cli/src/ui/hooks/useChat.ts +63 −12
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | import type { ChatHistoryItem, Session } from "core/index.js"; |
| 2 | 2 | import { useApp } from "ink"; |
| 3 | -import { useEffect, useState } from "react"; | |
| 3 | +import { useEffect, useRef, useState } from "react"; | |
| 4 | 4 | |
| 5 | 5 | import { findCompactionIndex } from "../../compaction.js"; |
| 6 | 6 | import { toolPermissionManager } from "../../permissions/permissionManager.js"; |
| @@ -46,6 +46,7 @@ | ||
| 46 | 46 | llmApi, |
| 47 | 47 | initialPrompt, |
| 48 | 48 | resume, |
| 49 | + fork, | |
| 49 | 50 | additionalRules, |
| 50 | 51 | additionalPrompts, |
| 51 | 52 | onShowConfigSelector, |
| @@ -59,6 +60,9 @@ | ||
| 59 | 60 | }: UseChatProps) { |
| 60 | 61 | const { exit } = useApp(); |
| 61 | 62 | |
| 63 | + // Track service subscription | |
| 64 | + const serviceListenerCleanupRef = useRef<null | (() => void)>(null); | |
| 65 | + | |
| 62 | 66 | // Store the current session |
| 63 | 67 | const [currentSession, setCurrentSession] = useState<Session>(() => { |
| 64 | 68 | // In remote mode, start with empty session (will be populated by polling) |
| @@ -66,6 +70,17 @@ | ||
| 66 | 70 | return createSession([]); |
| 67 | 71 | } |
| 68 | 72 | |
| 73 | + // Fork from an existing session if fork flag is used | |
| 74 | + if (fork) { | |
| 75 | + const { loadSessionById, startNewSession } = require("../../session.js"); | |
| 76 | + const sessionToFork = loadSessionById(fork); | |
| 77 | + if (sessionToFork) { | |
| 78 | + return startNewSession(sessionToFork.history); | |
| 79 | + } | |
| 80 | + // If session not found, create a new empty session | |
| 81 | + return createSession([]); | |
| 82 | + } | |
| 83 | + | |
| 69 | 84 | // Load previous session if resume flag is used |
| 70 | 85 | if (resume) { |
| 71 | 86 | const savedSession = loadSession(); |
| @@ -78,9 +93,45 @@ | ||
| 78 | 93 | return createSession([]); |
| 79 | 94 | }); |
| 80 | 95 | |
| 81 | - const [chatHistory, setChatHistory] = useState<ChatHistoryItem[]>( | |
| 82 | - () => currentSession.history, | |
| 96 | + // Local view of history driven solely by ChatHistoryService | |
| 97 | + const [chatHistory, setChatHistoryView] = useState<ChatHistoryItem[]>(() => | |
| 98 | + services.chatHistory?.isReady() | |
| 99 | + ? services.chatHistory.getHistory() | |
| 100 | + : currentSession.history, | |
| 83 | 101 | ); |
| 102 | + // Proxy setter: apply changes to ChatHistoryService (single source of truth) | |
| 103 | + const setChatHistory: React.Dispatch< | |
| 104 | + React.SetStateAction<ChatHistoryItem[]> | |
| 105 | + > = (value) => { | |
| 106 | + const svc = services.chatHistory; | |
| 107 | + const current = svc.getHistory(); | |
| 108 | + const next = typeof value === "function" ? (value as any)(current) : value; | |
| 109 | + svc.setHistory(next); | |
| 110 | + }; | |
| 111 | + | |
| 112 | + // Initialize ChatHistoryService and subscribe to updates | |
| 113 | + useEffect(() => { | |
| 114 | + const svc = services.chatHistory; | |
| 115 | + svc | |
| 116 | + .initialize(currentSession, isRemoteMode) | |
| 117 | + .then(() => { | |
| 118 | + setChatHistoryView(svc.getHistory()); | |
| 119 | + const listener = () => { | |
| 120 | + setChatHistoryView(svc.getHistory()); | |
| 121 | + }; | |
| 122 | + svc.on("stateChanged", listener); | |
| 123 | + serviceListenerCleanupRef.current = () => | |
| 124 | + svc.off("stateChanged", listener); | |
| 125 | + }) | |
| 126 | + .catch((error) => { | |
| 127 | + logger.error("Failed to initialize ChatHistoryService", { error }); | |
| 128 | + }); | |
| 129 | + | |
| 130 | + return () => { | |
| 131 | + serviceListenerCleanupRef.current?.(); | |
| 132 | + serviceListenerCleanupRef.current = null; | |
| 133 | + }; | |
| 134 | + }, []); | |
| 84 | 135 | |
| 85 | 136 | const [isWaitingForResponse, setIsWaitingForResponse] = useState(false); |
| 86 | 137 | const [responseStartTime, setResponseStartTime] = useState<number | null>( |
| @@ -91,8 +142,11 @@ | ||
| 91 | 142 | useState<AbortController | null>(null); |
| 92 | 143 | const [isChatHistoryInitialized, setIsChatHistoryInitialized] = useState( |
| 93 | 144 | // If we're resuming and found a saved session, we're already initialized |
| 145 | + // If we're forking and found a session to fork from, we're already initialized | |
| 94 | 146 | // If we're in remote mode, we're initialized (will be populated by polling) |
| 95 | - isRemoteMode || (resume && currentSession.history.length > 0), | |
| 147 | + isRemoteMode || | |
| 148 | + (resume && currentSession.history.length > 0) || | |
| 149 | + (fork && currentSession.history.length > 0), | |
| 96 | 150 | ); |
| 97 | 151 | |
| 98 | 152 | // Capture initial rules to prevent re-initialization when rules change |
| @@ -101,8 +155,8 @@ | ||
| 101 | 155 | const [activePermissionRequest, setActivePermissionRequest] = |
| 102 | 156 | useState<ActivePermissionRequest | null>(null); |
| 103 | 157 | const [compactionIndex, setCompactionIndex] = useState<number | null>(() => { |
| 104 | - // When resuming, check for compaction markers in the loaded history | |
| 105 | - if (resume && currentSession.history.length > 0) { | |
| 158 | + // When resuming or forking, check for compaction markers in the loaded history | |
| 159 | + if ((resume || fork) && currentSession.history.length > 0) { | |
| 106 | 160 | return findCompactionIndex(currentSession.history); |
| 107 | 161 | } |
| 108 | 162 | return null; |
| @@ -126,7 +180,6 @@ | ||
| 126 | 180 | |
| 127 | 181 | return setupRemotePolling({ |
| 128 | 182 | remoteUrl, |
| 129 | - setChatHistory, | |
| 130 | 183 | setIsWaitingForResponse, |
| 131 | 184 | responseStartTime, |
| 132 | 185 | setResponseStartTime, |
| @@ -204,7 +257,7 @@ | ||
| 204 | 257 | |
| 205 | 258 | try { |
| 206 | 259 | const streamCallbacks = createStreamCallbacks({ |
| 207 | - setChatHistory, | |
| 260 | + setChatHistory: setChatHistory, | |
| 208 | 261 | setActivePermissionRequest, |
| 209 | 262 | llmApi, |
| 210 | 263 | model, |
| @@ -366,7 +419,6 @@ | ||
| 366 | 419 | remoteUrl, |
| 367 | 420 | onShowConfigSelector, |
| 368 | 421 | exit, |
| 369 | - setChatHistory, | |
| 370 | 422 | }); |
| 371 | 423 | |
| 372 | 424 | if (handled) return; |
| @@ -406,7 +458,6 @@ | ||
| 406 | 458 | await handleRemoteMessage({ |
| 407 | 459 | remoteUrl, |
| 408 | 460 | messageContent: messageContentString, |
| 409 | - setChatHistory, | |
| 410 | 461 | }); |
| 411 | 462 | return; |
| 412 | 463 | } |
| @@ -418,7 +469,7 @@ | ||
| 418 | 469 | model, |
| 419 | 470 | llmApi, |
| 420 | 471 | compactionIndex, |
| 421 | - setChatHistory, | |
| 472 | + setChatHistory: setChatHistory, | |
| 422 | 473 | setCompactionIndex, |
| 423 | 474 | }); |
| 424 | 475 | |
| @@ -549,7 +600,7 @@ | ||
| 549 | 600 | |
| 550 | 601 | return { |
| 551 | 602 | chatHistory, |
| 552 | - setChatHistory, | |
| 603 | + setChatHistory: setChatHistory, | |
| 553 | 604 | isWaitingForResponse, |
| 554 | 605 | responseStartTime, |
| 555 | 606 | inputMode, |
modified extensions/cli/src/ui/hooks/useChat.types.ts +1 −0
| @@ -10,6 +10,7 @@ | ||
| 10 | 10 | llmApi?: BaseLlmApi; |
| 11 | 11 | initialPrompt?: string; |
| 12 | 12 | resume?: boolean; |
| 13 | + fork?: string; | |
| 13 | 14 | additionalRules?: string[]; |
| 14 | 15 | additionalPrompts?: string[]; |
| 15 | 16 | onShowConfigSelector: () => void; |
modified extensions/cli/src/ui/hooks/useUserInput.ts +2 −2
| @@ -194,7 +194,7 @@ | ||
| 194 | 194 | |
| 195 | 195 | export function updateTextBufferState(options: TextBufferStateOptions) { |
| 196 | 196 | const { |
| 197 | - handled, | |
| 197 | + handled: _handled, | |
| 198 | 198 | textBuffer, |
| 199 | 199 | setInputText, |
| 200 | 200 | setCursorPosition, |
| @@ -204,7 +204,7 @@ | ||
| 204 | 204 | } = options; |
| 205 | 205 | |
| 206 | 206 | // Skip state updates during rapid input mode to avoid conflicts with timer-based updates |
| 207 | - if (handled && !textBuffer.isInRapidInputMode()) { | |
| 207 | + if (!textBuffer.isInRapidInputMode()) { | |
| 208 | 208 | const newText = textBuffer.text; |
| 209 | 209 | const newCursor = textBuffer.cursor; |
| 210 | 210 | setInputText(newText); |
modified extensions/cli/src/ui/index.ts +3 −0
| @@ -12,6 +12,7 @@ | ||
| 12 | 12 | interface StartTUIChatOptions { |
| 13 | 13 | initialPrompt?: string; |
| 14 | 14 | resume?: boolean; |
| 15 | + fork?: string; | |
| 15 | 16 | config?: string; |
| 16 | 17 | org?: string; |
| 17 | 18 | rule?: string[]; |
| @@ -31,6 +32,7 @@ | ||
| 31 | 32 | const { |
| 32 | 33 | initialPrompt, |
| 33 | 34 | resume, |
| 35 | + fork, | |
| 34 | 36 | config, |
| 35 | 37 | org, |
| 36 | 38 | rule, |
| @@ -63,6 +65,7 @@ | ||
| 63 | 65 | configPath: config, |
| 64 | 66 | initialPrompt, |
| 65 | 67 | resume, |
| 68 | + fork, | |
| 66 | 69 | additionalRules: rule, |
| 67 | 70 | additionalPrompts: prompt, |
| 68 | 71 | }), |
deleted extensions/cli/src/ui/types.ts +0 −2
| @@ -1,2 +0,0 @@ | ||
| 1 | -// This file has been intentionally left empty after migration to ChatHistoryItem | |
| 2 | -// All types have been migrated to use @continuedev/core types |
modified packages/openai-adapters/package-lock.json +0 −0
Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.