Compare commits

...

49 Commits

Author SHA1 Message Date
Andrew df646b34e2 amend 2024-10-31 20:31:45 -07:00
Andrew 5e41a555dc add inset-update test 2024-10-31 20:31:07 -07:00
mp 4a9962a7fc add native updateEditorInset() function 2024-10-31 19:24:44 -07:00
mp dd48db0ed3 minor changes 2024-10-31 19:23:17 -07:00
mp d7c00addd5 update inline diffs 2024-10-31 17:10:39 -07:00
Andrew Pareles b34119c4df Merge pull request #134 from Piyu-Pika/Gemini
Gemini added #new feature
2024-10-30 23:19:52 -07:00
Andrew Pareles d098291c90 minor note 2024-10-30 23:19:34 -07:00
Andrew ed9e126a4a remove duplicate extension.ts 2024-10-30 23:16:36 -07:00
Andrew a8010eec15 simplify gemini 2024-10-30 22:46:47 -07:00
Piyu-Pika 8cd1ea305c Gemini 2024-10-31 10:41:04 +05:30
Piyush Bhardwaj 762264b030 Merge branch 'main' into Gemini 2024-10-31 10:28:17 +05:30
Andrew Pareles 48d5369196 amend 2024-10-30 19:09:43 -07:00
Andrew Pareles aab840db2d amend 2024-10-30 19:02:48 -07:00
Andrew Pareles 3526005e1c amend 2024-10-30 19:02:22 -07:00
Andrew Pareles 0ef8c66d54 simplify readme 2024-10-30 19:01:56 -07:00
Andrew cd9173c802 move ctrlk 2024-10-30 18:59:17 -07:00
Piyu-Pika 0c8a185df7 Gemini added 2024-10-29 18:05:07 +05:30
Andrew 0f0719c596 fix type 2024-10-29 00:26:46 -07:00
Andrew d9397d870f change CodeSelection type 2024-10-28 17:17:26 -07:00
Andrew 1704a7de7a improve line rounding 2024-10-28 16:34:19 -07:00
Andrew 616cd2e39b update back to enum 2024-10-28 15:58:48 -07:00
Andrew Pareles 222f90bbea Merge pull request #133 from voideditor/multiple-webviews
Max tokens is optional + other config updates - Fixes #128
2024-10-28 15:50:40 -07:00
Andrew ab5245d2d9 Max tokens is optional + other config updates - Fixes #128 2024-10-28 15:50:05 -07:00
Andrew Pareles a7a4488848 minor Contributing changes 2024-10-28 04:22:19 -07:00
Andrew Pareles 8e72c1392a Merge pull request #125 from voideditor/multiple-webviews
Speculative Edits
2024-10-28 03:59:53 -07:00
Andrew 70b6af34e1 Merge branch 'main' into multiple-webviews 2024-10-28 03:58:36 -07:00
Andrew 119462f663 fix imports?? 2024-10-28 03:58:09 -07:00
Andrew 8ee665cd57 fix imports 2024-10-28 03:53:40 -07:00
Andrew ace3f181ed Merge branch 'speculative-edits' into multiple-webviews 2024-10-28 03:53:02 -07:00
Andrew d3962acd30 merge - but appears broken 2024-10-28 03:44:13 -07:00
Andrew 18557c8f6e comment out ctrlk so it builds 2024-10-28 03:37:18 -07:00
Andrew 29b037726e Merge branch 'speculative-edits' into multiple-webviews 2024-10-28 03:36:39 -07:00
Andrew 59dc193f97 update contrib 2024-10-26 21:36:45 -07:00
Andrew Pareles bd778d259b fix typo 2024-10-26 21:33:12 -07:00
Andrew 605cf236a5 link issues 2024-10-26 19:17:53 -07:00
Andrew 8bc3a0d277 windows build works!! 2024-10-26 19:17:20 -07:00
Andrew d80c88bc38 move files to right places 2024-10-25 22:39:13 -07:00
Andrew dd34a5be57 fix ctrl L change 2024-10-25 22:35:13 -07:00
Andrew f4be80b724 Merge remote-tracking branch 'origin/ctrlk-diff-ui' into multiple-webviews 2024-10-25 22:31:44 -07:00
Andrew b40c58b78a Merge remote-tracking branch 'origin/speculative-edits' into multiple-webviews 2024-10-25 22:25:47 -07:00
Andrew 64468b6f4d Merge branch 'speculative-edits' into multiple-webviews 2024-10-25 22:14:11 -07:00
Andrew 8f83b063f1 add ctrlk webview provider 2024-10-25 22:10:22 -07:00
Andrew f56772a07a amend 2024-10-25 19:58:35 -07:00
Andrew 38662d2824 major refactor, allow 3 types of webview 2024-10-25 19:49:59 -07:00
Andrew a51873c06a move files to extension/ 2024-10-25 15:58:06 -07:00
Andrew a29543e4a7 Promisify 2024-10-25 01:33:54 -07:00
Andrew d4a2ac2796 draft 2024-10-25 01:22:10 -07:00
Andrew 4b5e09c124 Merge remote-tracking branch 'origin/speculative-edits' into ctrlk-diff-ui 2024-10-24 21:08:57 -07:00
Andrew f8f48fb98b + 2024-10-24 20:48:04 -07:00
45 changed files with 699 additions and 397 deletions
+68 -46
View File
@@ -1,15 +1,13 @@
# Contributing to Void
Welcome! 👋 This is a guide on how to contribute to Void. We want to make it as easy as possible to contribute, so if you have any questions or comments, reach out via email or discord!
Welcome! 👋 This is the official guide on how to contribute to Void. We want to make it as easy as possible to contribute, so if you have any questions or comments, reach out via email or discord!
There are two main ways to contribute:
There are a few ways to contribute:
- Suggest New Features ([discord](https://discord.gg/RSNjgaugJs))
- Build New Features ([project](https://github.com/orgs/voideditor/projects/2/views/3))
- Suggest New Features ([Discord](https://discord.gg/RSNjgaugJs))
- Build New Features ([Project](https://github.com/orgs/voideditor/projects/2/views/3))
- Submit Issues/Docs/Bugs ([Issues](https://github.com/voideditor/void/issues))
We use a [VSCode extension](https://code.visualstudio.com/api/get-started/your-first-extension) to implement most of Void's functionality. Scroll down to see 1. How to build/contribute to the Extension, or 2. How to build/contribute to the full IDE (for more native changes).
For some useful links we've compiled see [`VOID_USEFUL_LINKS.md`](https://github.com/voideditor/void/blob/main/VOID_USEFUL_LINKS.md).
## 1. Building the Extension
@@ -29,23 +27,51 @@ git clone https://github.com/voideditor/void
npm install
```
4. Compile the React by running `npm run build`. We created this build command to convert `sidebar/index.tsx` into `dist/`.
1. Compile the React files by running `npm run build`. This build command converts all the Tailwind/React entrypoint files into raw .css and .js files in `dist/`.
```
npm run build
```
5. Run the project by pressing <kbd>F5</kbd>.
5. Run the extension in a new window by pressing <kbd>F5</kbd>.
This will start a new instance of VSCode with the extension enabled. If this doesn't work, you can press <kbd>Ctrl+Shift+P</kbd>, select "Debug: Start Debugging", and select "VSCode Extension Development".
## 2. Building the full IDE
If you want to work on the full IDE, please follow the steps below. If you have any questions/issues, you can refer to VSCode's full [How to Contribute](https://github.com/microsoft/vscode/wiki/How-to-Contribute) page, which is where the steps below come from. Also feel free to submit an issue or get in touch with us with any build errors.
If you want to work on the full IDE, please follow the steps below. If you have any questions/issues, you can refer to VSCode's full [How to Contribute](https://github.com/microsoft/vscode/wiki/How-to-Contribute) page. Also feel free to submit an issue or get in touch with us with any build errors.
### a. Building on a Mac
<!-- TODO say whether you can build each distribution on any Operating System, or if you need to build Windows on Windows, etc -->
To build on a Mac, open `void/` in VSCode. Make sure you've built the extension by following the steps above (or just run `cd ./extensions/void && npm install && npm run build && npm run compile && cd ../..`). Also make sure you have Python and XCode installed on your system (you probably do by default).
### a. Build Prerequisites - Mac
If you're using a Mac, make sure you have Python and XCode installed (you probably do by default).
### b. Build Prerequisites - Windows
If you're using a Windows computer, first get [Visual Studio 2022](https://visualstudio.microsoft.com/thank-you-downloading-visual-studio/?sku=Community) (recommended) or [VS Build Tools](https://visualstudio.microsoft.com/thank-you-downloading-visual-studio/?sku=BuildTools) (not recommended). If you already have both, you might need to run the next few steps on both of them.
Find the box for Visual Studio 2022 (or VS Build Tools) and click Install/Modify.
Under Workloads, select "Desktop development with C++" and "Node.js build tools".
Under Individual components, select every item under:
- `MSVC v143 - VS 2022 C++ x64/x86 Spectre-mitigated libs (Latest)`,
- `C++ ATL for latest build tools with Spectre Mitigations`,
- `C++ MFC for latest build tools with Spectre Mitigations`.
Finally, click Install/Modify.
### c. Build Prerequisites - Linux
We haven't created prerequisite steps for building on Linux yet, but you can follow [How to Contribute](https://github.com/microsoft/vscode/wiki/How-to-Contribute).
### Build instructions
Before building Void, please follow the prerequisite steps above for your operating system. Also make sure you've already built the Void extension (or just run `cd ./extensions/void && npm install && npm run build && npm run compile && cd ../..`).
To build Void, first open `void/` in VSCode. Then:
1. Install all dependencies.
@@ -53,9 +79,13 @@ To build on a Mac, open `void/` in VSCode. Make sure you've built the extension
npm install
```
2. Run `npm run watch`.
2. Press <kbd>Ctrl+Shift+B</kbd>, or if you prefer using the terminal run `npm run watch`.
This can take ~5 min. It's done when you see something like:
This can take ~5 min.
If you ran <kbd>Ctrl+Shift+B</kbd>, the build is done when you see two check marks.
If you ran `npm run watch`, the build is done when you see something like this:
```
[watch-extensions] [00:37:39] Finished compilation extensions with 0 errors after 19303 ms
@@ -66,48 +96,37 @@ This can take ~5 min. It's done when you see something like:
<!-- 3. Press <kbd>Ctrl+Shift+B</kbd> to start the build process. -->
3. In a new terminal, run `./scripts/code.sh`.
This should open up the built IDE after loading for some time. To see new changes without restarting the build, use <kbd>Ctrl+Shift+P</kbd> and run "Reload Window".
To bundle the IDE, run `npm run gulp vscode-darwin-arm64`. Here are the full options: `vscode-{win32-ia32 | win32-x64 | darwin-x64 | darwin-arm64 | linux-ia32 | linux-x64 | linux-arm}(-min)`
1. In a new terminal, run `./scripts/code.sh` (Mac/Linux) or `/.scripts/code.bat` (Windows). This should open up the built IDE!
You can always press <kbd>Ctrl+Shift+P</kbd> and run "Reload Window" inside the new window to see changes without re-building.
Now that you're set up, feel free to check out our [Issues](https://github.com/voideditor/void/issues) page!
**Common Fixes:**
### Common Fixes
- Make sure you have the same NodeJS version as `.nvmrc`.
- If you see `X [ERROR] Cannot start service: Host version "0.23.1" does not match binary version "0.23.0"`, run `npm i -D esbuild@0.23.0`
### b. Building on Windows
To build on Windows, please refer to [How to Contribute](https://github.com/microsoft/vscode/wiki/How-to-Contribute). We recommend building on Mac; we're Windows users who switch to Mac to build right now.
<!-- Get [Visual Studio 2022](https://visualstudio.microsoft.com/thank-you-downloading-visual-studio/?sku=Community). Also find the boxes for "Desktop development with C++" and "Node.js development" and get those, too.
If you get a node-gyp error in the next few steps, you should also get [Visual Studio Build Tools](https://visualstudio.microsoft.com/thank-you-downloading-visual-studio/?sku=BuildTools), find the Visual Studio Build Tools box, click Install (or Modify), then in Individual Components:
check every item under `MSVC v143 - VS 2022 C++ x64/x86 Spectre-mitigated libs (Latest)`, `C++ ATL for latest build tools with Spectre Mitigations`, and `C++ MFC for latest build tools with Spectre Mitigations`.
- If you see `[ERROR] Cannot start service: Host version "0.23.1" does not match binary version "0.23.0"`, run `npm i -D esbuild@0.23.0` or do a clean install of your npm dependencies.
```
npm config set msvs_version 2022
```
-->
## Bundling
To bundle the IDE into an executable, run `npm run gulp vscode-darwin-arm64`.
Here are the full options: `vscode-{win32-ia32 | win32-x64 | darwin-x64 | darwin-arm64 | linux-ia32 | linux-x64 | linux-arm}(-min)`
## Roadmap
Here are the most important topics on our Roadmap. More ⭐'s = more important.
These sometimes get outdated - please refer to our Issues page for the latest issues.
Here are the most important topics on our Roadmap. More ⭐'s = more important. Please refer to our [Issues](https://github.com/voideditor/void/issues) page for the latest issues.
## ⭐⭐⭐ Make History work well.
When the user submits a response or presses the apply/accept/reject button, we should add these events to the history, allowing the user to undo/redo them. Right now there is unexpected behavior if the user tries to undo or redo their changes.
## ⭐⭐⭐ Build Cursor-style quick edits (ctrl+k).
## ⭐⭐⭐ Build Cursor-style quick edits (Ctrl+K).
When the user presses ctrl+k, an input box should appear inline with the code that they were selecting. This is somewhat difficult to do because an extension alone cannot do this, and it requires creating a new component in the IDE. We think you can modify vscode's built-in "codelens" or "zone widget" components, but we are open to alternatives.
When the user presses Ctrl+K, an input box should appear inline with the code that they were selecting. This is somewhat difficult to do because an extension alone cannot do this, and it requires creating a new component in the IDE. We think you can modify vscode's built-in "codelens" or "zone widget" components, but we are open to alternatives.
## ⭐⭐⭐ Creative.
@@ -117,21 +136,19 @@ Eventually, we want to build a convenient API for creating AI tools. The API wil
## ⭐ One-stars.
⭐ Let the user accept / reject all Diffs in an entire file via the sidebar.
⭐ Let the user Accept / Reject all Diffs in an entire file via the sidebar.
# Guidelines
Please don't make big refactors without speaking with us first. We'd like to keep the codebase similar to vscode so we can periodically rebase, and if we have big changes that gets complicated.
We're always glad to talk about new ideas, help you get set up, and make sure your changes align with our vision for the project. Feel free to shoot us a message in the #general channel of the [Discord](https://discord.gg/RSNjgaugJs) for any reason. Please check in especially if you want to make a lot of changes or build a large new feature.
# Submitting a Pull Request
Please submit a pull request once you've made a change. Here are a few guidelines:
- A PR should be about one _single_ feature change. The fewer items you change, the more likely the PR is to be accepted.
## Submitting a Pull Request
- Your PR should contain a description that first explains at a high level what you did, and then describes the exact changes you made (and to which files). Please don't use vague statements like "refactored code" or "improved types" (instead, describe what code you refactored, or what types you changed).
Please submit a pull request once you've made a change. You don't need to submit an issue.
- Try to avoid refactoring and making feature changes in the same PR.
Please don't use AI to write your PR 🙂.
# Relevant files
@@ -156,3 +173,8 @@ We keep track of all the files we've changed with Void so it's easy to rebase:
- build/npm/dirs.js
- vscode.proposed.editorInsets.d.ts - not modified, but code copied
## References
For some useful links we've compiled on VSCode, see [`VOID_USEFUL_LINKS.md`](https://github.com/voideditor/void/blob/main/VOID_USEFUL_LINKS.md).
+4 -10
View File
@@ -1,22 +1,16 @@
# Welcome to Void.
Void is the open-source Cursor alternative. This repo contains the full sourcecode for Void. We have a [waitlist](https://voideditor.com/email) for downloading the official release, but you can build and develop Void right now.
Void is the open-source Cursor alternative.
If you're new, welcome! Feel free to check out our [Project board](https://github.com/orgs/voideditor/projects/2/views/3) for the most pressing Issues to work on, and see [`CONTRIBUTING.md`](https://github.com/voideditor/void/blob/main/CONTRIBUTING.md) for instructions on building and running Void.
This repo contains the full sourcecode for Void. We have a [waitlist](https://voideditor.com/email) for downloading the official release, but you can build and develop Void right now.
If you're new, welcome!
## Contributing
To build and run Void, see [`CONTRIBUTING.md`](https://github.com/voideditor/void/blob/main/CONTRIBUTING.md).
To build and run Void, follow the steps in [`CONTRIBUTING.md`](https://github.com/voideditor/void/blob/main/CONTRIBUTING.md).
## Reference
Void is a fork of the of [vscode](https://github.com/microsoft/vscode) repository.
For some useful links we've compiled see [`VOID_USEFUL_LINKS.md`](https://github.com/voideditor/void/blob/main/VOID_USEFUL_LINKS.md).
Void is a fork of the of [vscode](https://github.com/microsoft/vscode) repository. For some useful links on VSCode, see [`VOID_USEFUL_LINKS.md`](https://github.com/voideditor/void/blob/main/VOID_USEFUL_LINKS.md).
## Support
Feel free to reach out in our [Discord](https://discord.gg/RSNjgaugJs) or contact us via email.
+3 -2
View File
@@ -10,7 +10,8 @@
"type": "extensionHost",
"request": "launch",
"args": [
"--extensionDevelopmentPath=${workspaceFolder}"
"--extensionDevelopmentPath=${workspaceFolder}",
"--enable-proposed-api=void.void",
],
"outFiles": [
"${workspaceFolder}/out/**/*.js"
@@ -18,4 +19,4 @@
"preLaunchTask": "${defaultBuildTask}"
}
]
}
}
-19
View File
@@ -1,19 +0,0 @@
const tailwindcss = require('tailwindcss')
const autoprefixer = require('autoprefixer')
const postcss = require('postcss')
const fs = require('fs')
const from = 'src/sidebar/styles.css'
const to = 'dist/sidebar/styles.css'
const original_css_contents = fs.readFileSync(from, 'utf8')
postcss([
tailwindcss, // this compiles tailwind of all the files specified in tailwind.config.json
autoprefixer,
])
.process(original_css_contents, { from, to })
.then(processed_css_contents => { fs.writeFileSync(to, processed_css_contents.css) })
.catch(error => {
console.error('Error in build-css:', error)
})
-13
View File
@@ -1,13 +0,0 @@
const esbuild = require('esbuild')
// Build JS
esbuild.build({
entryPoints: ['src/sidebar/index.tsx'],
bundle: true,
minify: true,
sourcemap: true,
outfile: 'dist/sidebar/index.js',
format: 'iife', // apparently iife is safe for browsers (safer than cjs)
platform: 'browser',
external: ['vscode'],
}).catch(() => process.exit(1));
+64
View File
@@ -0,0 +1,64 @@
const tailwindcss = require('tailwindcss')
const autoprefixer = require('autoprefixer')
const postcss = require('postcss')
const fs = require('fs')
const convertTailwindToCSS = ({ from, to }) => {
console.log('converting ', from, ' --> ', to)
const original_css_contents = fs.readFileSync(from, 'utf8')
return postcss([
tailwindcss, // this compiles tailwind of all the files specified in tailwind.config.json
autoprefixer,
])
.process(original_css_contents, { from, to })
.then(processed_css_contents => { fs.writeFileSync(to, processed_css_contents.css) })
.catch(error => {
console.error('Error in build-css:', error)
})
}
const esbuild = require('esbuild')
const convertTSXtoJS = async ({ from, to }) => {
console.log('converting ', from, ' --> ', to)
return esbuild.build({
entryPoints: [from],
bundle: true,
minify: true,
sourcemap: true,
outfile: to,
format: 'iife', // apparently iife is safe for browsers (safer than cjs)
platform: 'browser',
external: ['vscode'],
}).catch(() => process.exit(1));
}
(async () => {
// convert tsx to js
await convertTSXtoJS({
from: 'src/webviews/sidebar/index.tsx',
to: 'dist/webviews/sidebar/index.js',
})
await convertTSXtoJS({
from: 'src/webviews/ctrlk/index.tsx',
to: 'dist/webviews/ctrlk/index.js',
})
await convertTSXtoJS({
from: 'src/webviews/diffline/index.tsx',
to: 'dist/webviews/diffline/index.js',
})
// convert tailwind to css
await convertTailwindToCSS({
from: 'src/webviews/styles.css',
to: 'dist/webviews/styles.css',
})
})()
+11 -8
View File
@@ -10,6 +10,7 @@
"devDependencies": {
"@anthropic-ai/sdk": "^0.29.2",
"@eslint/js": "^9.9.1",
"@google/generative-ai": "^0.21.0",
"@monaco-editor/react": "^4.6.0",
"@rrweb/types": "^2.0.0-alpha.17",
"@types/diff": "^5.2.2",
@@ -737,6 +738,16 @@
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
}
},
"node_modules/@google/generative-ai": {
"version": "0.21.0",
"resolved": "https://registry.npmjs.org/@google/generative-ai/-/generative-ai-0.21.0.tgz",
"integrity": "sha512-7XhUbtnlkSEZK15kN3t+tzIMxsbKm/dSkKBFalj+20NvPKe1kBY7mR2P7vuijEn+f06z5+A8bVGKO0v39cr6Wg==",
"dev": true,
"license": "Apache-2.0",
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@humanwhocodes/config-array": {
"version": "0.13.0",
"resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.13.0.tgz",
@@ -6013,14 +6024,6 @@
"node": ">=10"
}
},
"node_modules/monaco-editor": {
"version": "0.52.0",
"resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.52.0.tgz",
"integrity": "sha512-OeWhNpABLCeTqubfqLMXGsqf6OmPU6pHM85kF3dhy6kq5hnhuVS1p3VrEW/XhWHc71P2tHyS5JFySD8mgs1crw==",
"dev": true,
"license": "MIT",
"peer": true
},
"node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+6 -2
View File
@@ -10,8 +10,11 @@
"categories": [
"Other"
],
"enabledApiProposals": [
"editorInsets"
],
"activationEvents": [],
"main": "./out/extension.js",
"main": "./out/extension/extension.js",
"contributes": {
"configuration": {
"title": "Void",
@@ -104,13 +107,14 @@
"vscode:prepublish": "npm run compile",
"compile": "tsc -p ./",
"watch": "tsc -watch -p ./",
"build": "rimraf dist && node build-tsx.js && node build-css.js",
"build": "rimraf dist && node build/build.js",
"pretest": "tsc -p ./ && eslint src --ext ts",
"test": "vscode-test"
},
"devDependencies": {
"@anthropic-ai/sdk": "^0.29.2",
"@eslint/js": "^9.9.1",
"@google/generative-ai": "^0.21.0",
"@monaco-editor/react": "^4.6.0",
"@rrweb/types": "^2.0.0-alpha.17",
"@types/diff": "^5.2.2",
@@ -1,85 +0,0 @@
// renders the code from `src/sidebar`
import * as vscode from 'vscode';
function generateNonce() {
let text = "";
const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (let i = 0; i < 32; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
export class SidebarWebviewProvider implements vscode.WebviewViewProvider {
public static readonly viewId = 'void.viewnumberone';
public webview: Promise<vscode.Webview> // used to send messages to the webview, resolved by _res in resolveWebviewView
private _res: (c: vscode.Webview) => void // used to resolve the webview
private readonly _extensionUri: vscode.Uri
// private _webviewView?: vscode.WebviewView;
private _webviewDeps: string[] = [];
constructor(context: vscode.ExtensionContext) {
// const extensionPath = context.extensionPath // the directory where the extension is installed, might be useful later... was included in webviewProvider code
this._extensionUri = context.extensionUri
let temp_res: typeof this._res | undefined = undefined
this.webview = new Promise((res, rej) => { temp_res = res })
if (!temp_res) throw new Error("Void sidebar provider: resolver was undefined")
this._res = temp_res
}
// called by us
updateWebviewHTML(webview: vscode.Webview) {
this._webviewDeps = []
const scriptUri = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, 'dist/sidebar/index.js'));
const stylesUri = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, 'dist/sidebar/styles.css'));
const rootUri = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri));
const nonce = generateNonce();
const webviewHTML = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Custom View</title>
<meta http-equiv="Content-Security-Policy" content="img-src vscode-resource: https:; script-src 'nonce-${nonce}'; style-src vscode-resource: 'unsafe-inline' http: https: data:;">
<base href="${rootUri}/">
<link href="${stylesUri}" rel="stylesheet">
</head>
<body>
<div id="root"></div>
<div id="ctrlkroot"></div>
<script nonce="${nonce}" src="${scriptUri}"></script>
</body>
</html>`;
webview.html = webviewHTML;
}
// called internally by vscode
resolveWebviewView(
webviewView: vscode.WebviewView,
context: vscode.WebviewViewResolveContext,
token: vscode.CancellationToken,
) {
const webview = webviewView.webview;
webview.options = {
enableScripts: true,
localResourceRoots: [this._extensionUri]
};
this.updateWebviewHTML(webview);
// resolve webview and _webviewView
this._res(webview);
// this._webviewView = webviewView;
}
}
@@ -1,14 +0,0 @@
import * as vscode from 'vscode'
export const readFileContentOfUri = async (uri: vscode.Uri): Promise<string> => {
const document = await vscode.workspace.openTextDocument(uri);
return document.getText().replace(/\r\n/g, '\n') ?? '' // Normalize line endings
};
// this is the old version, which only reads the most recently saved version
// export const readFileContentOfUri = async (uri: vscode.Uri) => {
// return Buffer.from(await vscode.workspace.fs.readFile(uri)).toString('utf8')
// .replace(/\r\n/g, '\n') // replace windows \r\n with \n
// }
+73 -15
View File
@@ -1,7 +1,8 @@
import Anthropic from '@anthropic-ai/sdk';
import OpenAI from 'openai';
import { Ollama } from 'ollama/browser'
import { VoidConfig } from '../sidebar/contextForConfig';
import { Content, GoogleGenerativeAI, GoogleGenerativeAIError, GoogleGenerativeAIFetchError } from '@google/generative-ai';
import { VoidConfig } from '../webviews/common/contextForConfig'
export type AbortRef = { current: (() => void) | null }
@@ -37,8 +38,13 @@ type SendLLMMessageFnTypeExternal = (params: {
abortRef: AbortRef,
}) => void
const parseMaxTokensStr = (maxTokensStr: string) => {
// parse the string but only if the full string is a valid number, eg parseInt('100abc') should return NaN
let int = isNaN(Number(maxTokensStr)) ? undefined : parseInt(maxTokensStr)
if (Number.isNaN(int))
return undefined
return int
}
// Anthropic
const sendAnthropicMsg: SendLLMMessageFnTypeInternal = ({ messages, onText, onFinalMessage, onError, voidConfig }) => {
@@ -58,7 +64,7 @@ const sendAnthropicMsg: SendLLMMessageFnTypeInternal = ({ messages, onText, onFi
system: systemMessage,
messages: anthropicMessages,
model: voidConfig.anthropic.model,
max_tokens: parseInt(voidConfig.default.maxTokens),
max_tokens: parseMaxTokensStr(voidConfig.default.maxTokens)!, // this might be undefined, but it will just throw an error for the user
});
let did_abort = false
@@ -96,8 +102,62 @@ const sendAnthropicMsg: SendLLMMessageFnTypeInternal = ({ messages, onText, onFi
return { abort }
};
// Gemini
const sendGeminiMsg: SendLLMMessageFnTypeInternal = async ({ messages, onText, onFinalMessage, onError, voidConfig, abortRef }) => {
let didAbort = false
let fullText = ''
abortRef.current = () => {
didAbort = true
}
const genAI = new GoogleGenerativeAI(voidConfig.gemini.apikey);
const model = genAI.getGenerativeModel({ model: voidConfig.gemini.model });
// remove system messages that get sent to Gemini
// str of all system messages
let systemMessage = messages
.filter(msg => msg.role === 'system')
.map(msg => msg.content)
.join('\n');
// Convert messages to Gemini format
const geminiMessages: Content[] = messages
.filter(msg => msg.role !== 'system')
.map((msg, i) => ({
parts: [{ text: msg.content }],
role: msg.role === 'assistant' ? 'model' : 'user'
}))
model.generateContentStream({ contents: geminiMessages, systemInstruction: systemMessage, })
.then(async response => {
abortRef.current = () => {
// response.stream.return(fullText)
didAbort = true;
}
for await (const chunk of response.stream) {
if (didAbort) return;
const newText = chunk.text();
fullText += newText;
onText(newText, fullText);
}
onFinalMessage(fullText);
})
.catch((error) => {
if (error instanceof GoogleGenerativeAIFetchError) {
if (error.status === 400) {
onError('Invalid API key.');
}
else {
onError(`${error.name}:\n${error.message}`);
}
}
else {
onError(error);
}
})
}
// OpenAI, OpenRouter, OpenAICompatible
const sendOpenAIMsg: SendLLMMessageFnTypeInternal = ({ messages, onText, onFinalMessage, onError, voidConfig, abortRef }) => {
@@ -113,9 +173,11 @@ const sendOpenAIMsg: SendLLMMessageFnTypeInternal = ({ messages, onText, onFinal
let openai: OpenAI
let options: OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming
let maxTokens = parseMaxTokensStr(voidConfig.default.maxTokens)
if (voidConfig.default.whichApi === 'openAI') {
openai = new OpenAI({ apiKey: voidConfig.openAI.apikey, dangerouslyAllowBrowser: true });
options = { model: voidConfig.openAI.model, messages: messages, stream: true, max_completion_tokens: parseInt(voidConfig.default.maxTokens) }
options = { model: voidConfig.openAI.model, messages: messages, stream: true, max_completion_tokens: maxTokens }
}
else if (voidConfig.default.whichApi === 'openRouter') {
openai = new OpenAI({
@@ -125,11 +187,11 @@ const sendOpenAIMsg: SendLLMMessageFnTypeInternal = ({ messages, onText, onFinal
"X-Title": 'Void Editor', // Optional. Shows in rankings on openrouter.ai.
},
});
options = { model: voidConfig.openRouter.model, messages: messages, stream: true, max_completion_tokens: parseInt(voidConfig.default.maxTokens) }
options = { model: voidConfig.openRouter.model, messages: messages, stream: true, max_completion_tokens: maxTokens }
}
else if (voidConfig.default.whichApi === 'openAICompatible') {
openai = new OpenAI({ baseURL: voidConfig.openAICompatible.endpoint, apiKey: voidConfig.openAICompatible.apikey, dangerouslyAllowBrowser: true })
options = { model: voidConfig.openAICompatible.model, messages: messages, stream: true, max_completion_tokens: parseInt(voidConfig.default.maxTokens) }
options = { model: voidConfig.openAICompatible.model, messages: messages, stream: true, max_completion_tokens: maxTokens }
}
else {
console.error(`sendOpenAIMsg: invalid whichApi: ${voidConfig.default.whichApi}`)
@@ -159,7 +221,7 @@ const sendOpenAIMsg: SendLLMMessageFnTypeInternal = ({ messages, onText, onFinal
onError('Invalid API key.');
}
else {
onError(error.message);
onError(`${error.name}:\n${error.message}`);
}
}
else {
@@ -169,7 +231,6 @@ const sendOpenAIMsg: SendLLMMessageFnTypeInternal = ({ messages, onText, onFinal
};
// Ollama
export const sendOllamaMsg: SendLLMMessageFnTypeInternal = ({ messages, onText, onFinalMessage, onError, voidConfig, abortRef }) => {
@@ -187,7 +248,7 @@ export const sendOllamaMsg: SendLLMMessageFnTypeInternal = ({ messages, onText,
model: voidConfig.ollama.model,
messages: messages,
stream: true,
options: { num_predict: parseInt(voidConfig.default.maxTokens) } // this is max_tokens
options: { num_predict: parseMaxTokensStr(voidConfig.default.maxTokens) } // this is max_tokens
})
.then(async stream => {
abortRef.current = () => {
@@ -211,8 +272,6 @@ export const sendOllamaMsg: SendLLMMessageFnTypeInternal = ({ messages, onText,
};
// Greptile
// https://docs.greptile.com/api-reference/query
// https://docs.greptile.com/quickstart#sample-response-streamed
@@ -227,7 +286,6 @@ const sendGreptileMsg: SendLLMMessageFnTypeInternal = ({ messages, onText, onFin
didAbort = true
}
fetch('https://api.greptile.com/v2/query', {
method: 'POST',
headers: {
@@ -282,8 +340,6 @@ const sendGreptileMsg: SendLLMMessageFnTypeInternal = ({ messages, onText, onFin
}
export const sendLLMMessage: SendLLMMessageFnTypeExternal = ({ messages, onText, onFinalMessage, onError, voidConfig, abortRef }) => {
if (!voidConfig) return;
@@ -297,6 +353,8 @@ export const sendLLMMessage: SendLLMMessageFnTypeExternal = ({ messages, onText,
case 'openRouter':
case 'openAICompatible':
return sendOpenAIMsg({ messages, onText, onFinalMessage, onError, voidConfig, abortRef });
case 'gemini':
return sendGeminiMsg({ messages, onText, onFinalMessage, onError, voidConfig, abortRef });
case 'ollama':
return sendOllamaMsg({ messages, onText, onFinalMessage, onError, voidConfig, abortRef });
case 'greptile':
+3 -6
View File
@@ -1,11 +1,8 @@
import * as vscode from 'vscode';
import { PartialVoidConfig } from '../sidebar/contextForConfig';
import { PartialVoidConfig } from '../webviews/common/contextForConfig'
// a selection is a frozen snapshot
type CodeSelection = { selectionStr: string, selectionRange: vscode.Range, filePath: vscode.Uri }
type CodeSelection = { selectionStr: string, filePath: vscode.Uri }
type File = { filepath: vscode.Uri, content: string }
@@ -37,7 +34,7 @@ type Diff = {
// editor -> sidebar
type MessageToSidebar = (
| { type: 'ctrl+l', selection: CodeSelection } // user presses ctrl+l in the editor
| { type: 'ctrl+l', selection: CodeSelection } // user presses ctrl+l in the editor. selection and path are frozen snapshots
| { type: 'ctrl+k', selection: CodeSelection }
| { type: 'files', files: { filepath: vscode.Uri, content: string }[] }
| { type: 'partialVoidConfig', partialVoidConfig: PartialVoidConfig }
@@ -1,8 +1,9 @@
import * as vscode from 'vscode';
import { findDiffs } from './findDiffs';
import { Diff, DiffArea, BaseDiff, } from './common/shared_types';
import { readFileContentOfUri } from './common/readFileContentOfUri';
import { throttle } from 'lodash';
import { DiffArea, BaseDiff, Diff } from '../common/shared_types';
import { readFileContentOfUri } from './extensionLib/readFileContentOfUri';
import { updateWebviewHTML } from './extensionLib/updateWebviewHTML';
const THROTTLE_TIME = 100
@@ -27,10 +28,14 @@ export class DiffProvider implements vscode.CodeLensProvider {
private _originalFileOfDocument: { [docUriStr: string]: string } = {}
private _diffAreasOfDocument: { [docUriStr: string]: DiffArea[] } = {}
private _diffsOfDocument: { [docUriStr: string]: Diff[] } = {}
private _insetsOfDocument: { [docUriStr: string]: vscode.WebviewEditorInset[] } = {}
private _diffareaidPool = 0
private _diffidPool = 0
private _extensionUri: vscode.Uri
// used internally by vscode
private _onDidChangeCodeLenses: vscode.EventEmitter<void> = new vscode.EventEmitter<void>(); // signals a UI refresh on .fire() events
public readonly onDidChangeCodeLenses: vscode.Event<void> = this._onDidChangeCodeLenses.event;
@@ -42,7 +47,8 @@ export class DiffProvider implements vscode.CodeLensProvider {
}
// declared by us, registered with vscode.languages.registerCodeLensProvider()
constructor() {
constructor(context: vscode.ExtensionContext) {
this._extensionUri = context.extensionUri
console.log('Creating DisplayChangesProvider')
@@ -172,6 +178,10 @@ export class DiffProvider implements vscode.CodeLensProvider {
// reset all diffs (we update them below)
this._diffsOfDocument[docUriStr] = []
// reset all insets (we update them below)
this._insetsOfDocument[docUriStr]?.forEach(inset => inset.dispose())
this._insetsOfDocument[docUriStr] = []
// for each diffArea
for (const diffArea of diffAreas) {
@@ -210,6 +220,28 @@ export class DiffProvider implements vscode.CodeLensProvider {
)
);
// update red highlighting
this._insetsOfDocument[docUriStr] = this._diffsOfDocument[docUriStr]
.filter(diff => diff.originalCode !== '')
.map(diff => {
// create new inset
const text = originalFile.split('\n').slice(diff.originalRange.start.line, diff.originalRange.end.line + 1).join('\n')
const height = text.split('\n').length
const line = diff.range.start.line - 1
const inset = vscode.window.createWebviewTextEditorInset(editor, line, height);
updateWebviewHTML(inset.webview, this._extensionUri, { jsOutLocation: 'dist/webviews/diffline/index.js', cssOutLocation: 'dist/webviews/styles.css' },
{ text }
)
setTimeout(() => {
console.log('updating!')
vscode.window.updateWebviewTextEditorInset(inset.handle, line + 2, height)
}, 2000)
return inset
})
// for each diffArea, highlight its sweepIndex in dark gray
editor.setDecorations(
@@ -234,8 +266,6 @@ export class DiffProvider implements vscode.CodeLensProvider {
)
)
// TODO update red highlighting
// this._diffsOfDocument[docUriStr].map(diff => diff.deletedCode)
// update code lenses
this._onDidChangeCodeLenses.fire()
@@ -392,7 +422,7 @@ export class DiffProvider implements vscode.CodeLensProvider {
// figure out where to highlight based on where the AI is in the stream right now, use the last diff in findDiffs to figure that out
const diffs = findDiffs(originalDiffAreaCode, newDiffAreaCode)
const lastDiff = diffs[diffs.length - 1] ?? null
const lastDiff = diffs?.[diffs.length - 1] ?? null
// these are two different coordinate systems - new and old line number
let newFileEndLine: number // get new[0...newStoppingPoint] with line=newStoppingPoint highlighted
@@ -1,19 +1,13 @@
import * as vscode from 'vscode';
import { AbortRef, OnFinalMessage, OnText, sendLLMMessage } from "./sendLLMMessage"
import { VoidConfig } from '../sidebar/contextForConfig';
import { findDiffs } from '../findDiffs';
import { searchDiffChunkInstructions, writeFileWithDiffInstructions } from './systemPrompts';
import { throttle } from 'lodash';
import { readFileContentOfUri } from './readFileContentOfUri';
import { DiffProvider } from '../DiffProvider';
import { DiffArea } from './shared_types';
import { AbortRef, sendLLMMessage } from '../common/sendLLMMessage';
import { DiffArea } from '../common/shared_types';
import { writeFileWithDiffInstructions, searchDiffChunkInstructions } from '../common/systemPrompts';
import { VoidConfig } from '../webviews/common/contextForConfig';
import { DiffProvider } from './DiffProvider';
import { readFileContentOfUri } from './extensionLib/readFileContentOfUri';
const LINES_PER_CHUNK = 20 // number of lines to search at a time
// const THRTOTLE_TIME = 100 // minimum time between edits
// throttle(
// THRTOTLE_TIME, { trailing: true }
// )
type CompetedReturn = { isFinished: true, } | { isFinished?: undefined, }
const streamChunk = ({ diffProvider, docUri, oldFileStr, completedStr, diffRepr, diffArea, voidConfig, abortRef }: { diffProvider: DiffProvider, docUri: vscode.Uri, oldFileStr: string, completedStr: string, diffRepr: string, voidConfig: VoidConfig, diffArea: DiffArea, abortRef: AbortRef }) => {
@@ -140,7 +134,7 @@ Return \`true\` if ANY part of the chunk should be modified, and \`false\` if it
// lazily applies the diff to the file
// we chunk the text in the file, and ask an LLM whether it should edit each chunk
const applyDiffLazily = async ({ docUri, oldFileStr, voidConfig, abortRef, diffRepr, diffProvider, diffArea }: { docUri: vscode.Uri, oldFileStr: string, diffRepr: string, voidConfig: VoidConfig, diffProvider: DiffProvider, diffArea: DiffArea, abortRef: AbortRef }) => {
export const applyDiffLazily = async ({ docUri, oldFileStr, voidConfig, abortRef, diffRepr, diffProvider, diffArea }: { docUri: vscode.Uri, oldFileStr: string, diffRepr: string, voidConfig: VoidConfig, diffProvider: DiffProvider, diffArea: DiffArea, abortRef: AbortRef }) => {
// stateful variables
@@ -185,7 +179,3 @@ const applyDiffLazily = async ({ docUri, oldFileStr, voidConfig, abortRef, diffR
}
export { applyDiffLazily }
@@ -1,10 +1,9 @@
import * as vscode from 'vscode';
import { AbortRef, OnFinalMessage, OnText, sendLLMMessage } from "./sendLLMMessage"
import { VoidConfig } from '../sidebar/contextForConfig';
import { findDiffs } from '../findDiffs';
import { searchDiffChunkInstructions, writeFileWithDiffInstructions } from './systemPrompts';
import { AbortRef, OnFinalMessage, OnText, sendLLMMessage } from "../common/sendLLMMessage"
import { VoidConfig } from '../webviews/common/contextForConfig';
import { searchDiffChunkInstructions, writeFileWithDiffInstructions } from '../common/systemPrompts';
import { throttle } from 'lodash';
import { readFileContentOfUri } from './readFileContentOfUri';
import { readFileContentOfUri } from './extensionLib/readFileContentOfUri';
type Res<T> = ((value: T) => void)
@@ -1,30 +1,47 @@
import * as vscode from 'vscode';
import { DiffProvider } from './DiffProvider';
import { DiffArea, ChatThreads, MessageFromSidebar, MessageToSidebar } from './common/shared_types';
import { SidebarWebviewProvider } from './SidebarWebviewProvider';
import { v4 as uuidv4 } from 'uuid'
import { applyDiffLazily } from './common/ctrlL';
import { getVoidConfig } from './sidebar/contextForConfig';
import { readFileContentOfUri } from './common/readFileContentOfUri';
import { AbortRef } from './common/sendLLMMessage';
import { AbortRef } from '../common/sendLLMMessage';
import { MessageToSidebar, MessageFromSidebar, DiffArea, ChatThreads } from '../common/shared_types';
import { getVoidConfigFromPartial } from '../webviews/common/contextForConfig';
import { applyDiffLazily } from './applyDiffLazily';
import { DiffProvider } from './DiffProvider';
import { readFileContentOfUri } from './extensionLib/readFileContentOfUri';
import { SidebarWebviewProvider } from './providers/SidebarWebviewProvider';
import { CtrlKWebviewProvider } from './providers/CtrlKWebviewProvider';
// this comes from vscode.proposed.editorInsets.d.ts
declare module 'vscode' {
export interface WebviewEditorInset {
readonly editor: vscode.TextEditor;
readonly line: number;
readonly height: number;
readonly webview: vscode.Webview;
readonly handle: number;
readonly onDidDispose: Event<void>;
dispose(): void;
}
export namespace window {
export function createWebviewTextEditorInset(editor: vscode.TextEditor, line: number, height: number, options?: vscode.WebviewOptions): WebviewEditorInset;
export function updateWebviewTextEditorInset(handle: number, line: number, height: number): WebviewEditorInset;
}
}
const roundRangeToLines = (selection: vscode.Selection) => {
return new vscode.Range(selection.start.line, 0, selection.end.line, Number.MAX_SAFE_INTEGER)
let endLine = selection.end.character === 0 ? selection.end.line - 1 : selection.end.line // e.g. if the user triple clicks, it selects column=0, line=line -> column=0, line=line+1
return new vscode.Range(selection.start.line, 0, endLine, Number.MAX_SAFE_INTEGER)
}
const getSelection = (editor: vscode.TextEditor) => {
// get the range of the selection and the file the user is in
const selectionRange = roundRangeToLines(editor.selection);
const selectionStr = editor.document.getText(selectionRange).trim();
const filePath = editor.document.uri;
return { selectionStr, filePath }
}
export function activate(context: vscode.ExtensionContext) {
@@ -35,6 +52,8 @@ export function activate(context: vscode.ExtensionContext) {
vscode.window.registerWebviewViewProvider(SidebarWebviewProvider.viewId, sidebarWebviewProvider, { webviewOptions: { retainContextWhenHidden: true } })
);
// 1.5
const ctrlKWebviewProvider = new CtrlKWebviewProvider(context)
// 2. ctrl+l
@@ -43,30 +62,14 @@ export function activate(context: vscode.ExtensionContext) {
const editor = vscode.window.activeTextEditor
if (!editor) return
// const inset = vscode.window.createWebviewTextEditorInset(editor, 10, 10, {})
// inset.webview.html = `
// <html>
// <body style="pointer-events:none;">Hello World!</body>
// </html>
// `;
// show the sidebar
vscode.commands.executeCommand('workbench.view.extension.voidViewContainer');
// vscode.commands.executeCommand('vscode.moveViewToPanel', CustomViewProvider.viewId); // move to aux bar
// get the range of the selection
const selectionRange = roundRangeToLines(editor.selection);
// get the text the user is selecting
const selectionStr = editor.document.getText(selectionRange);
// get the file the user is in
const filePath = editor.document.uri;
const { selectionStr, filePath } = getSelection(editor)
// send message to the webview (Sidebar.tsx)
sidebarWebviewProvider.webview.then(webview => webview.postMessage({ type: 'ctrl+l', selection: { selectionStr, selectionRange, filePath } } satisfies MessageToSidebar));
sidebarWebviewProvider.webview.then(webview => webview.postMessage({ type: 'ctrl+l', selection: { selectionStr, filePath } } satisfies MessageToSidebar));
})
);
@@ -77,22 +80,16 @@ export function activate(context: vscode.ExtensionContext) {
const editor = vscode.window.activeTextEditor
if (!editor) return
// get the range of the selection
const selectionRange = roundRangeToLines(editor.selection);
// get the text the user is selecting
const selectionStr = editor.document.getText(selectionRange);
// get the file the user is in
const filePath = editor.document.uri;
const { selectionStr, filePath } = getSelection(editor)
// send message to the webview (Sidebar.tsx)
sidebarWebviewProvider.webview.then(webview => webview.postMessage({ type: 'ctrl+k', selection: { selectionStr, selectionRange, filePath } } satisfies MessageToSidebar));
// ctrlKWebviewProvider.onPressCtrlK()
// sidebarWebviewProvider.webview.then(webview => webview.postMessage({ type: 'ctrl+k', selection: { selectionStr, filePath } } satisfies MessageToSidebar));
})
);
// 3. Show an approve/reject codelens above each change
const diffProvider = new DiffProvider();
const diffProvider = new DiffProvider(context);
context.subscriptions.push(vscode.languages.registerCodeLensProvider('*', diffProvider));
// 4. Add approve/reject commands
@@ -153,7 +150,7 @@ export function activate(context: vscode.ExtensionContext) {
const docUri = editor.document.uri
const fileStr = await readFileContentOfUri(docUri)
const voidConfig = getVoidConfig(context.globalState.get('partialVoidConfig') ?? {})
const voidConfig = getVoidConfigFromPartial(context.globalState.get('partialVoidConfig') ?? {})
await applyDiffLazily({ docUri, oldFileStr: fileStr, diffRepr: m.diffRepr, voidConfig, diffProvider, diffArea, abortRef: abortApplyRef })
}
@@ -0,0 +1,13 @@
import * as vscode from 'vscode'
// export const readFileContentOfUri = async (uri: vscode.Uri): Promise<string> => {
// const document = await vscode.workspace.openTextDocument(uri.fsPath);
// return document.getText().replace(/\r\n/g, '\n') ?? '' // Normalize line endings
// };
// TODO this only accesses the most recently saved version; make it instead access the most recent version in the vscode editor
export const readFileContentOfUri = async (uri: vscode.Uri) => {
return Buffer.from(await vscode.workspace.fs.readFile(uri)).toString('utf8')
.replace(/\r\n/g, '\n') // replace windows \r\n with \n
}
@@ -0,0 +1,46 @@
import * as vscode from 'vscode'
function generateNonce() {
let text = "";
const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (let i = 0; i < 32; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
// call this when you have access to the webview to set its html
export const updateWebviewHTML = (webview: vscode.Webview, extensionUri: vscode.Uri, { jsOutLocation, cssOutLocation }: { jsOutLocation: string, cssOutLocation: string }, props?: object) => {
// 'dist/sidebar/index.js'
// 'dist/sidebar/styles.css'
const scriptUri = webview.asWebviewUri(vscode.Uri.joinPath(extensionUri, jsOutLocation));
const stylesUri = webview.asWebviewUri(vscode.Uri.joinPath(extensionUri, cssOutLocation));
const rootUri = webview.asWebviewUri(vscode.Uri.joinPath(extensionUri));
const nonce = generateNonce();
const webviewHTML = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Custom View</title>
<meta http-equiv="Content-Security-Policy" content="img-src vscode-resource: https:; script-src 'nonce-${nonce}'; style-src vscode-resource: 'unsafe-inline' http: https: data:;">
<base href="${rootUri}/">
<link href="${stylesUri}" rel="stylesheet">
</head>
<body>
<div id="root"${props ? ` data-void-props="${encodeURIComponent(JSON.stringify(props))}"` : ''}></div>
<script nonce="${nonce}" src="${scriptUri}"></script>
</body>
</html>`;
webview.html = webviewHTML
webview.options = {
enableScripts: true,
localResourceRoots: [extensionUri]
};
}
@@ -1,7 +1,8 @@
import { Range } from 'vscode';
import { diffLines, Change } from 'diff';
import { BaseDiff } from './common/shared_types';
import { BaseDiff } from '../common/shared_types';
// class Range {
@@ -0,0 +1,41 @@
// renders the code from `src/sidebar`
import * as vscode from 'vscode';
import { updateWebviewHTML as _updateWebviewHTML, updateWebviewHTML } from '../extensionLib/updateWebviewHTML';
export class CtrlKWebviewProvider {
private readonly _extensionUri: vscode.Uri
private _idPool = 0
constructor(context: vscode.ExtensionContext) {
this._extensionUri = context.extensionUri
}
onPressCtrlK() {
// // TODO if currently selecting a ctrl k element, just focus it and do nothing
// const inset = vscode.window.createWebviewTextEditorInset(editor, line, height);
// const newCtrlKId = this._idPool++
// updateWebviewHTML(inset.webview, this._extensionUri, { jsOutLocation: 'dist/webviews/ctrlk/index.js', cssOutLocation: 'dist/webviews/styles.css' },
// { id: newCtrlKId }
// )
// ctrlKWebviewProvider.webview.then(webview => webview.postMessage({ type: 'ctrl+k', selection: { selectionStr, selectionRange, filePath } } satisfies MessageToSidebar));
}
onDisposeCtrlK() {
}
}
@@ -0,0 +1,30 @@
// renders the code from `src/sidebar`
import * as vscode from 'vscode';
import { updateWebviewHTML as _updateWebviewHTML } from '../extensionLib/updateWebviewHTML';
export class SidebarWebviewProvider implements vscode.WebviewViewProvider {
public static readonly viewId = 'void.viewnumberone';
public webview: Promise<vscode.Webview> // used to send messages to the webview, resolved by _res in resolveWebviewView
private _res: (c: vscode.Webview) => void // used to resolve the webview
private readonly _extensionUri: vscode.Uri
constructor(context: vscode.ExtensionContext) {
// const extensionPath = context.extensionPath // the directory where the extension is installed, might be useful later... was included in webviewProvider code
this._extensionUri = context.extensionUri
let temp_res: typeof this._res | undefined = undefined
this.webview = new Promise((res, rej) => { temp_res = res })
if (!temp_res) throw new Error("Void sidebar provider: resolver was undefined")
this._res = temp_res
}
// called internally by vscode
resolveWebviewView(webviewView: vscode.WebviewView, context: vscode.WebviewViewResolveContext, token: vscode.CancellationToken,) {
const webview = webviewView.webview;
_updateWebviewHTML(webview, this._extensionUri, { jsOutLocation: 'dist/webviews/sidebar/index.js', cssOutLocation: 'dist/webviews/styles.css' })
this._res(webview); // resolve webview and _webviewView
}
}
-20
View File
@@ -1,20 +0,0 @@
import React, { useState } from 'react';
import { useOnVSCodeMessage } from './getVscodeApi';
export const CtrlK = () => {
const [x, sx] = useState('abc')
useOnVSCodeMessage('ctrl+k', () => {
console.log('Ctrl+K pressed')
sx('Pressed ctrl+k')
})
return <>
<div>
{x}
</div>
</>
};
-66
View File
@@ -1,66 +0,0 @@
import * as React from "react"
import { useEffect } from "react"
import * as ReactDOM from "react-dom/client"
import Sidebar from "./Sidebar"
import { CtrlK } from "./CtrlK"
import { ThreadsProvider } from "./contextForThreads"
import { ConfigProvider } from "./contextForConfig"
import { MessageToSidebar } from "../common/shared_types"
import { awaitVSCodeResponse, getVSCodeAPI, onMessageFromVSCode } from "./getVscodeApi"
import { identifyUser, initPosthog } from "./metrics/posthog"
if (typeof document === "undefined") {
console.log("index.tsx error: document was undefined")
}
const CommonEffects = () => {
// initialize posthog
useEffect(() => {
initPosthog()
}, [])
// when we get the deviceid, identify the user
useEffect(() => {
getVSCodeAPI().postMessage({ type: 'getDeviceId' });
awaitVSCodeResponse('deviceId').then((m => {
identifyUser(m.deviceId)
}))
}, [])
// Receive messages from the VSCode extension
useEffect(() => {
const listener = (event: MessageEvent) => {
const m = event.data as MessageToSidebar;
onMessageFromVSCode(m)
}
window.addEventListener('message', listener);
return () => window.removeEventListener('message', listener)
}, [])
return null
}
(() => {
// mount the sidebar on the id="root" element
const rootElement = document.getElementById("root")!
console.log("Void root Element:", rootElement)
const sidebar = (<>
<CommonEffects />
<ThreadsProvider>
<ConfigProvider>
<Sidebar />
</ConfigProvider>
</ThreadsProvider>
<ConfigProvider>
<CtrlK />
</ConfigProvider>
</>)
const root = ReactDOM.createRoot(rootElement)
root.render(sidebar)
})();
@@ -21,11 +21,12 @@ const configString = (description: string, defaultVal: string) => {
export const configFields = [
'anthropic',
'openAI',
'gemini',
'greptile',
'ollama',
'openRouter',
'openAICompatible',
'azure'
'azure',
] as const
@@ -50,6 +51,7 @@ const voidConfigInfo: Record<
"Max number of tokens to output.",
'1024',
[
"default", // this will be parseInt'd into NaN and ignored by the API. Anything that's not a number has this behavior.
"1024",
"2048",
"4096",
@@ -163,6 +165,19 @@ const voidConfigInfo: Record<
// }
// },
},
gemini: {
apikey: configString('Google API key.', ''),
model: configEnum(
'Gemini model to use.',
'gemini-1.5-flash',
[
"gemini-1.5-flash",
"gemini-1.5-pro",
"gemini-1.5-flash-8b",
"gemini-1.0-pro"
] as const
),
},
}
@@ -185,18 +200,18 @@ export type VoidConfig = {
export const getVoidConfig = (currentConfig: PartialVoidConfig): VoidConfig => {
export const getVoidConfigFromPartial = (partialVoidConfig: PartialVoidConfig): VoidConfig => {
const config = {} as PartialVoidConfig
for (let field of [...configFields, 'default'] as const) {
config[field] = {}
for (let prop in voidConfigInfo[field]) {
config[field][prop] = currentConfig[field]?.[prop] || voidConfigInfo[field][prop].defaultVal
config[field][prop] = partialVoidConfig[field]?.[prop]?.trim() || voidConfigInfo[field][prop].defaultVal
}
}
return config as VoidConfig
}
const defaultVoidConfig: VoidConfig = getVoidConfig({})
const defaultVoidConfig: VoidConfig = getVoidConfigFromPartial({})
// const [stateRef, setState] = useInstantState(initVal)
// setState instantly changes the value of stateRef instead of having to wait until the next render
@@ -234,7 +249,7 @@ export function ConfigProvider({ children }: { children: ReactNode }) {
getVSCodeAPI().postMessage({ type: 'getPartialVoidConfig' })
awaitVSCodeResponse('partialVoidConfig').then((m) => {
setPartialVoidConfig(m.partialVoidConfig)
const newFullConfig = getVoidConfig(m.partialVoidConfig)
const newFullConfig = getVoidConfigFromPartial(m.partialVoidConfig)
setVoidConfig(newFullConfig)
})
}, [setPartialVoidConfig])
@@ -254,7 +269,7 @@ export function ConfigProvider({ children }: { children: ReactNode }) {
}
}
setPartialVoidConfig(newPartialConfig)
const newFullConfig = getVoidConfig(newPartialConfig)
const newFullConfig = getVoidConfigFromPartial(newPartialConfig)
setVoidConfig(newFullConfig)
getVSCodeAPI().postMessage({ type: 'persistPartialVoidConfig', partialVoidConfig: newPartialConfig })
}
@@ -272,4 +287,3 @@ export function useVoidConfig(): ConfigValueType {
}
return context
}
@@ -0,0 +1,36 @@
import React, { ReactNode, createContext, useCallback, useContext, useEffect, useRef, useState, } from "react"
const PropsContext = createContext<any>(undefined as unknown as any)
// provider for whatever came in data-void-props
export function PropsProvider({ children, rootElement }: { children: ReactNode, rootElement: HTMLElement }) {
const [props, setProps] = useState<object | null>(null)
// update props when rootElement changes
useEffect(() => {
let props = rootElement.getAttribute("data-void-props")
let propsObj: object | null = null
if (props !== null) {
propsObj = JSON.parse(decodeURIComponent(props))
}
setProps(propsObj)
}, [rootElement])
return (
<PropsContext.Provider value={props}>
{children}
</PropsContext.Provider>
)
}
export function useVoidProps<T extends {}>(): T | null {
// context is the "value" from above
const context: T | null | undefined = useContext<T>(PropsContext)
// only undefined if has no provider
if (context === undefined) {
throw new Error("useVoidProps missing Provider")
}
return context
}
@@ -1,5 +1,5 @@
import React, { ReactNode, createContext, useCallback, useContext, useEffect, useRef, useState, } from "react"
import { ChatMessage, ChatThreads } from "../common/shared_types"
import { ChatMessage, ChatThreads } from "../../common/shared_types"
import { awaitVSCodeResponse, getVSCodeAPI } from "./getVscodeApi"
@@ -1,5 +1,5 @@
import { useEffect } from "react";
import { MessageFromSidebar, MessageToSidebar, } from "../common/shared_types";
import { MessageFromSidebar, MessageToSidebar, } from "../../common/shared_types";
import { v4 as uuidv4 } from 'uuid';
@@ -0,0 +1,66 @@
import React, { useEffect } from "react";
import * as ReactDOM from "react-dom/client"
import { MessageToSidebar } from "../../common/shared_types";
import { getVSCodeAPI, awaitVSCodeResponse, onMessageFromVSCode } from "./getVscodeApi";
import { initPosthog, identifyUser } from "./posthog";
import { ThreadsProvider } from "./contextForThreads";
import { ConfigProvider } from "./contextForConfig";
import { PropsProvider } from "./contextForProps";
const ListenersAndTracking = () => {
// initialize posthog
useEffect(() => {
initPosthog()
}, [])
// when we get the deviceid, identify the user
useEffect(() => {
getVSCodeAPI().postMessage({ type: 'getDeviceId' });
awaitVSCodeResponse('deviceId').then((m => {
identifyUser(m.deviceId)
}))
}, [])
// Receive messages from the VSCode extension
useEffect(() => {
const listener = (event: MessageEvent) => {
const m = event.data as MessageToSidebar;
onMessageFromVSCode(m)
}
window.addEventListener('message', listener);
return () => window.removeEventListener('message', listener)
}, [])
return null
}
export const mount = (children: React.ReactNode) => {
if (typeof document === "undefined") {
console.error("index.tsx error: document was undefined")
return
}
// mount the sidebar on the id="root" element
const rootElement = document.getElementById("root")!
// console.log("Void root Element:", rootElement)
const content = (<>
<ListenersAndTracking />
<PropsProvider rootElement={rootElement}>
<ThreadsProvider>
<ConfigProvider>
{children}
</ConfigProvider>
</ThreadsProvider>
</PropsProvider>
</>)
const root = ReactDOM.createRoot(rootElement)
root.render(content);
}
@@ -0,0 +1,27 @@
import React, { useState } from 'react';
import { useOnVSCodeMessage } from '../common/getVscodeApi';
export const CtrlK = () => {
const [x, sx] = useState('abc')
useOnVSCodeMessage('ctrl+k', () => {
console.log('Ctrl+K pressed')
sx('Pressed ctrl+k')
})
// const inset = vscode.window.createWebviewTextEditorInset(editor, 10, 10, {})
// inset.webview.html = `
// <html>
// <body style="pointer-events:none;">Hello World!</body>
// </html>
// `;
return <>
<div>
{x}
</div>
</>
};
@@ -0,0 +1,7 @@
import React from "react"
import { mount } from "../common/mount"
import { CtrlK } from "./CtrlK"
// this is the entry point that mounts ctrlk
mount(<CtrlK />)
@@ -0,0 +1,29 @@
import React, { useState } from 'react';
import { useOnVSCodeMessage } from '../common/getVscodeApi';
import { useVoidProps } from '../common/contextForProps';
type props = {
text: string
}
export const DiffLine = () => {
const props = useVoidProps<props>()
console.log('props!', props)
if (!props) {
return null
}
// eslint-disable-next-line react/prop-types
const text = props.text
return <>
<pre>
{text}
</pre>
</>
};
@@ -0,0 +1,7 @@
import React from "react"
import { mount } from "../common/mount"
import { DiffLine } from "./DiffLine"
// this is the entry point that mounts diffline
mount(<DiffLine />)
@@ -1,11 +1,11 @@
import React, { useState, useEffect, useRef, useCallback, FormEvent } from "react"
import { CodeSelection, ChatMessage, MessageToSidebar } from "../common/shared_types"
import { awaitVSCodeResponse, getVSCodeAPI, onMessageFromVSCode, useOnVSCodeMessage } from "./getVscodeApi"
import { CodeSelection, ChatMessage, MessageToSidebar } from "../../common/shared_types"
import { awaitVSCodeResponse, getVSCodeAPI, onMessageFromVSCode, useOnVSCodeMessage } from "../common/getVscodeApi"
import { SidebarThreadSelector } from "./SidebarThreadSelector";
import { SidebarChat } from "./SidebarChat";
import { SidebarSettings } from './SidebarSettings';
import { identifyUser } from "./metrics/posthog";
import { SidebarSettings } from "./SidebarSettings";
import { identifyUser } from "../common/posthog";
const Sidebar = () => {
@@ -4,14 +4,14 @@ import React, { FormEvent, useCallback, useEffect, useRef, useState } from "reac
import { marked } from 'marked';
import MarkdownRender from "./markdown/MarkdownRender";
import BlockCode from "./markdown/BlockCode";
import { File, ChatMessage, CodeSelection } from "../common/shared_types";
import { File, ChatMessage, CodeSelection } from "../../common/shared_types";
import * as vscode from 'vscode'
import { awaitVSCodeResponse, getVSCodeAPI, onMessageFromVSCode, useOnVSCodeMessage } from "./getVscodeApi";
import { useThreads } from "./contextForThreads";
import { sendLLMMessage } from "../common/sendLLMMessage";
import { useVoidConfig } from "./contextForConfig";
import { generateDiffInstructions } from "../common/systemPrompts";
import { captureEvent } from "./metrics/posthog";
import { awaitVSCodeResponse, getVSCodeAPI, onMessageFromVSCode, useOnVSCodeMessage } from "../common/getVscodeApi";
import { useThreads } from "../common/contextForThreads";
import { sendLLMMessage } from "../../common/sendLLMMessage";
import { useVoidConfig } from "../common/contextForConfig";
import { captureEvent } from "../common/posthog";
import { generateDiffInstructions } from "../../common/systemPrompts";
@@ -1,5 +1,5 @@
import React, { useState } from "react";
import { configFields, useVoidConfig, VoidConfigField } from "./contextForConfig";
import { configFields, useVoidConfig, VoidConfigField } from "../common/contextForConfig";
const SettingOfFieldAndParam = ({ field, param }: { field: VoidConfigField, param: string }) => {
@@ -1,5 +1,5 @@
import React from "react";
import { ThreadsProvider, useThreads } from "./contextForThreads";
import { ThreadsProvider, useThreads } from "../common/contextForThreads";
const truncate = (s: string) => {
@@ -0,0 +1,7 @@
import React from "react"
import Sidebar from "./Sidebar"
import { mount } from "../common/mount"
// this is the entry point that mounts the sidebar
mount(<Sidebar />)
@@ -1,7 +1,7 @@
import React, { JSX, useCallback, useEffect, useState } from "react"
import { marked, MarkedToken, Token, TokensList } from "marked"
import BlockCode from "./BlockCode"
import { getVSCodeAPI } from "../getVscodeApi"
import { getVSCodeAPI } from "../../common/getVscodeApi"
enum CopyButtonState {
@@ -1,3 +1,5 @@
/* all the styles are shared right now between all webviews */
@tailwind base;
@tailwind components;
@tailwind utilities;
+1 -1
View File
@@ -2,7 +2,7 @@
// inject user's vscode theme colors: https://code.visualstudio.com/api/extension-guides/webview#theming-webview-content
module.exports = {
content: ["./src/sidebar/**/*.{html,js,ts,jsx,tsx}"],
content: ["./src/webviews/**/*.{html,js,ts,jsx,tsx}"],
theme: {
extend: {
colors: {
@@ -826,6 +826,10 @@ export function createApiFactoryAndRegisterActors(accessor: ServicesAccessor): I
// checkProposedApiEnabled(extension, 'editorInsets'); // Void commented this out
return extHostEditorInsets.createWebviewEditorInset(editor, line, height, options, extension);
},
// Void created this function:
updateWebviewTextEditorInset(handle: number, line: number, height: number): vscode.WebviewEditorInset {
return extHostEditorInsets.updateEditorInset(handle, line, height);
},
createTerminal(nameOrOptions?: vscode.TerminalOptions | vscode.ExtensionTerminalOptions | string, shellPath?: string, shellArgs?: readonly string[] | string): vscode.Terminal {
if (typeof nameOrOptions === 'object') {
if ('pty' in nameOrOptions) {
@@ -99,11 +99,11 @@ export class ExtHostEditorInsets implements ExtHostEditorInsetsShape {
};
const inset = new class implements vscode.WebviewEditorInset {
readonly editor: vscode.TextEditor = editor;
readonly line: number = line;
readonly height: number = height;
readonly webview: vscode.Webview = webview;
readonly handle: number = handle;
readonly onDidDispose: vscode.Event<void> = onDidDispose.event;
dispose(): void {
@@ -125,6 +125,34 @@ export class ExtHostEditorInsets implements ExtHostEditorInsetsShape {
return inset;
}
updateEditorInset(handle: number, line: number, height: number): vscode.WebviewEditorInset {
const _inset = this._insets.get(handle);
if (!_inset) {
throw new Error(`Inset with handle ${handle} not found`);
}
const { editor, onDidReceiveMessage, inset: { webview, onDidDispose, dispose } } = _inset
const inset = new class implements vscode.WebviewEditorInset {
readonly editor: vscode.TextEditor = editor;
readonly line: number = line;
readonly height: number = height;
readonly webview: vscode.Webview = webview;
readonly handle: number = handle;
readonly onDidDispose: vscode.Event<void> = onDidDispose;
dispose = dispose
};
this._insets.set(handle, { editor, inset: inset, onDidReceiveMessage });
// _inset?.onDidReceiveMessage.fire({});
return inset
}
$onDidDispose(handle: number): void {
const value = this._insets.get(handle);
if (value) {
+2
View File
@@ -12,11 +12,13 @@ declare module 'vscode' {
readonly line: number;
readonly height: number;
readonly webview: Webview;
readonly handle: number;
readonly onDidDispose: Event<void>;
dispose(): void;
}
export namespace window {
export function createWebviewTextEditorInset(editor: TextEditor, line: number, height: number, options?: WebviewOptions): WebviewEditorInset;
export function updateWebviewTextEditorInset(handle: number, line: number, height: number): WebviewEditorInset;
}
}