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