Skip to content
This repository was archived by the owner on Aug 27, 2024. It is now read-only.

Commit c7bde16

Browse files
committed
- update to v1.9
- bug fix: document.lineCount in getPrompt function is wrong - add try catch inside provideInlineCompletionItems function
1 parent 593dac6 commit c7bde16

File tree

5 files changed

+112
-87
lines changed

5 files changed

+112
-87
lines changed

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
"name": "fauxpilot",
33
"displayName": "Fauxpilot",
44
"description": "Get completions from Fauxpilot server",
5-
"version": "1.1.8",
5+
"version": "1.1.9",
66
"icon": "assets/icon.png",
77
"keywords": [
88
"code-suggestion",

src/Constants.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
// Proportion of lines from the beginning of the file in the prompt
2-
export const LEADING_LINES_PROP = 0.15;
2+
export const LEADING_LINES_PROP = 0.21;

src/FauxpilotClient.ts

+10-2
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ export class FauxpilotClient {
2020
private stopWords: string[];
2121
private token: string;
2222
private requestType = RequestType.OpenAI;
23+
private maxLines: number;
2324

2425
public version: string;
2526

@@ -28,11 +29,12 @@ export class FauxpilotClient {
2829
this.excludeFileExts = [];
2930
this.baseUrl = '';
3031
this.model = '<<UNSET>>';
31-
this.maxTokens = 100;
32+
this.maxTokens = 80;
3233
this.temperature = 0.5;
3334
this.stopWords = [];
3435
this.version = '';
3536
this.token = '';
37+
this.maxLines = 150;
3638
}
3739

3840
public init(extConfig: WorkspaceConfiguration, channel: OutputChannel) {
@@ -58,11 +60,12 @@ export class FauxpilotClient {
5860
}
5961

6062
this.model = extConfig.get("model") ?? "<<UNSET>>";
61-
this.maxTokens = extConfig.get("maxTokens", 100);
63+
this.maxTokens = extConfig.get("maxTokens", 80);
6264
this.temperature = extConfig.get("temperature", 0.5);
6365
this.stopWords = extConfig.get("inlineCompletion") ? ["\n"] : [];
6466
this.token = extConfig.get("token", '');
6567
this.requestType = extConfig.get("requestType", 'openai') === 'openai' ? RequestType.OpenAI : RequestType.Aixos;
68+
this.maxLines = extConfig.get("maxLines", 150);
6669

6770
this.log(`enabled = ${this.enabled}`);
6871
this.log(`baseUrl = ${this.baseUrl}`);
@@ -74,6 +77,7 @@ export class FauxpilotClient {
7477
this.log(`stopWords = ${this.stopWords}`);
7578
this.log(`token = ${this.token}`);
7679
this.log(`requestType = ${this.requestType}`);
80+
this.log(`maxLines = ${this.maxLines}`);
7781

7882
rebuildAccessBackendCache();
7983
this.log("reload config finish.");
@@ -122,6 +126,10 @@ export class FauxpilotClient {
122126
public get MaxTokens(): number {
123127
return this.maxTokens;
124128
}
129+
130+
public get MaxLines(): number {
131+
return this.maxLines;
132+
}
125133
public get Temperature(): number {
126134
return this.temperature;
127135
}

src/FauxpilotCompletionProvider.ts

+98-82
Original file line numberDiff line numberDiff line change
@@ -18,120 +18,136 @@ export class FauxpilotCompletionProvider implements InlineCompletionItemProvider
1818
private statusBar: StatusBarItem;
1919
private extConfig: WorkspaceConfiguration;
2020
private userPressKeyCount = 0;
21-
private baseUrl: string;
2221

2322
constructor(statusBar: StatusBarItem, extConfig: WorkspaceConfiguration) {
2423
this.statusBar = statusBar;
2524
this.extConfig = extConfig;
26-
this.baseUrl = fauxpilotClient.BaseUrl;
27-
this.baseUrl = fauxpilotClient.BaseUrl;
2825
}
2926

3027
//@ts-ignore
3128
// because ASYNC and PROMISE
3229
public async provideInlineCompletionItems(document: TextDocument, position: Position, context: InlineCompletionContext, token: CancellationToken): ProviderResult<InlineCompletionItem[] | InlineCompletionList> {
33-
if (!fauxpilotClient.isEnabled) {
34-
fauxpilotClient.log("Extension not enabled, skipping.");
35-
return Promise.resolve(([] as InlineCompletionItem[]));
36-
}
30+
fauxpilotClient.log(`call inline: ${position.line}:${position.character}`);
3731

38-
var fileExt = document.fileName.split('.').pop();
39-
if (fileExt && fauxpilotClient.ExcludeFileExts.includes(fileExt)) {
40-
// check if fileExt in array excludeFileExts
41-
fauxpilotClient.log("Ignore file ext: " + fileExt);
42-
return [];
43-
}
32+
try {
33+
if (!fauxpilotClient.isEnabled) {
34+
fauxpilotClient.log("Extension not enabled, skipping.");
35+
return;
36+
}
4437

45-
const prompt = this.getPrompt(document, position);
46-
let suggestionDelay = fauxpilotClient.SuggestionDelay;
47-
if (suggestionDelay > 0) {
48-
let holdPressId = ++this.userPressKeyCount;
49-
fauxpilotClient.log(`try await ${suggestionDelay}, ${holdPressId}`);
50-
await delay(suggestionDelay);
51-
if (holdPressId != this.userPressKeyCount) {
52-
return [];
53-
}
54-
fauxpilotClient.log(`after await, ${holdPressId}, ${this.userPressKeyCount}`);
55-
if (token.isCancellationRequested) {
56-
fauxpilotClient.log('request cancelled.');
57-
return [];
38+
var fileExt = document.fileName.split('.').pop();
39+
if (fileExt && fauxpilotClient.ExcludeFileExts.includes(fileExt)) {
40+
// check if fileExt in array excludeFileExts
41+
fauxpilotClient.log("Ignore file ext: " + fileExt);
42+
return;
5843
}
59-
}
6044

61-
// fauxpilotClient.log(`Requesting completion for prompt: ${prompt}`);
62-
fauxpilotClient.log(`Requesting completion for prompt, length: ${prompt?.length ?? 0}`);
45+
const prompt = this.getPrompt(document, position);
46+
let suggestionDelay = fauxpilotClient.SuggestionDelay;
47+
if (suggestionDelay > 0) {
48+
let holdPressId = ++this.userPressKeyCount;
49+
fauxpilotClient.log(`try await ${suggestionDelay}, ${holdPressId}`);
50+
await delay(suggestionDelay);
51+
if (holdPressId != this.userPressKeyCount) {
52+
return;
53+
}
54+
fauxpilotClient.log(`after await, ${holdPressId}, ${this.userPressKeyCount}`);
55+
if (token.isCancellationRequested) {
56+
fauxpilotClient.log('request cancelled.');
57+
return;
58+
}
59+
}
6360

64-
if (this.isNil(prompt)) {
65-
fauxpilotClient.log("Prompt is empty, skipping");
66-
return Promise.resolve(([] as InlineCompletionItem[]));
67-
}
61+
// fauxpilotClient.log(`Requesting completion for prompt: ${prompt}`);
62+
fauxpilotClient.log(`Requesting completion for prompt, length: ${prompt?.length ?? 0}`);
6863

69-
const currentTimestamp = Date.now();
70-
const currentId = nextId();
71-
this.cachedPrompts.set(currentId, currentTimestamp);
72-
73-
// check there is no newer request util this.request_status is done
74-
while (this.requestStatus === "pending") {
75-
fauxpilotClient.log("pending, and Waiting for response...");
76-
await delay(200);
77-
fauxpilotClient.log("current id = " + currentId + " request status = " + this.requestStatus);
78-
if (this.newestTimestamp() > currentTimestamp) {
79-
fauxpilotClient.log("newest timestamp=" + this.newestTimestamp() + "current timestamp=" + currentTimestamp);
80-
fauxpilotClient.log("Newer request is pending, skipping");
81-
this.cachedPrompts.delete(currentId);
64+
if (this.isNil(prompt)) {
65+
fauxpilotClient.log("Prompt is empty, skipping");
8266
return Promise.resolve(([] as InlineCompletionItem[]));
8367
}
84-
}
8568

86-
if (token.isCancellationRequested) {
87-
fauxpilotClient.log('request cancelled.');
88-
return [];
89-
}
90-
91-
fauxpilotClient.log("Calling OpenAi, prompt length: " + prompt?.length);
92-
const promptStr = prompt?.toString();
93-
if (!promptStr) {
94-
return [];
95-
}
69+
const currentTimestamp = Date.now();
70+
const currentId = nextId();
71+
this.cachedPrompts.set(currentId, currentTimestamp);
72+
73+
// check there is no newer request util this.request_status is done
74+
while (this.requestStatus === "pending") {
75+
fauxpilotClient.log("pending, and Waiting for response...");
76+
await delay(200);
77+
fauxpilotClient.log("current id = " + currentId + " request status = " + this.requestStatus);
78+
if (this.newestTimestamp() > currentTimestamp) {
79+
fauxpilotClient.log("newest timestamp=" + this.newestTimestamp() + "current timestamp=" + currentTimestamp);
80+
fauxpilotClient.log("Newer request is pending, skipping");
81+
this.cachedPrompts.delete(currentId);
82+
return Promise.resolve(([] as InlineCompletionItem[]));
83+
}
84+
}
9685

97-
fauxpilotClient.log("current id = " + currentId + "set request status to pending");
98-
this.requestStatus = "pending";
99-
this.statusBar.tooltip = "Fauxpilot - Working";
100-
this.statusBar.text = "$(loading~spin)";
101-
return fetch(promptStr).then((response) => {
102-
this.statusBar.text = "$(light-bulb)";
103-
// if (token.isCancellationRequested) {
104-
// fauxpilotClient.log('request cancelled.');
105-
// return [];
106-
// }
107-
var result = this.toInlineCompletions(response, position);
108-
fauxpilotClient.log("inline completions array length: " + result.length);
109-
return result;
110-
}).finally(() => {
111-
fauxpilotClient.log("current id = " + currentId + " set request status to done");
112-
this.requestStatus = "done";
113-
this.cachedPrompts.delete(currentId);
114-
});
86+
if (token.isCancellationRequested) {
87+
fauxpilotClient.log('request cancelled.');
88+
return;
89+
}
11590

91+
fauxpilotClient.log("Calling OpenAi, prompt length: " + prompt?.length);
92+
const promptStr = prompt?.toString();
93+
if (!promptStr) {
94+
return;
95+
}
96+
// fauxpilotClient.log(promptStr);
97+
98+
fauxpilotClient.log("current id = " + currentId + " set request status to pending");
99+
this.requestStatus = "pending";
100+
this.statusBar.tooltip = "Fauxpilot - Working";
101+
this.statusBar.text = "$(loading~spin)";
102+
return fetch(promptStr).then((response) => {
103+
this.statusBar.text = "$(light-bulb)";
104+
// if (token.isCancellationRequested) {
105+
// fauxpilotClient.log('request cancelled.');
106+
// return [];
107+
// }
108+
var result = this.toInlineCompletions(response, position);
109+
fauxpilotClient.log("inline completions array length: " + result.length);
110+
return result;
111+
}).finally(() => {
112+
fauxpilotClient.log("current id = " + currentId + " set request status to done");
113+
this.requestStatus = "done";
114+
this.cachedPrompts.delete(currentId);
115+
});
116+
117+
} catch (error) {
118+
console.log('An error occurred: ' + error);
119+
if (typeof error === 'string') {
120+
fauxpilotClient.log("Catch an error: " + error);
121+
} else if (error instanceof Error) {
122+
fauxpilotClient.log(`Catch an error, ${error.name}: ${error.message}`);
123+
fauxpilotClient.log(`stack: ${error.stack}`);
124+
} else {
125+
fauxpilotClient.log('an unknown error!');
126+
}
127+
}
116128
}
117129

118-
private getPrompt(document: TextDocument, position: Position): String | undefined {
119-
const promptLinesCount = this.extConfig.get("maxLines") as number;
130+
private getPrompt(document: TextDocument, position: Position): string {
131+
const promptLinesCount = fauxpilotClient.MaxLines;
120132

121133
/*
122134
Put entire file in prompt if it's small enough, otherwise only
123135
take lines above the cursor and from the beginning of the file.
124136
*/
125-
if (document.lineCount <= promptLinesCount) {
137+
138+
// Only determine the content before the cursor
139+
const currentLine = position.line; // document.lineCount
140+
if (currentLine <= promptLinesCount) {
126141
const range = new Range(0, 0, position.line, position.character);
127142
return document.getText(range);
128143
} else {
129144
const leadingLinesCount = Math.floor(LEADING_LINES_PROP * promptLinesCount);
130145
const prefixLinesCount = promptLinesCount - leadingLinesCount;
131-
const firstPrefixLine = position.line - prefixLinesCount;
146+
const firstPrefixLine = Math.max(position.line - prefixLinesCount, 0);
147+
148+
const leading = document.getText(new Range(0, 0, leadingLinesCount, 200));
132149
const prefix = document.getText(new Range(firstPrefixLine, 0, position.line, position.character));
133-
const leading = document.getText(new Range(0, 0, leadingLinesCount, 0));
134-
return leading + prefix;
150+
return `${leading}\n${prefix}`;
135151
}
136152
}
137153

@@ -155,7 +171,7 @@ export class FauxpilotCompletionProvider implements InlineCompletionItemProvider
155171
}
156172

157173
fauxpilotClient.log('Get choice text: ' + choice1Text);
158-
fauxpilotClient.log('---------END-OF-CHOICE-TEXT-----------');
174+
// fauxpilotClient.log('---------END-OF-CHOICE-TEXT-----------');
159175
if (choice1Text.trim().length <= 0) {
160176
return [];
161177
}

src/extension.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,6 @@ export function activate(context: ExtensionContext) {
3838
languages.registerInlineCompletionItemProvider(
3939
fileFilter, new FauxpilotCompletionProvider(statusBar, extConfig)
4040
),
41-
4241
commands.registerCommand(turnOnFauxpilot.command, statusUpdateCallback(turnOnFauxpilot.callback, true)),
4342
commands.registerCommand(turnOffFauxpilot.command, statusUpdateCallback(turnOffFauxpilot.callback, false)),
4443
statusBar
@@ -54,6 +53,8 @@ export function activate(context: ExtensionContext) {
5453
if (fauxpilotClient.isEnabled) {
5554
statusBar.show();
5655
}
56+
57+
fauxpilotClient.log('end of context activate');
5758
}
5859

5960
// this method is called when your extension is deactivated

0 commit comments

Comments
 (0)