Merge branch 'main' into pe/generating-text-lump

This commit is contained in:
Patrick Erichsen 2025-04-01 21:06:52 -07:00 • committed by GitHub
commit a30bbd33fa
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
65 changed files with 818 additions and 619 deletions

View file

@ -9,7 +9,7 @@
## Screenshots
[ For visual changes, include screenshots. ]
[ For visual changes, include screenshots. Screen recordings are particularly helpful, and appreciated! ]
## Testing instructions

View file

@ -54,7 +54,7 @@ jobs:
ref: ${{ github.event.release.tag_name }}
- name: Import Apple certificate
uses: apple-actions/import-codesign-certs@v3
uses: apple-actions/import-codesign-certs@v5
with:
keychain: ${{ github.run_id }}
keychain-password: ${{ github.run_id }}

View file

@ -139,7 +139,7 @@ Similarly, any changes to `core` or `extensions/vscode` will be automatically in
#### JetBrains
See the [`CONTRIBUTING.md`](./extensions/intellij/CONTRIBUTING.md) for the JetBrains extension.
See [`intellij/CONTRIBUTING.md`](./extensions/intellij/CONTRIBUTING.md) for the JetBrains extension.
### Our Git Workflow
@ -147,7 +147,7 @@ We keep a single permanent branch: `main`. When we are ready to create a "pre-re
### Testing
We have a mix of unit, functional, and e2e test suites, with a primary focus on functional testing. These tests run on each pull request. If your PR causes one of these tests to fail, we will ask that you resolve the issue before we merge.
We have a mix of unit, functional, and e2e test suites, with a primary focus on functional testing. These tests run on each pull request. If your PR causes one of these tests to fail, we will ask that you to resolve the issue before we merge.
When contributing, please update or create the appropriate tests to help verify the correctness of your implementaiton.
@ -217,7 +217,7 @@ Continue consists of 2 parts that are split so that it can be extended to work i
1. **Continue GUI** - The Continue GUI is a React application that gives the user control over Continue. It displays the current chat history, allows the user to ask questions, invoke slash commands, and use context providers. The GUI also handles most state and holds as much of the logic as possible so that it can be reused between IDEs.
2. **Continue Extension** - The Continue Extension is a plugin for the IDE which implements the [IDE Interface](./core/index.d.ts#L229). This allows the GUI to request information from or actions to be taken within the IDE. This same interface is used regardless of IDE. The first Continue extensions we have built are for VS Code and JetBrains, but we plan to build clients for other IDEs in the future. The IDE Client must 1. implement IDE Interface, as is done [here](./extensions/vscode/src/ideProtocol.ts) for VS Code and 2. display the Continue GUI in a sidebar, like [here](./extensions/vscode/src/ContinueGUIWebviewViewProvider.ts).
2. **Continue Extension** - The Continue Extension is a plugin for the IDE which implements the [IDE Interface](./core/index.d.ts#L229). This allows the GUI to request information from or actions to be taken within the IDE. This same interface is used regardless of IDE. The first Continue extensions we have built are for VS Code and JetBrains, but we plan to build clients for other IDEs in the future. The IDE Client must 1. implement IDE Interface, as is done [here](./extensions/vscode/src/VsCodeIde.ts) for VS Code and 2. display the Continue GUI in a sidebar, like [here](./extensions/vscode/src/ContinueGUIWebviewViewProvider.ts).
### Continue VS Code Extension

View file

@ -48,9 +48,9 @@
"@aws-sdk/client-sagemaker-runtime": "^3.758.0",
"@aws-sdk/credential-providers": "^3.758.0",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "^1.0.63",
"@continuedev/config-yaml": "^1.0.67",
"@continuedev/fetch": "^1.0.4",
"@continuedev/llm-info": "^1.0.2",
"@continuedev/llm-info": "^1.0.8",
"@continuedev/openai-adapters": "^1.0.18",
"@modelcontextprotocol/sdk": "^1.5.0",
"@mozilla/readability": "^0.5.0",
@ -135,7 +135,8 @@
"myers-diff": "^2.1.0",
"onnxruntime-common": "1.14.0",
"onnxruntime-web": "1.14.0",
"ts-jest": "^29.1.1"
"ts-jest": "^29.1.1",
"typescript": "^5.6.3"
},
"engines": {
"node": ">=20.11.0"
@ -6404,10 +6405,11 @@
}
},
"node_modules/tar-fs": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.1.tgz",
"integrity": "sha512-V0r2Y9scmbDRLCNex/+hYzvp/zyYjvFbHPNgVTKfQvVrb6guiE/fxP+XblDNR011utopbkex2nM4dHNV6GDsng==",
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.2.tgz",
"integrity": "sha512-EsaAXwxmx8UB7FRKqeozqEPop69DXcmYwTQwXvyAPF352HJsPdkVhvTaDPYqfNgruveJIJy3TA2l+2zj8LJIJA==",
"dev": true,
"license": "MIT",
"dependencies": {
"chownr": "^1.1.1",
"mkdirp-classic": "^0.5.2",

View file

@ -5,6 +5,7 @@ import {
getParserForFile,
getQueryForFile,
} from "../../util/treeSitter";
import { findUriInDirs } from "../../util/uri";
interface FileInfo {
imports: { [key: string]: RangeInFileWithContents[] };
@ -44,7 +45,15 @@ export class ImportDefinitionsService {
let fileContents: string | undefined = undefined;
try {
fileContents = await this.ide.readFile(filepath);
const { foundInDir } = findUriInDirs(
filepath,
await this.ide.getWorkspaceDirs(),
);
if (!foundInDir) {
return null;
} else {
fileContents = await this.ide.readFile(filepath);
}
} catch (err) {
// File removed
return null;

View file

@ -1,5 +1,6 @@
import { CustomCommand, SlashCommand, SlashCommandDescription } from "../";
import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString";
import { replaceSlashCommandWithPromptInChatHistory } from "../promptFiles/v1/updateChatHistory";
import { renderChatMessage } from "../util/messageContent";
import SlashCommands from "./slash";
@ -7,68 +8,34 @@ import SlashCommands from "./slash";
export function slashFromCustomCommand(
customCommand: CustomCommand,
): SlashCommand {
const commandName = customCommand.name.startsWith("/")
? customCommand.name.substring(1)
: customCommand.name;
return {
name: customCommand.name,
name: commandName,
description: customCommand.description ?? "",
prompt: customCommand.prompt,
run: async function* ({ input, llm, history, ide, completionOptions }) {
// Remove slash command prefix from input
let userInput = input;
if (userInput.startsWith(`/${customCommand.name}`)) {
userInput = userInput
.slice(customCommand.name.length + 1, userInput.length)
.trimStart();
}
// Render prompt template
let promptUserInput: string;
let renderedPrompt: string;
if (customCommand.prompt.includes("{{{ input }}}")) {
promptUserInput = await renderTemplatedString(
renderedPrompt = await renderTemplatedString(
customCommand.prompt,
ide.readFile.bind(ide),
{ input: userInput },
{ input },
);
} else {
promptUserInput = customCommand.prompt + "\n\n" + userInput;
renderedPrompt = customCommand.prompt + "\n\n" + input;
}
const messages = [...history];
// Find the last chat message with this slash command and replace it with the user input
for (let i = messages.length - 1; i >= 0; i--) {
const message = messages[i];
const { role, content } = message;
if (role !== "user") {
continue;
}
if (
Array.isArray(content) &&
content.some(
(part) =>
"text" in part && part.text?.startsWith(`/${customCommand.name}`),
)
) {
messages[i] = {
...message,
content: content.map((part) => {
if (
"text" in part &&
part.text.startsWith(`/${customCommand.name}`)
) {
return { type: "text", text: promptUserInput };
}
return part;
}),
};
break;
} else if (
typeof content === "string" &&
content.startsWith(`/${customCommand.name}`)
) {
messages[i] = { ...message, content: promptUserInput };
break;
}
}
// Replaces slash command messages with the rendered prompt
// which INCLUDES the input
const messages = replaceSlashCommandWithPromptInChatHistory(
history,
commandName,
renderedPrompt,
undefined,
);
for await (const chunk of llm.streamChat(
messages,

View file

@ -2,6 +2,9 @@ import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import { SerializedContinueConfig } from "../..";
/*
TODO this is not functional
*/
export function convertConfigJsonToConfigYaml(
configJson: SerializedContinueConfig,
): AssistantUnrolled {

View file

@ -39,7 +39,7 @@ async function modelConfigToBaseLLM(
let options: LLMOptions = {
...rest,
// contextLength: model.defaultCompletionOptions?.contextLength ?? undefined,
contextLength: model.defaultCompletionOptions?.contextLength,
completionOptions: {
...(model.defaultCompletionOptions ?? {}),
model: model.model,

View file

@ -1,12 +1,40 @@
import { spawn } from "node:child_process";
import { fileURLToPath } from "node:url";
import {
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
ContextSubmenuItem,
LoadSubmenuItemsArgs,
} from "../../index.js";
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
ContextSubmenuItem,
LoadSubmenuItemsArgs,
} from "../../index.js";
import { BaseContextProvider } from "../index.js";
import { fileURLToPath} from "node:url";
const runGitCommand = (args: string[], cwd: string): Promise<string> => {
return new Promise((resolve, reject) => {
// First argument is the command, rest are arguments
const gitProcess = spawn("git", args, {
cwd,
});
let stdout = "";
let stderr = "";
gitProcess.stdout.on("data", (data) => {
stdout += data.toString();
});
gitProcess.stderr.on("data", (data) => {
stderr += data.toString();
});
gitProcess.on("close", (code) => {
if (code !== 0) {
reject(new Error(`Git command failed: ${stderr}`));
return;
}
resolve(stdout);
});
});
};
class GitCommitContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
@ -16,29 +44,55 @@ class GitCommitContextProvider extends BaseContextProvider {
type: "submenu",
};
async getContextItems(query: string, extras: ContextProviderExtras): Promise<ContextItem[]> {
async getContextItems(
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
const lastXCommitsDepth = this.options?.LastXCommitsDepth ?? 10;
if (typeof lastXCommitsDepth !== "number") {
throw new Error("LastXCommitsDepth must be a number");
}
const topLevelDir = fileURLToPath((await extras.ide.getWorkspaceDirs())[0]);
try{
if(query.includes("last ")){
try {
if (query.includes("last ")) {
const content = await runGitCommand(
[
"--no-pager",
"log",
'--pretty=format:"%H,%h,%an,%ae,%ad,%P,%s,%b"',
"-p",
"-n",
lastXCommitsDepth.toString(),
],
topLevelDir,
);
return [
{
name: query,
description: query,
content: (await extras.ide.subprocess(`git --no-pager log --pretty=format:"%H,%h,%an,%ae,%ad,%P,%s,%b" -p -n ${lastXCommitsDepth}`, topLevelDir))[0],
}
]
}
else{
name: query,
description: query,
content,
},
];
} else {
const content = await runGitCommand(
[
"--no-pager",
"show",
'--pretty=format:"%H,%h,%an,%ae,%ad,%P,%s,%b"',
query,
],
topLevelDir,
);
return [
{
name: query,
description: `commit ${query}`,
content: (await extras.ide.subprocess(`git --no-pager show --pretty=format:"%H,%h,%an,%ae,%ad,%P,%s,%b" ${query}`, topLevelDir))[0],
}
]
content,
},
];
}
}catch(err){
} catch (err) {
return [];
}
}
@ -48,24 +102,48 @@ class GitCommitContextProvider extends BaseContextProvider {
): Promise<ContextSubmenuItem[]> {
const depth = this.options?.Depth ?? 50;
const lastXCommitsDepth = this.options?.LastXCommitsDepth ?? 10;
const topLevelDir = fileURLToPath((await args.ide.getWorkspaceDirs())[0]);
try{
const [gitResult] = await args.ide.subprocess(`git --no-pager log --pretty=format:"%H%x00%s" -n ${depth}`, topLevelDir);
const recentCommits = [{ id: `last ${lastXCommitsDepth} commits`, title: `last ${lastXCommitsDepth} commits`, description: "recent commits" }];
const allCommits = gitResult
.trim()
.split('\n')
.map(line => {
const [hash, message] = line.split("\0");
return {
id: hash,
title: message,
description: hash
};
}
if (typeof depth !== "number") {
throw new Error("Depth must be a number");
}
if (typeof lastXCommitsDepth !== "number") {
throw new Error("LastXCommitsDepth must be a number");
}
const topLevelDir = fileURLToPath((await args.ide.getWorkspaceDirs())[0]);
try {
const gitResult = await runGitCommand(
[
"--no-pager",
"log",
'--pretty=format:"%H%x00%s"',
`-n`,
depth.toString(),
],
topLevelDir,
);
const recentCommits = [
{
id: `last ${lastXCommitsDepth} commits`,
title: `last ${lastXCommitsDepth} commits`,
description: "recent commits",
},
];
const allCommits = gitResult
.trim()
.split("\n")
.map((line) => {
let [hash, message] = line.split("\0");
hash = hash.replace(/"/g, "");
message = message.replace(/"/g, "");
return {
id: hash,
title: message,
description: hash,
};
});
return recentCommits.concat(allCommits);
}catch(err: any){
} catch (err: any) {
//could be nice to toast the error eg. not a git repo or git is not installed
return [];
}

View file

@ -27,9 +27,9 @@ class LlamaEncoding implements Encoding {
}
class NonWorkerAsyncEncoder implements AsyncEncoder {
constructor(private readonly encoding: Encoding) { }
constructor(private readonly encoding: Encoding) {}
async close(): Promise<void> { }
async close(): Promise<void> {}
async encode(text: string): Promise<number[]> {
return this.encoding.encode(text);
@ -313,8 +313,21 @@ function pruneChatHistory(
// 4. Remove entire messages in the last 5, except last 1
while (totalTokens > contextLength && chatHistory.length > 1) {
const message = chatHistory.shift()!;
totalTokens -= countTokens(message.content, modelName);
// If tool call/response detected prune both (can't have response with no call)
// TODO prune lines from tool response before pruning both messages
if (
chatHistory.length > 2 &&
messageHasToolCalls(chatHistory[0]) &&
chatHistory[1].role === "tool"
) {
const firstMessage = chatHistory.shift()!;
const secondMessage = chatHistory.shift()!;
totalTokens -= countTokens(firstMessage.content, modelName);
totalTokens -= countTokens(secondMessage.content, modelName);
} else {
const message = chatHistory.shift()!;
totalTokens -= countTokens(message.content, modelName);
}
}
// 5. Truncate last message
@ -328,7 +341,6 @@ function pruneChatHistory(
);
totalTokens = contextLength;
}
return chatHistory;
}
@ -384,8 +396,8 @@ function compileChatMessages(
): ChatMessage[] {
let msgsCopy = msgs
? msgs
.map((msg) => ({ ...msg }))
.filter((msg) => !chatMessageIsEmpty(msg) && msg.role !== "system")
.map((msg) => ({ ...msg }))
.filter((msg) => !chatMessageIsEmpty(msg) && msg.role !== "system")
: [];
msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy);
@ -470,6 +482,5 @@ export {
pruneLinesFromTop,
pruneRawPromptFromTop,
pruneStringFromBottom,
pruneStringFromTop
pruneStringFromTop,
};

View file

@ -4,6 +4,7 @@ import {
CompletionOptions,
LLMOptions,
MessagePart,
TextMessagePart,
ToolCallDelta,
} from "../../index.js";
import { findLast } from "../../util/findLast.js";
@ -69,20 +70,84 @@ class Gemini extends BaseLLM {
}
}
/**
* Removes the system message and merges it with the next user message if present.
* @param messages Array of chat messages
* @returns Modified array with system message merged into user message if applicable
*/
public removeSystemMessage(messages: ChatMessage[]): ChatMessage[] {
// should be public for use within VertexAI
const msgs = [...messages];
// If no messages or first message isn't system, return copy of original messages
if (messages.length === 0 || messages[0]?.role !== "system") {
return [...messages];
}
if (msgs[0]?.role === "system") {
const sysMsg = msgs.shift()?.content;
// @ts-ignore
if (msgs[0]?.role === "user") {
// @ts-ignore
msgs[0].content = `System message - follow these instructions in every response: ${sysMsg}\n\n---\n\n${msgs[0].content}`;
// Extract system message
const systemMessage: ChatMessage = messages[0];
// Extract system content based on its type
let systemContent = "";
if (typeof systemMessage.content === "string") {
systemContent = systemMessage.content;
} else if (Array.isArray(systemMessage.content)) {
const contentArray: Array<MessagePart> =
systemMessage.content as Array<MessagePart>;
const concatenatedText = contentArray
.filter((part): part is TextMessagePart => part.type === "text")
.map((part) => part.text)
.join(" ");
systemContent = concatenatedText ? concatenatedText : "";
} else if (
systemMessage.content &&
typeof systemMessage.content === "object"
) {
const typedContent = systemMessage.content as TextMessagePart;
systemContent = typedContent?.text || "";
}
// Create new array without the system message
const remainingMessages: ChatMessage[] = messages.slice(1);
// Check if there's a user message to merge with
if (remainingMessages.length > 0 && remainingMessages[0].role === "user") {
const userMessage: ChatMessage = remainingMessages[0];
const prefix = `System message - follow these instructions in every response: ${systemContent}\n\n---\n\n`;
// Merge based on user content type
if (typeof userMessage.content === "string") {
userMessage.content = prefix + userMessage.content;
} else if (Array.isArray(userMessage.content)) {
const contentArray: Array<MessagePart> =
userMessage.content as Array<MessagePart>;
const textPart = contentArray.find((part) => part.type === "text") as
| TextMessagePart
| undefined;
if (textPart) {
textPart.text = prefix + textPart.text;
} else {
userMessage.content.push({
type: "text",
text: prefix,
} as TextMessagePart);
}
} else if (
userMessage.content &&
typeof userMessage.content === "object"
) {
const typedContent = userMessage.content as TextMessagePart;
userMessage.content = [
{
type: "text",
text: prefix + (typedContent.text || ""),
} as TextMessagePart,
];
}
}
return msgs;
return remainingMessages;
}
protected async *_streamChat(

View file

@ -21,7 +21,7 @@ class WatsonX extends BaseLLM {
if (this.apiBase?.includes("cloud.ibm.com")) {
// watsonx SaaS
const wxToken = await (
await fetch(
await this.fetch(
`https://iam.cloud.ibm.com/identity/token?apikey=${this.apiKey}&grant_type=urn:ibm:params:oauth:grant-type:apikey`,
{
method: "POST",
@ -48,7 +48,7 @@ class WatsonX extends BaseLLM {
// Using username/password auth
const userPass = this.apiKey?.split(":");
const wxToken = await (
await fetch(`${this.apiBase}/icp4d-api/v1/authorize`, {
await this.fetch(`${this.apiBase}/icp4d-api/v1/authorize`, {
method: "POST",
headers: {
"Content-Type": "application/json",
@ -61,7 +61,7 @@ class WatsonX extends BaseLLM {
})
).json();
const wxTokenExpiry = await (
await fetch(`${this.apiBase}/usermgmt/v1/user/tokenExpiry`, {
await this.fetch(`${this.apiBase}/usermgmt/v1/user/tokenExpiry`, {
method: "GET",
headers: {
Accept: "application/json",

View file

@ -5,7 +5,7 @@ import { parsePromptFileV1V2 } from "../v2/parsePromptFileV1V2";
import { getContextProviderHelpers } from "./getContextProviderHelpers";
import { renderTemplatedString } from "./renderTemplatedString";
import { updateChatHistory } from "./updateChatHistory";
import { replaceSlashCommandWithPromptInChatHistory } from "./updateChatHistory";
export function extractName(preamble: { name?: string }, path: string): string {
return preamble.name ?? getLastNPathParts(path, 1).split(".prompt")[0];
@ -68,7 +68,7 @@ export function slashCommandFromPromptFileV1(
const userInput = extractUserInput(context.input, name);
const renderedPrompt = await renderPromptV1(prompt, context, userInput);
const messages = updateChatHistory(
const messages = replaceSlashCommandWithPromptInChatHistory(
context.history,
name,
renderedPrompt,

View file

@ -1,4 +1,4 @@
export function updateChatHistory(
export function replaceSlashCommandWithPromptInChatHistory(
history: any[],
commandName: string,
renderedPrompt: string,

View file

@ -6,7 +6,7 @@ export const readCurrentlyOpenFileTool: Tool = {
displayTitle: "Read Currently Open File",
wouldLikeTo: "read the current file",
isCurrently: "reading the current file",
hasAlready: "read the current file",
hasAlready: "viewed the current file",
readonly: true,
group: BUILT_IN_GROUP_NAME,
function: {

View file

@ -6,7 +6,7 @@ export const readFileTool: Tool = {
displayTitle: "Read File",
wouldLikeTo: "read {{{ filepath }}}",
isCurrently: "reading {{{ filepath }}}",
hasAlready: "read {{{ filepath }}}",
hasAlready: "viewed {{{ filepath }}}",
readonly: true,
group: BUILT_IN_GROUP_NAME,
function: {

View file

@ -128,8 +128,8 @@ You can also configure generation parameters, such as temperature, topP, topK, f
apiBase: watsonx endpoint e.g. https://us-south.ml.cloud.ibm.com
apiKey: API_KEY/ZENAPI_KEY/USERNAME:PASSWORD
template: granite
contextLength: 8000
defaultCompletionOptions:
contextLength: 8000
temperature: 0.1
topP: 0.3
topK: 20
@ -245,7 +245,6 @@ To view the list of available embeddings models, visit [this page](https://datap
</TabItem>
</Tabs>
## Reranker
<Tabs groupId="config-example">

View file

@ -0,0 +1,20 @@
---
title: Creating an Organization
description: Creating an Organization
keywords: [governance, organization, org, create]
---
To Create an Organization, click the organization selector in the top right and select `Create Organization`
![create an org selector](/img/hub/org-selector.png)
1. Choose a name, which will be used as the display name for your organization throughout the hub
2. Add a slug, which will be used for your org URL and as the prefix to all organization blocks and assistant slugs
3. Select an icon for your organization using the image uploader
4. Finally, add a Biography, which will be displayed on your org Home Page
![Creating an org](/img/hub/create-org-form.png)
You will then be signed in to your org and taken to the org home page
![Org home page](/img/hub/org-home-page.png)

View file

@ -22,4 +22,4 @@ keywords:
- [Chat](chat/how-to-use-it) to understand and iterate on code in the sidebar
- [Autocomplete](autocomplete/how-to-use-it) to receive inline code suggestions as you type
- [Edit](edit/how-to-use-it) to modify code without leaving your current file
- [Agent](agent/how-to-use-it) to make more substanial changes to your codebase
- [Agent](agent/how-to-use-it) to make more substantial changes to your codebase

View file

@ -165,7 +165,11 @@ const sidebars = {
{
type: "category",
label: "Governance",
items: ["hub/governance/org-permissions", "hub/governance/pricing"],
items: [
"hub/governance/org-permissions",
"hub/governance/creating-an-org",
"hub/governance/pricing",
],
},
{
type: "link",

BIN
docs/static/img/hub/create-org-form.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 117 KiB

BIN
docs/static/img/hub/org-home-page.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 122 KiB

BIN
docs/static/img/hub/org-selector.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

View file

@ -3,7 +3,7 @@ pluginGroup=com.github.continuedev.continueintellijextension
pluginName=continue-intellij-extension
pluginRepositoryUrl=https://github.com/continuedev/continue
# SemVer format -> https://semver.org
pluginVersion=1.0.8
pluginVersion=1.0.9
# Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html
pluginSinceBuild=223
# IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension

View file

@ -1,4 +1,5 @@
package com.github.continuedev.continueintellijextension.activities
import IntelliJIDE
import com.intellij.openapi.fileEditor.FileEditorManagerListener
import com.github.continuedev.continueintellijextension.auth.AuthListener
import com.github.continuedev.continueintellijextension.auth.ContinueAuthService
@ -185,6 +186,8 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware {
// Notify core of content changes
if (changedURIs.isNotEmpty()) {
continuePluginService.updateLastFileSaveTimestamp()
val data = mapOf("uris" to changedURIs)
continuePluginService.coreMessenger?.request("files/changed", data, null) { _ -> }
}

View file

@ -0,0 +1,94 @@
package com.github.continuedev.continueintellijextension.`continue`
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.github.continuedev.continueintellijextension.utils.toUriOrNull
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.guessProjectDir
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.BufferedReader
import java.io.File
import java.io.InputStreamReader
import java.net.URI
class GitService(
private val project: Project,
private val continuePluginService: ContinuePluginService
) {
// Add a simple cache for diff results
private data class DiffCache(
val timestamp: Long,
val diffs: List<String>
)
// Cache the last diff result
private var diffCache: DiffCache? = null
private var lastFileSaveTimestamp: Long = System.currentTimeMillis()
/**
* Updates the timestamp when a file is saved
*/
fun updateLastFileSaveTimestamp() {
lastFileSaveTimestamp = System.currentTimeMillis()
}
/**
* Returns the git diff for all workspace directories
*/
suspend fun getDiff(includeUnstaged: Boolean): List<String> {
// Check if we have a valid cache entry
if (diffCache != null && diffCache!!.timestamp == lastFileSaveTimestamp) {
return diffCache!!.diffs
}
// If no cache hit, compute the diff
val workspaceDirs = workspaceDirectories()
val diffs = mutableListOf<String>()
for (workspaceDir in workspaceDirs) {
val output = StringBuilder()
val builder = if (includeUnstaged) {
ProcessBuilder("git", "diff")
} else {
ProcessBuilder("git", "diff", "--cached")
}
builder.directory(File(URI(workspaceDir)))
val process = withContext(Dispatchers.IO) {
builder.start()
}
val reader = BufferedReader(InputStreamReader(process.inputStream))
var line: String? = withContext(Dispatchers.IO) {
reader.readLine()
}
while (line != null) {
output.append(line)
output.append("\n")
line = withContext(Dispatchers.IO) {
reader.readLine()
}
}
withContext(Dispatchers.IO) {
process.waitFor()
}
diffs.add(output.toString())
}
// Cache the result
diffCache = DiffCache(lastFileSaveTimestamp, diffs)
return diffs
}
private fun workspaceDirectories(): Array<String> {
val dirs = this.continuePluginService.workspacePaths
if (dirs?.isNotEmpty() == true) {
return dirs
}
return listOfNotNull(project.guessProjectDir()?.toUriOrNull()).toTypedArray()
}
}

View file

@ -45,6 +45,10 @@ class IdeProtocolClient(
)
}
fun updateLastFileSaveTimestamp() {
(ide as IntelliJIDE).updateLastFileSaveTimestamp()
}
fun handleMessage(msg: String, respond: (Any?) -> Unit) {
coroutineScope.launch(Dispatchers.IO) {
val message = Gson().fromJson(msg, Message::class.java)

View file

@ -1,13 +1,9 @@
import com.github.continuedev.continueintellijextension.*
import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath
import com.github.continuedev.continueintellijextension.`continue`.GitService
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.github.continuedev.continueintellijextension.utils.OS
import com.github.continuedev.continueintellijextension.utils.getMachineUniqueID
import com.github.continuedev.continueintellijextension.utils.getOS
import com.github.continuedev.continueintellijextension.utils.toUriOrNull
import com.github.continuedev.continueintellijextension.utils.Desktop
import com.google.gson.Gson
import com.github.continuedev.continueintellijextension.utils.*
import com.intellij.codeInsight.daemon.impl.HighlightInfo
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.util.ExecUtil
@ -31,12 +27,7 @@ import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.psi.PsiDocumentManager
import com.intellij.testFramework.LightVirtualFile
import com.intellij.util.containers.toArray
import kotlinx.coroutines.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import java.awt.Toolkit
import java.awt.datatransfer.DataFlavor
import java.io.BufferedReader
@ -44,7 +35,6 @@ import java.io.File
import java.io.FileInputStream
import java.io.InputStreamReader
import java.net.URI
import java.net.URL
import java.nio.charset.Charset
import java.nio.file.Paths
@ -52,7 +42,11 @@ class IntelliJIDE(
private val project: Project,
private val continuePluginService: ContinuePluginService,
) : IDE {
) : IDE {
private val gitService = GitService(project, continuePluginService)
private val ripgrep: String
init {
@ -66,6 +60,13 @@ class IntelliJIDE(
Paths.get(pluginPath.toString(), "ripgrep", "bin", "rg" + if (os == OS.WINDOWS) ".exe" else "").toString()
}
/**
* Updates the timestamp when a file is saved
*/
override fun updateLastFileSaveTimestamp() {
gitService.updateLastFileSaveTimestamp()
}
override suspend fun getIdeInfo(): IdeInfo {
val applicationInfo = ApplicationInfo.getInstance()
val ideName: String = applicationInfo.fullApplicationName
@ -110,41 +111,7 @@ class IntelliJIDE(
}
override suspend fun getDiff(includeUnstaged: Boolean): List<String> {
val workspaceDirs = workspaceDirectories()
val diffs = mutableListOf<String>()
for (workspaceDir in workspaceDirs) {
val output = StringBuilder()
val builder = if (includeUnstaged) {
ProcessBuilder("git", "diff")
} else {
ProcessBuilder("git", "diff", "--cached")
}
builder.directory(File(URI(workspaceDir)))
val process = withContext(Dispatchers.IO) {
builder.start()
}
val reader = BufferedReader(InputStreamReader(process.inputStream))
var line: String? = withContext(Dispatchers.IO) {
reader.readLine()
}
while (line != null) {
output.append(line)
output.append("\n")
line = withContext(Dispatchers.IO) {
reader.readLine()
}
}
withContext(Dispatchers.IO) {
process.waitFor()
}
diffs.add(output.toString())
}
return diffs
return gitService.getDiff(includeUnstaged)
}
override suspend fun getClipboardContent(): Map<String, String> {
@ -185,7 +152,7 @@ class IntelliJIDE(
}
override suspend fun getWorkspaceConfigs(): List<ContinueRcJson> {
val workspaceDirs = workspaceDirectories()
val workspaceDirs = this.getWorkspaceDirs()
val configs = mutableListOf<String>()
@ -434,7 +401,7 @@ class IntelliJIDE(
}
override suspend fun getTags(artifactId: String): List<IndexTag> {
val workspaceDirs = workspaceDirectories()
val workspaceDirs = this.getWorkspaceDirs()
// Collect branches concurrently using Kotlin coroutines
val branches = withContext(Dispatchers.IO) {
@ -577,4 +544,5 @@ class IntelliJIDE(
return listOfNotNull(project.guessProjectDir()?.toUriOrNull()).toTypedArray()
}
}

View file

@ -41,4 +41,8 @@ class ContinuePluginService : Disposable, DumbAware {
) {
continuePluginWindow?.browser?.sendToWebview(messageType, data, messageId)
}
fun updateLastFileSaveTimestamp() {
ideProtocolClient?.updateLastFileSaveTimestamp()
}
}

View file

@ -192,6 +192,10 @@ interface IDE {
// Callbacks
fun onDidChangeActiveTextEditor(callback: (filepath: String) -> Unit)
fun updateLastFileSaveTimestamp() {
// Default implementation does nothing
}
}
data class GetGhTokenArgs(

View file

@ -3063,7 +3063,7 @@
"default": {
"title": "Tab Autocomplete Model",
"provider": "ollama",
"model": "deepseek-coder:1.3b-base"
"model": "qwen2.5-coder:1.5b-base"
},
"oneOf": [
{

View file

@ -1,12 +1,12 @@
{
"name": "continue",
"version": "1.1.17",
"version": "1.1.18",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "1.1.17",
"version": "1.1.18",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/fetch": "^1.0.3",

View file

@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
"version": "1.1.17",
"version": "1.1.18",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"

8
gui/package-lock.json generated
View file

@ -95,7 +95,7 @@
"tailwindcss": "^3.2.7",
"typescript": "^5.6.3",
"typescript-eslint": "^8.16.0",
"vite": "^4.1.0",
"vite": "^4.5.11",
"vitest": "^2.1.3"
},
"engines": {
@ -12291,9 +12291,9 @@
}
},
"node_modules/vite": {
"version": "4.5.9",
"resolved": "https://registry.npmjs.org/vite/-/vite-4.5.9.tgz",
"integrity": "sha512-qK9W4xjgD3gXbC0NmdNFFnVFLMWSNiR3swj957yutwzzN16xF/E7nmtAyp1rT9hviDroQANjE4HK3H4WqWdFtw==",
"version": "4.5.11",
"resolved": "https://registry.npmjs.org/vite/-/vite-4.5.11.tgz",
"integrity": "sha512-4mVdhLkZ0vpqZLGJhNm+X1n7juqXApEMGlUXcOQawA45UmpxivOYaMBkI/Js3FlBsNA8hCgEnX5X04moFitSGw==",
"dev": true,
"license": "MIT",
"dependencies": {

View file

@ -103,7 +103,7 @@
"tailwindcss": "^3.2.7",
"typescript": "^5.6.3",
"typescript-eslint": "^8.16.0",
"vite": "^4.1.0",
"vite": "^4.5.11",
"vitest": "^2.1.3"
},
"engine-strict": true,

View file

@ -39,15 +39,15 @@ export default function AddFileButton({ onClick }: AddFileButtonProps) {
className="bg-vsc-editor-background m-0 rounded-md p-0"
>
<div
className="flex h-5 w-14 items-center justify-center gap-1 hover:brightness-125"
className="flex h-5 items-center justify-center gap-1 hover:brightness-125"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
onClick();
}}
>
<PlusIcon className="text-vsc-foreground inline h-2.5 w-2.5 brightness-75" />
<span className="text-vsc-foreground text-[10px] brightness-75">
<PlusIcon className="text-vsc-foreground inline h-2.5 w-2.5 px-1 brightness-75" />
<span className="text-vsc-foreground xs:block hidden text-[10px] brightness-75">
Add file
</span>
</div>

View file

@ -1,16 +1,16 @@
import { PlusIcon, XMarkIcon } from "@heroicons/react/24/outline";
import type { CodeToEdit } from "core";
import { useContext, useState } from "react";
import { useDispatch } from "react-redux";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import CodeToEditListItem from "./CodeToEditListItem";
import type { CodeToEdit } from "core";
import AddFileButton from "./AddFileButton";
import AddFileCombobox from "./AddFileCombobox";
import { PlusIcon, XMarkIcon } from "@heroicons/react/24/outline";
import { useAppSelector } from "../../redux/hooks";
import {
addCodeToEdit,
removeCodeToEdit,
} from "../../redux/slices/sessionSlice";
import AddFileButton from "./AddFileButton";
import AddFileCombobox from "./AddFileCombobox";
import CodeToEditListItem from "./CodeToEditListItem";
export default function CodeToEditCard() {
const dispatch = useDispatch();
@ -18,12 +18,12 @@ export default function CodeToEditCard() {
const [showAddFileCombobox, setShowAddFileCombobox] = useState(false);
const codeToEdit = useAppSelector((state) => state.session.codeToEdit);
const title =
const itemCount =
codeToEdit.length === 0
? "Code to edit"
? ""
: codeToEdit.length === 1
? "Code to edit (1 item)"
: `Code to edit (${codeToEdit.length} items)`;
? "(1 item)"
: `(${codeToEdit.length} items)`;
function onDelete(rif: CodeToEdit) {
dispatch(removeCodeToEdit(rif));
@ -57,7 +57,11 @@ export default function CodeToEditCard() {
return (
<div className="bg-vsc-editor-background mx-3 flex flex-col rounded-t-lg p-1">
<div className="text-lightgray flex items-center justify-between gap-1.5 py-1.5 pl-3 pr-2 text-xs">
<span>{title}</span>
<div className="flex items-center gap-1">
<span>Code to edit</span>
<span className="hidden sm:inline">{itemCount}</span>
</div>
<AddFileButton onClick={() => setShowAddFileCombobox(true)} />
</div>

View file

@ -23,12 +23,17 @@ export function ExploreHubCard() {
return dispatch(setIsExploreDialogOpen(false));
}}
>
<div className="flex flex-col items-center gap-1 p-4 text-center">
<h2 className="text-2xl font-semibold">Create Your Own Assistant</h2>
<div className="flex flex-col items-center gap-1 px-4 text-center">
<div className="mb-4">
<h2 className="mb-1 text-xl font-semibold">
Create Your Own Assistant
</h2>
<p className="max-w-lg text-base leading-relaxed">
Discover and remix popular assistants, or create your own from scratch
</p>
<p className="text-lightgray my-0 max-w-lg text-sm font-light leading-relaxed">
Discover and remix popular assistants, or create your own from
scratch
</p>
</div>
<Button
className="w-full"
@ -50,7 +55,7 @@ export function ExploreHubCard() {
});
}}
>
<div className="mt-4 flex cursor-pointer items-center justify-center gap-1">
<div className="flex cursor-pointer items-center justify-center gap-1">
<span>Or, create your own assistant from scratch</span>
<ChevronRightIcon className="h-3 w-3" />
</div>

View file

@ -33,10 +33,10 @@ export function ReusableCard({
>
{showCloseButton && (
<CloseButton onClick={onClose}>
<XMarkIcon className="mt-1.5 hidden h-5 w-5 hover:brightness-125 sm:flex" />
<XMarkIcon className="flex h-5 w-5 hover:brightness-125" />
</CloseButton>
)}
<div className="content py-4">{children}</div>
<div className="content py-2">{children}</div>
</StyledCard>
);
}

View file

@ -1,6 +1,6 @@
import { Editor, JSONContent } from "@tiptap/react";
import { ContextItemWithId, InputModifiers } from "core";
import { useMemo, useState } from "react";
import { useMemo } from "react";
import styled, { keyframes } from "styled-components";
import { defaultBorderRadius, vscBackground } from "..";
import { useAppSelector } from "../../redux/hooks";
@ -113,12 +113,10 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
}
: {};
const [lumpOpen, setLumpOpen] = useState(true);
return (
<div className={`${props.hidden ? "hidden" : ""}`}>
<div className={`relative flex flex-col px-2`}>
{props.isMainInput && <Lump open={lumpOpen} setOpen={setLumpOpen} />}
{props.isMainInput && <Lump />}
<GradientBorder
loading={isStreaming && props.isLastUserInput ? 1 : 0}
borderColor={
@ -135,8 +133,6 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
availableSlashCommands={filteredSlashCommands}
historyKey={historyKey}
toolbarOptions={toolbarOptions}
lumpOpen={lumpOpen}
setLumpOpen={setLumpOpen}
inputId={props.inputId}
/>
</GradientBorder>

View file

@ -31,7 +31,7 @@ import { ToolTip } from "../gui/Tooltip";
import ModelSelect from "../modelSelection/ModelSelect";
import ModeSelect from "../modelSelection/ModeSelect";
import { useFontSize } from "../ui/font";
import HoverItem from "./InputToolbar/bottom/HoverItem";
import HoverItem from "./InputToolbar/HoverItem";
const StyledDiv = styled.div<{ isHidden?: boolean }>`
padding-top: 4px;
@ -87,8 +87,6 @@ interface InputToolbarProps {
toolbarOptions?: ToolbarOptions;
disabled?: boolean;
isMainInput?: boolean;
lumpOpen: boolean;
setLumpOpen: (open: boolean) => void;
}
function InputToolbar(props: InputToolbarProps) {

View file

@ -2,10 +2,10 @@ import { InformationCircleIcon } from "@heroicons/react/24/outline";
import { Tool } from "core";
import { useEffect } from "react";
import { useDispatch } from "react-redux";
import { useAppSelector } from "../../../../redux/hooks";
import { addTool, toggleToolSetting } from "../../../../redux/slices/uiSlice";
import { fontSize } from "../../../../util";
import { ToolTip } from "../../../gui/Tooltip";
import { useAppSelector } from "../../../redux/hooks";
import { addTool, toggleToolSetting } from "../../../redux/slices/uiSlice";
import { fontSize } from "../../../util";
import { ToolTip } from "../../gui/Tooltip";
interface ToolDropdownItemProps {
tool: Tool;

View file

@ -1,9 +1,9 @@
import { Tool } from "core";
import { useMemo } from "react";
import { useAppDispatch, useAppSelector } from "../../../../redux/hooks";
import { toggleToolGroupSetting } from "../../../../redux/slices/uiSlice";
import { fontSize } from "../../../../util";
import ToggleSwitch from "../../../gui/Switch";
import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
import { toggleToolGroupSetting } from "../../../redux/slices/uiSlice";
import { fontSize } from "../../../util";
import ToggleSwitch from "../../gui/Switch";
import ToolDropdownItem from "./ToolDropdownItem";
export const ToolPermissionsDialog = () => {

View file

@ -1,22 +0,0 @@
import { EllipsisHorizontalIcon } from "@heroicons/react/24/outline";
import { ToolbarOptions } from "../../InputToolbar";
import HoverItem from "../bottom/HoverItem";
interface TopInputToolbarProps {
toolbarOptions?: ToolbarOptions;
onAddContextItem?: () => void;
lumpOpen: boolean;
setLumpOpen: (open: boolean) => void;
}
export function TopInputToolbar(props: TopInputToolbarProps) {
return (
<div className="-mb-2 -mt-1 flex items-center">
<HoverItem
onClick={() => props.setLumpOpen(!props.lumpOpen)}
className="ml-auto"
>
<EllipsisHorizontalIcon className="h-3 w-3 text-gray-400 hover:brightness-125" />
</HoverItem>
</div>
);
}

View file

@ -13,7 +13,7 @@ import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
import { toggleBlockSettingsToolbar } from "../../../redux/slices/uiSlice";
import { fontSize } from "../../../util";
import AssistantSelect from "../../modelSelection/platform/AssistantSelect";
import HoverItem from "../InputToolbar/bottom/HoverItem";
import HoverItem from "../InputToolbar/HoverItem";
interface BlockSettingsToolbarIcon {
tooltip: string;
@ -57,7 +57,7 @@ function BlockSettingsToolbarIcon(props: BlockSettingsToolbarIcon) {
className={`relative flex select-none items-center rounded-full px-1 transition-all duration-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500/50 ${props.className || ""}`}
>
<props.icon
className="h-3 w-3 hover:brightness-125"
className="h-[13px] w-[13px] flex-shrink-0 hover:brightness-125"
style={{
color: props.isSelected ? vscBadgeForeground : undefined,
}}
@ -129,7 +129,7 @@ export function BlockSettingsTopToolbar(props: BlockSettingsTopToolbarProps) {
</div>
</div>
</div>
<div className="ml-auto">
<div>
<AssistantSelect />
</div>
</div>

View file

@ -3,10 +3,7 @@ import styled from "styled-components";
import { AnimatedEllipsis } from "../..";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
import {
clearLastEmptyResponse,
setInactive,
} from "../../../redux/slices/sessionSlice";
import { cancelStream } from "../../../redux/thunks/cancelStream";
import { getFontSize, getMetaKeyLabel } from "../../../util";
import { BlockSettingsTopToolbar } from "./BlockSettingsTopToolbar";
@ -67,8 +64,7 @@ export function LumpToolbar(props: TopToolbarProps) {
<StopButton
className="text-gray-400"
onClick={() => {
dispatch(setInactive());
dispatch(clearLastEmptyResponse());
dispatch(cancelStream());
}}
>
{getMetaKeyLabel()} ⌫ Cancel

View file

@ -9,12 +9,7 @@ import { useAppSelector } from "../../../redux/hooks";
import { LumpToolbar } from "./LumpToolbar";
import { SelectedSection } from "./sections/SelectedSection";
interface LumpProps {
open: boolean;
setOpen: (open: boolean) => void;
}
const LumpDiv = styled.div<{ open: boolean }>`
const LumpDiv = styled.div`
background-color: ${vscInputBackground};
margin-left: 4px;
margin-right: 4px;
@ -35,33 +30,50 @@ const ContentDiv = styled.div<{ hasSection: boolean; isVisible: boolean }>`
overflow-y: auto;
`;
export function Lump(props: LumpProps) {
const { open, setOpen } = props;
export function Lump() {
const [selectedSection, setSelectedSection] = useState<string | null>(null);
const [displayedSection, setDisplayedSection] = useState<string | null>(null);
const [isVisible, setIsVisible] = useState(false);
const isStreaming = useAppSelector((state) => state.session.isStreaming);
useEffect(() => {
if (!selectedSection) {
return;
}
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape") {
setSelectedSection(null);
}
};
document.addEventListener("keydown", handleKeyDown);
return () => {
document.removeEventListener("keydown", handleKeyDown);
};
}, [selectedSection]);
useEffect(() => {
if (isStreaming) {
setSelectedSection(null);
}
}, [isStreaming]);
useEffect(() => {
if (selectedSection) {
setDisplayedSection(selectedSection);
setIsVisible(true);
} else {
setIsVisible(false);
// Delay clearing the displayed section until after the fade-out
const timeout = setTimeout(() => {
setDisplayedSection(null);
}, 300); // Match the transition duration
return () => clearTimeout(timeout);
}, 300);
return () => {
clearTimeout(timeout);
};
}
}, [selectedSection]);
if (!open) {
return null;
}
return (
<LumpDiv open={open}>
<LumpDiv>
<div className="mt-0.5 px-2">
<LumpToolbar
selectedSection={selectedSection}
@ -73,9 +85,7 @@ export function Lump(props: LumpProps) {
hasSection={!!selectedSection}
isVisible={isVisible}
>
{!isStreaming && (
<SelectedSection selectedSection={displayedSection} />
)}
<SelectedSection selectedSection={displayedSection} />
</ContentDiv>
</div>
</LumpDiv>

View file

@ -1,4 +1,4 @@
import { ToolPermissionsDialog } from "../../InputToolbar/bottom/ToolPermissionsDialog";
import { ToolPermissionsDialog } from "../../InputToolbar/ToolPermissionsDialog";
interface ToolsSectionProps {}

View file

@ -32,8 +32,6 @@ export interface TipTapEditorProps {
) => void;
editorState?: JSONContent;
toolbarOptions?: ToolbarOptions;
lumpOpen: boolean;
setLumpOpen: (open: boolean) => void;
placeholder?: string;
historyKey: string;
inputId: string;
@ -262,8 +260,6 @@ function TipTapEditor(props: TipTapEditorProps) {
activeKey={activeKey}
hidden={shouldHideToolbar && !props.isMainInput}
onAddContextItem={() => insertCharacterWithWhitespace("@")}
lumpOpen={props.lumpOpen}
setLumpOpen={props.setLumpOpen}
onEnter={onEnterRef.current}
onImageFileSelected={(file) => {
handleImageFile(ideMessenger, file).then((result) => {

View file

@ -30,7 +30,6 @@ import { getFontSize } from "../../../util";
import { AddCodeToEdit } from "./extensions/AddCodeToEditExtension";
import { CodeBlockExtension } from "./extensions/CodeBlockExtension";
import { SlashCommand } from "./extensions/CommandsExtension";
import { MockExtension } from "./extensions/FillerExtension";
import { Mention } from "./extensions/MentionExtension";
import {
getContextProviderDropdownOptions,
@ -352,22 +351,20 @@ export function createEditorConfig(options: {
},
},
}),
props.availableSlashCommands.length
? SlashCommand.configure({
HTMLAttributes: {
class: "mention",
},
suggestion: getSlashCommandDropdownOptions(
availableSlashCommandsRef,
onClose,
onOpen,
ideMessenger,
),
renderText: (props) => {
return props.node.attrs.label;
},
})
: MockExtension,
SlashCommand.configure({
HTMLAttributes: {
class: "mention",
},
suggestion: getSlashCommandDropdownOptions(
availableSlashCommandsRef,
onClose,
onOpen,
ideMessenger,
),
renderText: (props) => {
return props.node.attrs.label;
},
}),
CodeBlockExtension,
],
editorProps: {

View file

@ -1,20 +0,0 @@
import { Node } from "@tiptap/core";
export const MockExtension = Node.create({
name: "mockExtension",
addOptions() {
return {
enabled: false,
};
},
addCommands() {
return {};
},
addKeyboardShortcuts() {
return {};
},
addProseMirrorPlugins() {
return [];
},
});

View file

@ -203,7 +203,7 @@ export function getSlashCommandDropdownOptions(
const filteredCommands =
query.length > 0
? options.filter((slashCommand) => {
const sc = slashCommand.title.substring(1).toLowerCase();
const sc = slashCommand.title.toLowerCase();
const iv = query.toLowerCase();
return sc.startsWith(iv);
})
@ -219,7 +219,7 @@ export function getSlashCommandDropdownOptions(
action: provider.action,
}));
if (query.length === 0 && commandItems.length > 0) {
if (query.length === 0 && commandItems.length === 0) {
commandItems.push({
title: "Explore prompts",
type: "action",

View file

@ -7,10 +7,11 @@ import {
MessageContent,
MessagePart,
RangeInFile,
SlashCommandDescription,
TextMessagePart,
} from "core";
import { ctxItemToRifWithContents } from "core/commands/util";
import { stripImages } from "core/util/messageContent";
import { renderChatMessage, stripImages } from "core/util/messageContent";
import { getUriFileExtension } from "core/util/uri";
import { IIdeMessenger } from "../../../context/IdeMessenger";
import { setIsGatheringContext } from "../../../redux/slices/sessionSlice";
@ -27,6 +28,7 @@ interface ResolveEditorContentInput {
modifiers: InputModifiers;
ideMessenger: IIdeMessenger;
defaultContextProviders: DefaultContextProvider[];
availableSlashCommands: SlashCommandDescription[];
selectedModelTitle: string;
dispatch: Dispatch;
}
@ -40,22 +42,37 @@ async function resolveEditorContent({
modifiers,
ideMessenger,
defaultContextProviders,
availableSlashCommands,
selectedModelTitle,
dispatch,
}: ResolveEditorContentInput): Promise<
[ContextItemWithId[], RangeInFile[], MessageContent]
[
ContextItemWithId[],
RangeInFile[],
MessageContent,
(
| {
command: SlashCommandDescription;
input: string;
}
| undefined
),
]
> {
let parts: MessagePart[] = [];
let contextItemAttrs: MentionAttrs[] = [];
const selectedCode: RangeInFile[] = [];
let slashCommand: string | undefined = undefined;
let slashCommandName: string | undefined = undefined;
let slashCommandWithInput:
| { command: SlashCommandDescription; input: string }
| undefined = undefined;
if (editorState?.content) {
for (const p of editorState.content) {
if (p.type === "paragraph") {
const [text, ctxItems, foundSlashCommand] = resolveParagraph(p);
// Only take the first slash command\
if (foundSlashCommand && typeof slashCommand === "undefined") {
slashCommand = foundSlashCommand;
// Only take the first slash command
if (foundSlashCommand && typeof slashCommandName === "undefined") {
slashCommandName = foundSlashCommand;
}
contextItemAttrs.push(...ctxItems);
@ -113,7 +130,38 @@ async function resolveEditorContent({
}
}
const shouldGatherContext = modifiers.useCodebase || slashCommand;
if (slashCommandName) {
const command = availableSlashCommands.find(
(c) => c.name === slashCommandName,
);
if (command) {
const lastTextIndex = findLastIndex(
parts,
(part) => part.type === "text",
);
const lastTextPart = parts[lastTextIndex] as TextMessagePart;
let input: string;
// Get input and add text of last slash command text back in to last text node
if (lastTextPart) {
input = renderChatMessage({
role: "user",
content: lastTextPart.text,
}).trimStart();
lastTextPart.text = `/${command.name} ${lastTextPart.text}`;
} else {
input = "";
parts.push({ type: "text", text: `/${command.name}` });
}
slashCommandWithInput = {
command,
input,
};
}
}
const shouldGatherContext = modifiers.useCodebase || slashCommandWithInput;
if (shouldGatherContext) {
dispatch(setIsGatheringContext(true));
}
@ -179,21 +227,11 @@ async function resolveEditorContent({
contextItemsText += "\n";
}
if (slashCommand) {
let lastTextIndex = findLastIndex(parts, (part) => part.type === "text");
const lastTextPart = parts[lastTextIndex] as TextMessagePart;
const lastPart = `${slashCommand} ${lastTextPart?.text || ""}`;
if (parts.length > 0) {
lastTextPart.text = lastPart;
} else {
parts = [{ type: "text", text: lastPart }];
}
}
if (shouldGatherContext) {
dispatch(setIsGatheringContext(false));
}
return [contextItems, selectedCode, parts];
return [contextItems, selectedCode, parts, slashCommandWithInput];
}
function findLastIndex<T>(
@ -236,30 +274,4 @@ function resolveParagraph(
return [text, contextItems, slashCommand];
}
export function hasSlashCommandOrContextProvider(
editorState: JSONContent,
): boolean {
if (!editorState?.content) {
return false;
}
for (const p of editorState.content) {
if (p.type === "paragraph" && p.content) {
for (const child of p.content) {
if (child.type === "slashcommand") {
return true;
}
if (
child.type === "mention" &&
child.attrs?.itemType === "contextProvider"
) {
return true;
}
}
}
}
return false;
}
export default resolveEditorContent;

View file

@ -1,12 +1,13 @@
import {
ArrowTopRightOnSquareIcon,
BuildingOfficeIcon,
CheckIcon,
ChevronDownIcon,
Cog6ToothIcon,
ExclamationTriangleIcon,
PlusIcon,
} from "@heroicons/react/24/outline";
import { useContext, useEffect, useMemo, useRef, useState } from "react";
import { useContext, useEffect, useMemo, useRef } from "react";
import { useAuth } from "../../../context/Auth";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
import { cycleProfile, selectProfileThunk } from "../../../redux";
@ -35,14 +36,16 @@ import AssistantIcon from "./AssistantIcon";
interface AssistantSelectOptionProps {
profile: ProfileDescription;
selected: boolean;
onClick: () => void;
}
const AssistantSelectOption = ({
profile,
selected,
onClick,
}: AssistantSelectOptionProps) => {
const navigate = useNavigate();
const [hovered, setHovered] = useState(false);
const hasFatalErrors = useMemo(() => {
return !!profile.errors?.find((error) => error.fatal);
@ -72,8 +75,6 @@ const AssistantSelectOption = ({
return (
<ListboxOption
onMouseEnter={() => setHovered(true)}
onMouseLeave={() => setHovered(false)}
value={profile.id}
disabled={hasFatalErrors}
onClick={!hasFatalErrors ? handleOptionClick : undefined}
@ -81,20 +82,22 @@ const AssistantSelectOption = ({
>
<div className="flex w-full flex-col gap-0.5">
<div className="flex w-full items-center justify-between">
<div className="flex w-full items-center">
<div className="flex w-full items-center gap-2">
<div className="mr-2 h-4 w-4 flex-shrink-0">
<AssistantIcon assistant={profile} />
</div>
<span className="line-clamp-1 flex-1">{profile.title}</span>
<span
className={`line-clamp-1 flex-1 ${selected ? "font-bold" : ""}`}
>
{profile.title}
</span>
</div>
<div className="ml-2 flex items-center">
<div className="flex flex-row items-center gap-2">
<div>{selected ? <CheckIcon className="h-3 w-3" /> : null}</div>
{!profile.errors?.length ? (
isLocalProfile(profile) ? (
<Cog6ToothIcon
className="h-3 w-3 flex-shrink-0 cursor-pointer"
style={{
opacity: hovered ? 1 : 0,
}}
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
@ -103,9 +106,6 @@ const AssistantSelectOption = ({
/>
) : (
<ArrowTopRightOnSquareIcon
style={{
opacity: hovered ? 1 : 0,
}}
className="h-3 w-3 flex-shrink-0 cursor-pointer"
onClick={(e) => {
e.stopPropagation();
@ -215,7 +215,7 @@ export default function AssistantSelect() {
return (
<Listbox>
<div className="sm:max-w-4/5 relative flex">
<div className="relative">
<ListboxButton
data-testid="assistant-select-button"
ref={buttonRef}
@ -249,6 +249,7 @@ export default function AssistantSelect() {
key={idx}
profile={profile}
onClick={close}
selected={profile.id === selectedProfile.id}
/>
);
})}

View file

@ -46,7 +46,7 @@ const ListboxOptions = React.forwardRef<HTMLUListElement, ListboxOptionsProps>(
anchor={"bottom start"}
{...props}
className={cn(
"bg-vsc-input-background flex flex-col overflow-auto px-0 shadow-md",
"bg-vsc-input-background flex w-max min-w-[160px] max-w-[400px] flex-col overflow-auto px-0 shadow-md",
props.className,
)}
style={{

View file

@ -101,55 +101,69 @@ export function UserSettingsForm() {
}, [ideMessenger]);
return (
<div className="divide-x-0 divide-y-2 divide-solid divide-zinc-700">
<div className="flex flex-col pt-3">
{/* {selectedProfile && isLocalProfile(selectedProfile) ? (
<div className="flex items-center justify-center">
<SecondaryButton
className="flex flex-row items-center gap-1"
onClick={() => {
ideMessenger.post("config/openProfile", {
profileId: selectedProfile.id,
});
}}
>
<span>Open</span>
<span>Config</span>
<span className="xs:flex hidden">File</span>
</SecondaryButton>
</div>
) : null} */}
{!controlServerBetaEnabled || hubEnabled ? (
<div className="flex flex-col">
<div className="flex flex-col">
<div className="flex flex-col gap-4 py-6">
<div>
<h2 className="mb-2 mt-0">User settings</h2>
</div>
<div className="flex flex-col gap-4 py-4">
<div>
<h2 className="mb-2 mt-0 p-0">User settings</h2>
</div>
<div className="flex flex-col gap-4">
<ToggleSwitch
isToggled={showSessionTabs}
onToggle={() =>
handleUpdate({
showSessionTabs: !showSessionTabs,
})
}
text="Show Session Tabs"
/>
<ToggleSwitch
isToggled={codeWrap}
onToggle={() =>
handleUpdate({
codeWrap: !codeWrap,
})
}
text="Wrap Codeblocks"
/>
<div className="flex flex-col gap-4">
<ToggleSwitch
isToggled={showSessionTabs}
onToggle={() =>
handleUpdate({
showSessionTabs: !showSessionTabs,
})
}
text="Show Session Tabs"
/>
<ToggleSwitch
isToggled={codeWrap}
onToggle={() =>
handleUpdate({
codeWrap: !codeWrap,
})
}
text="Wrap Codeblocks"
/>
<ToggleSwitch
isToggled={showChatScrollbar}
onToggle={() =>
handleUpdate({
showChatScrollbar: !showChatScrollbar,
})
}
text="Show Chat Scrollbar"
/>
<ToggleSwitch
isToggled={readResponseTTS}
onToggle={() =>
handleUpdate({
readResponseTTS: !readResponseTTS,
})
}
text="Text-to-Speech Output"
/>
<ToggleSwitch
isToggled={showChatScrollbar}
onToggle={() =>
handleUpdate({
showChatScrollbar: !showChatScrollbar,
})
}
text="Show Chat Scrollbar"
/>
<ToggleSwitch
isToggled={readResponseTTS}
onToggle={() =>
handleUpdate({
readResponseTTS: !readResponseTTS,
})
}
text="Text-to-Speech Output"
/>
{/* <ToggleSwitch
{/* <ToggleSwitch
isToggled={useChromiumForDocsCrawling}
onToggle={() =>
handleUpdate({
@ -158,46 +172,46 @@ export function UserSettingsForm() {
}
text="Use Chromium for Docs Crawling"
/> */}
<ToggleSwitch
isToggled={!disableSessionTitles}
onToggle={() =>
handleUpdate({
disableSessionTitles: !disableSessionTitles,
})
}
text="Enable Session Titles"
/>
<ToggleSwitch
isToggled={!displayRawMarkdown}
onToggle={() =>
handleUpdate({
displayRawMarkdown: !displayRawMarkdown,
})
}
text="Format Markdown"
/>
<ToggleSwitch
isToggled={!disableSessionTitles}
onToggle={() =>
handleUpdate({
disableSessionTitles: !disableSessionTitles,
})
}
text="Enable Session Titles"
/>
<ToggleSwitch
isToggled={!displayRawMarkdown}
onToggle={() =>
handleUpdate({
displayRawMarkdown: !displayRawMarkdown,
})
}
text="Format Markdown"
/>
<ToggleSwitch
isToggled={allowAnonymousTelemetry}
onToggle={() =>
handleUpdate({
allowAnonymousTelemetry: !allowAnonymousTelemetry,
})
}
text="Allow Anonymous Telemetry"
/>
<ToggleSwitch
isToggled={allowAnonymousTelemetry}
onToggle={() =>
handleUpdate({
allowAnonymousTelemetry: !allowAnonymousTelemetry,
})
}
text="Allow Anonymous Telemetry"
/>
<ToggleSwitch
isToggled={!disableIndexing}
onToggle={() =>
handleUpdate({
disableIndexing: !disableIndexing,
})
}
text="Enable Indexing"
/>
<ToggleSwitch
isToggled={!disableIndexing}
onToggle={() =>
handleUpdate({
disableIndexing: !disableIndexing,
})
}
text="Enable Indexing"
/>
{/* <ToggleSwitch
{/* <ToggleSwitch
isToggled={useAutocompleteCache}
onToggle={() =>
handleUpdate({
@ -207,89 +221,86 @@ export function UserSettingsForm() {
text="Use Autocomplete Cache"
/> */}
<label className="flex items-center justify-between gap-3">
<span className="text-left">Font Size</span>
<NumberInput
value={fontSize}
onChange={(val) =>
handleUpdate({
fontSize: val,
})
}
min={7}
max={50}
<label className="flex items-center justify-between gap-3">
<span className="text-left">Font Size</span>
<NumberInput
value={fontSize}
onChange={(val) =>
handleUpdate({
fontSize: val,
})
}
min={7}
max={50}
/>
</label>
<label className="flex items-center justify-between gap-3">
<span className="line-clamp-1 text-left">
Multiline Autocompletions
</span>
<Select
value={useAutocompleteMultilineCompletions}
onChange={(e) =>
handleUpdate({
useAutocompleteMultilineCompletions: e.target.value as
| "auto"
| "always"
| "never",
})
}
>
<option value="auto">Auto</option>
<option value="always">Always</option>
<option value="never">Never</option>
</Select>
</label>
<form
className="flex flex-col gap-1"
onSubmit={(e) => {
e.preventDefault();
handleDisableAutocompleteSubmit();
}}
>
<div className="flex items-center justify-between">
<span>Disable autocomplete in files</span>
<div className="flex items-center gap-2">
<Input
value={formDisableAutocomplete}
className="max-w-[100px]"
onChange={(e) => {
setFormDisableAutocomplete(e.target.value);
}}
/>
</label>
<label className="flex items-center justify-between gap-3">
<span className="line-clamp-1 text-left">
Multiline Autocompletions
</span>
<Select
value={useAutocompleteMultilineCompletions}
onChange={(e) =>
handleUpdate({
useAutocompleteMultilineCompletions: e.target.value as
| "auto"
| "always"
| "never",
})
}
>
<option value="auto">Auto</option>
<option value="always">Always</option>
<option value="never">Never</option>
</Select>
</label>
<form
className="flex flex-col gap-1"
onSubmit={(e) => {
e.preventDefault();
handleDisableAutocompleteSubmit();
}}
>
<div className="flex items-center justify-between">
<span>Disable autocomplete in files</span>
<div className="flex items-center gap-2">
<Input
value={formDisableAutocomplete}
className="max-w-[100px]"
onChange={(e) => {
setFormDisableAutocomplete(e.target.value);
}}
/>
<div className="flex h-full flex-col">
{formDisableAutocomplete !==
disableAutocompleteInFiles ? (
<>
<div
onClick={handleDisableAutocompleteSubmit}
className="cursor-pointer"
>
<CheckIcon className="h-4 w-4 text-green-500 hover:opacity-80" />
</div>
<div
onClick={cancelChangeDisableAutocomplete}
className="cursor-pointer"
>
<XMarkIcon className="h-4 w-4 text-red-500 hover:opacity-80" />
</div>
</>
) : (
<div>
<CheckIcon className="text-vsc-foreground-muted h-4 w-4" />
</div>
)}
<div className="flex h-full flex-col">
{formDisableAutocomplete !== disableAutocompleteInFiles ? (
<>
<div
onClick={handleDisableAutocompleteSubmit}
className="cursor-pointer"
>
<CheckIcon className="h-4 w-4 text-green-500 hover:opacity-80" />
</div>
<div
onClick={cancelChangeDisableAutocomplete}
className="cursor-pointer"
>
<XMarkIcon className="h-4 w-4 text-red-500 hover:opacity-80" />
</div>
</>
) : (
<div>
<CheckIcon className="text-vsc-foreground-muted h-4 w-4" />
</div>
</div>
)}
</div>
<span className="text-vsc-foreground-muted text-lightgray self-end text-xs">
Comma-separated list of path matchers
</span>
</form>
</div>
</div>
</div>
<span className="text-vsc-foreground-muted text-lightgray self-end text-xs">
Comma-separated list of path matchers
</span>
</form>
</div>
</div>
) : null}

View file

@ -235,7 +235,8 @@ export function Chat() {
console.error("No selected chat model");
return;
}
const [contextItems, __, userInstructions] = await resolveEditorContent({
const [contextItems, __, userInstructions, _] = await resolveEditorContent({
editorState,
modifiers: {
noContext: true,
@ -243,6 +244,7 @@ export function Chat() {
},
ideMessenger,
defaultContextProviders: [],
availableSlashCommands: [],
dispatch,
selectedModelTitle: defaultModel.title,
});

View file

@ -54,7 +54,7 @@ export function ToolCallDisplay(props: ToolCallDisplayProps) {
Mustache.render(tool.isCurrently, props.toolCallState.parsedArgs)
) : (
<>
<span>using the</span> {defaultToolDescription}
<span>calling the</span> {defaultToolDescription}
</>
);
} else if (props.toolCallState.status === "done") {

View file

@ -3,8 +3,8 @@ import { Chat } from "./Chat";
export default function GUI() {
return (
<div className="flex w-screen flex-col overflow-hidden">
<aside className="4xl:block border-vsc-input-border no-scrollbar hidden w-96 overflow-y-auto border-0 border-r border-solid">
<div className="flex w-screen flex-row overflow-hidden">
<aside className="4xl:flex border-vsc-input-border no-scrollbar hidden w-96 overflow-y-auto border-0 border-r border-solid">
<History />
</aside>
<main className="no-scrollbar flex flex-1 flex-col overflow-y-auto">

View file

@ -8,7 +8,7 @@ export const selectSlashCommandComboBoxInputs = createSelector(
return (
slashCommands?.map((cmd) => {
return {
title: `${cmd.name}`,
title: cmd.name,
description: cmd.description,
type: "slashCommand" as ComboBoxItemType,
};

View file

@ -111,6 +111,12 @@ export const sessionSlice = createSlice({
lastMessage.promptLogs = lastMessage.promptLogs
? lastMessage.promptLogs.concat(payload)
: payload;
// Inactive thinking for reasoning models when '</think>' tag is not received on request completion
if (lastMessage.reasoning?.active) {
lastMessage.reasoning.active = false;
lastMessage.reasoning.endAt = Date.now();
}
},
setActive: (state) => {
state.isStreaming = true;

View file

@ -5,6 +5,7 @@ import {
InputModifiers,
MessageContent,
RangeInFile,
SlashCommandDescription,
} from "core";
import * as URI from "uri-js";
import resolveEditorContent from "../../components/mainInput/tiptap/resolveInput";
@ -16,6 +17,12 @@ export const gatherContext = createAsyncThunk<
selectedContextItems: ContextItemWithId[];
selectedCode: RangeInFile[];
content: MessageContent;
slashCommandWithInput:
| {
command: SlashCommandDescription;
input: string;
}
| undefined;
},
{
editorState: JSONContent;
@ -42,12 +49,13 @@ export const gatherContext = createAsyncThunk<
}
// Resolve context providers and construct new history
let [selectedContextItems, selectedCode, content] =
let [selectedContextItems, selectedCode, content, slashCommandWithInput] =
await resolveEditorContent({
editorState,
modifiers,
ideMessenger: extra.ideMessenger,
defaultContextProviders,
availableSlashCommands: state.config.config.slashCommands,
dispatch,
selectedModelTitle: defaultModel.title,
});
@ -107,7 +115,11 @@ export const gatherContext = createAsyncThunk<
}
}
// dispatch(addContextItems(contextItems));
return { selectedContextItems, selectedCode, content };
return {
selectedContextItems,
selectedCode,
content,
slashCommandWithInput,
};
},
);

View file

@ -9,7 +9,7 @@ import {
addPromptCompletionPair,
selectUseTools,
setToolGenerated,
streamUpdate,
streamUpdate
} from "../slices/sessionSlice";
import { ThunkApiType } from "../store";
import { callTool } from "./callTool";
@ -37,7 +37,6 @@ export const streamNormalInput = createAsyncThunk<
if (!defaultModel) {
throw new Error("Default model not defined");
}
const includeTools = useTools && modelSupportsTools(defaultModel);
// Send request
@ -71,12 +70,12 @@ export const streamNormalInput = createAsyncThunk<
next = await gen.next();
}
// Attach prompt log
// Attach prompt log and end thinking for reasoning models
if (next.done && next.value) {
dispatch(addPromptCompletionPair([next.value]));
try {
if (state.session.mode === "chat") {
if (state.session.mode === "chat" || state.session.mode === "agent") {
extra.ideMessenger.post("devdata/log", {
name: "chatInteraction",
data: {

View file

@ -1,13 +1,7 @@
import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
import { JSONContent } from "@tiptap/core";
import {
InputModifiers,
MessageContent,
SlashCommandDescription,
TextMessagePart,
} from "core";
import { InputModifiers } from "core";
import { constructMessages } from "core/llm/constructMessages";
import { renderChatMessage } from "core/util/messageContent";
import posthog from "posthog-js";
import { v4 as uuidv4 } from "uuid";
import { selectDefaultModel } from "../slices/configSlice";
@ -22,36 +16,6 @@ import { streamNormalInput } from "./streamNormalInput";
import { streamThunkWrapper } from "./streamThunkWrapper";
import { updateFileSymbolsFromFiles } from "./updateFileSymbols";
const getSlashCommandForInput = (
input: MessageContent,
slashCommands: SlashCommandDescription[],
): [SlashCommandDescription, string] | undefined => {
let slashCommand: SlashCommandDescription | undefined;
let slashCommandName: string | undefined;
let lastText =
typeof input === "string"
? input
: (
input.filter((part) => part.type === "text").slice(-1)[0] as
| TextMessagePart
| undefined
)?.text || "";
if (lastText.startsWith("/")) {
slashCommandName = lastText.split(" ")[0].substring(1);
slashCommand = slashCommands.find((command) =>
lastText.startsWith(`/${command.name} `),
);
}
if (!slashCommand || !slashCommandName) {
return undefined;
}
// Convert to actual slash command object with runnable function
return [slashCommand, renderChatMessage({ role: "user", content: input })];
};
export const streamResponseThunk = createAsyncThunk<
void,
{
@ -90,8 +54,12 @@ export const streamResponseThunk = createAsyncThunk<
promptPreamble,
}),
);
const unwrapped = unwrapResult(result);
const { selectedContextItems, selectedCode, content } = unwrapped;
const {
selectedContextItems,
selectedCode,
content,
slashCommandWithInput,
} = unwrapResult(result);
// symbols for both context items AND selected codeblocks
const filesForSymbols = [
@ -126,36 +94,29 @@ export const streamResponseThunk = createAsyncThunk<
});
posthog.capture("userInput", {});
// Determine if the input is a slash command
let commandAndInput = getSlashCommandForInput(content, slashCommands);
if (!commandAndInput) {
unwrapResult(await dispatch(streamNormalInput({ messages })));
} else {
const [slashCommand, commandInput] = commandAndInput;
if (slashCommandWithInput) {
posthog.capture("step run", {
step_name: slashCommand.name,
step_name: slashCommandWithInput.command.name,
params: {},
});
// TODO - handle non-legacy slash commands, update messages if relevant
// Pass around isFromConfigTs
unwrapResult(
await dispatch(
streamNormalInput({
messages,
legacySlashCommandData: {
command: slashCommand,
contextItems: selectedContextItems,
historyIndex: inputIndex,
input: commandInput,
selectedCode,
},
}),
),
);
}
unwrapResult(
await dispatch(
streamNormalInput({
messages,
legacySlashCommandData: slashCommandWithInput
? {
command: slashCommandWithInput.command,
contextItems: selectedContextItems,
historyIndex: inputIndex,
input: slashCommandWithInput.input,
selectedCode,
}
: undefined,
}),
),
);
}),
);
},