Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,14 @@
{
"command": "twinny.rejectEdit",
"when": "twinnyInlineEditPending"
},
{
"command": "twinny.suggestLine",
"when": "editorTextFocus && !editorReadonly"
},
{
"command": "twinny.suggestLines",
"when": "editorTextFocus && !editorReadonly"
}
],
"terminal/context": [
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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": {
Expand All @@ -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,
Expand Down
2 changes: 2 additions & 0 deletions src/common/constants/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
101 changes: 83 additions & 18 deletions src/extension/completion/provider.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {
CancellationToken,
commands,
Disposable,
EndOfLine,
ExtensionContext,
Expand Down Expand Up @@ -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
Expand All @@ -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
}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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()
Expand Down Expand Up @@ -310,6 +329,7 @@ export class CompletionProvider
? (lineBefore.match(/[\w$]+$/)?.[0] ?? "")
: "",
selected,
lines,
provider,
token
}
Expand All @@ -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<Record<string, boolean>>(
"enabledLanguages",
Expand Down Expand Up @@ -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
Expand All @@ -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<boolean>(
"multilineCompletionsEnabled",
true
)
})
const multiline = request.lines
? request.lines === "multi"
: getShouldUseMultiline({
document,
position,
node,
multilineEnabled: this.config.get<boolean>(
"multilineCompletionsEnabled",
true
)
})
const stream = new CompletionStream({
stopWords,
multiline,
Expand Down
6 changes: 6 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading