Skip to content

Commit

Permalink
feat: add ai rename variable feature
Browse files Browse the repository at this point in the history
  • Loading branch information
2214962083 committed Jul 12, 2024
1 parent 0454b70 commit cb03027
Show file tree
Hide file tree
Showing 19 changed files with 398 additions and 61 deletions.
4 changes: 2 additions & 2 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": [
"--extensionDevelopmentPath=${workspaceFolder}",
"--disable-extensions"
"--extensionDevelopmentPath=${workspaceFolder}"
// "--disable-extensions"
],
"outFiles": ["${workspaceFolder}/dist/**/*.js"],
"preLaunchTask": "npm: watch",
Expand Down
13 changes: 12 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ Master Any Code: One-Click Comments and Language Conversion. 💪
- 📖 **Code Annotation**: One-click detailed comments for better readability.
- 📋 **Quick Copy**: Copy files/folders as AI prompts instantly.
- 💬 **Custom Commands**: Execute custom AI commands on selected files.
- 🔀 **Variable Rename**: Rename variables using AI-suggested variable names.
- 🎛 **Prompt Templates**: Define flexible AI prompt templates.
- 📁 **Multi-File Support**: Select multiple files/folders for AI prompts or commands.
- 🚫 **Ignore Patterns**: Exclude files/folders using custom glob rules.
Expand Down Expand Up @@ -77,7 +78,17 @@ Prepare and execute custom AI commands based on selected files and user input.
- Right-click and choose `✨ Aide: Ask AI`.
- Enter your question when prompted.

### 5. Customizing Keyboard Shortcuts
### 5. Aide: Rename Variable

Rename variables using AI-suggested variable names.

**How to Use:**

- Select a variable in the editor.
- Right-click and choose `✨ Aide: Rename Variable`.
- Select a suggested variable name.

### 6. Customizing Keyboard Shortcuts

Assign custom keyboard shortcuts to these commands for faster access:

Expand Down
13 changes: 12 additions & 1 deletion README_CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
- 📖 **代码注释**:一键添加详细注释,提升可读性。
- 📋 **快速复制**:即时复制文件/文件夹为AI提示。
- 💬 **自定义命令**:对选定文件执行自定义AI命令。
- 🔀 **变量重命名**:使用AI给出的变量名建议重命名变量。
- 🎛 **提示模板**:定义灵活的AI提示模板。
- 📁 **多文件支持**:选择多个文件/文件夹进行AI提示或命令。
- 🚫 **忽略模式**:使用自定义 glob 规则排除文件/文件夹。
Expand Down Expand Up @@ -75,7 +76,17 @@
- 右键选择 `✨ Aide: 问 AI`
- 按提示输入您的问题。

### 5. 自定义键盘快捷键
### 5. Aide: 重命名变量

使用 AI 给出几个可能的变量名建议以及解释,帮助您更快地重命名变量。

**使用方法:**

- 在编辑器中选择变量。
- 点击右键选择 `✨ Aide: 重命名变量`
- 选择一个建议的变量名。

### 6. 自定义键盘快捷键

为这些命令分配自定义键盘快捷键以更快地访问:

Expand Down
9 changes: 9 additions & 0 deletions docs/configuration/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,14 @@ This setting allows you to specify the template for the code viewer helper promp
#{content}
```

### `✨ Aide: Rename Variable`

This command allows you to rename variables using AI-suggested variable names.

You can select a variable in the editor, right-click, and choose `✨ Aide: Rename Variable`. Then, you can select a suggested variable name from the list.

It uses the built-in `rename symbol` feature of `vscode`, which renames all references to the variable together.

---

### OpenAI Configuration
Expand Down Expand Up @@ -357,6 +365,7 @@ Here are the default commands you can customize:
- `aide.askAI`: Ask AI
- `aide.codeConvert`: Code Convert
- `aide.codeViewerHelper`: Code Viewer Helper
- `aide.renameVariable`: Rename Variable
- ...maybe more

Example:
Expand Down
9 changes: 9 additions & 0 deletions docs/configuration/README_CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,14 @@ VSCode 将打开一个临时文本以显示带注释的代码。
#{content}
```

### `✨ Aide: 重命名变量`

此命令使用 AI 给出几个可能的变量名建议以及解释,帮助您更快地重命名变量。

你可以在编辑器中选择一个变量,右键点击并选择 `✨ Aide: 重命名变量`。然后你可以从 AI 给出的建议中选择一个变量名。

它使用的是 `vscode` 内部自带的重命名变量功能,会把所有引用此变量的地方一起重命名。

---

### OpenAI 配置
Expand Down Expand Up @@ -358,6 +366,7 @@ VSCode 将打开一个临时文本以显示带注释的代码。
- `aide.askAI`: 问 AI
- `aide.codeConvert`: 代码转换
- `aide.codeViewerHelper`: 代码查看器助手
- `aide.renameVariable`: 重命名变量
- ...也许更多

**示例:**
Expand Down
19 changes: 14 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,10 @@
"command": "aide.codeViewerHelper",
"title": "%command.codeViewerHelper%",
"icon": "$(open-editors-view-icon)"
},
{
"command": "aide.renameVariable",
"title": "%command.renameVariable%"
}
],
"menus": {
Expand All @@ -102,21 +106,25 @@
"editor/context": [
{
"command": "aide.codeViewerHelper",
"group": "0_navigation@0"
"group": "0_aide@100"
},
{
"command": "aide.codeConvert",
"group": "0_navigation@1"
"group": "0_aide@101"
},
{
"command": "aide.renameVariable",
"group": "0_aide@102"
}
],
"editor/title": [
{
"command": "aide.codeViewerHelper",
"group": "navigation@1"
"group": "0_aide@1"
},
{
"command": "aide.codeConvert",
"group": "navigation@2"
"group": "0_aide@2"
}
]
},
Expand Down Expand Up @@ -260,7 +268,8 @@
"typescript": "5.4.5",
"undici": "^6.19.2",
"vite": "^5.3.3",
"vitest": "^2.0.2"
"vitest": "^2.0.2",
"zod": "^3.23.8"
},
"pnpm": {
"overrides": {
Expand Down
4 changes: 4 additions & 0 deletions package.nls.en.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"command.askAI": "✨ Aide: Ask AI",
"command.codeConvert": "✨ Aide: Code Convert",
"command.codeViewerHelper": "✨ Aide: Code Viewer Helper",
"command.renameVariable": "✨ Aide: Rename Variable",
"config.title": "Aide Configuration",
"config.aiPrompt.description": "Template for copied content, use #{content} as a placeholder for file content",
"config.aiCommand.description": "Custom AI command template. Available variables: #{filesRelativePath}, #{filesFullPath}, #{content}",
Expand All @@ -29,10 +30,13 @@
"error.noContext": "Context not initialized",
"info.copied": "File contents have been copied to clipboard",
"info.customLanguage": "Custom language",
"info.noAiSuggestionsVariableName": "AI thinks your variable name is already good",
"info.processing": "Aide is processing...",
"input.array.promptEnding": "Enter comma separated values",
"input.json.promptEnding": "Enter JSON formatted value",
"input.aiCommand.prompt": "Enter question for AI command",
"input.aiCommand.placeholder": "Enter question for AI command",
"input.codeConvertTargetLanguage.prompt": "Select convert target language",
"input.selectAiSuggestionsVariableName.prompt": "Select AI suggestions variable name",
"file.content": "File: {0}\n```{1}\n{2}\n```\n\n"
}
4 changes: 4 additions & 0 deletions package.nls.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"command.askAI": "✨ Aide: Ask AI",
"command.codeConvert": "✨ Aide: Code Convert",
"command.codeViewerHelper": "✨ Aide: Code Viewer Helper",
"command.renameVariable": "✨ Aide: Rename Variable",
"config.title": "Aide Configuration",
"config.aiPrompt.description": "Template for copied content, use #{content} as a placeholder for file content",
"config.aiCommand.description": "Custom AI command template. Available variables: #{filesRelativePath}, #{filesFullPath}, #{content}",
Expand All @@ -29,10 +30,13 @@
"error.noContext": "Context not initialized",
"info.copied": "File contents have been copied to clipboard",
"info.customLanguage": "Custom language",
"info.noAiSuggestionsVariableName": "AI thinks your variable name is already good",
"info.processing": "Aide is processing...",
"input.array.promptEnding": "Enter comma separated values",
"input.json.promptEnding": "Enter JSON formatted value",
"input.aiCommand.prompt": "Enter question for AI command",
"input.aiCommand.placeholder": "Enter question for AI command",
"input.codeConvertTargetLanguage.prompt": "Select convert target language",
"input.selectAiSuggestionsVariableName.prompt": "Select AI suggestions variable name",
"file.content": "File: {0}\n```{1}\n{2}\n```\n\n"
}
4 changes: 4 additions & 0 deletions package.nls.zh-cn.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"command.askAI": "✨ Aide: 问 AI",
"command.codeConvert": "✨ Aide: 代码转换",
"command.codeViewerHelper": "✨ Aide: 代码查看器助手",
"command.renameVariable": "✨ Aide: 重命名变量",
"config.title": "Aide 配置",
"config.aiPrompt.description": "复制内容的模板,使用#{content}作为文件内容的占位符",
"config.aiCommand.description": "自定义 AI 命令模板。可用变量:#{filesRelativePath}, #{filesFullPath}, #{content}",
Expand All @@ -29,10 +30,13 @@
"error.noContext": "上下文未初始化",
"info.copied": "文件内容已复制到剪贴板",
"info.customLanguage": "自定义语言",
"info.noAiSuggestionsVariableName": " AI 觉得你这个变量名字已经很好了",
"info.processing": "Aide 正在处理中...",
"input.array.promptEnding": "输入逗号分隔的值",
"input.json.promptEnding": "输入 JSON 格式的值",
"input.aiCommand.prompt": "输入 AI 命令的问题",
"input.aiCommand.placeholder": "输入 AI 命令的问题",
"input.codeConvertTargetLanguage.prompt": "选择转换目标语言",
"input.selectAiSuggestionsVariableName.prompt": "选择 AI 建议的变量名",
"file.content": "File: {0}\n```{1}\n{2}\n```\n\n"
}
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

38 changes: 26 additions & 12 deletions src/ai/model-providers/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,17 @@ import {
type Runnable,
type RunnableConfig
} from '@langchain/core/runnables'
import { z } from 'zod'

export interface BaseModelProviderCreateRunnableOptions {
historyMessages: BaseMessage[]
historyMessages?: BaseMessage[]
}

export interface BaseModelProviderCreateStructuredOutputRunnableOptions<
ZSchema extends z.ZodType<any>
> {
historyMessages?: BaseMessage[]
zodSchema: ZSchema
}

export abstract class BaseModelProvider<Model extends BaseChatModel> {
Expand Down Expand Up @@ -46,16 +54,8 @@ export abstract class BaseModelProvider<Model extends BaseChatModel> {
return prompt
}

createChain(
prompt: ChatPromptTemplate,
model: Model
): MaybePromise<Runnable<any, AIMessageChunk, RunnableConfig>> {
const chain = prompt.pipe(model)
return chain
}

createRunnableWithMessageHistory(
chain: Runnable<any, AIMessageChunk, RunnableConfig>,
createRunnableWithMessageHistory<Chunk extends AIMessageChunk>(
chain: Runnable<any, Chunk, RunnableConfig>,
historyMessages: BaseMessage[]
) {
return new RunnableWithMessageHistory({
Expand All @@ -82,7 +82,21 @@ export abstract class BaseModelProvider<Model extends BaseChatModel> {
const { historyMessages } = options ?? {}
const model = await this.createModel()
const prompt = await this.createPrompt()
const chain = await this.createChain(prompt, model)
const chain = prompt.pipe(model)
return await this.createRunnableWithMessageHistory(
chain,
historyMessages || []
)
}

async createStructuredOutputRunnable<ZSchema extends z.ZodType<any>>(
options: BaseModelProviderCreateStructuredOutputRunnableOptions<ZSchema>
) {
const { historyMessages, zodSchema } = options
const model = await this.createModel()
const prompt = await this.createPrompt()
const chain = prompt.pipe(model.withStructuredOutput(zodSchema))

return await this.createRunnableWithMessageHistory(
chain,
historyMessages || []
Expand Down
4 changes: 2 additions & 2 deletions src/ai/model-providers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ export const getCurrentSessionIdHistoriesMap = async () => {
return ModelProvider.sessionIdHistoriesMap
}

export const createCurrentModelRunnable = async () => {
export const createModelProvider = async () => {
const ModelProvider = await getCurrentModelProvider()
const modelProvider = new ModelProvider()
return modelProvider.createRunnable()
return modelProvider
}
8 changes: 4 additions & 4 deletions src/ai/tmp-file-writer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import {
createTmpFileAndWriter,
type CreateTmpFileOptions
} from '@/create-tmp-file'
import { hideLoading, showLoading } from '@/loading'
import { hideProcessLoading, showProcessLoading } from '@/loading'
import {
removeCodeBlockEndSyntax,
removeCodeBlockStartSyntax,
Expand All @@ -24,12 +24,12 @@ export const tmpFileWriter = async (options: TmpFileWriterOptions) => {
const ModelProvider = await getCurrentModelProvider()

try {
showLoading()
showProcessLoading()
const aiStream = await buildAiStream()

for await (const chunk of aiStream) {
if (isClosedWithoutSaving()) {
hideLoading()
hideProcessLoading()
return
}

Expand Down Expand Up @@ -65,6 +65,6 @@ export const tmpFileWriter = async (options: TmpFileWriterOptions) => {
// write the final code
await writeText(finalCode)
} finally {
hideLoading()
hideProcessLoading()
}
}
10 changes: 5 additions & 5 deletions src/commands/code-convert.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {
createCurrentModelRunnable,
createModelProvider,
getCurrentSessionIdHistoriesMap
} from '@/ai/model-providers'
import { tmpFileWriter } from '@/ai/tmp-file-writer'
Expand Down Expand Up @@ -104,8 +104,8 @@ export const handleCodeConvert = async () => {
} = await createTmpFileInfo()

const targetLanguageId = await getTargetLanguageId(originalFileLanguageId)

const aiRunnable = await createCurrentModelRunnable()
const modelProvider = await createModelProvider()
const aiRunnable = await modelProvider.createRunnable()
const sessionId = `codeConvert:${tmpFileUri.fsPath}}`
const aiRunnableConfig: RunnableConfig = {
configurable: {
Expand All @@ -117,7 +117,7 @@ export const handleCodeConvert = async () => {
const isSessionHistoryExists = !!sessionIdHistoriesMap[sessionId]
const isContinue = isTmpFileHasContent && isSessionHistoryExists

const generatePrompt = await buildGeneratePrompt({
const prompt = await buildGeneratePrompt({
sourceLanguageId: originalFileLanguageId,
targetLanguageId,
sourceCode: originalFileContent
Expand All @@ -132,7 +132,7 @@ export const handleCodeConvert = async () => {

const aiStream = aiRunnable.stream(
{
input: generatePrompt
input: prompt
},
aiRunnableConfig
)
Expand Down
Loading

0 comments on commit cb03027

Please sign in to comment.