merge main
This commit is contained in:
commit
b8b893d3d0
77 changed files with 1819 additions and 768 deletions
15
.continue/rules/intellij-plugin-test-execution.yaml
Normal file
15
.continue/rules/intellij-plugin-test-execution.yaml
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
name: IntelliJ Plugin Test Execution
|
||||
version: 0.0.1
|
||||
schema: v1
|
||||
rules:
|
||||
- name: IntelliJ Plugin Test Execution
|
||||
rule: |-
|
||||
Run IntelliJ plugin tests using Gradle with the fully qualified test class or method name:
|
||||
```bash
|
||||
# Run test class
|
||||
./gradlew test --tests "com.github.continuedev.continueintellijextension.unit.ApplyToFileHandlerTest"
|
||||
|
||||
# Run specific test method
|
||||
./gradlew test --tests "com.github.continuedev.continueintellijextension.unit.ApplyToFileHandlerTest.should*"
|
||||
```
|
||||
globs: extensions/intellij/**/*Test.kt
|
||||
10
.continue/rules/intellij-test-standards.yaml
Normal file
10
.continue/rules/intellij-test-standards.yaml
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
name: IntelliJ Test Standards
|
||||
version: 0.0.1
|
||||
schema: v1
|
||||
rules:
|
||||
- name: IntelliJ Test Standards
|
||||
rule: When writing tests for the IntelliJ plugin, use the mockk library for
|
||||
mocking. Prefer mockk's idiomatic syntax for creating and verifying mocks.
|
||||
Always structure tests with clear Arrange-Act-Assert patterns and use
|
||||
descriptive test names that indicate the scenario being tested.
|
||||
globs: "**/test/**/*.kt"
|
||||
30
.continue/rules/unit-testing-rules.yaml
Normal file
30
.continue/rules/unit-testing-rules.yaml
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
name: unit-testing-rules
|
||||
version: 0.0.1
|
||||
schema: v1
|
||||
rules:
|
||||
- name: unit-testing-rules
|
||||
rule: >-
|
||||
For unit testing in this project:
|
||||
|
||||
|
||||
1. The project uses Jest as the testing framework
|
||||
|
||||
2. Run tests using `npm test` from within the specific package/module
|
||||
directory
|
||||
|
||||
3. Command structure: `cd [directory] && npm test -- [test file path]`
|
||||
|
||||
4. The test script uses experimental VM modules via NODE_OPTIONS flag
|
||||
|
||||
5. Test files follow the pattern `*.test.ts`
|
||||
|
||||
6. Tests must import Jest with `import { jest } from "@jest/globals";`
|
||||
|
||||
7. Run tests from within the specific package directory (e.g., `cd core`
|
||||
for core module tests)
|
||||
|
||||
8. Write tests as top-level `test()` functions - DO NOT use `describe()`
|
||||
blocks
|
||||
|
||||
9. Include the function name being tested in the test description for
|
||||
clarity
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
|
|
@ -162,5 +162,8 @@ extensions/.continue-debug/
|
|||
|
||||
*.vsix
|
||||
|
||||
# intellij module library files
|
||||
*.iml
|
||||
|
||||
.continuerules
|
||||
**/.continue/assistants/
|
||||
6
.idea/jsLinters/eslint.xml
generated
Normal file
6
.idea/jsLinters/eslint.xml
generated
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="EslintConfiguration">
|
||||
<option name="fix-on-save" value="true" />
|
||||
</component>
|
||||
</project>
|
||||
1
.idea/prettier.xml
generated
1
.idea/prettier.xml
generated
|
|
@ -2,5 +2,6 @@
|
|||
<project version="4">
|
||||
<component name="PrettierConfiguration">
|
||||
<option name="myConfigurationMode" value="AUTOMATIC" />
|
||||
<option name="myRunOnSave" value="true" />
|
||||
</component>
|
||||
</project>
|
||||
|
|
@ -64,7 +64,7 @@ async function buildWithEsbuild() {
|
|||
format: "cjs",
|
||||
platform: "node",
|
||||
sourcemap: true,
|
||||
minify: true,
|
||||
minify: !esbuildOnly,
|
||||
treeShaking: true,
|
||||
loader: {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
|
|
|
|||
20
binary/package-lock.json
generated
20
binary/package-lock.json
generated
|
|
@ -33,6 +33,7 @@
|
|||
"@types/jest": "^29.5.12",
|
||||
"@types/uuid": "^9.0.8",
|
||||
"@vercel/ncc": "^0.38.1",
|
||||
"cross-env": "^7.0.3",
|
||||
"esbuild": "0.19.11",
|
||||
"jest": "^29.7.0",
|
||||
"pkg": "^5.8.1",
|
||||
|
|
@ -3196,6 +3197,25 @@
|
|||
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/cross-env": {
|
||||
"version": "7.0.3",
|
||||
"resolved": "https://registry.npmjs.org/cross-env/-/cross-env-7.0.3.tgz",
|
||||
"integrity": "sha512-+/HKd6EgcQCJGh2PSjZuUitQBQynKor4wrFbRg4DtAgS1aWO+gU52xpH7M9ScGgXSYmAVS9bIJ8EzuaGw0oNAw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"cross-spawn": "^7.0.1"
|
||||
},
|
||||
"bin": {
|
||||
"cross-env": "src/bin/cross-env.js",
|
||||
"cross-env-shell": "src/bin/cross-env-shell.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10.14",
|
||||
"npm": ">=6",
|
||||
"yarn": ">=1"
|
||||
}
|
||||
},
|
||||
"node_modules/cross-spawn": {
|
||||
"version": "7.0.6",
|
||||
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
|
||||
|
|
|
|||
|
|
@ -33,6 +33,7 @@
|
|||
"@types/jest": "^29.5.12",
|
||||
"@types/uuid": "^9.0.8",
|
||||
"@vercel/ncc": "^0.38.1",
|
||||
"cross-env": "^7.0.3",
|
||||
"esbuild": "0.19.11",
|
||||
"jest": "^29.7.0",
|
||||
"pkg": "^5.8.1",
|
||||
|
|
|
|||
|
|
@ -71,6 +71,21 @@ const qwenCoderFimTemplate: AutocompleteTemplate = {
|
|||
},
|
||||
};
|
||||
|
||||
const seedCoderFimTemplate: AutocompleteTemplate = {
|
||||
template: "<[fim-prefix]>{{{prefix}}}<[fim-suffix]>{{{suffix}}}<[fim-middle]>",
|
||||
completionOptions: {
|
||||
stop: [
|
||||
"<[end▁of▁sentence]>",
|
||||
"<[fim-prefix]>",
|
||||
"<[fim-middle]>",
|
||||
"<[fim-suffix]>",
|
||||
"<[PAD▁TOKEN]>",
|
||||
"<[SEP▁TOKEN]>",
|
||||
"<[begin▁of▁sentence]>",
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const codestralFimTemplate: AutocompleteTemplate = {
|
||||
template: "[SUFFIX]{{{suffix}}}[PREFIX]{{{prefix}}}",
|
||||
completionOptions: {
|
||||
|
|
@ -426,6 +441,10 @@ export function getTemplateForModel(model: string): AutocompleteTemplate {
|
|||
return qwenCoderFimTemplate;
|
||||
}
|
||||
|
||||
if (lowerCaseModel.includes("seed") && lowerCaseModel.includes("coder")) {
|
||||
return seedCoderFimTemplate;
|
||||
}
|
||||
|
||||
if (
|
||||
lowerCaseModel.includes("starcoder") ||
|
||||
lowerCaseModel.includes("star-coder") ||
|
||||
|
|
|
|||
51
core/index.d.ts
vendored
51
core/index.d.ts
vendored
|
|
@ -197,15 +197,14 @@ export interface CustomContextProvider {
|
|||
description?: string;
|
||||
renderInlineAs?: string;
|
||||
type?: ContextProviderType;
|
||||
loadSubmenuItems?: (
|
||||
args: LoadSubmenuItemsArgs,
|
||||
) => Promise<ContextSubmenuItem[]>;
|
||||
|
||||
getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]>;
|
||||
|
||||
loadSubmenuItems?: (
|
||||
args: LoadSubmenuItemsArgs,
|
||||
) => Promise<ContextSubmenuItem[]>;
|
||||
}
|
||||
|
||||
export interface ContextSubmenuItem {
|
||||
|
|
@ -459,6 +458,7 @@ export interface ChatHistoryItem {
|
|||
toolCallState?: ToolCallState;
|
||||
isGatheringContext?: boolean;
|
||||
reasoning?: Reasoning;
|
||||
appliedRules?: RuleWithSource[];
|
||||
}
|
||||
|
||||
export interface LLMFullCompletionOptions extends BaseCompletionOptions {
|
||||
|
|
@ -1167,6 +1167,7 @@ export interface MCPResource {
|
|||
description?: string;
|
||||
mimeType?: string;
|
||||
}
|
||||
|
||||
export interface MCPTool {
|
||||
name: string;
|
||||
description?: string;
|
||||
|
|
@ -1229,6 +1230,28 @@ export interface ApplyState {
|
|||
toolCallId?: string;
|
||||
}
|
||||
|
||||
export interface StreamDiffLinesPayload {
|
||||
prefix: string;
|
||||
highlighted: string;
|
||||
suffix: string;
|
||||
input: string;
|
||||
language: string | undefined;
|
||||
modelTitle: string | undefined;
|
||||
includeRulesInSystemMessage: boolean;
|
||||
fileUri?: string;
|
||||
}
|
||||
|
||||
export interface HighlightedCodePayload {
|
||||
rangeInFileWithContents: RangeInFileWithContents;
|
||||
prompt?: string;
|
||||
shouldRun?: boolean;
|
||||
}
|
||||
|
||||
export interface AcceptOrRejectDiffPayload {
|
||||
filepath: string;
|
||||
streamId?: string;
|
||||
}
|
||||
|
||||
export interface RangeInFileWithContents {
|
||||
filepath: string;
|
||||
range: {
|
||||
|
|
@ -1238,7 +1261,7 @@ export interface RangeInFileWithContents {
|
|||
contents: string;
|
||||
}
|
||||
|
||||
export type CodeToEdit = RangeInFileWithContents | FileWithContents;
|
||||
export type SetCodeToEditPayload = RangeInFileWithContents | FileWithContents;
|
||||
|
||||
/**
|
||||
* Represents the configuration for a quick action in the Code Lens.
|
||||
|
|
@ -1497,17 +1520,19 @@ export interface TerminalOptions {
|
|||
waitForCompletion?: boolean;
|
||||
}
|
||||
|
||||
export type RuleSource =
|
||||
| "default-chat"
|
||||
| "default-agent"
|
||||
| "model-chat-options"
|
||||
| "model-agent-options"
|
||||
| "rules-block"
|
||||
| "json-systemMessage"
|
||||
| ".continuerules";
|
||||
|
||||
export interface RuleWithSource {
|
||||
name?: string;
|
||||
slug?: string;
|
||||
source:
|
||||
| "default-chat"
|
||||
| "default-agent"
|
||||
| "model-chat-options"
|
||||
| "model-agent-options"
|
||||
| "rules-block"
|
||||
| "json-systemMessage"
|
||||
| ".continuerules";
|
||||
source: RuleSource;
|
||||
globs?: string | string[];
|
||||
rule: string;
|
||||
description?: string;
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ import {
|
|||
getQueryForFile,
|
||||
} from "../util/treeSitter";
|
||||
|
||||
import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex";
|
||||
import { DatabaseConnection, SqliteDb } from "./refreshIndex";
|
||||
import {
|
||||
IndexResultType,
|
||||
MarkCompleteCallback,
|
||||
|
|
@ -29,6 +29,7 @@ import {
|
|||
getLastNUriRelativePathParts,
|
||||
getUriPathBasename,
|
||||
} from "../util/uri";
|
||||
import { tagToString } from "./utils";
|
||||
|
||||
type SnippetChunk = ChunkWithoutID & { title: string; signature: string };
|
||||
|
||||
|
|
|
|||
|
|
@ -3,13 +3,14 @@ import { RETRIEVAL_PARAMS } from "../util/parameters";
|
|||
import { getUriPathBasename } from "../util/uri";
|
||||
|
||||
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex";
|
||||
import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex";
|
||||
import { DatabaseConnection, SqliteDb } from "./refreshIndex";
|
||||
import {
|
||||
IndexResultType,
|
||||
MarkCompleteCallback,
|
||||
RefreshIndexResults,
|
||||
type CodebaseIndex,
|
||||
} from "./types";
|
||||
import { tagToString } from "./utils";
|
||||
|
||||
export interface RetrieveConfig {
|
||||
tags: BranchAndDir[];
|
||||
|
|
@ -97,11 +98,14 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex {
|
|||
|
||||
// Delete
|
||||
for (const item of results.del) {
|
||||
await db.run(`
|
||||
await db.run(
|
||||
`
|
||||
DELETE FROM fts WHERE rowid IN (
|
||||
SELECT id FROM fts_metadata WHERE path = ? AND cacheKey = ?
|
||||
)
|
||||
`,[item.path, item.cacheKey]);
|
||||
`,
|
||||
[item.path, item.cacheKey],
|
||||
);
|
||||
await db.run("DELETE FROM fts_metadata WHERE path = ? AND cacheKey = ?", [
|
||||
item.path,
|
||||
item.cacheKey,
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ import { getUriPathBasename } from "../util/uri";
|
|||
|
||||
import { basicChunker } from "./chunk/basic.js";
|
||||
import { chunkDocument, shouldChunk } from "./chunk/chunk.js";
|
||||
import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex.js";
|
||||
import { DatabaseConnection, SqliteDb } from "./refreshIndex.js";
|
||||
import {
|
||||
CodebaseIndex,
|
||||
IndexResultType,
|
||||
|
|
@ -24,6 +24,7 @@ import {
|
|||
} from "./types";
|
||||
|
||||
import type * as LanceType from "vectordb";
|
||||
import { tagToString } from "./utils";
|
||||
|
||||
interface LanceDbRow {
|
||||
uuid: string;
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import { RunResult } from "sqlite3";
|
|||
|
||||
import { IContinueServerClient } from "../../continueServer/interface.js";
|
||||
import { Chunk, IndexTag, IndexingProgressUpdate } from "../../index.js";
|
||||
import { DatabaseConnection, SqliteDb, tagToString } from "../refreshIndex.js";
|
||||
import { DatabaseConnection, SqliteDb } from "../refreshIndex.js";
|
||||
import {
|
||||
IndexResultType,
|
||||
MarkCompleteCallback,
|
||||
|
|
@ -13,8 +13,9 @@ import {
|
|||
type CodebaseIndex,
|
||||
} from "../types.js";
|
||||
|
||||
import { chunkDocument, shouldChunk } from "./chunk.js";
|
||||
import { getUriPathBasename } from "../../util/uri.js";
|
||||
import { tagToString } from "../utils.js";
|
||||
import { chunkDocument, shouldChunk } from "./chunk.js";
|
||||
|
||||
export class ChunkCodebaseIndex implements CodebaseIndex {
|
||||
relativeExpectedTime: number = 1;
|
||||
|
|
|
|||
|
|
@ -18,10 +18,6 @@ import {
|
|||
|
||||
export type DatabaseConnection = Database<sqlite3.Database>;
|
||||
|
||||
export function tagToString(tag: IndexTag): string {
|
||||
return `${tag.directory}::${tag.branch}::${tag.artifactId}`;
|
||||
}
|
||||
|
||||
export class SqliteDb {
|
||||
static db: DatabaseConnection | null = null;
|
||||
|
||||
|
|
|
|||
|
|
@ -3,11 +3,11 @@ import { jest } from "@jest/globals";
|
|||
import { IndexTag } from "../..";
|
||||
import { IContinueServerClient } from "../../continueServer/interface";
|
||||
import { ChunkCodebaseIndex } from "../chunk/ChunkCodebaseIndex";
|
||||
import { tagToString } from "../refreshIndex";
|
||||
import { CodebaseIndex, RefreshIndexResults } from "../types";
|
||||
|
||||
import { testIde } from "../../test/fixtures";
|
||||
import { addToTestDir, TEST_DIR } from "../../test/testDir";
|
||||
import { tagToString } from "../utils";
|
||||
|
||||
export const mockFilename = "test.py";
|
||||
export const mockPathAndCacheKey = {
|
||||
|
|
|
|||
58
core/indexing/utils.test.ts
Normal file
58
core/indexing/utils.test.ts
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
import { IndexTag } from "..";
|
||||
import { tagToString } from "./utils";
|
||||
|
||||
test("tagToString returns full tag string when under length limit", () => {
|
||||
const tag: IndexTag = {
|
||||
directory: "/normal/path/to/repo",
|
||||
branch: "main",
|
||||
artifactId: "12345",
|
||||
};
|
||||
|
||||
expect(tagToString(tag)).toBe("/normal/path/to/repo::main::12345");
|
||||
});
|
||||
|
||||
test("tagToString truncates beginning of directory when path is too long", () => {
|
||||
// Create a very long directory path that exceeds MAX_DIR_LENGTH (200)
|
||||
const longPrefix = "/very/long/path/that/will/be/truncated/";
|
||||
const importantSuffix = "/user/important-project/src/feature";
|
||||
const longPath = longPrefix + "x".repeat(200) + importantSuffix;
|
||||
|
||||
const tag: IndexTag = {
|
||||
directory: longPath,
|
||||
branch: "feature-branch",
|
||||
artifactId: "67890",
|
||||
};
|
||||
|
||||
const result = tagToString(tag);
|
||||
|
||||
// The result should keep the important suffix part
|
||||
expect(result).toContain(importantSuffix);
|
||||
// The result should NOT contain the beginning of the path
|
||||
expect(result).not.toContain(longPrefix);
|
||||
// The result should include the branch and artifactId
|
||||
expect(result).toContain("::feature-branch::67890");
|
||||
// The result should be within the MAX_TABLE_NAME_LENGTH limit (240)
|
||||
expect(result.length).toBeLessThanOrEqual(240);
|
||||
});
|
||||
|
||||
test("tagToString preserves branch and artifactId exactly, even when truncating", () => {
|
||||
const longPath = "/a".repeat(300); // Much longer than MAX_DIR_LENGTH
|
||||
const tag: IndexTag = {
|
||||
directory: longPath,
|
||||
branch: "release-v2.0",
|
||||
artifactId: "build-123",
|
||||
};
|
||||
|
||||
const result = tagToString(tag);
|
||||
|
||||
// Should contain the exact branch and artifactId
|
||||
expect(result).toContain("::release-v2.0::build-123");
|
||||
// Should contain the end of the path
|
||||
expect(result).toContain("/a/a/a");
|
||||
// Should not contain the full original path (it should be truncated)
|
||||
expect(result.length).toBeLessThan(
|
||||
longPath.length + "::release-v2.0::build-123".length,
|
||||
);
|
||||
// The result should be within the MAX_TABLE_NAME_LENGTH limit
|
||||
expect(result.length).toBeLessThanOrEqual(240);
|
||||
});
|
||||
45
core/indexing/utils.ts
Normal file
45
core/indexing/utils.ts
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
import { IndexTag } from "..";
|
||||
|
||||
// Maximum length for table names to stay under OS filename limits
|
||||
const MAX_TABLE_NAME_LENGTH = 240;
|
||||
|
||||
// Leave room for branch and artifactId
|
||||
const MAX_DIR_LENGTH = 200;
|
||||
|
||||
/**
|
||||
* Converts an IndexTag to a string representation, safely handling long paths.
|
||||
*
|
||||
* The string is used as a table name and identifier in various places, so it needs
|
||||
* to stay under OS filename length limits (typically 255 chars). This is especially
|
||||
* important for dev containers where the directory path can be very long due to
|
||||
* containing container configuration.
|
||||
*
|
||||
* The format is: "{directory}::{branch}::{artifactId}"
|
||||
*
|
||||
* To handle long paths:
|
||||
* 1. First tries the full string - most backwards compatible
|
||||
* 2. If too long, truncates directory from the beginning to maintain uniqueness
|
||||
* (since final parts of paths are more unique than prefixes)
|
||||
* 3. Finally ensures entire string stays under MAX_TABLE_NAME_LENGTH for OS compatibility
|
||||
*
|
||||
* @param tag The tag containing directory, branch, and artifactId
|
||||
* @returns A string representation safe for use as a table name
|
||||
*/
|
||||
export function tagToString(tag: IndexTag): string {
|
||||
const result = `${tag.directory}::${tag.branch}::${tag.artifactId}`;
|
||||
|
||||
if (result.length <= MAX_TABLE_NAME_LENGTH) {
|
||||
return result;
|
||||
}
|
||||
|
||||
// Truncate from the beginning of directory path to preserve the more unique end parts
|
||||
const dir =
|
||||
tag.directory.length > MAX_DIR_LENGTH
|
||||
? tag.directory.slice(tag.directory.length - MAX_DIR_LENGTH)
|
||||
: tag.directory;
|
||||
|
||||
return `${dir}::${tag.branch}::${tag.artifactId}`.slice(
|
||||
0,
|
||||
MAX_TABLE_NAME_LENGTH,
|
||||
);
|
||||
}
|
||||
|
|
@ -230,6 +230,7 @@ describe("LLM", () => {
|
|||
testFim: true,
|
||||
skip: false,
|
||||
testToolCall: true,
|
||||
timeout: 60000,
|
||||
},
|
||||
);
|
||||
testLLM(
|
||||
|
|
|
|||
|
|
@ -23,6 +23,29 @@ const matchesGlobs = (
|
|||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
* Filters rules that apply to the given message
|
||||
*/
|
||||
export const getApplicableRules = (
|
||||
userMessage: UserChatMessage | ToolResultChatMessage | undefined,
|
||||
rules: RuleWithSource[],
|
||||
): RuleWithSource[] => {
|
||||
const filePathsFromMessage = userMessage
|
||||
? extractPathsFromCodeBlocks(renderChatMessage(userMessage))
|
||||
: [];
|
||||
|
||||
return rules.filter((rule) => {
|
||||
// A rule is active if it has no globs (applies to all files)
|
||||
// or if at least one file path matches its globs
|
||||
const hasNoGlobs = !rule.globs;
|
||||
const matchesAnyFilePath = filePathsFromMessage.some((path) =>
|
||||
matchesGlobs(path, rule.globs),
|
||||
);
|
||||
|
||||
return hasNoGlobs || matchesAnyFilePath;
|
||||
});
|
||||
};
|
||||
|
||||
export const getSystemMessageWithRules = ({
|
||||
baseSystemMessage,
|
||||
userMessage,
|
||||
|
|
@ -32,23 +55,11 @@ export const getSystemMessageWithRules = ({
|
|||
userMessage: UserChatMessage | ToolResultChatMessage | undefined;
|
||||
rules: RuleWithSource[];
|
||||
}) => {
|
||||
const filePathsFromMessage = userMessage
|
||||
? extractPathsFromCodeBlocks(renderChatMessage(userMessage))
|
||||
: [];
|
||||
|
||||
const applicableRules = getApplicableRules(userMessage, rules);
|
||||
let systemMessage = baseSystemMessage ?? "";
|
||||
|
||||
for (const rule of rules) {
|
||||
// A rule is active if it has no globs (applies to all files)
|
||||
// or if at least one file path matches its globs
|
||||
const hasNoGlobs = !rule.globs;
|
||||
const matchesAnyFilePath = filePathsFromMessage.some((path) =>
|
||||
matchesGlobs(path, rule.globs),
|
||||
);
|
||||
|
||||
if (hasNoGlobs || matchesAnyFilePath) {
|
||||
systemMessage += `\n\n${rule.rule}`;
|
||||
}
|
||||
for (const rule of applicableRules) {
|
||||
systemMessage += `\n\n${rule.rule}`;
|
||||
}
|
||||
|
||||
return systemMessage;
|
||||
|
|
|
|||
|
|
@ -64,6 +64,8 @@ export const gptEditPrompt: PromptTemplateFunction = (history, otherData) => {
|
|||
\`\`\`
|
||||
|
||||
The user's request is: "${otherData.userInput}"
|
||||
|
||||
DO NOT output any natural language, only output the code changes.
|
||||
|
||||
Here is the rewritten code:`);
|
||||
|
||||
|
|
|
|||
6
core/package-lock.json
generated
6
core/package-lock.json
generated
|
|
@ -15266,9 +15266,9 @@
|
|||
}
|
||||
},
|
||||
"node_modules/undici": {
|
||||
"version": "6.21.1",
|
||||
"resolved": "https://registry.npmjs.org/undici/-/undici-6.21.1.tgz",
|
||||
"integrity": "sha512-q/1rj5D0/zayJB2FraXdaWxbhWiNKDvu8naDT2dl1yTlvJp4BLtOcp2a5BvgGNQpYYJzau7tf1WgKv3b+7mqpQ==",
|
||||
"version": "6.21.3",
|
||||
"resolved": "https://registry.npmjs.org/undici/-/undici-6.21.3.tgz",
|
||||
"integrity": "sha512-gBLkYIlEnSp8pFbT64yFgGE6UIB9tAkhukC23PmMDCe5Nd+cRqKxSjw5y54MK2AZMgZfJWMaNE4nYUHgi1XEOw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18.17"
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ import { AutocompleteInput } from "../autocomplete/util/types";
|
|||
import { SharedConfigSchema } from "../config/sharedConfig";
|
||||
import { GlobalContextModelSelections } from "../util/GlobalContext";
|
||||
|
||||
import type {
|
||||
import {
|
||||
BrowserSerializedContinueConfig,
|
||||
ChatMessage,
|
||||
ContextItem,
|
||||
|
|
@ -29,6 +29,7 @@ import type {
|
|||
SessionMetadata,
|
||||
SiteIndexingConfig,
|
||||
SlashCommandDescription,
|
||||
StreamDiffLinesPayload,
|
||||
ToolCall,
|
||||
} from "../";
|
||||
import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager";
|
||||
|
|
@ -143,19 +144,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
},
|
||||
AsyncGenerator<ChatMessage, PromptLog>,
|
||||
];
|
||||
streamDiffLines: [
|
||||
{
|
||||
prefix: string;
|
||||
highlighted: string;
|
||||
suffix: string;
|
||||
input: string;
|
||||
language: string | undefined;
|
||||
modelTitle: string | undefined;
|
||||
includeRulesInSystemMessage: boolean;
|
||||
fileUri?: string;
|
||||
},
|
||||
AsyncGenerator<DiffLine>,
|
||||
];
|
||||
streamDiffLines: [StreamDiffLinesPayload, AsyncGenerator<DiffLine>];
|
||||
"chatDescriber/describe": [
|
||||
{
|
||||
text: string;
|
||||
|
|
|
|||
|
|
@ -1,11 +1,13 @@
|
|||
import { ToIdeFromWebviewOrCoreProtocol } from "./ide";
|
||||
import { ToWebviewFromIdeOrCoreProtocol } from "./webview";
|
||||
|
||||
import type {
|
||||
import {
|
||||
ApplyState,
|
||||
CodeToEdit,
|
||||
SetCodeToEditPayload,
|
||||
HighlightedCodePayload,
|
||||
MessageContent,
|
||||
RangeInFileWithContents,
|
||||
AcceptOrRejectDiffPayload,
|
||||
} from "../";
|
||||
|
||||
export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
|
||||
|
|
@ -42,8 +44,8 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
|
|||
"jetbrains/getColors": [undefined, Record<string, string>];
|
||||
"vscode/openMoveRightMarkdown": [undefined, void];
|
||||
setGitHubAuthToken: [{ token: string }, void];
|
||||
acceptDiff: [{ filepath: string; streamId?: string }, void];
|
||||
rejectDiff: [{ filepath: string; streamId?: string }, void];
|
||||
acceptDiff: [AcceptOrRejectDiffPayload, void];
|
||||
rejectDiff: [AcceptOrRejectDiffPayload, void];
|
||||
"edit/sendPrompt": [
|
||||
{
|
||||
prompt: MessageContent;
|
||||
|
|
@ -63,15 +65,8 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
|
|||
focusContinueInput: [undefined, void];
|
||||
focusContinueInputWithoutClear: [undefined, void];
|
||||
focusContinueInputWithNewSession: [undefined, void];
|
||||
highlightedCode: [
|
||||
{
|
||||
rangeInFileWithContents: RangeInFileWithContents;
|
||||
prompt?: string;
|
||||
shouldRun?: boolean;
|
||||
},
|
||||
void,
|
||||
];
|
||||
setCodeToEdit: [CodeToEdit, void];
|
||||
highlightedCode: [HighlightedCodePayload, void];
|
||||
setCodeToEdit: [SetCodeToEditPayload, void];
|
||||
navigateTo: [{ path: string; toggle?: boolean }, void];
|
||||
addModel: [undefined, void];
|
||||
|
||||
|
|
|
|||
|
|
@ -29,11 +29,12 @@ async function callHttpTool(
|
|||
}),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to call tool: ${url}`);
|
||||
throw new Error(`Failed to call tool at ${url}:\n${JSON.stringify(data)}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
return data.output;
|
||||
}
|
||||
|
||||
|
|
@ -84,7 +85,7 @@ async function callToolFromUri(
|
|||
});
|
||||
|
||||
if (response.isError === true) {
|
||||
throw new Error(`Failed to call tool: ${toolName}`);
|
||||
throw new Error(JSON.stringify(response.content));
|
||||
}
|
||||
|
||||
const contextItems: ContextItem[] = [];
|
||||
|
|
@ -130,6 +131,37 @@ async function callToolFromUri(
|
|||
}
|
||||
}
|
||||
|
||||
async function callBuiltInTool(
|
||||
functionName: string,
|
||||
args: any,
|
||||
extras: ToolExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
switch (functionName) {
|
||||
case BuiltInToolNames.ReadFile:
|
||||
return await readFileImpl(args, extras);
|
||||
case BuiltInToolNames.CreateNewFile:
|
||||
return await createNewFileImpl(args, extras);
|
||||
case BuiltInToolNames.GrepSearch:
|
||||
return await grepSearchImpl(args, extras);
|
||||
case BuiltInToolNames.FileGlobSearch:
|
||||
return await fileGlobSearchImpl(args, extras);
|
||||
case BuiltInToolNames.RunTerminalCommand:
|
||||
return await runTerminalCommandImpl(args, extras);
|
||||
case BuiltInToolNames.SearchWeb:
|
||||
return await searchWebImpl(args, extras);
|
||||
case BuiltInToolNames.ViewDiff:
|
||||
return await viewDiffImpl(args, extras);
|
||||
case BuiltInToolNames.LSTool:
|
||||
return await lsToolImpl(args, extras);
|
||||
case BuiltInToolNames.ReadCurrentlyOpenFile:
|
||||
return await readCurrentlyOpenFileImpl(args, extras);
|
||||
case BuiltInToolNames.CreateRuleBlock:
|
||||
return await createRuleBlockImpl(args, extras);
|
||||
default:
|
||||
throw new Error(`Tool "${functionName}" not found`);
|
||||
}
|
||||
}
|
||||
|
||||
// Handles calls for core/non-client tools
|
||||
// Returns an error context item if the tool call fails
|
||||
// Note: Edit tool is handled on client
|
||||
|
|
@ -141,44 +173,11 @@ export async function callTool(
|
|||
contextItems: ContextItem[];
|
||||
errorMessage: string | undefined;
|
||||
}> {
|
||||
const args = JSON.parse(callArgs || "{}");
|
||||
const uri = tool.uri ?? tool.function.name;
|
||||
try {
|
||||
let contextItems: ContextItem[] = [];
|
||||
switch (uri) {
|
||||
case BuiltInToolNames.ReadFile:
|
||||
contextItems = await readFileImpl(args, extras);
|
||||
break;
|
||||
case BuiltInToolNames.CreateNewFile:
|
||||
contextItems = await createNewFileImpl(args, extras);
|
||||
break;
|
||||
case BuiltInToolNames.GrepSearch:
|
||||
contextItems = await grepSearchImpl(args, extras);
|
||||
break;
|
||||
case BuiltInToolNames.FileGlobSearch:
|
||||
contextItems = await fileGlobSearchImpl(args, extras);
|
||||
break;
|
||||
case BuiltInToolNames.RunTerminalCommand:
|
||||
contextItems = await runTerminalCommandImpl(args, extras);
|
||||
break;
|
||||
case BuiltInToolNames.SearchWeb:
|
||||
contextItems = await searchWebImpl(args, extras);
|
||||
break;
|
||||
case BuiltInToolNames.ViewDiff:
|
||||
contextItems = await viewDiffImpl(args, extras);
|
||||
break;
|
||||
case BuiltInToolNames.LSTool:
|
||||
contextItems = await lsToolImpl(args, extras);
|
||||
break;
|
||||
case BuiltInToolNames.ReadCurrentlyOpenFile:
|
||||
contextItems = await readCurrentlyOpenFileImpl(args, extras);
|
||||
break;
|
||||
case BuiltInToolNames.CreateRuleBlock:
|
||||
contextItems = await createRuleBlockImpl(args, extras);
|
||||
break;
|
||||
default:
|
||||
contextItems = await callToolFromUri(uri, args, extras);
|
||||
}
|
||||
const args = JSON.parse(callArgs || "{}");
|
||||
const contextItems = tool.uri
|
||||
? await callToolFromUri(tool.uri, args, extras)
|
||||
: await callBuiltInTool(tool.function.name, args, extras);
|
||||
if (tool.faviconUrl) {
|
||||
contextItems.forEach((item) => {
|
||||
item.icon = tool.faviconUrl;
|
||||
|
|
|
|||
|
|
@ -17,6 +17,13 @@ past and future “Contributions” submitted to **Continue (the “Project”)*
|
|||
|
||||
## 2. Copyright License
|
||||
|
||||
You grant **Continue Dev, Inc.** and all recipients of software distributed by the
|
||||
Project a perpetual, worldwide, non‑exclusive, royalty‑free, irrevocable
|
||||
license to reproduce, prepare derivative works of, publicly display, publicly
|
||||
perform, sublicense, and distribute Your Contributions and derivative works.
|
||||
|
||||
## 3. Patent License
|
||||
|
||||
You grant **Continue Dev, Inc.** and all recipients of the Project a perpetual,
|
||||
worldwide, non‑exclusive, royalty‑free, irrevocable (except as below) patent
|
||||
license to make, have made, use, sell, offer to sell, import, and otherwise
|
||||
|
|
@ -38,4 +45,4 @@ entity under this CLA terminate.
|
|||
|
||||
This Agreement is governed by the laws of the **State of California**, USA,
|
||||
excluding its conflict‑of‑laws rules. If any provision is held unenforceable,
|
||||
the remaining provisions remain in force.
|
||||
the remaining provisions remain in force.
|
||||
|
|
|
|||
|
|
@ -7,8 +7,6 @@ keywords: [reload, delete, manually, logs, server, console]
|
|||
import TabItem from "@theme/TabItem";
|
||||
import Tabs from "@theme/Tabs";
|
||||
|
||||
The Continue VS Code extension is currently in beta, and the JetBrains extension is in Alpha. If you are having trouble, please follow the steps below.
|
||||
|
||||
1. [Check the logs](#check-the-logs)
|
||||
2. [Try the latest pre-release](#download-the-latest-pre-release)
|
||||
3. [Download an older version](#download-an-older-version)
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="Start Core Dev Server (CE)" type="ShConfigurationType">
|
||||
<option name="SCRIPT_TEXT" value="cross-env 'PROJECT_DIR="$PROJECT_DIR$"' node core-dev-server.js" />
|
||||
<option name="SCRIPT_TEXT" value="npx cross-env 'PROJECT_DIR="$PROJECT_DIR$"' node core-dev-server.js" />
|
||||
<option name="INDEPENDENT_SCRIPT_PATH" value="true" />
|
||||
<option name="SCRIPT_PATH" value="" />
|
||||
<option name="SCRIPT_OPTIONS" value="" />
|
||||
|
|
|
|||
|
|
@ -173,6 +173,12 @@ to run.
|
|||
./gradlew test
|
||||
```
|
||||
|
||||
Run a single test
|
||||
|
||||
```sh
|
||||
./gradlew test --tests "com.github.continuedev.continueintellijextension.e2e.TESTNAME"
|
||||
```
|
||||
|
||||
#### Identifying selectors
|
||||
|
||||
While the `runIdeForUiTests` task is running, you can visit the following URL
|
||||
|
|
|
|||
|
|
@ -42,10 +42,12 @@ dependencies {
|
|||
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.5.0")
|
||||
testImplementation("com.intellij.remoterobot:remote-robot:$remoteRobotVersion")
|
||||
testImplementation("com.intellij.remoterobot:remote-fixtures:$remoteRobotVersion")
|
||||
testImplementation("io.mockk:mockk:1.14.2")
|
||||
testImplementation("org.junit.jupiter:junit-jupiter-api:5.10.0")
|
||||
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.9.2")
|
||||
testImplementation("com.squareup.okhttp3:logging-interceptor:4.12.0")
|
||||
implementation("com.automation-remarks:video-recorder-junit5:2.0")
|
||||
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.3")
|
||||
|
||||
|
||||
// Exclude vulnerable Log4j from all dependencies
|
||||
|
|
@ -62,6 +64,7 @@ dependencies {
|
|||
// Add Log4j 2.x explicitly
|
||||
implementation("org.apache.logging.log4j:log4j-core:2.20.0")
|
||||
implementation("org.apache.logging.log4j:log4j-api:2.20.0")
|
||||
testImplementation(kotlin("test"))
|
||||
}
|
||||
|
||||
// Set the JVM language level used to build the project. Use Java 11 for 2020.3+, and Java 17 for
|
||||
|
|
@ -162,6 +165,7 @@ tasks {
|
|||
// This is to ensure we load the GUI with OSR enabled. We have logic that
|
||||
// renders with OSR disabled below a particular IDE version.
|
||||
// See ContinueExtensionSettingsService.kt for more info.
|
||||
// Currently commented out however since test fail in CI with this version
|
||||
// intellij {
|
||||
// version.set("2024.1")
|
||||
// }
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ pluginSinceBuild=223
|
|||
# IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension
|
||||
platformType=IC
|
||||
platformVersion=2022.3.3
|
||||
#org.gradle.java.home=/opt/homebrew/opt/openjdk@17
|
||||
# org.gradle.java.home=/opt/homebrew/opt/openjdk@17
|
||||
#platformVersion = LATEST-EAP-SNAPSHOT
|
||||
# Plugin Dependencies -> https://plugins.jetbrains.com/docs/intellij/plugin-dependencies.html
|
||||
# Example: platformPlugins = com.intellij.java, com.jetbrains.php:203.4449.22
|
||||
|
|
|
|||
|
|
@ -1,6 +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
|
||||
|
|
|
|||
|
|
@ -0,0 +1,187 @@
|
|||
package com.github.continuedev.continueintellijextension.`continue`
|
||||
|
||||
import com.github.continuedev.continueintellijextension.ApplyState
|
||||
import com.github.continuedev.continueintellijextension.ApplyStateStatus
|
||||
import com.github.continuedev.continueintellijextension.IDE
|
||||
import com.github.continuedev.continueintellijextension.ToastType
|
||||
import com.github.continuedev.continueintellijextension.editor.DiffStreamHandler
|
||||
import com.github.continuedev.continueintellijextension.editor.DiffStreamService
|
||||
import com.github.continuedev.continueintellijextension.editor.EditorUtils
|
||||
import com.github.continuedev.continueintellijextension.protocol.ApplyToFileParams
|
||||
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
|
||||
import com.github.continuedev.continueintellijextension.utils.castNestedOrNull
|
||||
import com.intellij.openapi.editor.Editor
|
||||
import com.intellij.openapi.project.Project
|
||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||
import kotlin.coroutines.resume
|
||||
import kotlin.coroutines.resumeWithException
|
||||
|
||||
/**
|
||||
* Handles applying text to a file with streaming diff preview
|
||||
*/
|
||||
class ApplyToFileHandler(
|
||||
private val project: Project,
|
||||
private val continuePluginService: ContinuePluginService,
|
||||
private val ide: IDE,
|
||||
private val params: ApplyToFileParams,
|
||||
private val editorUtils: EditorUtils?,
|
||||
private val diffStreamService: DiffStreamService
|
||||
) {
|
||||
|
||||
suspend fun handleApplyToFile() {
|
||||
// Notify webview that we're starting to stream
|
||||
notifyStreamStarted()
|
||||
|
||||
if (editorUtils == null) {
|
||||
ide.showToast(ToastType.ERROR, "No active editor to apply edits to")
|
||||
notifyStreamClosed()
|
||||
return
|
||||
}
|
||||
|
||||
if (editorUtils.isDocumentEmpty()) {
|
||||
editorUtils.insertTextIntoEmptyDocument(params.text)
|
||||
notifyStreamClosed()
|
||||
return
|
||||
}
|
||||
|
||||
// Get the LLM configuration for applying edits
|
||||
val llm = fetchApplyLLMConfig() ?: run {
|
||||
ide.showToast(ToastType.ERROR, "Failed to fetch model configuration")
|
||||
notifyStreamClosed()
|
||||
return
|
||||
}
|
||||
|
||||
setupAndStreamDiffs(editorUtils, llm)
|
||||
}
|
||||
|
||||
private fun notifyStreamStarted() {
|
||||
sendApplyStateUpdate(ApplyStateStatus.STREAMING)
|
||||
}
|
||||
|
||||
private fun notifyStreamClosed(numDiffs: Int? = 0) {
|
||||
sendApplyStateUpdate(ApplyStateStatus.CLOSED, numDiffs)
|
||||
}
|
||||
|
||||
private fun sendApplyStateUpdate(
|
||||
status: ApplyStateStatus,
|
||||
numDiffs: Int? = null
|
||||
) {
|
||||
val payload = ApplyState(
|
||||
streamId = params.streamId,
|
||||
status = status.status,
|
||||
numDiffs = numDiffs,
|
||||
filepath = params.filepath,
|
||||
fileContent = params.text,
|
||||
toolCallId = params.toolCallId.toString()
|
||||
)
|
||||
|
||||
continuePluginService.sendToWebview("updateApplyState", payload)
|
||||
}
|
||||
|
||||
private suspend fun fetchApplyLLMConfig(): Any? {
|
||||
return try {
|
||||
suspendCancellableCoroutine { continuation ->
|
||||
continuePluginService.coreMessenger?.request(
|
||||
"config/getSerializedProfileInfo",
|
||||
null,
|
||||
null
|
||||
) { response ->
|
||||
try {
|
||||
val selectedModels = response.castNestedOrNull<Map<String, Any>>(
|
||||
"content",
|
||||
"result",
|
||||
"config",
|
||||
"selectedModelByRole"
|
||||
)
|
||||
|
||||
// If "apply" role model is not found, try "chat" role
|
||||
val applyCodeBlockModel = selectedModels?.get("apply") ?: selectedModels?.get("chat")
|
||||
|
||||
if (applyCodeBlockModel != null) {
|
||||
continuation.resume(applyCodeBlockModel)
|
||||
} else {
|
||||
// If neither "apply" nor "chat" models are available, return with exception
|
||||
continuation.resumeWithException(IllegalStateException("No 'apply' or 'chat' model found in configuration."))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
continuation.resumeWithException(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private fun setupAndStreamDiffs(editorUtils: EditorUtils, llm: Any) {
|
||||
// Clear all diff blocks before running the diff stream
|
||||
diffStreamService.reject(editorUtils.editor)
|
||||
|
||||
val llmTitle = (llm as? Map<*, *>)?.get("title") as? String ?: ""
|
||||
val prompt = buildApplyPrompt()
|
||||
|
||||
// Extract the code ranges (highlighted or full document)
|
||||
val (prefix, highlighted, suffix) = editorUtils.extractCodeRanges()
|
||||
|
||||
// Get the line range for the diff stream
|
||||
val rif = editorUtils.getHighlightedCode()
|
||||
val startLine = rif?.range?.start?.line ?: 0
|
||||
val endLine = rif?.range?.end?.line ?: (editorUtils.getLineCount() - 1)
|
||||
|
||||
// Create and register the diff stream handler
|
||||
val diffStreamHandler = createDiffStreamHandler(editorUtils.editor, startLine, endLine)
|
||||
diffStreamService.register(diffStreamHandler, editorUtils.editor)
|
||||
|
||||
// Stream the diffs
|
||||
diffStreamHandler.streamDiffLinesToEditor(
|
||||
prompt, prefix, highlighted, suffix, llmTitle, false
|
||||
)
|
||||
}
|
||||
|
||||
private fun buildApplyPrompt(): String {
|
||||
return "The following code was suggested as an edit:\n```\n${params.text}\n```\nPlease apply it to the previous code."
|
||||
}
|
||||
|
||||
private fun createDiffStreamHandler(
|
||||
editor: Editor,
|
||||
startLine: Int,
|
||||
endLine: Int
|
||||
): DiffStreamHandler {
|
||||
return DiffStreamHandler(
|
||||
project,
|
||||
editor,
|
||||
startLine,
|
||||
endLine,
|
||||
{},
|
||||
{},
|
||||
params.streamId,
|
||||
params.toolCallId.toString()
|
||||
)
|
||||
}
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* Factory method to create and execute a new handler for a single apply-to-file operation
|
||||
*/
|
||||
suspend fun apply(
|
||||
project: Project,
|
||||
continuePluginService: ContinuePluginService,
|
||||
ide: IDE,
|
||||
params: ApplyToFileParams
|
||||
) {
|
||||
val editorUtils = EditorUtils.getOrOpenEditor(project, params.filepath)
|
||||
val diffStreamService = project.getService(DiffStreamService::class.java)
|
||||
|
||||
val handler = ApplyToFileHandler(
|
||||
project,
|
||||
continuePluginService,
|
||||
ide,
|
||||
params,
|
||||
editorUtils,
|
||||
diffStreamService
|
||||
)
|
||||
|
||||
handler.handleApplyToFile()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -62,7 +62,7 @@ class DiffManager(private val project: Project) : DumbAware {
|
|||
file.createNewFile()
|
||||
}
|
||||
file.writeText(replacement)
|
||||
openDiffWindow(URI(filepath).toString(), file.toURI().toString(), stepIndex)
|
||||
openDiffWindow(UriUtils.parseUri(filepath).toString(), file.toURI().toString(), stepIndex)
|
||||
}
|
||||
|
||||
private fun cleanUpFile(file2: String) {
|
||||
|
|
@ -80,7 +80,8 @@ class DiffManager(private val project: Project) : DumbAware {
|
|||
val diffInfo = diffInfoMap[file] ?: return
|
||||
|
||||
// Write contents to original file
|
||||
val virtualFile = LocalFileSystem.getInstance().findFileByPath(URI(diffInfo.originalFilepath).path) ?: return
|
||||
val virtualFile =
|
||||
LocalFileSystem.getInstance().findFileByPath(UriUtils.parseUri(diffInfo.originalFilepath).path) ?: return
|
||||
val document = FileDocumentManager.getInstance().getDocument(virtualFile) ?: return
|
||||
WriteCommandAction.runWriteCommandAction(project) {
|
||||
document.setText(File(file).readText())
|
||||
|
|
@ -119,8 +120,8 @@ class DiffManager(private val project: Project) : DumbAware {
|
|||
lastFile2 = file2
|
||||
|
||||
// Create a DiffContent for each of the texts you want to compare
|
||||
val content1: DiffContent = DiffContentFactory.getInstance().create(File(URI(file1)).readText())
|
||||
val content2: DiffContent = DiffContentFactory.getInstance().create(File(URI(file2)).readText())
|
||||
val content1: DiffContent = DiffContentFactory.getInstance().create(UriUtils.uriToFile(file1).readText())
|
||||
val content2: DiffContent = DiffContentFactory.getInstance().create(UriUtils.uriToFile(file2).readText())
|
||||
|
||||
// Create a SimpleDiffRequest and populate it with the DiffContents and titles
|
||||
val diffRequest = SimpleDiffRequest("Continue Diff", content1, content2, "Old", "New")
|
||||
|
|
|
|||
|
|
@ -7,9 +7,7 @@ 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,
|
||||
|
|
@ -52,7 +50,7 @@ class GitService(
|
|||
} else {
|
||||
ProcessBuilder("git", "diff", "--cached")
|
||||
}
|
||||
builder.directory(File(URI(workspaceDir)))
|
||||
builder.directory(UriUtils.uriToFile(workspaceDir))
|
||||
val process = withContext(Dispatchers.IO) {
|
||||
builder.start()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,13 +1,11 @@
|
|||
package com.github.continuedev.continueintellijextension.`continue`
|
||||
|
||||
import IntelliJIDE
|
||||
import com.github.continuedev.continueintellijextension.*
|
||||
import com.github.continuedev.continueintellijextension.activities.ContinuePluginDisposable
|
||||
import com.github.continuedev.continueintellijextension.activities.showTutorial
|
||||
import com.github.continuedev.continueintellijextension.auth.AuthListener
|
||||
import com.github.continuedev.continueintellijextension.auth.ContinueAuthService
|
||||
import com.github.continuedev.continueintellijextension.editor.DiffStreamHandler
|
||||
import com.github.continuedev.continueintellijextension.editor.DiffStreamService
|
||||
import com.github.continuedev.continueintellijextension.editor.EditorUtils
|
||||
import com.github.continuedev.continueintellijextension.protocol.*
|
||||
import com.github.continuedev.continueintellijextension.services.*
|
||||
import com.github.continuedev.continueintellijextension.utils.*
|
||||
|
|
@ -16,21 +14,15 @@ import com.intellij.openapi.application.ApplicationManager
|
|||
import com.intellij.openapi.command.WriteCommandAction
|
||||
import com.intellij.openapi.components.ServiceManager
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.editor.Editor
|
||||
import com.intellij.openapi.editor.SelectionModel
|
||||
import com.intellij.openapi.fileEditor.FileDocumentManager
|
||||
import com.intellij.openapi.fileEditor.FileEditorManager
|
||||
import com.intellij.openapi.project.DumbAware
|
||||
import com.intellij.openapi.project.Project
|
||||
import com.intellij.openapi.util.TextRange
|
||||
import com.intellij.openapi.vfs.VirtualFileManager
|
||||
import com.intellij.openapi.wm.ToolWindowManager
|
||||
import kotlinx.coroutines.*
|
||||
import java.awt.Toolkit
|
||||
import java.awt.datatransfer.StringSelection
|
||||
import java.lang.IllegalStateException
|
||||
import kotlin.coroutines.resume
|
||||
import kotlin.coroutines.resumeWithException
|
||||
|
||||
|
||||
class IdeProtocolClient(
|
||||
|
|
@ -39,6 +31,8 @@ class IdeProtocolClient(
|
|||
private val project: Project
|
||||
) : DumbAware {
|
||||
private val ide: IDE = IntelliJIDE(project, continuePluginService)
|
||||
private val diffStreamService = project.service<DiffStreamService>()
|
||||
|
||||
|
||||
/**
|
||||
* Create a dispatcher with limited parallelism to prevent UI freezing.
|
||||
|
|
@ -46,6 +40,7 @@ class IdeProtocolClient(
|
|||
*
|
||||
* See this thread for details: https://github.com/continuedev/continue/issues/4098#issuecomment-2854865310
|
||||
*/
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
private val limitedDispatcher = Dispatchers.IO.limitedParallelism(4)
|
||||
|
||||
init {
|
||||
|
|
@ -447,7 +442,13 @@ class IdeProtocolClient(
|
|||
)
|
||||
val filepath = params.filepath;
|
||||
|
||||
acceptOrRejectDiff(filepath, true)
|
||||
val editor = EditorUtils.getOrOpenEditor(project, filepath)?.editor
|
||||
|
||||
if (editor != null) {
|
||||
diffStreamService.accept(editor)
|
||||
}
|
||||
|
||||
respond(null)
|
||||
}
|
||||
|
||||
"rejectDiff" -> {
|
||||
|
|
@ -456,7 +457,13 @@ class IdeProtocolClient(
|
|||
RejectDiffParams::class.java
|
||||
)
|
||||
val filepath = params.filepath;
|
||||
acceptOrRejectDiff(filepath, false)
|
||||
|
||||
val editor = EditorUtils.getOrOpenEditor(project, filepath)?.editor
|
||||
if (editor != null) {
|
||||
diffStreamService.reject(editor)
|
||||
}
|
||||
respond(null)
|
||||
|
||||
}
|
||||
|
||||
"applyToFile" -> {
|
||||
|
|
@ -464,141 +471,13 @@ class IdeProtocolClient(
|
|||
dataElement.toString(),
|
||||
ApplyToFileParams::class.java
|
||||
)
|
||||
val filepath = params.filepath
|
||||
|
||||
continuePluginService.sendToWebview(
|
||||
"updateApplyState", mapOf(
|
||||
"streamId" to params.streamId,
|
||||
"status" to "streaming",
|
||||
"fileContent" to params.text,
|
||||
"toolCallId" to params.toolCallId,
|
||||
"filepath" to filepath
|
||||
)
|
||||
ApplyToFileHandler.apply(
|
||||
project,
|
||||
continuePluginService,
|
||||
ide,
|
||||
params
|
||||
)
|
||||
|
||||
|
||||
fun closeStream() {
|
||||
continuePluginService.sendToWebview(
|
||||
"updateApplyState", mapOf(
|
||||
"numDiffs" to 0,
|
||||
"streamId" to params.streamId,
|
||||
"status" to "closed",
|
||||
"fileContent" to params.text,
|
||||
"toolCallId" to params.toolCallId,
|
||||
"filepath" to filepath
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
var editor: Editor? = null;
|
||||
|
||||
if (!filepath.isNullOrEmpty()) {
|
||||
val virtualFile = VirtualFileManager.getInstance().findFileByUrl(filepath)
|
||||
if (virtualFile != null) {
|
||||
ApplicationManager.getApplication().invokeAndWait {
|
||||
FileEditorManager.getInstance(project).openFile(virtualFile, true)?.first()
|
||||
}
|
||||
}
|
||||
}
|
||||
editor = FileEditorManager.getInstance(project).selectedTextEditor
|
||||
|
||||
if (editor == null) {
|
||||
ide.showToast(ToastType.ERROR, "No active editor to apply edits to")
|
||||
closeStream()
|
||||
respond(null)
|
||||
return@launch
|
||||
}
|
||||
|
||||
if (editor.document.text.trim().isEmpty()) {
|
||||
WriteCommandAction.runWriteCommandAction(project) {
|
||||
editor.document.insertString(0, params.text)
|
||||
}
|
||||
closeStream()
|
||||
respond(null)
|
||||
return@launch
|
||||
}
|
||||
|
||||
val llm: Any = try {
|
||||
suspendCancellableCoroutine { continuation ->
|
||||
continuePluginService.coreMessenger?.request(
|
||||
"config/getSerializedProfileInfo",
|
||||
null,
|
||||
null
|
||||
) { response ->
|
||||
try {
|
||||
val selectedModels = response.castNestedOrNull<Map<String, Any>>("content", "result", "config", "selectedModelByRole")
|
||||
|
||||
// If "apply" role model is not found, try "chat" role
|
||||
val applyCodeBlockModel = selectedModels?.get("apply") ?: selectedModels?.get("chat")
|
||||
|
||||
if (applyCodeBlockModel != null) {
|
||||
continuation.resume(applyCodeBlockModel)
|
||||
} else {
|
||||
// If neither "apply" nor "chat" models are available, return with exception
|
||||
continuation.resumeWithException(IllegalStateException("No 'apply' or 'chat' model found in configuration."))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
continuation.resumeWithException(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
launch {
|
||||
ide.showToast(
|
||||
ToastType.ERROR, "Failed to fetch model configuration"
|
||||
)
|
||||
}
|
||||
closeStream()
|
||||
respond(null)
|
||||
return@launch
|
||||
}
|
||||
|
||||
val diffStreamService = project.service<DiffStreamService>()
|
||||
// Clear all diff blocks before running the diff stream
|
||||
diffStreamService.reject(editor)
|
||||
|
||||
val llmTitle = (llm as? Map<*, *>)?.get("title") as? String ?: ""
|
||||
|
||||
val prompt =
|
||||
"The following code was suggested as an edit:\n```\n${params.text}\n```\nPlease apply it to the previous code."
|
||||
|
||||
val rif = getHighlightedCode()
|
||||
|
||||
val (prefix, highlighted, suffix) = if (rif == null) {
|
||||
// If no highlight, use the whole document as highlighted
|
||||
Triple("", editor.document.text, "")
|
||||
} else {
|
||||
val prefix = editor.document.getText(TextRange(0, rif.range.start.character))
|
||||
val highlighted = rif.contents
|
||||
val suffix =
|
||||
editor.document.getText(TextRange(rif.range.end.character, editor.document.textLength))
|
||||
|
||||
// Remove the selection after processing
|
||||
ApplicationManager.getApplication().invokeLater {
|
||||
editor.selectionModel.removeSelection()
|
||||
}
|
||||
|
||||
Triple(prefix, highlighted, suffix)
|
||||
}
|
||||
|
||||
val diffStreamHandler =
|
||||
DiffStreamHandler(
|
||||
project,
|
||||
editor,
|
||||
rif?.range?.start?.line ?: 0,
|
||||
rif?.range?.end?.line ?: (editor.document.lineCount - 1),
|
||||
{},
|
||||
{},
|
||||
params.streamId,
|
||||
params.toolCallId
|
||||
)
|
||||
|
||||
diffStreamService.register(diffStreamHandler, editor)
|
||||
|
||||
diffStreamHandler.streamDiffLinesToEditor(
|
||||
prompt, prefix, highlighted, suffix, llmTitle, false
|
||||
)
|
||||
|
||||
respond(null)
|
||||
}
|
||||
|
||||
|
|
@ -612,52 +491,15 @@ class IdeProtocolClient(
|
|||
}
|
||||
}
|
||||
|
||||
private fun getHighlightedCode(): RangeInFileWithContents? {
|
||||
val result = ApplicationManager.getApplication().runReadAction<RangeInFileWithContents?> {
|
||||
// Get the editor instance for the currently active editor window
|
||||
val editor = FileEditorManager.getInstance(project).selectedTextEditor ?: return@runReadAction null
|
||||
val virtualFile =
|
||||
editor.let { FileDocumentManager.getInstance().getFile(it.document) } ?: return@runReadAction null
|
||||
|
||||
// Get the selection range and content
|
||||
val selectionModel: SelectionModel = editor.selectionModel
|
||||
val selectedText = selectionModel.selectedText ?: ""
|
||||
|
||||
val document = editor.document
|
||||
val startOffset = selectionModel.selectionStart
|
||||
val endOffset = selectionModel.selectionEnd
|
||||
|
||||
if (startOffset == endOffset) {
|
||||
return@runReadAction null
|
||||
}
|
||||
|
||||
val startLine = document.getLineNumber(startOffset)
|
||||
val endLine = document.getLineNumber(endOffset)
|
||||
|
||||
val startChar = startOffset - document.getLineStartOffset(startLine)
|
||||
val endChar = endOffset - document.getLineStartOffset(endLine)
|
||||
|
||||
return@runReadAction virtualFile.toUriOrNull()?.let {
|
||||
RangeInFileWithContents(
|
||||
it, Range(
|
||||
Position(startLine, startChar),
|
||||
Position(endLine, endChar)
|
||||
), selectedText
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
fun sendHighlightedCode(edit: Boolean = false) {
|
||||
val rif = getHighlightedCode() ?: return
|
||||
val editor = EditorUtils.getEditor(project)
|
||||
val rif = editor?.getHighlightedCode() ?: return
|
||||
|
||||
continuePluginService.sendToWebview(
|
||||
"highlightedCode",
|
||||
mapOf(
|
||||
"rangeInFileWithContents" to rif,
|
||||
"edit" to edit
|
||||
HighlightedCodePayload(
|
||||
rangeInFileWithContents = rif,
|
||||
shouldRun = edit
|
||||
)
|
||||
)
|
||||
}
|
||||
|
|
@ -667,28 +509,6 @@ class IdeProtocolClient(
|
|||
continuePluginService.sendToWebview("acceptRejectDiff", AcceptRejectDiff(accepted, stepIndex), uuid())
|
||||
}
|
||||
|
||||
fun acceptOrRejectDiff(filepath: String, accepted: Boolean) {
|
||||
val virtualFile = VirtualFileManager.getInstance().findFileByUrl(filepath)
|
||||
|
||||
if (virtualFile != null) {
|
||||
ApplicationManager.getApplication().invokeAndWait {
|
||||
val openedEditor =
|
||||
FileEditorManager.getInstance(project).openFile(virtualFile, true)?.first()
|
||||
if (openedEditor != null) {
|
||||
val editor: Editor? = FileEditorManager.getInstance(project).selectedTextEditor
|
||||
|
||||
if (editor != null) {
|
||||
val diffStreamService = project.service<DiffStreamService>()
|
||||
if (accepted) {
|
||||
diffStreamService.accept(editor)
|
||||
} else {
|
||||
diffStreamService.reject(editor)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun deleteAtIndex(index: Int) {
|
||||
continuePluginService.sendToWebview("deleteAtIndex", DeleteAtIndex(index), uuid())
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
package com.github.continuedev.continueintellijextension.`continue`
|
||||
|
||||
import com.github.continuedev.continueintellijextension.*
|
||||
import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath
|
||||
import com.github.continuedev.continueintellijextension.constants.ContinueConstants
|
||||
|
|
@ -167,7 +169,7 @@ class IntelliJIDE(
|
|||
// Find any .continuerc.json files
|
||||
for (file in contents) {
|
||||
if (file.endsWith(".continuerc.json")) {
|
||||
val fileContent = File(URI(file)).readText()
|
||||
val fileContent = UriUtils.uriToFile(file).readText()
|
||||
configs.add(fileContent)
|
||||
}
|
||||
}
|
||||
|
|
@ -178,12 +180,12 @@ class IntelliJIDE(
|
|||
}
|
||||
|
||||
override suspend fun fileExists(filepath: String): Boolean {
|
||||
val file = File(URI(filepath))
|
||||
val file = UriUtils.uriToFile(filepath)
|
||||
return file.exists()
|
||||
}
|
||||
|
||||
override suspend fun writeFile(path: String, contents: String) {
|
||||
val file = File(URI(path))
|
||||
val file = UriUtils.uriToFile(path)
|
||||
file.parentFile?.mkdirs()
|
||||
file.writeText(contents)
|
||||
}
|
||||
|
|
@ -201,7 +203,7 @@ class IntelliJIDE(
|
|||
|
||||
override suspend fun openFile(path: String) {
|
||||
// Convert URI path to absolute file path
|
||||
val filePath = File(URI(path)).absolutePath
|
||||
val filePath = UriUtils.uriToFile(path).absolutePath
|
||||
// Find the file using the absolute path
|
||||
val file = withContext(Dispatchers.IO) {
|
||||
LocalFileSystem.getInstance().refreshAndFindFileByPath(filePath)
|
||||
|
|
@ -216,7 +218,7 @@ class IntelliJIDE(
|
|||
|
||||
override suspend fun openUrl(url: String) {
|
||||
withContext(Dispatchers.IO) {
|
||||
Desktop.browse(java.net.URI(url))
|
||||
Desktop.browse(URI(url))
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -226,7 +228,8 @@ class IntelliJIDE(
|
|||
|
||||
override suspend fun saveFile(filepath: String) {
|
||||
ApplicationManager.getApplication().invokeLater {
|
||||
val file = LocalFileSystem.getInstance().findFileByPath(URI(filepath).path) ?: return@invokeLater
|
||||
val file =
|
||||
LocalFileSystem.getInstance().findFileByPath(UriUtils.parseUri(filepath).path) ?: return@invokeLater
|
||||
val fileDocumentManager = FileDocumentManager.getInstance()
|
||||
val document = fileDocumentManager.getDocument(file)
|
||||
|
||||
|
|
@ -239,7 +242,7 @@ class IntelliJIDE(
|
|||
override suspend fun readFile(filepath: String): String {
|
||||
return try {
|
||||
val content = ApplicationManager.getApplication().runReadAction<String?> {
|
||||
val virtualFile = LocalFileSystem.getInstance().findFileByPath(URI(filepath).path)
|
||||
val virtualFile = LocalFileSystem.getInstance().findFileByPath(UriUtils.parseUri(filepath).path)
|
||||
if (virtualFile != null && FileDocumentManager.getInstance().isFileModified(virtualFile)) {
|
||||
return@runReadAction FileDocumentManager.getInstance().getDocument(virtualFile)?.text
|
||||
}
|
||||
|
|
@ -249,7 +252,7 @@ class IntelliJIDE(
|
|||
if (content != null) {
|
||||
content
|
||||
} else {
|
||||
val file = File(URI(filepath))
|
||||
val file = UriUtils.uriToFile(filepath)
|
||||
if (!file.exists() || file.isDirectory) return ""
|
||||
withContext(Dispatchers.IO) {
|
||||
FileInputStream(file).use { fis ->
|
||||
|
|
@ -455,7 +458,7 @@ class IntelliJIDE(
|
|||
return withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val builder = ProcessBuilder("git", "rev-parse", "--abbrev-ref", "HEAD")
|
||||
builder.directory(File(URI(dir)))
|
||||
builder.directory(UriUtils.uriToFile(dir))
|
||||
val process = builder.start()
|
||||
val reader = BufferedReader(InputStreamReader(process.inputStream))
|
||||
val output = reader.readLine()
|
||||
|
|
@ -485,7 +488,7 @@ class IntelliJIDE(
|
|||
|
||||
override suspend fun getRepoName(dir: String): String? {
|
||||
return withContext(Dispatchers.IO) {
|
||||
val directory = File(URI(dir))
|
||||
val directory = UriUtils.uriToFile(dir)
|
||||
val targetDir = if (directory.isFile) directory.parentFile else directory
|
||||
val builder = ProcessBuilder("git", "config", "--get", "remote.origin.url")
|
||||
builder.directory(targetDir)
|
||||
|
|
@ -549,7 +552,7 @@ class IntelliJIDE(
|
|||
override suspend fun getGitRootPath(dir: String): String? {
|
||||
return withContext(Dispatchers.IO) {
|
||||
val builder = ProcessBuilder("git", "rev-parse", "--show-toplevel")
|
||||
builder.directory(File(URI(dir)))
|
||||
builder.directory(UriUtils.uriToFile(dir))
|
||||
val process = builder.start()
|
||||
|
||||
val reader = BufferedReader(InputStreamReader(process.inputStream))
|
||||
|
|
@ -560,7 +563,7 @@ class IntelliJIDE(
|
|||
}
|
||||
|
||||
override suspend fun listDir(dir: String): List<List<Any>> {
|
||||
val files = File(URI(dir)).listFiles()?.map {
|
||||
val files = UriUtils.uriToFile(dir).listFiles()?.map {
|
||||
listOf(it.name, if (it.isDirectory) FileType.DIRECTORY.value else FileType.FILE.value)
|
||||
} ?: emptyList()
|
||||
|
||||
|
|
@ -569,7 +572,7 @@ class IntelliJIDE(
|
|||
|
||||
override suspend fun getFileStats(files: List<String>): Map<String, FileStats> {
|
||||
return files.associateWith { file ->
|
||||
FileStats(File(URI(file)).lastModified(), File(URI(file)).length())
|
||||
FileStats(UriUtils.uriToFile(file).lastModified(), UriUtils.uriToFile(file).length())
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -587,7 +590,7 @@ class IntelliJIDE(
|
|||
}
|
||||
|
||||
private fun setFileOpen(filepath: String, open: Boolean = true) {
|
||||
val file = LocalFileSystem.getInstance().findFileByPath(URI(filepath).path)
|
||||
val file = LocalFileSystem.getInstance().findFileByPath(UriUtils.uriToFile(filepath).path)
|
||||
|
||||
file?.let {
|
||||
if (open) {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,39 @@
|
|||
package com.github.continuedev.continueintellijextension.`continue`
|
||||
|
||||
import java.io.File
|
||||
import java.net.URI
|
||||
|
||||
/**
|
||||
* Utility class for URI operations
|
||||
*/
|
||||
object UriUtils {
|
||||
/**
|
||||
* Parses a URI string into a URI object, handling special cases for Windows file paths
|
||||
*/
|
||||
fun parseUri(uri: String): URI {
|
||||
try {
|
||||
// Remove query parameters if present
|
||||
val uriStr = uri.substringBefore("?")
|
||||
|
||||
// Handle Windows file paths with authority component
|
||||
if (uriStr.startsWith("file://") && !uriStr.startsWith("file:///")) {
|
||||
val path = uriStr.substringAfter("file://")
|
||||
return URI("file:///$path")
|
||||
}
|
||||
|
||||
// Standard URI handling for other cases
|
||||
val uriWithoutQuery = URI(uriStr)
|
||||
return uriWithoutQuery
|
||||
} catch (e: Exception) {
|
||||
println("Error parsing URI: $uri ${e.message}")
|
||||
throw Exception("Invalid URI: $uri ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a URI string to a File object
|
||||
*/
|
||||
fun uriToFile(uri: String): File {
|
||||
return File(parseUri(uri))
|
||||
}
|
||||
}
|
||||
|
|
@ -1,5 +1,8 @@
|
|||
package com.github.continuedev.continueintellijextension.editor
|
||||
|
||||
import com.github.continuedev.continueintellijextension.ApplyState
|
||||
import com.github.continuedev.continueintellijextension.ApplyStateStatus
|
||||
import com.github.continuedev.continueintellijextension.StreamDiffLinesPayload
|
||||
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
|
||||
import com.intellij.openapi.application.ApplicationManager
|
||||
import com.intellij.openapi.command.WriteCommandAction
|
||||
|
|
@ -12,7 +15,6 @@ import com.intellij.openapi.fileEditor.FileDocumentManager
|
|||
import com.intellij.openapi.fileEditor.FileEditorManager
|
||||
import com.intellij.openapi.fileEditor.TextEditor
|
||||
import com.intellij.openapi.project.Project
|
||||
import com.intellij.openapi.vfs.VirtualFile
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
|
||||
|
|
@ -35,41 +37,41 @@ class DiffStreamHandler(
|
|||
var index: Int, var highlighter: RangeHighlighter? = null, var diffBlock: VerticalDiffBlock? = null
|
||||
)
|
||||
|
||||
private val diffBlocks: MutableList<VerticalDiffBlock> = mutableListOf()
|
||||
private var curLine = CurLineState(startLine)
|
||||
private var isRunning: Boolean = false
|
||||
private var hasAcceptedOrRejectedBlock: Boolean = false
|
||||
|
||||
private val unfinishedHighlighters: MutableList<RangeHighlighter> = mutableListOf()
|
||||
private val diffBlocks: MutableList<VerticalDiffBlock> = mutableListOf()
|
||||
private val continuePluginService = ServiceManager.getService(project, ContinuePluginService::class.java)
|
||||
private val virtualFile = FileDocumentManager.getInstance().getFile(editor.document)
|
||||
|
||||
private val curLineKey = createTextAttributesKey("CONTINUE_DIFF_CURRENT_LINE", 0x40888888, editor)
|
||||
private val unfinishedKey = createTextAttributesKey("CONTINUE_DIFF_UNFINISHED_LINE", 0x20888888, editor)
|
||||
|
||||
init {
|
||||
initUnfinishedRangeHighlights()
|
||||
}
|
||||
|
||||
private fun sendUpdate(status: String) {
|
||||
if(this.streamId == null) {
|
||||
private fun sendUpdate(status: ApplyStateStatus) {
|
||||
if (streamId == null) {
|
||||
return
|
||||
}
|
||||
val virtualFile = getVirtualFile()
|
||||
val continuePluginService = ServiceManager.getService(project, ContinuePluginService::class.java)
|
||||
continuePluginService.sendToWebview("updateApplyState", mapOf(
|
||||
"numDiffs" to this.diffBlocks.size,
|
||||
"streamId" to this.streamId,
|
||||
"status" to status,
|
||||
"fileContent" to "not implemented",
|
||||
"toolCallId" to this.toolCallId,
|
||||
"filepath" to virtualFile?.url
|
||||
))
|
||||
|
||||
// Define a single payload and use it for sending
|
||||
val payload = ApplyState(
|
||||
streamId = streamId,
|
||||
status = status.status,
|
||||
numDiffs = diffBlocks.size,
|
||||
filepath = virtualFile?.url,
|
||||
fileContent = "not implemented",
|
||||
toolCallId = toolCallId?.toString()
|
||||
)
|
||||
|
||||
continuePluginService.sendToWebview("updateApplyState", payload)
|
||||
}
|
||||
|
||||
fun acceptAll() {
|
||||
editor.markupModel.removeAllHighlighters();
|
||||
sendUpdate("closed")
|
||||
|
||||
resetState()
|
||||
ApplicationManager.getApplication().invokeLater {
|
||||
diffBlocks.toList().forEach { it.handleAccept() }
|
||||
}
|
||||
}
|
||||
|
||||
fun rejectAll() {
|
||||
|
|
@ -77,26 +79,42 @@ class DiffStreamHandler(
|
|||
// to our changes. However, if the user has accepted or rejected one or more diff blocks, there isn't a simple
|
||||
// way to undo our changes without also undoing the diff that the user accepted or rejected.
|
||||
if (hasAcceptedOrRejectedBlock) {
|
||||
diffBlocks.forEach { it.handleReject() }
|
||||
ApplicationManager.getApplication().invokeLater {
|
||||
val blocksToReject = diffBlocks.toList()
|
||||
blocksToReject.toList().forEach { it.handleReject() }
|
||||
}
|
||||
} else {
|
||||
undoChanges()
|
||||
// We have to manually call `handleClosedState`, but above,
|
||||
// this is done by invoking the button handlers
|
||||
setClosed()
|
||||
}
|
||||
sendUpdate("closed")
|
||||
|
||||
resetState()
|
||||
}
|
||||
|
||||
fun streamDiffLinesToEditor(
|
||||
input: String, prefix: String, highlighted: String, suffix: String, modelTitle: String, includeRulesInSystemMessage: Boolean
|
||||
input: String,
|
||||
prefix: String,
|
||||
highlighted: String,
|
||||
suffix: String,
|
||||
modelTitle: String,
|
||||
includeRulesInSystemMessage: Boolean
|
||||
) {
|
||||
isRunning = true
|
||||
this.sendUpdate("streaming")
|
||||
|
||||
val continuePluginService = ServiceManager.getService(project, ContinuePluginService::class.java)
|
||||
val virtualFile = getVirtualFile()
|
||||
sendUpdate(ApplyStateStatus.STREAMING)
|
||||
|
||||
continuePluginService.coreMessenger?.request(
|
||||
"streamDiffLines", createRequestParams(input, prefix, highlighted, suffix, virtualFile, modelTitle, includeRulesInSystemMessage), null
|
||||
"streamDiffLines",
|
||||
StreamDiffLinesPayload(
|
||||
input = input,
|
||||
prefix = prefix,
|
||||
highlighted = highlighted,
|
||||
suffix = suffix,
|
||||
language = virtualFile?.fileType?.name,
|
||||
modelTitle = modelTitle,
|
||||
includeRulesInSystemMessage = includeRulesInSystemMessage,
|
||||
fileUri = virtualFile?.url
|
||||
),
|
||||
null
|
||||
) { response ->
|
||||
if (!isRunning) return@request
|
||||
|
||||
|
|
@ -104,7 +122,6 @@ class DiffStreamHandler(
|
|||
|
||||
if (response["done"] as? Boolean == true) {
|
||||
handleFinishedResponse()
|
||||
sendUpdate(if (diffBlocks.isEmpty()) "closed" else "done")
|
||||
return@request
|
||||
}
|
||||
|
||||
|
|
@ -113,6 +130,9 @@ class DiffStreamHandler(
|
|||
}
|
||||
|
||||
private fun initUnfinishedRangeHighlights() {
|
||||
val editorUtils = EditorUtils(editor)
|
||||
val unfinishedKey = editorUtils.createTextAttributesKey("CONTINUE_DIFF_UNFINISHED_LINE", 0x20888888)
|
||||
|
||||
for (i in startLine..endLine) {
|
||||
val highlighter = editor.markupModel.addLineHighlighter(
|
||||
unfinishedKey, min(
|
||||
|
|
@ -155,10 +175,11 @@ class DiffStreamHandler(
|
|||
}
|
||||
|
||||
if (diffBlocks.isEmpty()) {
|
||||
sendUpdate("closed")
|
||||
onClose()
|
||||
setClosed()
|
||||
} else {
|
||||
sendUpdate("done")
|
||||
// TODO: It's confusing that we pass `DONE` here. What we're doing is updating the UI with the latest
|
||||
// diff count. We should have a dedicated status for this.
|
||||
sendUpdate(ApplyStateStatus.DONE)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -169,8 +190,6 @@ class DiffStreamHandler(
|
|||
)
|
||||
|
||||
diffBlocks.add(diffBlock)
|
||||
sendUpdate("streaming")
|
||||
|
||||
return diffBlock
|
||||
}
|
||||
|
||||
|
|
@ -203,12 +222,17 @@ class DiffStreamHandler(
|
|||
}
|
||||
|
||||
private fun updateProgressHighlighters(type: DiffLineType) {
|
||||
val editorUtils = EditorUtils(editor)
|
||||
val curLineKey = editorUtils.createTextAttributesKey("CONTINUE_DIFF_CURRENT_LINE", 0x40888888)
|
||||
|
||||
// Update the highlighter to show the current line
|
||||
curLine.highlighter?.let { editor.markupModel.removeHighlighter(it) }
|
||||
curLine.highlighter = editor.markupModel.addLineHighlighter(
|
||||
curLineKey, min(curLine.index, max(0, editor.document.lineCount - 1)), HighlighterLayer.LAST
|
||||
)
|
||||
|
||||
editorUtils.scrollToLine(curLine.index)
|
||||
|
||||
// Remove the unfinished lines highlighter
|
||||
if (type != DiffLineType.OLD && unfinishedHighlighters.isNotEmpty()) {
|
||||
editor.markupModel.removeHighlighter(unfinishedHighlighters.removeAt(0))
|
||||
|
|
@ -242,15 +266,18 @@ class DiffStreamHandler(
|
|||
curLine = CurLineState(startLine)
|
||||
isRunning = false
|
||||
|
||||
// Close the Edit input
|
||||
// Close the Edit input if editing
|
||||
onClose()
|
||||
}
|
||||
|
||||
|
||||
private fun undoChanges() {
|
||||
if (virtualFile == null) {
|
||||
return
|
||||
}
|
||||
|
||||
WriteCommandAction.runWriteCommandAction(project) {
|
||||
val undoManager = UndoManager.getInstance(project)
|
||||
val virtualFile = getVirtualFile() ?: return@runWriteCommandAction
|
||||
val fileEditor = FileEditorManager.getInstance(project).getSelectedEditor(virtualFile) as TextEditor
|
||||
|
||||
if (undoManager.isUndoAvailable(fileEditor)) {
|
||||
|
|
@ -260,35 +287,9 @@ class DiffStreamHandler(
|
|||
undoManager.undo(fileEditor)
|
||||
}
|
||||
}
|
||||
sendUpdate("done")
|
||||
}
|
||||
}
|
||||
|
||||
private fun getVirtualFile(): VirtualFile? {
|
||||
return FileDocumentManager.getInstance().getFile(editor.document) ?: return null
|
||||
}
|
||||
|
||||
private fun createRequestParams(
|
||||
input: String,
|
||||
prefix: String,
|
||||
highlighted: String,
|
||||
suffix: String,
|
||||
virtualFile: VirtualFile?,
|
||||
modelTitle: String,
|
||||
includeRulesInSystemMessage: Boolean
|
||||
): Map<String, Any?> {
|
||||
return mapOf(
|
||||
"input" to input,
|
||||
"prefix" to prefix,
|
||||
"highlighted" to highlighted,
|
||||
"suffix" to suffix,
|
||||
"language" to virtualFile?.fileType?.name,
|
||||
"modelTitle" to modelTitle,
|
||||
"includeRulesInSystemMessage" to includeRulesInSystemMessage,
|
||||
"fileUri" to virtualFile?.url,
|
||||
)
|
||||
}
|
||||
|
||||
private fun handleFinishedResponse() {
|
||||
ApplicationManager.getApplication().invokeLater {
|
||||
// Since we only call onLastDiffLine() when we reach a "same" line, we need to handle the case where
|
||||
|
|
@ -297,6 +298,12 @@ class DiffStreamHandler(
|
|||
|
||||
onFinish()
|
||||
cleanupProgressHighlighters()
|
||||
|
||||
if (diffBlocks.isEmpty()) {
|
||||
setClosed()
|
||||
} else {
|
||||
sendUpdate(ApplyStateStatus.DONE)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -326,4 +333,10 @@ class DiffStreamHandler(
|
|||
else -> throw Exception("Unknown diff line type: $type")
|
||||
}
|
||||
}
|
||||
|
||||
private fun setClosed() {
|
||||
sendUpdate(ApplyStateStatus.CLOSED)
|
||||
resetState()
|
||||
onClose()
|
||||
}
|
||||
}
|
||||
|
|
@ -1,22 +1,167 @@
|
|||
package com.github.continuedev.continueintellijextension.editor
|
||||
|
||||
import com.github.continuedev.continueintellijextension.Position
|
||||
import com.github.continuedev.continueintellijextension.Range
|
||||
import com.github.continuedev.continueintellijextension.utils.toUriOrNull
|
||||
import com.intellij.openapi.application.ApplicationManager
|
||||
import com.intellij.openapi.command.WriteCommandAction
|
||||
import com.intellij.openapi.editor.Editor
|
||||
import com.intellij.openapi.editor.SelectionModel
|
||||
import com.intellij.openapi.editor.colors.TextAttributesKey
|
||||
import com.intellij.openapi.editor.markup.TextAttributes
|
||||
import com.intellij.openapi.fileEditor.FileDocumentManager
|
||||
import com.intellij.openapi.fileEditor.FileEditorManager
|
||||
import com.intellij.openapi.project.Project
|
||||
import com.intellij.openapi.util.TextRange
|
||||
import com.intellij.openapi.vfs.VirtualFileManager
|
||||
import com.intellij.ui.JBColor
|
||||
import com.intellij.openapi.editor.ScrollType
|
||||
|
||||
class EditorUtils {
|
||||
fun isTerminal(editor: Editor): Boolean {
|
||||
return editor.javaClass.name.contains("Terminal")
|
||||
}
|
||||
}
|
||||
|
||||
fun createTextAttributesKey(name: String, color: Int, editor: Editor): TextAttributesKey {
|
||||
val attributes = TextAttributes().apply {
|
||||
backgroundColor = JBColor(color, color)
|
||||
}
|
||||
|
||||
return TextAttributesKey.createTextAttributesKey(name).also {
|
||||
editor.colorsScheme.setAttributes(it, attributes)
|
||||
/**
|
||||
* Utility class for working with Editor instances.
|
||||
*/
|
||||
class EditorUtils(val editor: Editor) {
|
||||
private val project: Project
|
||||
get() = editor.project!!
|
||||
|
||||
/**
|
||||
* Checks if the editor is a terminal editor
|
||||
*/
|
||||
fun isTerminal(): Boolean {
|
||||
return editor.javaClass.name.contains("Terminal")
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the document is empty (contains only whitespace)
|
||||
*/
|
||||
fun isDocumentEmpty(): Boolean {
|
||||
return editor.document.text.trim().isEmpty()
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the total number of lines in the document
|
||||
*/
|
||||
fun getLineCount(): Int {
|
||||
return editor.document.lineCount
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts text at the specified position in the document
|
||||
*/
|
||||
fun insertTextAtPos(pos: Int, text: String) {
|
||||
WriteCommandAction.runWriteCommandAction(project) {
|
||||
editor.document.insertString(pos, text)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts text at the beginning of the document
|
||||
*/
|
||||
fun insertTextIntoEmptyDocument(text: String) {
|
||||
insertTextAtPos(0, text)
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Scrolls the editor to make the specified line visible
|
||||
*/
|
||||
fun scrollToLine(lineNumber: Int) {
|
||||
val safeLineNumber = lineNumber.coerceIn(0, editor.document.lineCount - 1)
|
||||
val lineStartOffset = editor.document.getLineStartOffset(safeLineNumber)
|
||||
val logicalPosition = editor.offsetToLogicalPosition(lineStartOffset)
|
||||
editor.scrollingModel.scrollTo(logicalPosition, ScrollType.CENTER_UP)
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Extracts code ranges from the editor: (prefix, highlighted/selected text, suffix)
|
||||
*/
|
||||
fun extractCodeRanges(): Triple<String, String, String> {
|
||||
val rif = getHighlightedCode()
|
||||
|
||||
return if (rif == null) {
|
||||
// If no highlight, use the whole document as highlighted
|
||||
Triple("", editor.document.text, "")
|
||||
} else {
|
||||
// Use the RangeInFileWithContents to get absolute offsets
|
||||
val startOffset = rif.getStartOffset(editor.document)
|
||||
val endOffset = rif.getEndOffset(editor.document)
|
||||
val prefix = editor.document.getText(TextRange(0, startOffset))
|
||||
val highlighted = rif.contents
|
||||
val suffix = editor.document.getText(TextRange(endOffset, editor.document.textLength))
|
||||
|
||||
// Remove the selection after processing
|
||||
ApplicationManager.getApplication().invokeLater {
|
||||
editor.selectionModel.removeSelection()
|
||||
}
|
||||
|
||||
Triple(prefix, highlighted, suffix)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the selected code from the current editor.
|
||||
* Returns null if there is no selection.
|
||||
*/
|
||||
fun getHighlightedCode(): RangeInFileWithContents? {
|
||||
return ApplicationManager.getApplication().runReadAction<RangeInFileWithContents?> {
|
||||
val virtualFile =
|
||||
FileDocumentManager.getInstance().getFile(editor.document) ?: return@runReadAction null
|
||||
|
||||
// Get the selection range
|
||||
val selectionModel: SelectionModel = editor.selectionModel
|
||||
val startOffset = selectionModel.selectionStart
|
||||
val endOffset = selectionModel.selectionEnd
|
||||
|
||||
if (startOffset == endOffset) {
|
||||
return@runReadAction null
|
||||
}
|
||||
|
||||
return@runReadAction virtualFile.toUriOrNull()?.let {
|
||||
RangeInFileWithContents.fromSelection(
|
||||
it,
|
||||
editor.document,
|
||||
startOffset,
|
||||
endOffset
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun createTextAttributesKey(name: String, color: Int): TextAttributesKey {
|
||||
val attributes = TextAttributes().apply {
|
||||
backgroundColor = JBColor(color, color)
|
||||
}
|
||||
|
||||
return TextAttributesKey.createTextAttributesKey(name).also {
|
||||
editor.colorsScheme.setAttributes(it, attributes)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* Gets an editor for the currently selected file without opening any new files
|
||||
*/
|
||||
fun getEditor(project: Project): EditorUtils? {
|
||||
val editor = FileEditorManager.getInstance(project).selectedTextEditor ?: return null
|
||||
return EditorUtils(editor)
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets or opens an editor for the specified filepath and returns an EditorUtils instance
|
||||
*/
|
||||
fun getOrOpenEditor(project: Project, filepath: String?): EditorUtils? {
|
||||
if (!filepath.isNullOrEmpty()) {
|
||||
val virtualFile = VirtualFileManager.getInstance().findFileByUrl(filepath)
|
||||
if (virtualFile != null) {
|
||||
ApplicationManager.getApplication().invokeAndWait {
|
||||
FileEditorManager.getInstance(project).openFile(virtualFile, true).first()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val editor = FileEditorManager.getInstance(project).selectedTextEditor ?: return null
|
||||
return EditorUtils(editor)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -120,7 +120,7 @@ fun openInlineEdit(project: Project?, editor: Editor) {
|
|||
if (project == null) return
|
||||
|
||||
// Don't open in terminal
|
||||
if (EditorUtils().isTerminal(editor)) {
|
||||
if (EditorUtils(editor).isTerminal()) {
|
||||
return
|
||||
}
|
||||
|
||||
|
|
@ -131,7 +131,8 @@ fun openInlineEdit(project: Project?, editor: Editor) {
|
|||
val modelTitles = mutableListOf<String>()
|
||||
|
||||
continuePluginService.coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response ->
|
||||
val modelsByRole = response.castNestedOrNull<Map<String, Any>>("content", "result", "config", "modelsByRole") ?: return@request
|
||||
val modelsByRole =
|
||||
response.castNestedOrNull<Map<String, Any>>("content", "result", "config", "modelsByRole") ?: return@request
|
||||
val role = if (modelsByRole.containsKey("edit")) "edit" else "chat"
|
||||
modelsByRole.castNestedOrNull<List<*>>(role)
|
||||
?.mapNotNull { it.castNestedOrNull<String>("title") }
|
||||
|
|
|
|||
|
|
@ -0,0 +1,62 @@
|
|||
package com.github.continuedev.continueintellijextension.editor
|
||||
|
||||
import com.github.continuedev.continueintellijextension.Position
|
||||
import com.github.continuedev.continueintellijextension.Range
|
||||
import com.intellij.openapi.editor.Document
|
||||
import com.intellij.openapi.util.TextRange
|
||||
|
||||
/**
|
||||
* Represents a range of text in a file with its contents.
|
||||
* Provides utility methods for working with document positions and offsets.
|
||||
*/
|
||||
class RangeInFileWithContents(
|
||||
val filepath: String,
|
||||
val range: Range,
|
||||
val contents: String
|
||||
) {
|
||||
/**
|
||||
* Returns the absolute document offset for the start position
|
||||
*/
|
||||
fun getStartOffset(document: Document): Int {
|
||||
return document.getLineStartOffset(range.start.line) + range.start.character
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the absolute document offset for the end position
|
||||
*/
|
||||
fun getEndOffset(document: Document): Int {
|
||||
return document.getLineStartOffset(range.end.line) + range.end.character
|
||||
}
|
||||
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* Create a RangeInFileWithContents from a document selection
|
||||
*/
|
||||
fun fromSelection(
|
||||
filepath: String,
|
||||
document: Document,
|
||||
selectionStart: Int,
|
||||
selectionEnd: Int
|
||||
): RangeInFileWithContents {
|
||||
val startLine = document.getLineNumber(selectionStart)
|
||||
val endLine = document.getLineNumber(selectionEnd)
|
||||
|
||||
val startChar = selectionStart - document.getLineStartOffset(startLine)
|
||||
val endChar = selectionEnd - document.getLineStartOffset(endLine)
|
||||
|
||||
val selectedText = document.getText(
|
||||
TextRange(selectionStart, selectionEnd)
|
||||
)
|
||||
|
||||
return RangeInFileWithContents(
|
||||
filepath,
|
||||
Range(
|
||||
Position(startLine, startChar),
|
||||
Position(endLine, endChar)
|
||||
),
|
||||
selectedText
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -32,8 +32,6 @@ class VerticalDiffBlock(
|
|||
private var deletionInlay: Disposable? = null
|
||||
private var textArea: JTextArea? = null // Used for calculation of the text area height when rendering buttons
|
||||
private var hasRenderedDiffBlock: Boolean = false
|
||||
private val editorComponentInlaysManager = EditorComponentInlaysManager.from(editor, false)
|
||||
private val greenKey = createTextAttributesKey("CONTINUE_DIFF_NEW_LINE", 0x3000FF00, editor)
|
||||
|
||||
init {
|
||||
val (acceptBtn, rejectBtn) = createButtons()
|
||||
|
|
@ -78,6 +76,8 @@ class VerticalDiffBlock(
|
|||
|
||||
|
||||
fun addNewLine(text: String, line: Int) {
|
||||
val greenKey = EditorUtils(editor).createTextAttributesKey("CONTINUE_DIFF_NEW_LINE", 0x3000FF00)
|
||||
|
||||
if (line == editor.document.lineCount) {
|
||||
editor.document.insertString(editor.document.textLength, "\n")
|
||||
}
|
||||
|
|
@ -97,7 +97,7 @@ class VerticalDiffBlock(
|
|||
return
|
||||
}
|
||||
|
||||
if (deletedLines.size > 0) {
|
||||
if (deletedLines.isNotEmpty()) {
|
||||
renderDeletedLinesInlay()
|
||||
}
|
||||
|
||||
|
|
@ -107,20 +107,32 @@ class VerticalDiffBlock(
|
|||
}
|
||||
|
||||
fun handleReject() {
|
||||
revertDiff()
|
||||
// Note that the logic for clearing editor UI state assumes that we do it
|
||||
// prior to undoing the diff changes, changing this order will break things
|
||||
clearEditorUI()
|
||||
revertDiff()
|
||||
|
||||
onAcceptReject(this@VerticalDiffBlock, false)
|
||||
}
|
||||
|
||||
fun handleAccept() {
|
||||
clearEditorUI()
|
||||
onAcceptReject(this@VerticalDiffBlock, true)
|
||||
}
|
||||
|
||||
|
||||
private fun refreshEditor() {
|
||||
editor.contentComponent.revalidate()
|
||||
editor.contentComponent.repaint()
|
||||
}
|
||||
|
||||
private fun renderDeletedLinesInlay() {
|
||||
val textArea = createDeletionTextArea(deletedLines.joinToString("\n"))
|
||||
this.textArea = textArea
|
||||
val editorComponentInlaysManager = EditorComponentInlaysManager.from(editor, false)
|
||||
val newTextArea = createDeletionTextArea(deletedLines.joinToString("\n"))
|
||||
|
||||
val disposable = editorComponentInlaysManager.insert(startLine, textArea, true)
|
||||
textArea = newTextArea
|
||||
|
||||
val disposable = editorComponentInlaysManager.insert(startLine, newTextArea, true)
|
||||
deletionInlay = disposable
|
||||
}
|
||||
|
||||
|
|
@ -158,7 +170,6 @@ class VerticalDiffBlock(
|
|||
).apply {
|
||||
addActionListener {
|
||||
handleReject()
|
||||
onAcceptReject(this@VerticalDiffBlock, false)
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -171,7 +182,6 @@ class VerticalDiffBlock(
|
|||
).apply {
|
||||
addActionListener {
|
||||
handleAccept()
|
||||
onAcceptReject(this@VerticalDiffBlock, true)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -185,9 +195,6 @@ class VerticalDiffBlock(
|
|||
refreshEditor()
|
||||
}
|
||||
|
||||
private fun handleAccept() {
|
||||
clearEditorUI()
|
||||
}
|
||||
|
||||
private fun revertDiff() {
|
||||
WriteCommandAction.runWriteCommandAction(project) {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,5 @@
|
|||
package com.github.continuedev.continueintellijextension.services
|
||||
|
||||
import IntelliJIDE
|
||||
import com.github.continuedev.continueintellijextension.`continue`.CoreMessenger
|
||||
import com.github.continuedev.continueintellijextension.`continue`.CoreMessengerManager
|
||||
import com.github.continuedev.continueintellijextension.`continue`.DiffManager
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
package com.github.continuedev.continueintellijextension
|
||||
|
||||
import com.github.continuedev.continueintellijextension.editor.RangeInFileWithContents
|
||||
import com.google.gson.JsonElement
|
||||
|
||||
enum class ToastType(val value: String) {
|
||||
|
|
@ -213,3 +214,41 @@ data class Message(
|
|||
data class AcceptRejectDiff(val accepted: Boolean, val stepIndex: Int)
|
||||
|
||||
data class DeleteAtIndex(val index: Int)
|
||||
|
||||
enum class ApplyStateStatus(val status: String) {
|
||||
NOT_STARTED("not-started"),
|
||||
STREAMING("streaming"),
|
||||
DONE("done"),
|
||||
CLOSED("closed");
|
||||
}
|
||||
|
||||
data class ApplyState(
|
||||
val streamId: String,
|
||||
val status: String,
|
||||
val numDiffs: Int? = null,
|
||||
val filepath: String? = null,
|
||||
val fileContent: String? = null,
|
||||
val toolCallId: String? = null
|
||||
)
|
||||
|
||||
data class HighlightedCodePayload(
|
||||
val rangeInFileWithContents: RangeInFileWithContents,
|
||||
val prompt: String? = null,
|
||||
val shouldRun: Boolean? = null
|
||||
)
|
||||
|
||||
data class StreamDiffLinesPayload(
|
||||
val prefix: String,
|
||||
val highlighted: String,
|
||||
val suffix: String,
|
||||
val input: String,
|
||||
val language: String?,
|
||||
val modelTitle: String?,
|
||||
val includeRulesInSystemMessage: Boolean
|
||||
val fileUri: String?
|
||||
)
|
||||
|
||||
data class AcceptOrRejectDiffPayload(
|
||||
val filepath: String,
|
||||
val streamId: String? = null
|
||||
)
|
||||
|
|
@ -0,0 +1,94 @@
|
|||
package com.github.continuedev.continueintellijextension.unit
|
||||
|
||||
import com.github.continuedev.continueintellijextension.ApplyStateStatus
|
||||
import com.github.continuedev.continueintellijextension.IDE
|
||||
import com.github.continuedev.continueintellijextension.ApplyState
|
||||
import com.github.continuedev.continueintellijextension.`continue`.ApplyToFileHandler
|
||||
import com.github.continuedev.continueintellijextension.`continue`.CoreMessenger
|
||||
import com.github.continuedev.continueintellijextension.editor.DiffStreamService
|
||||
import com.github.continuedev.continueintellijextension.editor.EditorUtils
|
||||
import com.github.continuedev.continueintellijextension.protocol.ApplyToFileParams
|
||||
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
|
||||
import com.intellij.openapi.editor.Editor
|
||||
import com.intellij.openapi.project.Project
|
||||
import io.mockk.*
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import org.junit.jupiter.api.BeforeEach
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
@ExperimentalCoroutinesApi
|
||||
class ApplyToFileHandlerTest {
|
||||
// Mock all dependencies
|
||||
private val mockProject = mockk<Project>(relaxed = true)
|
||||
private val mockContinuePluginService = mockk<ContinuePluginService>(relaxed = true)
|
||||
private val mockIde = mockk<IDE>(relaxed = true)
|
||||
private val mockEditorUtils = mockk<EditorUtils>(relaxed = true)
|
||||
private val mockDiffStreamService = mockk<DiffStreamService>(relaxed = true)
|
||||
private val mockEditor = mockk<Editor>(relaxed = true)
|
||||
private val mockCoreMessenger = mockk<CoreMessenger>(relaxed = true)
|
||||
|
||||
// Test subject
|
||||
private lateinit var handler: ApplyToFileHandler
|
||||
|
||||
// Constants for testing
|
||||
private val testParams = ApplyToFileParams(
|
||||
"Sample text to apply",
|
||||
"stream123",
|
||||
"test/file.kt",
|
||||
"tool-call-123"
|
||||
)
|
||||
|
||||
@BeforeEach
|
||||
fun setUp() {
|
||||
// Common setup
|
||||
every { mockEditorUtils.editor } returns mockEditor
|
||||
every { mockContinuePluginService.coreMessenger } returns mockCoreMessenger
|
||||
|
||||
// Create the handler with mocked dependencies
|
||||
handler = ApplyToFileHandler(
|
||||
mockProject,
|
||||
mockContinuePluginService,
|
||||
mockIde,
|
||||
testParams,
|
||||
mockEditorUtils,
|
||||
mockDiffStreamService
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `should insert text directly when document is empty`() = runTest {
|
||||
// Given
|
||||
every { mockEditorUtils.isDocumentEmpty() } returns true
|
||||
|
||||
// When
|
||||
handler.handleApplyToFile()
|
||||
|
||||
// Then
|
||||
verify { mockEditorUtils.insertTextIntoEmptyDocument(testParams.text) }
|
||||
verify(exactly = 0) { mockDiffStreamService.register(any(), any()) } // Ensure no diff streaming happened
|
||||
|
||||
// Verify notifications sent
|
||||
verify {
|
||||
mockContinuePluginService.sendToWebview(
|
||||
eq("updateApplyState"),
|
||||
withArg { payload ->
|
||||
assert(payload is ApplyState)
|
||||
assert((payload as ApplyState).status == ApplyStateStatus.STREAMING.status)
|
||||
},
|
||||
any()
|
||||
)
|
||||
}
|
||||
|
||||
verify {
|
||||
mockContinuePluginService.sendToWebview(
|
||||
eq("updateApplyState"),
|
||||
withArg { payload ->
|
||||
assert(payload is ApplyState)
|
||||
assert((payload as ApplyState).status == ApplyStateStatus.CLOSED.status)
|
||||
},
|
||||
any()
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,66 @@
|
|||
package com.github.continuedev.continueintellijextension.unit
|
||||
|
||||
import com.github.continuedev.continueintellijextension.`continue`.UriUtils
|
||||
import org.junit.jupiter.api.Disabled
|
||||
import org.junit.jupiter.api.Test
|
||||
import java.io.File
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
class UriUtilsTest {
|
||||
@Test
|
||||
fun testUriToFile() {
|
||||
val uri = "file:///path/to/file"
|
||||
val file = UriUtils.uriToFile(uri)
|
||||
assertEquals(File("/path/to/file"), file)
|
||||
}
|
||||
|
||||
@Disabled("Not working")
|
||||
@Test
|
||||
fun testUriToFileWithWindowsPath() {
|
||||
val uri = "file:///C:/path/to/file"
|
||||
val file = UriUtils.uriToFile(uri)
|
||||
assertEquals(File("C:/path/to/file"), file)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun shouldHandleAuthorityComponent() {
|
||||
val uri = "file://C:/path/to/file"
|
||||
val file = UriUtils.uriToFile(uri)
|
||||
assertEquals(File("/C:/path/to/file"), file)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testUriToFileWithSpaces() {
|
||||
val uri = "file:///path/to/file%20with%20spaces"
|
||||
val file = UriUtils.uriToFile(uri)
|
||||
assertEquals(File("/path/to/file with spaces"), file)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testUriToFileWithSpecialCharacters() {
|
||||
val uri = "file:///path/to/file%23with%25special%26chars"
|
||||
val file = UriUtils.uriToFile(uri)
|
||||
assertEquals(File("/path/to/file#with%special&chars"), file)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testUriToFileWithQueryParams() {
|
||||
val uri = "file:///path/to/file?param=value"
|
||||
val file = UriUtils.uriToFile(uri)
|
||||
assertEquals(File("/path/to/file"), file)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testUriToFileWithWSLPath() {
|
||||
val uri = "file:///wsl$/Ubuntu/home/user/file.txt"
|
||||
val file = UriUtils.uriToFile(uri)
|
||||
assertEquals(File("/wsl$/Ubuntu/home/user/file.txt"), file)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testUriToFileWithWSLLocalhostPath() {
|
||||
val uri = "file:///wsl.localhost/Ubuntu/home/user/file.txt"
|
||||
val file = UriUtils.uriToFile(uri)
|
||||
assertEquals(File("/wsl.localhost/Ubuntu/home/user/file.txt"), file)
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,76 @@
|
|||
/**
|
||||
* Notes:
|
||||
* - `sendIntellijMessage` isn't working, but keeping this around as an example of how we might be able to implement
|
||||
* - Below is an AI generated summary of what the problem might be based on troubleshooting attempts
|
||||
* - For details, see https://intellij-support.jetbrains.com/hc/en-us/community/posts/26714246086162--intellij-ui-test-robot-Error-when-attempting-to-click-on-DomElement-491
|
||||
*
|
||||
*
|
||||
* The issue is with how the JCefBrowserFixture.executeJsInBrowser method handles JavaScript code execution.
|
||||
* When trying to call window.postIntellijMessage, we're encountering these challenges:
|
||||
*
|
||||
* 1. **Double Injection Problem**: The postIntellijMessage function already uses JBCefJSQuery.inject internally.
|
||||
* When we try to call it through executeJsInBrowser, we're essentially trying to pass it through another injection
|
||||
* mechanism, creating nested injections that break.
|
||||
*
|
||||
* 2. **String Escaping Issues**: The way quotes are being escaped between the layers of execution is causing syntax
|
||||
* errors in the final JavaScript that gets executed.
|
||||
*
|
||||
* 3. **Context Isolation**: The executeJsInBrowser method likely runs in a different execution context than where the
|
||||
* function was defined, causing scope/reference issues.
|
||||
*
|
||||
* The key insight is that we cannot directly call a function that itself uses the JBCefJSQuery bridge through the test
|
||||
* framework's executeJsInBrowser method. These bridge functions are designed to be called directly in the browser
|
||||
* context, not through another layer of script injection.
|
||||
*/
|
||||
package com.github.continuedev.continueintellijextension.utils
|
||||
|
||||
import com.intellij.remoterobot.fixtures.JCefBrowserFixture
|
||||
|
||||
/**
|
||||
* Utility functions for interacting with browser components in tests
|
||||
*/
|
||||
object BrowserUtils {
|
||||
|
||||
/**
|
||||
* Sends a message to the webview using JCefBrowserFixture's executeJsInBrowser
|
||||
*
|
||||
* @param browser The JCefBrowserFixture to execute JavaScript in
|
||||
* @param messageType The type of message to send
|
||||
* @param messageData The data object to send as message payload
|
||||
* @param messageId A unique ID for the message
|
||||
*/
|
||||
fun sendIntellijMessage(
|
||||
browser: JCefBrowserFixture,
|
||||
messageType: String,
|
||||
messageData: Any,
|
||||
messageId: String = "test-message-id"
|
||||
) {
|
||||
// Convert the messageData to a JSON string
|
||||
val dataJson = when (messageData) {
|
||||
is String -> "\"$messageData\""
|
||||
else -> messageData.toString()
|
||||
}
|
||||
|
||||
val jsCode = """
|
||||
(function() {
|
||||
window.postIntellijMessage(
|
||||
"$messageType",
|
||||
$dataJson,
|
||||
"$messageId"
|
||||
);
|
||||
return true;
|
||||
})();
|
||||
""".trimIndent()
|
||||
|
||||
browser.executeJsInBrowser(jsCode)
|
||||
}
|
||||
}
|
||||
|
||||
// Extension function for JCefBrowserFixture for easier usage
|
||||
fun JCefBrowserFixture.sendIntellijMessage(
|
||||
messageType: String,
|
||||
messageData: Any,
|
||||
messageId: String = "test-message-id"
|
||||
) {
|
||||
BrowserUtils.sendIntellijMessage(this, messageType, messageData, messageId)
|
||||
}
|
||||
|
|
@ -46,7 +46,7 @@ export class GUISelectors {
|
|||
}
|
||||
|
||||
public static getToolCallStatusMessage(view: WebView) {
|
||||
return SelectorUtils.getElementByDataTestId(view, "toggle-div-title");
|
||||
return SelectorUtils.getElementByDataTestId(view, "tool-call-title");
|
||||
}
|
||||
|
||||
public static getToolButton(view: WebView) {
|
||||
|
|
@ -89,6 +89,14 @@ export class GUISelectors {
|
|||
);
|
||||
}
|
||||
|
||||
public static getRulesPeek(view: WebView) {
|
||||
return SelectorUtils.getElementByDataTestId(view, "rules-peek");
|
||||
}
|
||||
|
||||
public static getFirstRulesPeekItem(view: WebView) {
|
||||
return SelectorUtils.getElementByDataTestId(view, "rules-peek-item");
|
||||
}
|
||||
|
||||
public static getNthHistoryTableRow(view: WebView, index: number) {
|
||||
return SelectorUtils.getElementByDataTestId(view, `history-row-${index}`);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -245,6 +245,47 @@ describe("GUI Test", () => {
|
|||
await GUIActions.selectModeFromDropdown(view, "Agent");
|
||||
});
|
||||
|
||||
it("should display rules peek and show rule details", async () => {
|
||||
// Send a message to trigger the model response
|
||||
const [messageInput] = await GUISelectors.getMessageInputFields(view);
|
||||
await messageInput.sendKeys("Hello");
|
||||
await messageInput.sendKeys(Key.ENTER);
|
||||
|
||||
// Wait for the response to appear
|
||||
await TestUtils.waitForSuccess(() =>
|
||||
GUISelectors.getThreadMessageByText(view, "I'm going to call a tool:"),
|
||||
);
|
||||
|
||||
// Verify that "1 rule" text appears
|
||||
const rulesPeek = await TestUtils.waitForSuccess(() =>
|
||||
GUISelectors.getRulesPeek(view),
|
||||
);
|
||||
const rulesPeekText = await rulesPeek.getText();
|
||||
expect(rulesPeekText).to.include("1 rule");
|
||||
|
||||
// Click on the rules peek to expand it
|
||||
await rulesPeek.click();
|
||||
|
||||
// Wait for the rule details to appear
|
||||
const ruleItem = await TestUtils.waitForSuccess(() =>
|
||||
GUISelectors.getFirstRulesPeekItem(view),
|
||||
);
|
||||
|
||||
await TestUtils.waitForSuccess(async () => {
|
||||
const text = await ruleItem.getText();
|
||||
if (!text || text.trim() === "") {
|
||||
throw new Error("Rule item text is empty");
|
||||
}
|
||||
return ruleItem;
|
||||
});
|
||||
|
||||
// Verify the rule content
|
||||
const ruleItemText = await ruleItem.getText();
|
||||
expect(ruleItemText).to.include("Assistant rule");
|
||||
expect(ruleItemText).to.include("Always applied");
|
||||
expect(ruleItemText).to.include("TEST_SYS_MSG");
|
||||
}).timeout(DEFAULT_TIMEOUT.MD);
|
||||
|
||||
it("should render tool call", async () => {
|
||||
const [messageInput] = await GUISelectors.getMessageInputFields(view);
|
||||
await messageInput.sendKeys("Hello");
|
||||
|
|
@ -258,7 +299,9 @@ describe("GUI Test", () => {
|
|||
expect(await statusMessage.getText()).contain(
|
||||
"Continue viewed the git diff",
|
||||
);
|
||||
}).timeout(DEFAULT_TIMEOUT.MD);
|
||||
// wait for 30 seconds, promise
|
||||
await new Promise((resolve) => setTimeout(resolve, 30000));
|
||||
}).timeout(DEFAULT_TIMEOUT.MD * 100);
|
||||
|
||||
it("should call tool after approval", async () => {
|
||||
await GUIActions.toggleToolPolicy(view, "builtin_view_diff", 2);
|
||||
|
|
|
|||
12
extensions/vscode/package-lock.json
generated
12
extensions/vscode/package-lock.json
generated
|
|
@ -1,12 +1,12 @@
|
|||
{
|
||||
"name": "continue",
|
||||
"version": "1.1.34",
|
||||
"version": "1.1.35",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "continue",
|
||||
"version": "1.1.34",
|
||||
"version": "1.1.35",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@continuedev/config-types": "^1.0.14",
|
||||
|
|
@ -53,7 +53,7 @@
|
|||
"svg-builder": "^2.0.0",
|
||||
"systeminformation": "^5.23.7",
|
||||
"tailwindcss": "^3.3.2",
|
||||
"undici": "^6.2.0",
|
||||
"undici": "^6.21.3",
|
||||
"uuid": "^9.0.1",
|
||||
"uuidv4": "^6.2.13",
|
||||
"vectordb": "^0.4.20",
|
||||
|
|
@ -13095,9 +13095,9 @@
|
|||
"dev": true
|
||||
},
|
||||
"node_modules/undici": {
|
||||
"version": "6.21.1",
|
||||
"resolved": "https://registry.npmjs.org/undici/-/undici-6.21.1.tgz",
|
||||
"integrity": "sha512-q/1rj5D0/zayJB2FraXdaWxbhWiNKDvu8naDT2dl1yTlvJp4BLtOcp2a5BvgGNQpYYJzau7tf1WgKv3b+7mqpQ==",
|
||||
"version": "6.21.3",
|
||||
"resolved": "https://registry.npmjs.org/undici/-/undici-6.21.3.tgz",
|
||||
"integrity": "sha512-gBLkYIlEnSp8pFbT64yFgGE6UIB9tAkhukC23PmMDCe5Nd+cRqKxSjw5y54MK2AZMgZfJWMaNE4nYUHgi1XEOw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18.17"
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
"name": "continue",
|
||||
"icon": "media/icon.png",
|
||||
"author": "Continue Dev, Inc",
|
||||
"version": "1.1.34",
|
||||
"version": "1.1.35",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/continuedev/continue"
|
||||
|
|
@ -704,7 +704,7 @@
|
|||
"svg-builder": "^2.0.0",
|
||||
"systeminformation": "^5.23.7",
|
||||
"tailwindcss": "^3.3.2",
|
||||
"undici": "^6.2.0",
|
||||
"undici": "^6.21.3",
|
||||
"uuid": "^9.0.1",
|
||||
"uuidv4": "^6.2.13",
|
||||
"vectordb": "^0.4.20",
|
||||
|
|
|
|||
|
|
@ -23,21 +23,16 @@ export interface VerticalDiffHandlerOptions {
|
|||
}
|
||||
|
||||
export class VerticalDiffHandler implements vscode.Disposable {
|
||||
public insertedInCurrentBlock = 0;
|
||||
disposables: vscode.Disposable[] = [];
|
||||
private currentLineIndex: number;
|
||||
private cancelled = false;
|
||||
private newLinesAdded = 0;
|
||||
private deletionBuffer: string[] = [];
|
||||
private removedLineDecorations: RemovedLineDecorationManager;
|
||||
private addedLineDecorations: AddedLineDecorationManager;
|
||||
|
||||
private get fileUri() {
|
||||
return this.editor.document.uri.toString();
|
||||
}
|
||||
public insertedInCurrentBlock = 0;
|
||||
public get range(): vscode.Range {
|
||||
const startLine = Math.min(this.startLine, this.endLine);
|
||||
const endLine = Math.max(this.startLine, this.endLine);
|
||||
return new vscode.Range(startLine, 0, endLine, Number.MAX_SAFE_INTEGER);
|
||||
}
|
||||
private _diffLinesQueue: DiffLine[] = [];
|
||||
private _queueLock = false;
|
||||
|
||||
constructor(
|
||||
private startLine: number,
|
||||
|
|
@ -78,156 +73,18 @@ export class VerticalDiffHandler implements vscode.Disposable {
|
|||
this.disposables.push(disposable);
|
||||
}
|
||||
|
||||
private async insertDeletionBuffer() {
|
||||
if (this.deletionBuffer.length || this.insertedInCurrentBlock > 0) {
|
||||
const blocks = this.editorToVerticalDiffCodeLens.get(this.fileUri) || [];
|
||||
|
||||
blocks.push({
|
||||
start: this.currentLineIndex - this.insertedInCurrentBlock,
|
||||
numRed: this.deletionBuffer.length,
|
||||
numGreen: this.insertedInCurrentBlock,
|
||||
});
|
||||
|
||||
this.editorToVerticalDiffCodeLens.set(this.fileUri, blocks);
|
||||
}
|
||||
|
||||
if (this.deletionBuffer.length === 0) {
|
||||
this.insertedInCurrentBlock = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
// Insert the block of deleted lines as empty new lines
|
||||
await this.insertTextAboveLine(
|
||||
this.currentLineIndex - this.insertedInCurrentBlock,
|
||||
"\n".repeat(this.deletionBuffer.length - 1),
|
||||
);
|
||||
|
||||
this.removedLineDecorations.addLines(
|
||||
this.currentLineIndex - this.insertedInCurrentBlock,
|
||||
this.deletionBuffer,
|
||||
);
|
||||
|
||||
// Shift green decorations downward
|
||||
this.addedLineDecorations.shiftDownAfterLine(
|
||||
this.currentLineIndex - this.insertedInCurrentBlock,
|
||||
this.deletionBuffer.length,
|
||||
);
|
||||
|
||||
// Update line index, clear buffer
|
||||
for (let i = 0; i < this.deletionBuffer.length; i++) {
|
||||
this.incrementCurrentLineIndex();
|
||||
}
|
||||
|
||||
this.deletionBuffer = [];
|
||||
this.insertedInCurrentBlock = 0;
|
||||
this.refreshCodeLens();
|
||||
public get range(): vscode.Range {
|
||||
const startLine = Math.min(this.startLine, this.endLine);
|
||||
const endLine = Math.max(this.startLine, this.endLine);
|
||||
return new vscode.Range(startLine, 0, endLine, Number.MAX_SAFE_INTEGER);
|
||||
}
|
||||
|
||||
private incrementCurrentLineIndex() {
|
||||
this.currentLineIndex++;
|
||||
this.updateIndexLineDecorations();
|
||||
const range = new vscode.Range(
|
||||
this.currentLineIndex,
|
||||
0,
|
||||
this.currentLineIndex,
|
||||
0,
|
||||
);
|
||||
this.editor.revealRange(range, vscode.TextEditorRevealType.Default);
|
||||
get isCancelled() {
|
||||
return this.cancelled;
|
||||
}
|
||||
|
||||
private async insertTextAboveLine(index: number, text: string) {
|
||||
await this.editor.edit(
|
||||
(editBuilder) => {
|
||||
const lineCount = this.editor.document.lineCount;
|
||||
if (index >= lineCount) {
|
||||
// Append to end of file
|
||||
editBuilder.insert(
|
||||
new vscode.Position(
|
||||
lineCount,
|
||||
this.editor.document.lineAt(lineCount - 1).text.length,
|
||||
),
|
||||
`\n${text}`,
|
||||
);
|
||||
} else {
|
||||
editBuilder.insert(new vscode.Position(index, 0), `${text}\n`);
|
||||
}
|
||||
},
|
||||
{
|
||||
undoStopAfter: false,
|
||||
undoStopBefore: false,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
private async insertLineAboveIndex(index: number, line: string) {
|
||||
await this.insertTextAboveLine(index, line);
|
||||
this.addedLineDecorations.addLine(index);
|
||||
this.newLinesAdded++;
|
||||
}
|
||||
|
||||
private async deleteLinesAt(index: number, numLines = 1) {
|
||||
const startLine = new vscode.Position(index, 0);
|
||||
await this.editor.edit(
|
||||
(editBuilder) => {
|
||||
editBuilder.delete(
|
||||
new vscode.Range(startLine, startLine.translate(numLines)),
|
||||
);
|
||||
},
|
||||
{
|
||||
undoStopAfter: false,
|
||||
undoStopBefore: false,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
private async deleteRangeLines(ranges: vscode.Range[]) {
|
||||
await this.editor.edit(
|
||||
(editBuilder) => {
|
||||
for (const range of ranges) {
|
||||
editBuilder.delete(
|
||||
new vscode.Range(
|
||||
range.start,
|
||||
new vscode.Position(range.end.line + 1, 0),
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
{
|
||||
undoStopAfter: false,
|
||||
undoStopBefore: false,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
private updateIndexLineDecorations() {
|
||||
if (this.options.instant) {
|
||||
// We don't show progress on instant apply
|
||||
return;
|
||||
}
|
||||
|
||||
// Highlight the line at the currentLineIndex
|
||||
// And lightly highlight all lines between that and endLine
|
||||
if (this.currentLineIndex - this.newLinesAdded >= this.endLine) {
|
||||
this.editor.setDecorations(indexDecorationType, []);
|
||||
this.editor.setDecorations(belowIndexDecorationType, []);
|
||||
} else {
|
||||
const start = new vscode.Position(this.currentLineIndex, 0);
|
||||
this.editor.setDecorations(indexDecorationType, [
|
||||
new vscode.Range(
|
||||
start,
|
||||
new vscode.Position(start.line, Number.MAX_SAFE_INTEGER),
|
||||
),
|
||||
]);
|
||||
const end = new vscode.Position(this.endLine, 0);
|
||||
this.editor.setDecorations(belowIndexDecorationType, [
|
||||
new vscode.Range(start.translate(1), end.translate(this.newLinesAdded)),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
private clearIndexLineDecorations() {
|
||||
this.editor.setDecorations(belowIndexDecorationType, []);
|
||||
this.editor.setDecorations(indexDecorationType, []);
|
||||
private get fileUri() {
|
||||
return this.editor.document.uri.toString();
|
||||
}
|
||||
|
||||
async clear(accept: boolean) {
|
||||
|
|
@ -258,19 +115,15 @@ export class VerticalDiffHandler implements vscode.Disposable {
|
|||
this.editor.document.getText(),
|
||||
);
|
||||
|
||||
this.cancelled = true;
|
||||
this.refreshCodeLens();
|
||||
this.dispose();
|
||||
}
|
||||
|
||||
disposables: vscode.Disposable[] = [];
|
||||
|
||||
dispose() {
|
||||
this.disposables.forEach((disposable) => disposable.dispose());
|
||||
}
|
||||
|
||||
private _diffLinesQueue: DiffLine[] = [];
|
||||
private _queueLock = false;
|
||||
|
||||
async queueDiffLine(diffLine: DiffLine | undefined) {
|
||||
if (diffLine) {
|
||||
this._diffLinesQueue.push(diffLine);
|
||||
|
|
@ -300,25 +153,6 @@ export class VerticalDiffHandler implements vscode.Disposable {
|
|||
this._queueLock = false;
|
||||
}
|
||||
|
||||
private async _handleDiffLine(diffLine: DiffLine) {
|
||||
switch (diffLine.type) {
|
||||
case "same":
|
||||
await this.insertDeletionBuffer();
|
||||
this.incrementCurrentLineIndex();
|
||||
break;
|
||||
case "old":
|
||||
// Add to deletion buffer and delete the line for now
|
||||
this.deletionBuffer.push(diffLine.line);
|
||||
await this.deleteLinesAt(this.currentLineIndex);
|
||||
break;
|
||||
case "new":
|
||||
await this.insertLineAboveIndex(this.currentLineIndex, diffLine.line);
|
||||
this.incrementCurrentLineIndex();
|
||||
this.insertedInCurrentBlock++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
async run(diffLineGenerator: AsyncGenerator<DiffLine>) {
|
||||
let diffLines = [];
|
||||
|
||||
|
|
@ -327,6 +161,9 @@ export class VerticalDiffHandler implements vscode.Disposable {
|
|||
this.updateIndexLineDecorations();
|
||||
|
||||
for await (const diffLine of diffLineGenerator) {
|
||||
if (this.isCancelled) {
|
||||
return;
|
||||
}
|
||||
diffLines.push(diffLine);
|
||||
await this.queueDiffLine(diffLine);
|
||||
}
|
||||
|
|
@ -337,7 +174,10 @@ export class VerticalDiffHandler implements vscode.Disposable {
|
|||
await this.reapplyWithMyersDiff(diffLines);
|
||||
|
||||
const range = new vscode.Range(this.startLine, 0, this.startLine, 0);
|
||||
this.editor.revealRange(range, vscode.TextEditorRevealType.Default);
|
||||
this.editor.revealRange(
|
||||
range,
|
||||
vscode.TextEditorRevealType.Default,
|
||||
);
|
||||
|
||||
this.options.onStatusUpdate(
|
||||
"done",
|
||||
|
|
@ -411,23 +251,6 @@ export class VerticalDiffHandler implements vscode.Disposable {
|
|||
}
|
||||
}
|
||||
|
||||
private shiftCodeLensObjects(startLine: number, offset: number) {
|
||||
// Shift the codelens objects
|
||||
const blocks =
|
||||
this.editorToVerticalDiffCodeLens
|
||||
.get(this.fileUri)
|
||||
?.filter((x) => x.start !== startLine)
|
||||
.map((x) => {
|
||||
if (x.start > startLine) {
|
||||
return { ...x, start: x.start + offset };
|
||||
}
|
||||
return x;
|
||||
}) || [];
|
||||
this.editorToVerticalDiffCodeLens.set(this.fileUri, blocks);
|
||||
|
||||
this.refreshCodeLens();
|
||||
}
|
||||
|
||||
public updateLineDelta(
|
||||
fileUri: string,
|
||||
startLine: number,
|
||||
|
|
@ -551,4 +374,190 @@ export class VerticalDiffHandler implements vscode.Disposable {
|
|||
this.editorToVerticalDiffCodeLens.set(this.fileUri, codeLensBlocks);
|
||||
this.refreshCodeLens();
|
||||
}
|
||||
|
||||
private async insertDeletionBuffer() {
|
||||
if (this.deletionBuffer.length || this.insertedInCurrentBlock > 0) {
|
||||
const blocks = this.editorToVerticalDiffCodeLens.get(this.fileUri) || [];
|
||||
|
||||
blocks.push({
|
||||
start: this.currentLineIndex - this.insertedInCurrentBlock,
|
||||
numRed: this.deletionBuffer.length,
|
||||
numGreen: this.insertedInCurrentBlock,
|
||||
});
|
||||
|
||||
this.editorToVerticalDiffCodeLens.set(this.fileUri, blocks);
|
||||
}
|
||||
|
||||
if (this.deletionBuffer.length === 0) {
|
||||
this.insertedInCurrentBlock = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
// Insert the block of deleted lines as empty new lines
|
||||
await this.insertTextAboveLine(
|
||||
this.currentLineIndex - this.insertedInCurrentBlock,
|
||||
"\n".repeat(this.deletionBuffer.length - 1),
|
||||
);
|
||||
|
||||
this.removedLineDecorations.addLines(
|
||||
this.currentLineIndex - this.insertedInCurrentBlock,
|
||||
this.deletionBuffer,
|
||||
);
|
||||
|
||||
// Shift green decorations downward
|
||||
this.addedLineDecorations.shiftDownAfterLine(
|
||||
this.currentLineIndex - this.insertedInCurrentBlock,
|
||||
this.deletionBuffer.length,
|
||||
);
|
||||
|
||||
// Update line index, clear buffer
|
||||
for (let i = 0; i < this.deletionBuffer.length; i++) {
|
||||
this.incrementCurrentLineIndex();
|
||||
}
|
||||
|
||||
this.deletionBuffer = [];
|
||||
this.insertedInCurrentBlock = 0;
|
||||
this.refreshCodeLens();
|
||||
}
|
||||
|
||||
private incrementCurrentLineIndex() {
|
||||
this.currentLineIndex++;
|
||||
this.updateIndexLineDecorations();
|
||||
const range = new vscode.Range(this.currentLineIndex, 0, this.currentLineIndex, 0);
|
||||
this.editor.revealRange(
|
||||
range,
|
||||
vscode.TextEditorRevealType.Default,
|
||||
);
|
||||
}
|
||||
|
||||
private async insertTextAboveLine(index: number, text: string) {
|
||||
await this.editor.edit(
|
||||
(editBuilder) => {
|
||||
const lineCount = this.editor.document.lineCount;
|
||||
if (index >= lineCount) {
|
||||
// Append to end of file
|
||||
editBuilder.insert(
|
||||
new vscode.Position(
|
||||
lineCount,
|
||||
this.editor.document.lineAt(lineCount - 1).text.length,
|
||||
),
|
||||
`\n${text}`,
|
||||
);
|
||||
} else {
|
||||
editBuilder.insert(new vscode.Position(index, 0), `${text}\n`);
|
||||
}
|
||||
},
|
||||
{
|
||||
undoStopAfter: false,
|
||||
undoStopBefore: false,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
private async insertLineAboveIndex(index: number, line: string) {
|
||||
await this.insertTextAboveLine(index, line);
|
||||
this.addedLineDecorations.addLine(index);
|
||||
this.newLinesAdded++;
|
||||
}
|
||||
|
||||
private async deleteLinesAt(index: number, numLines = 1) {
|
||||
const startLine = new vscode.Position(index, 0);
|
||||
await this.editor.edit(
|
||||
(editBuilder) => {
|
||||
editBuilder.delete(
|
||||
new vscode.Range(startLine, startLine.translate(numLines)),
|
||||
);
|
||||
},
|
||||
{
|
||||
undoStopAfter: false,
|
||||
undoStopBefore: false,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
private async deleteRangeLines(ranges: vscode.Range[]) {
|
||||
await this.editor.edit(
|
||||
(editBuilder) => {
|
||||
for (const range of ranges) {
|
||||
editBuilder.delete(
|
||||
new vscode.Range(
|
||||
range.start,
|
||||
new vscode.Position(range.end.line + 1, 0),
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
{
|
||||
undoStopAfter: false,
|
||||
undoStopBefore: false,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
private updateIndexLineDecorations() {
|
||||
if (this.options.instant) {
|
||||
// We don't show progress on instant apply
|
||||
return;
|
||||
}
|
||||
|
||||
// Highlight the line at the currentLineIndex
|
||||
// And lightly highlight all lines between that and endLine
|
||||
if (this.currentLineIndex - this.newLinesAdded >= this.endLine) {
|
||||
this.editor.setDecorations(indexDecorationType, []);
|
||||
this.editor.setDecorations(belowIndexDecorationType, []);
|
||||
} else {
|
||||
const start = new vscode.Position(this.currentLineIndex, 0);
|
||||
this.editor.setDecorations(indexDecorationType, [
|
||||
new vscode.Range(
|
||||
start,
|
||||
new vscode.Position(start.line, Number.MAX_SAFE_INTEGER),
|
||||
),
|
||||
]);
|
||||
const end = new vscode.Position(this.endLine, 0);
|
||||
this.editor.setDecorations(belowIndexDecorationType, [
|
||||
new vscode.Range(start.translate(1), end.translate(this.newLinesAdded)),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
private clearIndexLineDecorations() {
|
||||
this.editor.setDecorations(belowIndexDecorationType, []);
|
||||
this.editor.setDecorations(indexDecorationType, []);
|
||||
}
|
||||
|
||||
private async _handleDiffLine(diffLine: DiffLine) {
|
||||
switch (diffLine.type) {
|
||||
case "same":
|
||||
await this.insertDeletionBuffer();
|
||||
this.incrementCurrentLineIndex();
|
||||
break;
|
||||
case "old":
|
||||
// Add to deletion buffer and delete the line for now
|
||||
this.deletionBuffer.push(diffLine.line);
|
||||
await this.deleteLinesAt(this.currentLineIndex);
|
||||
break;
|
||||
case "new":
|
||||
await this.insertLineAboveIndex(this.currentLineIndex, diffLine.line);
|
||||
this.incrementCurrentLineIndex();
|
||||
this.insertedInCurrentBlock++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private shiftCodeLensObjects(startLine: number, offset: number) {
|
||||
// Shift the codelens objects
|
||||
const blocks =
|
||||
this.editorToVerticalDiffCodeLens
|
||||
.get(this.fileUri)
|
||||
?.filter((x) => x.start !== startLine)
|
||||
.map((x) => {
|
||||
if (x.start > startLine) {
|
||||
return { ...x, start: x.start + offset };
|
||||
}
|
||||
return x;
|
||||
}) || [];
|
||||
this.editorToVerticalDiffCodeLens.set(this.fileUri, blocks);
|
||||
|
||||
this.refreshCodeLens();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ import {
|
|||
import { stripImages } from "core/util/messageContent";
|
||||
import * as vscode from "vscode";
|
||||
|
||||
import { DataLogger } from "core/data/log";
|
||||
import { EDIT_MODE_STREAM_ID } from "core/edit/constants";
|
||||
import { ApplyManager } from "../apply";
|
||||
import { VerticalDiffManager } from "../diff/vertical/manager";
|
||||
|
|
@ -228,6 +229,18 @@ export class VsCodeMessenger {
|
|||
),
|
||||
rulesToInclude: config.rules,
|
||||
});
|
||||
|
||||
// Log dev data
|
||||
await DataLogger.getInstance().logDevData({
|
||||
name: "editInteraction",
|
||||
data: {
|
||||
prompt: stripImages(prompt),
|
||||
completion: fileAfterEdit ?? "",
|
||||
modelProvider: model.providerName,
|
||||
modelTitle: model.title ?? "",
|
||||
},
|
||||
});
|
||||
|
||||
return fileAfterEdit;
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ export default function AcceptRejectAllButtons({
|
|||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
|
||||
const tinyFont = useFontSize(-3);
|
||||
|
||||
async function handleAcceptOrReject(status: AcceptOrRejectOutcome) {
|
||||
for (const { filepath = "", streamId } of pendingApplyStates) {
|
||||
ideMessenger.post(status, {
|
||||
|
|
@ -1,6 +1,5 @@
|
|||
import { CheckIcon, PlayIcon, XMarkIcon } from "@heroicons/react/24/outline";
|
||||
import { ApplyState } from "core";
|
||||
import { useEffect, useState } from "react";
|
||||
import { getMetaKeyLabel } from "../../../util";
|
||||
import Spinner from "../../gui/Spinner";
|
||||
import { ToolTip } from "../../gui/Tooltip";
|
||||
|
|
@ -16,47 +15,10 @@ interface ApplyActionsProps {
|
|||
}
|
||||
|
||||
export function ApplyActions(props: ApplyActionsProps) {
|
||||
const [hasRejected, setHasRejected] = useState(false);
|
||||
const [showApplied, setShowApplied] = useState(false);
|
||||
const isClosed = props.applyState?.status === "closed";
|
||||
const isSuccessful = !hasRejected && props.applyState?.numDiffs === 0;
|
||||
|
||||
useEffect(() => {
|
||||
if (isClosed && isSuccessful) {
|
||||
setShowApplied(true);
|
||||
const timer = setTimeout(() => {
|
||||
setShowApplied(false);
|
||||
}, 3_000);
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
}, [isClosed, isSuccessful]);
|
||||
|
||||
function onClickReject() {
|
||||
props.onClickReject();
|
||||
setHasRejected(true);
|
||||
}
|
||||
|
||||
const applyButton = (text: string) => (
|
||||
<HoverItem
|
||||
data-tooltip-id="codeblock-apply-code-button-tooltip"
|
||||
className="!p-0"
|
||||
>
|
||||
<button
|
||||
data-testid="codeblock-toolbar-apply"
|
||||
className="text-lightgray text-[${vscForeground}] flex cursor-pointer items-center border-none bg-transparent pl-0 text-xs outline-none hover:brightness-125"
|
||||
onClick={props.onClickApply}
|
||||
>
|
||||
<div className="text-lightgray flex items-center gap-1">
|
||||
<PlayIcon className="h-3.5 w-3.5" />
|
||||
<span className="xs:inline hidden">{text}</span>
|
||||
</div>
|
||||
</button>
|
||||
<ToolTip id="codeblock-apply-code-button-tooltip" place="top">
|
||||
{text} Code
|
||||
</ToolTip>
|
||||
</HoverItem>
|
||||
);
|
||||
|
||||
switch (props.applyState ? props.applyState.status : null) {
|
||||
case "streaming":
|
||||
return (
|
||||
|
|
@ -94,21 +56,30 @@ export function ApplyActions(props: ApplyActionsProps) {
|
|||
</div>
|
||||
);
|
||||
case "closed":
|
||||
if (isSuccessful) {
|
||||
if (showApplied || props.disableManualApply) {
|
||||
return (
|
||||
<span className="flex select-none items-center rounded bg-zinc-700 text-slate-400 max-sm:px-0.5 sm:pl-2">
|
||||
<span className="max-sm:hidden">Applied</span>
|
||||
<CheckIcon className="h-3.5 w-3.5 hover:brightness-125 sm:px-1" />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return applyButton("Reapply");
|
||||
}
|
||||
default:
|
||||
if (props.disableManualApply) {
|
||||
return null;
|
||||
}
|
||||
return applyButton("Apply");
|
||||
|
||||
return (
|
||||
<HoverItem
|
||||
data-tooltip-id="codeblock-apply-code-button-tooltip"
|
||||
className="!p-0"
|
||||
>
|
||||
<button
|
||||
data-testid="codeblock-toolbar-apply"
|
||||
className="text-lightgray text-[${vscForeground}] flex cursor-pointer items-center border-none bg-transparent pl-0 text-xs outline-none hover:brightness-125"
|
||||
onClick={props.onClickApply}
|
||||
>
|
||||
<div className="text-lightgray flex items-center gap-1">
|
||||
<PlayIcon className="h-3.5 w-3.5" />
|
||||
<span className="xs:inline hidden">Apply</span>
|
||||
</div>
|
||||
</button>
|
||||
<ToolTip id="codeblock-apply-code-button-tooltip" place="top">
|
||||
Apply Code
|
||||
</ToolTip>
|
||||
</HoverItem>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,15 +6,21 @@ interface ToggleProps {
|
|||
children: React.ReactNode;
|
||||
title: React.ReactNode;
|
||||
icon?: ComponentType<React.SVGProps<SVGSVGElement>>;
|
||||
testId?: string;
|
||||
}
|
||||
|
||||
function ToggleDiv({ children, title, icon: Icon }: ToggleProps) {
|
||||
function ToggleDiv({
|
||||
children,
|
||||
title,
|
||||
icon: Icon,
|
||||
testId = "context-items-peek",
|
||||
}: ToggleProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [isHovered, setIsHovered] = useState(false);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`pl-2 pt-2`}
|
||||
className={`pl-2`}
|
||||
style={{
|
||||
backgroundColor: vscBackground,
|
||||
}}
|
||||
|
|
@ -24,7 +30,7 @@ function ToggleDiv({ children, title, icon: Icon }: ToggleProps) {
|
|||
onClick={() => setOpen((prev) => !prev)}
|
||||
onMouseEnter={() => setIsHovered(true)}
|
||||
onMouseLeave={() => setIsHovered(false)}
|
||||
data-testid="context-items-peek"
|
||||
data-testid={testId}
|
||||
>
|
||||
<div className="relative mr-1 h-4 w-4">
|
||||
{Icon && !isHovered && !open ? (
|
||||
|
|
@ -44,10 +50,7 @@ function ToggleDiv({ children, title, icon: Icon }: ToggleProps) {
|
|||
</>
|
||||
)}
|
||||
</div>
|
||||
<span
|
||||
className="ml-1 text-xs text-gray-400 transition-colors duration-200"
|
||||
data-testid="toggle-div-title"
|
||||
>
|
||||
<span className="ml-1 text-xs text-gray-400 transition-colors duration-200">
|
||||
{title}
|
||||
</span>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { ChevronRightIcon, XMarkIcon } from "@heroicons/react/24/outline";
|
||||
import { CodeToEdit } from "core";
|
||||
import { SetCodeToEditPayload } from "core";
|
||||
import { getMarkdownLanguageTagForFile } from "core/util";
|
||||
import { getUriPathBasename } from "core/util/uri";
|
||||
import { useContext, useMemo, useState } from "react";
|
||||
|
|
@ -26,7 +26,7 @@ const NoPaddingWrapper = styled.div`
|
|||
`;
|
||||
|
||||
interface CodeToEditItemProps {
|
||||
code: CodeToEdit;
|
||||
code: SetCodeToEditPayload;
|
||||
}
|
||||
|
||||
function CodeToEditItem({ code }: CodeToEditItemProps) {
|
||||
|
|
@ -143,6 +143,7 @@ function CodeToEditItem({ code }: CodeToEditItemProps) {
|
|||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function CodeToEditCard() {
|
||||
// Array from previous multi-file edit
|
||||
const codeToEditArray = useAppSelector(
|
||||
|
|
|
|||
|
|
@ -1,11 +1,12 @@
|
|||
import { Editor, JSONContent } from "@tiptap/react";
|
||||
import { ContextItemWithId, InputModifiers } from "core";
|
||||
import { ContextItemWithId, InputModifiers, RuleWithSource } from "core";
|
||||
import { useMemo } from "react";
|
||||
import styled, { keyframes } from "styled-components";
|
||||
import { defaultBorderRadius, vscBackground } from "..";
|
||||
import { useAppSelector } from "../../redux/hooks";
|
||||
import { selectSlashCommandComboBoxInputs } from "../../redux/selectors";
|
||||
import { ContextItemsPeek } from "./belowMainInput/ContextItemsPeek";
|
||||
import { RulesPeek } from "./belowMainInput/RulesPeek";
|
||||
import { ToolbarOptions } from "./InputToolbar";
|
||||
import { Lump } from "./Lump";
|
||||
import { TipTapEditor } from "./TipTapEditor";
|
||||
|
|
@ -20,6 +21,7 @@ interface ContinueInputBoxProps {
|
|||
) => void;
|
||||
editorState?: JSONContent;
|
||||
contextItems?: ContextItemWithId[];
|
||||
appliedRules?: RuleWithSource[];
|
||||
hidden?: boolean;
|
||||
inputId: string; // used to keep track of things per input in redux
|
||||
}
|
||||
|
|
@ -116,6 +118,8 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
|
|||
}
|
||||
: {};
|
||||
|
||||
const { appliedRules = [], contextItems = [] } = props;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`${props.hidden ? "hidden" : ""}`}
|
||||
|
|
@ -143,10 +147,15 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
|
|||
/>
|
||||
</GradientBorder>
|
||||
</div>
|
||||
<ContextItemsPeek
|
||||
contextItems={props.contextItems}
|
||||
isCurrentContextPeek={props.isLastUserInput}
|
||||
/>
|
||||
{(appliedRules.length > 0 || contextItems.length > 0) && (
|
||||
<div className="mt-2 flex flex-col">
|
||||
<RulesPeek appliedRules={props.appliedRules} />
|
||||
<ContextItemsPeek
|
||||
contextItems={props.contextItems}
|
||||
isCurrentContextPeek={props.isLastUserInput}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import { useContext } from "react";
|
|||
import { IdeMessengerContext } from "../../context/IdeMessenger";
|
||||
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
|
||||
import { exitEditMode } from "../../redux/thunks/editMode";
|
||||
import AcceptRejectAllButtons from "../AcceptRejectAllButtons";
|
||||
import AcceptRejectDiffButtons from "../AcceptRejectDiffButtons";
|
||||
import { useMainEditor } from "./TipTapEditor";
|
||||
|
||||
const EditModeDetails = () => {
|
||||
|
|
@ -28,7 +28,7 @@ const EditModeDetails = () => {
|
|||
<div className="flex flex-col items-center justify-center pb-1 pt-3 text-xs italic text-gray-400">
|
||||
<span className="">{`${editApplyState.numDiffs} diff${plural} remaining`}</span>
|
||||
</div>
|
||||
<AcceptRejectAllButtons
|
||||
<AcceptRejectDiffButtons
|
||||
applyStates={[editApplyState]}
|
||||
onAcceptOrReject={async (outcome) => {
|
||||
if (outcome === "acceptDiff") {
|
||||
|
|
|
|||
122
gui/src/components/mainInput/belowMainInput/RulesPeek.tsx
Normal file
122
gui/src/components/mainInput/belowMainInput/RulesPeek.tsx
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
import { DocumentTextIcon, GlobeAltIcon } from "@heroicons/react/24/outline";
|
||||
import { RuleSource, RuleWithSource } from "core";
|
||||
import { ComponentType, useMemo, useState } from "react";
|
||||
import ToggleDiv from "../../ToggleDiv";
|
||||
|
||||
interface RulesPeekProps {
|
||||
appliedRules?: RuleWithSource[];
|
||||
icon?: ComponentType<React.SVGProps<SVGSVGElement>>;
|
||||
}
|
||||
|
||||
interface RulesPeekItemProps {
|
||||
rule: RuleWithSource;
|
||||
}
|
||||
|
||||
// Convert technical source to user-friendly text
|
||||
const getSourceLabel = (source: RuleSource): string => {
|
||||
switch (source) {
|
||||
case "default-chat":
|
||||
return "Default Chat";
|
||||
case "default-agent":
|
||||
return "Default Agent";
|
||||
case "model-chat-options":
|
||||
return "Model Chat Options";
|
||||
case "model-agent-options":
|
||||
return "Model Agent Options";
|
||||
case "rules-block":
|
||||
return "Rules Block";
|
||||
case "json-systemMessage":
|
||||
return "System Message";
|
||||
case ".continuerules":
|
||||
return "Project Rules";
|
||||
default:
|
||||
return source;
|
||||
}
|
||||
};
|
||||
|
||||
export function RulesPeekItem({ rule }: RulesPeekItemProps) {
|
||||
const isGlobal = !rule.globs;
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
|
||||
// Define maximum length for rule text display
|
||||
const maxRuleLength = 100;
|
||||
const isRuleLong = rule.rule.length > maxRuleLength;
|
||||
|
||||
// Get the displayed rule text based on expanded state
|
||||
const displayedRule =
|
||||
isRuleLong && !expanded
|
||||
? `${rule.rule.slice(0, maxRuleLength)}...`
|
||||
: rule.rule;
|
||||
|
||||
const toggleExpand = () => {
|
||||
if (isRuleLong) {
|
||||
setExpanded(!expanded);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`group mr-2 flex flex-col overflow-hidden rounded px-1.5 py-1 text-xs hover:bg-white/10 ${isRuleLong ? "cursor-pointer hover:text-gray-200" : ""}`}
|
||||
data-testid="rules-peek-item"
|
||||
onClick={toggleExpand}
|
||||
>
|
||||
<div className="flex w-full items-center">
|
||||
{isGlobal ? (
|
||||
<GlobeAltIcon className="mr-2 h-4 w-4 flex-shrink-0 text-gray-400" />
|
||||
) : (
|
||||
<DocumentTextIcon className="mr-2 h-4 w-4 flex-shrink-0 text-gray-400" />
|
||||
)}
|
||||
|
||||
<div className="flex min-w-0 flex-1 gap-2 text-xs">
|
||||
<div className="max-w-[50%] flex-shrink-0 truncate font-medium">
|
||||
{rule.name || "Assistant rule"}
|
||||
</div>
|
||||
|
||||
<div className="min-w-0 flex-1 overflow-hidden truncate whitespace-nowrap text-xs text-gray-500">
|
||||
{isGlobal
|
||||
? "Always applied"
|
||||
: `Pattern: ${typeof rule.globs === "string" ? rule.globs : Array.isArray(rule.globs) ? rule.globs.join(", ") : ""}`}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
className={`mt-1 whitespace-pre-line pl-6 pr-2 text-xs italic text-gray-300`}
|
||||
title={
|
||||
isRuleLong ? (expanded ? "Click to collapse" : "Click to expand") : ""
|
||||
}
|
||||
>
|
||||
{displayedRule}
|
||||
{isRuleLong && (
|
||||
<span className="ml-1 text-gray-400 opacity-0 transition-opacity group-hover:opacity-100">
|
||||
{expanded ? "(collapse)" : "(expand)"}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-1 pl-6 pr-2 text-xs text-gray-500">
|
||||
Source: {getSourceLabel(rule.source)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function RulesPeek({ appliedRules, icon }: RulesPeekProps) {
|
||||
const rules = useMemo(() => {
|
||||
return appliedRules ?? [];
|
||||
}, [appliedRules]);
|
||||
|
||||
if (!rules || rules.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<ToggleDiv
|
||||
icon={icon}
|
||||
title={`${rules.length} rule${rules.length > 1 ? "s" : ""}`}
|
||||
testId="rules-peek"
|
||||
>
|
||||
{rules.map((rule, idx) => (
|
||||
<RulesPeekItem key={`rule-${idx}`} rule={rule} />
|
||||
))}
|
||||
</ToggleDiv>
|
||||
);
|
||||
}
|
||||
|
|
@ -173,17 +173,24 @@ function ModeSelect() {
|
|||
{mode === "chat" && <CheckIcon className="ml-auto h-3 w-3" />}
|
||||
</ListboxOption>
|
||||
|
||||
<ListboxOption value="agent" disabled={!agentModeSupported}>
|
||||
<ListboxOption
|
||||
value="agent"
|
||||
disabled={!agentModeSupported}
|
||||
className={"gap-1"}
|
||||
>
|
||||
<div className="flex flex-row items-center gap-1.5">
|
||||
<SparklesIcon className="h-3 w-3" />
|
||||
<span className="">Agent</span>
|
||||
</div>
|
||||
{mode === "agent" && <CheckIcon className="ml-auto h-3 w-3" />}
|
||||
{!agentModeSupported && <span> (Not supported)</span>}
|
||||
{agentModeSupported ? (
|
||||
mode === "agent" && <CheckIcon className="ml-auto h-3 w-3" />
|
||||
) : (
|
||||
<span>(Not supported)</span>
|
||||
)}
|
||||
</ListboxOption>
|
||||
|
||||
<div className="text-lightgray px-2 py-1">
|
||||
{metaKeyLabel}. for next mode
|
||||
{`${metaKeyLabel} . for next mode`}
|
||||
</div>
|
||||
</ListboxOptions>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -166,7 +166,11 @@ function ModelSelect() {
|
|||
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === "'" && isMetaEquivalentKeyPressed(event as any)) {
|
||||
if (
|
||||
event.key === "'" &&
|
||||
isMetaEquivalentKeyPressed(event as any) &&
|
||||
!event.shiftKey // To prevent collisions w/ assistant toggle logic
|
||||
) {
|
||||
if (!selectedProfile) {
|
||||
return;
|
||||
}
|
||||
|
|
@ -179,7 +183,7 @@ function ModelSelect() {
|
|||
if (nextIndex < 0) nextIndex = options.length - 1;
|
||||
const newModelTitle = options[nextIndex].value;
|
||||
|
||||
dispatch(
|
||||
void dispatch(
|
||||
updateSelectedModelByRole({
|
||||
selectedProfile,
|
||||
role: "chat",
|
||||
|
|
@ -219,7 +223,7 @@ function ModelSelect() {
|
|||
<Listbox
|
||||
onChange={async (val: string) => {
|
||||
if (val === selectedModel?.title) return;
|
||||
dispatch(
|
||||
void dispatch(
|
||||
updateSelectedModelByRole({
|
||||
selectedProfile,
|
||||
role: mode === "edit" ? "edit" : "chat",
|
||||
|
|
|
|||
|
|
@ -19,7 +19,6 @@ export const LocalStorageProvider: React.FC<{ children: React.ReactNode }> = ({
|
|||
const [values, setValues] = useState<LocalStorageType>(DEFAULT_LOCAL_STORAGE);
|
||||
|
||||
// TODO setvalue
|
||||
|
||||
useEffect(() => {
|
||||
const isJetbrains = getLocalStorage("ide") === "jetbrains";
|
||||
let fontSize = getLocalStorage("fontSize") ?? (isJetbrains ? 15 : 14);
|
||||
|
|
|
|||
|
|
@ -20,6 +20,15 @@ export function HelpCenterSection() {
|
|||
<div className="py-5">
|
||||
<h3 className="mb-4 mt-0 text-xl">Help center</h3>
|
||||
<div className="-mx-4 flex flex-col">
|
||||
<MoreHelpRow
|
||||
title="Continue Hub"
|
||||
description="Visit hub.continue.dev to explore custom assistants and blocks"
|
||||
Icon={ArrowTopRightOnSquareIcon}
|
||||
onClick={() =>
|
||||
ideMessenger.post("openUrl", "https://hub.continue.dev/")
|
||||
}
|
||||
/>
|
||||
|
||||
<MoreHelpRow
|
||||
title="Documentation"
|
||||
description="Learn how to configure and use Continue"
|
||||
|
|
|
|||
|
|
@ -1,8 +1,6 @@
|
|||
import {
|
||||
ArrowLeftIcon,
|
||||
ChatBubbleOvalLeftIcon,
|
||||
CodeBracketSquareIcon,
|
||||
ExclamationTriangleIcon,
|
||||
} from "@heroicons/react/24/outline";
|
||||
import { Editor, JSONContent } from "@tiptap/react";
|
||||
import { InputModifiers } from "core";
|
||||
|
|
@ -20,7 +18,6 @@ import {
|
|||
import { ErrorBoundary } from "react-error-boundary";
|
||||
import styled from "styled-components";
|
||||
import { Button, lightGray, vscBackground } from "../../components";
|
||||
import AcceptRejectAllButtons from "../../components/AcceptRejectAllButtons";
|
||||
import FeedbackDialog from "../../components/dialogs/FeedbackDialog";
|
||||
import FreeTrialOverDialog from "../../components/dialogs/FreeTrialOverDialog";
|
||||
import { useFindWidget } from "../../components/find/FindWidget";
|
||||
|
|
@ -50,7 +47,7 @@ import {
|
|||
import { cancelStream } from "../../redux/thunks/cancelStream";
|
||||
import { streamEditThunk } from "../../redux/thunks/editMode";
|
||||
import { loadLastSession } from "../../redux/thunks/session";
|
||||
import { streamResponseThunk } from "../../redux/thunks/streamResponse";
|
||||
import { streamResponseThunk } from "../../redux/thunks";
|
||||
import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util";
|
||||
import {
|
||||
FREE_TRIAL_LIMIT_REQUESTS,
|
||||
|
|
@ -64,6 +61,7 @@ import { EmptyChatBody } from "./EmptyChatBody";
|
|||
import { ExploreDialogWatcher } from "./ExploreDialogWatcher";
|
||||
import { ToolCallDiv } from "./ToolCallDiv";
|
||||
import { useAutoScroll } from "./useAutoScroll";
|
||||
import AcceptRejectDiffButtons from "../../components/AcceptRejectDiffButtons";
|
||||
|
||||
const StepsDiv = styled.div`
|
||||
position: relative;
|
||||
|
|
@ -74,7 +72,7 @@ const StepsDiv = styled.div`
|
|||
}
|
||||
|
||||
.thread-message {
|
||||
margin: 0px 0px 0px 1px;
|
||||
margin: 0 0 0 1px;
|
||||
}
|
||||
`;
|
||||
|
||||
|
|
@ -112,7 +110,7 @@ export function Chat() {
|
|||
(store) => store.config?.config.selectedModelByRole,
|
||||
);
|
||||
const isStreaming = useAppSelector((state) => state.session.isStreaming);
|
||||
const [stepsOpen, setStepsOpen] = useState<(boolean | undefined)[]>([]);
|
||||
const [stepsOpen] = useState<(boolean | undefined)[]>([]);
|
||||
const mainTextInputRef = useRef<HTMLInputElement>(null);
|
||||
const stepsDivRef = useRef<HTMLDivElement>(null);
|
||||
const history = useAppSelector((state) => state.session.history);
|
||||
|
|
@ -134,6 +132,8 @@ export function Chat() {
|
|||
return isJetBrains();
|
||||
}, []);
|
||||
|
||||
useAutoScroll(stepsDivRef, history);
|
||||
|
||||
useEffect(() => {
|
||||
// Cmd + Backspace to delete current step
|
||||
const listener = (e: any) => {
|
||||
|
|
@ -201,7 +201,7 @@ export function Chat() {
|
|||
if (newCount >= FREE_TRIAL_LIMIT_REQUESTS) {
|
||||
// Show this message whether using platform or not
|
||||
// So that something happens if in new chat
|
||||
ideMessenger.ide.showToast(
|
||||
void ideMessenger.ide.showToast(
|
||||
"error",
|
||||
"You've reached the free trial limit. Please configure a model to continue.",
|
||||
);
|
||||
|
|
@ -285,8 +285,6 @@ export function Chat() {
|
|||
|
||||
const showScrollbar = showChatScrollbar ?? window.innerHeight > 5000;
|
||||
|
||||
useAutoScroll(stepsDivRef, history);
|
||||
|
||||
return (
|
||||
<>
|
||||
{widget}
|
||||
|
|
@ -302,7 +300,7 @@ export function Chat() {
|
|||
<div
|
||||
key={item.message.id}
|
||||
style={{
|
||||
minHeight: index === history.length - 1 ? "25vh" : 0,
|
||||
minHeight: index === history.length - 1 ? "200px" : 0,
|
||||
}}
|
||||
>
|
||||
<ErrorBoundary
|
||||
|
|
@ -321,6 +319,7 @@ export function Chat() {
|
|||
isMainInput={false}
|
||||
editorState={item.editorState}
|
||||
contextItems={item.contextItems}
|
||||
appliedRules={item.appliedRules}
|
||||
inputId={item.message.id}
|
||||
/>
|
||||
</>
|
||||
|
|
@ -356,23 +355,11 @@ export function Chat() {
|
|||
<TimelineItem
|
||||
item={item}
|
||||
iconElement={
|
||||
false ? (
|
||||
<CodeBracketSquareIcon width="16px" height="16px" />
|
||||
) : false ? (
|
||||
<ExclamationTriangleIcon
|
||||
width="16px"
|
||||
height="16px"
|
||||
color="red"
|
||||
/>
|
||||
) : (
|
||||
<ChatBubbleOvalLeftIcon width="16px" height="16px" />
|
||||
)
|
||||
<ChatBubbleOvalLeftIcon width="16px" height="16px" />
|
||||
}
|
||||
open={
|
||||
typeof stepsOpen[index] === "undefined"
|
||||
? false
|
||||
? false
|
||||
: true
|
||||
? true
|
||||
: stepsOpen[index]!
|
||||
}
|
||||
onToggle={() => {}}
|
||||
|
|
@ -392,7 +379,7 @@ export function Chat() {
|
|||
<div className={"relative"}>
|
||||
<>
|
||||
{!isStreaming && mode !== "edit" && (
|
||||
<AcceptRejectAllButtons
|
||||
<AcceptRejectDiffButtons
|
||||
applyStates={applyStates}
|
||||
onAcceptOrReject={async () => {}}
|
||||
/>
|
||||
|
|
|
|||
|
|
@ -61,7 +61,7 @@ export function SimpleToolCallUI({
|
|||
</div>
|
||||
<span
|
||||
className="ml-1 text-xs text-gray-400 transition-colors duration-200"
|
||||
data-testid="toggle-div-title"
|
||||
data-testid="tool-call-title"
|
||||
>
|
||||
<ToolCallStatusMessage tool={tool} toolCallState={toolCallState} />
|
||||
</span>
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
import { Tool, ToolCallState } from "core";
|
||||
import Mustache from "mustache";
|
||||
import { ReactNode } from "react";
|
||||
import { getFontSize } from "../../../util";
|
||||
import { useFontSize } from "../../../components/ui/font";
|
||||
|
||||
interface ToolCallStatusMessageProps {
|
||||
tool: Tool | undefined;
|
||||
|
|
@ -11,6 +13,7 @@ export function ToolCallStatusMessage({
|
|||
tool,
|
||||
toolCallState,
|
||||
}: ToolCallStatusMessageProps) {
|
||||
const fontSize = useFontSize();
|
||||
if (!tool) return "Agent tool use";
|
||||
|
||||
const defaultToolDescription = (
|
||||
|
|
@ -65,7 +68,7 @@ export function ToolCallStatusMessage({
|
|||
message = futureMessage;
|
||||
}
|
||||
return (
|
||||
<div className="block">
|
||||
<div className="block" style={{ fontSize }}>
|
||||
<span>Continue</span> {intro} {message}
|
||||
</div>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,16 +1,24 @@
|
|||
import { useEffect, useState } from "react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { ChatHistoryItemWithMessageId } from "../../redux/slices/sessionSlice";
|
||||
|
||||
/**
|
||||
* Only reset scroll state when a new user message is added to the chat.
|
||||
* We don't want to auto-scroll on new tool response messages.
|
||||
*/
|
||||
function getNumUserMsgs(history: ChatHistoryItemWithMessageId[]) {
|
||||
return history.filter((msg) => msg.message.role === "user").length;
|
||||
}
|
||||
|
||||
export const useAutoScroll = (
|
||||
ref: React.RefObject<HTMLDivElement>,
|
||||
history: unknown[],
|
||||
history: ChatHistoryItemWithMessageId[],
|
||||
) => {
|
||||
const [userHasScrolled, setUserHasScrolled] = useState(false);
|
||||
const numUserMsgs = useMemo(() => getNumUserMsgs(history), [history.length]);
|
||||
|
||||
useEffect(() => {
|
||||
if (history.length) {
|
||||
setUserHasScrolled(false);
|
||||
}
|
||||
}, [history.length]);
|
||||
setUserHasScrolled(false);
|
||||
}, [numUserMsgs]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!ref.current || history.length === 0) return;
|
||||
|
|
|
|||
|
|
@ -1,10 +1,11 @@
|
|||
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
|
||||
import { ApplyState, CodeToEdit, MessageModes } from "core";
|
||||
import { ApplyState, SetCodeToEditPayload, MessageModes } from "core";
|
||||
import { EDIT_MODE_STREAM_ID } from "core/edit/constants";
|
||||
|
||||
export interface EditModeState {
|
||||
// Array because of previous multi-file edit functionality
|
||||
// Keeping array to not break persisted redux for now
|
||||
codeToEdit: CodeToEdit[];
|
||||
codeToEdit: SetCodeToEditPayload[];
|
||||
applyState: ApplyState;
|
||||
returnToMode: MessageModes;
|
||||
lastNonEditSessionWasEmpty: boolean;
|
||||
|
|
@ -46,7 +47,7 @@ export const editModeStateSlice = createSlice({
|
|||
{
|
||||
payload,
|
||||
}: PayloadAction<{
|
||||
codeToEdit: CodeToEdit | CodeToEdit[];
|
||||
codeToEdit: SetCodeToEditPayload | SetCodeToEditPayload[];
|
||||
}>,
|
||||
) => {
|
||||
state.codeToEdit = Array.isArray(payload.codeToEdit)
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ import {
|
|||
FileSymbolMap,
|
||||
MessageModes,
|
||||
PromptLog,
|
||||
RuleWithSource,
|
||||
Session,
|
||||
SessionMetadata,
|
||||
ToolCallDelta,
|
||||
|
|
@ -31,7 +32,7 @@ import { findCurrentToolCall, findToolCall } from "../util";
|
|||
|
||||
// We need this to handle reorderings (e.g. a mid-array deletion) of the messages array.
|
||||
// The proper fix is adding a UUID to all chat messages, but this is the temp workaround.
|
||||
type ChatHistoryItemWithMessageId = ChatHistoryItem & {
|
||||
export type ChatHistoryItemWithMessageId = ChatHistoryItem & {
|
||||
message: ChatMessage & { id: string };
|
||||
};
|
||||
|
||||
|
|
@ -247,6 +248,19 @@ export const sessionSlice = createSlice({
|
|||
...payload.contextItems,
|
||||
];
|
||||
},
|
||||
setAppliedRulesAtIndex: (
|
||||
state,
|
||||
{
|
||||
payload,
|
||||
}: PayloadAction<{
|
||||
index: number;
|
||||
appliedRules: RuleWithSource[];
|
||||
}>,
|
||||
) => {
|
||||
if (state.history[payload.index]) {
|
||||
state.history[payload.index].appliedRules = payload.appliedRules;
|
||||
}
|
||||
},
|
||||
setInactive: (state) => {
|
||||
const curMessage = state.history.at(-1);
|
||||
|
||||
|
|
@ -698,6 +712,7 @@ export const {
|
|||
updateFileSymbols,
|
||||
setContextItemsAtIndex,
|
||||
addContextItemsAtIndex,
|
||||
setAppliedRulesAtIndex,
|
||||
setInactive,
|
||||
streamUpdate,
|
||||
newSession,
|
||||
|
|
|
|||
|
|
@ -1,6 +1,10 @@
|
|||
import { createAsyncThunk } from "@reduxjs/toolkit";
|
||||
import { JSONContent } from "@tiptap/core";
|
||||
import { CodeToEdit, MessageModes, RangeInFileWithContents } from "core";
|
||||
import {
|
||||
SetCodeToEditPayload,
|
||||
MessageModes,
|
||||
RangeInFileWithContents,
|
||||
} from "core";
|
||||
import { stripImages } from "core/util/messageContent";
|
||||
import { resolveEditorContent } from "../../components/mainInput/TipTapEditor";
|
||||
import {
|
||||
|
|
@ -18,7 +22,7 @@ export const streamEditThunk = createAsyncThunk<
|
|||
void,
|
||||
{
|
||||
editorState: JSONContent;
|
||||
codeToEdit: CodeToEdit[];
|
||||
codeToEdit: SetCodeToEditPayload[];
|
||||
},
|
||||
ThunkApiType
|
||||
>(
|
||||
|
|
|
|||
|
|
@ -1,12 +1,14 @@
|
|||
import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
|
||||
import { JSONContent } from "@tiptap/core";
|
||||
import { InputModifiers } from "core";
|
||||
import { InputModifiers, ToolResultChatMessage, UserChatMessage } from "core";
|
||||
import { constructMessages } from "core/llm/constructMessages";
|
||||
import { getApplicableRules } from "core/llm/rules/getSystemMessageWithRules";
|
||||
import posthog from "posthog-js";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { getBaseSystemMessage } from "../../util";
|
||||
import { selectSelectedChatModel } from "../slices/configSlice";
|
||||
import {
|
||||
setAppliedRulesAtIndex,
|
||||
submitEditorAndInitAtIndex,
|
||||
updateHistoryItemAtIndex,
|
||||
} from "../slices/sessionSlice";
|
||||
|
|
@ -84,17 +86,41 @@ export const streamResponseThunk = createAsyncThunk<
|
|||
}),
|
||||
);
|
||||
|
||||
// Construct messages from updated history
|
||||
// Get updated history after the update
|
||||
const updatedHistory = getState().session.history;
|
||||
const messageMode = getState().session.mode
|
||||
|
||||
const baseChatOrAgentSystemMessage = getBaseSystemMessage(selectedChatModel, messageMode)
|
||||
// Determine which rules apply to this message
|
||||
const userMsg = updatedHistory[inputIndex].message;
|
||||
const rules = getState().config.config.rules;
|
||||
|
||||
// Calculate applicable rules once
|
||||
// We need to check the message type to match what getApplicableRules expects
|
||||
const applicableRules = getApplicableRules(
|
||||
userMsg.role === "user" || userMsg.role === "tool"
|
||||
? (userMsg as UserChatMessage | ToolResultChatMessage)
|
||||
: undefined,
|
||||
rules,
|
||||
);
|
||||
|
||||
// Store in history for UI display
|
||||
dispatch(
|
||||
setAppliedRulesAtIndex({
|
||||
index: inputIndex,
|
||||
appliedRules: applicableRules,
|
||||
}),
|
||||
);
|
||||
|
||||
const messageMode = getState().session.mode;
|
||||
const baseChatOrAgentSystemMessage = getBaseSystemMessage(
|
||||
selectedChatModel,
|
||||
messageMode,
|
||||
);
|
||||
|
||||
const messages = constructMessages(
|
||||
messageMode,
|
||||
[...updatedHistory],
|
||||
baseChatOrAgentSystemMessage,
|
||||
state.config.config.rules,
|
||||
applicableRules,
|
||||
);
|
||||
|
||||
posthog.capture("step run", {
|
||||
|
|
|
|||
|
|
@ -31,3 +31,6 @@ class Test {
|
|||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,9 @@
|
|||
import { z } from "zod";
|
||||
import { baseDevDataAllSchema } from "../base.js";
|
||||
|
||||
/**
|
||||
* The "editInteraction" event is sent whenever the user submits an input in edit mode and the model's response is completed
|
||||
*/
|
||||
export const editInteractionEventAllSchema = baseDevDataAllSchema.extend({
|
||||
modelProvider: z.string(),
|
||||
modelTitle: z.string(),
|
||||
|
|
|
|||
|
|
@ -23,6 +23,11 @@ import {
|
|||
chatInteractionEventSchema_0_2_0,
|
||||
chatInteractionEventSchema_0_2_0_noCode,
|
||||
} from "./chatInteraction/v0.2.0.js";
|
||||
import { editInteractionEventAllSchema } from "./editInteraction/index.js";
|
||||
import {
|
||||
editInteractionEventSchema_0_2_0,
|
||||
editInteractionEventSchema_0_2_0_noCode,
|
||||
} from "./editInteraction/v0.2.0.js";
|
||||
import { quickEditEventAllSchema } from "./quickEdit/index.js";
|
||||
import {
|
||||
quickEditEventSchema_0_1_0,
|
||||
|
|
@ -66,7 +71,7 @@ const devEventAllVersionDataSchemas = z.object({
|
|||
chatFeedback: chatFeedbackEventAllSchema,
|
||||
tokensGenerated: tokensGeneratedEventAllSchema,
|
||||
chatInteraction: chatInteractionEventAllSchema,
|
||||
// editInteraction: editInteractionEventAllSchema,
|
||||
editInteraction: editInteractionEventAllSchema,
|
||||
});
|
||||
|
||||
// Version and level specific schemas are organized here
|
||||
|
|
@ -91,14 +96,14 @@ export const devDataVersionedSchemas = {
|
|||
chatFeedback: chatFeedbackEventSchema_0_2_0,
|
||||
tokensGenerated: tokensGeneratedEventSchema_0_2_0,
|
||||
chatInteraction: chatInteractionEventSchema_0_2_0,
|
||||
// editInteraction: editInteractionEventSchema_0_2_0,
|
||||
editInteraction: editInteractionEventSchema_0_2_0,
|
||||
},
|
||||
noCode: {
|
||||
autocomplete: autocompleteEventSchema_0_2_0_noCode,
|
||||
chatFeedback: chatFeedbackEventSchema_0_2_0_noCode,
|
||||
tokensGenerated: tokensGeneratedEventSchema_0_2_0_noCode,
|
||||
chatInteraction: chatInteractionEventSchema_0_2_0_noCode,
|
||||
// editInteraction: editInteractionEventSchema_0_2_0_noCode,
|
||||
editInteraction: editInteractionEventSchema_0_2_0_noCode,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue