| 1 | import { ListenableGenerator } from "./ListenableGenerator"; |
| 2 | |
| 3 | export class GeneratorReuseManager { |
| 4 | currentGenerator: ListenableGenerator<string> | undefined; |
| 5 | pendingGeneratorPrefix: string | undefined; |
| 6 | pendingCompletion = ""; |
| 7 | |
| 8 | constructor(private readonly onError: (err: any) => void) {} |
| 9 | |
| 10 | private _createListenableGenerator( |
| 11 | abortController: AbortController, |
| 12 | gen: AsyncGenerator<string>, |
| 13 | prefix: string, |
| 14 | ) { |
| 15 | this.currentGenerator?.cancel(); |
| 16 | |
| 17 | const listenableGen = new ListenableGenerator( |
| 18 | gen, |
| 19 | this.onError, |
| 20 | abortController, |
| 21 | ); |
| 22 | listenableGen.listen((chunk) => (this.pendingCompletion += chunk ?? "")); |
| 23 | |
| 24 | this.pendingGeneratorPrefix = prefix; |
| 25 | this.pendingCompletion = ""; |
| 26 | this.currentGenerator = listenableGen; |
| 27 | } |
| 28 | |
| 29 | private shouldReuseExistingGenerator(prefix: string): boolean { |
| 30 | return ( |
| 31 | !!this.currentGenerator && |
| 32 | !!this.pendingGeneratorPrefix && |
| 33 | (this.pendingGeneratorPrefix + this.pendingCompletion).startsWith( |
| 34 | prefix, |
| 35 | ) && |
| 36 | // for e.g. backspace |
| 37 | this.pendingGeneratorPrefix?.length <= prefix?.length |
| 38 | ); |
| 39 | } |
| 40 | |
| 41 | async *getGenerator( |
| 42 | prefix: string, |
| 43 | newGenerator: (abortSignal: AbortSignal) => AsyncGenerator<string>, |
| 44 | multiline: boolean, |
| 45 | ): AsyncGenerator<string> { |
| 46 | // If we can't reuse, then create a new generator |
| 47 | if (!this.shouldReuseExistingGenerator(prefix)) { |
| 48 | // Create a wrapper over the current generator to fix the prompt |
| 49 | const abortController = new AbortController(); |
| 50 | this._createListenableGenerator( |
| 51 | abortController, |
| 52 | newGenerator(abortController.signal), |
| 53 | prefix, |
| 54 | ); |
| 55 | } |
| 56 | |
| 57 | // Already typed characters are those that are new in the prefix from the old generator |
| 58 | let typedSinceLastGenerator = |
| 59 | prefix.slice(this.pendingGeneratorPrefix?.length) || ""; |
| 60 | for await (let chunk of this.currentGenerator?.tee() ?? []) { |
| 61 | if (!chunk) { |
| 62 | continue; |
| 63 | } |
| 64 | |
| 65 | // Ignore already typed characters in the completion |
| 66 | while (chunk.length && typedSinceLastGenerator.length) { |
| 67 | if (chunk[0] === typedSinceLastGenerator[0]) { |
| 68 | typedSinceLastGenerator = typedSinceLastGenerator.slice(1); |
| 69 | chunk = chunk.slice(1); |
| 70 | } else { |
| 71 | break; |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | // Break at newline unless we are in multiline mode |
| 76 | const newLineIndex = chunk.indexOf("\n"); |
| 77 | if (newLineIndex >= 0 && !multiline) { |
| 78 | yield chunk.slice(0, newLineIndex); |
| 79 | break; |
| 80 | } else if (chunk !== "") { |
| 81 | yield chunk; |
| 82 | } |
| 83 | } |
| 84 | } |
| 85 | } |