From 7ddcdb5037bce584b32bf6e776a18f577374f526 Mon Sep 17 00:00:00 2001 From: Asish Kumar Date: Fri, 20 Nov 2026 03:35:09 +0530 Subject: [PATCH] Commands to ask for a one-line or a several-line suggestion Whether an inline suggestion runs over several lines is decided by twinny.multilineCompletionsEnabled and a guess from the code round the cursor. Users who usually want one line, and a block only now and then (or the other way round), had no way to ask for the other length at the moment they wanted it (#201). Two commands now trigger a suggestion at the cursor with the length chosen by the user, whatever the setting and the guess would pick: - "Twinny - Suggest one line" (twinny.suggestLine) - "Twinny - Suggest several lines" (twinny.suggestLines), up to twinny.maxLines They have no default keys, so nothing clashes with Alt+\ or other extensions; they can be bound in Keyboard Shortcuts and show in the command palette while an editable editor has focus. The command records the length with the document, version and cursor it was asked at, then runs editor.action.inlineSuggest.trigger. The first invoked request takes it, and uses it only if it is for that same place, so the next suggestion follows the settings again. A request with an asked length is never served from the suggestion on screen or the one prefetched for the next line, since either may be the other length, and it is cached under its own key. Typing through a suggestion the command showed still serves the rest of it. The settings' descriptions mention the commands. Tests drive the command through the editor with the provider registered against a fake Ollama: several lines where the settings give one, one line where they give a block, and the asked length being let go once a request elsewhere takes it. The prefetch tests' helpers move up a level so the new suite can share them. --- package.json | 20 +- src/common/constants/commands.ts | 2 + src/extension/completion/provider.ts | 101 +++++++-- src/index.ts | 6 + src/test/suite/completion-lifecycle.test.ts | 234 ++++++++++++++------ 5 files changed, 276 insertions(+), 87 deletions(-) diff --git a/package.json b/package.json index 325ccafa..9aadc1da 100644 --- a/package.json +++ b/package.json @@ -174,6 +174,14 @@ { "command": "twinny.rejectEdit", "when": "twinnyInlineEditPending" + }, + { + "command": "twinny.suggestLine", + "when": "editorTextFocus && !editorReadonly" + }, + { + "command": "twinny.suggestLines", + "when": "editorTextFocus && !editorReadonly" } ], "terminal/context": [ @@ -232,6 +240,14 @@ "shortTitle": "Enable twinny", "title": "Enable twinny" }, + { + "command": "twinny.suggestLine", + "title": "Twinny - Suggest one line" + }, + { + "command": "twinny.suggestLines", + "title": "Twinny - Suggest several lines" + }, { "command": "twinny.stopGeneration", "title": "Stop generation" @@ -503,7 +519,7 @@ "order": 7, "type": "boolean", "default": true, - "markdownDescription": "When `true`, Twinny will attempt to generate multi-line completions. This is an experimental feature and may not work perfectly in all scenarios." + "markdownDescription": "When `true`, Twinny will attempt to generate multi-line completions. This is an experimental feature and may not work perfectly in all scenarios. Whatever this is set to, **Twinny - Suggest one line** (`twinny.suggestLine`) and **Twinny - Suggest several lines** (`twinny.suggestLines`) ask for one or the other at the cursor; give them keyboard shortcuts in Keyboard Shortcuts." }, "twinny.maxLines": { "dependencies": { @@ -512,7 +528,7 @@ "order": 8, "type": "number", "default": 40, - "markdownDescription": "Sets the maximum number of lines for multi-line completions. Only applies when `twinny.multilineCompletionsEnabled` is `true`." + "markdownDescription": "Sets the maximum number of lines for multi-line completions. Applies when `twinny.multilineCompletionsEnabled` is `true`, and to **Twinny - Suggest several lines** (`twinny.suggestLines`) whatever it is set to." }, "twinny.fileContextEnabled": { "order": 9, diff --git a/src/common/constants/commands.ts b/src/common/constants/commands.ts index 429403f7..8d10dbd5 100644 --- a/src/common/constants/commands.ts +++ b/src/common/constants/commands.ts @@ -31,6 +31,8 @@ export const TWINNY_COMMAND_NAME = { setUpTeam: "twinny.setUpTeam", statusBarMenu: "twinny.statusBarMenu", stopGeneration: "twinny.stopGeneration", + suggestLine: "twinny.suggestLine", + suggestLines: "twinny.suggestLines", templateCompletion: "twinny.templateCompletion", templates: "twinny.templates", addFileToContext: "twinny.addFileToContext", diff --git a/src/extension/completion/provider.ts b/src/extension/completion/provider.ts index 5309c002..6b4c7278 100644 --- a/src/extension/completion/provider.ts +++ b/src/extension/completion/provider.ts @@ -1,5 +1,6 @@ import { CancellationToken, + commands, Disposable, EndOfLine, ExtensionContext, @@ -71,6 +72,17 @@ import { HeldDefinitions, StableOrder } from "./stable-context" import { CompletionStream } from "./stream" import { ModelWarmer, shouldWarm } from "./warm-up" +/** How many lines a suggestion may run to, when the user asked for one or the other. */ +export type SuggestionLines = "single" | "multi" + +/** A suggestion asked for by command, and the place it was asked for. */ +interface AskedLines { + document: TextDocument + version: number + position: Position + lines: SuggestionLines +} + /** Everything one inline-completion request needs, kept off the instance. */ interface CompletionRequest { id: number @@ -95,6 +107,11 @@ interface CompletionRequest { * that item were already accepted and the result is returned with it. */ selected?: SelectedCompletionInfo + /** + * One line or several, when a command asked for it; otherwise the + * settings and the code round the cursor decide. + */ + lines?: SuggestionLines provider: TwinnyProvider token: CancellationToken } @@ -140,6 +157,7 @@ export class CompletionProvider { private _run: GenerationRun | null = null private _acceptedLastCompletion = false + private _askedLines: AskedLines | undefined private _definitions = new DefinitionContext() private _fileInteractionCache: FileInteractionCache private _lastSuggestion: LastSuggestion | undefined @@ -198,6 +216,7 @@ export class CompletionProvider // document: each debug line written mid-request asked again and // aborted it (#559). if (IGNORED_SCHEMES.has(document.uri.scheme)) return + const lines = this.takeAskedLines(document, position, context) // Invalidate even when this invocation returns early or uses the cache. this.abortCompletion() if (token.isCancellationRequested) return @@ -248,12 +267,12 @@ export class CompletionProvider this.config.get("numPredictFim", 512), this.config.get("temperature", 0.2) ]) - const cacheScope = JSON.stringify([scope, document.version]) - const continuation = getSuggestionContinuation( - this._lastSuggestion, - prefixSuffix, - scope - ) + const cacheScope = JSON.stringify([scope, document.version, lines ?? null]) + // The suggestion on screen, or the one made ahead, may be the other + // length: a command asking for one has the model asked afresh. + const continuation = lines + ? undefined + : getSuggestionContinuation(this._lastSuggestion, prefixSuffix, scope) if (continuation) { logger.debug("FIM served from the previous suggestion (typed through)") return this.toInlineCompletion(continuation, position, selected) @@ -274,7 +293,7 @@ export class CompletionProvider return } - const ahead = selected ? undefined : this.prefetchFor(document, prefixSuffix, scope) + const ahead = selected || lines ? undefined : this.prefetchFor(document, prefixSuffix, scope) if (ahead) { const id = this._requestId const waited = logger.timer() @@ -310,6 +329,7 @@ export class CompletionProvider ? (lineBefore.match(/[\w$]+$/)?.[0] ?? "") : "", selected, + lines, provider, token } @@ -322,6 +342,47 @@ export class CompletionProvider return this.complete(request) } + /** + * Asks the editor for a suggestion at the cursor of one line, or of + * several up to `twinny.maxLines`, whatever + * `twinny.multilineCompletionsEnabled` and the code round the cursor + * would choose. + */ + public async suggest(lines: SuggestionLines) { + const editor = window.activeTextEditor + if (!editor) return + const { document, selection } = editor + this._askedLines = { + document, + version: document.version, + position: selection.active, + lines + } + await commands.executeCommand("editor.action.inlineSuggest.trigger") + } + + /** + * The length a command asked for, if this is the request it set off: + * one the user invoked, at the place and the version it was asked for. + * Taken once, so the next suggestion is the settings' again. + */ + private takeAskedLines( + document: TextDocument, + position: Position, + context: InlineCompletionContext + ): SuggestionLines | undefined { + const asked = this._askedLines + if (!asked || context.triggerKind !== InlineCompletionTriggerKind.Invoke) { + return undefined + } + this._askedLines = undefined + return asked.document === document && + asked.version === document.version && + asked.position.isEqual(position) + ? asked.lines + : undefined + } + private isLanguageEnabled(languageId: string) { const enabledLanguages = this.config.get>( "enabledLanguages", @@ -362,7 +423,8 @@ export class CompletionProvider if (this.isStale(request)) return const [node, prepared] = await Promise.all([ - this.getNodeAtCursor(document, position), + // Only the settings' choice of length looks at the code round the cursor. + request.lines ? null : this.getNodeAtCursor(document, position), this.getPrompt(request) ]) if (!prepared || this.isStale(request)) return @@ -374,19 +436,22 @@ export class CompletionProvider } logger.info( `FIM #${request.id} → ${provider.modelName} · ${where} · ` + - `prompt ${formatCount(prompt.length)} chars` + `prompt ${formatCount(prompt.length)} chars` + + (request.lines ? ` · ${request.lines === "multi" ? "several lines" : "one line"} asked for` : "") ) const stopWords = getStopWords(provider.modelName, provider.fimTemplate) - const multiline = getShouldUseMultiline({ - document, - position, - node, - multilineEnabled: this.config.get( - "multilineCompletionsEnabled", - true - ) - }) + const multiline = request.lines + ? request.lines === "multi" + : getShouldUseMultiline({ + document, + position, + node, + multilineEnabled: this.config.get( + "multilineCompletionsEnabled", + true + ) + }) const stream = new CompletionStream({ stopWords, multiline, diff --git a/src/index.ts b/src/index.ts index 3533fc88..7a74dcc3 100644 --- a/src/index.ts +++ b/src/index.ts @@ -332,6 +332,12 @@ export async function activate(context: ExtensionContext) { const chat = await requireChat() if (chat) await fixTerminalError(chat, terminalHistory) }), + commands.registerCommand(TWINNY_COMMAND_NAME.suggestLine, () => + completionProvider.suggest("single") + ), + commands.registerCommand(TWINNY_COMMAND_NAME.suggestLines, () => + completionProvider.suggest("multi") + ), languages.registerInlineCompletionItemProvider( { pattern: "**" }, completionProvider diff --git a/src/test/suite/completion-lifecycle.test.ts b/src/test/suite/completion-lifecycle.test.ts index 44cac52f..b008beeb 100644 --- a/src/test/suite/completion-lifecycle.test.ts +++ b/src/test/suite/completion-lifecycle.test.ts @@ -5,7 +5,7 @@ import * as vscode from "vscode" import { ACTIVE_FIM_PROVIDER_STORAGE_KEY, API_PROVIDERS } from "../../common/constants" import { FileInteractionCache } from "../../extension/completion/file-interaction" -import { CompletionProvider } from "../../extension/completion/provider" +import { CompletionProvider, SuggestionLines } from "../../extension/completion/provider" import { GenerationTracker } from "../../extension/generations" import { TemplateProvider } from "../../extension/templates/provider" @@ -88,77 +88,83 @@ suite("Completion lifecycle", () => { } }) - suite("prefetch", () => { - /** An Ollama that answers each `/api/generate` in turn and keeps the prompts it was sent. */ - const fakeOllama = (replies: string[]) => - new Promise<{ port: number; prompts: string[]; close(): Promise }>((resolve) => { - const prompts: string[] = [] - const server = http.createServer((request, response) => { - let text = "" - request.on("data", (chunk) => (text += chunk)) - request.on("end", () => { - prompts.push(String(JSON.parse(text).prompt)) - response.writeHead(200, { "Content-Type": "application/x-ndjson" }) - response.write(`${JSON.stringify({ response: replies[prompts.length - 1] ?? "", done: false })}\n`) - response.end(`${JSON.stringify({ response: "", done: true })}\n`) - }) + /** An Ollama that answers each `/api/generate` in turn and keeps the prompts it was sent. */ + const fakeOllama = (replies: string[]) => + new Promise<{ port: number; prompts: string[]; close(): Promise }>((resolve) => { + const prompts: string[] = [] + const server = http.createServer((request, response) => { + let text = "" + request.on("data", (chunk) => (text += chunk)) + request.on("end", () => { + prompts.push(String(JSON.parse(text).prompt)) + response.writeHead(200, { "Content-Type": "application/x-ndjson" }) + response.write(`${JSON.stringify({ response: replies[prompts.length - 1] ?? "", done: false })}\n`) + response.end(`${JSON.stringify({ response: "", done: true })}\n`) }) - server.listen(0, "127.0.0.1", () => - resolve({ - port: (server.address() as AddressInfo).port, - prompts, - close: () => - new Promise((done) => { - (server as unknown as { closeAllConnections?: () => void }).closeAllConnections?.() - server.close(() => done()) - }) - }) - ) }) - - const setUp = async (replies: string[], provider: string = API_PROVIDERS.Ollama) => { - const server = await fakeOllama(replies) - const config = { - id: "fake", label: "Fake", modelName: "codellama:7b-code", provider, type: "fim", - apiHostname: "127.0.0.1", apiPort: server.port, apiProtocol: "http", apiPath: "/api/generate" - } - const context = { - globalState: { get: (key: string) => (key === ACTIVE_FIM_PROVIDER_STORAGE_KEY ? config : undefined) } - } as unknown as vscode.ExtensionContext - const completions = new CompletionProvider( - new GenerationTracker(), new FileInteractionCache(), new TemplateProvider(undefined), context + server.listen(0, "127.0.0.1", () => + resolve({ + port: (server.address() as AddressInfo).port, + prompts, + close: () => + new Promise((done) => { + (server as unknown as { closeAllConnections?: () => void }).closeAllConnections?.() + server.close(() => done()) + }) + }) ) - const document = await vscode.workspace.openTextDocument({ - content: "const total = sum(items)\n\nexport {}\n", language: "javascript" - }) - const editor = await vscode.window.showTextDocument(document) - const source = new vscode.CancellationTokenSource() - const ask = async (position: vscode.Position) => { - editor.selection = new vscode.Selection(position, position) - const items = await completions.provideInlineCompletionItems( - document, position, - { triggerKind: vscode.InlineCompletionTriggerKind.Invoke, selectedCompletionInfo: undefined }, - source.token - ) - const text = items?.[0]?.insertText - return typeof text === "string" ? text : text?.value ?? "" - } - const type = async (position: vscode.Position, text: string) => { - await editor.edit((edit) => edit.insert(position, text)) - const end = document.positionAt(document.offsetAt(position) + text.length) - editor.selection = new vscode.Selection(end, end) - return end - } - const pending = () => (completions as unknown as { _prefetch?: { result: Promise } })._prefetch - const tearDown = async () => { - source.dispose() - completions.dispose() - await server.close() - await vscode.commands.executeCommand("workbench.action.closeAllEditors") - } - return { server, completions, ask, type, pending, tearDown } + }) + + /** What an inline completion item inserts, as plain text. */ + const textOf = (items: vscode.InlineCompletionItem[] | undefined) => { + const text = items?.[0]?.insertText + return typeof text === "string" ? text : text?.value ?? "" + } + + const setUp = async ( + replies: string[], + provider: string = API_PROVIDERS.Ollama, + content = "const total = sum(items)\n\nexport {}\n" + ) => { + const server = await fakeOllama(replies) + const config = { + id: "fake", label: "Fake", modelName: "codellama:7b-code", provider, type: "fim", + apiHostname: "127.0.0.1", apiPort: server.port, apiProtocol: "http", apiPath: "/api/generate" + } + const context = { + globalState: { get: (key: string) => (key === ACTIVE_FIM_PROVIDER_STORAGE_KEY ? config : undefined) } + } as unknown as vscode.ExtensionContext + const completions = new CompletionProvider( + new GenerationTracker(), new FileInteractionCache(), new TemplateProvider(undefined), context + ) + const document = await vscode.workspace.openTextDocument({ content, language: "javascript" }) + const editor = await vscode.window.showTextDocument(document) + const source = new vscode.CancellationTokenSource() + const ask = async (position: vscode.Position) => { + editor.selection = new vscode.Selection(position, position) + return textOf(await completions.provideInlineCompletionItems( + document, position, + { triggerKind: vscode.InlineCompletionTriggerKind.Invoke, selectedCompletionInfo: undefined }, + source.token + )) + } + const type = async (position: vscode.Position, text: string) => { + await editor.edit((edit) => edit.insert(position, text)) + const end = document.positionAt(document.offsetAt(position) + text.length) + editor.selection = new vscode.Selection(end, end) + return end } + const pending = () => (completions as unknown as { _prefetch?: { result: Promise } })._prefetch + const tearDown = async () => { + source.dispose() + completions.dispose() + await server.close() + await vscode.commands.executeCommand("workbench.action.closeAllEditors") + } + return { server, completions, editor, ask, type, pending, tearDown } + } + suite("prefetch", () => { test("accepting a suggestion and pressing Enter shows the next one without another request", async () => { const { server, completions, ask, type, pending, tearDown } = await setUp([ "const mean = total / items.length", @@ -215,4 +221,98 @@ suite("Completion lifecycle", () => { } }) }) + + suite("one line or several, asked for by command (#201)", () => { + /** + * Runs the command the way a keyboard shortcut does, with the provider + * registered so the editor itself asks it, and returns what it showed. + */ + const suggest = async ( + completions: CompletionProvider, + editor: vscode.TextEditor, + position: vscode.Position, + lines: SuggestionLines + ) => { + editor.selection = new vscode.Selection(position, position) + let shown: (text: string) => void = () => undefined + const result = new Promise((resolve) => (shown = resolve)) + const registration = vscode.languages.registerInlineCompletionItemProvider({ pattern: "**" }, { + async provideInlineCompletionItems(document, at, context, token) { + const items = await completions.provideInlineCompletionItems(document, at, context, token) + if (context.triggerKind === vscode.InlineCompletionTriggerKind.Invoke) shown(textOf(items)) + return items + } + }) + try { + await completions.suggest(lines) + return await result + } finally { + registration.dispose() + await vscode.commands.executeCommand("editor.action.inlineSuggest.hide") + } + } + + test("Suggest several lines shows a block where the settings show one line", async () => { + const reply = ".filter(Boolean)\n .length" + const { completions, editor, ask, tearDown } = await setUp( + // Each suggestion shown also has the line after it asked for. + Array(8).fill(reply), + API_PROVIDERS.Ollama, + "const total = items\nconst count = items\n" + ) + try { + const end = new vscode.Position(0, 19) + assert.strictEqual(await ask(end), ".filter(Boolean)") + // The line on screen would be served again as typed-through text; + // the block shows only when the model is asked afresh. + assert.strictEqual(await suggest(completions, editor, end, "multi"), reply) + + assert.strictEqual( + await ask(new vscode.Position(1, 19)), + ".filter(Boolean)", + "the next suggestion is the settings' length again" + ) + } finally { + await tearDown() + } + }) + + test("Suggest one line stops at the end of the line where the settings show a block", async () => { + const reply = "const total = sum(items)\n return total / items.length" + const { completions, editor, ask, tearDown } = await setUp( + // Each suggestion shown also has the line after it asked for. + Array(8).fill(reply), + API_PROVIDERS.Ollama, + "function mean(items) {\n \n}\n" + ) + try { + const indented = new vscode.Position(1, 2) + assert.strictEqual(await ask(indented), reply) + assert.strictEqual(await suggest(completions, editor, indented, "single"), "const total = sum(items)") + } finally { + await tearDown() + } + }) + + test("the asked length is for the request it sets off, at the place it was asked", async () => { + const reply = ".filter(Boolean)\n .length" + const { completions, editor, ask, tearDown } = await setUp( + // Each suggestion shown also has the line after it asked for. + Array(8).fill(reply), + API_PROVIDERS.Ollama, + "const total = items\nconst count = items\n" + ) + try { + // Asked for on the first line. This provider is not registered + // with the editor, so the command's own request never reaches it + // and the first one it sees is made on the second line. + editor.selection = new vscode.Selection(0, 19, 0, 19) + await completions.suggest("multi") + assert.strictEqual(await ask(new vscode.Position(1, 19)), ".filter(Boolean)") + assert.strictEqual(await ask(new vscode.Position(0, 19)), ".filter(Boolean)", "it was let go") + } finally { + await tearDown() + } + }) + }) })