| 1 | import { |
| 2 | afterEach, |
| 3 | beforeEach, |
| 4 | describe, |
| 5 | expect, |
| 6 | it, |
| 7 | MockedFunction, |
| 8 | vi, |
| 9 | } from "vitest"; |
| 10 | |
| 11 | // Mock all modules FIRST with inline factories (no external references) |
| 12 | vi.mock("vscode", () => ({ |
| 13 | commands: { |
| 14 | executeCommand: vi.fn(), |
| 15 | registerCommand: vi.fn(), |
| 16 | }, |
| 17 | window: { |
| 18 | activeTextEditor: undefined, |
| 19 | visibleTextEditors: [], |
| 20 | createTextEditorDecorationType: vi.fn(), |
| 21 | onDidChangeTextEditorSelection: vi.fn(() => ({ dispose: vi.fn() })), |
| 22 | onDidChangeVisibleTextEditors: vi.fn(() => ({ dispose: vi.fn() })), |
| 23 | onDidChangeActiveColorTheme: vi.fn(() => ({ dispose: vi.fn() })), |
| 24 | showInformationMessage: vi.fn(), |
| 25 | }, |
| 26 | workspace: { |
| 27 | getConfiguration: vi.fn(() => ({ |
| 28 | get: vi.fn((key: string) => { |
| 29 | const config: Record<string, any> = { |
| 30 | fontSize: 14, |
| 31 | fontFamily: "monospace", |
| 32 | showInlineTip: true, |
| 33 | }; |
| 34 | return config[key]; |
| 35 | }), |
| 36 | })), |
| 37 | onDidChangeConfiguration: vi.fn(() => ({ dispose: vi.fn() })), |
| 38 | }, |
| 39 | Position: class { |
| 40 | constructor( |
| 41 | public line: number, |
| 42 | public character: number, |
| 43 | ) {} |
| 44 | }, |
| 45 | Range: class { |
| 46 | constructor( |
| 47 | public start: any, |
| 48 | public end: any, |
| 49 | ) {} |
| 50 | }, |
| 51 | Selection: class { |
| 52 | constructor( |
| 53 | public anchor: any, |
| 54 | public active: any, |
| 55 | ) {} |
| 56 | }, |
| 57 | Uri: { |
| 58 | parse: vi.fn((str: string) => ({ toString: () => str, scheme: "file" })), |
| 59 | }, |
| 60 | DecorationRangeBehavior: { |
| 61 | ClosedClosed: 1, |
| 62 | }, |
| 63 | MarkdownString: class { |
| 64 | value: string = ""; |
| 65 | isTrusted: boolean = false; |
| 66 | supportHtml: boolean = false; |
| 67 | constructor(value: string) { |
| 68 | this.value = value; |
| 69 | } |
| 70 | }, |
| 71 | ExtensionContext: class { |
| 72 | subscriptions: any[] = []; |
| 73 | }, |
| 74 | ViewColumn: { |
| 75 | One: 1, |
| 76 | Two: 2, |
| 77 | }, |
| 78 | })); |
| 79 | |
| 80 | vi.mock("core/control-plane/env", () => ({ |
| 81 | EXTENSION_NAME: "continue", |
| 82 | })); |
| 83 | |
| 84 | vi.mock("../util/getTheme", () => ({ |
| 85 | getThemeString: vi.fn(() => "dark"), |
| 86 | })); |
| 87 | |
| 88 | vi.mock("core/codeRenderer/CodeRenderer", () => ({ |
| 89 | CodeRenderer: { |
| 90 | getInstance: vi.fn(() => ({ |
| 91 | setTheme: vi.fn(), |
| 92 | getDataUri: vi.fn().mockResolvedValue("data:image/svg+xml;base64,mock"), |
| 93 | })), |
| 94 | }, |
| 95 | })); |
| 96 | |
| 97 | vi.mock("core/nextEdit/NextEditProvider", () => ({ |
| 98 | NextEditProvider: { |
| 99 | getInstance: vi.fn(() => ({ |
| 100 | deleteChain: vi.fn(), |
| 101 | })), |
| 102 | }, |
| 103 | })); |
| 104 | |
| 105 | vi.mock("core/nextEdit/NextEditLoggingService", () => ({ |
| 106 | NextEditLoggingService: { |
| 107 | getInstance: vi.fn(() => ({ |
| 108 | cancelRejectionTimeout: vi.fn(), |
| 109 | cancelRejectionTimeoutButKeepCompletionId: vi.fn(), |
| 110 | })), |
| 111 | }, |
| 112 | })); |
| 113 | |
| 114 | vi.mock("core/diff/myers", () => ({ |
| 115 | myersCharDiff: vi.fn(() => []), |
| 116 | })); |
| 117 | |
| 118 | vi.mock("core/nextEdit/diff/diff", () => ({ |
| 119 | getOffsetPositionAtLastNewLine: vi.fn(() => ({ line: 0, character: 0 })), |
| 120 | })); |
| 121 | |
| 122 | // Import after mocks are set up |
| 123 | import * as vscode from "vscode"; |
| 124 | |
| 125 | import { |
| 126 | ACCEPT_NEXT_EDIT_SUGGESTION_COMMAND, |
| 127 | HIDE_NEXT_EDIT_SUGGESTION_COMMAND, |
| 128 | NextEditWindowManager, |
| 129 | } from "./NextEditWindowManager"; |
| 130 | |
| 131 | const mockVscode = vi.mocked(vscode); |
| 132 | |
| 133 | describe("NextEditWindowManager", () => { |
| 134 | let manager: NextEditWindowManager; |
| 135 | let mockEditor: any; |
| 136 | let mockDocument: any; |
| 137 | let mockContext: any; |
| 138 | |
| 139 | beforeEach(() => { |
| 140 | vi.clearAllMocks(); |
| 141 | |
| 142 | // Clear singleton instance |
| 143 | NextEditWindowManager.clearInstance(); |
| 144 | |
| 145 | // Create mock document |
| 146 | mockDocument = { |
| 147 | uri: { toString: () => "file:///test.ts", scheme: "file" }, |
| 148 | version: 1, |
| 149 | lineCount: 10, |
| 150 | lineAt: vi.fn((line: number) => ({ |
| 151 | text: `line ${line} content`, |
| 152 | range: new mockVscode.Range( |
| 153 | new mockVscode.Position(line, 0), |
| 154 | new mockVscode.Position(line, 20), |
| 155 | ), |
| 156 | })), |
| 157 | }; |
| 158 | |
| 159 | // Create mock editor |
| 160 | mockEditor = { |
| 161 | document: mockDocument, |
| 162 | selection: { |
| 163 | active: new mockVscode.Position(0, 0), |
| 164 | }, |
| 165 | setDecorations: vi.fn(), |
| 166 | edit: vi.fn((callback: any) => { |
| 167 | callback({ |
| 168 | replace: vi.fn(), |
| 169 | delete: vi.fn(), |
| 170 | }); |
| 171 | return Promise.resolve(true); |
| 172 | }), |
| 173 | }; |
| 174 | |
| 175 | // Create mock context |
| 176 | mockContext = { |
| 177 | subscriptions: [], |
| 178 | }; |
| 179 | |
| 180 | // Setup default mock implementations |
| 181 | ( |
| 182 | mockVscode.commands.executeCommand as MockedFunction<any> |
| 183 | ).mockResolvedValue(undefined); |
| 184 | (mockVscode.commands.registerCommand as MockedFunction<any>) |
| 185 | //@ts-ignore |
| 186 | .mockImplementation((command: string, callback: any) => ({ |
| 187 | dispose: vi.fn(), |
| 188 | })); |
| 189 | ( |
| 190 | mockVscode.window.createTextEditorDecorationType as MockedFunction<any> |
| 191 | ).mockReturnValue({ |
| 192 | dispose: vi.fn(), |
| 193 | }); |
| 194 | |
| 195 | // Get manager instance |
| 196 | manager = NextEditWindowManager.getInstance(); |
| 197 | }); |
| 198 | |
| 199 | afterEach(() => { |
| 200 | NextEditWindowManager.clearInstance(); |
| 201 | }); |
| 202 | |
| 203 | describe("Singleton Pattern", () => { |
| 204 | it("should return the same instance", () => { |
| 205 | const instance1 = NextEditWindowManager.getInstance(); |
| 206 | const instance2 = NextEditWindowManager.getInstance(); |
| 207 | expect(instance1).toBe(instance2); |
| 208 | }); |
| 209 | |
| 210 | it("should properly clear instance", () => { |
| 211 | const instance1 = NextEditWindowManager.getInstance(); |
| 212 | NextEditWindowManager.clearInstance(); |
| 213 | const instance2 = NextEditWindowManager.getInstance(); |
| 214 | expect(instance1).not.toBe(instance2); |
| 215 | }); |
| 216 | }); |
| 217 | |
| 218 | describe("Key Reservation State Management", () => { |
| 219 | beforeEach(async () => { |
| 220 | await manager.setupNextEditWindowManager(mockContext); |
| 221 | }); |
| 222 | |
| 223 | it("should start with keys in free state", () => { |
| 224 | expect(manager["keyReservationState"]).toBe("free"); |
| 225 | }); |
| 226 | |
| 227 | it("should reserve keys when showing window", async () => { |
| 228 | await manager.showNextEditWindow( |
| 229 | mockEditor, |
| 230 | new mockVscode.Position(0, 0), |
| 231 | 0, |
| 232 | 0, |
| 233 | "old", |
| 234 | "new", |
| 235 | [], |
| 236 | ); |
| 237 | |
| 238 | expect(mockVscode.commands.executeCommand).toHaveBeenCalledWith( |
| 239 | "setContext", |
| 240 | "nextEditWindowActive", |
| 241 | true, |
| 242 | ); |
| 243 | expect(manager["keyReservationState"]).toBe("reserved"); |
| 244 | }); |
| 245 | |
| 246 | it("should free keys when hiding windows", async () => { |
| 247 | // First show a window |
| 248 | await manager.showNextEditWindow( |
| 249 | mockEditor, |
| 250 | new mockVscode.Position(0, 0), |
| 251 | 0, |
| 252 | 0, |
| 253 | "old", |
| 254 | "new", |
| 255 | [], |
| 256 | ); |
| 257 | |
| 258 | // Then hide it |
| 259 | await manager.hideAllNextEditWindows(); |
| 260 | |
| 261 | expect(mockVscode.commands.executeCommand).toHaveBeenCalledWith( |
| 262 | "setContext", |
| 263 | "nextEditWindowActive", |
| 264 | false, |
| 265 | ); |
| 266 | expect(manager["keyReservationState"]).toBe("free"); |
| 267 | }); |
| 268 | |
| 269 | it("should handle sequential reserve/free operations", async () => { |
| 270 | const executeCommand = mockVscode.commands |
| 271 | .executeCommand as MockedFunction<any>; |
| 272 | |
| 273 | await NextEditWindowManager.reserveTabAndEsc(); |
| 274 | expect(manager["keyReservationState"]).toBe("reserved"); |
| 275 | |
| 276 | await NextEditWindowManager.freeTabAndEsc(); |
| 277 | expect(manager["keyReservationState"]).toBe("free"); |
| 278 | |
| 279 | await NextEditWindowManager.reserveTabAndEsc(); |
| 280 | expect(manager["keyReservationState"]).toBe("reserved"); |
| 281 | |
| 282 | // Should have been called 3 times + 1 from beforeEach |
| 283 | expect(executeCommand).toHaveBeenCalledTimes(4); |
| 284 | }); |
| 285 | |
| 286 | it("should skip redundant reserve operations", async () => { |
| 287 | const executeCommand = mockVscode.commands |
| 288 | .executeCommand as MockedFunction<any>; |
| 289 | |
| 290 | await NextEditWindowManager.reserveTabAndEsc(); |
| 291 | executeCommand.mockClear(); |
| 292 | |
| 293 | // Try to reserve again |
| 294 | await NextEditWindowManager.reserveTabAndEsc(); |
| 295 | |
| 296 | // Should not have called executeCommand again |
| 297 | expect(executeCommand).not.toHaveBeenCalled(); |
| 298 | expect(manager["keyReservationState"]).toBe("reserved"); |
| 299 | }); |
| 300 | |
| 301 | it("should skip redundant free operations", async () => { |
| 302 | const executeCommand = mockVscode.commands |
| 303 | .executeCommand as MockedFunction<any>; |
| 304 | executeCommand.mockClear(); |
| 305 | |
| 306 | // Already free, try to free again |
| 307 | await NextEditWindowManager.freeTabAndEsc(); |
| 308 | |
| 309 | // Should not have called executeCommand |
| 310 | expect(executeCommand).not.toHaveBeenCalled(); |
| 311 | expect(manager["keyReservationState"]).toBe("free"); |
| 312 | }); |
| 313 | }); |
| 314 | |
| 315 | describe("Race Condition Prevention", () => { |
| 316 | beforeEach(async () => { |
| 317 | await manager.setupNextEditWindowManager(mockContext); |
| 318 | }); |
| 319 | |
| 320 | it("should handle concurrent operations with random delays and last-write-wins", async () => { |
| 321 | const executeCommand = mockVscode.commands |
| 322 | .executeCommand as MockedFunction<any>; |
| 323 | let completedOperations: string[] = []; |
| 324 | |
| 325 | // Reset key reservation to ensure clean state |
| 326 | await manager.resetKeyReservation(); |
| 327 | |
| 328 | // Start from reserved state so first free() will proceed |
| 329 | manager["keyReservationState"] = "reserved"; |
| 330 | executeCommand.mockClear(); |
| 331 | |
| 332 | // Make executeCommand take random time and track completions |
| 333 | executeCommand.mockImplementation((cmd, key, value) => { |
| 334 | const operationId = `${value ? "reserve" : "free"}-${Date.now()}-${Math.random()}`; |
| 335 | return new Promise((resolve) => { |
| 336 | setTimeout(() => { |
| 337 | completedOperations.push(operationId); |
| 338 | // Immediately update state to ensure next operation proceeds |
| 339 | // This simulates fast state changes |
| 340 | manager["keyReservationState"] = value ? "reserved" : "free"; |
| 341 | resolve(undefined); |
| 342 | }, Math.random() * 50); |
| 343 | }); |
| 344 | }); |
| 345 | |
| 346 | // Fire multiple operations concurrently |
| 347 | const operations = [ |
| 348 | NextEditWindowManager.reserveTabAndEsc(), // operation 1: reserve (skipped - already reserved) |
| 349 | NextEditWindowManager.freeTabAndEsc(), // operation 2: free (proceeds) |
| 350 | NextEditWindowManager.reserveTabAndEsc(), // operation 3: reserve (proceeds after 2 completes) |
| 351 | NextEditWindowManager.freeTabAndEsc(), // operation 4: free (proceeds after 3 completes) |
| 352 | ]; |
| 353 | |
| 354 | await Promise.all(operations); |
| 355 | |
| 356 | // Count how many actually proceeded (those that didn't early return) |
| 357 | const actualCalls = executeCommand.mock.calls.length; |
| 358 | |
| 359 | // The state should match the last operation's intent |
| 360 | // But the actual number of calls depends on timing and early returns |
| 361 | expect(manager["latestOperationId"]).toBeGreaterThanOrEqual(actualCalls); |
| 362 | }); |
| 363 | |
| 364 | it("should ignore stale operations", async () => { |
| 365 | const executeCommand = mockVscode.commands |
| 366 | .executeCommand as MockedFunction<any>; |
| 367 | |
| 368 | await manager.resetKeyReservation(); |
| 369 | executeCommand.mockClear(); |
| 370 | |
| 371 | // Create deferred promises with guaranteed resolvers |
| 372 | const createDeferred = () => { |
| 373 | let resolve: Function; |
| 374 | const promise = new Promise((res) => { |
| 375 | resolve = res; |
| 376 | }); |
| 377 | return { promise, resolve: resolve! }; |
| 378 | }; |
| 379 | |
| 380 | const deferred1 = createDeferred(); |
| 381 | const deferred2 = createDeferred(); |
| 382 | |
| 383 | // Control when each operation completes |
| 384 | executeCommand |
| 385 | .mockImplementationOnce(() => deferred1.promise) |
| 386 | .mockImplementationOnce(() => deferred2.promise); |
| 387 | |
| 388 | // Start operations |
| 389 | const op1 = NextEditWindowManager.reserveTabAndEsc(); |
| 390 | const op2 = NextEditWindowManager.freeTabAndEsc(); |
| 391 | |
| 392 | // Complete op2 first (even though op1 started first) |
| 393 | deferred2.resolve(undefined); |
| 394 | await op2; |
| 395 | |
| 396 | // State should be free (from op2) |
| 397 | expect(manager["keyReservationState"]).toBe("free"); |
| 398 | expect(manager["latestOperationId"]).toBe(2); |
| 399 | |
| 400 | // Now complete op1 (should be ignored as stale) |
| 401 | deferred1.resolve(undefined); |
| 402 | await op1; |
| 403 | |
| 404 | // State should still be free (op1 was ignored) |
| 405 | expect(manager["keyReservationState"]).toBe("free"); |
| 406 | expect(manager["latestOperationId"]).toBe(2); |
| 407 | }); |
| 408 | |
| 409 | it("should handle rapid fire operations correctly (loop)", async () => { |
| 410 | const executeCommand = mockVscode.commands |
| 411 | .executeCommand as MockedFunction<any>; |
| 412 | |
| 413 | await manager.resetKeyReservation(); |
| 414 | executeCommand.mockClear(); |
| 415 | |
| 416 | // Make operations instant |
| 417 | executeCommand.mockResolvedValue(undefined); |
| 418 | |
| 419 | // Fire many operations rapidly |
| 420 | const operations = []; |
| 421 | for (let i = 0; i < 20; i++) { |
| 422 | operations.push( |
| 423 | i % 2 === 0 |
| 424 | ? NextEditWindowManager.reserveTabAndEsc() |
| 425 | : NextEditWindowManager.freeTabAndEsc(), |
| 426 | ); |
| 427 | } |
| 428 | |
| 429 | await Promise.all(operations); |
| 430 | |
| 431 | // Last operation (i=19) was free (odd number) |
| 432 | expect(manager["keyReservationState"]).toBe("free"); |
| 433 | expect(manager["latestOperationId"]).toBe(20); |
| 434 | }); |
| 435 | |
| 436 | it("should handle alternating reserve/free with delays", async () => { |
| 437 | const executeCommand = mockVscode.commands |
| 438 | .executeCommand as MockedFunction<any>; |
| 439 | |
| 440 | await manager.resetKeyReservation(); |
| 441 | executeCommand.mockClear(); |
| 442 | |
| 443 | // Track actual VS Code context values set |
| 444 | const contextValues: boolean[] = []; |
| 445 | executeCommand.mockImplementation((cmd, key, value) => { |
| 446 | if (cmd === "setContext") { |
| 447 | //@ts-ignore |
| 448 | contextValues.push(value); |
| 449 | } |
| 450 | return Promise.resolve(undefined); |
| 451 | }); |
| 452 | |
| 453 | // Alternating operations |
| 454 | await NextEditWindowManager.reserveTabAndEsc(); |
| 455 | expect(manager["keyReservationState"]).toBe("reserved"); |
| 456 | |
| 457 | await NextEditWindowManager.freeTabAndEsc(); |
| 458 | expect(manager["keyReservationState"]).toBe("free"); |
| 459 | |
| 460 | await NextEditWindowManager.reserveTabAndEsc(); |
| 461 | expect(manager["keyReservationState"]).toBe("reserved"); |
| 462 | |
| 463 | // Check that context was set correctly each time |
| 464 | expect(contextValues).toEqual([true, false, true]); |
| 465 | }); |
| 466 | |
| 467 | it("should handle rapid alternations correctly", async () => { |
| 468 | const executeCommand = mockVscode.commands |
| 469 | .executeCommand as MockedFunction<any>; |
| 470 | |
| 471 | await manager.resetKeyReservation(); |
| 472 | executeCommand.mockClear(); |
| 473 | |
| 474 | // Track all setContext calls |
| 475 | const contextCalls: boolean[] = []; |
| 476 | executeCommand.mockImplementation((cmd, key, value) => { |
| 477 | if (cmd === "setContext" && key === "nextEditWindowActive") { |
| 478 | //@ts-ignore |
| 479 | contextCalls.push(value); |
| 480 | } |
| 481 | return Promise.resolve(); |
| 482 | }); |
| 483 | |
| 484 | // Simulate rapid SEQUENTIAL user interactions: |
| 485 | // These need to be sequential to ensure state changes between calls |
| 486 | await NextEditWindowManager.reserveTabAndEsc(); // free -> reserved |
| 487 | await NextEditWindowManager.freeTabAndEsc(); // reserved -> free |
| 488 | await NextEditWindowManager.reserveTabAndEsc(); // free -> reserved |
| 489 | await NextEditWindowManager.freeTabAndEsc(); // reserved -> free |
| 490 | |
| 491 | // Should end in free state (last operation) |
| 492 | expect(manager["keyReservationState"]).toBe("free"); |
| 493 | |
| 494 | // Should have made all 4 calls since state alternates |
| 495 | expect(contextCalls).toEqual([true, false, true, false]); |
| 496 | }); |
| 497 | |
| 498 | it("should handle concurrent duplicate operations efficiently", async () => { |
| 499 | const executeCommand = mockVscode.commands |
| 500 | .executeCommand as MockedFunction<any>; |
| 501 | |
| 502 | await manager.resetKeyReservation(); |
| 503 | executeCommand.mockClear(); |
| 504 | |
| 505 | // Track all setContext calls |
| 506 | const contextCalls: boolean[] = []; |
| 507 | executeCommand.mockImplementation((cmd, key, value) => { |
| 508 | if (cmd === "setContext" && key === "nextEditWindowActive") { |
| 509 | //@ts-ignore |
| 510 | contextCalls.push(value); |
| 511 | } |
| 512 | return Promise.resolve(); |
| 513 | }); |
| 514 | |
| 515 | // When multiple reserve operations happen concurrently (e.g., multiple completions) |
| 516 | // Only the first should actually make the call |
| 517 | const operations = [ |
| 518 | NextEditWindowManager.reserveTabAndEsc(), |
| 519 | NextEditWindowManager.reserveTabAndEsc(), |
| 520 | NextEditWindowManager.reserveTabAndEsc(), |
| 521 | ]; |
| 522 | |
| 523 | await Promise.all(operations); |
| 524 | |
| 525 | // Should have made only the necessary calls |
| 526 | // Since all start with state "free", all will proceed to call setContext |
| 527 | // This is because they all check state before any completes |
| 528 | expect(contextCalls.length).toBeGreaterThan(0); |
| 529 | expect(manager["keyReservationState"]).toBe("reserved"); |
| 530 | |
| 531 | // All calls should be trying to reserve (true) |
| 532 | expect(contextCalls.every((call) => call === true)).toBe(true); |
| 533 | }); |
| 534 | |
| 535 | it("should handle truly concurrent mixed operations", async () => { |
| 536 | const executeCommand = mockVscode.commands |
| 537 | .executeCommand as MockedFunction<any>; |
| 538 | |
| 539 | await manager.resetKeyReservation(); |
| 540 | // Start in reserved state |
| 541 | await NextEditWindowManager.reserveTabAndEsc(); |
| 542 | executeCommand.mockClear(); |
| 543 | |
| 544 | // Track all setContext calls |
| 545 | const contextCalls: boolean[] = []; |
| 546 | executeCommand.mockImplementation((cmd, key, value) => { |
| 547 | if (cmd === "setContext" && key === "nextEditWindowActive") { |
| 548 | //@ts-ignore |
| 549 | contextCalls.push(value); |
| 550 | // Add small delay to simulate real async behavior |
| 551 | return new Promise((resolve) => setTimeout(resolve, 5)); |
| 552 | } |
| 553 | return Promise.resolve(); |
| 554 | }); |
| 555 | |
| 556 | // Mix of operations starting from "reserved" state |
| 557 | const operations = [ |
| 558 | NextEditWindowManager.freeTabAndEsc(), // Will proceed (reserved -> free) |
| 559 | NextEditWindowManager.freeTabAndEsc(), // Will proceed (checks while first is in flight) |
| 560 | NextEditWindowManager.reserveTabAndEsc(), // Will proceed (different operation) |
| 561 | ]; |
| 562 | |
| 563 | await Promise.all(operations); |
| 564 | |
| 565 | // The last operation to complete wins (but order is non-deterministic) |
| 566 | // State should be either "free" or "reserved" depending on completion order |
| 567 | expect(["free", "reserved"]).toContain(manager["keyReservationState"]); |
| 568 | |
| 569 | // Should have made at least some calls |
| 570 | expect(contextCalls.length).toBeGreaterThan(0); |
| 571 | }); |
| 572 | |
| 573 | it("should maintain correct state with stale operations", async () => { |
| 574 | const executeCommand = mockVscode.commands |
| 575 | .executeCommand as MockedFunction<any>; |
| 576 | |
| 577 | await manager.resetKeyReservation(); |
| 578 | executeCommand.mockClear(); |
| 579 | |
| 580 | // Create a controlled execution order |
| 581 | let resolveFirst: () => void; |
| 582 | let resolveSecond: () => void; |
| 583 | |
| 584 | const firstPromise = new Promise<void>((resolve) => { |
| 585 | resolveFirst = resolve; |
| 586 | }); |
| 587 | |
| 588 | const secondPromise = new Promise<void>((resolve) => { |
| 589 | resolveSecond = resolve; |
| 590 | }); |
| 591 | |
| 592 | executeCommand |
| 593 | .mockImplementationOnce(() => firstPromise) |
| 594 | .mockImplementationOnce(() => secondPromise); |
| 595 | |
| 596 | // Start operations |
| 597 | const op1 = NextEditWindowManager.reserveTabAndEsc(); |
| 598 | const op2 = NextEditWindowManager.freeTabAndEsc(); |
| 599 | |
| 600 | // Complete second operation first (out of order) |
| 601 | resolveSecond!(); |
| 602 | await op2; |
| 603 | |
| 604 | // State should be free (last operation to start, even though it completed first) |
| 605 | expect(manager["keyReservationState"]).toBe("free"); |
| 606 | |
| 607 | // Complete first operation |
| 608 | resolveFirst!(); |
| 609 | await op1; |
| 610 | |
| 611 | // State should still be free (op1 was stale) |
| 612 | expect(manager["keyReservationState"]).toBe("free"); |
| 613 | }); |
| 614 | }); |
| 615 | |
| 616 | describe("Error Recovery", () => { |
| 617 | beforeEach(async () => { |
| 618 | await manager.setupNextEditWindowManager(mockContext); |
| 619 | }); |
| 620 | |
| 621 | it("should recover from failed key reservation", async () => { |
| 622 | const executeCommand = mockVscode.commands |
| 623 | .executeCommand as MockedFunction<any>; |
| 624 | |
| 625 | // Make reservation fail |
| 626 | executeCommand.mockRejectedValueOnce(new Error("VS Code busy")); |
| 627 | |
| 628 | await expect(NextEditWindowManager.reserveTabAndEsc()).rejects.toThrow( |
| 629 | "VS Code busy", |
| 630 | ); |
| 631 | |
| 632 | // State should reset to free |
| 633 | expect(manager["keyReservationState"]).toBe("free"); |
| 634 | |
| 635 | // Should be able to try again |
| 636 | executeCommand.mockResolvedValueOnce(undefined); |
| 637 | await NextEditWindowManager.reserveTabAndEsc(); |
| 638 | expect(manager["keyReservationState"]).toBe("reserved"); |
| 639 | }); |
| 640 | |
| 641 | it("should recover from failed key freeing", async () => { |
| 642 | const executeCommand = mockVscode.commands |
| 643 | .executeCommand as MockedFunction<any>; |
| 644 | |
| 645 | // First reserve successfully |
| 646 | await NextEditWindowManager.reserveTabAndEsc(); |
| 647 | expect(manager["keyReservationState"]).toBe("reserved"); |
| 648 | |
| 649 | // Make freeing fail |
| 650 | executeCommand.mockRejectedValueOnce(new Error("VS Code busy")); |
| 651 | |
| 652 | await expect(NextEditWindowManager.freeTabAndEsc()).rejects.toThrow( |
| 653 | "VS Code busy", |
| 654 | ); |
| 655 | |
| 656 | // State should still reset to free (safety mechanism) |
| 657 | expect(manager["keyReservationState"]).toBe("free"); |
| 658 | }); |
| 659 | |
| 660 | it("should handle decoration creation failure", async () => { |
| 661 | const createDecoration = mockVscode.window |
| 662 | .createTextEditorDecorationType as MockedFunction<any>; |
| 663 | createDecoration.mockImplementationOnce(() => { |
| 664 | throw new Error("Failed to create decoration"); |
| 665 | }); |
| 666 | |
| 667 | // Should not throw, but should clean up |
| 668 | await manager.showNextEditWindow( |
| 669 | mockEditor, |
| 670 | new mockVscode.Position(0, 0), |
| 671 | 0, |
| 672 | 0, |
| 673 | "old", |
| 674 | "new", |
| 675 | [], |
| 676 | ); |
| 677 | |
| 678 | // Keys should be freed due to error |
| 679 | expect(manager["keyReservationState"]).toBe("free"); |
| 680 | expect(manager["currentDecoration"]).toBeNull(); |
| 681 | }); |
| 682 | }); |
| 683 | |
| 684 | describe("Command Registration", () => { |
| 685 | it("should register hide command", async () => { |
| 686 | await manager.setupNextEditWindowManager(mockContext); |
| 687 | |
| 688 | expect(mockVscode.commands.registerCommand).toHaveBeenCalledWith( |
| 689 | HIDE_NEXT_EDIT_SUGGESTION_COMMAND, |
| 690 | expect.any(Function), |
| 691 | ); |
| 692 | }); |
| 693 | |
| 694 | it("should register accept command", async () => { |
| 695 | await manager.setupNextEditWindowManager(mockContext); |
| 696 | |
| 697 | expect(mockVscode.commands.registerCommand).toHaveBeenCalledWith( |
| 698 | ACCEPT_NEXT_EDIT_SUGGESTION_COMMAND, |
| 699 | expect.any(Function), |
| 700 | ); |
| 701 | }); |
| 702 | |
| 703 | it("should handle command registration failure gracefully", async () => { |
| 704 | const registerCommand = mockVscode.commands |
| 705 | .registerCommand as MockedFunction<any>; |
| 706 | registerCommand.mockImplementationOnce(() => { |
| 707 | throw new Error("Command already registered"); |
| 708 | }); |
| 709 | |
| 710 | // Should not throw |
| 711 | await expect( |
| 712 | manager.setupNextEditWindowManager(mockContext), |
| 713 | ).resolves.not.toThrow(); |
| 714 | }); |
| 715 | }); |
| 716 | |
| 717 | describe("Window Management", () => { |
| 718 | beforeEach(async () => { |
| 719 | await manager.setupNextEditWindowManager(mockContext); |
| 720 | }); |
| 721 | |
| 722 | it("should store tooltip text when showing window", async () => { |
| 723 | await manager.showNextEditWindow( |
| 724 | mockEditor, |
| 725 | new mockVscode.Position(0, 0), |
| 726 | 0, |
| 727 | 2, |
| 728 | "old code", |
| 729 | "new code", |
| 730 | [], |
| 731 | ); |
| 732 | |
| 733 | expect(manager["currentTooltipText"]).toBe("new code"); |
| 734 | expect(manager["activeEditor"]).toBe(mockEditor); |
| 735 | }); |
| 736 | |
| 737 | it("should clear tooltip text when hiding windows", async () => { |
| 738 | // Show first |
| 739 | await manager.showNextEditWindow( |
| 740 | mockEditor, |
| 741 | new mockVscode.Position(0, 0), |
| 742 | 0, |
| 743 | 2, |
| 744 | "old", |
| 745 | "new", |
| 746 | [], |
| 747 | ); |
| 748 | |
| 749 | // Then hide |
| 750 | await manager.hideAllNextEditWindows(); |
| 751 | |
| 752 | expect(manager["currentTooltipText"]).toBeNull(); |
| 753 | expect(manager["activeEditor"]).toBeNull(); |
| 754 | }); |
| 755 | |
| 756 | it("should handle line deletion case", async () => { |
| 757 | mockEditor.document.lineAt = vi.fn((lineNumber: number) => ({ |
| 758 | text: "line to delete", |
| 759 | })); |
| 760 | |
| 761 | await manager.showNextEditWindow( |
| 762 | mockEditor, |
| 763 | new mockVscode.Position(1, 0), |
| 764 | 1, |
| 765 | 1, |
| 766 | "line to delete", |
| 767 | "", // Empty means deletion |
| 768 | [{ type: "old", line: "line to delete" }], |
| 769 | ); |
| 770 | |
| 771 | expect(manager["isLineDelete"]).toBe(true); |
| 772 | // Final cursor should be at end of previous line |
| 773 | expect(manager["finalCursorPos"]?.line).toBe(0); |
| 774 | }); |
| 775 | |
| 776 | it("should skip rendering for excluded URIs", async () => { |
| 777 | mockEditor.document.uri = { |
| 778 | toString: () => "output://test", |
| 779 | scheme: "output", |
| 780 | }; |
| 781 | |
| 782 | await manager.showNextEditWindow( |
| 783 | mockEditor, |
| 784 | new mockVscode.Position(0, 0), |
| 785 | 0, |
| 786 | 0, |
| 787 | "old", |
| 788 | "new", |
| 789 | [], |
| 790 | ); |
| 791 | |
| 792 | // Should not create decoration for excluded URI |
| 793 | expect( |
| 794 | mockVscode.window.createTextEditorDecorationType, |
| 795 | ).not.toHaveBeenCalled(); |
| 796 | expect(manager["currentDecoration"]).toBeNull(); |
| 797 | }); |
| 798 | }); |
| 799 | |
| 800 | describe("Accept/Reject Flow", () => { |
| 801 | beforeEach(async () => { |
| 802 | await manager.setupNextEditWindowManager(mockContext); |
| 803 | }); |
| 804 | |
| 805 | it("should apply text when accepting", async () => { |
| 806 | // Show window first |
| 807 | await manager.showNextEditWindow( |
| 808 | mockEditor, |
| 809 | new mockVscode.Position(0, 0), |
| 810 | 0, |
| 811 | 0, |
| 812 | "old", |
| 813 | "new text", |
| 814 | [], |
| 815 | ); |
| 816 | |
| 817 | // Get the accept command callback |
| 818 | const registerCalls = ( |
| 819 | mockVscode.commands.registerCommand as MockedFunction<any> |
| 820 | ).mock.calls; |
| 821 | const acceptCall = registerCalls.find( |
| 822 | (call) => call[0] === ACCEPT_NEXT_EDIT_SUGGESTION_COMMAND, |
| 823 | ); |
| 824 | //@ts-ignore |
| 825 | const acceptCallback = acceptCall[1]; |
| 826 | |
| 827 | // Call accept |
| 828 | //@ts-ignore |
| 829 | await acceptCallback(); |
| 830 | |
| 831 | // Should have called edit |
| 832 | expect(mockEditor.edit).toHaveBeenCalled(); |
| 833 | |
| 834 | // Should have cleared the decoration |
| 835 | expect(manager["currentTooltipText"]).toBeNull(); |
| 836 | expect(manager["keyReservationState"]).toBe("free"); |
| 837 | }); |
| 838 | |
| 839 | it("should not accept when no active window", async () => { |
| 840 | // Get the accept command callback |
| 841 | const registerCalls = ( |
| 842 | mockVscode.commands.registerCommand as MockedFunction<any> |
| 843 | ).mock.calls; |
| 844 | const acceptCall = registerCalls.find( |
| 845 | (call) => call[0] === ACCEPT_NEXT_EDIT_SUGGESTION_COMMAND, |
| 846 | ); |
| 847 | //@ts-ignore |
| 848 | const acceptCallback = acceptCall[1]; |
| 849 | |
| 850 | // Call accept without showing window |
| 851 | //@ts-ignore |
| 852 | await acceptCallback(); |
| 853 | |
| 854 | // Should not have called edit |
| 855 | expect(mockEditor.edit).not.toHaveBeenCalled(); |
| 856 | }); |
| 857 | |
| 858 | it("should hide window when rejecting", async () => { |
| 859 | // Show window first |
| 860 | await manager.showNextEditWindow( |
| 861 | mockEditor, |
| 862 | new mockVscode.Position(0, 0), |
| 863 | 0, |
| 864 | 0, |
| 865 | "old", |
| 866 | "new", |
| 867 | [], |
| 868 | ); |
| 869 | |
| 870 | // Get the hide command callback |
| 871 | const registerCalls = ( |
| 872 | mockVscode.commands.registerCommand as MockedFunction<any> |
| 873 | ).mock.calls; |
| 874 | const hideCall = registerCalls.find( |
| 875 | (call) => call[0] === HIDE_NEXT_EDIT_SUGGESTION_COMMAND, |
| 876 | ); |
| 877 | //@ts-ignore |
| 878 | const hideCallback = hideCall[1]; |
| 879 | |
| 880 | // Call hide |
| 881 | //@ts-ignore |
| 882 | await hideCallback(); |
| 883 | |
| 884 | // Should have cleared everything |
| 885 | expect(manager["currentTooltipText"]).toBeNull(); |
| 886 | expect(manager["activeEditor"]).toBeNull(); |
| 887 | expect(manager["keyReservationState"]).toBe("free"); |
| 888 | }); |
| 889 | }); |
| 890 | |
| 891 | describe("Disposal", () => { |
| 892 | it("should free keys on disposal", async () => { |
| 893 | await manager.setupNextEditWindowManager(mockContext); |
| 894 | |
| 895 | // Reserve keys first |
| 896 | await NextEditWindowManager.reserveTabAndEsc(); |
| 897 | expect(manager["keyReservationState"]).toBe("reserved"); |
| 898 | |
| 899 | // Dispose |
| 900 | manager.dispose(); |
| 901 | |
| 902 | // Should attempt to free keys |
| 903 | expect(mockVscode.commands.executeCommand).toHaveBeenCalledWith( |
| 904 | "setContext", |
| 905 | "nextEditWindowActive", |
| 906 | false, |
| 907 | ); |
| 908 | }); |
| 909 | |
| 910 | it("should dispose decorations on disposal", async () => { |
| 911 | await manager.setupNextEditWindowManager(mockContext); |
| 912 | |
| 913 | const mockDecoration = { dispose: vi.fn() }; |
| 914 | const mockDisposable1 = { dispose: vi.fn() }; |
| 915 | const mockDisposable2 = { dispose: vi.fn() }; |
| 916 | |
| 917 | manager["currentDecoration"] = mockDecoration as any; |
| 918 | manager["disposables"] = [mockDisposable1, mockDisposable2]; |
| 919 | |
| 920 | manager.dispose(); |
| 921 | |
| 922 | expect(mockDecoration.dispose).toHaveBeenCalled(); |
| 923 | expect(mockDisposable1.dispose).toHaveBeenCalled(); |
| 924 | expect(mockDisposable2.dispose).toHaveBeenCalled(); |
| 925 | }); |
| 926 | }); |
| 927 | |
| 928 | describe("Configuration Changes", () => { |
| 929 | it("should update on theme change", async () => { |
| 930 | await manager.setupNextEditWindowManager(mockContext); |
| 931 | |
| 932 | // Get the configuration change listener |
| 933 | const onDidChange = mockVscode.workspace |
| 934 | .onDidChangeConfiguration as MockedFunction<any>; |
| 935 | const changeCallback = onDidChange.mock.calls[0][0]; |
| 936 | |
| 937 | // Simulate theme change |
| 938 | //@ts-ignore |
| 939 | await changeCallback({ |
| 940 | affectsConfiguration: (key: string) => key === "workbench.colorTheme", |
| 941 | }); |
| 942 | |
| 943 | // Should have updated theme |
| 944 | const { getThemeString } = await import("../util/getTheme"); |
| 945 | expect(getThemeString).toHaveBeenCalled(); |
| 946 | }); |
| 947 | |
| 948 | it("should update on font size change", async () => { |
| 949 | await manager.setupNextEditWindowManager(mockContext); |
| 950 | |
| 951 | const onDidChange = mockVscode.workspace |
| 952 | .onDidChangeConfiguration as MockedFunction<any>; |
| 953 | const changeCallback = onDidChange.mock.calls[0][0]; |
| 954 | |
| 955 | // Change font size |
| 956 | ( |
| 957 | mockVscode.workspace.getConfiguration as MockedFunction<any> |
| 958 | ).mockReturnValueOnce({ |
| 959 | get: (key: string) => (key === "fontSize" ? 16 : "monospace"), |
| 960 | }); |
| 961 | |
| 962 | //@ts-ignore |
| 963 | await changeCallback({ |
| 964 | affectsConfiguration: (key: string) => key === "editor.fontSize", |
| 965 | }); |
| 966 | |
| 967 | expect(manager["fontSize"]).toBe(16); |
| 968 | }); |
| 969 | }); |
| 970 | }); |