Elffuss BraidHub

kikocis/continue public

Merge pull request #7512 from continuedev/fix-duplicate-chat-history-state

refactor: duplicate chat history state
Changeset937b30c7b45d8666fe9b171d9fcebf28f3533f8998cd96c896ea74426ea4084b
AuthorNate Sesti <33237525+sestinj@users.noreply.github.com> · 2025-09-01 15:45 -07:00
CommitterGitHub <noreply@github.com> · 2025-09-01 15:45 -07:00
Parents4409bbdbfe8e, 6ea18b3a4328

Browse the files at this changeset

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 @@
9797 "eslint-plugin-import": "^2.32.0",
9898 "eslint-plugin-unused-imports": "^4.1.4",
9999 "execa": "^9.6.0",
100+ "clipboardy": "^4.0.0",
100101 "express": "^5.1.0",
101102 "glob": "^11.0.3",
102103 "gpt-tokenizer": "^3.0.1",
modified extensions/cli/src/args.ts +8 −0
@@ -3,6 +3,7 @@
33 organizationSlug?: string; // Organization slug to use for this session
44 prompt?: string; // Optional prompt argument
55 resume?: boolean; // Resume from last session
6+ fork?: string; // Fork from an existing session ID
67 readonly?: boolean; // Start in plan mode (backward compatibility)
78 rules?: string[]; // Array of rule specifications
89 mcps?: string[]; // Array of MCP server slugs from the hub
@@ -71,6 +72,12 @@
7172 result.readonly = true;
7273 }
7374
75+ // Parse fork flag
76+ const forkValue = extractSingleFlag(args, "--fork");
77+ if (forkValue) {
78+ result.fork = forkValue;
79+ }
80+
7481 // Parse single-value flags
7582 const formatValue = extractSingleFlag(args, "--format");
7683 if (formatValue === "json") {
@@ -124,6 +131,7 @@
124131 "--model",
125132 "--prompt",
126133 "--format",
134+ "--fork",
127135 ];
128136 const nonFlagArgs = args.filter((arg, index) => {
129137 if (arg.startsWith("--") || arg === "-p") return false;
modified extensions/cli/src/commands/chat.ts +62 −51
@@ -4,17 +4,13 @@
44 import { ChatDescriber } from "core/util/chatDescriber.js";
55 import * as readlineSync from "readline-sync";
66
7-import {
8- compactChatHistory,
9- findCompactionIndex,
10- getHistoryForLLM,
11-} from "../compaction.js";
7+import { compactChatHistory, findCompactionIndex } from "../compaction.js";
128 import { processCommandFlags } from "../flags/flagProcessor.js";
139 import { safeStdout } from "../init.js";
1410 import { configureLogger } from "../logger.js";
1511 import * as logging from "../logging.js";
1612 import { sentryService } from "../sentry.js";
17-import { initializeServices } from "../services/index.js";
13+import { initializeServices, services } from "../services/index.js";
1814 import { serviceContainer } from "../services/ServiceContainer.js";
1915 import { ModelServiceState, SERVICE_NAMES } from "../services/types.js";
2016 import {
@@ -80,6 +76,7 @@
8076 export interface ChatOptions extends ExtendedCommandOptions {
8177 headless?: boolean;
8278 resume?: boolean;
79+ fork?: string; // Fork from an existing session ID
8380 format?: "json"; // Output format for headless mode
8481 silent?: boolean; // Strip <think></think> tags and excess whitespace
8582 }
@@ -89,6 +86,20 @@
8986 ): Promise<ChatHistoryItem[]> {
9087 let session: Session | null = null;
9188
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+
92103 // Load previous session if --resume flag is used
93104 if (options.resume) {
94105 session = loadSession();
@@ -115,21 +126,21 @@
115126 }
116127
117128 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+ );
126137
127138 if (isHeadless) {
128139 safeStdout(
129140 JSON.stringify({
130141 status: "success",
131142 message: "Chat history compacted",
132- historyLength: chatHistory.length,
143+ historyLength: services.chatHistory.getHistory().length,
133144 }) + "\n",
134145 );
135146 } else {
@@ -176,7 +187,7 @@
176187 message: "Auto-compacting triggered",
177188 contextUsage:
178189 calculateContextUsagePercentage(
179- countChatHistoryTokens(chatHistory),
190+ countChatHistoryTokens(services.chatHistory.getHistory()),
180191 model,
181192 ) + "%",
182193 }) + "\n",
@@ -186,11 +197,11 @@
186197 if (!isHeadless) {
187198 console.info(chalk.green(message));
188199 } else if (format === "json") {
200+ // Omit history length here; service updates occur after compaction completes
189201 safeStdout(
190202 JSON.stringify({
191203 status: "success",
192204 message: "Auto-compacted successfully",
193- historyLength: chatHistory.length,
194205 }) + "\n",
195206 );
196207 }
@@ -210,15 +221,19 @@
210221 },
211222 };
212223
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+ );
218234
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);
222237
223238 return result.compactionIndex;
224239 }
@@ -286,7 +301,7 @@
286301 telemetryService.logUserPrompt(userInput.length, userInput);
287302
288303 // Check if auto-compacting is needed BEFORE adding user message
289- if (shouldAutoCompact(chatHistory, model)) {
304+ if (shouldAutoCompact(services.chatHistory.getHistory(), model)) {
290305 const newIndex = await handleAutoCompaction(
291306 chatHistory,
292307 model,
@@ -296,17 +311,12 @@
296311 );
297312 if (newIndex !== null) {
298313 compactionIndex = newIndex;
299- // Replace chatHistory with compacted version
300- chatHistory.length = 0;
301- chatHistory.push(...chatHistory);
314+ // Service already updated in handleAutoCompaction via setHistory
302315 }
303316 }
304317
305318 // 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);
310320
311321 // Get AI response with potential tool usage
312322 if (!isHeadless) {
@@ -316,12 +326,12 @@
316326 try {
317327 const abortController = new AbortController();
318328
319- // Handle compaction properly - streamChatResponse modifies the array in place
329+ // Service-driven streaming; history updates occur via ChatHistoryService
320330 let finalResponse;
321331 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);
325335
326336 finalResponse = await streamChatResponse(
327337 historyForLLM,
@@ -329,19 +339,14 @@
329339 llmApi,
330340 abortController,
331341 );
332-
333- // Append any new messages (assistant/tool) that were added by streamChatResponse
334- const newMessages = historyForLLM.slice(originalLength);
335- chatHistory.push(...newMessages);
336342 } else {
337- // No compaction - just pass the full history directly
343+ // No compaction - get full history from service
338344 finalResponse = await streamChatResponse(
339- chatHistory,
345+ services.chatHistory.getHistory(),
340346 model,
341347 llmApi,
342348 abortController,
343349 );
344- // No need to sync back - streamChatResponse modifies chatHistory in place
345350 }
346351
347352 // Generate session title after first assistant response
@@ -368,7 +373,7 @@
368373 }
369374
370375 // Save session after each successful response
371- updateSessionHistory(chatHistory);
376+ updateSessionHistory(services.chatHistory.getHistory());
372377 } catch (e: any) {
373378 const error = e instanceof Error ? e : new Error(String(e));
374379
@@ -381,11 +386,17 @@
381386 sentryService.captureException(error, {
382387 context: "chat_response",
383388 isHeadless,
384- chatHistoryLength: chatHistory.length,
389+ chatHistoryLength: services.chatHistory.getHistory().length,
385390 });
386391 if (!isHeadless) {
387392 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+ ),
389400 );
390401 }
391402 }
@@ -414,12 +425,11 @@
414425 throw new Error("No models were found.");
415426 }
416427
417- // Initialize chat history
428+ // Initialize service-driven history (resume if requested)
418429 const chatHistory = await initializeChatHistory(options);
419-
420- // Track compaction index if resuming with compacted history
421430 let compactionIndex: number | null = null;
422- if (options.resume) {
431+ if (options.resume || options.fork) {
432+ services.chatHistory.setHistory(chatHistory);
423433 compactionIndex = findCompactionIndex(chatHistory);
424434 }
425435
@@ -502,6 +512,7 @@
502512 const tuiOptions: any = {
503513 initialPrompt: prompt,
504514 resume: options.resume,
515+ fork: options.fork,
505516 config: options.config,
506517 org: options.org,
507518 rule: options.rule,
modified extensions/cli/src/commands/commands.ts +5 −0
@@ -76,6 +76,11 @@
7676 description: "Resume a previous chat session",
7777 category: "system",
7878 },
79+ {
80+ name: "fork",
81+ description: "Start a forked chat session from the current history",
82+ category: "system",
83+ },
7984 {
8085 name: "exit",
8186 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";
22
3+import { services } from "../services/index.js";
34 import { streamChatResponse } from "../stream/streamChatResponse.js";
45 import { StreamCallbacks } from "../stream/streamChatResponse.types.js";
6+import { logger } from "../util/logger.js";
57
68 // Modified version of streamChatResponse that supports interruption
79 export async function streamChatResponseWithInterruption(
@@ -38,47 +40,11 @@
3840 // This callback is just for notification/UI updates
3941 // The tool call state is already created and added by handleToolCalls
4042 },
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
5945 },
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
8248 },
8349 onToolPermissionRequest: (
8450 toolName: string,
@@ -95,25 +61,33 @@
9561 toolCallPreview,
9662 };
9763
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+ }
10677
10778 // Don't wait here - the streamChatResponse will handle waiting
10879 },
10980 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+ }
11791 },
11892 };
11993
modified extensions/cli/src/commands/serve.ts +61 −23
@@ -12,13 +12,14 @@
1212 getService,
1313 initializeServices,
1414 SERVICE_NAMES,
15+ services,
1516 } from "../services/index.js";
1617 import {
1718 AuthServiceState,
1819 ConfigServiceState,
1920 ModelServiceState,
2021 } from "../services/types.js";
21-import { createSession, updateSessionHistory } from "../session.js";
22+import { createSession } from "../session.js";
2223 import { constructSystemMessage } from "../systemMessage.js";
2324 import { telemetryService } from "../telemetry/telemetryService.js";
2425 import { formatError } from "../util/formatError.js";
@@ -38,6 +39,7 @@
3839 port?: string;
3940 }
4041
42+// eslint-disable-next-line max-statements
4143 export async function serve(prompt?: string, options: ServeOptions = {}) {
4244 // Check if prompt should come from stdin instead of parameter
4345 let actualPrompt = prompt;
@@ -122,6 +124,13 @@
122124
123125 const session = createSession(initialHistory);
124126
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+
125134 // Initialize server state
126135 const state: ServerState = {
127136 session,
@@ -146,6 +155,14 @@
146155 // GET /state - Return the current state
147156 app.get("/state", (_req: Request, res: Response) => {
148157 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+ }
149166 res.json({
150167 session: state.session, // Return session directly instead of converting
151168 isProcessing: state.isProcessing,
@@ -328,6 +345,27 @@
328345 });
329346
330347 // 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+
331369 async function processMessages(state: ServerState, llmApi: any) {
332370 while (state.messageQueue.length > 0 && state.serverRunning) {
333371 const userMessage = state.messageQueue.shift()!;
@@ -335,11 +373,16 @@
335373 state.shouldInterrupt = false;
336374 state.lastActivity = Date.now();
337375
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+ }
343386
344387 try {
345388 // Create new abort controller for this response
@@ -353,31 +396,26 @@
353396 () => state.shouldInterrupt,
354397 );
355398
356- // Save session after successful response
357- updateSessionHistory(state.session.history);
399+ // No direct persistence here; ChatHistoryService handles persistence when appropriate
358400
359401 state.lastActivity = Date.now();
360402 } catch (e: any) {
361403 if (e.name === "AbortError") {
362404 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);
373407 } else {
374408 logger.error(`Error: ${formatError(e)}`);
375- // Add error message to chat history and display messages
409+ // Add error message via ChatHistoryService
376410 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+ }
381419 }
382420 } finally {
383421 state.currentAbortController = null;
modified extensions/cli/src/compaction.ts +1 −1
@@ -80,7 +80,7 @@
8080 historyForCompaction = [...historyToUse, compactionPrompt];
8181 }
8282
83- // Stream the compaction response
83+ // Stream the compaction response (service drives updates; this collects content locally)
8484 const controller = new AbortController();
8585
8686 let compactionContent = "";
modified extensions/cli/src/flags/flagValidator.ts +28 −0
@@ -16,6 +16,10 @@
1616 auto?: boolean;
1717 config?: string;
1818
19+ // Session flags
20+ resume?: boolean;
21+ fork?: string;
22+
1923 // Permission flags
2024 allow?: string[];
2125 ask?: string[];
@@ -101,6 +105,29 @@
101105 return errors;
102106 }
103107
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+
104131 /**
105132 * Validate config path exists (basic check)
106133 */
@@ -164,6 +191,7 @@
164191 validateSilentFlag,
165192 validateFormatValue,
166193 validateModeFlags,
194+ validateSessionFlags,
167195 validateConfigPath,
168196 validatePermissionFlags,
169197 ];
modified extensions/cli/src/index.ts +3 −0
@@ -64,6 +64,7 @@
6464 "Strip <think></think> tags and excess whitespace from output. Only works with -p/--print flag.",
6565 )
6666 .option("--resume", "Resume from last session")
67+ .option("--fork <sessionId>", "Fork from an existing session ID")
6768 .action(async (prompt, options) => {
6869 // Handle piped input - detect it early and decide on mode
6970 let stdinInput = null;
@@ -100,6 +101,8 @@
100101 readonly: options.readonly,
101102 auto: options.auto,
102103 config: options.config,
104+ resume: options.resume,
105+ fork: options.fork,
103106 allow: options.allow,
104107 ask: options.ask,
105108 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 @@
44
55 import { ApiClientService } from "./ApiClientService.js";
66 import { AuthService } from "./AuthService.js";
7+import { ChatHistoryService } from "./ChatHistoryService.js";
78 import { ConfigService } from "./ConfigService.js";
89 import { FileIndexService } from "./FileIndexService.js";
910 import { MCPService } from "./MCPService.js";
@@ -29,6 +30,7 @@
2930 const mcpService = new MCPService();
3031 const fileIndexService = new FileIndexService();
3132 const resourceMonitoringService = new ResourceMonitoringService();
33+const chatHistoryService = new ChatHistoryService();
3234
3335 /**
3436 * Initialize all services and register them with the service container
@@ -241,6 +243,12 @@
241243 [],
242244 );
243245
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+
244252 // Eagerly initialize all services to ensure they're ready when needed
245253 // This avoids race conditions and "service not ready" errors
246254 await serviceContainer.initializeAll();
@@ -284,6 +292,7 @@
284292 SERVICE_NAMES.MCP,
285293 SERVICE_NAMES.FILE_INDEX,
286294 SERVICE_NAMES.RESOURCE_MONITORING,
295+ SERVICE_NAMES.CHAT_HISTORY,
287296 ].every((name) => serviceContainer.isReady(name));
288297 }
289298
@@ -307,6 +316,7 @@
307316 mode: modeService,
308317 resourceMonitoring: resourceMonitoringService,
309318 systemMessage: systemMessageService,
319+ chatHistory: chatHistoryService,
310320 } as const;
311321
312322 // Export the service container for advanced usage
modified extensions/cli/src/services/types.ts +2 −0
@@ -93,6 +93,7 @@
9393 }
9494
9595 export type { FileIndexServiceState } from "./FileIndexService.js";
96+export type { ChatHistoryState } from "./ChatHistoryService.js";
9697
9798 /**
9899 * Service names as constants to prevent typos
@@ -107,6 +108,7 @@
107108 FILE_INDEX: "fileIndex",
108109 RESOURCE_MONITORING: "resourceMonitoring",
109110 SYSTEM_MESSAGE: "systemMessage",
111+ CHAT_HISTORY: "chatHistory",
110112 } as const;
111113
112114 /**
modified extensions/cli/src/slashCommands.ts +29 −0
@@ -199,6 +199,34 @@
199199 };
200200 }
201201
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+
202230 const commandHandlers: Record<string, CommandHandler> = {
203231 help: handleHelp,
204232 clear: () => {
@@ -230,6 +258,7 @@
230258 posthogService.capture("useSlashCommand", { name: "resume" });
231259 return { openSessionSelector: true };
232260 },
261+ fork: handleFork,
233262 };
234263
235264 export async function handleSlashCommands(
modified extensions/cli/src/stream/handleToolCalls.ts +81 −35
@@ -9,6 +9,7 @@
99 MCPServiceState,
1010 MCPTool,
1111 SERVICE_NAMES,
12+ services,
1213 } from "../services/index.js";
1314 import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js";
1415 import { getAllBuiltinTools, ToolCall } from "../tools/index.js";
@@ -27,14 +28,23 @@
2728 callbacks: StreamCallbacks | undefined,
2829 isHeadless: boolean,
2930 ): Promise<boolean> {
31+ const chatHistorySvc = services.chatHistory;
32+ const useService =
33+ typeof chatHistorySvc?.isReady === "function" && chatHistorySvc.isReady();
3034 if (toolCalls.length === 0) {
3135 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+ }
3848 }
3949 return false;
4050 }
@@ -68,7 +78,16 @@
6878 })),
6979 };
7080
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+ }
7291
7392 // First preprocess the tool calls
7493 const { preprocessedCalls, errorChatEntries } =
@@ -77,13 +96,17 @@
7796 // Add any preprocessing errors to chat history
7897 // Convert error entries from OpenAI format to ChatHistoryItem format
7998 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+ }
87110 });
88111
89112 // Execute the valid preprocessed tool calls
@@ -97,32 +120,55 @@
97120 return true; // Signal early return needed
98121 }
99122
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
102124 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 : "";
107127
128+ // Derive per-result status instead of applying batch-wide hasRejection
129+ let status: ToolStatus = "done";
130+ const lower = resultContent.toLowerCase();
108131 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")
111135 ) {
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+ }
115143
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+ }
126172 }
127173 }
128174 });
modified extensions/cli/src/stream/streamChatResponse.helpers.ts +117 −46
@@ -5,6 +5,7 @@
55 import { checkToolPermission } from "../permissions/permissionChecker.js";
66 import { toolPermissionManager } from "../permissions/permissionManager.js";
77 import { ToolCallRequest } from "../permissions/types.js";
8+import { services } from "../services/index.js";
89 import { telemetryService } from "../telemetry/telemetryService.js";
910 import { calculateTokenCost } from "../telemetry/utils.js";
1011 import {
@@ -373,81 +374,151 @@
373374 hasRejection: boolean;
374375 chatHistoryEntries: ChatCompletionToolMessageParam[];
375376 }> {
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.
378379
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+ }));
388385
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
392394
393- // Handle remaining tool calls in this batch to maintain chat history consistency
394395 try {
395396 logger.debug("Checking tool permissions", {
396- name: toolCall.name,
397- arguments: toolCall.arguments,
397+ name: call.name,
398+ arguments: call.arguments,
398399 });
399400
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);
403403
404- // Check tool permissions using helper
405404 const approved = await checkToolPermissionApproval(
406- toolCall,
405+ call,
407406 callbacks,
408407 isHeadless,
409408 );
410409
411410 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 {}
413431 hasRejection = true;
432+ // Remaining items will be auto-cancelled in subsequent iterations
414433 continue;
415434 }
416435
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+ );
431490 } catch (error) {
432- const errorMessage = `Error executing tool ${toolCall.name}: ${
491+ const errorMessage = `Error checking permissions for ${call.name}: ${
433492 error instanceof Error ? error.message : String(error)
434493 }`;
435-
436- logger.error("Tool execution failed", {
437- name: toolCall.name,
494+ logger.error("Permission check failed", {
495+ name: call.name,
438496 error: errorMessage,
439497 });
440-
441- chatHistoryEntries.push({
498+ entriesByIndex.set(index, {
442499 role: "tool",
443- tool_call_id: toolCall.id,
500+ tool_call_id: call.id,
444501 content: errorMessage,
445502 });
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 {}
448512 }
449513 }
450514
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+
451522 return {
452523 hasRejection,
453524 chatHistoryEntries,
modified extensions/cli/src/stream/streamChatResponse.ts +25 −3
@@ -8,7 +8,7 @@
88 ChatCompletionTool,
99 } from "openai/resources.mjs";
1010
11-import { getServiceSync, SERVICE_NAMES } from "../services/index.js";
11+import { getServiceSync, SERVICE_NAMES, services } from "../services/index.js";
1212 import { systemMessageService } from "../services/SystemMessageService.js";
1313 import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js";
1414 import { telemetryService } from "../telemetry/telemetryService.js";
@@ -298,6 +298,7 @@
298298 }
299299
300300 // Main function that handles the conversation loop
301+// eslint-disable-next-line complexity
301302 export async function streamChatResponse(
302303 chatHistory: ChatHistoryItem[],
303304 model: ModelConfig,
@@ -320,6 +321,16 @@
320321 let finalResponse = "";
321322
322323 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+ }
323334 logger.debug("Starting conversation iteration");
324335
325336 // Recompute tools on each iteration to handle mode changes during streaming
@@ -359,7 +370,7 @@
359370 // Handle content display
360371 handleContentDisplay(content, callbacks, isHeadless);
361372
362- // Handle tool calls and check for early return
373+ // Handle tool calls and check for early return. This updates history via ChatHistoryService.
363374 const shouldReturn = await handleToolCalls(
364375 toolCalls,
365376 chatHistory,
@@ -385,7 +396,18 @@
385396
386397 // Only update chat history if compaction actually occurred
387398 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+ }
389411 }
390412 }
391413
modified extensions/cli/src/test-helpers/ui-test-context.ts +15 −0
@@ -8,6 +8,21 @@
88 cleanup: () => void;
99 }
1010
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+
1126 /**
1227 * Creates a test context with common UI mocks for TUI components
1328 */
modified extensions/cli/src/ui/AppRoot.tsx +1 −0
@@ -8,6 +8,7 @@
88 configPath?: string;
99 initialPrompt?: string;
1010 resume?: boolean;
11+ fork?: string;
1112 additionalRules?: string[];
1213 additionalPrompts?: string[];
1314 }
modified extensions/cli/src/ui/TUIChat.tsx +3 −0
@@ -43,6 +43,7 @@
4343 configPath?: string;
4444 initialPrompt?: string;
4545 resume?: boolean;
46+ fork?: string;
4647 additionalRules?: string[];
4748 additionalPrompts?: string[];
4849 }
@@ -138,6 +139,7 @@
138139 configPath,
139140 initialPrompt,
140141 resume,
142+ fork,
141143 additionalRules,
142144 additionalPrompts,
143145 }) => {
@@ -200,6 +202,7 @@
200202 llmApi: services.model?.llmApi || undefined,
201203 initialPrompt,
202204 resume,
205+ fork,
203206 additionalRules,
204207 additionalPrompts,
205208 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";
22
33 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");
66
77 // Wait a bit for initial render
88 await new Promise((resolve) => setTimeout(resolve, 50));
@@ -16,52 +16,43 @@
1616 const frame = lastFrame()!;
1717
1818 // Should show @ character in input or show file search UI
19- // The @ might be in the input line or in a file search UI
2019 const hasAtSymbol = frame.includes("@") || frame.includes("◉ @");
2120 expect(hasAtSymbol).toBe(true);
2221
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");
3025 });
3126
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");
3432
35- // Type @ followed by text to filter files
36- stdin.write("@READ");
33+ // Type @ followed by text to filter files
34+ stdin.write("@READ");
3735
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));
4038
41- const frame = lastFrame()!;
39+ const frame = lastFrame()!;
4240
43- // Should show the typed text
44- expect(frame).toContain("@READ");
41+ // Should show the typed text
42+ expect(frame).toContain("@READ");
4543
46- // In local mode, should show either navigation hints or files
47- if (mode === "local") {
4844 // Should show either navigation hints or at least indicate file search is working
4945 const hasNavigationHints = frame.includes("↑/↓ to navigate");
50- const hasFileSearch =
51- frame.includes("@READ") && !frame.includes("Remote Mode");
46+ const hasFileSearch = frame.includes("@READ");
5247 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
5950 expect(frame).not.toContain("Remote Mode");
60- }
61- });
51+ },
52+ );
6253
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");
6556
6657 // Type multiple @ characters
6758 stdin.write("@@test");
@@ -75,36 +66,32 @@
7566 expect(frame).toBeDefined();
7667 expect(frame).toContain("@@test");
7768
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");
8471 });
8572
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");
8878
89- // Type @ to trigger file search
90- stdin.write("@");
79+ // Type @ to trigger file search
80+ stdin.write("@");
9181
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));
9484
95- const frame = lastFrame()!;
85+ const frame = lastFrame()!;
9686
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);
10090
101- // In local mode, should show either navigation hints or file search UI
102- if (mode === "local") {
10391 // Should show either navigation hints or at least the @ character in file search
10492 const hasNavigationHints = frame.includes("↑/↓ to navigate");
105- const hasFileSearchUI =
106- frame.includes("@") && !frame.includes("Remote Mode");
93+ const hasFileSearchUI = frame.includes("@");
10794 expect(hasNavigationHints || hasFileSearchUI).toBe(true);
108- }
109- });
95+ },
96+ );
11097 });
modified extensions/cli/src/ui/__tests__/TUIChat.slashCommands.test.tsx +7 −3
@@ -30,8 +30,10 @@
3030 // Type /log to trigger slash command filtering
3131 stdin.write("/log");
3232
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+ );
3537
3638 const frame = lastFrame();
3739
@@ -81,7 +83,9 @@
8183 // Type just /
8284 stdin.write("/");
8385
84- await new Promise((resolve) => setTimeout(resolve, 50));
86+ await new Promise((resolve) =>
87+ setTimeout(resolve, mode === "remote" ? 120 : 50),
88+ );
8589
8690 const frame = lastFrame();
8791
modified extensions/cli/src/ui/components/MemoizedMessage.tsx +9 −1
@@ -117,7 +117,15 @@
117117 >
118118 <Box>
119119 <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+ }
121129 >
122130 {isCompleted || isErrored ? "●" : "○"}
123131 </Text>
modified extensions/cli/src/ui/hooks/useChat.helpers.ts +1 −3
@@ -221,7 +221,6 @@
221221 remoteUrl?: string;
222222 onShowConfigSelector: () => void;
223223 exit: () => void;
224- setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>;
225224 }
226225
227226 /**
@@ -233,7 +232,6 @@
233232 remoteUrl,
234233 onShowConfigSelector,
235234 exit,
236- setChatHistory,
237235 }: HandleSpecialCommandsOptions): Promise<boolean> {
238236 const trimmedMessage = message.trim();
239237
@@ -246,7 +244,7 @@
246244 // Handle /exit command in remote mode
247245 if (isRemoteMode && remoteUrl && trimmedMessage === "/exit") {
248246 const { handleRemoteExit } = await import("./useChat.remote.helpers.js");
249- await handleRemoteExit(remoteUrl, setChatHistory, exit);
247+ await handleRemoteExit(remoteUrl, exit);
250248 return true;
251249 }
252250
modified extensions/cli/src/ui/hooks/useChat.remote.helpers.ts +50 −82
@@ -1,10 +1,19 @@
11 import type { ChatHistoryItem } from "core/index.js";
22
3+import { services } from "../../services/index.js";
34 import { posthogService } from "../../telemetry/posthogService.js";
45 import { logger } from "../../util/logger.js";
56
67 import { RemoteServerState } from "./useChat.types.js";
78
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+
817 /**
918 * Poll remote server for state updates
1019 */
@@ -25,7 +34,6 @@
2534
2635 interface SetupRemotePollingOptions {
2736 remoteUrl: string;
28- setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>;
2937 setIsWaitingForResponse: React.Dispatch<React.SetStateAction<boolean>>;
3038 responseStartTime: number | null;
3139 setResponseStartTime: React.Dispatch<React.SetStateAction<number | null>>;
@@ -36,7 +44,6 @@
3644 */
3745 export function setupRemotePolling({
3846 remoteUrl,
39- setChatHistory,
4047 setIsWaitingForResponse,
4148 responseStartTime,
4249 setResponseStartTime,
@@ -54,7 +61,6 @@
5461 if (state && isMounted) {
5562 updateStateFromRemote({
5663 state,
57- setChatHistory,
5864 setIsWaitingForResponse,
5965 responseStartTime,
6066 setResponseStartTime,
@@ -81,7 +87,6 @@
8187
8288 interface UpdateStateFromRemoteOptions {
8389 state: RemoteServerState;
84- setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>;
8590 setIsWaitingForResponse: React.Dispatch<React.SetStateAction<boolean>>;
8691 responseStartTime: number | null;
8792 setResponseStartTime: React.Dispatch<React.SetStateAction<number | null>>;
@@ -92,37 +97,26 @@
9297 */
9398 function updateStateFromRemote({
9499 state,
95- setChatHistory,
96100 setIsWaitingForResponse,
97101 responseStartTime,
98102 setResponseStartTime,
99103 }: UpdateStateFromRemoteOptions): void {
100104 // Update chat history from server - now using session.history directly
101105 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+ }
126120 }
127121
128122 // Update processing state
@@ -139,7 +133,6 @@
139133 */
140134 export async function handleRemoteExit(
141135 remoteUrl: string,
142- setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>,
143136 exit: () => void,
144137 ): Promise<void> {
145138 posthogService.capture("useSlashCommand", {
@@ -152,50 +145,36 @@
152145 });
153146
154147 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+ }
165155 setTimeout(() => exit(), 1000);
166156 } else {
167157 const text = await response.text();
168158 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 {}
179164 }
180165 } catch (error) {
181166 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 {}
192172 }
193173 }
194174
195175 interface HandleRemoteMessageOptions {
196176 remoteUrl: string;
197177 messageContent: string;
198- setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>;
199178 }
200179
201180 /**
@@ -204,7 +183,6 @@
204183 export async function handleRemoteMessage({
205184 remoteUrl,
206185 messageContent,
207- setChatHistory,
208186 }: HandleRemoteMessageOptions): Promise<void> {
209187 try {
210188 const response = await fetch(`${remoteUrl}/message`, {
@@ -217,29 +195,19 @@
217195
218196 if (!response.ok) {
219197 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 {}
230203 }
231204 // State will be updated by polling
232205 } catch (error) {
233206 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 {}
244212 }
245213 }
modified extensions/cli/src/ui/hooks/useChat.stream.helpers.ts +52 −19
@@ -1,5 +1,8 @@
11 import type { ChatHistoryItem, ToolCallState, ToolStatus } from "core/index.js";
22
3+import { logger } from "src/util/logger.js";
4+
5+import { services } from "../../services/index.js";
36 import { getCurrentSession, updateSessionTitle } from "../../session.js";
47
58 import { generateSessionTitle } from "./useChat.helpers.js";
@@ -23,18 +26,27 @@
2326 onContent: (_: string) => {},
2427
2528 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+ }
3850 // Generate session title after first assistant response
3951 if (content && llmApi && model) {
4052 const currentSession = getCurrentSession();
@@ -52,10 +64,15 @@
5264 },
5365
5466 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
5573 setChatHistory((prev) => {
5674 const newHistory = [...prev];
5775
58- // Always create a new assistant message for each tool call
5976 const toolCallId = `tool_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`;
6077 const toolCallState: ToolCallState = {
6178 toolCallId: toolCallId,
@@ -95,17 +112,22 @@
95112 },
96113
97114 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
98121 setChatHistory((prev) => {
99122 const newHistory = [...prev];
100123
101- // Find the tool call state and update it
102124 for (let i = newHistory.length - 1; i >= 0; i--) {
103125 const item = newHistory[i];
104126 if (item.toolCallStates) {
105127 const toolState = item.toolCallStates.find(
106128 (ts) =>
107129 ts.toolCall.function.name === toolName &&
108- ts.status === "calling",
130+ (ts.status === "calling" || ts.status === "generated"),
109131 );
110132
111133 if (toolState) {
@@ -127,10 +149,14 @@
127149 },
128150
129151 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+
130157 setChatHistory((prev) => {
131158 const newHistory = [...prev];
132159
133- // Find the tool call state and mark it as errored
134160 if (toolName) {
135161 for (let i = newHistory.length - 1; i >= 0; i--) {
136162 const item = newHistory[i];
@@ -138,7 +164,7 @@
138164 const toolState = item.toolCallStates.find(
139165 (ts) =>
140166 ts.toolCall.function.name === toolName &&
141- ts.status === "calling",
167+ (ts.status === "calling" || ts.status === "generated"),
142168 );
143169
144170 if (toolState) {
@@ -184,6 +210,14 @@
184210 },
185211
186212 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
187221 setChatHistory((prev) => [
188222 ...prev,
189223 {
@@ -241,8 +275,7 @@
241275 streamCallbacks,
242276 );
243277
244- // streamChatResponse modifies the array in place
245- // The new messages are already in historyForLLM
278+ // Service-driven streaming; history updates occur via ChatHistoryService
246279 } else {
247280 await streamChatResponse(
248281 chatHistory,
modified extensions/cli/src/ui/hooks/useChat.ts +63 −12
@@ -1,6 +1,6 @@
11 import type { ChatHistoryItem, Session } from "core/index.js";
22 import { useApp } from "ink";
3-import { useEffect, useState } from "react";
3+import { useEffect, useRef, useState } from "react";
44
55 import { findCompactionIndex } from "../../compaction.js";
66 import { toolPermissionManager } from "../../permissions/permissionManager.js";
@@ -46,6 +46,7 @@
4646 llmApi,
4747 initialPrompt,
4848 resume,
49+ fork,
4950 additionalRules,
5051 additionalPrompts,
5152 onShowConfigSelector,
@@ -59,6 +60,9 @@
5960 }: UseChatProps) {
6061 const { exit } = useApp();
6162
63+ // Track service subscription
64+ const serviceListenerCleanupRef = useRef<null | (() => void)>(null);
65+
6266 // Store the current session
6367 const [currentSession, setCurrentSession] = useState<Session>(() => {
6468 // In remote mode, start with empty session (will be populated by polling)
@@ -66,6 +70,17 @@
6670 return createSession([]);
6771 }
6872
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+
6984 // Load previous session if resume flag is used
7085 if (resume) {
7186 const savedSession = loadSession();
@@ -78,9 +93,45 @@
7893 return createSession([]);
7994 });
8095
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,
83101 );
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+ }, []);
84135
85136 const [isWaitingForResponse, setIsWaitingForResponse] = useState(false);
86137 const [responseStartTime, setResponseStartTime] = useState<number | null>(
@@ -91,8 +142,11 @@
91142 useState<AbortController | null>(null);
92143 const [isChatHistoryInitialized, setIsChatHistoryInitialized] = useState(
93144 // 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
94146 // 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),
96150 );
97151
98152 // Capture initial rules to prevent re-initialization when rules change
@@ -101,8 +155,8 @@
101155 const [activePermissionRequest, setActivePermissionRequest] =
102156 useState<ActivePermissionRequest | null>(null);
103157 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) {
106160 return findCompactionIndex(currentSession.history);
107161 }
108162 return null;
@@ -126,7 +180,6 @@
126180
127181 return setupRemotePolling({
128182 remoteUrl,
129- setChatHistory,
130183 setIsWaitingForResponse,
131184 responseStartTime,
132185 setResponseStartTime,
@@ -204,7 +257,7 @@
204257
205258 try {
206259 const streamCallbacks = createStreamCallbacks({
207- setChatHistory,
260+ setChatHistory: setChatHistory,
208261 setActivePermissionRequest,
209262 llmApi,
210263 model,
@@ -366,7 +419,6 @@
366419 remoteUrl,
367420 onShowConfigSelector,
368421 exit,
369- setChatHistory,
370422 });
371423
372424 if (handled) return;
@@ -406,7 +458,6 @@
406458 await handleRemoteMessage({
407459 remoteUrl,
408460 messageContent: messageContentString,
409- setChatHistory,
410461 });
411462 return;
412463 }
@@ -418,7 +469,7 @@
418469 model,
419470 llmApi,
420471 compactionIndex,
421- setChatHistory,
472+ setChatHistory: setChatHistory,
422473 setCompactionIndex,
423474 });
424475
@@ -549,7 +600,7 @@
549600
550601 return {
551602 chatHistory,
552- setChatHistory,
603+ setChatHistory: setChatHistory,
553604 isWaitingForResponse,
554605 responseStartTime,
555606 inputMode,
modified extensions/cli/src/ui/hooks/useChat.types.ts +1 −0
@@ -10,6 +10,7 @@
1010 llmApi?: BaseLlmApi;
1111 initialPrompt?: string;
1212 resume?: boolean;
13+ fork?: string;
1314 additionalRules?: string[];
1415 additionalPrompts?: string[];
1516 onShowConfigSelector: () => void;
modified extensions/cli/src/ui/hooks/useUserInput.ts +2 −2
@@ -194,7 +194,7 @@
194194
195195 export function updateTextBufferState(options: TextBufferStateOptions) {
196196 const {
197- handled,
197+ handled: _handled,
198198 textBuffer,
199199 setInputText,
200200 setCursorPosition,
@@ -204,7 +204,7 @@
204204 } = options;
205205
206206 // Skip state updates during rapid input mode to avoid conflicts with timer-based updates
207- if (handled && !textBuffer.isInRapidInputMode()) {
207+ if (!textBuffer.isInRapidInputMode()) {
208208 const newText = textBuffer.text;
209209 const newCursor = textBuffer.cursor;
210210 setInputText(newText);
modified extensions/cli/src/ui/index.ts +3 −0
@@ -12,6 +12,7 @@
1212 interface StartTUIChatOptions {
1313 initialPrompt?: string;
1414 resume?: boolean;
15+ fork?: string;
1516 config?: string;
1617 org?: string;
1718 rule?: string[];
@@ -31,6 +32,7 @@
3132 const {
3233 initialPrompt,
3334 resume,
35+ fork,
3436 config,
3537 org,
3638 rule,
@@ -63,6 +65,7 @@
6365 configPath: config,
6466 initialPrompt,
6567 resume,
68+ fork,
6669 additionalRules: rule,
6770 additionalPrompts: prompt,
6871 }),
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.