Merge branch 'dev' into pe/multifile-edit-slash-cmd

This commit is contained in:
Test 2024-11-05 20:57:55 -08:00
commit c43680bdb5
32 changed files with 1082 additions and 528 deletions

View file

@ -16,8 +16,9 @@ jobs:
repo-token: ${{ secrets.CI_GITHUB_TOKEN }}
assignees: sestinj,Patrick-Erichsen
numOfAssignee: 1
- name: Add default labels
- name: "Add default labels"
uses: actions-ecosystem/action-add-labels@v1
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
labels: "needs-triage"
labels: |
"needs-triage"

View file

@ -2,5 +2,8 @@
"tabWidth": 2,
"useTabs": false,
"trailingComma": "all",
"semi": true,
"singleQuote": false,
"bracketSpacing": true,
"plugins": ["prettier-plugin-tailwindcss"]
}

2
.vscode/tasks.json vendored
View file

@ -41,7 +41,7 @@
"background": {
"activeOnStart": true,
"beginsPattern": ">",
"endsPattern": "node scripts/esbuild.js --sourcemap --watch"
"endsPattern": "VS Code Extension esbuild complete"
}
}
]

View file

@ -17,7 +17,7 @@ class DiffContextProvider extends BaseContextProvider {
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
const diff = await extras.ide.getDiff(false);
const diff = await extras.ide.getDiff(this.options.includeUnstaged ?? true);
return [
{
description: "The current git diff",

View file

@ -15,6 +15,7 @@ export class HuggingFaceTEIReranker implements Reranker {
apiBase?: string;
truncate?: boolean;
truncation_direction?: string;
apiKey?: string;
},
) {}
@ -24,9 +25,17 @@ export class HuggingFaceTEIReranker implements Reranker {
apiBase += "/";
}
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
if (this.params.apiKey) {
headers["Authorization"] = `Bearer ${this.params.apiKey}`;
}
const resp = await fetch(new URL("rerank", apiBase), {
method: "POST",
headers: { "Content-Type": "application/json" },
headers,
body: JSON.stringify({
query: query,
return_text: false,

17
core/index.d.ts vendored
View file

@ -48,9 +48,9 @@ export interface IndexingProgressUpdate {
export type PromptTemplate =
| string
| ((
history: ChatMessage[],
otherData: Record<string, string>,
) => string | ChatMessage[]);
history: ChatMessage[],
otherData: Record<string, string>,
) => string | ChatMessage[]);
export interface ILLM extends LLMOptions {
get providerName(): ModelProvider;
@ -646,7 +646,8 @@ type ModelProvider =
| "cerebras"
| "askSage"
| "vertexai"
| "nebius";
| "nebius"
| "xAI";
export type ModelName =
| "AUTODETECT"
@ -696,6 +697,8 @@ export type ModelName =
| "llama3.2-3b"
| "llama3.2-11b"
| "llama3.2-90b"
// xAI
| "grok-beta"
// Other Open-source
| "phi2"
| "phind-codellama-34b"
@ -1054,9 +1057,9 @@ export interface Config {
embeddingsProvider?: EmbeddingsProviderDescription | EmbeddingsProvider;
/** The model that Continue will use for tab autocompletions. */
tabAutocompleteModel?:
| CustomLLM
| ModelDescription
| (CustomLLM | ModelDescription)[];
| CustomLLM
| ModelDescription
| (CustomLLM | ModelDescription)[];
/** Options for tab autocomplete */
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
/** UI styles customization */

View file

@ -404,12 +404,15 @@ export default class DocsService {
async getFavicon(startUrl: string) {
const db = await this.getOrCreateSqliteDb();
const { favicon } = await db.get(
const result = await db.get(
`SELECT favicon FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`,
startUrl,
);
return favicon;
if (!result) {
return;
}
return result.favicon;
}
private async init(configHandler: ConfigHandler) {

View file

@ -299,30 +299,32 @@ const preIndexedDocs: Record<
rootUrl: "https://docs.godotengine.org/en/latest/",
faviconUrl: "https://godotengine.org/favicon.ico",
},
"https://docs.amplify.aws/react/": {
"https://docs.amplify.aws/react/start/": {
title: "AWS Amplify (Gen 2)",
startUrl: "https://docs.amplify.aws/react/start/",
rootUrl: "https://docs.amplify.aws/react/",
faviconUrl: "https://docs.amplify.aws/favicon.ico"
faviconUrl: "https://docs.amplify.aws/favicon.ico",
},
"https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/": {
title: "AWS SDK for JavaScript v3",
startUrl: "https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/",
rootUrl: "https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/",
faviconUrl: "https://docs.aws.amazon.com/favicon.ico"
faviconUrl: "https://docs.aws.amazon.com/favicon.ico",
},
"https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html": {
title: "AWS CDK v2",
startUrl: "https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html",
startUrl:
"https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html",
rootUrl: "https://docs.aws.amazon.com/cdk/api/v2/docs/",
faviconUrl: "https://docs.aws.amazon.com/cdk/api/v2/img/favicon-32x32.png"
faviconUrl: "https://docs.aws.amazon.com/cdk/api/v2/img/favicon-32x32.png",
},
"https://awscli.amazonaws.com/v2/documentation/api/latest/index.html": {
title: "AWS CLI commands",
startUrl: "https://awscli.amazonaws.com/v2/documentation/api/latest/index.html",
startUrl:
"https://awscli.amazonaws.com/v2/documentation/api/latest/index.html",
rootUrl: "https://awscli.amazonaws.com/v2/documentation/api/latest/",
faviconUrl: "https://docs.aws.amazon.com/favicon.ico"
}
faviconUrl: "https://docs.aws.amazon.com/favicon.ico",
},
};
export default preIndexedDocs;

View file

@ -146,7 +146,8 @@ function autodetectTemplateType(model: string): TemplateType | undefined {
lower.includes("command") ||
lower.includes("chat-bison") ||
lower.includes("pplx") ||
lower.includes("gemini")
lower.includes("gemini") ||
lower.includes("grok")
) {
return undefined;
}

View file

@ -45,6 +45,7 @@ import WatsonX from "./WatsonX";
import ContinueProxy from "./stubs/ContinueProxy";
import VertexAI from "./VertexAI";
import Asksage from "./Asksage";
import xAI from "./xAI";
const LLMs = [
Anthropic,
@ -84,7 +85,8 @@ const LLMs = [
Cerebras,
Asksage,
Nebius,
VertexAI
VertexAI,
xAI
];
export async function llmFromDescription(

20
core/llm/llms/xAI.ts Normal file
View file

@ -0,0 +1,20 @@
import { LLMOptions, ModelProvider } from "../../index.js";
import OpenAI from "./OpenAI.js";
class xAI extends OpenAI {
static providerName: ModelProvider = "xAI";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://api.x.ai/v1/",
};
private static MODEL_IDS: { [name: string]: string } = {
"grok-beta": "grok-beta", // Future names might not line up
};
protected _convertModelName(model: string) {
return xAI.MODEL_IDS[model] || this.model;
}
}
export default xAI;

View file

@ -0,0 +1,53 @@
---
title: xAI
slug: ../xai
---
:::info
You can get an API key from the [xAI console](https://console.x.ai/)
:::
## Chat model
We recommend configuring **grok-beta** as your chat model.
```json title="config.json"
{
"models": [
{
"title": "Grok Beta",
"provider": "xAI",
"model": "grok-beta",
"apiKey": "[API_KEY]"
}
]
}
```
## Autocomplete model
xAI currently does not offer any autocomplete models.
[Click here](../../model-types/autocomplete.md) to see a list of autocomplete model providers.
## Embeddings model
xAI currently does not offer any embeddings models.
[Click here](../../model-types/embeddings.md) to see a list of embeddings model providers.
## Reranking model
xAI currently does not offer any reranking models.
[Click here](../../model-types/reranking.md) to see a list of reranking model providers.
## Legacy Completions
To force usage of `chat/completions` instead of `completions` endpoint you can set
```json
"useLegacyCompletionsEndpoint": false
```

View file

@ -72,6 +72,7 @@ The `"modelTitle"` field must match one of the models in your "models" array in
"name": "huggingface-tei",
"params": {
"apiBase": "http://localhost:8080",
"apiKey": "<TEI_API_KEY>",
"truncate": true,
"truncation_direction": "Right"
}

View file

@ -421,7 +421,7 @@ Several experimental config parameters are available, as described below:
- `fix`: Prompt for fixing code.
- `optimize`: Prompt for optimizing code.
- `fixGrammar`: Prompt for fixing grammar or spelling.
- `useChromiumForDocsCrawling`: Use chromium to crawl docs instead of default lighter-weight tool that can't render sites. Downloads and installs Chromium to `~/.continue/.utils`.
- `useChromiumForDocsCrawling`: Use Chromium to crawl docs locally. Useful if the default Cheerio crawler fails on sites that require JavaScript rendering. Downloads and installs Chromium to `~/.continue/.utils`..
Example

View file

@ -22,7 +22,7 @@ class ConfigJsonSchemaProviderFactory : JsonSchemaProviderFactory {
class ConfigJsonSchemaFileProvider : JsonSchemaFileProvider {
override fun isAvailable(file: VirtualFile): Boolean {
return path.endsWith("/.continue/config.json")
return file.path.endsWith("/.continue/config.json")
}
override fun getName(): String {

View file

@ -2,10 +2,12 @@ package com.github.continuedev.continueintellijextension.services
import com.github.continuedev.continueintellijextension.constants.getConfigJsPath
import com.github.continuedev.continueintellijextension.constants.getConfigJsonPath
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.*
import com.intellij.openapi.options.Configurable
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.util.SystemInfo
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.messages.Topic
import kotlinx.serialization.Serializable
@ -28,6 +30,7 @@ class ContinueSettingsComponent : DumbAware {
val userToken: JTextField = JTextField()
val enableTabAutocomplete: JCheckBox = JCheckBox("Enable Tab Autocomplete")
val enableContinueTeamsBeta: JCheckBox = JCheckBox("Enable Continue for Teams Beta")
val enableOSR: JCheckBox = JCheckBox("Enable Off-Screen Rendering")
val displayEditorTooltip: JCheckBox = JCheckBox("Display Editor Tooltip")
init {
@ -56,6 +59,8 @@ class ContinueSettingsComponent : DumbAware {
constraints.gridy++
panel.add(enableContinueTeamsBeta, constraints)
constraints.gridy++
panel.add(enableOSR, constraints)
constraints.gridy++
panel.add(displayEditorTooltip, constraints)
constraints.gridy++
@ -87,6 +92,7 @@ open class ContinueExtensionSettings : PersistentStateComponent<ContinueExtensio
var enableTabAutocomplete: Boolean = true
var ghAuthToken: String? = null
var enableContinueTeamsBeta: Boolean = false
var enableOSR: Boolean = shouldRenderOffScreen()
var displayEditorTooltip: Boolean = true
}
@ -107,6 +113,7 @@ open class ContinueExtensionSettings : PersistentStateComponent<ContinueExtensio
get() = ServiceManager.getService(ContinueExtensionSettings::class.java)
}
// Sync remote config from server
private fun syncRemoteConfig() {
val state = instance.continueState
@ -198,6 +205,7 @@ class ContinueExtensionConfigurable : Configurable {
mySettingsComponent?.userToken?.text != settings.continueState.userToken ||
mySettingsComponent?.enableTabAutocomplete?.isSelected != settings.continueState.enableTabAutocomplete ||
mySettingsComponent?.enableContinueTeamsBeta?.isSelected != settings.continueState.enableContinueTeamsBeta ||
mySettingsComponent?.enableOSR?.isSelected != settings.continueState.enableOSR ||
mySettingsComponent?.displayEditorTooltip?.isSelected != settings.continueState.displayEditorTooltip
return modified
}
@ -210,6 +218,7 @@ class ContinueExtensionConfigurable : Configurable {
settings.continueState.enableTabAutocomplete = mySettingsComponent?.enableTabAutocomplete?.isSelected ?: false
settings.continueState.enableContinueTeamsBeta =
mySettingsComponent?.enableContinueTeamsBeta?.isSelected ?: false
settings.continueState.enableOSR = mySettingsComponent?.enableOSR?.isSelected ?: true
settings.continueState.displayEditorTooltip = mySettingsComponent?.displayEditorTooltip?.isSelected ?: true
ApplicationManager.getApplication().messageBus.syncPublisher(SettingsListener.TOPIC)
@ -224,6 +233,7 @@ class ContinueExtensionConfigurable : Configurable {
mySettingsComponent?.userToken?.text = settings.continueState.userToken
mySettingsComponent?.enableTabAutocomplete?.isSelected = settings.continueState.enableTabAutocomplete
mySettingsComponent?.enableContinueTeamsBeta?.isSelected = settings.continueState.enableContinueTeamsBeta
mySettingsComponent?.enableOSR?.isSelected = settings.continueState.enableOSR
mySettingsComponent?.displayEditorTooltip?.isSelected = settings.continueState.displayEditorTooltip
ContinueExtensionSettings.instance.addRemoteSyncJob()
@ -237,3 +247,38 @@ class ContinueExtensionConfigurable : Configurable {
return "Continue Extension Settings"
}
}
/**
* This function checks if off-screen rendering (OSR) should be used.
*
* If ui.useOSR is set in config.json, that value is used.
*
* Otherwise, we check if the pluginSinceBuild is greater than or equal to 233, which corresponds
* to IntelliJ platform version 2023.3 and later.
*
* Setting `setOffScreenRendering` to `false` causes a number of issues such as a white screen flash when loading
* the GUI and the inability to set `cursor: pointer`. However, setting `setOffScreenRendering` to `true` on
* platform versions prior to 2023.3.4 causes larger issues such as an inability to type input for certain languages,
* e.g. Korean.
*
* References:
* 1. https://youtrack.jetbrains.com/issue/IDEA-347828/JCEF-white-flash-when-tool-window-show#focus=Comments-27-9334070.0-0
* This issue mentions that white screen flash problems were resolved in platformVersion 2023.3.4.
* 2. https://www.jetbrains.com/idea/download/other.html
* This documentation shows mappings from platformVersion to branchNumber.
*
* We use the branchNumber (e.g., 233) instead of the full version number (e.g., 2023.3.4) because
* it's a simple integer without dot notation, making it easier to compare.
*/
private fun shouldRenderOffScreen(): Boolean {
// With the 0.0.77 release, non-Mac users have been reporting issues with paste functionality
// in the browser. Disabling OSR for all non-Mac users for now.
if (!SystemInfo.isMac) {
return false
}
val minBuildNumber = 233
val applicationInfo = ApplicationInfo.getInstance()
val currentBuildNumber = applicationInfo.build.baselineVersion
return currentBuildNumber >= minBuildNumber
}

View file

@ -5,6 +5,7 @@ import com.github.continuedev.continueintellijextension.constants.MessageTypes
import com.github.continuedev.continueintellijextension.constants.getConfigJsonPath
import com.github.continuedev.continueintellijextension.`continue`.*
import com.github.continuedev.continueintellijextension.factories.CustomSchemeHandlerFactory
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.google.gson.Gson
import com.google.gson.JsonObject
@ -78,7 +79,8 @@ class ContinueBrowser(val project: Project, url: String) {
val browser: JBCefBrowser
init {
this.browser = JBCefBrowser.createBuilder().setOffScreenRendering(shouldRenderOffScreen()).build()
val enableOSR = ServiceManager.getService(ContinueExtensionSettings::class.java).continueState.enableOSR
this.browser = JBCefBrowser.createBuilder().setOffScreenRendering(enableOSR).build()
browser.jbCefClient.setProperty(
@ -274,34 +276,4 @@ class ContinueBrowser(val project: Project, url: String) {
return """window.postMessage($jsonData, "*");"""
}
/**
* This function checks if the pluginSinceBuild is greater than or equal to 233, which corresponds
* to IntelliJ platform version 2023.3 and later.
*
* Setting `setOffScreenRendering` to `false` causes a number of issues such as a white screen flash when loading
* the GUI and the inability to set `cursor: pointer`. However, setting `setOffScreenRendering` to `true` on
* platform versions prior to 2023.3.4 causes larger issues such as an inability to type input for certain langauges,
* e.g. Korean.
*
* References:
* 1. https://youtrack.jetbrains.com/issue/IDEA-347828/JCEF-white-flash-when-tool-window-show#focus=Comments-27-9334070.0-0
* This issue mentions that white screen flash problems were resolved in platformVersion 2023.3.4.
* 2. https://www.jetbrains.com/idea/download/other.html
* This documentation shows mappings from platformVersion to branchNumber.
*
* We use the branchNumber (e.g., 233) instead of the full version number (e.g., 2023.3.4) because
* it's a simple integer without dot notation, making it easier to compare.
*/
private fun shouldRenderOffScreen(): Boolean {
// With the 0.0.77 release, non-Mac users have been reporting issues with paste functionality
// in the browser. Disabling OSR for all non-Mac users for now.
if (!SystemInfo.isMac) {
return false
}
val minBuildNumber = 233
val applicationInfo = ApplicationInfo.getInstance()
val currentBuildNumber = applicationInfo.build.baselineVersion
return currentBuildNumber >= minBuildNumber
}
}

File diff suppressed because it is too large Load diff

View file

@ -30,4 +30,5 @@ const esbuildConfig = {
} else {
await esbuild.build(esbuildConfig);
}
})();
console.log("VS Code Extension esbuild complete"); // Used in task endpattern to signal completion
})();

2
gui/package-lock.json generated
View file

@ -37,7 +37,7 @@
"react-dom": "^18.2.0",
"react-error-boundary": "^4.0.11",
"react-hook-form": "^7.47.0",
"react-intersection-observer": "^9.10.3",
"react-intersection-observer": "^9.13.1",
"react-markdown": "^9.0.1",
"react-redux": "^8.0.5",
"react-remark": "^2.1.0",

View file

@ -45,7 +45,7 @@
"react-dom": "^18.2.0",
"react-error-boundary": "^4.0.11",
"react-hook-form": "^7.47.0",
"react-intersection-observer": "^9.10.3",
"react-intersection-observer": "^9.13.1",
"react-markdown": "^9.0.1",
"react-redux": "^8.0.5",
"react-remark": "^2.1.0",

BIN
gui/public/logos/xAI.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

View file

@ -1,5 +1,4 @@
import {
ArrowPathIcon,
BarsArrowDownIcon,
HandThumbDownIcon,
HandThumbUpIcon,
@ -14,7 +13,7 @@ import { vscBackground, vscInputBackground } from "..";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import useUIConfig from "../../hooks/useUIConfig";
import { RootState } from "../../redux/store";
import { getFontSize } from "../../util";
import { getFontSize, getMetaKeyLabel } from "../../util";
import ButtonWithTooltip from "../ButtonWithTooltip";
import { CopyButton } from "../markdown/CopyButton";
import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview";
@ -50,7 +49,7 @@ function StepContainer(props: StepContainerProps) {
const isUserInput = props.item.message.role === "user";
const uiConfig = useUIConfig();
const shouldRenderActions = !props.isLast || (props.isLast && !active);
const shouldRenderActions = !active || !props.isLast;
useEffect(() => {
if (!active) {
@ -84,7 +83,11 @@ function StepContainer(props: StepContainerProps) {
};
return (
<div className="relative">
<div className="relative"
style={{
minHeight: props.isLast ? "50vh" : 0
}}
>
<ContentDiv
hidden={!props.open}
isUserInput={isUserInput}
@ -104,52 +107,55 @@ function StepContainer(props: StepContainerProps) {
/>
)}
</ContentDiv>
{shouldRenderActions && (
<div className="flex items-center justify-end gap-0.5 xs:flex text-xs text-gray-400 p-2 pb-0 cursor-default">
{truncatedEarly && (
<ButtonWithTooltip
tabIndex={-1}
text="Continue generation"
onClick={props.onContinueGeneration}
>
<BarsArrowDownIcon className="h-3.5 w-3.5 text-gray-500" />
</ButtonWithTooltip>
)}
{props.index !== 1 && (
<ButtonWithTooltip
text="Delete"
tabIndex={-1}
onClick={props.onDelete}
>
<TrashIcon className="h-3.5 w-3.5 text-gray-500" />
</ButtonWithTooltip>
)}
<CopyButton
tabIndex={-1}
text={stripImages(props.item.message.content)}
clipboardIconClassName="h-3.5 w-3.5 text-gray-500"
/>
<div className="h-7 mb-2 mx-2 flex items-center justify-end gap-0.5 xs:flex text-xs text-gray-400 pb-0 cursor-default"
style={{
opacity: shouldRenderActions ? 1 : 0,
pointerEvents: shouldRenderActions ? "auto" : "none"
}}
>
{truncatedEarly && (
<ButtonWithTooltip
text="Helpful"
tabIndex={-1}
onClick={() => sendFeedback(true)}
text="Continue generation"
onClick={props.onContinueGeneration}
>
<HandThumbUpIcon className="h-3.5 w-3.5 text-gray-500 mx-0.5" />
<BarsArrowDownIcon className="h-3.5 w-3.5 text-gray-500" />
</ButtonWithTooltip>
)}
{props.index !== 1 && (
<ButtonWithTooltip
text="Unhelpful"
text="Delete"
tabIndex={-1}
onClick={() => sendFeedback(false)}
onClick={props.onDelete}
>
<HandThumbDownIcon className="h-3.5 w-3.5 text-gray-500" />
<TrashIcon className="h-3.5 w-3.5 text-gray-500" />
</ButtonWithTooltip>
</div>
)}
)}
<CopyButton
tabIndex={-1}
text={stripImages(props.item.message.content)}
clipboardIconClassName="h-3.5 w-3.5 text-gray-500"
checkIconClassName="h-3.5 w-3.5 text-green-400"
/>
<ButtonWithTooltip
text="Helpful"
tabIndex={-1}
onClick={() => sendFeedback(true)}
>
<HandThumbUpIcon className={`h-3.5 w-3.5 mx-0.5 ${feedback === true ? 'text-green-400' : 'text-gray-500'}`} />
</ButtonWithTooltip>
<ButtonWithTooltip
text="Unhelpful"
tabIndex={-1}
onClick={() => sendFeedback(false)}
>
<HandThumbDownIcon className={`h-3.5 w-3.5 ${feedback === false ? 'text-red-400' : 'text-gray-500'}`} />
</ButtonWithTooltip>
</div>
</div>
);
}

View file

@ -109,7 +109,7 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
}, [isGatheringContextStore]);
return (
<div className={`mb-1 mt-3 ${props.hidden ? "hidden" : ""}`}>
<div className={`mb-1 ${props.hidden ? "hidden" : ""}`}>
<div className={`relative flex px-2`}>
<GradientBorder
loading={active && props.isLastUserInput ? 1 : 0}

View file

@ -50,9 +50,11 @@ import {
getFontSize,
isJetBrains,
isMetaEquivalentKeyPressed,
isWebEnvironment,
} from "../../util";
import { handleMetaKeyPressJetBrains } from "../../util/handleMetaKeyPressJetBrains";
import {
handleJetBrainsMetaKeyPress,
handleMetaKeyPress,
} from "./handleMetaKeyPress";
import { CodeBlockExtension } from "./CodeBlockExtension";
import { SlashCommand } from "./CommandsExtension";
import InputToolbar, { ToolbarOptions } from "./InputToolbar";
@ -78,6 +80,7 @@ const InputBoxDiv = styled.div<{ border?: string }>`
props.border ? props.border : `0.5px solid ${vscInputBorder}`};
outline: none;
font-size: ${getFontSize()}px;
&:focus {
outline: none;
@ -561,86 +564,36 @@ function TipTapEditor(props: TipTapEditorProps) {
/**
* This handles various issues with meta key actions
* - In JetBrains, when using "off screen rendering", there is a bug where using the meta key to
* - In JetBrains, when using OSR in JCEF, there is a bug where using the meta key to
* highlight code using arrow keys is not working
* - In VS Code, while working with .ipynb files there is a problem where copy/paste/cut will affect
* the actual notebook cells, even when performing them in our GUI
*
* Currently keydown events for a number of keys are not registering if the
* meta/shift key is pressed, for example "x", "c", "v", "z", etc.
* Until this is resolved we can't turn on OSR for non-Mac users due to issues
* with those key actions.
*/
const handleKeyDown = async (e: KeyboardEvent<HTMLDivElement>) => {
if (!editor || !editorFocusedRef.current) return;
setActiveKey(e.key);
if (isMetaEquivalentKeyPressed(e)) {
const { key, code } = e;
const isWebEnv = isWebEnvironment();
const text = editor.state.doc.textBetween(
editor.state.selection.from,
editor.state.selection.to,
);
if (isJetBrains()) {
if (code === "KeyJ") {
e.stopPropagation();
e.preventDefault();
setIgnoreHighlightedCode(true);
setTimeout(() => {
setIgnoreHighlightedCode(false);
}, 100);
}
if (isMetaEquivalentKeyPressed(e)) {
e.stopPropagation();
e.preventDefault();
handleMetaKeyPressJetBrains(e, text, editor.commands.setContent);
}
} else {
if (code === "KeyL") {
e.stopPropagation();
e.preventDefault();
setIgnoreHighlightedCode(true);
setTimeout(() => {
setIgnoreHighlightedCode(false);
}, 100);
return;
}
switch (key) {
case "x":
e.stopPropagation();
e.preventDefault();
if (isWebEnv) {
await navigator.clipboard.writeText(text);
editor.commands.deleteSelection();
} else {
document.execCommand("cut");
}
break;
case "c":
e.stopPropagation();
e.preventDefault();
if (isWebEnv) {
await navigator.clipboard.writeText(text);
} else {
document.execCommand("copy");
}
break;
case "v":
e.stopPropagation();
e.preventDefault();
if (isWebEnv) {
const clipboardText = await navigator.clipboard.readText();
editor.commands.insertContent(clipboardText);
} else {
document.execCommand("paste");
}
break;
}
}
} else if (e.key === "Escape") {
// Allow users to use the escape key to jump back to the editor
if (e.key === "Escape") {
e.stopPropagation();
e.preventDefault();
ideMessenger.post("focusEditor", undefined);
return;
}
// Handle meta key issues
if (isMetaEquivalentKeyPressed(e)) {
if (isJetBrains()) {
handleJetBrainsMetaKeyPress(e, editor);
}
await handleMetaKeyPress(e, editor);
}
};
@ -671,9 +624,6 @@ function TipTapEditor(props: TipTapEditorProps) {
[props.onEnter, editor, props.isMainInput],
);
// This is a mechanism for overriding the IDE keyboard shortcut when inside of the webview
const [ignoreHighlightedCode, setIgnoreHighlightedCode] = useState(false);
// Re-focus main input after done generating
useEffect(() => {
if (editor && !active && props.isMainInput && document.hasFocus()) {
@ -748,71 +698,68 @@ function TipTapEditor(props: TipTapEditorProps) {
if (!props.isMainInput || !editor) {
return;
}
if (!ignoreHighlightedCode) {
const rif: RangeInFile & { contents: string } =
data.rangeInFileWithContents;
const basename = getBasename(rif.filepath);
const relativePath = getRelativePath(
rif.filepath,
await ideMessenger.ide.getWorkspaceDirs(),
);
const rangeStr = `(${rif.range.start.line + 1}-${
rif.range.end.line + 1
})`;
const item: ContextItemWithId = {
content: rif.contents,
name: `${basename} ${rangeStr}`,
// Description is passed on to the LLM to give more context on file path
description: `${relativePath} ${rangeStr}`,
id: {
providerTitle: "code",
itemId: v4(),
},
uri: {
type: "file",
value: rif.filepath,
},
};
let index = 0;
for (const el of editor.getJSON().content) {
if (el.type === "codeBlock") {
index += 2;
} else {
break;
}
const rif: RangeInFile & { contents: string } =
data.rangeInFileWithContents;
const basename = getBasename(rif.filepath);
const relativePath = getRelativePath(
rif.filepath,
await ideMessenger.ide.getWorkspaceDirs(),
);
const rangeStr = `(${rif.range.start.line + 1}-${
rif.range.end.line + 1
})`;
const item: ContextItemWithId = {
content: rif.contents,
name: `${basename} ${rangeStr}`,
// Description is passed on to the LLM to give more context on file path
description: `${relativePath} ${rangeStr}`,
id: {
providerTitle: "code",
itemId: v4(),
},
uri: {
type: "file",
value: rif.filepath,
},
};
let index = 0;
for (const el of editor.getJSON().content) {
if (el.type === "codeBlock") {
index += 2;
} else {
break;
}
editor
.chain()
.insertContentAt(index, {
type: "codeBlock",
attrs: {
item,
},
})
.run();
if (data.prompt) {
editor.commands.focus("end");
editor.commands.insertContent(data.prompt);
}
if (data.shouldRun) {
onEnterRef.current({ useCodebase: false, noContext: true });
}
setTimeout(() => {
editor.commands.blur();
editor.commands.focus("end");
}, 20);
}
setIgnoreHighlightedCode(false);
editor
.chain()
.insertContentAt(index, {
type: "codeBlock",
attrs: {
item,
},
})
.run();
if (data.prompt) {
editor.commands.focus("end");
editor.commands.insertContent(data.prompt);
}
if (data.shouldRun) {
onEnterRef.current({ useCodebase: false, noContext: true });
}
setTimeout(() => {
editor.commands.blur();
editor.commands.focus("end");
}, 20);
},
[
editor,
props.isMainInput,
historyLength,
ignoreHighlightedCode,
props.isMainInput,
onEnterRef.current,
],

View file

@ -0,0 +1,107 @@
import { KeyboardEvent } from "react";
import { isWebEnvironment } from "../../util";
import { Editor } from "@tiptap/react";
const isWebEnv = isWebEnvironment();
export const handleJetBrainsMetaKeyPress = (
e: KeyboardEvent,
editor: Editor,
) => {
const selection = window.getSelection();
const handlers: Record<string, () => void> = {
Backspace: () => handleJetBrainsMetaBackspace(editor),
ArrowLeft: () =>
selection.modify(
e.shiftKey ? "extend" : "move",
"backward",
"lineboundary",
),
ArrowRight: () =>
selection.modify(
e.shiftKey ? "extend" : "move",
"forward",
"lineboundary",
),
ArrowDown: () =>
selection.modify(
e.shiftKey ? "extend" : "move",
"forward",
"documentboundary",
),
ArrowUp: () => {
selection.modify(
e.shiftKey ? "extend" : "move",
"backward",
"documentboundary",
);
},
};
if (e.key in handlers) {
e.stopPropagation();
e.preventDefault();
handlers[e.key]();
}
};
export const handleMetaKeyPress = async (e: KeyboardEvent, editor: Editor) => {
const text = editor.state.doc.textBetween(
editor.state.selection.from,
editor.state.selection.to,
);
const handlers: Record<string, () => Promise<void>> = {
x: () => handleCutOperation(text, editor),
c: () => handleCopyOperation(text),
v: () => handlePasteOperation(editor),
};
if (e.key in handlers) {
e.stopPropagation();
e.preventDefault();
await handlers[e.key]();
}
};
export const handleJetBrainsMetaBackspace = (editor: Editor) => {
const { doc } = editor.state;
for (let i = doc.content.childCount - 1; i >= 0; i--) {
const node = doc.content.child(i);
if (node.type.name !== "codeBlock") {
editor.commands.deleteNode(node.type.name);
}
}
// Add an empty string so the user can keep typing
editor.commands.createParagraphNear();
};
export const handleCutOperation = async (text: string, editor: Editor) => {
if (isWebEnv) {
await navigator.clipboard.writeText(text);
editor.commands.deleteSelection();
} else {
document.execCommand("cut");
}
};
export const handleCopyOperation = async (text: string) => {
if (isWebEnv) {
await navigator.clipboard.writeText(text);
} else {
document.execCommand("copy");
}
};
export const handlePasteOperation = async (editor: Editor) => {
if (isWebEnv) {
const clipboardText = await navigator.clipboard.readText();
editor.commands.insertContent(clipboardText);
} else {
document.execCommand("paste");
}
};

View file

@ -1059,6 +1059,19 @@ export const models: { [key: string]: ModelPackage } = {
providerOptions: ["nebius"],
isOpenSource: true,
},
grokBeta: {
title: "Grok Beta",
description: "Generative artificial intelligence chatbot developed by xAI.",
refUrl: "",
params: {
title: "Grok Beta",
model: "grok-beta",
contextLength: 128_000,
},
icon: "xAI.png",
providerOptions: ["xAI"],
isOpenSource: false,
},
AUTODETECT: {
title: "Autodetect",
description:

View file

@ -352,6 +352,27 @@ Select the \`GPT-4o\` model below to complete your provider configuration, but n
packages: [models.gemini15Pro, models.geminiPro, models.gemini15Flash],
apiKeyUrl: "https://aistudio.google.com/app/apikey",
},
xAI: {
title: "xAI",
provider: "xAI",
icon: "xAI.png",
description: "xAI is a company working on building artificial intelligence to accelerate human scientific discovery",
longDescription: "To get started with xAI, obtain an API key from their [console](https://console.x.ai/).",
tags: [ModelProviderTags.RequiresApiKey, ModelProviderTags.OpenSource],
collectInputFor: [
{
inputType: "text",
key: "apiKey",
label: "API Key",
placeholder: "Enter your xAI API key",
required: true,
},
],
packages: [
models.grokBeta,
],
apiKeyUrl: "https://console.x.ai/",
},
lmstudio: {
title: "LM Studio",
provider: "lmstudio",

View file

@ -66,7 +66,6 @@ const TopGuiDiv = styled.div<{
showScrollbar?: boolean;
}>`
overflow-y: auto;
height: 100%;
scrollbar-width: ${(props) => (props.showScrollbar ? "thin" : "none")};
&::-webkit-scrollbar {
@ -75,6 +74,7 @@ const TopGuiDiv = styled.div<{
`;
const StopButton = styled.div`
background-color: ${vscBackground};
width: fit-content;
margin-right: auto;
margin-left: auto;
@ -97,6 +97,7 @@ const StopButton = styled.div`
`;
const StepsDiv = styled.div`
margin-top: 8px;
position: relative;
background-color: transparent;
@ -147,16 +148,17 @@ export function Chat() {
const { saveSession, getLastSessionId, loadLastSession } =
useHistory(dispatch);
useEffect(() => {
if (!active || !topGuiDivRef.current) return;
const scrollAreaElement = topGuiDivRef.current;
scrollAreaElement.scrollTop =
scrollAreaElement.scrollHeight - scrollAreaElement.clientHeight;
const scrollToBottom = useCallback(() => {
if (!topGuiDivRef.current) return;
const elem = topGuiDivRef.current;
elem.scrollTop = elem.scrollHeight - elem.clientHeight;
setIsAtBottom(true);
}, [active]);
}, [topGuiDivRef, setIsAtBottom]);
useEffect(() => {
if (active) scrollToBottom();
}, [active, scrollToBottom]);
useEffect(() => {
// Cmd + Backspace to delete current step
@ -311,6 +313,7 @@ export function Chat() {
return (
<>
<TopGuiDiv
className={`${state.history.length > 0 ? "h-full" : ""}`}
ref={topGuiDivRef}
onScroll={handleScroll}
showScrollbar={state.config.ui?.showChatScrollbar || false}
@ -415,22 +418,56 @@ export function Chat() {
</Fragment>
))}
</StepsDiv>
</div>
<ChatScrollAnchor
scrollAreaRef={topGuiDivRef}
isAtBottom={isAtBottom}
trackVisibility={active}
/>
</TopGuiDiv>
<ContinueInputBox
isMainInput
isLastUserInput={false}
hidden={active}
onEnter={(editorContent, modifiers) => {
sendInput(editorContent, modifiers);
}}
/>
{active ? (
<>
<br />
<br />
</>
) : state.history.length > 0 ? (
<div className={`relative`}>
<div className="absolute -top-8 right-2 z-30">
{ttsActive && (
<StopButton
className=""
onClick={() => {
ideMessenger.post("tts/kill", undefined);
}}
>
■ Stop TTS
</StopButton>
)}
{active && (
<StopButton
onClick={() => {
dispatch(setInactive());
if (
state.history[state.history.length - 1]?.message.content
.length === 0
) {
dispatch(clearLastResponse());
}
}}
>
{getMetaKeyLabel()} ⌫ Cancel
</StopButton>
)}
</div>
<ContinueInputBox
isMainInput
isLastUserInput={false}
onEnter={(editorContent, modifiers) => {
sendInput(editorContent, modifiers);
}}
/>
<div
style={{
// opacity: active ? 0 : 1,
pointerEvents: active ? "none" : "auto",
}}
>
{state.history.length > 0 ? (
<div className="xs:inline mt-2 hidden">
<NewSessionButton
onClick={() => {
@ -475,40 +512,7 @@ export function Chat() {
</>
)}
</div>
<ChatScrollAnchor
scrollAreaRef={topGuiDivRef}
isAtBottom={isAtBottom}
trackVisibility={active}
/>
</TopGuiDiv>
{ttsActive && (
<StopButton
className="mb-4 mt-2"
onClick={() => {
ideMessenger.post("tts/kill", undefined);
}}
>
■ Stop TTS
</StopButton>
)}
{active && (
<StopButton
className="mb-4 mt-auto"
onClick={() => {
dispatch(setInactive());
if (
state.history[state.history.length - 1]?.message.content
.length === 0
) {
dispatch(clearLastResponse());
}
}}
>
{getMetaKeyLabel()} ⌫ Cancel
</StopButton>
)}
</div>
</>
);
}

View file

@ -1,77 +0,0 @@
import { KeyboardEvent } from "react";
import { getPlatform } from ".";
export const handleMetaKeyPressJetBrains = (
e: KeyboardEvent,
text: string,
setText: (text: string) => void,
) => {
const { selectionStart, selectionEnd } = e.target as HTMLTextAreaElement;
if (e.key === "Backspace") {
handleMetaBackspace(e, text, setText, selectionStart, selectionEnd);
}
if (getPlatform() === "mac") {
if (e.key === "ArrowLeft") {
handleMacArrowLeftKey(e);
} else if (e.key === "ArrowRight") {
handleMacArrowRightKey(e);
}
}
};
const handleMetaBackspace = (
e: KeyboardEvent,
text: string,
setText: (text: string) => void,
start: number,
end: number,
) => {
const target = e.target as HTMLTextAreaElement;
let newStart = start;
if (start !== end) {
setText(text.slice(0, start) + text.slice(end));
} else {
newStart =
getPlatform() === "mac"
? text.lastIndexOf("\n", start - 1) + 1
: text.slice(0, start).trimEnd().lastIndexOf(" ") + 1;
setText(text.slice(0, newStart) + text.slice(start));
}
target.setSelectionRange(newStart, newStart);
};
const handleMacArrowLeftKey = (e: KeyboardEvent) => {
const target = e.target as HTMLDivElement;
const selection = window.getSelection();
const range = document.createRange();
if (e.shiftKey) {
selection.modify("extend", "backward", "character");
} else {
range.setStart(target.firstChild, 0);
range.setEnd(target.firstChild, 0);
selection.removeAllRanges();
selection.addRange(range);
}
};
const handleMacArrowRightKey = (e: KeyboardEvent) => {
const selection = window.getSelection();
const range = document.createRange();
const target = e.target as HTMLDivElement;
if (e.shiftKey) {
selection.modify("extend", "forward", "character");
} else {
range.selectNodeContents(target);
range.collapse(false);
selection.removeAllRanges();
selection.addRange(range);
}
};

View file

@ -8,6 +8,7 @@ import { Ollama } from "./providers/ollama.js";
import { OpenAi } from "./providers/openai.js";
import { Vllm } from "./providers/vllm.js";
import { Voyage } from "./providers/voyage.js";
import { xAI } from "./providers/xAI.js";
import { LlmInfo, ModelProvider, UseCase } from "./types.js";
export const allModelProviders: ModelProvider[] = [
@ -21,6 +22,7 @@ export const allModelProviders: ModelProvider[] = [
Vllm,
Bedrock,
Cohere,
xAI
];
export const allLlms: LlmInfo[] = allModelProviders.flatMap((provider) =>

View file

@ -0,0 +1,14 @@
import { ModelProvider } from "../types.js";
export const xAI: ModelProvider = {
models: [
{
model: "grok-beta",
displayName: "Grok Beta",
contextLength: 128000,
recommendedFor: ["chat"],
},
],
id: "xAI",
displayName: "xAI",
};