Skip to content

Commit 945f800

Browse files
committed
inline suggestions feature, dark mode support and monaco instance fix
Signed-off-by: Akshat Batra <[email protected]>
1 parent 61f3865 commit 945f800

File tree

15 files changed

+512
-158
lines changed

15 files changed

+512
-158
lines changed
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
const editorActivityMap: Map<string, number> = new Map();
2+
3+
export const updateEditorActivity = (editorType: 'markdown' | 'concerto' | 'json') => {
4+
editorActivityMap.set(editorType, Date.now());
5+
};
6+
7+
export const getLastActivity = (editorType: 'markdown' | 'concerto' | 'json'): number => {
8+
return editorActivityMap.get(editorType) || 0;
9+
};
10+
11+
export const clearActivity = (editorType: 'markdown' | 'concerto' | 'json') => {
12+
editorActivityMap.delete(editorType);
13+
};

src/ai-assistant/autocompletion.ts

Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
1+
import * as monaco from 'monaco-editor';
2+
import { sendMessage } from './chatRelay';
3+
import useAppStore from '../store/store';
4+
import { editorsContent } from '../types/components/AIAssistant.types';
5+
import { getLastActivity } from './activityTracker';
6+
7+
let lastRequestTime: number = 0;
8+
let isProcessing: boolean = false;
9+
10+
export const registerAutocompletion = (
11+
language: 'concerto' | 'markdown' | 'json',
12+
monacoInstance: typeof monaco
13+
) => {
14+
try {
15+
const provider = monacoInstance.languages.registerInlineCompletionsProvider(language, {
16+
provideInlineCompletions: async (model, position, _context, token) => {
17+
if (token.isCancellationRequested) {
18+
return { items: [] };
19+
}
20+
21+
const { aiConfig } = useAppStore.getState();
22+
const enableInlineSuggestions = aiConfig?.enableInlineSuggestions !== false;
23+
if (!enableInlineSuggestions) {
24+
return { items: [] };
25+
}
26+
27+
const initialTime = Date.now();
28+
29+
await new Promise(resolve => setTimeout(resolve, 1000));
30+
31+
const lastActivity = getLastActivity(language);
32+
if (lastActivity > initialTime) {
33+
return { items: [] };
34+
}
35+
36+
if (token.isCancellationRequested) {
37+
return { items: [] };
38+
}
39+
40+
const currentTime = Date.now();
41+
if (isProcessing || (currentTime - lastRequestTime < 2000)) {
42+
return { items: [] };
43+
}
44+
45+
isProcessing = true;
46+
lastRequestTime = currentTime;
47+
48+
try {
49+
const result = await getInlineCompletions(model, position, language, monacoInstance);
50+
return result;
51+
} finally {
52+
isProcessing = false;
53+
}
54+
},
55+
freeInlineCompletions: (_completions) => {
56+
},
57+
});
58+
return provider;
59+
} catch (error) {
60+
console.error('Error registering completion provider:', error);
61+
return null;
62+
}
63+
};
64+
65+
const getInlineCompletions = async (
66+
model: monaco.editor.ITextModel,
67+
position: monaco.Position,
68+
language: 'concerto' | 'markdown' | 'json',
69+
monacoInstance: typeof monaco
70+
): Promise<{ items: monaco.languages.InlineCompletion[] }> => {
71+
const { aiConfig } = useAppStore.getState();
72+
73+
if (!aiConfig) {
74+
return { items: [] };
75+
}
76+
77+
const lineContent = model.getLineContent(position.lineNumber);
78+
const textBeforeCursor = lineContent.substring(0, position.column - 1);
79+
const textAfterCursor = lineContent.substring(position.column - 1);
80+
81+
if (!textBeforeCursor.trim() || textBeforeCursor.length < 2) {
82+
return {
83+
items: []
84+
};
85+
}
86+
87+
const startLine = Math.max(1, position.lineNumber - 20);
88+
const endLine = Math.min(model.getLineCount(), position.lineNumber + 20);
89+
const contextLines: string[] = [];
90+
91+
for (let i = startLine; i <= endLine; i++) {
92+
if (i === position.lineNumber) {
93+
const fullCurrentLine = textBeforeCursor + '<CURSOR>' + textAfterCursor;
94+
contextLines.push(fullCurrentLine);
95+
} else if (i < position.lineNumber) {
96+
contextLines.push(model.getLineContent(i));
97+
} else {
98+
contextLines.push(model.getLineContent(i));
99+
}
100+
}
101+
102+
const contextText = contextLines.join('\n');
103+
104+
const editorsContent: editorsContent = {
105+
editorTemplateMark: useAppStore.getState().editorValue,
106+
editorModelCto: useAppStore.getState().editorModelCto,
107+
editorAgreementData: useAppStore.getState().editorAgreementData,
108+
};
109+
const prompt = `Current context:\n${contextText}`;
110+
111+
try {
112+
let completion = '';
113+
114+
await sendMessage(
115+
prompt,
116+
'inlineSuggestion',
117+
editorsContent,
118+
false,
119+
language,
120+
(chunk) => {
121+
completion += chunk;
122+
},
123+
(error) => {
124+
console.error('Autocompletion error:', error);
125+
}
126+
);
127+
128+
completion = completion.trim();
129+
130+
completion = completion.replace(/^```[\s\S]*?\n/, '').replace(/\n```$/, '');
131+
completion = completion.replace(/^`/, '').replace(/`$/, '');
132+
133+
if (!completion || completion.length < 2) {
134+
return { items: [] };
135+
}
136+
137+
const inlineCompletion: monaco.languages.InlineCompletion = {
138+
insertText: completion,
139+
range: new monacoInstance.Range(
140+
position.lineNumber,
141+
position.column,
142+
position.lineNumber,
143+
position.column
144+
),
145+
filterText: textBeforeCursor,
146+
};
147+
148+
return {
149+
items: [inlineCompletion],
150+
};
151+
} catch (error) {
152+
console.error('Error getting AI completion:', error);
153+
return { items: [] };
154+
}
155+
};

src/ai-assistant/chatRelay.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@ export const loadConfigFromLocalStorage = () => {
1818
const savedIncludeData = localStorage.getItem('aiIncludeData') === 'true';
1919

2020
const savedShowFullPrompt = localStorage.getItem('aiShowFullPrompt') === 'true';
21-
const savedEnableCodeSelectionMenu = localStorage.getItem('aiEnableCodeSelectionMenu') === 'true';
21+
const savedEnableCodeSelectionMenu = localStorage.getItem('aiEnableCodeSelectionMenu') !== 'false';
22+
const savedEnableInlineSuggestions = localStorage.getItem('aiEnableInlineSuggestions') !== 'false';
2223

2324
if (savedProvider && savedModel && savedApiKey) {
2425
const config: AIConfig = {
@@ -30,6 +31,7 @@ export const loadConfigFromLocalStorage = () => {
3031
includeDataContent: savedIncludeData,
3132
showFullPrompt: savedShowFullPrompt,
3233
enableCodeSelectionMenu: savedEnableCodeSelectionMenu,
34+
enableInlineSuggestions: savedEnableInlineSuggestions,
3335
};
3436

3537
if (savedCustomEndpoint && savedProvider === 'openai-compatible') {
@@ -132,6 +134,8 @@ export const sendMessage = async (
132134
systemPrompt = prepareSystemPrompt.createConcertoModel(editorsContent, aiConfig);
133135
} else if (promptPreset === "explainCode") {
134136
systemPrompt = prepareSystemPrompt.explainCode(editorsContent, aiConfig, editorType);
137+
} else if (promptPreset === "inlineSuggestion") {
138+
systemPrompt = prepareSystemPrompt.inlineSuggestion(editorsContent, aiConfig, editorType);
135139
} else {
136140
systemPrompt = prepareSystemPrompt.default(editorsContent, aiConfig);
137141
}

src/ai-assistant/prompts.ts

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,9 +51,29 @@ export const prepareSystemPrompt = {
5151
return includeEditorContents(prompt, aiConfig, editorsContent);
5252
},
5353

54+
inlineSuggestion: (editorsContent: editorsContent, aiConfig?: any, editorType?: 'markdown' | 'concerto' | 'json') => {
55+
const editorName = editorType === 'markdown' ? 'TemplateMark' : editorType === 'concerto' ? 'Concerto' : 'JSON Data';
56+
let prompt = `You are a helpful assistant that provides inline code completion suggestions for Accord Project
57+
${editorName} code. You should only suggest valid code that will
58+
compile. For instance, while making a suggestion in TemplateMark you must make sure that it conforms with
59+
provided (if any) Concerto model/JSON data.
60+
61+
IMPORTANT: Your response will be directly used for inline suggestions in the code editor.
62+
- <CURSOR> represents the current cursor position in the editor
63+
- Return ONLY the code completion text that should be inserted at the cursor position.
64+
- Do NOT include any explanations, markdown formatting, backticks, or additional text.
65+
- Do NOT repeat the existing code that's already in the editor.
66+
- Do NOT suggest replacement for existing code after the cursor, just addition.
67+
- Provide only the logical continuation from the cursor position.
68+
- If no meaningful completion can be suggested, return an empty response.
69+
- Responses should ideally not be very long unless the situation demands it.
70+
- The tendency should be to return a contentful ${editorName} completion every time and not empty response.
71+
- Focus on syntactically correct and contextually appropriate completions\n\n`;
72+
return includeEditorContents(prompt, aiConfig, editorsContent);
73+
},
74+
5475
default: (editorsContent: editorsContent, aiConfig?: any) => {
55-
let prompt = `You are a helpful assistant that answers questions about open source Accord Project. You assist the user
56-
to work with TemplateMark, Concerto models and JSON data. Code blocks returned by you should enclosed in backticks\n\n`;
76+
let prompt = `You are a helpful assistant that answers questions about open source Accord Project. You assist the user in working with TemplateMark, Concerto models and JSON data. Code blocks returned by you should be enclosed in backticks, the language names that you can use after three backticks are- "concerto","templatemark" and "json", suffix 'Apply' to the language name if it is a complete code block that can be used to replace the corresponding editor content, precisely, concertoApply, templatemarkApply and jsonApply. You must always try to return complete code block that can be applied to the editors. Concerto code, TemplateMark code and JSON data are supplied to TemplateEngine to produce the final output. For instance, a data field that is not in Concerto data model can't be in JSON data and therefore can't be used in TemplateMark you generate. Analyze the JSON data and Concerto model (if provided) carefully, only the fields with simple data types (String, Integer etc.) present in concept annotated with @template decorator can be directly accessed anywhere in the template. Other complex data fields that have custom concept declaration in the Concerto model and are represented as nested fields in JSON data, can only be used within {{#clause conceptName}} {{concept_property_name}} {{/clause}} tags. Therefore, in most cases you have to create a scope using clause tag in TemplateMark to access properties defined under a concept in Concerto. For enumerating through a list you can create a scope to access the properties in list items via {{#olist listName}} {{instancePropertyName}} {{/olist}} or {{#ulist listName}} {{instancePropertyName}} {{/ulist}}. For TemplateMark code, there's no such thing as 'this' keyword within list scope. Optional fields shouldn't be wrapped in an if or with block to check for their availability e.g. if Concerto model has age as optional don't wrap it in if block in TemplateMark. You can also use Typescript within TemplateMark by enclosing the Typescript code in {{% %}}, you must write all of the Typescript code within a single line enclosed in a single pair of opening {{% and closing %}}. You may use Typescript to achieve an objective in TemplateMark only if TemplateMark syntax makes doing something hard, the data objects from JSON are readily available within {{% %}} enclosed Typescript using direct access, e.g. {{% return order.orderLines %}}. For e.g., you could use TypeScript to render ordered/unordered primitive list types such as String[]. Keep your focus on generating valid output based on current editors' contents but if you make a change that isn't compatible with the content of existing editors, you must return the full code for those editors as well. You mustn't add any placeholder in TemplateMark which isn't in Concerto model and JSON data unless you modify the Concerto and JSON data to have that field at the appropriate place.\n\n`;
5777
return includeEditorContents(prompt, aiConfig, editorsContent);
5878
}
5979
};

0 commit comments

Comments
 (0)