| 1 | import { |
| 2 | EditableRegionStrategy, |
| 3 | getNextEditableRegion, |
| 4 | } from "core/nextEdit/NextEditEditableRegionCalculator"; |
| 5 | import { PrefetchQueue } from "core/nextEdit/NextEditPrefetchQueue"; |
| 6 | import { NextEditProvider } from "core/nextEdit/NextEditProvider"; |
| 7 | import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; |
| 8 | import * as vscode from "vscode"; |
| 9 | import { VsCodeIde } from "../VsCodeIde"; |
| 10 | import { VsCodeWebviewProtocol } from "../webviewProtocol"; |
| 11 | import { JumpManager } from "./JumpManager"; |
| 12 | import { NextEditWindowManager } from "./NextEditWindowManager"; |
| 13 | import { |
| 14 | HandlerPriority, |
| 15 | SelectionChangeManager, |
| 16 | } from "./SelectionChangeManager"; |
| 17 | |
| 18 | // Mock VSCode API |
| 19 | vi.mock("vscode", () => ({ |
| 20 | window: { |
| 21 | activeTextEditor: { |
| 22 | document: { |
| 23 | uri: { |
| 24 | toString: vi.fn().mockReturnValue("file:///test/file.ts"), |
| 25 | }, |
| 26 | getText: vi.fn().mockReturnValue("Sample document text"), |
| 27 | lineCount: 10, |
| 28 | lineAt: vi.fn((line) => ({ |
| 29 | text: "sample line text", |
| 30 | range: { |
| 31 | start: { line, character: 0 }, |
| 32 | end: { line, character: 16 }, |
| 33 | }, |
| 34 | })), |
| 35 | }, |
| 36 | selections: [ |
| 37 | { |
| 38 | active: { line: 2, character: 5 }, |
| 39 | anchor: { line: 2, character: 5 }, |
| 40 | }, |
| 41 | ], |
| 42 | }, |
| 43 | }, |
| 44 | Position: class { |
| 45 | constructor( |
| 46 | public line: number, |
| 47 | public character: number, |
| 48 | ) {} |
| 49 | }, |
| 50 | Selection: class { |
| 51 | constructor( |
| 52 | public anchor: any, |
| 53 | public active: any, |
| 54 | ) {} |
| 55 | }, |
| 56 | })); |
| 57 | |
| 58 | // Mock core dependencies |
| 59 | vi.mock("core/nextEdit/NextEditProvider", () => ({ |
| 60 | NextEditProvider: { |
| 61 | getInstance: vi.fn(() => ({ |
| 62 | deleteChain: vi.fn(), |
| 63 | })), |
| 64 | }, |
| 65 | })); |
| 66 | |
| 67 | vi.mock("core/nextEdit/NextEditEditableRegionCalculator", () => ({ |
| 68 | EditableRegionStrategy: { |
| 69 | Static: "static", |
| 70 | Sliding: "sliding", |
| 71 | }, |
| 72 | getNextEditableRegion: vi.fn(), |
| 73 | })); |
| 74 | |
| 75 | vi.mock("core/nextEdit/NextEditPrefetchQueue", () => ({ |
| 76 | PrefetchQueue: { |
| 77 | getInstance: vi.fn(() => ({ |
| 78 | enqueueUnprocessed: vi.fn(), |
| 79 | })), |
| 80 | }, |
| 81 | })); |
| 82 | |
| 83 | vi.mock("core/util/pathToUri", () => ({ |
| 84 | localPathOrUriToPath: vi.fn((uri) => uri.replace("file://", "")), |
| 85 | })); |
| 86 | |
| 87 | vi.mock("../VsCodeIde", () => ({ |
| 88 | VsCodeIde: vi.fn(), |
| 89 | })); |
| 90 | |
| 91 | vi.mock("./JumpManager", () => ({ |
| 92 | JumpManager: { |
| 93 | getInstance: vi.fn(() => ({ |
| 94 | isJumpInProgress: vi.fn().mockReturnValue(false), |
| 95 | wasJumpJustAccepted: vi.fn().mockReturnValue(false), |
| 96 | })), |
| 97 | }, |
| 98 | })); |
| 99 | |
| 100 | vi.mock("./NextEditWindowManager", () => ({ |
| 101 | NextEditWindowManager: { |
| 102 | isInstantiated: vi.fn().mockReturnValue(false), |
| 103 | getInstance: vi.fn(() => ({ |
| 104 | hasAccepted: vi.fn().mockReturnValue(false), |
| 105 | })), |
| 106 | }, |
| 107 | })); |
| 108 | |
| 109 | describe("SelectionChangeManager", () => { |
| 110 | let selectionChangeManager: SelectionChangeManager; |
| 111 | let mockIde: VsCodeIde; |
| 112 | let mockDeleteChain: ReturnType<typeof vi.fn>; |
| 113 | let mockEnqueueUnprocessed: ReturnType<typeof vi.fn>; |
| 114 | |
| 115 | beforeEach(() => { |
| 116 | vi.resetAllMocks(); |
| 117 | |
| 118 | // Setup mock implementations |
| 119 | mockDeleteChain = vi.fn(); |
| 120 | mockEnqueueUnprocessed = vi.fn(); |
| 121 | |
| 122 | vi.mocked(NextEditProvider.getInstance).mockReturnValue({ |
| 123 | deleteChain: mockDeleteChain, |
| 124 | } as any); |
| 125 | |
| 126 | vi.mocked(PrefetchQueue.getInstance).mockReturnValue({ |
| 127 | enqueueUnprocessed: mockEnqueueUnprocessed, |
| 128 | } as any); |
| 129 | |
| 130 | vi.mocked(getNextEditableRegion).mockResolvedValue([ |
| 131 | { |
| 132 | filepath: "/test/file.ts", |
| 133 | range: { |
| 134 | start: { line: 0, character: 0 }, |
| 135 | end: { line: 10, character: 0 }, |
| 136 | }, |
| 137 | // content: "test content", |
| 138 | // cursorPosition: { line: 2, character: 5 }, |
| 139 | }, |
| 140 | ]); |
| 141 | |
| 142 | // Create mock context and webview protocol promise |
| 143 | const mockContext = { |
| 144 | subscriptions: [], |
| 145 | workspaceState: { |
| 146 | get: vi.fn(), |
| 147 | update: vi.fn(), |
| 148 | keys: vi.fn().mockReturnValue([]), |
| 149 | }, |
| 150 | globalState: { |
| 151 | get: vi.fn(), |
| 152 | update: vi.fn(), |
| 153 | keys: vi.fn().mockReturnValue([]), |
| 154 | setKeysForSync: vi.fn(), |
| 155 | }, |
| 156 | secrets: { |
| 157 | get: vi.fn(), |
| 158 | store: vi.fn(), |
| 159 | delete: vi.fn(), |
| 160 | onDidChange: vi.fn(), |
| 161 | }, |
| 162 | extensionUri: { fsPath: "/mock/extension/path" } as any, |
| 163 | extensionPath: "/mock/extension/path", |
| 164 | environmentVariableCollection: {} as any, |
| 165 | asAbsolutePath: vi.fn(), |
| 166 | storageUri: undefined, |
| 167 | storagePath: undefined, |
| 168 | globalStorageUri: { fsPath: "/mock/global/storage" } as any, |
| 169 | globalStoragePath: "/mock/global/storage", |
| 170 | logUri: { fsPath: "/mock/log" } as any, |
| 171 | logPath: "/mock/log", |
| 172 | extensionMode: 1, // Production mode |
| 173 | extension: {} as any, |
| 174 | } as vscode.ExtensionContext; |
| 175 | let resolveWebviewProtocol: any = undefined; |
| 176 | const webviewProtocolPromise = new Promise<VsCodeWebviewProtocol>( |
| 177 | (resolve) => { |
| 178 | resolveWebviewProtocol = resolve; |
| 179 | }, |
| 180 | ); |
| 181 | |
| 182 | // Create VsCodeIde instance with proper constructor arguments |
| 183 | mockIde = new VsCodeIde(webviewProtocolPromise, mockContext); |
| 184 | |
| 185 | // Get a fresh instance |
| 186 | selectionChangeManager = SelectionChangeManager.getInstance(); |
| 187 | |
| 188 | // Clear any existing listeners from previous tests |
| 189 | const privateManager = selectionChangeManager as any; |
| 190 | privateManager.listeners = []; |
| 191 | |
| 192 | selectionChangeManager.initialize(mockIde, false); |
| 193 | }); |
| 194 | |
| 195 | afterEach(() => { |
| 196 | // Clear any timers |
| 197 | vi.clearAllTimers(); |
| 198 | |
| 199 | // Reset all private state to prevent test interference |
| 200 | const privateManager = selectionChangeManager as any; |
| 201 | privateManager.listeners = []; |
| 202 | privateManager.eventQueue = []; |
| 203 | privateManager.lastEventTime = 0; |
| 204 | privateManager.isProcessingEvent = false; |
| 205 | if (privateManager.processingTimeout) { |
| 206 | clearTimeout(privateManager.processingTimeout); |
| 207 | privateManager.processingTimeout = null; |
| 208 | } |
| 209 | privateManager.isTypingSession = false; |
| 210 | if (privateManager.typingTimer) { |
| 211 | clearTimeout(privateManager.typingTimer); |
| 212 | privateManager.typingTimer = null; |
| 213 | } |
| 214 | privateManager.lastDocumentChangeTime = 0; |
| 215 | }); |
| 216 | |
| 217 | describe("getInstance", () => { |
| 218 | it("should return the same instance on multiple calls", () => { |
| 219 | const instance1 = SelectionChangeManager.getInstance(); |
| 220 | const instance2 = SelectionChangeManager.getInstance(); |
| 221 | expect(instance1).toBe(instance2); |
| 222 | }); |
| 223 | }); |
| 224 | |
| 225 | describe("initialize", () => { |
| 226 | it("should set up IDE and register default fallback handler", () => { |
| 227 | const newManager = new (SelectionChangeManager as any)(); |
| 228 | const registerSpy = vi.spyOn(newManager, "registerListener"); |
| 229 | |
| 230 | newManager.initialize(mockIde, true); |
| 231 | |
| 232 | expect(registerSpy).toHaveBeenCalledWith( |
| 233 | "defaultFallbackHandler", |
| 234 | expect.any(Function), |
| 235 | HandlerPriority.FALLBACK, |
| 236 | ); |
| 237 | }); |
| 238 | }); |
| 239 | |
| 240 | describe("documentChanged", () => { |
| 241 | it("should set typing session to true and update last document change time", () => { |
| 242 | const beforeTime = Date.now(); |
| 243 | selectionChangeManager.documentChanged(); |
| 244 | const afterTime = Date.now(); |
| 245 | |
| 246 | // Access private properties for testing |
| 247 | const privateManager = selectionChangeManager as any; |
| 248 | expect(privateManager.isTypingSession).toBe(true); |
| 249 | expect(privateManager.lastDocumentChangeTime).toBeGreaterThanOrEqual( |
| 250 | beforeTime, |
| 251 | ); |
| 252 | expect(privateManager.lastDocumentChangeTime).toBeLessThanOrEqual( |
| 253 | afterTime, |
| 254 | ); |
| 255 | }); |
| 256 | |
| 257 | it("should reset typing session timer", () => { |
| 258 | vi.useFakeTimers(); |
| 259 | |
| 260 | selectionChangeManager.documentChanged(); |
| 261 | const privateManager = selectionChangeManager as any; |
| 262 | |
| 263 | expect(privateManager.isTypingSession).toBe(true); |
| 264 | |
| 265 | // Fast-forward past the typing session timeout |
| 266 | vi.advanceTimersByTime(2100); // TYPING_SESSION_TIMEOUT is 2000ms |
| 267 | |
| 268 | expect(privateManager.isTypingSession).toBe(false); |
| 269 | |
| 270 | vi.useRealTimers(); |
| 271 | }); |
| 272 | }); |
| 273 | |
| 274 | describe("registerListener", () => { |
| 275 | it("should register a handler with correct priority", () => { |
| 276 | const mockHandler = vi.fn(); |
| 277 | const unregister = selectionChangeManager.registerListener( |
| 278 | "testHandler", |
| 279 | mockHandler, |
| 280 | HandlerPriority.HIGH, |
| 281 | ); |
| 282 | |
| 283 | // Access private listeners array |
| 284 | const privateManager = selectionChangeManager as any; |
| 285 | const testHandler = privateManager.listeners.find( |
| 286 | (l: any) => l.id === "testHandler", |
| 287 | ); |
| 288 | |
| 289 | expect(testHandler).toBeDefined(); |
| 290 | expect(testHandler.priority).toBe(HandlerPriority.HIGH); |
| 291 | expect(testHandler.handler).toBe(mockHandler); |
| 292 | |
| 293 | // Test unregister function |
| 294 | unregister(); |
| 295 | const afterUnregister = privateManager.listeners.find( |
| 296 | (l: any) => l.id === "testHandler", |
| 297 | ); |
| 298 | expect(afterUnregister).toBeUndefined(); |
| 299 | }); |
| 300 | |
| 301 | it("should replace existing handler with same id", () => { |
| 302 | const firstHandler = vi.fn(); |
| 303 | const secondHandler = vi.fn(); |
| 304 | |
| 305 | selectionChangeManager.registerListener( |
| 306 | "testHandler", |
| 307 | firstHandler, |
| 308 | HandlerPriority.NORMAL, |
| 309 | ); |
| 310 | |
| 311 | selectionChangeManager.registerListener( |
| 312 | "testHandler", |
| 313 | secondHandler, |
| 314 | HandlerPriority.HIGH, |
| 315 | ); |
| 316 | |
| 317 | const privateManager = selectionChangeManager as any; |
| 318 | const handlers = privateManager.listeners.filter( |
| 319 | (l: any) => l.id === "testHandler", |
| 320 | ); |
| 321 | |
| 322 | expect(handlers).toHaveLength(1); |
| 323 | expect(handlers[0].handler).toBe(secondHandler); |
| 324 | expect(handlers[0].priority).toBe(HandlerPriority.HIGH); |
| 325 | }); |
| 326 | |
| 327 | it("should sort handlers by priority in descending order", () => { |
| 328 | selectionChangeManager.registerListener( |
| 329 | "low", |
| 330 | vi.fn(), |
| 331 | HandlerPriority.LOW, |
| 332 | ); |
| 333 | selectionChangeManager.registerListener( |
| 334 | "critical", |
| 335 | vi.fn(), |
| 336 | HandlerPriority.CRITICAL, |
| 337 | ); |
| 338 | selectionChangeManager.registerListener( |
| 339 | "normal", |
| 340 | vi.fn(), |
| 341 | HandlerPriority.NORMAL, |
| 342 | ); |
| 343 | |
| 344 | const privateManager = selectionChangeManager as any; |
| 345 | const priorities = privateManager.listeners.map((l: any) => l.priority); |
| 346 | |
| 347 | // Should be sorted in descending order (CRITICAL=5, NORMAL=3, LOW=2, FALLBACK=1) |
| 348 | expect(priorities[0]).toBe(HandlerPriority.CRITICAL); |
| 349 | expect(priorities[1]).toBe(HandlerPriority.NORMAL); |
| 350 | expect(priorities[2]).toBe(HandlerPriority.LOW); |
| 351 | expect(priorities[3]).toBe(HandlerPriority.FALLBACK); |
| 352 | }); |
| 353 | }); |
| 354 | |
| 355 | describe("handleSelectionChange", () => { |
| 356 | let mockEvent: vscode.TextEditorSelectionChangeEvent; |
| 357 | let mockEvent1: vscode.TextEditorSelectionChangeEvent; |
| 358 | let mockEvent2: vscode.TextEditorSelectionChangeEvent; |
| 359 | let mockEvent3: vscode.TextEditorSelectionChangeEvent; |
| 360 | |
| 361 | beforeEach(() => { |
| 362 | mockEvent = { |
| 363 | textEditor: vscode.window.activeTextEditor!, |
| 364 | selections: [ |
| 365 | new vscode.Selection( |
| 366 | new vscode.Position(2, 5), |
| 367 | new vscode.Position(2, 5), |
| 368 | ), |
| 369 | ], |
| 370 | kind: undefined, |
| 371 | }; |
| 372 | |
| 373 | mockEvent1 = { |
| 374 | textEditor: vscode.window.activeTextEditor!, |
| 375 | selections: [ |
| 376 | new vscode.Selection( |
| 377 | new vscode.Position(0, 0), |
| 378 | new vscode.Position(0, 1), |
| 379 | ), |
| 380 | ], |
| 381 | kind: undefined, |
| 382 | }; |
| 383 | |
| 384 | mockEvent2 = { |
| 385 | textEditor: vscode.window.activeTextEditor!, |
| 386 | selections: [ |
| 387 | new vscode.Selection( |
| 388 | new vscode.Position(1, 0), |
| 389 | new vscode.Position(2, 5), |
| 390 | ), |
| 391 | ], |
| 392 | kind: undefined, |
| 393 | }; |
| 394 | |
| 395 | mockEvent3 = { |
| 396 | textEditor: vscode.window.activeTextEditor!, |
| 397 | selections: [ |
| 398 | new vscode.Selection( |
| 399 | new vscode.Position(2, 0), |
| 400 | new vscode.Position(2, 5), |
| 401 | ), |
| 402 | ], |
| 403 | kind: undefined, |
| 404 | }; |
| 405 | }); |
| 406 | |
| 407 | it("should queue event if already processing", async () => { |
| 408 | vi.useFakeTimers(); |
| 409 | |
| 410 | // Mock Date.now to work with fake timers |
| 411 | const mockDateNow = vi.spyOn(Date, "now"); |
| 412 | let currentTime = 1000; // Start at some arbitrary time |
| 413 | mockDateNow.mockImplementation(() => currentTime); |
| 414 | |
| 415 | let firstHandlerResolve: (value: boolean) => void; |
| 416 | let handlerCallCount = 0; |
| 417 | |
| 418 | const slowHandler = vi.fn().mockImplementation(() => { |
| 419 | handlerCallCount++; |
| 420 | if (handlerCallCount === 1) { |
| 421 | return new Promise<boolean>((resolve) => { |
| 422 | firstHandlerResolve = resolve; |
| 423 | }); |
| 424 | } else { |
| 425 | return Promise.resolve(true); |
| 426 | } |
| 427 | }); |
| 428 | |
| 429 | selectionChangeManager.registerListener( |
| 430 | "slowHandler", |
| 431 | slowHandler, |
| 432 | HandlerPriority.HIGH, |
| 433 | ); |
| 434 | |
| 435 | // First event - should bypass debouncing and start processing immediately |
| 436 | const firstEventPromise = |
| 437 | selectionChangeManager.handleSelectionChange(mockEvent1); |
| 438 | |
| 439 | // Advance time to simulate the first event being processed |
| 440 | currentTime += 10; // Small increment to simulate processing start |
| 441 | vi.advanceTimersByTime(10); |
| 442 | |
| 443 | expect(slowHandler).toHaveBeenCalledTimes(1); |
| 444 | |
| 445 | // Second event comes quickly (within DEBOUNCE_DELAY of 50ms) |
| 446 | currentTime += 10; // Total elapsed: 10ms (< 50ms DEBOUNCE_DELAY) |
| 447 | const secondEventPromise = |
| 448 | selectionChangeManager.handleSelectionChange(mockEvent2); |
| 449 | |
| 450 | // The second event should be queued due to isProcessingEvent = true, not debouncing |
| 451 | expect(slowHandler).toHaveBeenCalledTimes(1); // Still only called once |
| 452 | |
| 453 | // Third event comes within debounce window, replacing the second event. |
| 454 | currentTime += 10; // Total elapsed: 30ms (< 50ms DEBOUNCE_DELAY) |
| 455 | const thirdEventPromise = |
| 456 | selectionChangeManager.handleSelectionChange(mockEvent3); |
| 457 | |
| 458 | // Still should only be called once |
| 459 | expect(slowHandler).toHaveBeenCalledTimes(1); |
| 460 | |
| 461 | // Now resolve the first handler to allow queued events to process |
| 462 | firstHandlerResolve!(true); |
| 463 | |
| 464 | // Advance time to allow any pending timers to resolve |
| 465 | vi.advanceTimersByTime(100); |
| 466 | |
| 467 | // Wait for all events to complete |
| 468 | await Promise.all([ |
| 469 | firstEventPromise, |
| 470 | secondEventPromise, |
| 471 | thirdEventPromise, |
| 472 | ]); |
| 473 | |
| 474 | // Should have been called twice total: |
| 475 | // - Once for the first event |
| 476 | // - Once for the last queued event (debouncing replaces earlier queued events) |
| 477 | expect(slowHandler).toHaveBeenCalledTimes(2); |
| 478 | |
| 479 | mockDateNow.mockRestore(); |
| 480 | vi.useRealTimers(); |
| 481 | }); |
| 482 | |
| 483 | it("should implement debouncing for rapid events", async () => { |
| 484 | vi.useFakeTimers(); |
| 485 | |
| 486 | const mockHandler = vi.fn().mockResolvedValue(true); |
| 487 | selectionChangeManager.registerListener( |
| 488 | "testHandler", |
| 489 | mockHandler, |
| 490 | HandlerPriority.HIGH, |
| 491 | ); |
| 492 | |
| 493 | // Fire multiple events rapidly |
| 494 | selectionChangeManager.handleSelectionChange(mockEvent); |
| 495 | selectionChangeManager.handleSelectionChange(mockEvent); |
| 496 | selectionChangeManager.handleSelectionChange(mockEvent); |
| 497 | |
| 498 | // Only the last event should be queued due to debouncing |
| 499 | const privateManager = selectionChangeManager as any; |
| 500 | expect(privateManager.eventQueue).toHaveLength(1); |
| 501 | |
| 502 | vi.useRealTimers(); |
| 503 | }); |
| 504 | |
| 505 | it("should handle timeout for slow processing", async () => { |
| 506 | vi.useFakeTimers(); |
| 507 | |
| 508 | const slowHandler = vi.fn().mockImplementation( |
| 509 | () => |
| 510 | new Promise((resolve) => |
| 511 | setTimeout(() => { |
| 512 | console.log("Slow handler resolving"); |
| 513 | resolve(true); |
| 514 | }, 1000), |
| 515 | ), |
| 516 | ); |
| 517 | |
| 518 | selectionChangeManager.registerListener( |
| 519 | "slowHandler", |
| 520 | slowHandler, |
| 521 | HandlerPriority.HIGH, |
| 522 | ); |
| 523 | |
| 524 | const consoleErrorSpy = vi |
| 525 | .spyOn(console, "error") |
| 526 | .mockImplementation(() => {}); |
| 527 | |
| 528 | // Start processing and advance past timeout |
| 529 | console.log("Starting event processing"); |
| 530 | const eventPromise = |
| 531 | selectionChangeManager.handleSelectionChange(mockEvent); |
| 532 | |
| 533 | console.log("Advancing timers by 600ms"); |
| 534 | vi.advanceTimersByTime(700); // PROCESSING_TIMEOUT is 500ms |
| 535 | |
| 536 | try { |
| 537 | await eventPromise; |
| 538 | console.log("Event promise resolved successfully"); |
| 539 | } catch (error) { |
| 540 | console.log("Event promise rejected:", error); |
| 541 | } |
| 542 | |
| 543 | console.log("Console error calls:", consoleErrorSpy.mock.calls); |
| 544 | expect(consoleErrorSpy).toHaveBeenCalled(); |
| 545 | |
| 546 | consoleErrorSpy.mockRestore(); |
| 547 | vi.useRealTimers(); |
| 548 | }); |
| 549 | |
| 550 | it("should handle errors in handlers gracefully", async () => { |
| 551 | const errorHandler = vi |
| 552 | .fn() |
| 553 | .mockRejectedValue(new Error("Handler error")); |
| 554 | const goodHandler = vi.fn().mockResolvedValue(true); |
| 555 | |
| 556 | selectionChangeManager.registerListener( |
| 557 | "errorHandler", |
| 558 | errorHandler, |
| 559 | HandlerPriority.HIGH, |
| 560 | ); |
| 561 | selectionChangeManager.registerListener( |
| 562 | "goodHandler", |
| 563 | goodHandler, |
| 564 | HandlerPriority.NORMAL, |
| 565 | ); |
| 566 | |
| 567 | const consoleErrorSpy = vi |
| 568 | .spyOn(console, "error") |
| 569 | .mockImplementation(() => {}); |
| 570 | |
| 571 | await selectionChangeManager.handleSelectionChange(mockEvent); |
| 572 | |
| 573 | expect(errorHandler).toHaveBeenCalled(); |
| 574 | expect(goodHandler).toHaveBeenCalled(); |
| 575 | expect(consoleErrorSpy).toHaveBeenCalledWith( |
| 576 | "Error in selection change handler:", |
| 577 | expect.any(Error), |
| 578 | ); |
| 579 | |
| 580 | consoleErrorSpy.mockRestore(); |
| 581 | }); |
| 582 | }); |
| 583 | |
| 584 | describe("captureState", () => { |
| 585 | beforeEach(() => { |
| 586 | vi.resetAllMocks(); |
| 587 | |
| 588 | // Explicitly set up the mocks. For some reason the toplevel mock leaves these as undefined. |
| 589 | vi.mocked(NextEditWindowManager.isInstantiated).mockReturnValue(false); |
| 590 | vi.mocked(NextEditWindowManager.getInstance).mockReturnValue({ |
| 591 | hasAccepted: vi.fn().mockReturnValue(false), |
| 592 | } as any); |
| 593 | |
| 594 | vi.mocked(JumpManager.getInstance).mockReturnValue({ |
| 595 | isJumpInProgress: vi.fn().mockReturnValue(false), |
| 596 | wasJumpJustAccepted: vi.fn().mockReturnValue(false), |
| 597 | } as any); |
| 598 | }); |
| 599 | |
| 600 | it("should capture current state snapshot", () => { |
| 601 | const mockEvent: vscode.TextEditorSelectionChangeEvent = { |
| 602 | textEditor: vscode.window.activeTextEditor!, |
| 603 | selections: [ |
| 604 | new vscode.Selection( |
| 605 | new vscode.Position(2, 5), |
| 606 | new vscode.Position(2, 5), |
| 607 | ), |
| 608 | ], |
| 609 | kind: undefined, |
| 610 | }; |
| 611 | |
| 612 | // Setup some state |
| 613 | selectionChangeManager.documentChanged(); |
| 614 | |
| 615 | const privateManager = selectionChangeManager as any; |
| 616 | const state = privateManager.captureState(mockEvent); |
| 617 | |
| 618 | expect(state).toEqual({ |
| 619 | nextEditWindowAccepted: false, |
| 620 | jumpInProgress: false, |
| 621 | jumpJustAccepted: false, |
| 622 | lastDocumentChangeTime: expect.any(Number), |
| 623 | isTypingSession: true, |
| 624 | document: mockEvent.textEditor.document, |
| 625 | cursorPosition: mockEvent.selections[0].active, |
| 626 | }); |
| 627 | }); |
| 628 | |
| 629 | it("should reflect NextEditWindowManager acceptance state", () => { |
| 630 | vi.mocked(NextEditWindowManager.isInstantiated).mockReturnValue(true); |
| 631 | vi.mocked(NextEditWindowManager.getInstance).mockReturnValue({ |
| 632 | hasAccepted: vi.fn().mockReturnValue(true), |
| 633 | } as any); |
| 634 | |
| 635 | const mockEvent: vscode.TextEditorSelectionChangeEvent = { |
| 636 | textEditor: vscode.window.activeTextEditor!, |
| 637 | selections: [ |
| 638 | new vscode.Selection( |
| 639 | new vscode.Position(2, 5), |
| 640 | new vscode.Position(2, 5), |
| 641 | ), |
| 642 | ], |
| 643 | kind: undefined, |
| 644 | }; |
| 645 | |
| 646 | const privateManager = selectionChangeManager as any; |
| 647 | const state = privateManager.captureState(mockEvent); |
| 648 | |
| 649 | expect(state.nextEditWindowAccepted).toBe(true); |
| 650 | }); |
| 651 | |
| 652 | it("should reflect JumpManager state", () => { |
| 653 | vi.mocked(JumpManager.getInstance).mockReturnValue({ |
| 654 | isJumpInProgress: vi.fn().mockReturnValue(true), |
| 655 | wasJumpJustAccepted: vi.fn().mockReturnValue(true), |
| 656 | } as any); |
| 657 | |
| 658 | const mockEvent: vscode.TextEditorSelectionChangeEvent = { |
| 659 | textEditor: vscode.window.activeTextEditor!, |
| 660 | selections: [ |
| 661 | new vscode.Selection( |
| 662 | new vscode.Position(2, 5), |
| 663 | new vscode.Position(2, 5), |
| 664 | ), |
| 665 | ], |
| 666 | kind: undefined, |
| 667 | }; |
| 668 | |
| 669 | const privateManager = selectionChangeManager as any; |
| 670 | const state = privateManager.captureState(mockEvent); |
| 671 | |
| 672 | expect(state.jumpInProgress).toBe(true); |
| 673 | expect(state.jumpJustAccepted).toBe(true); |
| 674 | }); |
| 675 | }); |
| 676 | |
| 677 | describe("defaultFallbackHandler", () => { |
| 678 | it("should call deleteChain on NextEditProvider", async () => { |
| 679 | const mockEvent: vscode.TextEditorSelectionChangeEvent = { |
| 680 | textEditor: { |
| 681 | ...vscode.window.activeTextEditor!, |
| 682 | document: { |
| 683 | //@ts-ignore |
| 684 | uri: { |
| 685 | toString: vi.fn().mockReturnValue("file:///test/file.ts"), |
| 686 | }, |
| 687 | }, |
| 688 | }, |
| 689 | selections: [ |
| 690 | new vscode.Selection( |
| 691 | new vscode.Position(2, 5), |
| 692 | new vscode.Position(2, 5), |
| 693 | ), |
| 694 | ], |
| 695 | kind: undefined, |
| 696 | }; |
| 697 | |
| 698 | const mockState = { |
| 699 | nextEditWindowAccepted: false, |
| 700 | jumpInProgress: false, |
| 701 | jumpJustAccepted: false, |
| 702 | lastDocumentChangeTime: Date.now(), |
| 703 | isTypingSession: false, |
| 704 | document: mockEvent.textEditor.document, |
| 705 | cursorPosition: mockEvent.selections[0].active, |
| 706 | }; |
| 707 | |
| 708 | const privateManager = selectionChangeManager as any; |
| 709 | const result = await privateManager.defaultFallbackHandler( |
| 710 | mockEvent, |
| 711 | mockState, |
| 712 | ); |
| 713 | |
| 714 | expect(mockDeleteChain).toHaveBeenCalled(); |
| 715 | expect(result).toBe(true); |
| 716 | }); |
| 717 | |
| 718 | it("should handle missing IDE gracefully", async () => { |
| 719 | const mockEvent: vscode.TextEditorSelectionChangeEvent = { |
| 720 | textEditor: vscode.window.activeTextEditor!, |
| 721 | selections: [ |
| 722 | new vscode.Selection( |
| 723 | new vscode.Position(2, 5), |
| 724 | new vscode.Position(2, 5), |
| 725 | ), |
| 726 | ], |
| 727 | kind: undefined, |
| 728 | }; |
| 729 | |
| 730 | const mockState = { |
| 731 | nextEditWindowAccepted: false, |
| 732 | jumpInProgress: false, |
| 733 | jumpJustAccepted: false, |
| 734 | lastDocumentChangeTime: Date.now(), |
| 735 | isTypingSession: false, |
| 736 | document: mockEvent.textEditor.document, |
| 737 | cursorPosition: mockEvent.selections[0].active, |
| 738 | }; |
| 739 | |
| 740 | const privateManager = selectionChangeManager as any; |
| 741 | privateManager.ide = null; |
| 742 | |
| 743 | const consoleErrorSpy = vi |
| 744 | .spyOn(console, "error") |
| 745 | .mockImplementation(() => {}); |
| 746 | |
| 747 | const result = await privateManager.defaultFallbackHandler( |
| 748 | mockEvent, |
| 749 | mockState, |
| 750 | ); |
| 751 | |
| 752 | expect(consoleErrorSpy).toHaveBeenCalledWith( |
| 753 | "IDE not initialized in SelectionChangeManager", |
| 754 | ); |
| 755 | expect(result).toBe(false); |
| 756 | |
| 757 | consoleErrorSpy.mockRestore(); |
| 758 | }); |
| 759 | |
| 760 | it("should prefetch editable regions when not using full file diff", async () => { |
| 761 | // Initialize with usingFullFileDiff = false |
| 762 | const newManager = SelectionChangeManager.getInstance(); |
| 763 | newManager.initialize(mockIde, false); |
| 764 | |
| 765 | const mockEvent: vscode.TextEditorSelectionChangeEvent = { |
| 766 | textEditor: { |
| 767 | ...vscode.window.activeTextEditor!, |
| 768 | document: { |
| 769 | //@ts-ignore |
| 770 | uri: { |
| 771 | toString: vi.fn().mockReturnValue("file:///test/file.ts"), |
| 772 | }, |
| 773 | }, |
| 774 | }, |
| 775 | selections: [ |
| 776 | new vscode.Selection( |
| 777 | new vscode.Position(2, 5), |
| 778 | new vscode.Position(2, 5), |
| 779 | ), |
| 780 | ], |
| 781 | kind: undefined, |
| 782 | }; |
| 783 | |
| 784 | const mockState = { |
| 785 | nextEditWindowAccepted: false, |
| 786 | jumpInProgress: false, |
| 787 | jumpJustAccepted: false, |
| 788 | lastDocumentChangeTime: Date.now(), |
| 789 | isTypingSession: false, |
| 790 | document: mockEvent.textEditor.document, |
| 791 | cursorPosition: mockEvent.selections[0].active, |
| 792 | }; |
| 793 | |
| 794 | const mockRegions = [ |
| 795 | { |
| 796 | filepath: "/test/file.ts", |
| 797 | range: { |
| 798 | start: { line: 0, character: 0 }, |
| 799 | end: { line: 0, character: 0 }, |
| 800 | }, |
| 801 | // content: "test content", |
| 802 | // cursorPosition: { line: 2, character: 5 }, |
| 803 | }, |
| 804 | ]; |
| 805 | |
| 806 | vi.mocked(getNextEditableRegion).mockResolvedValue(mockRegions); |
| 807 | |
| 808 | const privateManager = newManager as any; |
| 809 | await privateManager.defaultFallbackHandler(mockEvent, mockState); |
| 810 | |
| 811 | expect(getNextEditableRegion).toHaveBeenCalledWith( |
| 812 | EditableRegionStrategy.Static, |
| 813 | { |
| 814 | cursorPosition: mockEvent.selections[0].anchor, |
| 815 | filepath: "/test/file.ts", |
| 816 | ide: mockIde, |
| 817 | }, |
| 818 | ); |
| 819 | |
| 820 | expect(mockEnqueueUnprocessed).toHaveBeenCalledWith(mockRegions[0]); |
| 821 | }); |
| 822 | |
| 823 | it("should skip prefetching when using full file diff", async () => { |
| 824 | // Initialize with usingFullFileDiff = true |
| 825 | const newManager = SelectionChangeManager.getInstance(); |
| 826 | newManager.initialize(mockIde, true); |
| 827 | |
| 828 | const mockEvent: vscode.TextEditorSelectionChangeEvent = { |
| 829 | textEditor: vscode.window.activeTextEditor!, |
| 830 | selections: [ |
| 831 | new vscode.Selection( |
| 832 | new vscode.Position(2, 5), |
| 833 | new vscode.Position(2, 5), |
| 834 | ), |
| 835 | ], |
| 836 | kind: undefined, |
| 837 | }; |
| 838 | |
| 839 | const mockState = { |
| 840 | nextEditWindowAccepted: false, |
| 841 | jumpInProgress: false, |
| 842 | jumpJustAccepted: false, |
| 843 | lastDocumentChangeTime: Date.now(), |
| 844 | isTypingSession: false, |
| 845 | document: mockEvent.textEditor.document, |
| 846 | cursorPosition: mockEvent.selections[0].active, |
| 847 | }; |
| 848 | |
| 849 | const privateManager = newManager as any; |
| 850 | await privateManager.defaultFallbackHandler(mockEvent, mockState); |
| 851 | |
| 852 | expect(getNextEditableRegion).not.toHaveBeenCalled(); |
| 853 | expect(mockEnqueueUnprocessed).not.toHaveBeenCalled(); |
| 854 | }); |
| 855 | }); |
| 856 | |
| 857 | describe("handler execution order", () => { |
| 858 | it("should execute handlers in priority order and stop on first true return", async () => { |
| 859 | const handler1 = vi.fn().mockResolvedValue(false); |
| 860 | const handler2 = vi.fn().mockResolvedValue(true); |
| 861 | const handler3 = vi.fn().mockResolvedValue(false); |
| 862 | const fallbackHandler = vi.fn().mockResolvedValue(true); |
| 863 | |
| 864 | selectionChangeManager.registerListener( |
| 865 | "handler1", |
| 866 | handler1, |
| 867 | HandlerPriority.CRITICAL, |
| 868 | ); |
| 869 | selectionChangeManager.registerListener( |
| 870 | "handler2", |
| 871 | handler2, |
| 872 | HandlerPriority.HIGH, |
| 873 | ); |
| 874 | selectionChangeManager.registerListener( |
| 875 | "handler3", |
| 876 | handler3, |
| 877 | HandlerPriority.NORMAL, |
| 878 | ); |
| 879 | |
| 880 | const mockEvent: vscode.TextEditorSelectionChangeEvent = { |
| 881 | textEditor: vscode.window.activeTextEditor!, |
| 882 | selections: [ |
| 883 | new vscode.Selection( |
| 884 | new vscode.Position(2, 5), |
| 885 | new vscode.Position(2, 5), |
| 886 | ), |
| 887 | ], |
| 888 | kind: undefined, |
| 889 | }; |
| 890 | |
| 891 | await selectionChangeManager.handleSelectionChange(mockEvent); |
| 892 | |
| 893 | expect(handler1).toHaveBeenCalled(); |
| 894 | expect(handler2).toHaveBeenCalled(); |
| 895 | expect(handler3).not.toHaveBeenCalled(); // Should not be called because handler2 returned true |
| 896 | expect(mockDeleteChain).not.toHaveBeenCalled(); // Fallback should not run |
| 897 | }); |
| 898 | }); |
| 899 | }); |