Elffuss BraidHub

kikocis/continue public

4e263ad457a7 · 11.7 KiBRawPermalink
1import {
2 EditableRegionStrategy,
3 getNextEditableRegion,
4} from "core/nextEdit/NextEditEditableRegionCalculator";
5import { PrefetchQueue } from "core/nextEdit/NextEditPrefetchQueue";
6import { NextEditProvider } from "core/nextEdit/NextEditProvider";
7import { localPathOrUriToPath } from "core/util/pathToUri";
8import * as vscode from "vscode";
9import { VsCodeIde } from "../VsCodeIde";
10import { JumpManager } from "./JumpManager";
11import { NextEditWindowManager } from "./NextEditWindowManager";
12
13export enum HandlerPriority {
14 CRITICAL = 5,
15 HIGH = 4,
16 NORMAL = 3,
17 LOW = 2,
18 FALLBACK = 1,
19}
20
21interface StateSnapshot {
22 nextEditWindowAccepted: boolean;
23 jumpInProgress: boolean;
24 jumpJustAccepted: boolean;
25 lastDocumentChangeTime: number;
26 isTypingSession: boolean;
27 document?: vscode.TextDocument;
28 cursorPosition?: vscode.Position;
29}
30
31type SelectionChangeHandler = (
32 e: vscode.TextEditorSelectionChangeEvent,
33 state: StateSnapshot,
34) => Promise<boolean>;
35
36interface HandlerRegistration {
37 id: string;
38 priority: number;
39 handler: SelectionChangeHandler;
40}
41
42/**
43 * SelectionChangeManager handles cursor movement events in a coordinated way
44 * to prevent race conditions and ensure consistent behavior across features.
45 *
46 * Case 1: User just moves the cursor around.
47 * - vscode fires onDidChangeTextEditorSelection.
48 * - State is captured. All fields in StateSnapshot are false.
49 * - All registered handlers return false.
50 * - Fallback handler runs, deleting the chain.
51 *
52 * Case 2: User accepts a next edit suggestion from a window.
53 * - vscode fires onDidChangeTextEditorSelection.
54 * - State is captured. nextEditWindowAccepted is true.
55 * - NextEditWindowManager's handler returns true.
56 * - No other handlers run, and edit chain is preserved.
57 *
58 * Case 3: User accepts a next edit suggestion from a ghost text.
59 * - vscode fires onDidChangeTextEditorSelection.
60 * - State is captured with document and cursorPosition.
61 * - GhostTextTracker's handler checks if ghost text was accepted at that position.
62 * - If accepted, handler returns true and edit chain is preserved.
63 *
64 * Case 4: User is actively typing code.
65 * - Each keystroke triggers documentChanged() to update lastDocumentChangeTime.
66 * - When cursor moves due to typing, onDidChangeTextEditorSelection fires.
67 * - State is captured with isTypingSession=true and recent lastDocumentChangeTime.
68 * - Typing session handler detects time since last edit is < TYPING_DELAY.
69 * - Handler returns true, preserving the edit chain during typing.
70 *
71 * Case 5: User performs a jump operation.
72 * - Jump is initiated, setting jumpInProgress to true.
73 * - When cursor position changes due to jump, onDidChangeTextEditorSelection fires.
74 * - State is captured with jumpInProgress=true.
75 * - JumpManager's handler returns true, preserving the edit chain.
76 *
77 * Case 6: User just completed a jump operation.
78 * - Jump completes, setting jumpJustAccepted to true.
79 * - onDidChangeTextEditorSelection fires for the final position.
80 * - State is captured with jumpJustAccepted=true.
81 * - JumpManager's handler returns true, preserving the edit chain.
82 *
83 * Case 7: Rapid cursor movements (debouncing).
84 * - User rapidly moves cursor (e.g., holding an arrow key).
85 * - Multiple onDidChangeTextEditorSelection events fire in quick succession.
86 * - Events within DEBOUNCE_DELAY of each other are queued.
87 * - Only the most recent event in a rapid sequence gets processed.
88 * - Prevents performance issues from too many events.
89 *
90 * Case 8: Event processing timeout.
91 * - An event handler takes longer than PROCESSING_TIMEOUT.
92 * - The timeout promise resolves first, throwing an error.
93 * - Error is caught, processing state is reset to prevent deadlocks.
94 * - System can continue processing the next event.
95 * - NOTE: At the current moment, there should not be any deadlocks, but I'm just making sure.
96 *
97 * Case 9: Error in handler.
98 * - One of the handlers throws an exception.
99 * - The error is caught and logged.
100 * - Processing continues with the next handler rather than failing completely.
101 * - Ensures stability even when individual handlers have problems.
102 *
103 * Case 10: Multiple queued events.
104 * - An event is being processed when new events arrive.
105 * - New events are added to eventQueue.
106 * - After current event is processed, queued events are handled sequentially.
107 * - Ensures all events are processed in the order they were received.
108 * - NOTE: I'm not sure if we even want to queue these events...
109 */
110export class SelectionChangeManager {
111 private static instance: SelectionChangeManager;
112 private listeners: HandlerRegistration[] = [];
113 private ide: VsCodeIde | null = null;
114 private usingFullFileDiff: boolean = true;
115
116 // Event bus-related attributes.
117 private eventQueue: vscode.TextEditorSelectionChangeEvent[] = [];
118 private lastEventTime = 0;
119 private isProcessingEvent = false;
120 private processingTimeout: NodeJS.Timeout | null = null;
121
122 // Debounce settings.
123 private readonly DEBOUNCE_DELAY = 50;
124 private readonly PROCESSING_TIMEOUT = 500;
125
126 // Track typing session state.
127 private isTypingSession = false;
128 private typingTimer: NodeJS.Timeout | null = null;
129 private lastDocumentChangeTime = 0;
130 private readonly TYPING_SESSION_TIMEOUT = 2000; // ms
131
132 private constructor() {}
133
134 public static getInstance() {
135 if (!SelectionChangeManager.instance) {
136 SelectionChangeManager.instance = new SelectionChangeManager();
137 }
138 return SelectionChangeManager.instance;
139 }
140
141 public initialize(ide: VsCodeIde, usingFullFileDiff: boolean): void {
142 this.ide = ide;
143 this.usingFullFileDiff = usingFullFileDiff;
144
145 // After handling all other listeners, this will delete the chain.
146 this.registerListener(
147 "defaultFallbackHandler",
148 this.defaultFallbackHandler.bind(this),
149 HandlerPriority.FALLBACK,
150 );
151 }
152
153 /**
154 * Updates this class's usingFullFileDiff flag.
155 * @param usingFullFileDiff New value to set.
156 */
157 public updateUsingFullFileDiff(usingFullFileDiff: boolean) {
158 this.usingFullFileDiff = usingFullFileDiff;
159 }
160
161 public documentChanged(): void {
162 this.isTypingSession = true;
163 this.lastDocumentChangeTime = Date.now();
164 this.resetTypingSession();
165 }
166
167 private resetTypingSession(): void {
168 if (this.typingTimer) {
169 clearTimeout(this.typingTimer);
170 }
171 this.typingTimer = setTimeout(() => {
172 this.isTypingSession = false;
173 }, this.TYPING_SESSION_TIMEOUT);
174 }
175
176 /**
177 * Register a listener for the selection change event.
178 * @param id Unique id for this handler.
179 * @param handler Function to handle the event.
180 * @param priority Higher priority runs first.
181 * @returns Function to unregister this listener.
182 */
183 public registerListener(
184 id: string,
185 handler: SelectionChangeHandler,
186 priority: HandlerPriority = HandlerPriority.NORMAL,
187 ): () => void {
188 // Remove any existing handler with the same id.
189 this.listeners = this.listeners.filter((l) => l.id !== id);
190
191 // Add the new handler.
192 this.listeners.push({ id, priority, handler });
193
194 // Sort by desc priority.
195 this.listeners.sort((a, b) => b.priority - a.priority);
196
197 // Return the unregister function.
198 return () => {
199 this.listeners = this.listeners.filter((l) => l.id !== id);
200 };
201 }
202
203 /**
204 * Handle a given selection change event.
205 * @param e THe selection change event.
206 */
207 public async handleSelectionChange(
208 e: vscode.TextEditorSelectionChangeEvent,
209 ): Promise<void> {
210 const now = Date.now();
211
212 // Simple debouncing logic.
213 // Ignore events that come too quickly after the previous one.
214 // TODO: test this.
215 if (now - this.lastEventTime < this.DEBOUNCE_DELAY) {
216 // Replace the queued event with the most recent one.
217 if (this.eventQueue.length > 0) {
218 this.eventQueue[this.eventQueue.length - 1] = e;
219 } else {
220 this.eventQueue.push(e);
221 }
222
223 return;
224 }
225
226 this.lastEventTime = now;
227
228 // Queue this event for later if the manager is already processing an event.
229 // NOTE: Depending on if we want an event bus or not, do an early return instead.
230 if (this.isProcessingEvent) {
231 this.eventQueue.push(e);
232 return;
233 }
234
235 try {
236 // Process this event first.
237 await this.processEventWithTimeout(e);
238
239 // Process remaining queued events sequentially.
240 // NOTE: Depending on if we want an event bus or not, skip this.
241 while (this.eventQueue.length > 0) {
242 const nextEvent = this.eventQueue.shift()!;
243 await this.processEventWithTimeout(nextEvent);
244 }
245 } catch (err) {
246 console.error("Error processing selection change event:", err);
247 this.isProcessingEvent = false;
248 if (this.processingTimeout) {
249 clearTimeout(this.processingTimeout);
250 this.processingTimeout = null;
251 }
252 }
253 }
254
255 /**
256 * Process a given event with a timeout.
257 * This is in attempt to prevent deadlocks between events.
258 * @param e The selection change event.
259 */
260 private async processEventWithTimeout(
261 e: vscode.TextEditorSelectionChangeEvent,
262 ): Promise<void> {
263 this.isProcessingEvent = true;
264
265 // Set up a timeout to prevent deadlocks.
266 const timeoutPromise = new Promise<void>((_, reject) => {
267 this.processingTimeout = setTimeout(() => {
268 reject(new Error("Selection change event processing timed out"));
269 }, this.PROCESSING_TIMEOUT);
270 });
271
272 try {
273 await Promise.race([this.processEvent(e), timeoutPromise]);
274 } finally {
275 // Clean up.
276 if (this.processingTimeout) {
277 clearTimeout(this.processingTimeout);
278 this.processingTimeout = null;
279 }
280
281 this.isProcessingEvent = false;
282 }
283 }
284
285 /**
286 * Core event processing logic.
287 * @param e The selection change event.
288 */
289 private async processEvent(
290 e: vscode.TextEditorSelectionChangeEvent,
291 ): Promise<void> {
292 const snapshot = this.captureState(e);
293
294 for (const { handler } of this.listeners) {
295 try {
296 if (await handler(e, snapshot)) {
297 return;
298 }
299 } catch (err) {
300 console.error("Error in selection change handler:", err);
301 // Don't break just yet -- go to next handler.
302 }
303 }
304 }
305
306 private captureState(
307 e: vscode.TextEditorSelectionChangeEvent,
308 ): StateSnapshot {
309 return {
310 nextEditWindowAccepted:
311 NextEditWindowManager.isInstantiated() &&
312 NextEditWindowManager.getInstance().hasAccepted(),
313 jumpInProgress: JumpManager.getInstance().isJumpInProgress(),
314 jumpJustAccepted: JumpManager.getInstance().wasJumpJustAccepted(),
315 lastDocumentChangeTime: this.lastDocumentChangeTime,
316 isTypingSession: this.isTypingSession,
317 document: e.textEditor.document,
318 cursorPosition: e.selections[0].active,
319 };
320 }
321
322 private async defaultFallbackHandler(
323 e: vscode.TextEditorSelectionChangeEvent,
324 state: StateSnapshot,
325 ): Promise<boolean> {
326 if (!this.ide) {
327 console.error("IDE not initialized in SelectionChangeManager");
328 return false;
329 }
330
331 console.log(
332 "defaultFallbackHandler: deleteChain called from onDidChangeTextEditorSelection",
333 );
334 await NextEditProvider.getInstance().deleteChain();
335
336 if (!this.usingFullFileDiff) {
337 const nextEditableRegions =
338 (await getNextEditableRegion(EditableRegionStrategy.Static, {
339 cursorPosition: e.selections[0].anchor,
340 filepath: localPathOrUriToPath(e.textEditor.document.uri.toString()),
341 ide: this.ide,
342 })) ?? [];
343 // (await getNextEditableRegion(EditableRegionStrategy.Sliding, {
344 // filepath: localPathOrUriToPath(e.textEditor.document.uri.toString()),
345 // fileLines: e.textEditor.document.getText().split("\n"),
346 // })) ?? [];
347
348 nextEditableRegions.forEach((region) => {
349 PrefetchQueue.getInstance().enqueueUnprocessed(region);
350 });
351 }
352
353 return true;
354 }
355}