Changesets · Branches · Tags · Compare
| Changeset | ea74bf50486dc914e4a0ab04f88fb076e12399e200f675164a64c6a9d244c586 |
|---|---|
| Author | Nate <sestinj@gmail.com> · 2025-05-25 16:11 -07:00 |
| Committer | Nate <sestinj@gmail.com> · 2025-05-25 16:11 -07:00 |
| Parents | 584be92d98f1, 158decf78aee |
118 files changed
modified .github/workflows/cla.yaml +4 −3
| @@ -1,9 +1,9 @@ | ||
| 1 | 1 | name: "CLA Assistant" |
| 2 | 2 | on: |
| 3 | 3 | issue_comment: |
| 4 | - types: [ created ] | |
| 4 | + types: [created] | |
| 5 | 5 | pull_request_target: |
| 6 | - types: [ opened, closed, synchronize ] | |
| 6 | + types: [opened, closed, synchronize] | |
| 7 | 7 | |
| 8 | 8 | permissions: |
| 9 | 9 | actions: write |
| @@ -26,4 +26,5 @@ | ||
| 26 | 26 | path-to-signatures: "signatures/version1/cla.json" |
| 27 | 27 | path-to-document: "https://github.com/continuedev/continue/blob/main/docs/docs/CLA.md" |
| 28 | 28 | branch: cla-signatures |
| 29 | - allowlist: dependabot[bot] | |
| No newline at the end of the file | ||
| 29 | + allowlist: dependabot[bot] | |
| 30 | + signed-commit-message: "CLA signed in $pullRequestNo" |
modified .gitignore +2 −1
| @@ -166,4 +166,5 @@ | ||
| 166 | 166 | *.iml |
| 167 | 167 | |
| 168 | 168 | .continuerules |
| 169 | -**/.continue/assistants/ | |
| No newline at the end of the file | ||
| 169 | +**/.continue/assistants/ | |
| 170 | +keys | |
| No newline at the end of the file |
modified binary/package-lock.json +2 −0
| @@ -93,6 +93,7 @@ | ||
| 93 | 93 | "p-limit": "^6.1.0", |
| 94 | 94 | "partial-json": "^0.1.7", |
| 95 | 95 | "pg": "^8.11.3", |
| 96 | + "plist": "^3.1.0", | |
| 96 | 97 | "posthog-node": "^3.6.3", |
| 97 | 98 | "puppeteer": "^22.4.0", |
| 98 | 99 | "puppeteer-chromium-resolver": "^23.0.0", |
| @@ -129,6 +130,7 @@ | ||
| 129 | 130 | "@types/mustache": "^4.2.5", |
| 130 | 131 | "@types/node-fetch": "^2.6.11", |
| 131 | 132 | "@types/pg": "^8.11.6", |
| 133 | + "@types/plist": "^3.0.5", | |
| 132 | 134 | "@types/request": "^2.48.12", |
| 133 | 135 | "@types/tar": "^6.1.13", |
| 134 | 136 | "@types/uuid": "^9.0.7", |
modified core/autocomplete/generation/CompletionStreamer.ts +22 −7
| @@ -3,6 +3,7 @@ | ||
| 3 | 3 | import { HelperVars } from "../util/HelperVars"; |
| 4 | 4 | |
| 5 | 5 | import { GeneratorReuseManager } from "./GeneratorReuseManager"; |
| 6 | +import { stopAfterMaxProcessingTime } from "./utils"; | |
| 6 | 7 | |
| 7 | 8 | export class CompletionStreamer { |
| 8 | 9 | private streamTransformPipeline = new StreamTransformPipeline(); |
| @@ -22,23 +23,37 @@ | ||
| 22 | 23 | completionOptions: Partial<CompletionOptions> | undefined, |
| 23 | 24 | helper: HelperVars, |
| 24 | 25 | ) { |
| 26 | + // Full stop means to stop the LLM's generation, instead of just truncating the displayed completion | |
| 27 | + const fullStop = () => | |
| 28 | + this.generatorReuseManager.currentGenerator?.cancel(); | |
| 29 | + | |
| 25 | 30 | // Try to reuse pending requests if what the user typed matches start of completion |
| 26 | 31 | const generator = this.generatorReuseManager.getGenerator( |
| 27 | 32 | prefix, |
| 28 | - (abortSignal: AbortSignal) => | |
| 29 | - llm.supportsFim() | |
| 33 | + (abortSignal: AbortSignal) => { | |
| 34 | + const generator = llm.supportsFim() | |
| 30 | 35 | ? llm.streamFim(prefix, suffix, abortSignal, completionOptions) |
| 31 | 36 | : llm.streamComplete(prompt, abortSignal, { |
| 32 | 37 | ...completionOptions, |
| 33 | 38 | raw: true, |
| 34 | - }), | |
| 39 | + }); | |
| 40 | + | |
| 41 | + /** | |
| 42 | + * This transformer applies even on reused generator. We are deliberately | |
| 43 | + * not using streamTransformPipeline because we want to capture and stop | |
| 44 | + * the request even if the generator is being reused. | |
| 45 | + */ | |
| 46 | + return helper.options.transform | |
| 47 | + ? stopAfterMaxProcessingTime( | |
| 48 | + generator, | |
| 49 | + helper.options.modelTimeout * 2.5, | |
| 50 | + fullStop, | |
| 51 | + ) | |
| 52 | + : generator; | |
| 53 | + }, | |
| 35 | 54 | multiline, |
| 36 | 55 | ); |
| 37 | 56 | |
| 38 | - // Full stop means to stop the LLM's generation, instead of just truncating the displayed completion | |
| 39 | - const fullStop = () => | |
| 40 | - this.generatorReuseManager.currentGenerator?.cancel(); | |
| 41 | - | |
| 42 | 57 | // LLM |
| 43 | 58 | const generatorWithCancellation = async function* () { |
| 44 | 59 | for await (const update of generator) { |
added core/autocomplete/generation/utils.test.ts +138 −0
| @@ -0,0 +1,138 @@ | ||
| 1 | +import { jest } from "@jest/globals"; | |
| 2 | +import { stopAfterMaxProcessingTime } from "./utils"; | |
| 3 | + | |
| 4 | +describe("stopAfterMaxProcessingTime", () => { | |
| 5 | + beforeEach(() => { | |
| 6 | + jest.useFakeTimers(); | |
| 7 | + }); | |
| 8 | + | |
| 9 | + afterEach(() => { | |
| 10 | + jest.useRealTimers(); | |
| 11 | + }); | |
| 12 | + | |
| 13 | + async function* createMockStream(chunks: string[]): AsyncGenerator<string> { | |
| 14 | + for (const chunk of chunks) { | |
| 15 | + yield chunk; | |
| 16 | + } | |
| 17 | + } | |
| 18 | + | |
| 19 | + async function streamToString( | |
| 20 | + stream: AsyncGenerator<string>, | |
| 21 | + ): Promise<string> { | |
| 22 | + let result = ""; | |
| 23 | + for await (const chunk of stream) { | |
| 24 | + result += chunk; | |
| 25 | + } | |
| 26 | + return result; | |
| 27 | + } | |
| 28 | + | |
| 29 | + it("should yield all chunks when maxTimeMs is not reached", async () => { | |
| 30 | + const mockStream = createMockStream(["Hello", " world", "!"]); | |
| 31 | + const fullStop = jest.fn(); | |
| 32 | + const result = stopAfterMaxProcessingTime(mockStream, 1000, fullStop); | |
| 33 | + | |
| 34 | + const output = await streamToString(result); | |
| 35 | + | |
| 36 | + expect(output).toBe("Hello world!"); | |
| 37 | + expect(fullStop).not.toHaveBeenCalled(); | |
| 38 | + }); | |
| 39 | + | |
| 40 | + it.only("should stop processing after max time is reached", async () => { | |
| 41 | + // Mock implementation of Date.now | |
| 42 | + let currentTime = 0; | |
| 43 | + const originalDateNow = Date.now; | |
| 44 | + Date.now = jest.fn(() => currentTime); | |
| 45 | + | |
| 46 | + // Create a generator that we can control | |
| 47 | + async function* controlledGenerator(): AsyncGenerator<string> { | |
| 48 | + for (let i = 0; i < 100; i++) { | |
| 49 | + // After yielding 10 chunks, simulate time passing beyond our limit | |
| 50 | + if (i === 10) { | |
| 51 | + currentTime = 1000; // This exceeds our 500ms limit | |
| 52 | + } | |
| 53 | + yield `chunk-${i}`; | |
| 54 | + } | |
| 55 | + } | |
| 56 | + | |
| 57 | + const fullStop = jest.fn(); | |
| 58 | + const maxTimeMs = 500; | |
| 59 | + | |
| 60 | + const transformedGenerator = stopAfterMaxProcessingTime( | |
| 61 | + controlledGenerator(), | |
| 62 | + maxTimeMs, | |
| 63 | + fullStop, | |
| 64 | + ); | |
| 65 | + | |
| 66 | + // Consume the generator and collect outputs | |
| 67 | + const outputs: string[] = []; | |
| 68 | + for await (const chunk of transformedGenerator) { | |
| 69 | + outputs.push(chunk); | |
| 70 | + } | |
| 71 | + | |
| 72 | + // We expect: | |
| 73 | + // 1. Not all chunks were processed (less than 100) | |
| 74 | + // 2. fullStop was called | |
| 75 | + // 3. We processed at least the chunks before time was exceeded | |
| 76 | + expect(outputs.length).toBeLessThan(100); | |
| 77 | + expect(outputs.length).toBeGreaterThanOrEqual(10); // We should get at least the first 10 chunks | |
| 78 | + expect(fullStop).toHaveBeenCalled(); | |
| 79 | + | |
| 80 | + // Restore Date.now | |
| 81 | + Date.now = originalDateNow; | |
| 82 | + }); | |
| 83 | + | |
| 84 | + it("should check time only periodically based on checkInterval", async () => { | |
| 85 | + const chunks = Array(100).fill("x"); | |
| 86 | + const mockStream = createMockStream(chunks); | |
| 87 | + const fullStop = jest.fn(); | |
| 88 | + | |
| 89 | + // Spy on Date.now to count how many times it's called | |
| 90 | + const dateSpy = jest.spyOn(Date, "now"); | |
| 91 | + | |
| 92 | + // Stream should complete normally (not hitting the timeout) | |
| 93 | + await streamToString( | |
| 94 | + stopAfterMaxProcessingTime(mockStream, 10000, fullStop), | |
| 95 | + ); | |
| 96 | + | |
| 97 | + // The first call is to set startTime, then once every checkInterval (10) chunks | |
| 98 | + // So for 100 chunks, we expect startTime + ~10 checks = ~11 calls | |
| 99 | + // We use a range because implementation details might vary slightly | |
| 100 | + expect(dateSpy.mock.calls.length).toBeGreaterThanOrEqual(1); | |
| 101 | + expect(dateSpy.mock.calls.length).toBeLessThanOrEqual(15); | |
| 102 | + | |
| 103 | + dateSpy.mockRestore(); | |
| 104 | + }); | |
| 105 | + | |
| 106 | + it("should handle empty stream gracefully", async () => { | |
| 107 | + const mockStream = createMockStream([]); | |
| 108 | + const fullStop = jest.fn(); | |
| 109 | + const result = stopAfterMaxProcessingTime(mockStream, 1000, fullStop); | |
| 110 | + | |
| 111 | + const output = await streamToString(result); | |
| 112 | + | |
| 113 | + expect(output).toBe(""); | |
| 114 | + expect(fullStop).not.toHaveBeenCalled(); | |
| 115 | + }); | |
| 116 | + | |
| 117 | + it("should pass through all chunks if there's no timeout", async () => { | |
| 118 | + const chunks = Array(100).fill("test chunk"); | |
| 119 | + const mockStream = createMockStream(chunks); | |
| 120 | + const fullStop = jest.fn(); | |
| 121 | + | |
| 122 | + // Use undefined as timeout to simulate no timeout | |
| 123 | + const result = stopAfterMaxProcessingTime( | |
| 124 | + mockStream, | |
| 125 | + undefined as any, | |
| 126 | + fullStop, | |
| 127 | + ); | |
| 128 | + | |
| 129 | + // Process the stream | |
| 130 | + const processedChunks = []; | |
| 131 | + for await (const chunk of result) { | |
| 132 | + processedChunks.push(chunk); | |
| 133 | + } | |
| 134 | + | |
| 135 | + expect(processedChunks.length).toBe(chunks.length); | |
| 136 | + expect(fullStop).not.toHaveBeenCalled(); | |
| 137 | + }); | |
| 138 | +}); |
added core/autocomplete/generation/utils.ts +27 −0
| @@ -0,0 +1,27 @@ | ||
| 1 | +export async function* stopAfterMaxProcessingTime( | |
| 2 | + stream: AsyncGenerator<string>, | |
| 3 | + maxTimeMs: number, | |
| 4 | + fullStop: () => void, | |
| 5 | +): AsyncGenerator<string> { | |
| 6 | + const startTime = Date.now(); | |
| 7 | + /** | |
| 8 | + * Check every 10 chunks to avoid performance overhead. | |
| 9 | + */ | |
| 10 | + const checkInterval = 10; | |
| 11 | + let chunkCount = 0; | |
| 12 | + let totalCharCount = 0; | |
| 13 | + | |
| 14 | + for await (const chunk of stream) { | |
| 15 | + yield chunk; | |
| 16 | + | |
| 17 | + chunkCount++; | |
| 18 | + totalCharCount += chunk.length; | |
| 19 | + | |
| 20 | + if (chunkCount % checkInterval === 0) { | |
| 21 | + if (Date.now() - startTime > maxTimeMs) { | |
| 22 | + fullStop(); | |
| 23 | + return; | |
| 24 | + } | |
| 25 | + } | |
| 26 | + } | |
| 27 | +} |
modified core/config/ConfigHandler.ts +16 −9
| @@ -1,10 +1,6 @@ | ||
| 1 | 1 | import { ConfigResult } from "@continuedev/config-yaml"; |
| 2 | 2 | |
| 3 | -import { | |
| 4 | - ControlPlaneClient, | |
| 5 | - ControlPlaneSessionInfo, | |
| 6 | -} from "../control-plane/client.js"; | |
| 7 | -import { getControlPlaneEnv } from "../control-plane/env.js"; | |
| 3 | +import { ControlPlaneClient } from "../control-plane/client.js"; | |
| 8 | 4 | import { |
| 9 | 5 | BrowserSerializedContinueConfig, |
| 10 | 6 | ContinueConfig, |
| @@ -15,10 +11,15 @@ | ||
| 15 | 11 | } from "../index.js"; |
| 16 | 12 | import { GlobalContext } from "../util/GlobalContext.js"; |
| 17 | 13 | |
| 14 | +import { | |
| 15 | + AuthType, | |
| 16 | + ControlPlaneSessionInfo, | |
| 17 | +} from "../control-plane/AuthTypes.js"; | |
| 18 | +import { getControlPlaneEnv } from "../control-plane/env.js"; | |
| 18 | 19 | import { logger } from "../util/logger.js"; |
| 19 | 20 | import { |
| 20 | 21 | ASSISTANTS, |
| 21 | - getAllDotContinueYamlFiles, | |
| 22 | + getAllDotContinueDefinitionFiles, | |
| 22 | 23 | LoadAssistantFilesOptions, |
| 23 | 24 | } from "./loadLocalAssistants.js"; |
| 24 | 25 | import LocalProfileLoader from "./profile/LocalProfileLoader.js"; |
| @@ -136,8 +137,7 @@ | ||
| 136 | 137 | } |
| 137 | 138 | |
| 138 | 139 | private async getOrgs(): Promise<OrgWithProfiles[]> { |
| 139 | - const userId = await this.controlPlaneClient.userId; | |
| 140 | - if (userId) { | |
| 140 | + if (await this.controlPlaneClient.isSignedIn()) { | |
| 141 | 141 | const orgDescs = await this.controlPlaneClient.listOrganizations(); |
| 142 | 142 | const personalHubOrg = await this.getPersonalHubOrg(); |
| 143 | 143 | const hubOrgs = await Promise.all( |
| @@ -270,6 +270,13 @@ | ||
| 270 | 270 | /** |
| 271 | 271 | * Users can define as many local assistants as they want in a `.continue/assistants` folder |
| 272 | 272 | */ |
| 273 | + | |
| 274 | + // Local customization disabled for on-premise deployments | |
| 275 | + const env = await getControlPlaneEnv(this.ide.getIdeSettings()); | |
| 276 | + if (env.AUTH_TYPE === AuthType.OnPrem) { | |
| 277 | + return []; | |
| 278 | + } | |
| 279 | + | |
| 273 | 280 | const localProfiles: ProfileLifecycleManager[] = []; |
| 274 | 281 | |
| 275 | 282 | if (options.includeGlobal) { |
| @@ -277,7 +284,7 @@ | ||
| 277 | 284 | } |
| 278 | 285 | |
| 279 | 286 | if (options.includeWorkspace) { |
| 280 | - const assistantFiles = await getAllDotContinueYamlFiles( | |
| 287 | + const assistantFiles = await getAllDotContinueDefinitionFiles( | |
| 281 | 288 | this.ide, |
| 282 | 289 | options, |
| 283 | 290 | ASSISTANTS, |
modified core/config/load.ts +9 −3
| @@ -101,7 +101,14 @@ | ||
| 101 | 101 | |
| 102 | 102 | const configMergeKeys = { |
| 103 | 103 | models: (a: any, b: any) => a.title === b.title, |
| 104 | - contextProviders: (a: any, b: any) => a.name === b.name, | |
| 104 | + contextProviders: (a: any, b: any) => { | |
| 105 | + // If not HTTP providers, use the name only | |
| 106 | + if (a.name !== "http" || b.name !== "http") { | |
| 107 | + return a.name === b.name; | |
| 108 | + } | |
| 109 | + // For HTTP providers, consider them different if they have different URLs | |
| 110 | + return a.name === b.name && a.params?.url === b.params?.url; | |
| 111 | + }, | |
| 105 | 112 | slashCommands: (a: any, b: any) => a.name === b.name, |
| 106 | 113 | customCommands: (a: any, b: any) => a.name === b.name, |
| 107 | 114 | }; |
| @@ -970,6 +977,5 @@ | ||
| 970 | 977 | finalToBrowserConfig, |
| 971 | 978 | intermediateToFinalConfig, |
| 972 | 979 | loadContinueConfigFromJson, |
| 973 | - type BrowserSerializedContinueConfig | |
| 980 | + type BrowserSerializedContinueConfig, | |
| 974 | 981 | }; |
| 975 | - |
modified core/config/loadLocalAssistants.ts +5 −5
| @@ -13,7 +13,7 @@ | ||
| 13 | 13 | export const ASSISTANTS_FOLDER = `.continue/${ASSISTANTS}`; |
| 14 | 14 | |
| 15 | 15 | export function isLocalAssistantFile(uri: string): boolean { |
| 16 | - if (!uri.endsWith(".yaml") && !uri.endsWith(".yml")) { | |
| 16 | + if (!uri.endsWith(".yaml") && !uri.endsWith(".yml") && !uri.endsWith(".md")) { | |
| 17 | 17 | return false; |
| 18 | 18 | } |
| 19 | 19 | |
| @@ -21,7 +21,7 @@ | ||
| 21 | 21 | return normalizedUri.includes(`/${ASSISTANTS_FOLDER}/`); |
| 22 | 22 | } |
| 23 | 23 | |
| 24 | -export async function listYamlFilesInDir( | |
| 24 | +async function getDefinitionFilesInDir( | |
| 25 | 25 | ide: IDE, |
| 26 | 26 | dir: string, |
| 27 | 27 | ): Promise<{ path: string; content: string }[]> { |
| @@ -41,7 +41,7 @@ | ||
| 41 | 41 | source: "get assistant files", |
| 42 | 42 | }); |
| 43 | 43 | const assistantFilePaths = uris.filter( |
| 44 | - (p) => p.endsWith(".yaml") || p.endsWith(".yml"), | |
| 44 | + (p) => p.endsWith(".yaml") || p.endsWith(".yml") || p.endsWith(".md"), | |
| 45 | 45 | ); |
| 46 | 46 | const results = assistantFilePaths.map(async (uri) => { |
| 47 | 47 | const content = await ide.readFile(uri); // make a try catch |
| @@ -86,7 +86,7 @@ | ||
| 86 | 86 | * This method searches in both ~/.continue and workspace .continue |
| 87 | 87 | * for all YAML files in the specified subdirctory, for example .continue/assistants or .continue/prompts |
| 88 | 88 | */ |
| 89 | -export async function getAllDotContinueYamlFiles( | |
| 89 | +export async function getAllDotContinueDefinitionFiles( | |
| 90 | 90 | ide: IDE, |
| 91 | 91 | options: LoadAssistantFilesOptions, |
| 92 | 92 | subDirName: string, |
| @@ -103,7 +103,7 @@ | ||
| 103 | 103 | |
| 104 | 104 | // Get all assistant files from the directories |
| 105 | 105 | const assistantFiles = ( |
| 106 | - await Promise.all(fullDirs.map((dir) => listYamlFilesInDir(ide, dir))) | |
| 106 | + await Promise.all(fullDirs.map((dir) => getDefinitionFilesInDir(ide, dir))) | |
| 107 | 107 | ).flat(); |
| 108 | 108 | |
| 109 | 109 | return await Promise.all( |
added core/config/markdown/loadMarkdownRules.ts +47 −0
| @@ -0,0 +1,47 @@ | ||
| 1 | +import { ConfigValidationError } from "@continuedev/config-yaml"; | |
| 2 | +import { IDE, RuleWithSource } from "../.."; | |
| 3 | +import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants"; | |
| 4 | +import { convertMarkdownRuleToContinueRule } from "./parseMarkdownRule"; | |
| 5 | + | |
| 6 | +/** | |
| 7 | + * Loads rules from markdown files in the .continue/rules directory | |
| 8 | + */ | |
| 9 | +export async function loadMarkdownRules(ide: IDE): Promise<{ | |
| 10 | + rules: RuleWithSource[]; | |
| 11 | + errors: ConfigValidationError[]; | |
| 12 | +}> { | |
| 13 | + const errors: ConfigValidationError[] = []; | |
| 14 | + const rules: RuleWithSource[] = []; | |
| 15 | + | |
| 16 | + try { | |
| 17 | + // Get all .md files from .continue/rules | |
| 18 | + const markdownFiles = await getAllDotContinueDefinitionFiles( | |
| 19 | + ide, | |
| 20 | + { includeGlobal: true, includeWorkspace: true }, | |
| 21 | + "rules", | |
| 22 | + ); | |
| 23 | + | |
| 24 | + // Filter to just .md files | |
| 25 | + const mdFiles = markdownFiles.filter((file) => file.path.endsWith(".md")); | |
| 26 | + | |
| 27 | + // Process each markdown file | |
| 28 | + for (const file of mdFiles) { | |
| 29 | + try { | |
| 30 | + const rule = convertMarkdownRuleToContinueRule(file.path, file.content); | |
| 31 | + rules.push(rule); | |
| 32 | + } catch (e) { | |
| 33 | + errors.push({ | |
| 34 | + fatal: false, | |
| 35 | + message: `Failed to parse markdown rule file ${file.path}: ${e instanceof Error ? e.message : e}`, | |
| 36 | + }); | |
| 37 | + } | |
| 38 | + } | |
| 39 | + } catch (e) { | |
| 40 | + errors.push({ | |
| 41 | + fatal: false, | |
| 42 | + message: `Error loading markdown rule files: ${e instanceof Error ? e.message : e}`, | |
| 43 | + }); | |
| 44 | + } | |
| 45 | + | |
| 46 | + return { rules, errors }; | |
| 47 | +} |
added core/config/markdown/parseMarkdownRule.test.ts +174 −0
| @@ -0,0 +1,174 @@ | ||
| 1 | +import { | |
| 2 | + convertMarkdownRuleToContinueRule, | |
| 3 | + parseMarkdownRule, | |
| 4 | +} from "./parseMarkdownRule"; | |
| 5 | + | |
| 6 | +describe("parseMarkdownRule", () => { | |
| 7 | + it("should correctly parse markdown with YAML frontmatter", () => { | |
| 8 | + const content = `--- | |
| 9 | +globs: "**/test/**/*.kt" | |
| 10 | +--- | |
| 11 | + | |
| 12 | +# Test Rule | |
| 13 | + | |
| 14 | +This is a test rule.`; | |
| 15 | + | |
| 16 | + const result = parseMarkdownRule(content); | |
| 17 | + expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" }); | |
| 18 | + expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule."); | |
| 19 | + }); | |
| 20 | + | |
| 21 | + it("should handle missing frontmatter", () => { | |
| 22 | + const content = `# Test Rule | |
| 23 | + | |
| 24 | +This is a test rule without frontmatter.`; | |
| 25 | + | |
| 26 | + const result = parseMarkdownRule(content); | |
| 27 | + expect(result.frontmatter).toEqual({}); | |
| 28 | + expect(result.markdown).toBe(content); | |
| 29 | + }); | |
| 30 | + | |
| 31 | + it("should handle empty frontmatter", () => { | |
| 32 | + const content = `--- | |
| 33 | +--- | |
| 34 | + | |
| 35 | +# Test Rule | |
| 36 | + | |
| 37 | +This is a test rule with empty frontmatter.`; | |
| 38 | + | |
| 39 | + const result = parseMarkdownRule(content); | |
| 40 | + | |
| 41 | + // Log exact strings for debugging | |
| 42 | + console.log("Actual:", JSON.stringify(result.markdown)); | |
| 43 | + console.log( | |
| 44 | + "Expected:", | |
| 45 | + JSON.stringify( | |
| 46 | + "# Test Rule\n\nThis is a test rule with empty frontmatter.", | |
| 47 | + ), | |
| 48 | + ); | |
| 49 | + | |
| 50 | + expect(result.frontmatter).toEqual({}); | |
| 51 | + expect(result.markdown).toBe( | |
| 52 | + "# Test Rule\n\nThis is a test rule with empty frontmatter.", | |
| 53 | + ); | |
| 54 | + }); | |
| 55 | + | |
| 56 | + it("should handle frontmatter with whitespace", () => { | |
| 57 | + const content = `--- | |
| 58 | +globs: "**/test/**/*.kt" | |
| 59 | +--- | |
| 60 | + | |
| 61 | +# Test Rule | |
| 62 | + | |
| 63 | +This is a test rule.`; | |
| 64 | + | |
| 65 | + const result = parseMarkdownRule(content); | |
| 66 | + expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" }); | |
| 67 | + expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule."); | |
| 68 | + }); | |
| 69 | + | |
| 70 | + it("should handle Windows line endings (CRLF)", () => { | |
| 71 | + // Using \r\n for CRLF line endings | |
| 72 | + const content = `---\r | |
| 73 | +globs: "**/test/**/*.kt"\r | |
| 74 | +---\r | |
| 75 | +\r | |
| 76 | +# Test Rule\r | |
| 77 | +\r | |
| 78 | +This is a test rule.`; | |
| 79 | + | |
| 80 | + const result = parseMarkdownRule(content); | |
| 81 | + expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" }); | |
| 82 | + // The result should be normalized to \n | |
| 83 | + expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule."); | |
| 84 | + }); | |
| 85 | + | |
| 86 | + it("should handle malformed frontmatter", () => { | |
| 87 | + const content = `--- | |
| 88 | +globs: - "**/test/**/*.kt" | |
| 89 | +invalid: yaml: content | |
| 90 | +--- | |
| 91 | + | |
| 92 | +# Test Rule | |
| 93 | + | |
| 94 | +This is a test rule.`; | |
| 95 | + | |
| 96 | + // Should treat as only markdown when frontmatter is malformed | |
| 97 | + const result = parseMarkdownRule(content); | |
| 98 | + expect(result.frontmatter).toEqual({}); | |
| 99 | + expect(result.markdown).toBe(content); | |
| 100 | + }); | |
| 101 | +}); | |
| 102 | + | |
| 103 | +describe("convertMarkdownRuleToContinueRule", () => { | |
| 104 | + it("should convert markdown with frontmatter to a rule", () => { | |
| 105 | + const content = `--- | |
| 106 | +globs: "**/test/**/*.kt" | |
| 107 | +name: Custom Name | |
| 108 | +--- | |
| 109 | + | |
| 110 | +# Test Rule | |
| 111 | + | |
| 112 | +This is a test rule.`; | |
| 113 | + | |
| 114 | + const result = convertMarkdownRuleToContinueRule( | |
| 115 | + "/path/to/rule.md", | |
| 116 | + content, | |
| 117 | + ); | |
| 118 | + expect(result.rule).toBe("# Test Rule\n\nThis is a test rule."); | |
| 119 | + expect(result.globs).toBe("**/test/**/*.kt"); | |
| 120 | + expect(result.name).toBe("Custom Name"); | |
| 121 | + expect(result.source).toBe("rules-block"); | |
| 122 | + expect(result.ruleFile).toBe("/path/to/rule.md"); | |
| 123 | + }); | |
| 124 | + | |
| 125 | + it("should use the first heading as name if not in frontmatter", () => { | |
| 126 | + const content = `--- | |
| 127 | +globs: "**/test/**/*.kt" | |
| 128 | +--- | |
| 129 | + | |
| 130 | +# Test Rule Title | |
| 131 | + | |
| 132 | +This is a test rule.`; | |
| 133 | + | |
| 134 | + const result = convertMarkdownRuleToContinueRule( | |
| 135 | + "/path/to/rule.md", | |
| 136 | + content, | |
| 137 | + ); | |
| 138 | + expect(result.name).toBe("Test Rule Title"); | |
| 139 | + }); | |
| 140 | + | |
| 141 | + it("should use filename as name if no heading or frontmatter name", () => { | |
| 142 | + const content = `--- | |
| 143 | +globs: "**/test/**/*.kt" | |
| 144 | +--- | |
| 145 | + | |
| 146 | +This is a test rule without a heading.`; | |
| 147 | + | |
| 148 | + const result = convertMarkdownRuleToContinueRule( | |
| 149 | + "/path/to/custom-rule.md", | |
| 150 | + content, | |
| 151 | + ); | |
| 152 | + expect(result.name).toBe("custom-rule"); | |
| 153 | + }); | |
| 154 | + | |
| 155 | + it("should include description from frontmatter", () => { | |
| 156 | + const content = `--- | |
| 157 | +globs: "**/test/**/*.kt" | |
| 158 | +name: Test Rule | |
| 159 | +description: This is a rule description from frontmatter | |
| 160 | +--- | |
| 161 | + | |
| 162 | +# Test Rule | |
| 163 | + | |
| 164 | +This is the content of the rule.`; | |
| 165 | + | |
| 166 | + const result = convertMarkdownRuleToContinueRule( | |
| 167 | + "/path/to/rule.md", | |
| 168 | + content, | |
| 169 | + ); | |
| 170 | + expect(result.description).toBe( | |
| 171 | + "This is a rule description from frontmatter", | |
| 172 | + ); | |
| 173 | + }); | |
| 174 | +}); |
added core/config/markdown/parseMarkdownRule.ts +69 −0
| @@ -0,0 +1,69 @@ | ||
| 1 | +import { basename } from "path"; | |
| 2 | +import * as YAML from "yaml"; | |
| 3 | +import { RuleWithSource } from "../.."; | |
| 4 | + | |
| 5 | +/** | |
| 6 | + * Parses markdown content with YAML frontmatter | |
| 7 | + */ | |
| 8 | +export function parseMarkdownRule(content: string): { | |
| 9 | + frontmatter: Record<string, any>; | |
| 10 | + markdown: string; | |
| 11 | +} { | |
| 12 | + // Normalize line endings to \n | |
| 13 | + const normalizedContent = content.replace(/\r\n/g, "\n"); | |
| 14 | + | |
| 15 | + // More reliable frontmatter detection | |
| 16 | + const parts = normalizedContent.split(/^---\s*$/m); | |
| 17 | + | |
| 18 | + // If we have at least 3 parts (before ---, frontmatter, after ---), we have frontmatter | |
| 19 | + if (parts.length >= 3) { | |
| 20 | + const frontmatterStr = parts[1]; | |
| 21 | + // Join the remaining parts back together (in case there are more --- in the markdown) | |
| 22 | + const markdownContent = parts.slice(2).join("---"); | |
| 23 | + | |
| 24 | + try { | |
| 25 | + // Parse YAML frontmatter | |
| 26 | + const frontmatter = YAML.parse(frontmatterStr) || {}; // Handle empty frontmatter | |
| 27 | + return { frontmatter, markdown: markdownContent.trim() }; | |
| 28 | + } catch (e) { | |
| 29 | + // Error parsing frontmatter, treat as markdown only | |
| 30 | + console.warn("Error parsing markdown frontmatter:", e); | |
| 31 | + return { frontmatter: {}, markdown: normalizedContent }; | |
| 32 | + } | |
| 33 | + } | |
| 34 | + | |
| 35 | + // No frontmatter found | |
| 36 | + return { frontmatter: {}, markdown: normalizedContent }; | |
| 37 | +} | |
| 38 | + | |
| 39 | +/** | |
| 40 | + * Converts a markdown file with YAML frontmatter to a RuleWithSource object | |
| 41 | + */ | |
| 42 | +export function convertMarkdownRuleToContinueRule( | |
| 43 | + path: string, | |
| 44 | + content: string, | |
| 45 | +): RuleWithSource { | |
| 46 | + const { frontmatter, markdown } = parseMarkdownRule(content); | |
| 47 | + | |
| 48 | + // Try to extract title from first heading if no name in frontmatter | |
| 49 | + let name = frontmatter.name; | |
| 50 | + if (!name) { | |
| 51 | + // Look for a heading in the markdown | |
| 52 | + const headingMatch = markdown.match(/^#\s+(.+)$/m); | |
| 53 | + if (headingMatch) { | |
| 54 | + name = headingMatch[1].trim(); | |
| 55 | + } else { | |
| 56 | + // Fall back to filename | |
| 57 | + name = basename(path).replace(/\.md$/, ""); | |
| 58 | + } | |
| 59 | + } | |
| 60 | + | |
| 61 | + return { | |
| 62 | + name, | |
| 63 | + rule: markdown, | |
| 64 | + globs: frontmatter.globs, | |
| 65 | + description: frontmatter.description, | |
| 66 | + source: "rules-block", | |
| 67 | + ruleFile: path, | |
| 68 | + }; | |
| 69 | +} |
modified core/config/profile/doLoadConfig.ts +7 −0
| @@ -32,6 +32,7 @@ | ||
| 32 | 32 | import { TTS } from "../../util/tts"; |
| 33 | 33 | import { getWorkspaceContinueRuleDotFiles } from "../getWorkspaceContinueRuleDotFiles"; |
| 34 | 34 | import { loadContinueConfigFromJson } from "../load"; |
| 35 | +import { loadMarkdownRules } from "../markdown/loadMarkdownRules"; | |
| 35 | 36 | import { migrateJsonSharedConfig } from "../migrateSharedConfig"; |
| 36 | 37 | import { rectifySelectedModelsFromGlobalContext } from "../selectedModels"; |
| 37 | 38 | import { loadContinueConfigFromYaml } from "../yaml/loadYaml"; |
| @@ -128,6 +129,12 @@ | ||
| 128 | 129 | newConfig.rules.unshift(...rules); |
| 129 | 130 | errors.push(...continueRulesErrors); |
| 130 | 131 | |
| 132 | + // Add rules from markdown files in .continue/rules | |
| 133 | + const { rules: markdownRules, errors: markdownRulesErrors } = | |
| 134 | + await loadMarkdownRules(ide); | |
| 135 | + newConfig.rules.unshift(...markdownRules); | |
| 136 | + errors.push(...markdownRulesErrors); | |
| 137 | + | |
| 131 | 138 | // Rectify model selections for each role |
| 132 | 139 | newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId); |
| 133 | 140 |
modified core/config/util.ts +1 −0
| @@ -77,6 +77,7 @@ | ||
| 77 | 77 | model: model.model, |
| 78 | 78 | apiKey: model.apiKey, |
| 79 | 79 | apiBase: model.apiBase, |
| 80 | + maxStopWords: model.maxStopWords, | |
| 80 | 81 | defaultCompletionOptions: model.completionOptions, |
| 81 | 82 | }; |
| 82 | 83 | if (model.systemMessage) { |
modified core/config/yaml/loadYaml.ts +7 −8
| @@ -41,9 +41,8 @@ | ||
| 41 | 41 | import { modifyAnyConfigWithSharedConfig } from "../sharedConfig"; |
| 42 | 42 | |
| 43 | 43 | import { getControlPlaneEnvSync } from "../../control-plane/env"; |
| 44 | -import { logger } from "../../util/logger"; | |
| 45 | 44 | import { getCleanUriPath } from "../../util/uri"; |
| 46 | -import { getAllDotContinueYamlFiles } from "../loadLocalAssistants"; | |
| 45 | +import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants"; | |
| 47 | 46 | import { LocalPlatformClient } from "./LocalPlatformClient"; |
| 48 | 47 | import { llmsFromModelConfig } from "./models"; |
| 49 | 48 | |
| @@ -72,7 +71,7 @@ | ||
| 72 | 71 | command: server.command, |
| 73 | 72 | args: server.args ?? [], |
| 74 | 73 | env: server.env, |
| 75 | - }, | |
| 74 | + } as any, // TODO: Fix the mcpServers types in config-yaml (discriminated union) | |
| 76 | 75 | timeout: server.connectionTimeout, |
| 77 | 76 | }; |
| 78 | 77 | } |
| @@ -97,7 +96,7 @@ | ||
| 97 | 96 | // Add local .continue blocks |
| 98 | 97 | const allLocalBlocks: PackageIdentifier[] = []; |
| 99 | 98 | for (const blockType of BLOCK_TYPES) { |
| 100 | - const localBlocks = await getAllDotContinueYamlFiles( | |
| 99 | + const localBlocks = await getAllDotContinueDefinitionFiles( | |
| 101 | 100 | ide, |
| 102 | 101 | { includeGlobal: true, includeWorkspace: true }, |
| 103 | 102 | blockType, |
| @@ -115,9 +114,9 @@ | ||
| 115 | 114 | ? dirname(getCleanUriPath(packageIdentifier.filePath)) |
| 116 | 115 | : undefined; |
| 117 | 116 | |
| 118 | - logger.info( | |
| 119 | - `Loading config.yaml from ${JSON.stringify(packageIdentifier)} with root path ${rootPath}`, | |
| 120 | - ); | |
| 117 | + // logger.info( | |
| 118 | + // `Loading config.yaml from ${JSON.stringify(packageIdentifier)} with root path ${rootPath}`, | |
| 119 | + // ); | |
| 121 | 120 | |
| 122 | 121 | let config = |
| 123 | 122 | overrideConfigYaml ?? |
| @@ -459,7 +458,7 @@ | ||
| 459 | 458 | transport: { |
| 460 | 459 | type: "stdio", |
| 461 | 460 | args: [], |
| 462 | - ...server, | |
| 461 | + ...(server as any), // TODO: fix the types on mcpServers in config-yaml | |
| 463 | 462 | }, |
| 464 | 463 | timeout: server.connectionTimeout, |
| 465 | 464 | })), |
modified core/context/mcp/MCPConnection.ts +90 −79
| @@ -13,6 +13,7 @@ | ||
| 13 | 13 | MCPServerStatus, |
| 14 | 14 | MCPTool, |
| 15 | 15 | } from "../.."; |
| 16 | +import { getEnvPathFromUserShell } from "../../util/shellPath"; | |
| 16 | 17 | |
| 17 | 18 | const DEFAULT_MCP_TIMEOUT = 20_000; // 20 seconds |
| 18 | 19 | |
| @@ -29,17 +30,14 @@ | ||
| 29 | 30 | |
| 30 | 31 | class MCPConnection { |
| 31 | 32 | public client: Client; |
| 32 | - private transport: Transport; | |
| 33 | - | |
| 34 | - private connectionPromise: Promise<unknown> | null = null; | |
| 35 | 33 | public abortController: AbortController; |
| 36 | - | |
| 37 | 34 | public status: MCPConnectionStatus = "not-connected"; |
| 38 | 35 | public errors: string[] = []; |
| 39 | - | |
| 40 | 36 | public prompts: MCPPrompt[] = []; |
| 41 | 37 | public tools: MCPTool[] = []; |
| 42 | 38 | public resources: MCPResource[] = []; |
| 39 | + private transport: Transport; | |
| 40 | + private connectionPromise: Promise<unknown> | null = null; | |
| 43 | 41 | |
| 44 | 42 | constructor(public options: MCPOptions) { |
| 45 | 43 | this.transport = this.constructTransport(options); |
| @@ -63,80 +61,6 @@ | ||
| 63 | 61 | await this.transport.close(); |
| 64 | 62 | } |
| 65 | 63 | |
| 66 | - /** | |
| 67 | - * Resolves the command and arguments for the current platform | |
| 68 | - * On Windows, batch script commands need to be executed via cmd.exe | |
| 69 | - * @param originalCommand The original command | |
| 70 | - * @param originalArgs The original command arguments | |
| 71 | - * @returns An object with the resolved command and arguments | |
| 72 | - */ | |
| 73 | - private resolveCommandForPlatform( | |
| 74 | - originalCommand: string, | |
| 75 | - originalArgs: string[], | |
| 76 | - ): { command: string; args: string[] } { | |
| 77 | - // If not on Windows or not a batch command, return as-is | |
| 78 | - if ( | |
| 79 | - process.platform !== "win32" || | |
| 80 | - !WINDOWS_BATCH_COMMANDS.includes(originalCommand) | |
| 81 | - ) { | |
| 82 | - return { command: originalCommand, args: originalArgs }; | |
| 83 | - } | |
| 84 | - | |
| 85 | - // On Windows, we need to execute batch commands via cmd.exe | |
| 86 | - // Format: cmd.exe /c command [args] | |
| 87 | - return { | |
| 88 | - command: "cmd.exe", | |
| 89 | - args: ["/c", originalCommand, ...originalArgs], | |
| 90 | - }; | |
| 91 | - } | |
| 92 | - | |
| 93 | - private constructTransport(options: MCPOptions): Transport { | |
| 94 | - switch (options.transport.type) { | |
| 95 | - case "stdio": | |
| 96 | - const env: Record<string, string> = options.transport.env | |
| 97 | - ? { ...options.transport.env } | |
| 98 | - : {}; | |
| 99 | - | |
| 100 | - if (process.env.PATH !== undefined) { | |
| 101 | - env.PATH = process.env.PATH; | |
| 102 | - } | |
| 103 | - | |
| 104 | - // Resolve the command and args for the current platform | |
| 105 | - const { command, args } = this.resolveCommandForPlatform( | |
| 106 | - options.transport.command, | |
| 107 | - options.transport.args || [], | |
| 108 | - ); | |
| 109 | - | |
| 110 | - return new StdioClientTransport({ | |
| 111 | - command, | |
| 112 | - args, | |
| 113 | - env, | |
| 114 | - }); | |
| 115 | - case "websocket": | |
| 116 | - return new WebSocketClientTransport(new URL(options.transport.url)); | |
| 117 | - case "sse": | |
| 118 | - return new SSEClientTransport(new URL(options.transport.url), { | |
| 119 | - eventSourceInit: { | |
| 120 | - fetch: (input, init) => | |
| 121 | - fetch(input, { | |
| 122 | - ...init, | |
| 123 | - headers: { | |
| 124 | - ...init?.headers, | |
| 125 | - ...(options.transport.requestOptions?.headers as | |
| 126 | - | Record<string, string> | |
| 127 | - | undefined), | |
| 128 | - }, | |
| 129 | - }), | |
| 130 | - }, | |
| 131 | - requestInit: { headers: options.transport.requestOptions?.headers }, | |
| 132 | - }); | |
| 133 | - default: | |
| 134 | - throw new Error( | |
| 135 | - `Unsupported transport type: ${(options.transport as any).type}`, | |
| 136 | - ); | |
| 137 | - } | |
| 138 | - } | |
| 139 | - | |
| 140 | 64 | getStatus(): MCPServerStatus { |
| 141 | 65 | return { |
| 142 | 66 | ...this.options, |
| @@ -302,6 +226,93 @@ | ||
| 302 | 226 | |
| 303 | 227 | await this.connectionPromise; |
| 304 | 228 | } |
| 229 | + | |
| 230 | + /** | |
| 231 | + * Resolves the command and arguments for the current platform | |
| 232 | + * On Windows, batch script commands need to be executed via cmd.exe | |
| 233 | + * @param originalCommand The original command | |
| 234 | + * @param originalArgs The original command arguments | |
| 235 | + * @returns An object with the resolved command and arguments | |
| 236 | + */ | |
| 237 | + private resolveCommandForPlatform( | |
| 238 | + originalCommand: string, | |
| 239 | + originalArgs: string[], | |
| 240 | + ): { command: string; args: string[] } { | |
| 241 | + // If not on Windows or not a batch command, return as-is | |
| 242 | + if ( | |
| 243 | + process.platform !== "win32" || | |
| 244 | + !WINDOWS_BATCH_COMMANDS.includes(originalCommand) | |
| 245 | + ) { | |
| 246 | + return { command: originalCommand, args: originalArgs }; | |
| 247 | + } | |
| 248 | + | |
| 249 | + // On Windows, we need to execute batch commands via cmd.exe | |
| 250 | + // Format: cmd.exe /c command [args] | |
| 251 | + return { | |
| 252 | + command: "cmd.exe", | |
| 253 | + args: ["/c", originalCommand, ...originalArgs], | |
| 254 | + }; | |
| 255 | + } | |
| 256 | + | |
| 257 | + private constructTransport(options: MCPOptions): Transport { | |
| 258 | + switch (options.transport.type) { | |
| 259 | + case "stdio": | |
| 260 | + const env: Record<string, string> = options.transport.env | |
| 261 | + ? { ...options.transport.env } | |
| 262 | + : {}; | |
| 263 | + | |
| 264 | + if (process.env.PATH !== undefined) { | |
| 265 | + // Set the initial PATH from process.env | |
| 266 | + env.PATH = process.env.PATH; | |
| 267 | + | |
| 268 | + // For non-Windows platforms, try to get the PATH from user shell | |
| 269 | + if (process.platform !== "win32") { | |
| 270 | + try { | |
| 271 | + const shellEnvPath = getEnvPathFromUserShell(); | |
| 272 | + if (shellEnvPath && shellEnvPath !== process.env.PATH) { | |
| 273 | + env.PATH = shellEnvPath; | |
| 274 | + } | |
| 275 | + } catch (err) { | |
| 276 | + console.error("Error getting PATH:", err); | |
| 277 | + } | |
| 278 | + } | |
| 279 | + } | |
| 280 | + | |
| 281 | + // Resolve the command and args for the current platform | |
| 282 | + const { command, args } = this.resolveCommandForPlatform( | |
| 283 | + options.transport.command, | |
| 284 | + options.transport.args || [], | |
| 285 | + ); | |
| 286 | + | |
| 287 | + return new StdioClientTransport({ | |
| 288 | + command, | |
| 289 | + args, | |
| 290 | + env, | |
| 291 | + }); | |
| 292 | + case "websocket": | |
| 293 | + return new WebSocketClientTransport(new URL(options.transport.url)); | |
| 294 | + case "sse": | |
| 295 | + return new SSEClientTransport(new URL(options.transport.url), { | |
| 296 | + eventSourceInit: { | |
| 297 | + fetch: (input, init) => | |
| 298 | + fetch(input, { | |
| 299 | + ...init, | |
| 300 | + headers: { | |
| 301 | + ...init?.headers, | |
| 302 | + ...(options.transport.requestOptions?.headers as | |
| 303 | + | Record<string, string> | |
| 304 | + | undefined), | |
| 305 | + }, | |
| 306 | + }), | |
| 307 | + }, | |
| 308 | + requestInit: { headers: options.transport.requestOptions?.headers }, | |
| 309 | + }); | |
| 310 | + default: | |
| 311 | + throw new Error( | |
| 312 | + `Unsupported transport type: ${(options.transport as any).type}`, | |
| 313 | + ); | |
| 314 | + } | |
| 315 | + } | |
| 305 | 316 | } |
| 306 | 317 | |
| 307 | 318 | export default MCPConnection; |
added core/control-plane/AuthTypes.ts +55 −0
| @@ -0,0 +1,55 @@ | ||
| 1 | +export interface HubSessionInfo { | |
| 2 | + AUTH_TYPE: AuthType.WorkOsProd | AuthType.WorkOsStaging; | |
| 3 | + accessToken: string; | |
| 4 | + account: { | |
| 5 | + label: string; | |
| 6 | + id: string; | |
| 7 | + }; | |
| 8 | +} | |
| 9 | + | |
| 10 | +export interface OnPremSessionInfo { | |
| 11 | + AUTH_TYPE: AuthType.OnPrem; | |
| 12 | +} | |
| 13 | + | |
| 14 | +export type ControlPlaneSessionInfo = HubSessionInfo | OnPremSessionInfo; | |
| 15 | + | |
| 16 | +export function isHubSession( | |
| 17 | + sessionInfo: ControlPlaneSessionInfo | undefined, | |
| 18 | +): sessionInfo is HubSessionInfo { | |
| 19 | + return ( | |
| 20 | + sessionInfo !== undefined && | |
| 21 | + (sessionInfo.AUTH_TYPE === AuthType.WorkOsProd || | |
| 22 | + sessionInfo.AUTH_TYPE === AuthType.WorkOsStaging) | |
| 23 | + ); | |
| 24 | +} | |
| 25 | + | |
| 26 | +export enum AuthType { | |
| 27 | + WorkOsProd = "continue", | |
| 28 | + WorkOsStaging = "continue-staging", | |
| 29 | + OnPrem = "on-prem", | |
| 30 | +} | |
| 31 | + | |
| 32 | +export interface HubEnv { | |
| 33 | + DEFAULT_CONTROL_PLANE_PROXY_URL: string; | |
| 34 | + CONTROL_PLANE_URL: string; | |
| 35 | + AUTH_TYPE: AuthType.WorkOsProd | AuthType.WorkOsStaging; | |
| 36 | + WORKOS_CLIENT_ID: string; | |
| 37 | + APP_URL: string; | |
| 38 | +} | |
| 39 | + | |
| 40 | +export interface OnPremEnv { | |
| 41 | + AUTH_TYPE: AuthType.OnPrem; | |
| 42 | + DEFAULT_CONTROL_PLANE_PROXY_URL: string; | |
| 43 | + CONTROL_PLANE_URL: string; | |
| 44 | + APP_URL: string; | |
| 45 | +} | |
| 46 | + | |
| 47 | +export type ControlPlaneEnv = HubEnv | OnPremEnv; | |
| 48 | + | |
| 49 | +export function isHubEnv(env: ControlPlaneEnv): env is HubEnv { | |
| 50 | + return ( | |
| 51 | + "AUTH_TYPE" in env && | |
| 52 | + env.AUTH_TYPE !== "on-prem" && | |
| 53 | + "WORKOS_CLIENT_ID" in env | |
| 54 | + ); | |
| 55 | +} |
modified core/control-plane/auth/index.ts +6 −0
| @@ -1,5 +1,6 @@ | ||
| 1 | 1 | import { v4 as uuidv4 } from "uuid"; |
| 2 | 2 | import { IdeSettings } from "../.."; |
| 3 | +import { isHubEnv } from "../AuthTypes"; | |
| 3 | 4 | import { getControlPlaneEnv } from "../env"; |
| 4 | 5 | |
| 5 | 6 | export async function getAuthUrlForTokenPage( |
| @@ -7,6 +8,11 @@ | ||
| 7 | 8 | useOnboarding: boolean, |
| 8 | 9 | ): Promise<string> { |
| 9 | 10 | const env = await getControlPlaneEnv(ideSettingsPromise); |
| 11 | + | |
| 12 | + if (!isHubEnv(env)) { | |
| 13 | + throw new Error("Sign in disabled"); | |
| 14 | + } | |
| 15 | + | |
| 10 | 16 | const url = new URL("https://api.workos.com/user_management/authorize"); |
| 11 | 17 | const params = { |
| 12 | 18 | response_type: "code", |
modified core/control-plane/client.ts +17 −52
| @@ -12,16 +12,9 @@ | ||
| 12 | 12 | import { OrganizationDescription } from "../config/ProfileLifecycleManager.js"; |
| 13 | 13 | import { IdeSettings, ModelDescription } from "../index.js"; |
| 14 | 14 | |
| 15 | +import { ControlPlaneSessionInfo, isHubSession } from "./AuthTypes.js"; | |
| 15 | 16 | import { getControlPlaneEnv } from "./env.js"; |
| 16 | 17 | |
| 17 | -export interface ControlPlaneSessionInfo { | |
| 18 | - accessToken: string; | |
| 19 | - account: { | |
| 20 | - label: string; | |
| 21 | - id: string; | |
| 22 | - }; | |
| 23 | -} | |
| 24 | - | |
| 25 | 18 | export interface ControlPlaneWorkspace { |
| 26 | 19 | id: string; |
| 27 | 20 | name: string; |
| @@ -45,8 +38,7 @@ | ||
| 45 | 38 | fqsns: FQSN[], |
| 46 | 39 | orgScopeId: string | null, |
| 47 | 40 | ): Promise<(SecretResult | undefined)[]> { |
| 48 | - const userId = await this.userId; | |
| 49 | - if (!userId) { | |
| 41 | + if (!(await this.isSignedIn())) { | |
| 50 | 42 | return fqsns.map((fqsn) => ({ |
| 51 | 43 | found: false, |
| 52 | 44 | fqsn, |
| @@ -64,19 +56,24 @@ | ||
| 64 | 56 | return (await resp.json()) as any; |
| 65 | 57 | } |
| 66 | 58 | |
| 67 | - get userId(): Promise<string | undefined> { | |
| 68 | - return this.sessionInfoPromise.then( | |
| 69 | - (sessionInfo) => sessionInfo?.account.id, | |
| 70 | - ); | |
| 59 | + async isSignedIn(): Promise<boolean> { | |
| 60 | + const sessionInfo = await this.sessionInfoPromise; | |
| 61 | + return !!sessionInfo; | |
| 71 | 62 | } |
| 72 | 63 | |
| 73 | 64 | async getAccessToken(): Promise<string | undefined> { |
| 74 | - return (await this.sessionInfoPromise)?.accessToken; | |
| 65 | + const sessionInfo = await this.sessionInfoPromise; | |
| 66 | + return isHubSession(sessionInfo) ? sessionInfo.accessToken : undefined; | |
| 75 | 67 | } |
| 76 | 68 | |
| 77 | 69 | private async request(path: string, init: RequestInit): Promise<Response> { |
| 78 | - const accessToken = await this.getAccessToken(); | |
| 79 | - if (!accessToken) { | |
| 70 | + const sessionInfo = await this.sessionInfoPromise; | |
| 71 | + const hubSession = isHubSession(sessionInfo); | |
| 72 | + | |
| 73 | + const accessToken = hubSession ? sessionInfo.accessToken : undefined; | |
| 74 | + | |
| 75 | + // Bearer token not necessary for on-prem auth type | |
| 76 | + if (!accessToken && hubSession) { | |
| 80 | 77 | throw new Error("No access token"); |
| 81 | 78 | } |
| 82 | 79 | |
| @@ -99,22 +96,6 @@ | ||
| 99 | 96 | return resp; |
| 100 | 97 | } |
| 101 | 98 | |
| 102 | - public async listWorkspaces(): Promise<ControlPlaneWorkspace[]> { | |
| 103 | - const userId = await this.userId; | |
| 104 | - if (!userId) { | |
| 105 | - return []; | |
| 106 | - } | |
| 107 | - | |
| 108 | - try { | |
| 109 | - const resp = await this.request("workspaces", { | |
| 110 | - method: "GET", | |
| 111 | - }); | |
| 112 | - return (await resp.json()) as any; | |
| 113 | - } catch (e) { | |
| 114 | - return []; | |
| 115 | - } | |
| 116 | - } | |
| 117 | - | |
| 118 | 99 | public async listAssistants(organizationId: string | null): Promise< |
| 119 | 100 | { |
| 120 | 101 | configResult: ConfigResult<AssistantUnrolled>; |
| @@ -124,8 +105,7 @@ | ||
| 124 | 105 | rawYaml: string; |
| 125 | 106 | }[] |
| 126 | 107 | > { |
| 127 | - const userId = await this.userId; | |
| 128 | - if (!userId) { | |
| 108 | + if (!(await this.isSignedIn())) { | |
| 129 | 109 | return []; |
| 130 | 110 | } |
| 131 | 111 | |
| @@ -144,9 +124,7 @@ | ||
| 144 | 124 | } |
| 145 | 125 | |
| 146 | 126 | public async listOrganizations(): Promise<Array<OrganizationDescription>> { |
| 147 | - const userId = await this.userId; | |
| 148 | - | |
| 149 | - if (!userId) { | |
| 127 | + if (!(await this.isSignedIn())) { | |
| 150 | 128 | return []; |
| 151 | 129 | } |
| 152 | 130 | |
| @@ -164,8 +142,7 @@ | ||
| 164 | 142 | public async listAssistantFullSlugs( |
| 165 | 143 | organizationId: string | null, |
| 166 | 144 | ): Promise<FullSlug[] | null> { |
| 167 | - const userId = await this.userId; | |
| 168 | - if (!userId) { | |
| 145 | + if (!(await this.isSignedIn())) { | |
| 169 | 146 | return null; |
| 170 | 147 | } |
| 171 | 148 | |
| @@ -183,16 +160,4 @@ | ||
| 183 | 160 | return null; |
| 184 | 161 | } |
| 185 | 162 | } |
| 186 | - | |
| 187 | - async getSettingsForWorkspace(workspaceId: string): Promise<ConfigJson> { | |
| 188 | - const userId = await this.userId; | |
| 189 | - if (!userId) { | |
| 190 | - throw new Error("No user id"); | |
| 191 | - } | |
| 192 | - | |
| 193 | - const resp = await this.request(`workspaces/${workspaceId}`, { | |
| 194 | - method: "GET", | |
| 195 | - }); | |
| 196 | - return ((await resp.json()) as any).settings; | |
| 197 | - } | |
| 198 | 163 | } |
modified core/control-plane/env.ts +18 −15
| @@ -4,27 +4,18 @@ | ||
| 4 | 4 | getLocalEnvironmentDotFilePath, |
| 5 | 5 | getStagingEnvironmentDotFilePath, |
| 6 | 6 | } from "../util/paths"; |
| 7 | - | |
| 8 | -export interface ControlPlaneEnv { | |
| 9 | - DEFAULT_CONTROL_PLANE_PROXY_URL: string; | |
| 10 | - CONTROL_PLANE_URL: string; | |
| 11 | - AUTH_TYPE: string; | |
| 12 | - WORKOS_CLIENT_ID: string; | |
| 13 | - APP_URL: string; | |
| 14 | -} | |
| 7 | +import { AuthType, ControlPlaneEnv } from "./AuthTypes"; | |
| 8 | +import { getMdmKeys } from "./mdm"; | |
| 15 | 9 | |
| 16 | 10 | export const EXTENSION_NAME = "continue"; |
| 17 | 11 | |
| 18 | 12 | const WORKOS_CLIENT_ID_PRODUCTION = "client_01J0FW6XN8N2XJAECF7NE0Y65J"; |
| 19 | 13 | const WORKOS_CLIENT_ID_STAGING = "client_01J0FW6XCPMJMQ3CG51RB4HBZQ"; |
| 20 | 14 | |
| 21 | -const WORKOS_ENV_ID_PRODUCTION = "continue"; | |
| 22 | -const WORKOS_ENV_ID_STAGING = "continue-staging"; | |
| 23 | - | |
| 24 | 15 | const PRODUCTION_HUB_ENV: ControlPlaneEnv = { |
| 25 | 16 | DEFAULT_CONTROL_PLANE_PROXY_URL: "https://api.continue.dev/", |
| 26 | 17 | CONTROL_PLANE_URL: "https://api.continue.dev/", |
| 27 | - AUTH_TYPE: WORKOS_ENV_ID_PRODUCTION, | |
| 18 | + AUTH_TYPE: AuthType.WorkOsProd, | |
| 28 | 19 | WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_PRODUCTION, |
| 29 | 20 | APP_URL: "https://hub.continue.dev/", |
| 30 | 21 | }; |
| @@ -32,7 +23,7 @@ | ||
| 32 | 23 | const STAGING_ENV: ControlPlaneEnv = { |
| 33 | 24 | DEFAULT_CONTROL_PLANE_PROXY_URL: "https://api.continue-stage.tools/", |
| 34 | 25 | CONTROL_PLANE_URL: "https://api.continue-stage.tools/", |
| 35 | - AUTH_TYPE: WORKOS_ENV_ID_STAGING, | |
| 26 | + AUTH_TYPE: AuthType.WorkOsStaging, | |
| 36 | 27 | WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_STAGING, |
| 37 | 28 | APP_URL: "https://hub.continue-stage.tools/", |
| 38 | 29 | }; |
| @@ -40,7 +31,7 @@ | ||
| 40 | 31 | const TEST_ENV: ControlPlaneEnv = { |
| 41 | 32 | DEFAULT_CONTROL_PLANE_PROXY_URL: "https://api-test.continue.dev/", |
| 42 | 33 | CONTROL_PLANE_URL: "https://api-test.continue.dev/", |
| 43 | - AUTH_TYPE: WORKOS_ENV_ID_STAGING, | |
| 34 | + AUTH_TYPE: AuthType.WorkOsStaging, | |
| 44 | 35 | WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_STAGING, |
| 45 | 36 | APP_URL: "https://app-test.continue.dev/", |
| 46 | 37 | }; |
| @@ -48,7 +39,7 @@ | ||
| 48 | 39 | const LOCAL_ENV: ControlPlaneEnv = { |
| 49 | 40 | DEFAULT_CONTROL_PLANE_PROXY_URL: "http://localhost:3001/", |
| 50 | 41 | CONTROL_PLANE_URL: "http://localhost:3001/", |
| 51 | - AUTH_TYPE: WORKOS_ENV_ID_STAGING, | |
| 42 | + AUTH_TYPE: AuthType.WorkOsStaging, | |
| 52 | 43 | WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_STAGING, |
| 53 | 44 | APP_URL: "http://localhost:3000/", |
| 54 | 45 | }; |
| @@ -67,6 +58,18 @@ | ||
| 67 | 58 | export function getControlPlaneEnvSync( |
| 68 | 59 | ideTestEnvironment: IdeSettings["continueTestEnvironment"], |
| 69 | 60 | ): ControlPlaneEnv { |
| 61 | + // MDM override | |
| 62 | + const mdmKeys = getMdmKeys(); | |
| 63 | + if (mdmKeys) { | |
| 64 | + const { apiUrl } = mdmKeys; | |
| 65 | + return { | |
| 66 | + AUTH_TYPE: AuthType.OnPrem, | |
| 67 | + DEFAULT_CONTROL_PLANE_PROXY_URL: apiUrl, | |
| 68 | + CONTROL_PLANE_URL: apiUrl, | |
| 69 | + APP_URL: "https://hub.continue.dev/", | |
| 70 | + }; | |
| 71 | + } | |
| 72 | + | |
| 70 | 73 | // Note .local overrides .staging |
| 71 | 74 | if (fs.existsSync(getLocalEnvironmentDotFilePath())) { |
| 72 | 75 | return LOCAL_ENV; |
added core/control-plane/mdm.test.ts +127 −0
| @@ -0,0 +1,127 @@ | ||
| 1 | +import * as crypto from "crypto"; | |
| 2 | +import { LicenseData, validateLicenseKey } from "./mdm"; | |
| 3 | + | |
| 4 | +// We'll create a real key pair once for all tests | |
| 5 | +const testKeyPair = crypto.generateKeyPairSync("rsa", { | |
| 6 | + modulusLength: 2048, | |
| 7 | + publicKeyEncoding: { | |
| 8 | + type: "spki", | |
| 9 | + format: "pem", | |
| 10 | + }, | |
| 11 | + privateKeyEncoding: { | |
| 12 | + type: "pkcs8", | |
| 13 | + format: "pem", | |
| 14 | + }, | |
| 15 | +}); | |
| 16 | + | |
| 17 | +// Custom function to create test licenses (replaces the original mock-dependent one) | |
| 18 | +function createTestLicense( | |
| 19 | + licenseData: LicenseData, | |
| 20 | + useValidSignature: boolean = true, | |
| 21 | +): string { | |
| 22 | + // Convert license data to a string | |
| 23 | + const licenseDataStr = JSON.stringify(licenseData); | |
| 24 | + | |
| 25 | + // Create a signature with our generated private key | |
| 26 | + const sign = crypto.createSign("SHA256"); | |
| 27 | + sign.update(licenseDataStr); | |
| 28 | + sign.end(); | |
| 29 | + | |
| 30 | + let signature: string; | |
| 31 | + if (useValidSignature) { | |
| 32 | + signature = sign.sign(testKeyPair.privateKey, "base64"); | |
| 33 | + } else { | |
| 34 | + // For invalid tests, create an intentionally wrong signature by signing different data | |
| 35 | + const wrongSign = crypto.createSign("SHA256"); | |
| 36 | + wrongSign.update(licenseDataStr + "tampered"); | |
| 37 | + wrongSign.end(); | |
| 38 | + signature = wrongSign.sign(testKeyPair.privateKey, "base64"); | |
| 39 | + } | |
| 40 | + // Combine data and signature into a license key | |
| 41 | + const licenseKeyObj = { | |
| 42 | + data: licenseDataStr, | |
| 43 | + signature: signature, | |
| 44 | + }; | |
| 45 | + | |
| 46 | + return Buffer.from(JSON.stringify(licenseKeyObj)).toString("base64"); | |
| 47 | +} | |
| 48 | + | |
| 49 | +// We need to test the actual implementation - which we can't mock with ESM | |
| 50 | +// Instead, we'll have tests that bypass validation or are expected to fail | |
| 51 | +// depending on what we're testing | |
| 52 | + | |
| 53 | +test("validateLicenseKey returns false for malformed license key", () => { | |
| 54 | + // Test with a completely invalid license key | |
| 55 | + const invalidLicenseKey = "not-a-valid-license-key"; | |
| 56 | + | |
| 57 | + // Test - no mocks, real validation | |
| 58 | + const result = validateLicenseKey(invalidLicenseKey); | |
| 59 | + | |
| 60 | + // Assert | |
| 61 | + expect(result).toBe(false); | |
| 62 | +}); | |
| 63 | + | |
| 64 | +test("validateLicenseKey returns false for invalid JSON in license key", () => { | |
| 65 | + // Create a malformed but base64-encoded string | |
| 66 | + const malformedLicenseKey = Buffer.from("this is not valid JSON").toString( | |
| 67 | + "base64", | |
| 68 | + ); | |
| 69 | + | |
| 70 | + // Test - no mocks, real validation | |
| 71 | + const result = validateLicenseKey(malformedLicenseKey); | |
| 72 | + | |
| 73 | + // Assert | |
| 74 | + expect(result).toBe(false); | |
| 75 | +}); | |
| 76 | + | |
| 77 | +test("validateLicenseKey returns false for expired license", () => { | |
| 78 | + // Without mocking, we expect this to fail signature verification | |
| 79 | + // We're testing the date logic by itself | |
| 80 | + const licenseData: LicenseData = { | |
| 81 | + customerId: "customer123", | |
| 82 | + createdAt: new Date(Date.now() - 2000 * 60 * 60 * 24).toISOString(), // Created 2 days ago | |
| 83 | + expiresAt: new Date(Date.now() - 1000 * 60 * 60 * 24).toISOString(), // Expired 1 day ago | |
| 84 | + }; | |
| 85 | + | |
| 86 | + // Create a license key - will fail verification but test logic still works | |
| 87 | + const expiredLicenseKey = createTestLicense(licenseData); | |
| 88 | + | |
| 89 | + // Test - expect false, either due to signature or expiration - both are valid test cases | |
| 90 | + const result = validateLicenseKey(expiredLicenseKey); | |
| 91 | + | |
| 92 | + // Assert | |
| 93 | + expect(result).toBe(false); | |
| 94 | +}); | |
| 95 | + | |
| 96 | +test("validateLicenseKey returns false for invalid signature", () => { | |
| 97 | + // Create license data with valid dates | |
| 98 | + const licenseData: LicenseData = { | |
| 99 | + customerId: "customer123", | |
| 100 | + createdAt: new Date().toISOString(), | |
| 101 | + expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24).toISOString(), // Valid for 1 day | |
| 102 | + }; | |
| 103 | + | |
| 104 | + // Create a license with an invalid signature | |
| 105 | + const invalidSignatureKey = createTestLicense(licenseData, false); | |
| 106 | + | |
| 107 | + // Test - no mocks, real validation | |
| 108 | + const result = validateLicenseKey(invalidSignatureKey); | |
| 109 | + | |
| 110 | + // Assert | |
| 111 | + expect(result).toBe(false); | |
| 112 | +}); | |
| 113 | + | |
| 114 | +test("validateLicenseKey handles JSON parsing errors gracefully", () => { | |
| 115 | + // Create a base64 string that decodes to valid JSON but lacks required fields | |
| 116 | + const invalidStructureKey = Buffer.from( | |
| 117 | + JSON.stringify({ | |
| 118 | + notTheRightField: "wrong structure", | |
| 119 | + }), | |
| 120 | + ).toString("base64"); | |
| 121 | + | |
| 122 | + // Test - no mocks, real validation | |
| 123 | + const result = validateLicenseKey(invalidStructureKey); | |
| 124 | + | |
| 125 | + // Assert | |
| 126 | + expect(result).toBe(false); | |
| 127 | +}); |
added core/control-plane/mdm.ts +262 −0
| @@ -0,0 +1,262 @@ | ||
| 1 | +import * as crypto from "crypto"; | |
| 2 | +import * as fs from "fs"; | |
| 3 | +import * as os from "os"; | |
| 4 | +import * as path from "path"; | |
| 5 | +import * as plist from "plist"; | |
| 6 | + | |
| 7 | +export interface MdmKeys { | |
| 8 | + licenseKey: string; | |
| 9 | + apiUrl: string; | |
| 10 | +} | |
| 11 | + | |
| 12 | +const CONTINUE_PUBLIC_KEY = `-----BEGIN PUBLIC KEY----- | |
| 13 | +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz1pFVzsW2UScSnaPAwFp | |
| 14 | +93QU4+txtyJj8AOC3Kx7YkX1d48DGU2Fy1he7SXPHgcuhXYIqfWGn/Vy/4yJxXD7 | |
| 15 | +HlU8RM7LlWHRk7ecAvF4WtxZDjPE0OSG5T69w5f7tMCtQPQseInCKqleJuCjxrvA | |
| 16 | +zyTWTwKA1S6e+KxXS/kbqsumriljFujNr6Gmh8ygDnpF055Xo0vTenkMipVw/oYn | |
| 17 | +U0EHx5ic+Fmcob3EyOj25lu/CVYtU1Rn8jPbrBOMiIq5sePh2QXOwGRsuTiZk2mP | |
| 18 | +LXSsjLbeWHifRrQ18wj/PC990E33QaFGNFp0NcBXMPbq5eKYKEzKZ0GsxtLoGxar | |
| 19 | +FQIDAQAB | |
| 20 | +-----END PUBLIC KEY-----`; | |
| 21 | + | |
| 22 | +export interface LicenseData { | |
| 23 | + customerId: string; | |
| 24 | + createdAt: string; | |
| 25 | + expiresAt: string; | |
| 26 | +} | |
| 27 | + | |
| 28 | +export function validateLicenseKey(licenseKey: string): boolean { | |
| 29 | + try { | |
| 30 | + // Decode the base64 license key | |
| 31 | + const decodedString = Buffer.from(licenseKey, "base64").toString("utf8"); | |
| 32 | + const { data, signature } = JSON.parse(decodedString); | |
| 33 | + | |
| 34 | + // Verify the signature | |
| 35 | + const verify = crypto.createVerify("SHA256"); | |
| 36 | + verify.update(data); | |
| 37 | + verify.end(); | |
| 38 | + | |
| 39 | + const isValid = verify.verify(CONTINUE_PUBLIC_KEY, signature, "base64"); | |
| 40 | + | |
| 41 | + if (!isValid) return false; | |
| 42 | + | |
| 43 | + // Check license expiration | |
| 44 | + const licenseData: LicenseData = JSON.parse(data); | |
| 45 | + const expirationDate = new Date(licenseData.expiresAt); | |
| 46 | + const now = new Date(); | |
| 47 | + | |
| 48 | + return expirationDate > now; | |
| 49 | + } catch (error) { | |
| 50 | + console.error("License validation error:", error); | |
| 51 | + return false; | |
| 52 | + } | |
| 53 | +} | |
| 54 | + | |
| 55 | +function extractConfigFromArray(config: any[]): Record<string, string> { | |
| 56 | + const configObj: Record<string, string> = {}; | |
| 57 | + | |
| 58 | + for (let i = 0; i < config.length; i += 2) { | |
| 59 | + if (i + 1 < config.length) { | |
| 60 | + const key = config[i]; | |
| 61 | + const value = config[i + 1]; | |
| 62 | + if (typeof key === "string") { | |
| 63 | + configObj[key] = value as string; | |
| 64 | + } | |
| 65 | + } | |
| 66 | + } | |
| 67 | + | |
| 68 | + return configObj; | |
| 69 | +} | |
| 70 | + | |
| 71 | +const MACOS_MDM_PATHS = [ | |
| 72 | + // Organization-specific MDM plist | |
| 73 | + "/Library/Managed Preferences/dev.continue.app.plist", | |
| 74 | + // User-specific MDM plist | |
| 75 | + path.join(os.homedir(), "Library/Managed Preferences/dev.continue.app.plist"), | |
| 76 | +]; | |
| 77 | + | |
| 78 | +function readMdmKeysMacOS(): MdmKeys | undefined { | |
| 79 | + try { | |
| 80 | + // MDM configuration is typically stored in /Library/Managed Preferences/ on macOS | |
| 81 | + // The filename is often the bundle identifier of the application | |
| 82 | + | |
| 83 | + // Try to find a valid MDM configuration file | |
| 84 | + for (const mdmPath of MACOS_MDM_PATHS) { | |
| 85 | + if (fs.existsSync(mdmPath)) { | |
| 86 | + // Read the file content | |
| 87 | + const fileContent = fs.readFileSync(mdmPath, "utf8"); | |
| 88 | + | |
| 89 | + try { | |
| 90 | + // Parse the plist file using the plist package | |
| 91 | + const config = plist.parse(fileContent); | |
| 92 | + | |
| 93 | + // Extract the relevant fields from the config | |
| 94 | + // Config is an array of alternating keys and values | |
| 95 | + if (Array.isArray(config)) { | |
| 96 | + const configObj = extractConfigFromArray(config); | |
| 97 | + | |
| 98 | + // Check if required keys are present | |
| 99 | + if (configObj.licenseKey && configObj.apiUrl) { | |
| 100 | + return { | |
| 101 | + licenseKey: configObj.licenseKey, | |
| 102 | + apiUrl: configObj.apiUrl, | |
| 103 | + }; | |
| 104 | + } | |
| 105 | + } | |
| 106 | + } catch (parseError) { | |
| 107 | + console.error(`Error parsing MDM configuration: ${parseError}`); | |
| 108 | + } | |
| 109 | + } | |
| 110 | + } | |
| 111 | + | |
| 112 | + return undefined; | |
| 113 | + } catch (error) { | |
| 114 | + console.error("Error reading macOS MDM keys:", error); | |
| 115 | + return undefined; | |
| 116 | + } | |
| 117 | +} | |
| 118 | + | |
| 119 | +function readMdmKeysWindows(): MdmKeys | undefined { | |
| 120 | + try { | |
| 121 | + // For Windows, we need to read from the registry | |
| 122 | + // Using regedit or another synchronous registry access module | |
| 123 | + const { execSync } = require("child_process"); | |
| 124 | + | |
| 125 | + // Path to the registry where MDM configuration is stored | |
| 126 | + const regPath = "HKLM\\Software\\Continue\\MDM"; | |
| 127 | + const userRegPath = "HKCU\\Software\\Continue\\MDM"; | |
| 128 | + | |
| 129 | + // Try to read from HKEY_LOCAL_MACHINE first | |
| 130 | + try { | |
| 131 | + // Use REG QUERY command to read registry values | |
| 132 | + const licenseKeyCmd = `reg query "${regPath}" /v licenseKey`; | |
| 133 | + const apiUrlCmd = `reg query "${regPath}" /v apiUrl`; | |
| 134 | + | |
| 135 | + const licenseKeyOutput = execSync(licenseKeyCmd, { encoding: "utf8" }); | |
| 136 | + const apiUrlOutput = execSync(apiUrlCmd, { encoding: "utf8" }); | |
| 137 | + | |
| 138 | + // Extract values from command output | |
| 139 | + const licenseKey = extractRegValue(licenseKeyOutput); | |
| 140 | + const apiUrl = extractRegValue(apiUrlOutput); | |
| 141 | + | |
| 142 | + if (licenseKey && apiUrl) { | |
| 143 | + return { licenseKey, apiUrl }; | |
| 144 | + } | |
| 145 | + } catch (error) { | |
| 146 | + // Registry key might not exist, fallback to HKEY_CURRENT_USER | |
| 147 | + } | |
| 148 | + | |
| 149 | + // Try HKEY_CURRENT_USER if not found in HKEY_LOCAL_MACHINE | |
| 150 | + try { | |
| 151 | + const licenseKeyCmd = `reg query "${userRegPath}" /v licenseKey`; | |
| 152 | + const apiUrlCmd = `reg query "${userRegPath}" /v apiUrl`; | |
| 153 | + | |
| 154 | + const licenseKeyOutput = execSync(licenseKeyCmd, { encoding: "utf8" }); | |
| 155 | + const apiUrlOutput = execSync(apiUrlCmd, { encoding: "utf8" }); | |
| 156 | + | |
| 157 | + // Extract values from command output | |
| 158 | + const licenseKey = extractRegValue(licenseKeyOutput); | |
| 159 | + const apiUrl = extractRegValue(apiUrlOutput); | |
| 160 | + | |
| 161 | + if (licenseKey && apiUrl) { | |
| 162 | + return { licenseKey, apiUrl }; | |
| 163 | + } | |
| 164 | + } catch (error) { | |
| 165 | + // Registry key might not exist in HKCU either | |
| 166 | + } | |
| 167 | + | |
| 168 | + return undefined; | |
| 169 | + } catch (error) { | |
| 170 | + console.error("Error reading Windows MDM keys:", error); | |
| 171 | + return undefined; | |
| 172 | + } | |
| 173 | +} | |
| 174 | + | |
| 175 | +// Helper function to extract registry values from reg query output | |
| 176 | +function extractRegValue(output: string): string | undefined { | |
| 177 | + const match = output.match(/REG_SZ\s+(.+)$/m); | |
| 178 | + return match ? match[1].trim() : undefined; | |
| 179 | +} | |
| 180 | + | |
| 181 | +// Common locations for MDM configurations in Linux systems | |
| 182 | +const LINUX_MDM_PATHS = [ | |
| 183 | + // System-wide configuration | |
| 184 | + "/etc/continue/mdm.json", | |
| 185 | + "/var/lib/continue/mdm.json", | |
| 186 | + // User-specific configuration | |
| 187 | + path.join(os.homedir(), ".config/continue/mdm.json"), | |
| 188 | +]; | |
| 189 | + | |
| 190 | +function readMdmKeysLinux(): MdmKeys | undefined { | |
| 191 | + try { | |
| 192 | + // Try to find a valid MDM configuration file | |
| 193 | + for (const mdmPath of LINUX_MDM_PATHS) { | |
| 194 | + if (fs.existsSync(mdmPath)) { | |
| 195 | + // Read the file content | |
| 196 | + const fileContent = fs.readFileSync(mdmPath, "utf8"); | |
| 197 | + | |
| 198 | + try { | |
| 199 | + // Parse the JSON configuration file | |
| 200 | + const config = JSON.parse(fileContent); | |
| 201 | + | |
| 202 | + // Check if required keys are present | |
| 203 | + if (config.licenseKey && config.apiUrl) { | |
| 204 | + return { | |
| 205 | + licenseKey: config.licenseKey, | |
| 206 | + apiUrl: config.apiUrl, | |
| 207 | + }; | |
| 208 | + } | |
| 209 | + } catch (parseError) { | |
| 210 | + console.error(`Error parsing Linux MDM configuration: ${parseError}`); | |
| 211 | + } | |
| 212 | + } | |
| 213 | + } | |
| 214 | + | |
| 215 | + return undefined; | |
| 216 | + } catch (error) { | |
| 217 | + console.error("Error reading Linux MDM keys:", error); | |
| 218 | + return undefined; | |
| 219 | + } | |
| 220 | +} | |
| 221 | + | |
| 222 | +function readMdmKeys(): MdmKeys | undefined { | |
| 223 | + const platform = os.platform(); | |
| 224 | + | |
| 225 | + switch (platform) { | |
| 226 | + case "darwin": | |
| 227 | + return readMdmKeysMacOS(); | |
| 228 | + | |
| 229 | + case "win32": | |
| 230 | + return readMdmKeysWindows(); | |
| 231 | + | |
| 232 | + case "linux": | |
| 233 | + return readMdmKeysLinux(); | |
| 234 | + | |
| 235 | + default: | |
| 236 | + console.error(`MDM keys not supported on platform: ${platform}`); | |
| 237 | + return undefined; | |
| 238 | + } | |
| 239 | +} | |
| 240 | + | |
| 241 | +/** | |
| 242 | + * Read and validate MDM keys from the operating system's configuration files or registry. | |
| 243 | + */ | |
| 244 | +export function getMdmKeys(): MdmKeys | undefined { | |
| 245 | + try { | |
| 246 | + const mdmKeys = readMdmKeys(); | |
| 247 | + | |
| 248 | + if (mdmKeys) { | |
| 249 | + if (!validateLicenseKey(mdmKeys.licenseKey)) { | |
| 250 | + console.error("Invalid license key found: ", mdmKeys.licenseKey); | |
| 251 | + return undefined; | |
| 252 | + } | |
| 253 | + | |
| 254 | + return mdmKeys; | |
| 255 | + } | |
| 256 | + | |
| 257 | + return undefined; | |
| 258 | + } catch (e) { | |
| 259 | + console.warn("Error reading MDM keys: ", e); | |
| 260 | + return undefined; | |
| 261 | + } | |
| 262 | +} |
modified core/control-plane/schema.ts +1 −0
| @@ -26,6 +26,7 @@ | ||
| 26 | 26 | apiKey: z.string().optional(), |
| 27 | 27 | apiBase: z.string().optional(), |
| 28 | 28 | contextLength: z.number().optional(), |
| 29 | + maxStopWords: z.number().optional(), | |
| 29 | 30 | template: z |
| 30 | 31 | .enum([ |
| 31 | 32 | "llama2", |
added core/data/log.test.ts +192 −0
| @@ -0,0 +1,192 @@ | ||
| 1 | +import { DevDataLogEvent } from "@continuedev/config-yaml"; | |
| 2 | +import fs from "fs"; | |
| 3 | +import path from "path"; | |
| 4 | +import { IdeInfo, IdeSettings } from ".."; | |
| 5 | +import { Core } from "../core"; | |
| 6 | +import { getDevDataFilePath } from "../util/paths"; | |
| 7 | +import { DataLogger } from "./log"; | |
| 8 | + | |
| 9 | +// Only mock fetch, not fs | |
| 10 | +jest.mock("@continuedev/fetch"); | |
| 11 | + | |
| 12 | +const TEST_EVENT: DevDataLogEvent = { | |
| 13 | + name: "tokensGenerated", | |
| 14 | + data: { | |
| 15 | + generatedTokens: 100, | |
| 16 | + model: "gpt-4", | |
| 17 | + promptTokens: 50, | |
| 18 | + provider: "openai", | |
| 19 | + }, | |
| 20 | +}; | |
| 21 | +const SCHEMA = "0.2.0"; | |
| 22 | + | |
| 23 | +describe("DataLogger", () => { | |
| 24 | + let dataLogger: DataLogger; | |
| 25 | + const tempDir = path.join(process.cwd(), "temp-test-data"); | |
| 26 | + const testFilePath = path.join(tempDir, "tokensGenerated-test.jsonl"); | |
| 27 | + | |
| 28 | + // Create temp directory for test files | |
| 29 | + beforeAll(() => { | |
| 30 | + if (!fs.existsSync(tempDir)) { | |
| 31 | + fs.mkdirSync(tempDir, { recursive: true }); | |
| 32 | + } | |
| 33 | + }); | |
| 34 | + | |
| 35 | + // Clean up temp directory after tests | |
| 36 | + afterAll(() => { | |
| 37 | + if (fs.existsSync(tempDir)) { | |
| 38 | + fs.rmSync(tempDir, { recursive: true, force: true }); | |
| 39 | + } | |
| 40 | + }); | |
| 41 | + | |
| 42 | + beforeEach(() => { | |
| 43 | + // Reset mocks | |
| 44 | + jest.clearAllMocks(); | |
| 45 | + | |
| 46 | + // Remove test file if it exists | |
| 47 | + if (fs.existsSync(testFilePath)) { | |
| 48 | + fs.unlinkSync(testFilePath); | |
| 49 | + } | |
| 50 | + | |
| 51 | + // Get singleton instance | |
| 52 | + dataLogger = DataLogger.getInstance(); | |
| 53 | + | |
| 54 | + // Mock core and required promises | |
| 55 | + dataLogger.core = { | |
| 56 | + configHandler: { | |
| 57 | + loadConfig: jest.fn().mockResolvedValue({ | |
| 58 | + config: { | |
| 59 | + data: [], | |
| 60 | + }, | |
| 61 | + }), | |
| 62 | + currentProfile: { | |
| 63 | + profileDescription: { | |
| 64 | + id: "test-profile-id", | |
| 65 | + }, | |
| 66 | + }, | |
| 67 | + controlPlaneClient: { | |
| 68 | + getAccessToken: jest.fn().mockResolvedValue("test-access-token"), | |
| 69 | + }, | |
| 70 | + }, | |
| 71 | + } as unknown as Core; | |
| 72 | + | |
| 73 | + dataLogger.ideSettingsPromise = Promise.resolve({ | |
| 74 | + userToken: "test-user-token", | |
| 75 | + } as IdeSettings); | |
| 76 | + | |
| 77 | + dataLogger.ideInfoPromise = Promise.resolve({ | |
| 78 | + name: "VSCode", | |
| 79 | + version: "1.0.0", | |
| 80 | + extensionVersion: "0.1.0", | |
| 81 | + } as IdeInfo); | |
| 82 | + }); | |
| 83 | + | |
| 84 | + describe("getInstance", () => { | |
| 85 | + it("should return the same instance when called multiple times", () => { | |
| 86 | + const instance1 = DataLogger.getInstance(); | |
| 87 | + const instance2 = DataLogger.getInstance(); | |
| 88 | + expect(instance1).toBe(instance2); | |
| 89 | + }); | |
| 90 | + }); | |
| 91 | + | |
| 92 | + describe("addBaseValues", () => { | |
| 93 | + it("should add base values to event data based on schema", async () => { | |
| 94 | + const mockZodSchema = { | |
| 95 | + shape: { | |
| 96 | + eventName: true, | |
| 97 | + timestamp: true, | |
| 98 | + schema: true, | |
| 99 | + userAgent: true, | |
| 100 | + selectedProfileId: true, | |
| 101 | + userId: true, | |
| 102 | + }, | |
| 103 | + }; | |
| 104 | + | |
| 105 | + const result = await dataLogger.addBaseValues( | |
| 106 | + { customField: "value" }, | |
| 107 | + "testEvent", | |
| 108 | + SCHEMA, | |
| 109 | + mockZodSchema as any, | |
| 110 | + ); | |
| 111 | + | |
| 112 | + expect(result).toEqual({ | |
| 113 | + customField: "value", | |
| 114 | + eventName: "testEvent", | |
| 115 | + timestamp: expect.any(String), | |
| 116 | + schema: SCHEMA, | |
| 117 | + userAgent: "VSCode/1.0.0 (Continue/0.1.0)", | |
| 118 | + selectedProfileId: "test-profile-id", | |
| 119 | + userId: "test-user-token", | |
| 120 | + }); | |
| 121 | + }); | |
| 122 | + | |
| 123 | + it("should not add fields not present in schema shape", async () => { | |
| 124 | + const mockZodSchema = { | |
| 125 | + shape: { | |
| 126 | + eventName: true, | |
| 127 | + // No other fields | |
| 128 | + }, | |
| 129 | + }; | |
| 130 | + | |
| 131 | + const result = await dataLogger.addBaseValues( | |
| 132 | + { customField: "value" }, | |
| 133 | + "testEvent", | |
| 134 | + SCHEMA, | |
| 135 | + mockZodSchema as any, | |
| 136 | + ); | |
| 137 | + | |
| 138 | + expect(result).toEqual({ | |
| 139 | + customField: "value", | |
| 140 | + eventName: "testEvent", | |
| 141 | + }); | |
| 142 | + }); | |
| 143 | + }); | |
| 144 | + | |
| 145 | + describe("logLocalData", () => { | |
| 146 | + it("should actually write data to the local file", async () => { | |
| 147 | + // Call the method to log data locally | |
| 148 | + await dataLogger.logLocalData(TEST_EVENT); | |
| 149 | + | |
| 150 | + // Verify the file was created | |
| 151 | + const filepath = getDevDataFilePath(TEST_EVENT.name, SCHEMA); | |
| 152 | + expect(fs.existsSync(filepath)).toBe(true); | |
| 153 | + | |
| 154 | + // Read file contents and verify | |
| 155 | + const fileContent = fs.readFileSync(filepath, "utf8"); | |
| 156 | + expect(fileContent).toContain('"generatedTokens":100'); | |
| 157 | + expect(fileContent).toContain('"model":"gpt-4"'); | |
| 158 | + expect(fileContent).toContain('"eventName":"tokensGenerated"'); | |
| 159 | + }); | |
| 160 | + }); | |
| 161 | + | |
| 162 | + describe("logDevData", () => { | |
| 163 | + it("should log data locally and to configured destinations", async () => { | |
| 164 | + // Spy on logLocalData and logToOneDestination | |
| 165 | + const logLocalDataSpy = jest | |
| 166 | + .spyOn(dataLogger, "logLocalData") | |
| 167 | + .mockResolvedValue(); | |
| 168 | + const logToOneDestinationSpy = jest | |
| 169 | + .spyOn(dataLogger, "logToOneDestination") | |
| 170 | + .mockResolvedValue(); | |
| 171 | + | |
| 172 | + // Mock config with multiple data destinations | |
| 173 | + const mockConfig = { | |
| 174 | + config: { | |
| 175 | + data: [ | |
| 176 | + { destination: "https://example.com/logs", schema: SCHEMA }, | |
| 177 | + { destination: "file:///logs", schema: SCHEMA }, | |
| 178 | + ], | |
| 179 | + }, | |
| 180 | + }; | |
| 181 | + | |
| 182 | + dataLogger.core!.configHandler.loadConfig = jest | |
| 183 | + .fn() | |
| 184 | + .mockResolvedValue(mockConfig); | |
| 185 | + | |
| 186 | + await dataLogger.logDevData(TEST_EVENT); | |
| 187 | + | |
| 188 | + expect(logLocalDataSpy).toHaveBeenCalledWith(TEST_EVENT); | |
| 189 | + expect(logToOneDestinationSpy).toHaveBeenCalledTimes(2); | |
| 190 | + }); | |
| 191 | + }); | |
| 192 | +}); |
modified core/data/log.ts +134 −117
| @@ -12,7 +12,7 @@ | ||
| 12 | 12 | import { fileURLToPath } from "url"; |
| 13 | 13 | import { AnyZodObject } from "zod"; |
| 14 | 14 | import { Core } from "../core.js"; |
| 15 | -import { IdeInfo, IdeSettings } from "../index.js"; | |
| 15 | +import { ContinueConfig, IdeInfo, IdeSettings } from "../index.js"; | |
| 16 | 16 | import { getDevDataFilePath } from "../util/paths.js"; |
| 17 | 17 | import { joinPathsToUri } from "../util/uri.js"; |
| 18 | 18 | |
| @@ -68,8 +68,7 @@ | ||
| 68 | 68 | return newBody; |
| 69 | 69 | } |
| 70 | 70 | |
| 71 | - async logDevData(event: DevDataLogEvent) { | |
| 72 | - // Local logs (always on for all levels) | |
| 71 | + async logLocalData(event: DevDataLogEvent) { | |
| 73 | 72 | try { |
| 74 | 73 | const filepath: string = getDevDataFilePath( |
| 75 | 74 | event.name, |
| @@ -100,126 +99,144 @@ | ||
| 100 | 99 | } catch (error) { |
| 101 | 100 | console.error("Error logging local dev data:", error); |
| 102 | 101 | } |
| 102 | + } | |
| 103 | + | |
| 104 | + async logDevData(event: DevDataLogEvent) { | |
| 105 | + // Local logs (always on for all levels) | |
| 106 | + await this.logLocalData(event); | |
| 103 | 107 | |
| 104 | 108 | // Remote logs |
| 105 | 109 | const config = (await this.core?.configHandler.loadConfig())?.config; |
| 106 | 110 | if (config?.data?.length) { |
| 107 | 111 | await Promise.allSettled( |
| 108 | - config.data.map(async (dataConfig) => { | |
| 109 | - try { | |
| 110 | - // First extract the data schema based on the version and level | |
| 111 | - const { schema } = dataConfig; | |
| 112 | - | |
| 113 | - const level = dataConfig.level ?? DEFAULT_DEV_DATA_LEVEL; | |
| 114 | - | |
| 115 | - // Skip event if `events` is specified and does not include the event | |
| 116 | - const events = dataConfig.events ?? allDevEventNames; | |
| 117 | - if (!events.includes(event.name)) { | |
| 118 | - return; | |
| 119 | - } | |
| 120 | - | |
| 121 | - const versionSchemas = devDataVersionedSchemas[schema]; | |
| 122 | - if (!versionSchemas) { | |
| 123 | - throw new Error( | |
| 124 | - `Attempting to log dev data to non-existent version ${schema}`, | |
| 125 | - ); | |
| 126 | - } | |
| 127 | - | |
| 128 | - const levelSchemas = versionSchemas[level]; | |
| 129 | - if (!levelSchemas) { | |
| 130 | - throw new Error( | |
| 131 | - `Attempting to log dev data at level ${level} for version ${schema} which does not exist`, | |
| 132 | - ); | |
| 133 | - } | |
| 134 | - | |
| 135 | - const zodSchema = levelSchemas[event.name]; | |
| 136 | - if (!zodSchema) { | |
| 137 | - throw new Error( | |
| 138 | - `Attempting to log dev data for event ${event.name} at level ${level} for version ${schema}: no schema found`, | |
| 139 | - ); | |
| 140 | - } | |
| 141 | - | |
| 142 | - const eventDataWithBaseValues = await this.addBaseValues( | |
| 143 | - event.data, | |
| 144 | - event.name, | |
| 112 | + config.data.map((dataConfig) => | |
| 113 | + this.logToOneDestination(dataConfig, event), | |
| 114 | + ), | |
| 115 | + ); | |
| 116 | + } | |
| 117 | + } | |
| 118 | + | |
| 119 | + async parseEventData( | |
| 120 | + event: DevDataLogEvent, | |
| 121 | + schema: string, | |
| 122 | + level: "all" | "noCode", | |
| 123 | + ) { | |
| 124 | + const versionSchemas = devDataVersionedSchemas[schema]; | |
| 125 | + if (!versionSchemas) { | |
| 126 | + throw new Error( | |
| 127 | + `Attempting to log dev data to non-existent version ${schema}`, | |
| 128 | + ); | |
| 129 | + } | |
| 130 | + | |
| 131 | + const levelSchemas = versionSchemas[level]; | |
| 132 | + if (!levelSchemas) { | |
| 133 | + throw new Error( | |
| 134 | + `Attempting to log dev data at level ${level} for version ${schema} which does not exist`, | |
| 135 | + ); | |
| 136 | + } | |
| 137 | + | |
| 138 | + const zodSchema = levelSchemas[event.name]; | |
| 139 | + if (!zodSchema) { | |
| 140 | + throw new Error( | |
| 141 | + `Attempting to log dev data for event ${event.name} at level ${level} for version ${schema}: no schema found`, | |
| 142 | + ); | |
| 143 | + } | |
| 144 | + | |
| 145 | + const eventDataWithBaseValues = await this.addBaseValues( | |
| 146 | + event.data, | |
| 147 | + event.name, | |
| 148 | + schema, | |
| 149 | + zodSchema, | |
| 150 | + ); | |
| 151 | + | |
| 152 | + const parsed = zodSchema.safeParse(eventDataWithBaseValues); | |
| 153 | + if (!parsed.success) { | |
| 154 | + throw new Error( | |
| 155 | + `Failed to parse event data for event ${event.name} and schema ${schema}\n:${parsed.error.toString()}`, | |
| 156 | + ); | |
| 157 | + } | |
| 158 | + | |
| 159 | + return parsed.data; | |
| 160 | + } | |
| 161 | + | |
| 162 | + async logToOneDestination( | |
| 163 | + dataConfig: NonNullable<ContinueConfig["data"]>[number], | |
| 164 | + event: DevDataLogEvent, | |
| 165 | + ) { | |
| 166 | + try { | |
| 167 | + if (!dataConfig) { | |
| 168 | + return; | |
| 169 | + } | |
| 170 | + | |
| 171 | + // First extract the data schema based on the version and level | |
| 172 | + const { schema } = dataConfig; | |
| 173 | + const level = dataConfig.level ?? DEFAULT_DEV_DATA_LEVEL; | |
| 174 | + | |
| 175 | + // Skip event if `events` is specified and does not include the event | |
| 176 | + const events = dataConfig.events ?? allDevEventNames; | |
| 177 | + if (!events.includes(event.name)) { | |
| 178 | + return; | |
| 179 | + } | |
| 180 | + | |
| 181 | + // Parse the event data, throwing if it fails | |
| 182 | + const parsed = await this.parseEventData(event, schema, level); | |
| 183 | + | |
| 184 | + const uriComponents = URI.parse(dataConfig.destination); | |
| 185 | + | |
| 186 | + // Send to remote server | |
| 187 | + if (uriComponents.scheme === "https" || uriComponents.scheme === "http") { | |
| 188 | + const headers: Record<string, string> = { | |
| 189 | + "Content-Type": "application/json", | |
| 190 | + }; | |
| 191 | + | |
| 192 | + // If an API key is provided, use it, otherwise use the Continue access token | |
| 193 | + if (dataConfig.apiKey) { | |
| 194 | + headers["Authorization"] = `Bearer ${dataConfig.apiKey}`; | |
| 195 | + } else { | |
| 196 | + const accessToken = | |
| 197 | + await this.core?.configHandler.controlPlaneClient.getAccessToken(); | |
| 198 | + headers["Authorization"] = `Bearer ${accessToken}`; | |
| 199 | + } | |
| 200 | + | |
| 201 | + const profileId = | |
| 202 | + this.core?.configHandler.currentProfile?.profileDescription.id ?? ""; | |
| 203 | + const response = await fetchwithRequestOptions( | |
| 204 | + dataConfig.destination, | |
| 205 | + { | |
| 206 | + method: "POST", | |
| 207 | + headers, | |
| 208 | + body: JSON.stringify({ | |
| 209 | + name: event.name, | |
| 210 | + data: parsed, | |
| 145 | 211 | schema, |
| 146 | - zodSchema, | |
| 147 | - ); | |
| 148 | - | |
| 149 | - const parsed = zodSchema.safeParse(eventDataWithBaseValues); | |
| 150 | - if (!parsed.success) { | |
| 151 | - throw new Error( | |
| 152 | - `Failed to parse event data for event ${event.name} and schema ${schema}\n:${parsed.error.toString()}`, | |
| 153 | - ); | |
| 154 | - } | |
| 155 | - | |
| 156 | - const uriComponents = URI.parse(dataConfig.destination); | |
| 157 | - | |
| 158 | - // Send to remote server | |
| 159 | - if ( | |
| 160 | - uriComponents.scheme === "https" || | |
| 161 | - uriComponents.scheme === "http" | |
| 162 | - ) { | |
| 163 | - const headers: Record<string, string> = { | |
| 164 | - "Content-Type": "application/json", | |
| 165 | - }; | |
| 166 | - if (dataConfig.apiKey) { | |
| 167 | - headers["Authorization"] = `Bearer ${dataConfig.apiKey}`; | |
| 168 | - } | |
| 169 | - | |
| 170 | - // For events going to Continue, overwrite the access token | |
| 171 | - if ( | |
| 172 | - uriComponents.host?.endsWith(".continue.dev") || | |
| 173 | - uriComponents.host === "continue.dev" | |
| 174 | - ) { | |
| 175 | - // | |
| 176 | - const accessToken = | |
| 177 | - await this.core?.configHandler.controlPlaneClient.getAccessToken(); | |
| 178 | - headers["Authorization"] = `Bearer ${accessToken}`; | |
| 179 | - } | |
| 180 | - const profileId = | |
| 181 | - this.core?.configHandler.currentProfile?.profileDescription | |
| 182 | - .id ?? ""; | |
| 183 | - const response = await fetchwithRequestOptions( | |
| 184 | - dataConfig.destination, | |
| 185 | - { | |
| 186 | - method: "POST", | |
| 187 | - headers, | |
| 188 | - body: JSON.stringify({ | |
| 189 | - name: event.name, | |
| 190 | - data: parsed.data, | |
| 191 | - schema, | |
| 192 | - level, | |
| 193 | - profileId, | |
| 194 | - }), | |
| 195 | - }, | |
| 196 | - dataConfig.requestOptions, | |
| 197 | - ); | |
| 198 | - if (!response.ok) { | |
| 199 | - throw new Error( | |
| 200 | - `Post request failed. ${response.status}: ${response.statusText}`, | |
| 201 | - ); | |
| 202 | - } | |
| 203 | - } else if (uriComponents.scheme === "file") { | |
| 204 | - // Write to jsonc file for local file URIs | |
| 205 | - const dirUri = joinPathsToUri(dataConfig.destination, schema); | |
| 206 | - const dirPath = fileURLToPath(dirUri); | |
| 207 | - | |
| 208 | - if (!fs.existsSync(dirPath)) { | |
| 209 | - fs.mkdirSync(dirPath, { recursive: true }); | |
| 210 | - } | |
| 211 | - const filepath = path.join(dirPath, `${event.name}.jsonl`); | |
| 212 | - const jsonLine = JSON.stringify(event.data); | |
| 213 | - fs.writeFileSync(filepath, `${jsonLine}\n`, { flag: "a" }); | |
| 214 | - } else { | |
| 215 | - throw new Error(`Unsupported URI scheme ${uriComponents.scheme}`); | |
| 216 | - } | |
| 217 | - } catch (error) { | |
| 218 | - console.error( | |
| 219 | - `Error logging data to ${dataConfig.destination}: ${error instanceof Error ? error.message : error}`, | |
| 220 | - ); | |
| 221 | - } | |
| 222 | - }), | |
| 212 | + level, | |
| 213 | + profileId, | |
| 214 | + }), | |
| 215 | + }, | |
| 216 | + dataConfig.requestOptions, | |
| 217 | + ); | |
| 218 | + if (!response.ok) { | |
| 219 | + throw new Error( | |
| 220 | + `Post request failed. ${response.status}: ${response.statusText}`, | |
| 221 | + ); | |
| 222 | + } | |
| 223 | + } else if (uriComponents.scheme === "file") { | |
| 224 | + // Write to jsonc file for local file URIs | |
| 225 | + const dirUri = joinPathsToUri(dataConfig.destination, schema); | |
| 226 | + const dirPath = fileURLToPath(dirUri); | |
| 227 | + | |
| 228 | + if (!fs.existsSync(dirPath)) { | |
| 229 | + fs.mkdirSync(dirPath, { recursive: true }); | |
| 230 | + } | |
| 231 | + const filepath = path.join(dirPath, `${event.name}.jsonl`); | |
| 232 | + const jsonLine = JSON.stringify(event.data); | |
| 233 | + fs.writeFileSync(filepath, `${jsonLine}\n`, { flag: "a" }); | |
| 234 | + } else { | |
| 235 | + throw new Error(`Unsupported URI scheme ${uriComponents.scheme}`); | |
| 236 | + } | |
| 237 | + } catch (error) { | |
| 238 | + console.error( | |
| 239 | + `Error logging data to ${dataConfig.destination}: ${error instanceof Error ? error.message : error}`, | |
| 223 | 240 | ); |
| 224 | 241 | } |
| 225 | 242 | } |
modified core/edit/streamDiffLines.ts +1 −0
| @@ -127,6 +127,7 @@ | ||
| 127 | 127 | (msg) => msg.role === "user" || msg.role === "tool", |
| 128 | 128 | ) as UserChatMessage | ToolResultChatMessage | undefined), |
| 129 | 129 | baseSystemMessage: undefined, |
| 130 | + contextItems: [], | |
| 130 | 131 | }) |
| 131 | 132 | : undefined; |
| 132 | 133 |
modified core/index.d.ts +5 −1
| @@ -842,7 +842,7 @@ | ||
| 842 | 842 | description: string; |
| 843 | 843 | prompt?: string; |
| 844 | 844 | params?: { [key: string]: any }; |
| 845 | - promptFile?: string | |
| 845 | + promptFile?: string; | |
| 846 | 846 | run: (sdk: ContinueSDK) => AsyncGenerator<string | undefined>; |
| 847 | 847 | } |
| 848 | 848 | |
| @@ -1254,6 +1254,10 @@ | ||
| 1254 | 1254 | streamId?: string; |
| 1255 | 1255 | } |
| 1256 | 1256 | |
| 1257 | +export interface ShowFilePayload { | |
| 1258 | + filepath: string; | |
| 1259 | +} | |
| 1260 | + | |
| 1257 | 1261 | export interface RangeInFileWithContents { |
| 1258 | 1262 | filepath: string; |
| 1259 | 1263 | range: { |
modified core/llm/constructMessages.ts +35 −2
| @@ -1,6 +1,7 @@ | ||
| 1 | 1 | import { |
| 2 | 2 | ChatHistoryItem, |
| 3 | 3 | ChatMessage, |
| 4 | + ContextItemWithId, | |
| 4 | 5 | RuleWithSource, |
| 5 | 6 | TextMessagePart, |
| 6 | 7 | ToolResultChatMessage, |
| @@ -58,7 +59,7 @@ | ||
| 58 | 59 | at the beginning, middle, or end of files using these "lazy" comments. Only |
| 59 | 60 | provide the complete file when explicitly requested. Include a concise explanation |
| 60 | 61 | of changes unless the user specifically asks for code only. |
| 61 | -` | |
| 62 | +`; | |
| 62 | 63 | |
| 63 | 64 | export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\ |
| 64 | 65 | <important_rules> |
| @@ -77,6 +78,31 @@ | ||
| 77 | 78 | ${EDIT_MESSAGE} |
| 78 | 79 | </important_rules>`; |
| 79 | 80 | |
| 81 | +/** | |
| 82 | + * Helper function to get the context items for a user message | |
| 83 | + */ | |
| 84 | +function getUserContextItems( | |
| 85 | + userMsg: UserChatMessage | ToolResultChatMessage | undefined, | |
| 86 | + history: ChatHistoryItem[], | |
| 87 | +): ContextItemWithId[] { | |
| 88 | + if (!userMsg) return []; | |
| 89 | + | |
| 90 | + // Find the history item that contains the userMsg | |
| 91 | + const historyItem = history.find((item) => { | |
| 92 | + // Check if the message ID matches | |
| 93 | + if ("id" in userMsg && "id" in item.message) { | |
| 94 | + return (item.message as any).id === (userMsg as any).id; | |
| 95 | + } | |
| 96 | + // Fallback to content comparison | |
| 97 | + return ( | |
| 98 | + item.message.content === userMsg.content && | |
| 99 | + item.message.role === userMsg.role | |
| 100 | + ); | |
| 101 | + }); | |
| 102 | + | |
| 103 | + return historyItem?.contextItems || []; | |
| 104 | +} | |
| 105 | + | |
| 80 | 106 | export function constructMessages( |
| 81 | 107 | messageMode: string, |
| 82 | 108 | history: ChatHistoryItem[], |
| @@ -92,7 +118,8 @@ | ||
| 92 | 118 | const historyItem = filteredHistory[i]; |
| 93 | 119 | |
| 94 | 120 | if (messageMode === "chat") { |
| 95 | - const toolMessage: ToolResultChatMessage = historyItem.message as ToolResultChatMessage; | |
| 121 | + const toolMessage: ToolResultChatMessage = | |
| 122 | + historyItem.message as ToolResultChatMessage; | |
| 96 | 123 | if (historyItem.toolCallState?.toolCallId || toolMessage.toolCallId) { |
| 97 | 124 | // remove all tool calls from the history |
| 98 | 125 | continue; |
| @@ -127,10 +154,16 @@ | ||
| 127 | 154 | | ToolResultChatMessage |
| 128 | 155 | | undefined; |
| 129 | 156 | |
| 157 | + // Get context items for the last user message | |
| 158 | + const lastUserContextItems = getUserContextItems( | |
| 159 | + lastUserMsg, | |
| 160 | + filteredHistory, | |
| 161 | + ); | |
| 130 | 162 | const systemMessage = getSystemMessageWithRules({ |
| 131 | 163 | baseSystemMessage: baseChatOrAgentSystemMessage, |
| 132 | 164 | rules, |
| 133 | 165 | userMessage: lastUserMsg, |
| 166 | + contextItems: lastUserContextItems, | |
| 134 | 167 | }); |
| 135 | 168 | |
| 136 | 169 | if (systemMessage.trim()) { |
modified core/llm/llm.test.ts +24 −10
| @@ -22,6 +22,20 @@ | ||
| 22 | 22 | // maxTokens: 5, |
| 23 | 23 | }; |
| 24 | 24 | |
| 25 | +/** | |
| 26 | + * Retries a test function if it fails on the first attempt | |
| 27 | + * @param testFn The test function to run | |
| 28 | + * @returns A function that will retry once if the test fails | |
| 29 | + */ | |
| 30 | +const retryOnce = (testFn: () => Promise<any>) => async () => { | |
| 31 | + try { | |
| 32 | + return await testFn(); | |
| 33 | + } catch (error) { | |
| 34 | + console.log("Test failed on first attempt, retrying once..."); | |
| 35 | + return await testFn(); | |
| 36 | + } | |
| 37 | +}; | |
| 38 | + | |
| 25 | 39 | function testLLM( |
| 26 | 40 | llm: BaseLLM, |
| 27 | 41 | { |
| @@ -47,7 +61,7 @@ | ||
| 47 | 61 | describe(llm.providerName + "/" + llm.model, () => { |
| 48 | 62 | test( |
| 49 | 63 | "Stream Chat works", |
| 50 | - async () => { | |
| 64 | + retryOnce(async () => { | |
| 51 | 65 | let total = ""; |
| 52 | 66 | for await (const chunk of llm.streamChat( |
| 53 | 67 | [{ role: "user", content: "Hi" }], |
| @@ -58,13 +72,13 @@ | ||
| 58 | 72 | |
| 59 | 73 | expect(total.length).toBeGreaterThan(0); |
| 60 | 74 | return; |
| 61 | - }, | |
| 75 | + }), | |
| 62 | 76 | timeout, |
| 63 | 77 | ); |
| 64 | 78 | |
| 65 | 79 | test( |
| 66 | 80 | "Stream Complete works", |
| 67 | - async () => { | |
| 81 | + retryOnce(async () => { | |
| 68 | 82 | let total = ""; |
| 69 | 83 | for await (const chunk of llm.streamComplete( |
| 70 | 84 | "Hi", |
| @@ -75,13 +89,13 @@ | ||
| 75 | 89 | |
| 76 | 90 | expect(total.length).toBeGreaterThan(0); |
| 77 | 91 | return; |
| 78 | - }, | |
| 92 | + }), | |
| 79 | 93 | timeout, |
| 80 | 94 | ); |
| 81 | 95 | |
| 82 | 96 | test( |
| 83 | 97 | "Complete works", |
| 84 | - async () => { | |
| 98 | + retryOnce(async () => { | |
| 85 | 99 | const completion = await llm.complete( |
| 86 | 100 | "Hi", |
| 87 | 101 | new AbortController().signal, |
| @@ -89,14 +103,14 @@ | ||
| 89 | 103 | |
| 90 | 104 | expect(completion.length).toBeGreaterThan(0); |
| 91 | 105 | return; |
| 92 | - }, | |
| 106 | + }), | |
| 93 | 107 | timeout, |
| 94 | 108 | ); |
| 95 | 109 | |
| 96 | 110 | if (testFim) { |
| 97 | 111 | test( |
| 98 | 112 | "FIM works", |
| 99 | - async () => { | |
| 113 | + retryOnce(async () => { | |
| 100 | 114 | let total = ""; |
| 101 | 115 | for await (const chunk of llm.streamFim( |
| 102 | 116 | "Hi", |
| @@ -108,7 +122,7 @@ | ||
| 108 | 122 | |
| 109 | 123 | expect(total.length).toBeGreaterThan(0); |
| 110 | 124 | return; |
| 111 | - }, | |
| 125 | + }), | |
| 112 | 126 | timeout, |
| 113 | 127 | ); |
| 114 | 128 | } |
| @@ -116,7 +130,7 @@ | ||
| 116 | 130 | if (testToolCall) { |
| 117 | 131 | test( |
| 118 | 132 | "Tool Call works", |
| 119 | - async () => { | |
| 133 | + retryOnce(async () => { | |
| 120 | 134 | let args = ""; |
| 121 | 135 | let isFirstChunk = true; |
| 122 | 136 | for await (const chunk of llm.streamChat( |
| @@ -175,7 +189,7 @@ | ||
| 175 | 189 | |
| 176 | 190 | const parsedArgs = JSON.parse(args); |
| 177 | 191 | expect(parsedArgs.name).toBe("Nate"); |
| 178 | - }, | |
| 192 | + }), | |
| 179 | 193 | timeout, |
| 180 | 194 | ); |
| 181 | 195 | } |
modified core/llm/llms/Bedrock.ts +1 −1
| @@ -306,7 +306,7 @@ | ||
| 306 | 306 | } |
| 307 | 307 | |
| 308 | 308 | const supportsTools = |
| 309 | - PROVIDER_TOOL_SUPPORT.bedrock?.(options.model || "") ?? false; | |
| 309 | + (this.capabilities?.tools || PROVIDER_TOOL_SUPPORT.bedrock?.(options.model)) ?? false; | |
| 310 | 310 | |
| 311 | 311 | let toolConfig = supportsTools && options.tools |
| 312 | 312 | ? { |
added core/llm/llms/OpenAI.test.ts +34 −0
| @@ -0,0 +1,34 @@ | ||
| 1 | +import OpenAI from "./OpenAI"; | |
| 2 | + | |
| 3 | +describe("OpenAI", () => { | |
| 4 | + test("should identify correct o-series models", () => { | |
| 5 | + const openai = new OpenAI({ | |
| 6 | + model: "o3-mini", | |
| 7 | + }); | |
| 8 | + expect(openai.isOSeriesModel("o4-mini")).toBeTruthy(); | |
| 9 | + expect(openai.isOSeriesModel("o3-mini")).toBeTruthy(); | |
| 10 | + expect(openai.isOSeriesModel("o1-mini")).toBeTruthy(); | |
| 11 | + expect(openai.isOSeriesModel("o1")).toBeTruthy(); | |
| 12 | + expect(openai.isOSeriesModel("o3")).toBeTruthy(); | |
| 13 | + | |
| 14 | + // artificially correct samples for future models | |
| 15 | + expect(openai.isOSeriesModel("o5-mini")).toBeTruthy(); | |
| 16 | + expect(openai.isOSeriesModel("o6")).toBeTruthy(); | |
| 17 | + expect(openai.isOSeriesModel("o77")).toBeTruthy(); | |
| 18 | + expect(openai.isOSeriesModel("o54-mini")).toBeTruthy(); | |
| 19 | + }); | |
| 20 | + test("should identify incorrect o-series models", () => { | |
| 21 | + const openai = new OpenAI({ | |
| 22 | + model: "o3-mini", | |
| 23 | + }); | |
| 24 | + expect(openai.isOSeriesModel("gpt-o4-mini")).toBeFalsy(); | |
| 25 | + expect(openai.isOSeriesModel("gpt-4.5")).toBeFalsy(); | |
| 26 | + expect(openai.isOSeriesModel("gpt-4.1")).toBeFalsy(); | |
| 27 | + | |
| 28 | + // artificially wrong samples | |
| 29 | + expect(openai.isOSeriesModel("os1")).toBeFalsy(); | |
| 30 | + expect(openai.isOSeriesModel("so1")).toBeFalsy(); | |
| 31 | + expect(openai.isOSeriesModel("ao31")).toBeFalsy(); | |
| 32 | + expect(openai.isOSeriesModel("1os")).toBeFalsy(); | |
| 33 | + }); | |
| 34 | +}); |
modified core/llm/llms/OpenAI.ts +4 −4
| @@ -77,8 +77,8 @@ | ||
| 77 | 77 | return model; |
| 78 | 78 | } |
| 79 | 79 | |
| 80 | - private isO3orO1Model(model?: string): boolean { | |
| 81 | - return !!model && (model.startsWith("o1") || model.startsWith("o3")); | |
| 80 | + public isOSeriesModel(model?: string): boolean { | |
| 81 | + return !!model && !!model.match(/^o[0-9]+/); | |
| 82 | 82 | } |
| 83 | 83 | |
| 84 | 84 | private isFireworksAiModel(model?: string): boolean { |
| @@ -139,7 +139,7 @@ | ||
| 139 | 139 | finalOptions.stop = options.stop?.slice(0, this.getMaxStopWords()); |
| 140 | 140 | |
| 141 | 141 | // OpenAI o1-preview and o1-mini or o3-mini: |
| 142 | - if (this.isO3orO1Model(options.model)) { | |
| 142 | + if (this.isOSeriesModel(options.model)) { | |
| 143 | 143 | // a) use max_completion_tokens instead of max_tokens |
| 144 | 144 | finalOptions.max_completion_tokens = options.maxTokens; |
| 145 | 145 | finalOptions.max_tokens = undefined; |
| @@ -241,7 +241,7 @@ | ||
| 241 | 241 | body.stop = body.stop?.slice(0, this.getMaxStopWords()); |
| 242 | 242 | |
| 243 | 243 | // OpenAI o1-preview and o1-mini or o3-mini: |
| 244 | - if (this.isO3orO1Model(body.model)) { | |
| 244 | + if (this.isOSeriesModel(body.model)) { | |
| 245 | 245 | // a) use max_completion_tokens instead of max_tokens |
| 246 | 246 | body.max_completion_tokens = body.max_tokens; |
| 247 | 247 | body.max_tokens = undefined; |
modified core/llm/llms/stubs/ContinueProxy.ts +5 −0
| @@ -27,8 +27,12 @@ | ||
| 27 | 27 | // to call whatever LLM API is chosen |
| 28 | 28 | private actualApiBase?: string; |
| 29 | 29 | |
| 30 | + // Contains extra properties that we pass along to the proxy. Originally from `env` property on LLMOptions | |
| 31 | + private configEnv?: Record<string, any>; | |
| 32 | + | |
| 30 | 33 | constructor(options: LLMOptions) { |
| 31 | 34 | super(options); |
| 35 | + this.configEnv = options.env; | |
| 32 | 36 | this.actualApiBase = options.apiBase; |
| 33 | 37 | this.apiKeyLocation = options.apiKeyLocation; |
| 34 | 38 | this.orgScopeId = options.orgScopeId; |
| @@ -48,6 +52,7 @@ | ||
| 48 | 52 | apiKeyLocation: this.apiKeyLocation, |
| 49 | 53 | apiBase: this.actualApiBase, |
| 50 | 54 | orgScopeId: this.orgScopeId ?? null, |
| 55 | + env: this.configEnv, | |
| 51 | 56 | }; |
| 52 | 57 | return { |
| 53 | 58 | continueProperties, |
modified core/llm/rules/getSystemMessageWithRules.test.ts +207 −3
| @@ -1,4 +1,4 @@ | ||
| 1 | -import { RuleWithSource, UserChatMessage } from "../.."; | |
| 1 | +import { ContextItemWithId, RuleWithSource, UserChatMessage } from "../.."; | |
| 2 | 2 | import { getSystemMessageWithRules } from "./getSystemMessageWithRules"; |
| 3 | 3 | |
| 4 | 4 | describe("getSystemMessageWithRules", () => { |
| @@ -25,11 +25,48 @@ | ||
| 25 | 25 | source: "rules-block", |
| 26 | 26 | }; |
| 27 | 27 | |
| 28 | + // JavaScript rule | |
| 29 | + const jsRule: RuleWithSource = { | |
| 30 | + name: "JavaScript Rule", | |
| 31 | + rule: "Follow JavaScript best practices", | |
| 32 | + globs: "**/*.js", | |
| 33 | + source: "rules-block", | |
| 34 | + }; | |
| 35 | + | |
| 36 | + // Empty context items | |
| 37 | + const emptyContextItems: ContextItemWithId[] = []; | |
| 38 | + | |
| 39 | + // Context items with file paths | |
| 40 | + const tsContextItem: ContextItemWithId = { | |
| 41 | + content: "TypeScript file content", | |
| 42 | + name: "Component.tsx", | |
| 43 | + description: "A TypeScript component", | |
| 44 | + id: { providerTitle: "file", itemId: "src/Component.tsx" }, | |
| 45 | + uri: { type: "file", value: "src/Component.tsx" }, | |
| 46 | + }; | |
| 47 | + | |
| 48 | + const pyContextItem: ContextItemWithId = { | |
| 49 | + content: "Python file content", | |
| 50 | + name: "utils.py", | |
| 51 | + description: "A Python utility file", | |
| 52 | + id: { providerTitle: "file", itemId: "utils.py" }, | |
| 53 | + uri: { type: "file", value: "utils.py" }, | |
| 54 | + }; | |
| 55 | + | |
| 56 | + const jsContextItem: ContextItemWithId = { | |
| 57 | + content: "JavaScript file content", | |
| 58 | + name: "utils.js", | |
| 59 | + description: "A JavaScript utility file", | |
| 60 | + id: { providerTitle: "file", itemId: "src/utils.js" }, | |
| 61 | + uri: { type: "file", value: "src/utils.js" }, | |
| 62 | + }; | |
| 63 | + | |
| 28 | 64 | it("should not include pattern-matched rules when no file paths are mentioned", () => { |
| 29 | 65 | const result = getSystemMessageWithRules({ |
| 30 | 66 | baseSystemMessage, |
| 31 | 67 | userMessage: undefined, |
| 32 | 68 | rules: [tsRule], |
| 69 | + contextItems: emptyContextItems, | |
| 33 | 70 | }); |
| 34 | 71 | |
| 35 | 72 | expect(result).toBe(baseSystemMessage); |
| @@ -40,12 +77,13 @@ | ||
| 40 | 77 | baseSystemMessage, |
| 41 | 78 | userMessage: undefined, |
| 42 | 79 | rules: [generalRule], |
| 80 | + contextItems: emptyContextItems, | |
| 43 | 81 | }); |
| 44 | 82 | |
| 45 | 83 | expect(result).toBe(`${baseSystemMessage}\n\n${generalRule.rule}`); |
| 46 | 84 | }); |
| 47 | 85 | |
| 48 | - it("should include only matching rules based on file paths", () => { | |
| 86 | + it("should include only matching rules based on file paths in message", () => { | |
| 49 | 87 | const userMessage: UserChatMessage = { |
| 50 | 88 | role: "user", |
| 51 | 89 | content: |
| @@ -56,6 +94,20 @@ | ||
| 56 | 94 | baseSystemMessage, |
| 57 | 95 | userMessage, |
| 58 | 96 | rules: [tsRule, pythonRule, generalRule], |
| 97 | + contextItems: emptyContextItems, | |
| 98 | + }); | |
| 99 | + | |
| 100 | + // Should include TS rule and general rule, but not Python rule | |
| 101 | + const expected = `${baseSystemMessage}\n\n${tsRule.rule}\n\n${generalRule.rule}`; | |
| 102 | + expect(result).toBe(expected); | |
| 103 | + }); | |
| 104 | + | |
| 105 | + it("should include matching rules based on file paths in context items", () => { | |
| 106 | + const result = getSystemMessageWithRules({ | |
| 107 | + baseSystemMessage, | |
| 108 | + userMessage: undefined, | |
| 109 | + rules: [tsRule, pythonRule, generalRule], | |
| 110 | + contextItems: [tsContextItem], | |
| 59 | 111 | }); |
| 60 | 112 | |
| 61 | 113 | // Should include TS rule and general rule, but not Python rule |
| @@ -63,7 +115,25 @@ | ||
| 63 | 115 | expect(result).toBe(expected); |
| 64 | 116 | }); |
| 65 | 117 | |
| 66 | - it("should include multiple matching rules", () => { | |
| 118 | + it("should include matching rules from both message and context items", () => { | |
| 119 | + const userMessage: UserChatMessage = { | |
| 120 | + role: "user", | |
| 121 | + content: "```python test.py\nprint('hello')\n```", | |
| 122 | + }; | |
| 123 | + | |
| 124 | + const result = getSystemMessageWithRules({ | |
| 125 | + baseSystemMessage, | |
| 126 | + userMessage, | |
| 127 | + rules: [tsRule, pythonRule, generalRule], | |
| 128 | + contextItems: [tsContextItem], | |
| 129 | + }); | |
| 130 | + | |
| 131 | + // Should include TS rule, Python rule, and general rule | |
| 132 | + const expected = `${baseSystemMessage}\n\n${tsRule.rule}\n\n${pythonRule.rule}\n\n${generalRule.rule}`; | |
| 133 | + expect(result).toBe(expected); | |
| 134 | + }); | |
| 135 | + | |
| 136 | + it("should include multiple matching rules from message", () => { | |
| 67 | 137 | const userMessage: UserChatMessage = { |
| 68 | 138 | role: "user", |
| 69 | 139 | content: |
| @@ -74,6 +144,20 @@ | ||
| 74 | 144 | baseSystemMessage, |
| 75 | 145 | userMessage, |
| 76 | 146 | rules: [tsRule, pythonRule, generalRule], |
| 147 | + contextItems: emptyContextItems, | |
| 148 | + }); | |
| 149 | + | |
| 150 | + // Should include all rules | |
| 151 | + const expected = `${baseSystemMessage}\n\n${tsRule.rule}\n\n${pythonRule.rule}\n\n${generalRule.rule}`; | |
| 152 | + expect(result).toBe(expected); | |
| 153 | + }); | |
| 154 | + | |
| 155 | + it("should include multiple matching rules from context items", () => { | |
| 156 | + const result = getSystemMessageWithRules({ | |
| 157 | + baseSystemMessage, | |
| 158 | + userMessage: undefined, | |
| 159 | + rules: [tsRule, pythonRule, generalRule], | |
| 160 | + contextItems: [tsContextItem, pyContextItem], | |
| 77 | 161 | }); |
| 78 | 162 | |
| 79 | 163 | // Should include all rules |
| @@ -91,6 +175,7 @@ | ||
| 91 | 175 | baseSystemMessage, |
| 92 | 176 | userMessage, |
| 93 | 177 | rules: [tsRule, pythonRule, generalRule], |
| 178 | + contextItems: emptyContextItems, | |
| 94 | 179 | }); |
| 95 | 180 | |
| 96 | 181 | // Should only include the general rule |
| @@ -117,6 +202,7 @@ | ||
| 117 | 202 | baseSystemMessage, |
| 118 | 203 | userMessage, |
| 119 | 204 | rules: [commaRule], |
| 205 | + contextItems: emptyContextItems, | |
| 120 | 206 | }); |
| 121 | 207 | |
| 122 | 208 | // With the current implementation, the comma-separated pattern is treated as a single string, |
| @@ -143,6 +229,7 @@ | ||
| 143 | 229 | baseSystemMessage, |
| 144 | 230 | userMessage, |
| 145 | 231 | rules: [arrayGlobRule], |
| 232 | + contextItems: emptyContextItems, | |
| 146 | 233 | }); |
| 147 | 234 | |
| 148 | 235 | // With our new implementation, the array of patterns should match both src/main.ts and tests/example.test.ts |
| @@ -168,6 +255,7 @@ | ||
| 168 | 255 | baseSystemMessage, |
| 169 | 256 | userMessage, |
| 170 | 257 | rules: [arrayGlobRule], |
| 258 | + contextItems: emptyContextItems, | |
| 171 | 259 | }); |
| 172 | 260 | |
| 173 | 261 | // Should match src/main.ts but not config/settings.ts |
| @@ -193,9 +281,125 @@ | ||
| 193 | 281 | baseSystemMessage, |
| 194 | 282 | userMessage, |
| 195 | 283 | rules: [arrayGlobRule], |
| 284 | + contextItems: emptyContextItems, | |
| 196 | 285 | }); |
| 197 | 286 | |
| 198 | 287 | // Should not match any file paths |
| 199 | 288 | expect(result).toBe(baseSystemMessage); |
| 200 | 289 | }); |
| 290 | + | |
| 291 | + // New test for code block with filename only (no language) | |
| 292 | + it("should handle code blocks with filename only (no language identifier)", () => { | |
| 293 | + const userMessage: UserChatMessage = { | |
| 294 | + role: "user", | |
| 295 | + content: "```test.js\nclass Calculator { /* code */ }\n```", | |
| 296 | + }; | |
| 297 | + | |
| 298 | + const result = getSystemMessageWithRules({ | |
| 299 | + baseSystemMessage, | |
| 300 | + userMessage, | |
| 301 | + rules: [jsRule, tsRule, generalRule], | |
| 302 | + contextItems: emptyContextItems, | |
| 303 | + }); | |
| 304 | + | |
| 305 | + // Should include JS rule and general rule | |
| 306 | + const expected = `${baseSystemMessage}\n\n${jsRule.rule}\n\n${generalRule.rule}`; | |
| 307 | + expect(result).toBe(expected); | |
| 308 | + }); | |
| 309 | + | |
| 310 | + // New test for code blocks with line ranges | |
| 311 | + it("should handle code blocks with line ranges", () => { | |
| 312 | + const userMessage: UserChatMessage = { | |
| 313 | + role: "user", | |
| 314 | + content: "```js test.js (19-25)\ndivide(number) { /* code */ }\n```", | |
| 315 | + }; | |
| 316 | + | |
| 317 | + const result = getSystemMessageWithRules({ | |
| 318 | + baseSystemMessage, | |
| 319 | + userMessage, | |
| 320 | + rules: [jsRule, tsRule, generalRule], | |
| 321 | + contextItems: emptyContextItems, | |
| 322 | + }); | |
| 323 | + | |
| 324 | + // Should include JS rule and general rule | |
| 325 | + const expected = `${baseSystemMessage}\n\n${jsRule.rule}\n\n${generalRule.rule}`; | |
| 326 | + expect(result).toBe(expected); | |
| 327 | + }); | |
| 328 | + | |
| 329 | + // New test for mixed code block formats | |
| 330 | + it("should handle mixed code block formats in the same message", () => { | |
| 331 | + const userMessage: UserChatMessage = { | |
| 332 | + role: "user", | |
| 333 | + content: | |
| 334 | + "```test.js\nclass Calculator { /* code */ }\n```\n" + | |
| 335 | + "```js utils.js (19-25)\ndivide(number) { /* code */ }\n```\n" + | |
| 336 | + "```ts config/settings.ts\nconst config = {};\n```", | |
| 337 | + }; | |
| 338 | + | |
| 339 | + const result = getSystemMessageWithRules({ | |
| 340 | + baseSystemMessage, | |
| 341 | + userMessage, | |
| 342 | + rules: [jsRule, tsRule, generalRule], | |
| 343 | + contextItems: emptyContextItems, | |
| 344 | + }); | |
| 345 | + | |
| 346 | + // Should include JS rule, TS rule, and general rule | |
| 347 | + const expected = `${baseSystemMessage}\n\n${jsRule.rule}\n\n${tsRule.rule}\n\n${generalRule.rule}`; | |
| 348 | + expect(result).toBe(expected); | |
| 349 | + }); | |
| 350 | + | |
| 351 | + // Test for context items when there's no message | |
| 352 | + it("should apply rules based on context items only when no message is present", () => { | |
| 353 | + const result = getSystemMessageWithRules({ | |
| 354 | + baseSystemMessage, | |
| 355 | + userMessage: undefined, | |
| 356 | + rules: [jsRule, tsRule, generalRule], | |
| 357 | + contextItems: [jsContextItem], | |
| 358 | + }); | |
| 359 | + | |
| 360 | + // Should include JS rule and general rule | |
| 361 | + const expected = `${baseSystemMessage}\n\n${jsRule.rule}\n\n${generalRule.rule}`; | |
| 362 | + expect(result).toBe(expected); | |
| 363 | + }); | |
| 364 | + | |
| 365 | + // Test for non-file context items | |
| 366 | + it("should ignore non-file context items", () => { | |
| 367 | + const nonFileContextItem: ContextItemWithId = { | |
| 368 | + content: "Some search result", | |
| 369 | + name: "Search result", | |
| 370 | + description: "A search result", | |
| 371 | + id: { providerTitle: "search", itemId: "search-result" }, | |
| 372 | + // No uri with type "file" | |
| 373 | + }; | |
| 374 | + | |
| 375 | + const result = getSystemMessageWithRules({ | |
| 376 | + baseSystemMessage, | |
| 377 | + userMessage: undefined, | |
| 378 | + rules: [jsRule, tsRule, generalRule], | |
| 379 | + contextItems: [nonFileContextItem], | |
| 380 | + }); | |
| 381 | + | |
| 382 | + // Should only include general rule | |
| 383 | + const expected = `${baseSystemMessage}\n\n${generalRule.rule}`; | |
| 384 | + expect(result).toBe(expected); | |
| 385 | + }); | |
| 386 | + | |
| 387 | + // Test combining context items with message | |
| 388 | + it("should match rules from both message code blocks and context items", () => { | |
| 389 | + const userMessage: UserChatMessage = { | |
| 390 | + role: "user", | |
| 391 | + content: "```ts src/main.ts\nconsole.log('hello');\n```", | |
| 392 | + }; | |
| 393 | + | |
| 394 | + const result = getSystemMessageWithRules({ | |
| 395 | + baseSystemMessage, | |
| 396 | + userMessage, | |
| 397 | + rules: [jsRule, tsRule, pythonRule, generalRule], | |
| 398 | + contextItems: [jsContextItem, pyContextItem], | |
| 399 | + }); | |
| 400 | + | |
| 401 | + // Should include JS, TS, Python rules and general rule | |
| 402 | + const expected = `${baseSystemMessage}\n\n${jsRule.rule}\n\n${tsRule.rule}\n\n${pythonRule.rule}\n\n${generalRule.rule}`; | |
| 403 | + expect(result).toBe(expected); | |
| 404 | + }); | |
| 201 | 405 | }); |
modified core/llm/rules/getSystemMessageWithRules.ts +33 −4
| @@ -1,5 +1,10 @@ | ||
| 1 | 1 | import { minimatch } from "minimatch"; |
| 2 | -import { RuleWithSource, ToolResultChatMessage, UserChatMessage } from "../.."; | |
| 2 | +import { | |
| 3 | + ContextItemWithId, | |
| 4 | + RuleWithSource, | |
| 5 | + ToolResultChatMessage, | |
| 6 | + UserChatMessage, | |
| 7 | +} from "../.."; | |
| 3 | 8 | import { renderChatMessage } from "../../util/messageContent"; |
| 4 | 9 | import { extractPathsFromCodeBlocks } from "../utils/extractPathsFromCodeBlocks"; |
| 5 | 10 | |
| @@ -24,21 +29,34 @@ | ||
| 24 | 29 | }; |
| 25 | 30 | |
| 26 | 31 | /** |
| 27 | - * Filters rules that apply to the given message | |
| 32 | + * Filters rules that apply to the given message and/or context items | |
| 33 | + * | |
| 34 | + * @param userMessage - The user or tool message to check for file paths in code blocks | |
| 35 | + * @param rules - The list of rules to filter | |
| 36 | + * @param contextItems - Context items to check for file paths | |
| 37 | + * @returns List of applicable rules | |
| 28 | 38 | */ |
| 29 | 39 | export const getApplicableRules = ( |
| 30 | 40 | userMessage: UserChatMessage | ToolResultChatMessage | undefined, |
| 31 | 41 | rules: RuleWithSource[], |
| 42 | + contextItems: ContextItemWithId[], | |
| 32 | 43 | ): RuleWithSource[] => { |
| 33 | 44 | const filePathsFromMessage = userMessage |
| 34 | 45 | ? extractPathsFromCodeBlocks(renderChatMessage(userMessage)) |
| 35 | 46 | : []; |
| 36 | 47 | |
| 48 | + // Extract file paths from context items | |
| 49 | + const filePathsFromContextItems = contextItems | |
| 50 | + .filter((item) => item.uri?.type === "file" && item.uri?.value) | |
| 51 | + .map((item) => item.uri!.value); | |
| 52 | + // Combine file paths from both sources | |
| 53 | + const allFilePaths = [...filePathsFromMessage, ...filePathsFromContextItems]; | |
| 54 | + | |
| 37 | 55 | return rules.filter((rule) => { |
| 38 | 56 | // A rule is active if it has no globs (applies to all files) |
| 39 | 57 | // or if at least one file path matches its globs |
| 40 | 58 | const hasNoGlobs = !rule.globs; |
| 41 | - const matchesAnyFilePath = filePathsFromMessage.some((path) => | |
| 59 | + const matchesAnyFilePath = allFilePaths.some((path) => | |
| 42 | 60 | matchesGlobs(path, rule.globs), |
| 43 | 61 | ); |
| 44 | 62 | |
| @@ -46,16 +64,27 @@ | ||
| 46 | 64 | }); |
| 47 | 65 | }; |
| 48 | 66 | |
| 67 | +/** | |
| 68 | + * Creates a system message string with applicable rules appended | |
| 69 | + * | |
| 70 | + * @param baseSystemMessage - The base system message to start with | |
| 71 | + * @param userMessage - The user message to check for file paths | |
| 72 | + * @param rules - The list of rules to filter | |
| 73 | + * @param contextItems - Context items to check for file paths | |
| 74 | + * @returns System message with applicable rules appended | |
| 75 | + */ | |
| 49 | 76 | export const getSystemMessageWithRules = ({ |
| 50 | 77 | baseSystemMessage, |
| 51 | 78 | userMessage, |
| 52 | 79 | rules, |
| 80 | + contextItems, | |
| 53 | 81 | }: { |
| 54 | 82 | baseSystemMessage?: string; |
| 55 | 83 | userMessage: UserChatMessage | ToolResultChatMessage | undefined; |
| 56 | 84 | rules: RuleWithSource[]; |
| 85 | + contextItems: ContextItemWithId[]; | |
| 57 | 86 | }) => { |
| 58 | - const applicableRules = getApplicableRules(userMessage, rules); | |
| 87 | + const applicableRules = getApplicableRules(userMessage, rules, contextItems); | |
| 59 | 88 | let systemMessage = baseSystemMessage ?? ""; |
| 60 | 89 | |
| 61 | 90 | for (const rule of applicableRules) { |
modified core/llm/toolSupport.test.ts +3 −0
| @@ -155,6 +155,7 @@ | ||
| 155 | 155 | expect(supportsFn("pixtral-12b-2409")).toBe(true); |
| 156 | 156 | expect(supportsFn("pixtral-large-latest")).toBe(true); |
| 157 | 157 | expect(supportsFn("open-mistral-nemo")).toBe(true); |
| 158 | + expect(supportsFn("devstral-latest")).toBe(true); | |
| 158 | 159 | }); |
| 159 | 160 | |
| 160 | 161 | it("should return false for other unsupported models", () => { |
| @@ -170,6 +171,7 @@ | ||
| 170 | 171 | expect(supportsFn("CODESTRAL-LATEST")).toBe(true); |
| 171 | 172 | expect(supportsFn("MINISTRAL-8B-LATEST")).toBe(true); |
| 172 | 173 | expect(supportsFn("PIXTRAL-12B-2409")).toBe(true); |
| 174 | + expect(supportsFn("DEVSTRAL-LATEST")).toBe(true); | |
| 173 | 175 | }); |
| 174 | 176 | }); |
| 175 | 177 | |
| @@ -192,6 +194,7 @@ | ||
| 192 | 194 | expect(supportsFn("aya-expanse")).toBe(true); |
| 193 | 195 | expect(supportsFn("firefunction-v2")).toBe(true); |
| 194 | 196 | expect(supportsFn("mistral-7b")).toBe(true); |
| 197 | + expect(supportsFn("devstral-24b")).toBe(true); | |
| 195 | 198 | }); |
| 196 | 199 | |
| 197 | 200 | it("should return false for explicitly unsupported models", () => { |
modified core/llm/toolSupport.ts +5 −2
| @@ -17,6 +17,7 @@ | ||
| 17 | 17 | "claude-3.5", |
| 18 | 18 | "claude-3-7", |
| 19 | 19 | "claude-3.7", |
| 20 | + "claude-sonnet-4", | |
| 20 | 21 | "gpt-4", |
| 21 | 22 | "o3", |
| 22 | 23 | "gemini", |
| @@ -24,7 +25,7 @@ | ||
| 24 | 25 | }, |
| 25 | 26 | anthropic: (model) => { |
| 26 | 27 | if ( |
| 27 | - ["claude-3-5", "claude-3.5", "claude-3-7", "claude-3.7"].some((part) => | |
| 28 | + ["claude-3-5", "claude-3.5", "claude-3-7", "claude-3.7","claude-sonnet-4"].some((part) => | |
| 28 | 29 | model.toLowerCase().startsWith(part), |
| 29 | 30 | ) |
| 30 | 31 | ) { |
| @@ -76,7 +77,7 @@ | ||
| 76 | 77 | // For Bedrock, only support Claude Sonnet models with versions 3.5/3-5 and 3.7/3-7 |
| 77 | 78 | if ( |
| 78 | 79 | model.toLowerCase().includes("sonnet") && |
| 79 | - ["claude-3-5", "claude-3.5", "claude-3-7", "claude-3.7"].some((part) => | |
| 80 | + ["claude-3-5", "claude-3.5", "claude-3-7", "claude-3.7","claude-sonnet-4"].some((part) => | |
| 80 | 81 | model.toLowerCase().includes(part), |
| 81 | 82 | ) |
| 82 | 83 | ) { |
| @@ -88,6 +89,7 @@ | ||
| 88 | 89 | return ( |
| 89 | 90 | !model.toLowerCase().includes("mamba") && |
| 90 | 91 | [ |
| 92 | + "devstral", | |
| 91 | 93 | "codestral", |
| 92 | 94 | "mistral-large", |
| 93 | 95 | "mistral-small", |
| @@ -136,6 +138,7 @@ | ||
| 136 | 138 | "aya-expanse", |
| 137 | 139 | "firefunction-v2", |
| 138 | 140 | "mistral", |
| 141 | + "devstral", | |
| 139 | 142 | ].some((part) => modelName.toLowerCase().includes(part)) |
| 140 | 143 | ) { |
| 141 | 144 | return true; |
added core/llm/utils/extractPathsFromCodeBlocks.test.ts +35 −0
| @@ -0,0 +1,35 @@ | ||
| 1 | +import { extractPathsFromCodeBlocks } from "./extractPathsFromCodeBlocks"; | |
| 2 | + | |
| 3 | +describe("extractPathsFromCodeBlocks", () => { | |
| 4 | + it("should extract paths from code blocks with language and filepath", () => { | |
| 5 | + const content = "```typescript src/main.ts\nconst x = 1;\n```"; | |
| 6 | + expect(extractPathsFromCodeBlocks(content)).toEqual(["src/main.ts"]); | |
| 7 | + }); | |
| 8 | + | |
| 9 | + it("should extract paths from code blocks with filepath only (no language)", () => { | |
| 10 | + const content = "```test.js\nclass Calculator { }\n```"; | |
| 11 | + expect(extractPathsFromCodeBlocks(content)).toEqual(["test.js"]); | |
| 12 | + }); | |
| 13 | + | |
| 14 | + it("should extract paths from code blocks with line ranges", () => { | |
| 15 | + const content = "```js test.js (19-25)\nfunction test() {}\n```"; | |
| 16 | + expect(extractPathsFromCodeBlocks(content)).toEqual(["test.js"]); | |
| 17 | + }); | |
| 18 | + | |
| 19 | + it("should handle multiple code blocks with different formats", () => { | |
| 20 | + const content = | |
| 21 | + "```typescript src/main.ts\nconst x = 1;\n```\n" + | |
| 22 | + "```test.js\nclass Calculator { }\n```\n" + | |
| 23 | + "```js utils.js (19-25)\nfunction test() {}\n```"; | |
| 24 | + const result = extractPathsFromCodeBlocks(content); | |
| 25 | + expect(result).toContain("src/main.ts"); | |
| 26 | + expect(result).toContain("test.js"); | |
| 27 | + expect(result).toContain("utils.js"); | |
| 28 | + expect(result.length).toBe(3); | |
| 29 | + }); | |
| 30 | + | |
| 31 | + it("should not extract paths from code blocks without file paths", () => { | |
| 32 | + const content = "```typescript\nconst x = 1;\n```"; | |
| 33 | + expect(extractPathsFromCodeBlocks(content)).toEqual([]); | |
| 34 | + }); | |
| 35 | +}); | |
| No newline at the end of the file |
modified core/llm/utils/extractPathsFromCodeBlocks.ts +29 −13
| @@ -2,21 +2,37 @@ | ||
| 2 | 2 | * Extracts file paths from markdown code blocks |
| 3 | 3 | */ |
| 4 | 4 | export function extractPathsFromCodeBlocks(content: string): string[] { |
| 5 | - // Match: | |
| 6 | - // 1. Starting ``` | |
| 7 | - // 2. Optional language identifier | |
| 8 | - // 3. Required whitespace | |
| 9 | - // 4. File path (captured) that must contain a dot and extension | |
| 10 | - const codeBlockRegex = /```(?:[\w-+#]+)?\s+([^\s\n()]+\.[a-zA-Z0-9]+)/g; | |
| 5 | + console.log("CONTENT", content); | |
| 6 | + | |
| 11 | 7 | const paths: string[] = []; |
| 12 | - let match; | |
| 13 | - | |
| 14 | - while ((match = codeBlockRegex.exec(content)) !== null) { | |
| 15 | - const path = match[1]; | |
| 16 | - if (path && !path.startsWith("```")) { | |
| 17 | - paths.push(path); | |
| 8 | + | |
| 9 | + // Match code block opening patterns: | |
| 10 | + // 1. ```language filepath | |
| 11 | + // 2. ```filepath | |
| 12 | + // 3. ```language filepath (range) | |
| 13 | + | |
| 14 | + // First match all code block starts | |
| 15 | + const codeBlockStarts = content.match(/```[^\n]+/g) || []; | |
| 16 | + | |
| 17 | + for (const blockStart of codeBlockStarts) { | |
| 18 | + // Try to extract a valid filename with extension | |
| 19 | + const filenameMatches = blockStart.match(/([^\s()```]+\.[a-zA-Z0-9]+)/); | |
| 20 | + | |
| 21 | + if (filenameMatches && filenameMatches[1]) { | |
| 22 | + const filename = filenameMatches[1]; | |
| 23 | + | |
| 24 | + // Verify this is a legitimate filename (not part of something else) | |
| 25 | + if ( | |
| 26 | + // Check if valid extension | |
| 27 | + /\.[a-zA-Z0-9]+$/.test(filename) && | |
| 28 | + // Make sure it's not a URL | |
| 29 | + !filename.includes("://") && | |
| 30 | + // Avoid duplicates | |
| 31 | + !paths.includes(filename) | |
| 32 | + ) { | |
| 33 | + paths.push(filename); | |
| 34 | + } | |
| 18 | 35 | } |
| 19 | 36 | } |
| 20 | - | |
| 21 | 37 | return paths; |
| 22 | 38 | } |
modified core/package-lock.json +0 −0
Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.
modified core/package.json +2 −0
| @@ -27,6 +27,7 @@ | ||
| 27 | 27 | "@types/mustache": "^4.2.5", |
| 28 | 28 | "@types/node-fetch": "^2.6.11", |
| 29 | 29 | "@types/pg": "^8.11.6", |
| 30 | + "@types/plist": "^3.0.5", | |
| 30 | 31 | "@types/request": "^2.48.12", |
| 31 | 32 | "@types/tar": "^6.1.13", |
| 32 | 33 | "@types/uuid": "^9.0.7", |
| @@ -89,6 +90,7 @@ | ||
| 89 | 90 | "p-limit": "^6.1.0", |
| 90 | 91 | "partial-json": "^0.1.7", |
| 91 | 92 | "pg": "^8.11.3", |
| 93 | + "plist": "^3.1.0", | |
| 92 | 94 | "posthog-node": "^3.6.3", |
| 93 | 95 | "puppeteer": "^22.4.0", |
| 94 | 96 | "puppeteer-chromium-resolver": "^23.0.0", |
modified core/protocol/core.ts +1 −1
| @@ -33,7 +33,7 @@ | ||
| 33 | 33 | ToolCall, |
| 34 | 34 | } from "../"; |
| 35 | 35 | import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager"; |
| 36 | -import { ControlPlaneSessionInfo } from "../control-plane/client"; | |
| 36 | +import { ControlPlaneSessionInfo } from "../control-plane/AuthTypes"; | |
| 37 | 37 | |
| 38 | 38 | export type OnboardingModes = "Local" | "Best" | "Custom" | "Quickstart"; |
| 39 | 39 |
modified core/protocol/ide.ts +2 −3
| @@ -1,5 +1,3 @@ | ||
| 1 | -import { ControlPlaneSessionInfo } from "../control-plane/client"; | |
| 2 | - | |
| 3 | 1 | import type { |
| 4 | 2 | ContinueRcJson, |
| 5 | 3 | DiffLine, |
| @@ -16,6 +14,7 @@ | ||
| 16 | 14 | TerminalOptions, |
| 17 | 15 | Thread, |
| 18 | 16 | } from "../"; |
| 17 | +import { ControlPlaneSessionInfo } from "../control-plane/AuthTypes"; | |
| 19 | 18 | |
| 20 | 19 | export interface GetGhTokenArgs { |
| 21 | 20 | force?: boolean; |
| @@ -99,7 +98,7 @@ | ||
| 99 | 98 | ControlPlaneSessionInfo | undefined, |
| 100 | 99 | ]; |
| 101 | 100 | logoutOfControlPlane: [undefined, void]; |
| 102 | - reportError:[any, void]; | |
| 101 | + reportError: [any, void]; | |
| 103 | 102 | closeSidebar: [undefined, void]; |
| 104 | 103 | }; |
| 105 | 104 |
modified core/protocol/ideWebview.ts +5 −4
| @@ -2,12 +2,13 @@ | ||
| 2 | 2 | import { ToWebviewFromIdeOrCoreProtocol } from "./webview"; |
| 3 | 3 | |
| 4 | 4 | import { |
| 5 | + AcceptOrRejectDiffPayload, | |
| 5 | 6 | ApplyState, |
| 6 | - SetCodeToEditPayload, | |
| 7 | 7 | HighlightedCodePayload, |
| 8 | 8 | MessageContent, |
| 9 | 9 | RangeInFileWithContents, |
| 10 | - AcceptOrRejectDiffPayload, | |
| 10 | + SetCodeToEditPayload, | |
| 11 | + ShowFilePayload, | |
| 11 | 12 | } from "../"; |
| 12 | 13 | |
| 13 | 14 | export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { |
| @@ -23,7 +24,7 @@ | ||
| 23 | 24 | ]; |
| 24 | 25 | overwriteFile: [{ filepath: string; prevFileContent: string | null }, void]; |
| 25 | 26 | showTutorial: [undefined, void]; |
| 26 | - showFile: [{ filepath: string }, void]; | |
| 27 | + showFile: [ShowFilePayload, void]; | |
| 27 | 28 | toggleDevTools: [undefined, void]; |
| 28 | 29 | reloadWindow: [undefined, void]; |
| 29 | 30 | focusEditor: [undefined, void]; |
| @@ -41,7 +42,7 @@ | ||
| 41 | 42 | vscMediaUrl: string; |
| 42 | 43 | }, |
| 43 | 44 | ]; |
| 44 | - "jetbrains/getColors": [undefined, Record<string, string>]; | |
| 45 | + "jetbrains/getColors": [undefined, Record<string, string | null | undefined>]; | |
| 45 | 46 | "vscode/openMoveRightMarkdown": [undefined, void]; |
| 46 | 47 | setGitHubAuthToken: [{ token: string }, void]; |
| 47 | 48 | acceptDiff: [AcceptOrRejectDiffPayload, void]; |
modified core/protocol/webview.ts +2 −2
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | import { ConfigResult } from "@continuedev/config-yaml"; |
| 2 | 2 | import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager.js"; |
| 3 | -import { ControlPlaneSessionInfo } from "../control-plane/client.js"; | |
| 3 | +import { ControlPlaneSessionInfo } from "../control-plane/AuthTypes.js"; | |
| 4 | 4 | import type { |
| 5 | 5 | BrowserSerializedContinueConfig, |
| 6 | 6 | ContextItemWithId, |
| @@ -40,7 +40,7 @@ | ||
| 40 | 40 | setTTSActive: [boolean, void]; |
| 41 | 41 | getWebviewHistoryLength: [undefined, number]; |
| 42 | 42 | getCurrentSessionId: [undefined, string]; |
| 43 | - "jetbrains/setColors": [Record<string, string>, void]; | |
| 43 | + "jetbrains/setColors": [Record<string, string | null | undefined>, void]; | |
| 44 | 44 | sessionUpdate: [{ sessionInfo: ControlPlaneSessionInfo | undefined }, void]; |
| 45 | 45 | toolCallPartialOutput: [{ toolCallId: string; contextItems: any[] }, void]; |
| 46 | 46 | }; |
modified core/tools/definitions/createRuleBlock.ts +5 −1
| @@ -13,7 +13,7 @@ | ||
| 13 | 13 | function: { |
| 14 | 14 | name: BuiltInToolNames.CreateRuleBlock, |
| 15 | 15 | description: |
| 16 | - "Creates a persistent rule for all future conversations. For establishing code standards or preferences that should be applied consistently.", | |
| 16 | + "Creates a persistent rule for all future conversations. For establishing code standards or preferences that should be applied consistently. To modify existing rules, use the edit tool instead.", | |
| 17 | 17 | parameters: { |
| 18 | 18 | type: "object", |
| 19 | 19 | required: ["name", "rule"], |
| @@ -28,6 +28,10 @@ | ||
| 28 | 28 | description: |
| 29 | 29 | "Clear, imperative instruction for future code generation (e.g. 'Use named exports', 'Add Python type hints'). Each rule should focus on one specific standard.", |
| 30 | 30 | }, |
| 31 | + description: { | |
| 32 | + type: "string", | |
| 33 | + description: "Short description of the rule", | |
| 34 | + }, | |
| 31 | 35 | globs: { |
| 32 | 36 | type: "string", |
| 33 | 37 | description: |
modified core/tools/implementations/createRuleBlock.test.ts +54 −36
| @@ -1,4 +1,4 @@ | ||
| 1 | -import * as YAML from "yaml"; | |
| 1 | +import { parseMarkdownRule } from "../../config/markdown/parseMarkdownRule"; | |
| 2 | 2 | import { createRuleBlockImpl } from "./createRuleBlock"; |
| 3 | 3 | |
| 4 | 4 | // Mock the extras parameter with necessary functions |
| @@ -17,33 +17,6 @@ | ||
| 17 | 17 | jest.clearAllMocks(); |
| 18 | 18 | }); |
| 19 | 19 | |
| 20 | - it("should create a basic rule with name and rule content", async () => { | |
| 21 | - const args = { | |
| 22 | - name: "Test Rule", | |
| 23 | - rule: "Always write tests", | |
| 24 | - }; | |
| 25 | - | |
| 26 | - const result = await createRuleBlockImpl(args, mockExtras as any); | |
| 27 | - | |
| 28 | - // Verify that writeFile was called with the correct YAML | |
| 29 | - expect(mockIde.writeFile).toHaveBeenCalled(); | |
| 30 | - const yamlContent = mockIde.writeFile.mock.calls[0][1]; | |
| 31 | - const parsedYaml = YAML.parse(yamlContent); | |
| 32 | - | |
| 33 | - // Verify the structure of the YAML | |
| 34 | - expect(parsedYaml).toEqual({ | |
| 35 | - name: "Test Rule", | |
| 36 | - version: "0.0.1", | |
| 37 | - schema: "v1", | |
| 38 | - rules: [ | |
| 39 | - { | |
| 40 | - name: "Test Rule", | |
| 41 | - rule: "Always write tests", | |
| 42 | - }, | |
| 43 | - ], | |
| 44 | - }); | |
| 45 | - }); | |
| 46 | - | |
| 47 | 20 | it("should create a rule with glob pattern", async () => { |
| 48 | 21 | const args = { |
| 49 | 22 | name: "TypeScript Rule", |
| @@ -53,14 +26,16 @@ | ||
| 53 | 26 | |
| 54 | 27 | await createRuleBlockImpl(args, mockExtras as any); |
| 55 | 28 | |
| 56 | - // Verify the YAML structure with globs | |
| 57 | - const yamlContent = mockIde.writeFile.mock.calls[0][1]; | |
| 58 | - const parsedYaml = YAML.parse(yamlContent); | |
| 59 | - expect(parsedYaml.rules[0]).toEqual({ | |
| 60 | - name: "TypeScript Rule", | |
| 61 | - rule: "Use interfaces for object shapes", | |
| 29 | + const fileContent = mockIde.writeFile.mock.calls[0][1]; | |
| 30 | + | |
| 31 | + const { frontmatter, markdown } = parseMarkdownRule(fileContent); | |
| 32 | + | |
| 33 | + expect(frontmatter).toEqual({ | |
| 62 | 34 | globs: "**/*.{ts,tsx}", |
| 63 | 35 | }); |
| 36 | + | |
| 37 | + expect(markdown).toContain("# TypeScript Rule"); | |
| 38 | + expect(markdown).toContain("Use interfaces for object shapes"); | |
| 64 | 39 | }); |
| 65 | 40 | |
| 66 | 41 | it("should create a filename based on sanitized rule name", async () => { |
| @@ -71,8 +46,51 @@ | ||
| 71 | 46 | |
| 72 | 47 | await createRuleBlockImpl(args, mockExtras as any); |
| 73 | 48 | |
| 74 | - // Check that the filename is sanitized | |
| 75 | 49 | const fileUri = mockIde.writeFile.mock.calls[0][0]; |
| 76 | - expect(fileUri).toContain("special-chracters-spaces.yaml"); | |
| 50 | + expect(fileUri).toContain("special-chracters-spaces.md"); | |
| 51 | + }); | |
| 52 | + | |
| 53 | + it("should create a rule with description pattern", async () => { | |
| 54 | + const args = { | |
| 55 | + name: "Description Test", | |
| 56 | + rule: "This is the rule content", | |
| 57 | + description: "This is a detailed explanation of the rule", | |
| 58 | + }; | |
| 59 | + | |
| 60 | + await createRuleBlockImpl(args, mockExtras as any); | |
| 61 | + | |
| 62 | + const fileContent = mockIde.writeFile.mock.calls[0][1]; | |
| 63 | + | |
| 64 | + const { frontmatter, markdown } = parseMarkdownRule(fileContent); | |
| 65 | + | |
| 66 | + expect(frontmatter).toEqual({ | |
| 67 | + description: "This is a detailed explanation of the rule", | |
| 68 | + }); | |
| 69 | + | |
| 70 | + expect(markdown).toContain("# Description Test"); | |
| 71 | + expect(markdown).toContain("This is the rule content"); | |
| 72 | + }); | |
| 73 | + | |
| 74 | + it("should include both globs and description in frontmatter", async () => { | |
| 75 | + const args = { | |
| 76 | + name: "Complete Rule", | |
| 77 | + rule: "Follow this standard", | |
| 78 | + description: "This rule enforces our team standards", | |
| 79 | + globs: "**/*.js", | |
| 80 | + }; | |
| 81 | + | |
| 82 | + await createRuleBlockImpl(args, mockExtras as any); | |
| 83 | + | |
| 84 | + const fileContent = mockIde.writeFile.mock.calls[0][1]; | |
| 85 | + | |
| 86 | + const { frontmatter, markdown } = parseMarkdownRule(fileContent); | |
| 87 | + | |
| 88 | + expect(frontmatter).toEqual({ | |
| 89 | + description: "This rule enforces our team standards", | |
| 90 | + globs: "**/*.js", | |
| 91 | + }); | |
| 92 | + | |
| 93 | + expect(markdown).toContain("# Complete Rule"); | |
| 94 | + expect(markdown).toContain("Follow this standard"); | |
| 77 | 95 | }); |
| 78 | 96 | }); |
modified core/tools/implementations/createRuleBlock.ts +22 −17
| @@ -1,4 +1,3 @@ | ||
| 1 | -import { ConfigYaml } from "@continuedev/config-yaml"; | |
| 2 | 1 | import * as YAML from "yaml"; |
| 3 | 2 | import { ToolImpl } from "."; |
| 4 | 3 | import { joinPathsToUri } from "../../util/uri"; |
| @@ -6,6 +5,7 @@ | ||
| 6 | 5 | export interface CreateRuleBlockArgs { |
| 7 | 6 | name: string; |
| 8 | 7 | rule: string; |
| 8 | + description: string; | |
| 9 | 9 | globs?: string; |
| 10 | 10 | } |
| 11 | 11 | |
| @@ -19,41 +19,46 @@ | ||
| 19 | 19 | .replace(/[^a-z0-9\s-]/g, "") |
| 20 | 20 | .replace(/\s+/g, "-"); |
| 21 | 21 | |
| 22 | - const ruleObject = { | |
| 23 | - name: args.name, | |
| 24 | - rule: args.rule, | |
| 25 | - ...(args.globs ? { globs: args.globs.trim() } : {}), | |
| 26 | - }; | |
| 22 | + const fileExtension = "md"; | |
| 27 | 23 | |
| 28 | - const ruleBlock: ConfigYaml = { | |
| 29 | - name: args.name, | |
| 30 | - version: "0.0.1", | |
| 31 | - schema: "v1", | |
| 32 | - rules: [ruleObject], | |
| 33 | - }; | |
| 24 | + const frontmatter: Record<string, string> = {}; | |
| 34 | 25 | |
| 35 | - const ruleYaml = YAML.stringify(ruleBlock); | |
| 26 | + if (args.globs) { | |
| 27 | + frontmatter.globs = args.globs.trim(); | |
| 28 | + } | |
| 36 | 29 | |
| 30 | + if (args.description) { | |
| 31 | + frontmatter.description = args.description.trim(); | |
| 32 | + } | |
| 33 | + const frontmatterYaml = YAML.stringify(frontmatter).trim(); | |
| 34 | + let fileContent = `--- | |
| 35 | +${frontmatterYaml} | |
| 36 | +--- | |
| 37 | + | |
| 38 | +# ${args.name} | |
| 39 | + | |
| 40 | +${args.rule} | |
| 41 | +`; | |
| 37 | 42 | const [localContinueDir] = await extras.ide.getWorkspaceDirs(); |
| 38 | 43 | const rulesDirUri = joinPathsToUri( |
| 39 | 44 | localContinueDir, |
| 40 | 45 | ".continue", |
| 41 | 46 | "rules", |
| 42 | - `${safeRuleName}.yaml`, | |
| 47 | + `${safeRuleName}.${fileExtension}`, | |
| 43 | 48 | ); |
| 44 | 49 | |
| 45 | - await extras.ide.writeFile(rulesDirUri, ruleYaml); | |
| 50 | + await extras.ide.writeFile(rulesDirUri, fileContent); | |
| 46 | 51 | await extras.ide.openFile(rulesDirUri); |
| 47 | 52 | |
| 48 | 53 | return [ |
| 49 | 54 | { |
| 50 | 55 | name: "New Rule Block", |
| 51 | - description: "", // No description throws an error in the GUI | |
| 56 | + description: args.description || "", | |
| 52 | 57 | uri: { |
| 53 | 58 | type: "file", |
| 54 | 59 | value: rulesDirUri, |
| 55 | 60 | }, |
| 56 | - content: "Rule created successfully", | |
| 61 | + content: `Rule created successfully`, | |
| 57 | 62 | }, |
| 58 | 63 | ]; |
| 59 | 64 | }; |
added core/util/shellPath.ts +29 −0
| @@ -0,0 +1,29 @@ | ||
| 1 | +import { execSync } from "child_process"; | |
| 2 | + | |
| 3 | +/** | |
| 4 | + * Gets the PATH env var from the user's login shell on non-Windows platforms. | |
| 5 | + * Windows is not implemented primarily because it is not needed at the moment. | |
| 6 | + * @returns The enhanced PATH from the user's shell, or the current PATH if it cannot be determined | |
| 7 | + */ | |
| 8 | +export function getEnvPathFromUserShell(): string | undefined { | |
| 9 | + if (process.platform === "win32") { | |
| 10 | + console.warn(`${getEnvPathFromUserShell.name} not implemented for Windows`); | |
| 11 | + return undefined; | |
| 12 | + } | |
| 13 | + | |
| 14 | + if (!process.env.SHELL) { | |
| 15 | + return undefined; | |
| 16 | + } | |
| 17 | + | |
| 18 | + try { | |
| 19 | + const command = `${process.env.SHELL} -l -c 'echo $PATH'`; | |
| 20 | + | |
| 21 | + const stdout = execSync(command, { | |
| 22 | + encoding: "utf8", | |
| 23 | + }); | |
| 24 | + | |
| 25 | + return stdout.trim(); | |
| 26 | + } catch (error) { | |
| 27 | + return process.env.PATH; // Fallback to current PATH | |
| 28 | + } | |
| 29 | +} |
modified docs/docs/reference.md +2 −1
| @@ -188,6 +188,7 @@ | ||
| 188 | 188 | not currently used. |
| 189 | 189 | - `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on |
| 190 | 190 | provider and model. Supported capabilities include `tool_use` and `image_input`. |
| 191 | +- `maxStopWords`: Maximum number of stop words allowed, to avoid API errors with extensive lists. | |
| 191 | 192 | - `promptTemplates`: Can be used to override the default prompt templates for different model roles. Valid values are |
| 192 | 193 | `chat`, [`edit`](./customize/model-roles/edit.mdx#prompt-templating), [ |
| 193 | 194 | `apply`](./customize/model-roles/apply.mdx#prompt-templating) and [ |
| @@ -406,7 +407,7 @@ | ||
| 406 | 407 | - `destination` (**required**): The destination/endpoint that will receive the data. Can be: |
| 407 | 408 | - an HTTP endpoint that will receive a POST request with a JSON blob |
| 408 | 409 | - a file URL to a directory in which events will be dumpted to `.jsonl` files |
| 409 | -- `schema` (**required**): the schema version of the JSON blobs to be sent | |
| 410 | +- `schema` (**required**): the schema version of the JSON blobs to be sent. Options include `0.1.0` and `0.2.0` | |
| 410 | 411 | - `events`: an array of event names to include. Defaults to all events if not specified. |
| 411 | 412 | - `level`: a pre-defined filter for event fields. Options include `all` and `noCode`; the latter excludes data like file |
| 412 | 413 | contents, prompts, and completions. Defaults to `all` |
modified docs/docs/troubleshooting.mdx +2 −0
| @@ -120,6 +120,8 @@ | ||
| 120 | 120 | |
| 121 | 121 | You may also set `requestOptions.caBundlePath` to an array of paths to multiple certificates. |
| 122 | 122 | |
| 123 | +***Windows VS Code Users***: Installing the [win-ca](https://marketplace.visualstudio.com/items?itemName=ukoloff.win-ca) extension should also correct this issue. | |
| 124 | + | |
| 123 | 125 | #### VS Code Proxy Settings |
| 124 | 126 | |
| 125 | 127 | If you are using VS Code and require requests to be made through a proxy, you are likely already set up through VS Code's [Proxy Server Support](https://code.visualstudio.com/docs/setup/network#_proxy-server-support). To double-check that this is enabled, use <kbd>cmd/ctrl</kbd> + <kbd>,</kbd> to open settings and search for "Proxy Support". Unless it is set to "off", then VS Code is responsible for making the request to the proxy. |
modified docs/docusaurus.config.js +3 −1
| @@ -66,7 +66,9 @@ | ||
| 66 | 66 | ], |
| 67 | 67 | |
| 68 | 68 | scripts: [ |
| 69 | - '!function(){var e,t,n;e="7aa28ed11570734",t=function(){Reo.init({clientID:"7aa28ed11570734"})},(n=document.createElement("script")).src="https://static.reo.dev/"+e+"/reo.js",n.defer=!0,n.onload=t,document.head.appendChild(n)}();', | |
| 69 | + { | |
| 70 | + src: "/scripts/custom-reo.js", // it references from static folder | |
| 71 | + }, | |
| 70 | 72 | ], |
| 71 | 73 | |
| 72 | 74 | themeConfig: |
added docs/static/scripts/custom-reo.js +1 −0
| @@ -0,0 +1,1 @@ | ||
| 1 | +!function(){var e,t,n;e="7aa28ed11570734",t=function(){Reo.init({clientID:"7aa28ed11570734"})},(n=document.createElement("script")).src="https://static.reo.dev/"+e+"/reo.js",n.async=!0,n.onload=t,document.head.appendChild(n)}(); | |
| No newline at the end of the file |
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinueActionPromote.kt +11 −7
| @@ -11,15 +11,19 @@ | ||
| 11 | 11 | class ContinueActionPromote : ActionPromoter { |
| 12 | 12 | |
| 13 | 13 | override fun promote(@NotNull actions: List<AnAction>, @NotNull context: DataContext): List<AnAction>? { |
| 14 | - | |
| 15 | - if (actions.none { it is AcceptAutocompleteAction }) { | |
| 16 | - return null | |
| 17 | - } else { | |
| 14 | + // For autocomplete actions | |
| 15 | + if (actions.any { it is AcceptAutocompleteAction }) { | |
| 18 | 16 | val settings = ServiceManager.getService(ContinueExtensionSettings::class.java) |
| 19 | - if (!settings.continueState.showIDECompletionSideBySide) { | |
| 20 | - return null; | |
| 17 | + if (settings.continueState.showIDECompletionSideBySide) { | |
| 18 | + return actions.filterIsInstance<AcceptAutocompleteAction>() | |
| 21 | 19 | } |
| 22 | - return actions.filterIsInstance<AcceptAutocompleteAction>() | |
| 23 | 20 | } |
| 21 | + | |
| 22 | + val rejectDiffActions = actions.filterIsInstance<RejectDiffAction>() | |
| 23 | + if (rejectDiffActions.isNotEmpty()) { | |
| 24 | + return rejectDiffActions | |
| 25 | + } | |
| 26 | + | |
| 27 | + return null | |
| 24 | 28 | } |
| 25 | 29 | } |
| No newline at the end of the file |
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt +6 −38
| @@ -1,25 +1,12 @@ | ||
| 1 | 1 | package com.github.continuedev.continueintellijextension.actions |
| 2 | 2 | |
| 3 | 3 | import com.github.continuedev.continueintellijextension.editor.DiffStreamService |
| 4 | -import com.github.continuedev.continueintellijextension.services.ContinuePluginService | |
| 5 | 4 | import com.intellij.openapi.actionSystem.AnAction |
| 6 | 5 | import com.intellij.openapi.actionSystem.AnActionEvent |
| 7 | 6 | import com.intellij.openapi.actionSystem.PlatformDataKeys |
| 8 | -import com.intellij.openapi.components.ServiceManager | |
| 9 | 7 | import com.intellij.openapi.components.service |
| 10 | 8 | import com.intellij.openapi.fileEditor.FileEditorManager |
| 11 | -import com.intellij.openapi.project.Project | |
| 12 | -import com.intellij.openapi.wm.ToolWindowManager | |
| 13 | - | |
| 14 | -fun getPluginService(project: Project?): ContinuePluginService? { | |
| 15 | - if (project == null) { | |
| 16 | - return null | |
| 17 | - } | |
| 18 | - return ServiceManager.getService( | |
| 19 | - project, | |
| 20 | - ContinuePluginService::class.java | |
| 21 | - ) | |
| 22 | -} | |
| 9 | + | |
| 23 | 10 | |
| 24 | 11 | class AcceptDiffAction : AnAction() { |
| 25 | 12 | override fun actionPerformed(e: AnActionEvent) { |
| @@ -29,7 +16,7 @@ | ||
| 29 | 16 | |
| 30 | 17 | private fun acceptHorizontalDiff(e: AnActionEvent) { |
| 31 | 18 | val continuePluginService = getPluginService(e.project) ?: return |
| 32 | - continuePluginService?.diffManager?.acceptDiff(null) | |
| 19 | + continuePluginService.diffManager?.acceptDiff(null) | |
| 33 | 20 | } |
| 34 | 21 | |
| 35 | 22 | private fun acceptVerticalDiff(e: AnActionEvent) { |
| @@ -61,28 +48,6 @@ | ||
| 61 | 48 | } |
| 62 | 49 | } |
| 63 | 50 | |
| 64 | -fun getContinuePluginService(project: Project?): ContinuePluginService? { | |
| 65 | - if (project != null) { | |
| 66 | - val toolWindowManager = ToolWindowManager.getInstance(project) | |
| 67 | - val toolWindow = toolWindowManager.getToolWindow("Continue") | |
| 68 | - | |
| 69 | - if (toolWindow != null) { | |
| 70 | - if (!toolWindow.isVisible) { | |
| 71 | - toolWindow.activate(null) | |
| 72 | - } | |
| 73 | - } | |
| 74 | - } | |
| 75 | - | |
| 76 | - return getPluginService(project) | |
| 77 | -} | |
| 78 | - | |
| 79 | -fun focusContinueInput(project: Project?) { | |
| 80 | - val continuePluginService = getContinuePluginService(project) ?: return | |
| 81 | - continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus() | |
| 82 | - continuePluginService.sendToWebview("focusContinueInputWithoutClear", null) | |
| 83 | - | |
| 84 | - continuePluginService.ideProtocolClient?.sendHighlightedCode() | |
| 85 | -} | |
| 86 | 51 | |
| 87 | 52 | class FocusContinueInputWithoutClearAction : AnAction() { |
| 88 | 53 | override fun actionPerformed(e: AnActionEvent) { |
| @@ -134,8 +99,11 @@ | ||
| 134 | 99 | if (logFile.exists()) { |
| 135 | 100 | val virtualFile = com.intellij.openapi.vfs.LocalFileSystem.getInstance().findFileByIoFile(logFile) |
| 136 | 101 | if (virtualFile != null) { |
| 137 | - com.intellij.openapi.fileEditor.FileEditorManager.getInstance(project).openFile(virtualFile, true) | |
| 102 | + FileEditorManager.getInstance(project).openFile(virtualFile, true) | |
| 138 | 103 | } |
| 139 | 104 | } |
| 140 | 105 | } |
| 141 | 106 | } |
| 107 | + | |
| 108 | + | |
| 109 | + |
added extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/utils.kt +39 −0
| @@ -0,0 +1,39 @@ | ||
| 1 | +package com.github.continuedev.continueintellijextension.actions | |
| 2 | + | |
| 3 | +import com.github.continuedev.continueintellijextension.services.ContinuePluginService | |
| 4 | +import com.intellij.openapi.components.ServiceManager | |
| 5 | +import com.intellij.openapi.project.Project | |
| 6 | +import com.intellij.openapi.wm.ToolWindowManager | |
| 7 | + | |
| 8 | +fun getContinuePluginService(project: Project?): ContinuePluginService? { | |
| 9 | + if (project != null) { | |
| 10 | + val toolWindowManager = ToolWindowManager.getInstance(project) | |
| 11 | + val toolWindow = toolWindowManager.getToolWindow("Continue") | |
| 12 | + | |
| 13 | + if (toolWindow != null) { | |
| 14 | + if (!toolWindow.isVisible) { | |
| 15 | + toolWindow.activate(null) | |
| 16 | + } | |
| 17 | + } | |
| 18 | + } | |
| 19 | + | |
| 20 | + return getPluginService(project) | |
| 21 | +} | |
| 22 | + | |
| 23 | +fun focusContinueInput(project: Project?) { | |
| 24 | + val continuePluginService = getContinuePluginService(project) ?: return | |
| 25 | + continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus() | |
| 26 | + continuePluginService.sendToWebview("focusContinueInputWithoutClear", null) | |
| 27 | + | |
| 28 | + continuePluginService.ideProtocolClient?.sendHighlightedCode() | |
| 29 | +} | |
| 30 | + | |
| 31 | +fun getPluginService(project: Project?): ContinuePluginService? { | |
| 32 | + if (project == null) { | |
| 33 | + return null | |
| 34 | + } | |
| 35 | + return ServiceManager.getService( | |
| 36 | + project, | |
| 37 | + ContinuePluginService::class.java | |
| 38 | + ) | |
| 39 | +} | |
| No newline at the end of the file |
deleted extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteActionGroup.kt +0 −29
| @@ -1,29 +0,0 @@ | ||
| 1 | -package com.github.continuedev.continueintellijextension.autocomplete | |
| 2 | - | |
| 3 | -import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings | |
| 4 | -import com.intellij.openapi.actionSystem.ActionUpdateThread | |
| 5 | -import com.intellij.openapi.actionSystem.AnActionEvent | |
| 6 | -import com.intellij.openapi.actionSystem.DefaultActionGroup | |
| 7 | -import com.intellij.openapi.components.service | |
| 8 | - | |
| 9 | -class AutocompleteActionGroup : DefaultActionGroup() { | |
| 10 | - override fun getActionUpdateThread(): ActionUpdateThread { | |
| 11 | - return ActionUpdateThread.EDT | |
| 12 | - } | |
| 13 | - | |
| 14 | - override fun update(e: AnActionEvent) { | |
| 15 | - super.update(e) | |
| 16 | - removeAll() | |
| 17 | - | |
| 18 | - val continueSettingsService = service<ContinueExtensionSettings>() | |
| 19 | - if (continueSettingsService.continueState.enableTabAutocomplete) { | |
| 20 | - addAll( | |
| 21 | - DisableTabAutocompleteAction(), | |
| 22 | - ) | |
| 23 | - } else { | |
| 24 | - addAll( | |
| 25 | - EnableTabAutocompleteAction(), | |
| 26 | - ) | |
| 27 | - } | |
| 28 | - } | |
| 29 | -} | |
| No newline at the end of the file |
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt +2 −2
| @@ -121,10 +121,10 @@ | ||
| 121 | 121 | val prompt = buildApplyPrompt() |
| 122 | 122 | |
| 123 | 123 | // Extract the code ranges (highlighted or full document) |
| 124 | - val (prefix, highlighted, suffix) = editorUtils.extractCodeRanges() | |
| 124 | + val (prefix, highlighted, suffix) = editorUtils.getHighlightedRangeTriplet() | |
| 125 | 125 | |
| 126 | 126 | // Get the line range for the diff stream |
| 127 | - val rif = editorUtils.getHighlightedCode() | |
| 127 | + val rif = editorUtils.getHighlightedRIF() | |
| 128 | 128 | val startLine = rif?.range?.start?.line ?: 0 |
| 129 | 129 | val endLine = rif?.range?.end?.line ?: (editorUtils.getLineCount() - 1) |
| 130 | 130 |
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GetTheme.kt +146 −35
| @@ -2,11 +2,13 @@ | ||
| 2 | 2 | |
| 3 | 3 | import com.intellij.openapi.editor.colors.EditorColors |
| 4 | 4 | import com.intellij.openapi.editor.colors.EditorColorsManager |
| 5 | +import com.intellij.openapi.editor.colors.CodeInsightColors | |
| 5 | 6 | import java.awt.Color |
| 6 | 7 | import kotlin.math.max |
| 7 | 8 | import kotlin.math.min |
| 8 | 9 | import com.intellij.ui.JBColor |
| 9 | 10 | import com.intellij.ui.ColorUtil |
| 11 | +import kotlin.math.roundToInt | |
| 10 | 12 | |
| 11 | 13 | class GetTheme { |
| 12 | 14 | fun getSecondaryDark(): Color { |
| @@ -38,64 +40,173 @@ | ||
| 38 | 40 | return globalScheme.getColor(EditorColors.MODIFIED_TAB_ICON_COLOR) ?: globalScheme.defaultForeground |
| 39 | 41 | } |
| 40 | 42 | |
| 41 | - fun getTheme(): Map<String, String> { | |
| 42 | - fun toHex(color: Color): String { | |
| 43 | - return String.format("#%02x%02x%02x", color.red, color.green, color.blue) | |
| 43 | + fun toHex(color: Color?): String? { | |
| 44 | + if(color == null) { | |
| 45 | + return null | |
| 44 | 46 | } |
| 47 | + return String.format("#%02x%02x%02x", color.red, color.green, color.blue) | |
| 48 | + } | |
| 49 | + | |
| 50 | + fun namedColor(name: String): Color? { | |
| 51 | + // JB Color named color will fall back to a default unless we give it a fallback | |
| 52 | + // We want defaults to be handled on the GUI side, so we give it this filler color | |
| 53 | + // Which has a very low chance of conflicting with a real one | |
| 54 | + // And return undefined if it gets the skip color | |
| 55 | + val SKIP_COLOR = Color (18, 52, 86) // Hex #123456 | |
| 56 | + val color = JBColor.namedColor(name, SKIP_COLOR) | |
| 57 | + if(toHex(color) == "#123456") { | |
| 58 | + return null | |
| 59 | + } | |
| 60 | + return color | |
| 61 | + } | |
| 62 | + | |
| 63 | + fun lighten(color: Color, percentage: Int = 5): Color { | |
| 64 | + // Increase each RGB component slightly | |
| 65 | + val factor = 1 + percentage / 100f; | |
| 66 | + fun lightenInt(value: Int): Int { | |
| 67 | + return (value * factor).roundToInt().coerceAtMost(255) | |
| 68 | + } | |
| 69 | + return Color( | |
| 70 | + lightenInt(color.red), | |
| 71 | + lightenInt (color.green), | |
| 72 | + lightenInt(color.blue), | |
| 73 | + color.alpha | |
| 74 | + ) | |
| 75 | + } | |
| 76 | + | |
| 77 | + fun darken(color: Color, percentage: Int = 5): Color { | |
| 78 | + // Decrease each RGB component slightly | |
| 79 | + val factor = 1 - percentage / 100f; | |
| 80 | + fun darkenInt(value: Int): Int { | |
| 81 | + return (value * factor).roundToInt().coerceAtLeast(0) | |
| 82 | + } | |
| 83 | + return Color( | |
| 84 | + darkenInt(color.red), | |
| 85 | + darkenInt(color.green), | |
| 86 | + darkenInt(color.blue), | |
| 87 | + color.alpha | |
| 88 | + ) | |
| 89 | + } | |
| 90 | + | |
| 91 | + fun slightChange(color: Color?, percentage: Int = 5): Color? { | |
| 92 | + if(color == null){ | |
| 93 | + return null | |
| 94 | + } | |
| 95 | + // If dark, make slightly lighter. If light, make slightly darker | |
| 96 | + val averageRgb = (color.red + color.green + color.blue) / 3 | |
| 97 | + return if (averageRgb > 128) darken(color, percentage) else lighten(color, percentage) | |
| 98 | + } | |
| 99 | + | |
| 100 | + fun getTheme(): Map<String, String?> { | |
| 45 | 101 | try { |
| 102 | + val editorScheme = EditorColorsManager.getInstance().globalScheme | |
| 103 | + | |
| 46 | 104 | val background = JBColor.background() |
| 47 | 105 | val foreground = JBColor.foreground() |
| 48 | 106 | |
| 49 | - val buttonBackground = JBColor.namedColor("Button.background", Color(230, 230, 230)) | |
| 50 | - val buttonForeground = JBColor.namedColor("Button.foreground", Color(0, 0, 0)) | |
| 107 | + val border = JBColor.border() | |
| 108 | + val focusBorder = namedColor("Focus.borderColor") ?: namedColor("Component.focusedBorderColor") | |
| 51 | 109 | |
| 52 | - val badgeBackground = JBColor.namedColor("Badge.background", Color(150, 150, 150)) | |
| 53 | - val badgeForeground = JBColor.namedColor("Badge.foreground", Color(0, 0, 0)) | |
| 110 | + val buttonBackground = namedColor("Button.default.startBackground") | |
| 111 | + ?: namedColor("Button.default.background") | |
| 54 | 112 | |
| 55 | - val inputBackground = JBColor.namedColor("TextField.background", Color(255, 255, 255)) | |
| 113 | + val buttonForeground = namedColor("Button.default.startForeground") | |
| 114 | + ?: namedColor("Button.default.foreground") | |
| 56 | 115 | |
| 57 | - val border = JBColor.border() | |
| 58 | - val focusBorder = JBColor.namedColor("Focus.borderColor", Color(100, 100, 255)) | |
| 59 | - val editorScheme = EditorColorsManager.getInstance().globalScheme | |
| 116 | + val buttonHoverBackground = namedColor("Button.default.hoverStartBackground") | |
| 117 | + ?: namedColor("Button.default.hoverBackground") | |
| 118 | + ?: namedColor("Button.default.startHoverBackground") | |
| 119 | + ?: slightChange(buttonBackground) | |
| 60 | 120 | |
| 61 | - val editorBackground = editorScheme.defaultBackground | |
| 62 | - val editorForeground = editorScheme.defaultForeground | |
| 121 | + val secondaryBackground = namedColor("Button.background") ?: background | |
| 122 | + val secondaryHoverBackground = namedColor("Button.hoverBackground") ?: slightChange(secondaryBackground) | |
| 63 | 123 | |
| 64 | - val actionHoverBackground = JBColor.namedColor("ActionButton.hoverBackground", Color(220, 220, 220)) | |
| 124 | + val badgeBackground = namedColor("Badge.background") | |
| 125 | + val badgeForeground = namedColor("Badge.foreground") | |
| 65 | 126 | |
| 66 | - val findMatchBackground = editorScheme.getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES)?.backgroundColor ?: Color(255, 221, 0) | |
| 127 | + val commandBackground = namedColor("CommandButton.background") ?: namedColor("ToolWindow.background") | |
| 128 | + val commandForeground = namedColor("CommandButton.foreground") ?: namedColor("ToolWindow.foreground") | |
| 67 | 129 | |
| 68 | - val theme = mapOf( | |
| 69 | - "--vscode-editor-foreground" to toHex(editorForeground), | |
| 70 | - "--vscode-editor-background" to toHex(editorBackground), | |
| 130 | + val inputBackground = namedColor("TextField.background") | |
| 131 | + val inputForeground = namedColor("TextField.foreground") | |
| 132 | + val inputPlaceholder = namedColor("TextField.inactiveForeground") | |
| 133 | + | |
| 134 | + val listHoverBackground = namedColor("List.hoverBackground") ?: slightChange(background) | |
| 135 | + val actionHoverBackground = namedColor("ActionButton.hoverBackground") ?: namedColor("Button.darcula.hoverBackground") | |
| 136 | + | |
| 137 | + val tableOddRow = namedColor("Table.hoverBackground") ?: namedColor("Table.stripeColor") | |
| 138 | + val listSelectionForeground = namedColor("List.selectionForeground") | |
| 71 | 139 | |
| 72 | - "--vscode-button-background" to toHex(buttonBackground), | |
| 73 | - "--vscode-button-foreground" to toHex(buttonForeground), | |
| 140 | + val description = namedColor("Label.disabledForeground") ?: namedColor("Label.infoForeground") | |
| 74 | 141 | |
| 75 | - "--vscode-list-activeSelectionBackground" to toHex(actionHoverBackground) + "50", | |
| 142 | + val mutedDescription = namedColor("Component.infoForeground") | |
| 143 | + ?: namedColor("ContextHelp.foreground") | |
| 144 | + ?: namedColor("TextField.placeholderForeground") | |
| 145 | + ?: namedColor("Label.disabledForeground") | |
| 146 | + ?: namedColor("ToolTip.foreground") | |
| 76 | 147 | |
| 77 | - "--vscode-quickInputList-focusForeground" to toHex(foreground), | |
| 78 | - "--vscode-quickInput-background" to toHex(inputBackground), | |
| 148 | + val link = namedColor("Link.activeForeground") | |
| 79 | 149 | |
| 80 | - "--vscode-badge-background" to toHex(badgeBackground), | |
| 81 | - "--vscode-badge-foreground" to toHex(badgeForeground), | |
| 150 | + val successColor = namedColor("ValidationSuccess.successColor") | |
| 151 | + ?: namedColor("Component.successForeground") | |
| 152 | + ?: namedColor("Label.successForeground") | |
| 153 | + val warningColor = namedColor("ValidationWarning.warningColor") | |
| 154 | + ?: EditorColorsManager.getInstance().globalScheme.getAttributes(CodeInsightColors.WARNINGS_ATTRIBUTES)?.effectColor | |
| 155 | + ?: namedColor("Component.warningForeground") | |
| 156 | + ?: namedColor("Label.warningForeground") | |
| 157 | + val errorColor = namedColor("ValidationError.errorColor") ?: namedColor("Component.errorForeground") ?: namedColor("Label.errorForeground") | |
| 82 | 158 | |
| 83 | - "--vscode-input-background" to toHex(inputBackground), | |
| 84 | - "--vscode-input-border" to toHex(border), | |
| 85 | - "--vscode-sideBar-background" to toHex(background), | |
| 86 | - "--vscode-sideBar-border" to toHex(border), | |
| 87 | - "--vscode-focusBorder" to toHex(focusBorder), | |
| 159 | + val accentColor = namedColor("Focus.defaultButtonBorderColor") ?: namedColor("Button.default.focusedBorderColor") ?: namedColor("Button.focusedBorderColor") | |
| 88 | 160 | |
| 89 | - "--vscode-commandCenter-activeBorder" to toHex(focusBorder), | |
| 90 | - "--vscode-commandCenter-inactiveBorder" to toHex(border), | |
| 161 | + val editorBackground = editorScheme.defaultBackground | |
| 162 | + val editorForeground = editorScheme.defaultForeground | |
| 91 | 163 | |
| 92 | - "--vscode-editor-findMatchHighlightBackground" to toHex(findMatchBackground) + "40" | |
| 93 | - ) | |
| 164 | + val findMatchBackground = editorScheme.getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES)?.backgroundColor | |
| 94 | 165 | |
| 166 | + val findMatchSelectedBackground = namedColor("SearchMatch.selectedBackground") ?: | |
| 167 | + editorScheme.getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES)?.backgroundColor | |
| 168 | + | |
| 169 | + // These should match the keys in GUI's theme.ts | |
| 170 | + val theme = mapOf( | |
| 171 | + "background" to background, | |
| 172 | + "foreground" to foreground, | |
| 173 | + "editor-background" to editorBackground, | |
| 174 | + "editor-foreground" to editorForeground, | |
| 175 | + "primary-background" to buttonBackground, | |
| 176 | + "primary-foreground" to buttonForeground, | |
| 177 | + "primary-hover" to buttonHoverBackground, | |
| 178 | + "secondary-background" to secondaryBackground, | |
| 179 | + "secondary-foreground" to foreground, | |
| 180 | + "secondary-hover" to secondaryHoverBackground, | |
| 181 | + "border" to border, | |
| 182 | + "border-focus" to focusBorder, | |
| 183 | + "command-background" to commandBackground, | |
| 184 | + "command-foreground" to commandForeground, | |
| 185 | + "command-border" to border, | |
| 186 | + "command-border-focus" to focusBorder, | |
| 187 | + "description" to description, | |
| 188 | + "description-muted" to mutedDescription, | |
| 189 | + "input-background" to inputBackground, | |
| 190 | + "input-foreground" to inputForeground, | |
| 191 | + "input-border" to border, | |
| 192 | + "input-placeholder" to inputPlaceholder, | |
| 193 | + "table-oddRow" to tableOddRow, | |
| 194 | + "badge-background" to badgeBackground, | |
| 195 | + "badge-foreground" to badgeForeground, | |
| 196 | + "success" to successColor, | |
| 197 | + "warning" to warningColor, | |
| 198 | + "error" to errorColor, | |
| 199 | + "link" to link, | |
| 200 | + "accent" to accentColor, | |
| 201 | + "find-match" to findMatchBackground, | |
| 202 | + "find-match-selected" to findMatchSelectedBackground, | |
| 203 | + "list-hover" to listHoverBackground, | |
| 204 | + "list-active" to actionHoverBackground, | |
| 205 | + "list-active-foreground" to listSelectionForeground | |
| 206 | + ).mapValues { toHex(it.value) } | |
| 95 | 207 | return theme |
| 96 | 208 | } catch (error: Error) { |
| 97 | 209 | return mapOf() |
| 98 | 210 | } |
| 99 | - | |
| 100 | 211 | } |
| 101 | 212 | } |
| No newline at the end of the file |
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +12 −3
| @@ -91,6 +91,15 @@ | ||
| 91 | 91 | respond(jsonData) |
| 92 | 92 | } |
| 93 | 93 | |
| 94 | + "showFile" -> { | |
| 95 | + val params = Gson().fromJson( | |
| 96 | + dataElement.toString(), | |
| 97 | + ShowFilePayload::class.java | |
| 98 | + ) | |
| 99 | + ide.openFile(params.filepath) | |
| 100 | + respond(null) | |
| 101 | + } | |
| 102 | + | |
| 94 | 103 | "getIdeSettings" -> { |
| 95 | 104 | val settings = ide.getIdeSettings() |
| 96 | 105 | respond(settings) |
| @@ -438,7 +447,7 @@ | ||
| 438 | 447 | "acceptDiff" -> { |
| 439 | 448 | val params = Gson().fromJson( |
| 440 | 449 | dataElement.toString(), |
| 441 | - AcceptDiffParams::class.java | |
| 450 | + AcceptOrRejectDiffPayload::class.java | |
| 442 | 451 | ) |
| 443 | 452 | val filepath = params.filepath; |
| 444 | 453 | |
| @@ -454,7 +463,7 @@ | ||
| 454 | 463 | "rejectDiff" -> { |
| 455 | 464 | val params = Gson().fromJson( |
| 456 | 465 | dataElement.toString(), |
| 457 | - RejectDiffParams::class.java | |
| 466 | + AcceptOrRejectDiffPayload::class.java | |
| 458 | 467 | ) |
| 459 | 468 | val filepath = params.filepath; |
| 460 | 469 | |
| @@ -493,7 +502,7 @@ | ||
| 493 | 502 | |
| 494 | 503 | fun sendHighlightedCode(edit: Boolean = false) { |
| 495 | 504 | val editor = EditorUtils.getEditor(project) |
| 496 | - val rif = editor?.getHighlightedCode() ?: return | |
| 505 | + val rif = editor?.getHighlightedRIF() ?: return | |
| 497 | 506 | |
| 498 | 507 | continuePluginService.sendToWebview( |
| 499 | 508 | "highlightedCode", |
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt +0 −1
| @@ -337,6 +337,5 @@ | ||
| 337 | 337 | private fun setClosed() { |
| 338 | 338 | sendUpdate(ApplyStateStatus.CLOSED) |
| 339 | 339 | resetState() |
| 340 | - onClose() | |
| 341 | 340 | } |
| 342 | 341 | } |
| No newline at the end of the file |
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/EditorUtils.kt +14 −11
| @@ -1,7 +1,5 @@ | ||
| 1 | 1 | package com.github.continuedev.continueintellijextension.editor |
| 2 | 2 | |
| 3 | -import com.github.continuedev.continueintellijextension.Position | |
| 4 | -import com.github.continuedev.continueintellijextension.Range | |
| 5 | 3 | import com.github.continuedev.continueintellijextension.utils.toUriOrNull |
| 6 | 4 | import com.intellij.openapi.application.ApplicationManager |
| 7 | 5 | import com.intellij.openapi.command.WriteCommandAction |
| @@ -72,28 +70,33 @@ | ||
| 72 | 70 | editor.scrollingModel.scrollTo(logicalPosition, ScrollType.CENTER_UP) |
| 73 | 71 | } |
| 74 | 72 | |
| 73 | + /** | |
| 74 | + * Remove the selected range in a thread-safe manner | |
| 75 | + */ | |
| 76 | + fun removeSelection() { | |
| 77 | + ApplicationManager.getApplication().invokeLater { | |
| 78 | + editor.selectionModel.removeSelection() | |
| 79 | + } | |
| 80 | + } | |
| 75 | 81 | |
| 76 | 82 | /** |
| 77 | 83 | * Extracts code ranges from the editor: (prefix, highlighted/selected text, suffix) |
| 78 | 84 | */ |
| 79 | - fun extractCodeRanges(): Triple<String, String, String> { | |
| 80 | - val rif = getHighlightedCode() | |
| 85 | + fun getHighlightedRangeTriplet(): Triple<String, String, String> { | |
| 86 | + val rif = getHighlightedRIF() | |
| 81 | 87 | |
| 82 | 88 | return if (rif == null) { |
| 83 | 89 | // If no highlight, use the whole document as highlighted |
| 84 | 90 | Triple("", editor.document.text, "") |
| 85 | 91 | } else { |
| 86 | 92 | // Use the RangeInFileWithContents to get absolute offsets |
| 87 | - val startOffset = rif.getStartOffset(editor.document) | |
| 88 | - val endOffset = rif.getEndOffset(editor.document) | |
| 93 | + val (startOffset, endOffset) = rif.offsets | |
| 94 | + | |
| 89 | 95 | val prefix = editor.document.getText(TextRange(0, startOffset)) |
| 90 | 96 | val highlighted = rif.contents |
| 91 | 97 | val suffix = editor.document.getText(TextRange(endOffset, editor.document.textLength)) |
| 92 | 98 | |
| 93 | - // Remove the selection after processing | |
| 94 | - ApplicationManager.getApplication().invokeLater { | |
| 95 | - editor.selectionModel.removeSelection() | |
| 96 | - } | |
| 99 | + removeSelection() | |
| 97 | 100 | |
| 98 | 101 | Triple(prefix, highlighted, suffix) |
| 99 | 102 | } |
| @@ -103,7 +106,7 @@ | ||
| 103 | 106 | * Gets the selected code from the current editor. |
| 104 | 107 | * Returns null if there is no selection. |
| 105 | 108 | */ |
| 106 | - fun getHighlightedCode(): RangeInFileWithContents? { | |
| 109 | + fun getHighlightedRIF(): RangeInFileWithContents? { | |
| 107 | 110 | return ApplicationManager.getApplication().runReadAction<RangeInFileWithContents?> { |
| 108 | 111 | val virtualFile = |
| 109 | 112 | FileDocumentManager.getInstance().getFile(editor.document) ?: return@runReadAction null |
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt +1 −740
| @@ -1,337 +1,11 @@ | ||
| 1 | 1 | package com.github.continuedev.continueintellijextension.editor |
| 2 | 2 | |
| 3 | -import com.github.continuedev.continueintellijextension.`continue`.GetTheme | |
| 4 | -import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings | |
| 5 | -import com.github.continuedev.continueintellijextension.services.ContinuePluginService | |
| 6 | -import com.github.continuedev.continueintellijextension.utils.castNestedOrNull | |
| 7 | -import com.github.continuedev.continueintellijextension.utils.getMetaKeyLabel | |
| 8 | -import com.github.continuedev.continueintellijextension.utils.getShiftKeyLabel | |
| 9 | -import com.intellij.openapi.Disposable | |
| 10 | 3 | import com.intellij.openapi.actionSystem.ActionUpdateThread |
| 11 | 4 | import com.intellij.openapi.actionSystem.AnAction |
| 12 | 5 | import com.intellij.openapi.actionSystem.AnActionEvent |
| 13 | 6 | import com.intellij.openapi.actionSystem.PlatformDataKeys |
| 14 | -import com.intellij.openapi.components.service | |
| 15 | -import com.intellij.openapi.editor.Editor | |
| 16 | -import com.intellij.openapi.editor.colors.EditorColorsManager | |
| 17 | -import com.intellij.openapi.editor.colors.EditorFontType | |
| 18 | -import com.intellij.openapi.editor.impl.EditorImpl | |
| 19 | 7 | import com.intellij.openapi.project.DumbAware |
| 20 | -import com.intellij.openapi.project.Project | |
| 21 | -import com.intellij.openapi.util.IconLoader | |
| 22 | -import com.intellij.openapi.util.Ref | |
| 23 | -import com.intellij.openapi.util.TextRange | |
| 24 | -import com.intellij.ui.JBColor | |
| 25 | -import com.intellij.util.ui.JBUI | |
| 26 | -import com.intellij.util.ui.UIUtil | |
| 27 | -import java.awt.* | |
| 28 | -import java.awt.event.* | |
| 29 | -import java.awt.geom.AffineTransform | |
| 30 | -import java.awt.geom.Path2D | |
| 31 | -import java.awt.geom.RoundRectangle2D | |
| 32 | -import javax.swing.* | |
| 33 | -import javax.swing.event.DocumentEvent | |
| 34 | -import javax.swing.event.DocumentListener | |
| 35 | -import javax.swing.event.ListDataListener | |
| 36 | -import javax.swing.plaf.basic.BasicComboBoxUI | |
| 37 | -import kotlin.math.max | |
| 38 | -import net.miginfocom.swing.MigLayout | |
| 39 | -import org.jdesktop.swingx.JXPanel | |
| 40 | -import org.jdesktop.swingx.JXTextArea | |
| 41 | 8 | |
| 42 | -const val MAIN_FONT_SIZE = 13 | |
| 43 | - | |
| 44 | -const val DOWN_ARROW = " ▾" | |
| 45 | - | |
| 46 | -fun makeTextArea(): JTextArea { | |
| 47 | - val textArea = | |
| 48 | - CustomTextArea(1, 40).apply { | |
| 49 | - lineWrap = true | |
| 50 | - wrapStyleWord = true | |
| 51 | - isOpaque = false | |
| 52 | - background = GetTheme().getSecondaryDark() | |
| 53 | - maximumSize = Dimension(400, Short.MAX_VALUE.toInt()) | |
| 54 | - margin = JBUI.insets(6, 8, 2, 4) | |
| 55 | - font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE) | |
| 56 | - preferredSize = Dimension(400, 75) | |
| 57 | - } | |
| 58 | - textArea.putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true) | |
| 59 | - return textArea | |
| 60 | -} | |
| 61 | - | |
| 62 | -fun makePanel( | |
| 63 | - project: Project, | |
| 64 | - customPanelRef: Ref<CustomPanel>, | |
| 65 | - textArea: JTextArea, | |
| 66 | - inlayRef: Ref<Disposable>, | |
| 67 | - comboBoxRef: Ref<JComboBox<String>>, | |
| 68 | - leftInset: Int, | |
| 69 | - modelTitles: List<String>, | |
| 70 | - onEnter: () -> Unit, | |
| 71 | - onCancel: () -> Unit, | |
| 72 | - onAccept: () -> Unit, | |
| 73 | - onReject: () -> Unit | |
| 74 | -): JPanel { | |
| 75 | - val topPanel = | |
| 76 | - ShadowPanel(MigLayout("wrap 1, insets 2 $leftInset 2 2, gap 0!")).apply { | |
| 77 | - background = JBColor(0x20888888, 0x20888888) | |
| 78 | - isOpaque = false | |
| 79 | - } | |
| 80 | - | |
| 81 | - val panel = | |
| 82 | - CustomPanel( | |
| 83 | - MigLayout("wrap 1, insets 4 10 0 2, gap 0!, fillx"), | |
| 84 | - project, | |
| 85 | - modelTitles, | |
| 86 | - comboBoxRef, | |
| 87 | - onEnter, | |
| 88 | - onCancel, | |
| 89 | - onAccept, | |
| 90 | - onReject, | |
| 91 | - textArea | |
| 92 | - ) | |
| 93 | - .apply { | |
| 94 | - val globalScheme = EditorColorsManager.getInstance().globalScheme | |
| 95 | - val defaultBackground = globalScheme.defaultBackground | |
| 96 | - background = defaultBackground | |
| 97 | - add(textArea, "grow, gap 0!, height 100%") | |
| 98 | - | |
| 99 | - putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true) | |
| 100 | - preferredSize = textArea.preferredSize | |
| 101 | - setup() | |
| 102 | - } | |
| 103 | - | |
| 104 | - customPanelRef.set(panel) | |
| 105 | - | |
| 106 | - textArea.addComponentListener( | |
| 107 | - object : ComponentAdapter() { | |
| 108 | - override fun componentResized(e: ComponentEvent?) { | |
| 109 | - panel.revalidate() | |
| 110 | - panel.repaint() | |
| 111 | - } | |
| 112 | - }) | |
| 113 | - | |
| 114 | - topPanel.add(panel, "grow, gap 0!") | |
| 115 | - | |
| 116 | - return topPanel | |
| 117 | -} | |
| 118 | - | |
| 119 | -fun openInlineEdit(project: Project?, editor: Editor) { | |
| 120 | - if (project == null) return | |
| 121 | - | |
| 122 | - // Don't open in terminal | |
| 123 | - if (EditorUtils(editor).isTerminal()) { | |
| 124 | - return | |
| 125 | - } | |
| 126 | - | |
| 127 | - val manager = EditorComponentInlaysManager.from(editor, true) | |
| 128 | - | |
| 129 | - // Get list of model titles | |
| 130 | - val continuePluginService = project.service<ContinuePluginService>() | |
| 131 | - val modelTitles = mutableListOf<String>() | |
| 132 | - | |
| 133 | - continuePluginService.coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response -> | |
| 134 | - val modelsByRole = | |
| 135 | - response.castNestedOrNull<Map<String, Any>>("content", "result", "config", "modelsByRole") ?: return@request | |
| 136 | - val role = if (modelsByRole.containsKey("edit")) "edit" else "chat" | |
| 137 | - modelsByRole.castNestedOrNull<List<*>>(role) | |
| 138 | - ?.mapNotNull { it.castNestedOrNull<String>("title") } | |
| 139 | - ?.let(modelTitles::addAll) | |
| 140 | - } | |
| 141 | - | |
| 142 | - // This is a hacky way to not complicate getting model titles with coroutines | |
| 143 | - // 1500 feels like way upper limit of "would be weird if panel showed up after that long" | |
| 144 | - // And should always allow enough time to load config | |
| 145 | - val maxWaitTime = 1500 | |
| 146 | - val startTime = System.currentTimeMillis() | |
| 147 | - while (modelTitles.isEmpty() && System.currentTimeMillis() - startTime < maxWaitTime) { | |
| 148 | - Thread.sleep(20) | |
| 149 | - } | |
| 150 | - | |
| 151 | - // Get highlighted range | |
| 152 | - val selectionModel = editor.selectionModel | |
| 153 | - val startOffset = selectionModel.selectionStart | |
| 154 | - val endOffset = selectionModel.selectionEnd | |
| 155 | - val startLineNumber = editor.document.getLineNumber(startOffset) | |
| 156 | - var endLineNumber = editor.document.getLineNumber(endOffset) | |
| 157 | - | |
| 158 | - // Doesn't seem to be any built-in methods to check for a line selection that contains trailing | |
| 159 | - // newlines. | |
| 160 | - // The only case this matters is when a user double-clicks to highlight a full line. Without this | |
| 161 | - // check. | |
| 162 | - // the highlighted range will continue to the following line. | |
| 163 | - val isSingleLineSelection = | |
| 164 | - endLineNumber > startLineNumber && | |
| 165 | - endLineNumber < editor.document.lineCount && | |
| 166 | - editor.document.getLineStartOffset(endLineNumber) == endOffset | |
| 167 | - | |
| 168 | - if (isSingleLineSelection) { | |
| 169 | - endLineNumber-- | |
| 170 | - } | |
| 171 | - | |
| 172 | - val prefix = editor.document.getText(TextRange(0, startOffset)) | |
| 173 | - val highlighted = editor.document.getText(TextRange(startOffset, endOffset)) | |
| 174 | - val suffix = editor.document.getText(TextRange(endOffset, editor.document.textLength)) | |
| 175 | - val lineNumber = if (startLineNumber == 0) 0 else max(0, startLineNumber - 1) | |
| 176 | - | |
| 177 | - // Un-highlight the selected text | |
| 178 | - selectionModel.removeSelection() | |
| 179 | - | |
| 180 | - // Get indentation width in pixels | |
| 181 | - val indentationLineNum = if (startLineNumber == 0) 0 else lineNumber + 1 | |
| 182 | - val lineStart = editor.document.getLineStartOffset(indentationLineNum) | |
| 183 | - val lineEnd = editor.document.getLineEndOffset(indentationLineNum) | |
| 184 | - val text = editor.document.getText(TextRange(lineStart, lineEnd)) | |
| 185 | - val indentation = text.takeWhile { it == ' ' }.length | |
| 186 | - val charWidth = | |
| 187 | - editor.contentComponent | |
| 188 | - .getFontMetrics(editor.colorsScheme.getFont(EditorFontType.PLAIN)) | |
| 189 | - .charWidth(' ') | |
| 190 | - val leftInset = indentation * charWidth * 2 / 3 | |
| 191 | - | |
| 192 | - val inlayRef = Ref<Disposable>() | |
| 193 | - val customPanelRef = Ref<CustomPanel>() | |
| 194 | - | |
| 195 | - // Create text area, attach key listener | |
| 196 | - val textArea = makeTextArea() | |
| 197 | - | |
| 198 | - // Create diff stream handler | |
| 199 | - val diffStreamHandler = | |
| 200 | - DiffStreamHandler( | |
| 201 | - project, | |
| 202 | - editor, | |
| 203 | - startLineNumber, | |
| 204 | - endLineNumber, | |
| 205 | - { | |
| 206 | - inlayRef.get()?.dispose() | |
| 207 | - }, | |
| 208 | - { | |
| 209 | - textArea.document.insertString(textArea.caretPosition, ", ", null) | |
| 210 | - textArea.requestFocus() | |
| 211 | - customPanelRef.get().finish() | |
| 212 | - }, | |
| 213 | - null, | |
| 214 | - null | |
| 215 | - ) | |
| 216 | - | |
| 217 | - val diffStreamService = project.service<DiffStreamService>() | |
| 218 | - diffStreamService.register(diffStreamHandler, editor) | |
| 219 | - | |
| 220 | - val comboBoxRef = Ref<JComboBox<String>>() | |
| 221 | - | |
| 222 | - fun onEnter() { | |
| 223 | - val selectedModelStrippedOfCaret = (comboBoxRef.get().selectedItem as String).removeSuffix(DOWN_ARROW) | |
| 224 | - customPanelRef.get().enter() | |
| 225 | - diffStreamHandler.streamDiffLinesToEditor( | |
| 226 | - textArea.text, prefix, highlighted, suffix, selectedModelStrippedOfCaret, true | |
| 227 | - ) | |
| 228 | - } | |
| 229 | - | |
| 230 | - val panel = | |
| 231 | - makePanel( | |
| 232 | - project, | |
| 233 | - customPanelRef, | |
| 234 | - textArea, | |
| 235 | - inlayRef, | |
| 236 | - comboBoxRef, | |
| 237 | - leftInset, | |
| 238 | - modelTitles, | |
| 239 | - { onEnter() }, | |
| 240 | - { | |
| 241 | - diffStreamService.reject(editor) | |
| 242 | - selectionModel.setSelection(startOffset, endOffset) | |
| 243 | - }, | |
| 244 | - { | |
| 245 | - diffStreamService.accept(editor) | |
| 246 | - inlayRef.get().dispose() | |
| 247 | - }, | |
| 248 | - { | |
| 249 | - diffStreamService.reject(editor) | |
| 250 | - inlayRef.get().dispose() | |
| 251 | - }) | |
| 252 | - | |
| 253 | - val inlay = manager.insert(startLineNumber, panel, true) | |
| 254 | - | |
| 255 | - panel.revalidate() | |
| 256 | - inlayRef.set(inlay) | |
| 257 | - val viewport = (editor as? EditorImpl)?.scrollPane?.viewport | |
| 258 | - viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED)) | |
| 259 | - | |
| 260 | - // Add key listener to text area | |
| 261 | - textArea.addKeyListener( | |
| 262 | - object : KeyAdapter() { | |
| 263 | - override fun keyTyped(e: KeyEvent) { | |
| 264 | - if (customPanelRef.get().isFinished) { | |
| 265 | - customPanelRef.get().setup() | |
| 266 | - } | |
| 267 | - } | |
| 268 | - | |
| 269 | - override fun keyPressed(e: KeyEvent) { | |
| 270 | - when (e.keyCode) { | |
| 271 | - KeyEvent.VK_ESCAPE -> { | |
| 272 | - diffStreamService.reject(editor) | |
| 273 | - selectionModel.setSelection(startOffset, endOffset) | |
| 274 | - } | |
| 275 | - | |
| 276 | - KeyEvent.VK_ENTER -> { | |
| 277 | - when (e.modifiersEx) { | |
| 278 | - KeyEvent.SHIFT_DOWN_MASK -> { | |
| 279 | - textArea.document.insertString(textArea.caretPosition, "\n", null) | |
| 280 | - } | |
| 281 | - | |
| 282 | - 0 -> { | |
| 283 | - onEnter() | |
| 284 | - e.consume() | |
| 285 | - } | |
| 286 | - } | |
| 287 | - } | |
| 288 | - } | |
| 289 | - } | |
| 290 | - | |
| 291 | - // We need this because backspace/delete is not registering properly on keyPressed for an | |
| 292 | - // unknown reason | |
| 293 | - override fun keyReleased(e: KeyEvent) { | |
| 294 | - if (e.keyCode == KeyEvent.VK_BACK_SPACE || e.keyCode == KeyEvent.VK_DELETE) { | |
| 295 | - if (customPanelRef.get().isFinished) { | |
| 296 | - customPanelRef.get().setup() | |
| 297 | - } | |
| 298 | - } | |
| 299 | - } | |
| 300 | - }) | |
| 301 | - | |
| 302 | - // Listen for changes to textarea line count | |
| 303 | - textArea.document.addDocumentListener( | |
| 304 | - object : DocumentListener { | |
| 305 | - private var lastNumLines: Int = 0 | |
| 306 | - | |
| 307 | - private fun updateSize() { | |
| 308 | - val numLines = textArea.text.lines().size | |
| 309 | - if (numLines != lastNumLines) { | |
| 310 | - lastNumLines = numLines | |
| 311 | - viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED)) | |
| 312 | - } | |
| 313 | - } | |
| 314 | - | |
| 315 | - override fun insertUpdate(e: DocumentEvent?) { | |
| 316 | - updateSize() | |
| 317 | - } | |
| 318 | - | |
| 319 | - override fun removeUpdate(e: DocumentEvent?) { | |
| 320 | - updateSize() | |
| 321 | - } | |
| 322 | - | |
| 323 | - override fun changedUpdate(e: DocumentEvent?) { | |
| 324 | - updateSize() | |
| 325 | - } | |
| 326 | - }) | |
| 327 | - | |
| 328 | - textArea.requestFocus() | |
| 329 | -} | |
| 330 | - | |
| 331 | -/** | |
| 332 | - * Adapted from | |
| 333 | - * https://github.com/cursive-ide/component-inlay-example/blob/master/src/main/kotlin/inlays/InlineEditAction.kt | |
| 334 | - */ | |
| 335 | 9 | class InlineEditAction : AnAction(), DumbAware { |
| 336 | 10 | override fun update(e: AnActionEvent) { |
| 337 | 11 | e.presentation.isEnabled = true |
| @@ -347,417 +21,4 @@ | ||
| 347 | 21 | val project = e.getData(PlatformDataKeys.PROJECT) ?: return |
| 348 | 22 | openInlineEdit(project, editor) |
| 349 | 23 | } |
| 350 | -} | |
| 351 | - | |
| 352 | -class CustomPanel( | |
| 353 | - layout: MigLayout, | |
| 354 | - project: Project, | |
| 355 | - modelTitles: List<String>, | |
| 356 | - comboBoxRef: Ref<JComboBox<String>>, | |
| 357 | - private val onEnter: () -> Unit, | |
| 358 | - private val onCancel: () -> Unit, | |
| 359 | - private val onAccept: () -> Unit, | |
| 360 | - private val onReject: () -> Unit, | |
| 361 | - private val textArea: JTextArea | |
| 362 | -) : JPanel(layout) { | |
| 363 | - private val shadowSize = 5 | |
| 364 | - private val cornerRadius = 8 | |
| 365 | - private val shadowColor = Color(0, 0, 0, 40) // Lighter shadow | |
| 366 | - private val borderColor = Color(128, 128, 128, 128) | |
| 367 | - private val borderThickness = 1 | |
| 368 | - private val triangleSize = 6 | |
| 369 | - private val rightMargin = 3.0 | |
| 370 | - private val closeButton: JComponent = createCloseButton() | |
| 371 | - private val originalTextColor: Color = textArea.foreground | |
| 372 | - private val greyTextColor: Color = Color(128, 128, 128, 200) | |
| 373 | - var isFinished = false | |
| 374 | - | |
| 375 | - init { | |
| 376 | - isOpaque = false | |
| 377 | - add(closeButton, "pos 100%-33 0 -3 3, w 20!, h 20!") | |
| 378 | - } | |
| 379 | - | |
| 380 | - private fun createCloseButton(): JComponent { | |
| 381 | - val closeIcon = IconLoader.getIcon("/icons/close.svg", javaClass) | |
| 382 | - return JLabel(closeIcon).apply { | |
| 383 | - background = Color(0, 0, 0, 0) | |
| 384 | - border = JBUI.Borders.empty(2, 6, 2, 0) | |
| 385 | - toolTipText = "`esc` to cancel" | |
| 386 | - isOpaque = false | |
| 387 | - addMouseListener( | |
| 388 | - object : MouseAdapter() { | |
| 389 | - override fun mouseEntered(e: MouseEvent) { | |
| 390 | - cursor = Cursor(Cursor.HAND_CURSOR) | |
| 391 | - } | |
| 392 | - | |
| 393 | - override fun mouseExited(e: MouseEvent) { | |
| 394 | - cursor = Cursor.getDefaultCursor() | |
| 395 | - } | |
| 396 | - | |
| 397 | - override fun mouseClicked(e: MouseEvent) { | |
| 398 | - onCancel() | |
| 399 | - } | |
| 400 | - }) | |
| 401 | - } | |
| 402 | - } | |
| 403 | - | |
| 404 | - private val subPanelA: JPanel = | |
| 405 | - JPanel(MigLayout("insets 0, fillx")).apply { | |
| 406 | - val globalScheme = EditorColorsManager.getInstance().globalScheme | |
| 407 | - val defaultBackground = globalScheme.defaultBackground | |
| 408 | - val continueSettingsService = service<ContinueExtensionSettings>() | |
| 409 | - val dropdown = | |
| 410 | - JComboBox(modelTitles.toTypedArray()).apply { | |
| 411 | - setUI(TransparentArrowButtonUI()) | |
| 412 | - isEditable = true | |
| 413 | - background = defaultBackground | |
| 414 | - foreground = Color(128, 128, 128, 200) | |
| 415 | - font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 12) | |
| 416 | - border = JBUI.Borders.empty(8) | |
| 417 | - isOpaque = false | |
| 418 | - isEditable = false | |
| 419 | - cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) | |
| 420 | - preferredSize = Dimension(200, 30) | |
| 421 | - | |
| 422 | - renderer = object : DefaultListCellRenderer() { | |
| 423 | - override fun getListCellRendererComponent( | |
| 424 | - list: JList<*>?, | |
| 425 | - value: Any?, | |
| 426 | - index: Int, | |
| 427 | - isSelected: Boolean, | |
| 428 | - cellHasFocus: Boolean | |
| 429 | - ): Component { | |
| 430 | - val component = | |
| 431 | - super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus) | |
| 432 | - if (component is JLabel) { | |
| 433 | - component.border = JBUI.Borders.empty(4, 6) | |
| 434 | - } | |
| 435 | - return component | |
| 436 | - } | |
| 437 | - }.apply { | |
| 438 | - horizontalAlignment = SwingConstants.LEFT | |
| 439 | - } | |
| 440 | - | |
| 441 | - selectedIndex = | |
| 442 | - if (itemCount == 0) -1 else continueSettingsService.continueState.lastSelectedInlineEditModel?.let { | |
| 443 | - if (modelTitles.isEmpty()) -1 | |
| 444 | - else { | |
| 445 | - val index = modelTitles.indexOf(it) | |
| 446 | - if (index != -1) index else 0 | |
| 447 | - } | |
| 448 | - } ?: 0 | |
| 449 | - | |
| 450 | - addActionListener { | |
| 451 | - continueSettingsService.continueState.lastSelectedInlineEditModel = | |
| 452 | - (selectedItem as String).removeSuffix(DOWN_ARROW) | |
| 453 | - } | |
| 454 | - } | |
| 455 | - | |
| 456 | - comboBoxRef.set(dropdown) | |
| 457 | - | |
| 458 | - val rightButton = | |
| 459 | - CustomButton("⏎ Enter") { onEnter() } | |
| 460 | - .apply { | |
| 461 | - background = globalScheme.defaultForeground | |
| 462 | - foreground = globalScheme.defaultBackground | |
| 463 | - border = JBUI.Borders.empty(2, 6) | |
| 464 | - } | |
| 465 | - | |
| 466 | - val rightPanel = JPanel(MigLayout("insets 0, fillx")).apply { | |
| 467 | - isOpaque = false | |
| 468 | - add(rightButton, "align right") | |
| 469 | - } | |
| 470 | - | |
| 471 | - border = JBUI.Borders.empty(0, 0, 16, 12) | |
| 472 | - isOpaque = false | |
| 473 | - | |
| 474 | - add(dropdown, "align left") | |
| 475 | - add(rightPanel, "align right") | |
| 476 | - | |
| 477 | - cursor = Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR) | |
| 478 | - } | |
| 479 | - | |
| 480 | - private val subPanelB: JPanel = | |
| 481 | - JPanel(BorderLayout()).apply { | |
| 482 | - isOpaque = false | |
| 483 | - | |
| 484 | - val progressBar = JProgressBar().apply { isIndeterminate = true } | |
| 485 | - | |
| 486 | - add(progressBar, BorderLayout.CENTER) | |
| 487 | - border = JBUI.Borders.empty(0, 0, 16, 12) | |
| 488 | - } | |
| 489 | - | |
| 490 | - private val subPanelC: JPanel = | |
| 491 | - JPanel(MigLayout("insets 0, fillx")).apply { | |
| 492 | - val leftLabel = | |
| 493 | - JLabel("Type to re-prompt").apply { | |
| 494 | - foreground = Color(156, 163, 175) // text-gray-400 | |
| 495 | - font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11) | |
| 496 | - border = JBUI.Borders.emptyLeft(4) | |
| 497 | - } | |
| 498 | - | |
| 499 | - val leftButton = | |
| 500 | - CustomButton("Reject All (${getMetaKeyLabel()}${getShiftKeyLabel()}⌫)") { onReject() } | |
| 501 | - .apply { | |
| 502 | - background = JBColor(0x30FF0000, 0x30FF0000) | |
| 503 | - } | |
| 504 | - | |
| 505 | - val rightButton = | |
| 506 | - CustomButton("Accept All (${getMetaKeyLabel()}${getShiftKeyLabel()}⏎)") { onAccept() } | |
| 507 | - .apply { | |
| 508 | - background = JBColor(0x3000FF00, 0x3000FF00) | |
| 509 | - } | |
| 510 | - | |
| 511 | - val rightPanel = | |
| 512 | - JPanel(MigLayout("insets 0, fillx")).apply { | |
| 513 | - isOpaque = false | |
| 514 | - add(leftButton, "align right") | |
| 515 | - add(rightButton, "align right") | |
| 516 | - border = JBUI.Borders.empty() | |
| 517 | - } | |
| 518 | - | |
| 519 | - add(leftLabel, "align left") | |
| 520 | - add(rightPanel, "align right") | |
| 521 | - border = JBUI.Borders.empty(0, 0, 16, 12) | |
| 522 | - isOpaque = false | |
| 523 | - } | |
| 524 | - | |
| 525 | - fun setup() { | |
| 526 | - remove(subPanelB) | |
| 527 | - remove(subPanelC) | |
| 528 | - add(subPanelA, "grow, gap 0!") | |
| 529 | - isFinished = false | |
| 530 | - revalidate() | |
| 531 | - repaint() | |
| 532 | - textArea.foreground = originalTextColor | |
| 533 | - } | |
| 534 | - | |
| 535 | - fun enter() { | |
| 536 | - remove(subPanelA) | |
| 537 | - remove(subPanelC) | |
| 538 | - add(subPanelB, "grow, gap 0!") | |
| 539 | - revalidate() | |
| 540 | - repaint() | |
| 541 | - } | |
| 542 | - | |
| 543 | - fun finish() { | |
| 544 | - remove(subPanelB) | |
| 545 | - add(subPanelC, "grow, gap 0!") | |
| 546 | - revalidate() | |
| 547 | - repaint() | |
| 548 | - isFinished = true | |
| 549 | - textArea.foreground = greyTextColor | |
| 550 | - } | |
| 551 | - | |
| 552 | - override fun paintComponent(g: Graphics) { | |
| 553 | - super.paintComponent(g) | |
| 554 | - | |
| 555 | - val g2 = g as Graphics2D | |
| 556 | - g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) | |
| 557 | - | |
| 558 | - val w = width - shadowSize | |
| 559 | - val h = height - shadowSize | |
| 560 | - | |
| 561 | - // Create the shape for the tooltip/triangle | |
| 562 | - val shape = Path2D.Double() | |
| 563 | - shape.moveTo(borderThickness / 2.0, cornerRadius.toDouble()) | |
| 564 | - shape.quadTo( | |
| 565 | - borderThickness / 2.0, | |
| 566 | - borderThickness / 2.0, | |
| 567 | - cornerRadius.toDouble(), | |
| 568 | - borderThickness / 2.0 | |
| 569 | - ) | |
| 570 | - shape.lineTo(w - cornerRadius.toDouble() - rightMargin, borderThickness / 2.0) | |
| 571 | - shape.quadTo( | |
| 572 | - w - borderThickness / 2.0 - rightMargin, | |
| 573 | - borderThickness / 2.0, | |
| 574 | - w - borderThickness / 2.0 - rightMargin, | |
| 575 | - cornerRadius.toDouble() | |
| 576 | - ) | |
| 577 | - shape.lineTo( | |
| 578 | - w - borderThickness / 2.0 - rightMargin, h - cornerRadius - triangleSize.toDouble() | |
| 579 | - ) | |
| 580 | - shape.quadTo( | |
| 581 | - w - borderThickness / 2.0 - rightMargin, | |
| 582 | - h - triangleSize.toDouble(), | |
| 583 | - w - cornerRadius.toDouble() - rightMargin, | |
| 584 | - h - triangleSize.toDouble() | |
| 585 | - ) | |
| 586 | - shape.lineTo(triangleSize.toDouble(), h - triangleSize.toDouble()) | |
| 587 | - shape.lineTo(borderThickness / 2.0, h.toDouble()) | |
| 588 | - shape.lineTo(borderThickness / 2.0, cornerRadius.toDouble()) | |
| 589 | - | |
| 590 | - // Draw shadow | |
| 591 | - g2.color = shadowColor | |
| 592 | - g2.fill( | |
| 593 | - shape.createTransformedShape( | |
| 594 | - AffineTransform.getTranslateInstance(shadowSize.toDouble(), shadowSize.toDouble()) | |
| 595 | - ) | |
| 596 | - ) | |
| 597 | - | |
| 598 | - // Draw main shape | |
| 599 | - g2.color = background | |
| 600 | - g2.fill(shape) | |
| 601 | - | |
| 602 | - // Draw border | |
| 603 | - g2.color = borderColor | |
| 604 | - g2.stroke = BasicStroke(borderThickness.toFloat()) | |
| 605 | - g2.draw(shape) | |
| 606 | - } | |
| 607 | -} | |
| 608 | - | |
| 609 | -class CustomButton(text: String, onClick: () -> Unit) : JLabel(text, CENTER) { | |
| 610 | - private var isHovered = false | |
| 611 | - | |
| 612 | - init { | |
| 613 | - isOpaque = false | |
| 614 | - cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) | |
| 615 | - addMouseListener( | |
| 616 | - object : MouseAdapter() { | |
| 617 | - override fun mouseEntered(e: MouseEvent?) { | |
| 618 | - isHovered = true | |
| 619 | - repaint() | |
| 620 | - } | |
| 621 | - | |
| 622 | - override fun mouseExited(e: MouseEvent?) { | |
| 623 | - isHovered = false | |
| 624 | - repaint() | |
| 625 | - } | |
| 626 | - | |
| 627 | - override fun mouseClicked(e: MouseEvent?) { | |
| 628 | - onClick() | |
| 629 | - } | |
| 630 | - }) | |
| 631 | - | |
| 632 | - font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11) | |
| 633 | - border = JBUI.Borders.empty(2, 6) | |
| 634 | - } | |
| 635 | - | |
| 636 | - override fun paintComponent(g: Graphics) { | |
| 637 | - val g2 = g as Graphics2D | |
| 638 | - g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) | |
| 639 | - | |
| 640 | - val cornerRadius = 8 | |
| 641 | - val rect = Rectangle(0, 0, width, height) | |
| 642 | - val roundRect = | |
| 643 | - RoundRectangle2D.Float( | |
| 644 | - rect.x.toFloat(), | |
| 645 | - rect.y.toFloat(), | |
| 646 | - rect.width.toFloat(), | |
| 647 | - rect.height.toFloat(), | |
| 648 | - cornerRadius.toFloat(), | |
| 649 | - cornerRadius.toFloat() | |
| 650 | - ) | |
| 651 | - g2.color = background | |
| 652 | - g2.fill(roundRect) | |
| 653 | - g2.color = foreground | |
| 654 | - g2.drawString( | |
| 655 | - text, | |
| 656 | - (width / 2 - g.fontMetrics.stringWidth(text) / 2).toFloat(), | |
| 657 | - (height / 2 + g.fontMetrics.ascent / 2).toFloat() | |
| 658 | - ) | |
| 659 | - } | |
| 660 | -} | |
| 661 | - | |
| 662 | -class CustomTextArea(rows: Int, columns: Int) : JXTextArea("") { | |
| 663 | - init { | |
| 664 | - setRows(rows) | |
| 665 | - setColumns(columns) | |
| 666 | - } | |
| 667 | - | |
| 668 | - override fun paintComponent(g: Graphics) { | |
| 669 | - // Draw placeholder | |
| 670 | - if (text.isEmpty()) { | |
| 671 | - g.color = Color(128, 128, 128, 255) | |
| 672 | - g.font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE) | |
| 673 | - g.drawString("Enter instructions...", 8, 20) | |
| 674 | - } | |
| 675 | - | |
| 676 | - super.paintComponent(g) | |
| 677 | - } | |
| 678 | -} | |
| 679 | - | |
| 680 | -class ShadowPanel(layout: LayoutManager) : JXPanel(layout) { | |
| 681 | - override fun getPreferredSize(): Dimension { | |
| 682 | - val prefSize = super.getPreferredSize() | |
| 683 | - val insets = getInsets() | |
| 684 | - prefSize.width += insets.left + insets.right | |
| 685 | - prefSize.height += insets.top + insets.bottom | |
| 686 | - return prefSize | |
| 687 | - } | |
| 688 | - | |
| 689 | - override fun paintComponent(g: Graphics) { | |
| 690 | - super.paintComponent(g) | |
| 691 | - } | |
| 692 | -} | |
| 693 | - | |
| 694 | -class TransparentArrowButtonUI : BasicComboBoxUI() { | |
| 695 | - override fun createArrowButton() = | |
| 696 | - JButton().apply { | |
| 697 | - isVisible = false | |
| 698 | - preferredSize = Dimension(0, 0) | |
| 699 | - } | |
| 700 | - | |
| 701 | - override fun getInsets(): Insets { | |
| 702 | - return JBUI.insetsLeft(6) | |
| 703 | - } | |
| 704 | - | |
| 705 | - override fun installUI(c: JComponent?) { | |
| 706 | - super.installUI(c) | |
| 707 | - comboBox.isOpaque = false | |
| 708 | - val globalScheme = EditorColorsManager.getInstance().globalScheme | |
| 709 | - val defaultBackground = globalScheme.defaultBackground | |
| 710 | - comboBox.background = defaultBackground | |
| 711 | - | |
| 712 | - // Modify the ComboBoxModel to include the down symbol | |
| 713 | - val originalModel = comboBox.model | |
| 714 | - comboBox.model = | |
| 715 | - object : ComboBoxModel<Any> { | |
| 716 | - override fun getSize(): Int = originalModel.size | |
| 717 | - | |
| 718 | - override fun getElementAt(index: Int): Any? = originalModel.getElementAt(index) | |
| 719 | - | |
| 720 | - override fun setSelectedItem(anItem: Any?) { | |
| 721 | - originalModel.selectedItem = anItem | |
| 722 | - } | |
| 723 | - | |
| 724 | - override fun getSelectedItem(): Any? { | |
| 725 | - val item = originalModel.selectedItem | |
| 726 | - return "$item$DOWN_ARROW" | |
| 727 | - } | |
| 728 | - | |
| 729 | - override fun addListDataListener(l: ListDataListener?) { | |
| 730 | - originalModel.addListDataListener(l) | |
| 731 | - } | |
| 732 | - | |
| 733 | - override fun removeListDataListener(l: ListDataListener?) { | |
| 734 | - originalModel.removeListDataListener(l) | |
| 735 | - } | |
| 736 | - } | |
| 737 | - } | |
| 738 | - | |
| 739 | - override fun paintCurrentValueBackground(g: Graphics, bounds: Rectangle, hasFocus: Boolean) { | |
| 740 | - // Do nothing to prevent painting the background | |
| 741 | - } | |
| 742 | - | |
| 743 | - override fun paintCurrentValue(g: Graphics, bounds: Rectangle, hasFocus: Boolean) { | |
| 744 | - val renderer = comboBox.renderer | |
| 745 | - val item = comboBox.selectedItem | |
| 746 | - | |
| 747 | - if (item != null) { | |
| 748 | - val c = renderer.getListCellRendererComponent(listBox, item, -1, false, false) | |
| 749 | - c.font = comboBox.font | |
| 750 | - c.foreground = Color(156, 163, 175) // text-gray-400 | |
| 751 | - c.background = comboBox.background | |
| 752 | - | |
| 753 | - if (c is JComponent) { | |
| 754 | - c.isOpaque = false | |
| 755 | - } | |
| 756 | - | |
| 757 | - val currentValuePane = currentValuePane | |
| 758 | - currentValuePane.paintComponent( | |
| 759 | - g, c, comboBox, bounds.x, bounds.y, bounds.width, bounds.height, true | |
| 760 | - ) | |
| 761 | - } | |
| 762 | - } | |
| 763 | -} | |
| 24 | +} | |
| No newline at the end of the file |
added extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditPanel.kt +746 −0
| @@ -0,0 +1,746 @@ | ||
| 1 | +package com.github.continuedev.continueintellijextension.editor | |
| 2 | + | |
| 3 | +import com.github.continuedev.continueintellijextension.`continue`.GetTheme | |
| 4 | +import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings | |
| 5 | +import com.github.continuedev.continueintellijextension.services.ContinuePluginService | |
| 6 | +import com.github.continuedev.continueintellijextension.utils.castNestedOrNull | |
| 7 | +import com.github.continuedev.continueintellijextension.utils.getMetaKeyLabel | |
| 8 | +import com.github.continuedev.continueintellijextension.utils.getShiftKeyLabel | |
| 9 | +import com.intellij.openapi.Disposable | |
| 10 | +import com.intellij.openapi.components.service | |
| 11 | +import com.intellij.openapi.editor.Editor | |
| 12 | +import com.intellij.openapi.editor.colors.EditorColorsManager | |
| 13 | +import com.intellij.openapi.editor.colors.EditorFontType | |
| 14 | +import com.intellij.openapi.editor.impl.EditorImpl | |
| 15 | +import com.intellij.openapi.project.Project | |
| 16 | +import com.intellij.openapi.util.IconLoader | |
| 17 | +import com.intellij.openapi.util.Ref | |
| 18 | +import com.intellij.openapi.util.TextRange | |
| 19 | +import com.intellij.ui.JBColor | |
| 20 | +import com.intellij.util.ui.JBUI | |
| 21 | +import com.intellij.util.ui.UIUtil | |
| 22 | +import java.awt.* | |
| 23 | +import java.awt.event.* | |
| 24 | +import java.awt.geom.AffineTransform | |
| 25 | +import java.awt.geom.Path2D | |
| 26 | +import java.awt.geom.RoundRectangle2D | |
| 27 | +import javax.swing.* | |
| 28 | +import javax.swing.event.DocumentEvent | |
| 29 | +import javax.swing.event.DocumentListener | |
| 30 | +import javax.swing.event.ListDataListener | |
| 31 | +import javax.swing.plaf.basic.BasicComboBoxUI | |
| 32 | +import kotlin.math.max | |
| 33 | +import net.miginfocom.swing.MigLayout | |
| 34 | +import org.jdesktop.swingx.JXPanel | |
| 35 | +import org.jdesktop.swingx.JXTextArea | |
| 36 | + | |
| 37 | +const val MAIN_FONT_SIZE = 13 | |
| 38 | +const val DOWN_ARROW = " ▾" | |
| 39 | +const val MAX_MODEL_WAIT_TIME = 1500 | |
| 40 | + | |
| 41 | +/** | |
| 42 | + * Fetches and combines available model titles from both "edit" and "chat" roles. | |
| 43 | + * Edit models are prioritized and appear first in the returned list. | |
| 44 | + * Handles duplicate models by only including them once (prioritizing edit role). | |
| 45 | + * | |
| 46 | + * @param continuePluginService The service used to fetch config information | |
| 47 | + * @return List of model titles with edit models first, duplicates removed | |
| 48 | + * @throws No exceptions, but will return empty list if request fails or times out after 1.5 seconds | |
| 49 | + */ | |
| 50 | +fun getModelTitles(continuePluginService: ContinuePluginService): List<String> { | |
| 51 | + val modelTitles = mutableListOf<String>() | |
| 52 | + | |
| 53 | + continuePluginService.coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response -> | |
| 54 | + val modelsByRole = | |
| 55 | + response.castNestedOrNull<Map<String, Any>>("content", "result", "config", "modelsByRole") ?: return@request | |
| 56 | + | |
| 57 | + // Get edit models first | |
| 58 | + val editModels = modelsByRole.castNestedOrNull<List<*>>("edit") | |
| 59 | + ?.mapNotNull { it.castNestedOrNull<String>("title") } ?: emptyList() | |
| 60 | + | |
| 61 | + // Then get chat models | |
| 62 | + val chatModels = modelsByRole.castNestedOrNull<List<*>>("chat") | |
| 63 | + ?.mapNotNull { it.castNestedOrNull<String>("title") } ?: emptyList() | |
| 64 | + | |
| 65 | + // Add edit models first, then chat models (avoiding duplicates) | |
| 66 | + modelTitles.addAll(editModels) | |
| 67 | + modelTitles.addAll(chatModels.filter { it !in editModels }) | |
| 68 | + } | |
| 69 | + | |
| 70 | + val startTime = System.currentTimeMillis() | |
| 71 | + while (modelTitles.isEmpty() && System.currentTimeMillis() - startTime < MAX_MODEL_WAIT_TIME) { | |
| 72 | + Thread.sleep(20) | |
| 73 | + } | |
| 74 | + | |
| 75 | + return modelTitles | |
| 76 | +} | |
| 77 | + | |
| 78 | +fun makeTextArea(): JTextArea { | |
| 79 | + val textArea = | |
| 80 | + CustomTextArea(1, 40).apply { | |
| 81 | + lineWrap = true | |
| 82 | + wrapStyleWord = true | |
| 83 | + isOpaque = false | |
| 84 | + background = GetTheme().getSecondaryDark() | |
| 85 | + maximumSize = Dimension(400, Short.MAX_VALUE.toInt()) | |
| 86 | + margin = JBUI.insets(6, 8, 2, 4) | |
| 87 | + font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE) | |
| 88 | + preferredSize = Dimension(400, 75) | |
| 89 | + } | |
| 90 | + textArea.putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true) | |
| 91 | + return textArea | |
| 92 | +} | |
| 93 | + | |
| 94 | +fun makePanel( | |
| 95 | + project: Project, | |
| 96 | + customPanelRef: Ref<CustomPanel>, | |
| 97 | + textArea: JTextArea, | |
| 98 | + inlayRef: Ref<Disposable>, | |
| 99 | + comboBoxRef: Ref<JComboBox<String>>, | |
| 100 | + leftInset: Int, | |
| 101 | + modelTitles: List<String>, | |
| 102 | + onEnter: () -> Unit, | |
| 103 | + onCancel: () -> Unit, | |
| 104 | + onAccept: () -> Unit, | |
| 105 | + onReject: () -> Unit | |
| 106 | +): JPanel { | |
| 107 | + val topPanel = | |
| 108 | + ShadowPanel(MigLayout("wrap 1, insets 2 $leftInset 2 2, gap 0!")).apply { | |
| 109 | + background = JBColor(0x20888888, 0x20888888) | |
| 110 | + isOpaque = false | |
| 111 | + } | |
| 112 | + | |
| 113 | + val panel = | |
| 114 | + CustomPanel( | |
| 115 | + MigLayout("wrap 1, insets 4 10 0 2, gap 0!, fillx"), | |
| 116 | + project, | |
| 117 | + modelTitles, | |
| 118 | + comboBoxRef, | |
| 119 | + onEnter, | |
| 120 | + onCancel, | |
| 121 | + onAccept, | |
| 122 | + onReject, | |
| 123 | + textArea | |
| 124 | + ) | |
| 125 | + .apply { | |
| 126 | + val globalScheme = EditorColorsManager.getInstance().globalScheme | |
| 127 | + val defaultBackground = globalScheme.defaultBackground | |
| 128 | + background = defaultBackground | |
| 129 | + add(textArea, "grow, gap 0!, height 100%") | |
| 130 | + | |
| 131 | + putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true) | |
| 132 | + preferredSize = textArea.preferredSize | |
| 133 | + setup() | |
| 134 | + } | |
| 135 | + | |
| 136 | + customPanelRef.set(panel) | |
| 137 | + | |
| 138 | + textArea.addComponentListener( | |
| 139 | + object : ComponentAdapter() { | |
| 140 | + override fun componentResized(e: ComponentEvent?) { | |
| 141 | + panel.revalidate() | |
| 142 | + panel.repaint() | |
| 143 | + } | |
| 144 | + }) | |
| 145 | + | |
| 146 | + topPanel.add(panel, "grow, gap 0!") | |
| 147 | + | |
| 148 | + return topPanel | |
| 149 | +} | |
| 150 | + | |
| 151 | +fun openInlineEdit(project: Project?, editor: Editor) { | |
| 152 | + if (project == null) return | |
| 153 | + | |
| 154 | + val editorUtils = EditorUtils(editor) | |
| 155 | + | |
| 156 | + // Don't open in terminal | |
| 157 | + if (editorUtils.isTerminal()) { | |
| 158 | + return | |
| 159 | + } | |
| 160 | + | |
| 161 | + val manager = EditorComponentInlaysManager.from(editor, true) | |
| 162 | + | |
| 163 | + val continuePluginService = project.service<ContinuePluginService>() | |
| 164 | + val modelTitles = getModelTitles(continuePluginService) | |
| 165 | + | |
| 166 | + val highlightedRIF = editorUtils.getHighlightedRIF() ?: return | |
| 167 | + val (startLineNumber, endLineNumber) = highlightedRIF.lines | |
| 168 | + val (highlightedStartOffset, highlightedEndOffset) = highlightedRIF.offsets | |
| 169 | + | |
| 170 | + | |
| 171 | + val (prefix, highlighted, suffix) = editorUtils.getHighlightedRangeTriplet() | |
| 172 | + val lineNumber = if (startLineNumber == 0) 0 else max(0, startLineNumber - 1) | |
| 173 | + | |
| 174 | + editorUtils.removeSelection() | |
| 175 | + | |
| 176 | + // Get indentation width in pixels | |
| 177 | + val indentationLineNum = if (startLineNumber == 0) 0 else lineNumber + 1 | |
| 178 | + val lineStart = editor.document.getLineStartOffset(indentationLineNum) | |
| 179 | + val lineEnd = editor.document.getLineEndOffset(indentationLineNum) | |
| 180 | + val text = editor.document.getText(TextRange(lineStart, lineEnd)) | |
| 181 | + val indentation = text.takeWhile { it == ' ' }.length | |
| 182 | + val charWidth = | |
| 183 | + editor.contentComponent | |
| 184 | + .getFontMetrics(editor.colorsScheme.getFont(EditorFontType.PLAIN)) | |
| 185 | + .charWidth(' ') | |
| 186 | + val leftInset = indentation * charWidth * 2 / 3 | |
| 187 | + | |
| 188 | + val inlayRef = Ref<Disposable>() | |
| 189 | + val customPanelRef = Ref<CustomPanel>() | |
| 190 | + | |
| 191 | + // Create text area, attach key listener | |
| 192 | + val textArea = makeTextArea() | |
| 193 | + | |
| 194 | + // Create diff stream handler | |
| 195 | + val diffStreamHandler = | |
| 196 | + DiffStreamHandler( | |
| 197 | + project, | |
| 198 | + editor, | |
| 199 | + startLineNumber, | |
| 200 | + endLineNumber, | |
| 201 | + { | |
| 202 | + inlayRef.get()?.dispose() | |
| 203 | + }, | |
| 204 | + { | |
| 205 | + textArea.document.insertString(textArea.caretPosition, ", ", null) | |
| 206 | + textArea.requestFocus() | |
| 207 | + customPanelRef.get().finish() | |
| 208 | + }, | |
| 209 | + null, | |
| 210 | + null | |
| 211 | + ) | |
| 212 | + | |
| 213 | + val diffStreamService = project.service<DiffStreamService>() | |
| 214 | + diffStreamService.register(diffStreamHandler, editor) | |
| 215 | + | |
| 216 | + val comboBoxRef = Ref<JComboBox<String>>() | |
| 217 | + | |
| 218 | + fun onEnter() { | |
| 219 | + val selectedModelStrippedOfCaret = (comboBoxRef.get().selectedItem as String).removeSuffix(DOWN_ARROW) | |
| 220 | + customPanelRef.get().enter() | |
| 221 | + diffStreamHandler.streamDiffLinesToEditor( | |
| 222 | + textArea.text, prefix, highlighted, suffix, selectedModelStrippedOfCaret, true | |
| 223 | + ) | |
| 224 | + } | |
| 225 | + | |
| 226 | + val panel = | |
| 227 | + makePanel( | |
| 228 | + project, | |
| 229 | + customPanelRef, | |
| 230 | + textArea, | |
| 231 | + inlayRef, | |
| 232 | + comboBoxRef, | |
| 233 | + leftInset, | |
| 234 | + modelTitles, | |
| 235 | + { onEnter() }, | |
| 236 | + { | |
| 237 | + diffStreamService.reject(editor) | |
| 238 | + editorUtils.editor.selectionModel.setSelection(highlightedStartOffset, highlightedEndOffset) | |
| 239 | + }, | |
| 240 | + { | |
| 241 | + diffStreamService.accept(editor) | |
| 242 | + inlayRef.get().dispose() | |
| 243 | + }, | |
| 244 | + { | |
| 245 | + diffStreamService.reject(editor) | |
| 246 | + inlayRef.get().dispose() | |
| 247 | + }) | |
| 248 | + | |
| 249 | + val inlay = manager.insert(startLineNumber, panel, true) | |
| 250 | + | |
| 251 | + panel.revalidate() | |
| 252 | + inlayRef.set(inlay) | |
| 253 | + val viewport = (editor as? EditorImpl)?.scrollPane?.viewport | |
| 254 | + viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED)) | |
| 255 | + | |
| 256 | + // Add key listener to text area | |
| 257 | + textArea.addKeyListener( | |
| 258 | + object : KeyAdapter() { | |
| 259 | + override fun keyTyped(e: KeyEvent) { | |
| 260 | + if (customPanelRef.get().isFinished) { | |
| 261 | + customPanelRef.get().setup() | |
| 262 | + } | |
| 263 | + } | |
| 264 | + | |
| 265 | + override fun keyPressed(e: KeyEvent) { | |
| 266 | + when (e.keyCode) { | |
| 267 | + KeyEvent.VK_ESCAPE -> { | |
| 268 | + diffStreamService.reject(editor) | |
| 269 | + editorUtils.editor.selectionModel.setSelection( | |
| 270 | + highlightedStartOffset, | |
| 271 | + highlightedEndOffset | |
| 272 | + ) | |
| 273 | + } | |
| 274 | + | |
| 275 | + KeyEvent.VK_ENTER -> { | |
| 276 | + when (e.modifiersEx) { | |
| 277 | + KeyEvent.SHIFT_DOWN_MASK -> { | |
| 278 | + textArea.document.insertString(textArea.caretPosition, "\n", null) | |
| 279 | + } | |
| 280 | + | |
| 281 | + 0 -> { | |
| 282 | + onEnter() | |
| 283 | + e.consume() | |
| 284 | + } | |
| 285 | + } | |
| 286 | + } | |
| 287 | + } | |
| 288 | + } | |
| 289 | + | |
| 290 | + // We need this because backspace/delete is not registering properly on keyPressed for an | |
| 291 | + // unknown reason | |
| 292 | + override fun keyReleased(e: KeyEvent) { | |
| 293 | + if (e.keyCode == KeyEvent.VK_BACK_SPACE || e.keyCode == KeyEvent.VK_DELETE) { | |
| 294 | + if (customPanelRef.get().isFinished) { | |
| 295 | + customPanelRef.get().setup() | |
| 296 | + } | |
| 297 | + } | |
| 298 | + } | |
| 299 | + }) | |
| 300 | + | |
| 301 | + // Listen for changes to textarea line count | |
| 302 | + textArea.document.addDocumentListener( | |
| 303 | + object : DocumentListener { | |
| 304 | + private var lastNumLines: Int = 0 | |
| 305 | + | |
| 306 | + private fun updateSize() { | |
| 307 | + val numLines = textArea.text.lines().size | |
| 308 | + if (numLines != lastNumLines) { | |
| 309 | + lastNumLines = numLines | |
| 310 | + viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED)) | |
| 311 | + } | |
| 312 | + } | |
| 313 | + | |
| 314 | + override fun insertUpdate(e: DocumentEvent?) { | |
| 315 | + updateSize() | |
| 316 | + } | |
| 317 | + | |
| 318 | + override fun removeUpdate(e: DocumentEvent?) { | |
| 319 | + updateSize() | |
| 320 | + } | |
| 321 | + | |
| 322 | + override fun changedUpdate(e: DocumentEvent?) { | |
| 323 | + updateSize() | |
| 324 | + } | |
| 325 | + }) | |
| 326 | + | |
| 327 | + textArea.requestFocus() | |
| 328 | +} | |
| 329 | + | |
| 330 | + | |
| 331 | +class CustomPanel( | |
| 332 | + layout: MigLayout, | |
| 333 | + project: Project, | |
| 334 | + modelTitles: List<String>, | |
| 335 | + comboBoxRef: Ref<JComboBox<String>>, | |
| 336 | + private val onEnter: () -> Unit, | |
| 337 | + private val onCancel: () -> Unit, | |
| 338 | + private val onAccept: () -> Unit, | |
| 339 | + private val onReject: () -> Unit, | |
| 340 | + private val textArea: JTextArea | |
| 341 | +) : JPanel(layout) { | |
| 342 | + private val shadowSize = 5 | |
| 343 | + private val cornerRadius = 8 | |
| 344 | + private val shadowColor = Color(0, 0, 0, 40) // Lighter shadow | |
| 345 | + private val borderColor = Color(128, 128, 128, 128) | |
| 346 | + private val borderThickness = 1 | |
| 347 | + private val triangleSize = 6 | |
| 348 | + private val rightMargin = 3.0 | |
| 349 | + private val closeButton: JComponent = createCloseButton() | |
| 350 | + private val originalTextColor: Color = textArea.foreground | |
| 351 | + private val greyTextColor: Color = Color(128, 128, 128, 200) | |
| 352 | + var isFinished = false | |
| 353 | + | |
| 354 | + init { | |
| 355 | + isOpaque = false | |
| 356 | + add(closeButton, "pos 100%-33 0 -3 3, w 20!, h 20!") | |
| 357 | + } | |
| 358 | + | |
| 359 | + private fun createCloseButton(): JComponent { | |
| 360 | + val closeIcon = IconLoader.getIcon("/icons/close.svg", javaClass) | |
| 361 | + return JLabel(closeIcon).apply { | |
| 362 | + background = Color(0, 0, 0, 0) | |
| 363 | + border = JBUI.Borders.empty(2, 6, 2, 0) | |
| 364 | + toolTipText = "`esc` to cancel" | |
| 365 | + isOpaque = false | |
| 366 | + addMouseListener( | |
| 367 | + object : MouseAdapter() { | |
| 368 | + override fun mouseEntered(e: MouseEvent) { | |
| 369 | + cursor = Cursor(Cursor.HAND_CURSOR) | |
| 370 | + } | |
| 371 | + | |
| 372 | + override fun mouseExited(e: MouseEvent) { | |
| 373 | + cursor = Cursor.getDefaultCursor() | |
| 374 | + } | |
| 375 | + | |
| 376 | + override fun mouseClicked(e: MouseEvent) { | |
| 377 | + onCancel() | |
| 378 | + } | |
| 379 | + }) | |
| 380 | + } | |
| 381 | + } | |
| 382 | + | |
| 383 | + private val subPanelA: JPanel = | |
| 384 | + JPanel(MigLayout("insets 0, fillx")).apply { | |
| 385 | + val globalScheme = EditorColorsManager.getInstance().globalScheme | |
| 386 | + val defaultBackground = globalScheme.defaultBackground | |
| 387 | + val continueSettingsService = service<ContinueExtensionSettings>() | |
| 388 | + val dropdown = | |
| 389 | + JComboBox(modelTitles.toTypedArray()).apply { | |
| 390 | + setUI(TransparentArrowButtonUI()) | |
| 391 | + isEditable = true | |
| 392 | + background = defaultBackground | |
| 393 | + foreground = Color(128, 128, 128, 200) | |
| 394 | + font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 12) | |
| 395 | + border = JBUI.Borders.empty(8) | |
| 396 | + isOpaque = false | |
| 397 | + isEditable = false | |
| 398 | + cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) | |
| 399 | + preferredSize = Dimension(200, 30) | |
| 400 | + | |
| 401 | + renderer = object : DefaultListCellRenderer() { | |
| 402 | + override fun getListCellRendererComponent( | |
| 403 | + list: JList<*>?, | |
| 404 | + value: Any?, | |
| 405 | + index: Int, | |
| 406 | + isSelected: Boolean, | |
| 407 | + cellHasFocus: Boolean | |
| 408 | + ): Component { | |
| 409 | + val component = | |
| 410 | + super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus) | |
| 411 | + if (component is JLabel) { | |
| 412 | + component.border = JBUI.Borders.empty(4, 6) | |
| 413 | + } | |
| 414 | + return component | |
| 415 | + } | |
| 416 | + }.apply { | |
| 417 | + horizontalAlignment = SwingConstants.LEFT | |
| 418 | + } | |
| 419 | + | |
| 420 | + selectedIndex = | |
| 421 | + if (itemCount == 0) -1 else continueSettingsService.continueState.lastSelectedInlineEditModel?.let { | |
| 422 | + if (modelTitles.isEmpty()) -1 | |
| 423 | + else { | |
| 424 | + val index = modelTitles.indexOf(it) | |
| 425 | + if (index != -1) index else 0 | |
| 426 | + } | |
| 427 | + } ?: 0 | |
| 428 | + | |
| 429 | + addActionListener { | |
| 430 | + continueSettingsService.continueState.lastSelectedInlineEditModel = | |
| 431 | + (selectedItem as String).removeSuffix(DOWN_ARROW) | |
| 432 | + } | |
| 433 | + } | |
| 434 | + | |
| 435 | + comboBoxRef.set(dropdown) | |
| 436 | + | |
| 437 | + val rightButton = | |
| 438 | + CustomButton("⏎ Enter") { onEnter() } | |
| 439 | + .apply { | |
| 440 | + background = JBColor.namedColor("Button.startBackground") | |
| 441 | + foreground = JBColor.namedColor("Button.foreground") | |
| 442 | + border = JBUI.Borders.empty(2, 6) | |
| 443 | + } | |
| 444 | + | |
| 445 | + val rightPanel = JPanel(MigLayout("insets 0, fillx")).apply { | |
| 446 | + isOpaque = false | |
| 447 | + add(rightButton, "align right") | |
| 448 | + } | |
| 449 | + | |
| 450 | + border = JBUI.Borders.empty(0, 0, 16, 12) | |
| 451 | + isOpaque = false | |
| 452 | + | |
| 453 | + add(dropdown, "align left") | |
| 454 | + add(rightPanel, "align right") | |
| 455 | + | |
| 456 | + cursor = Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR) | |
| 457 | + } | |
| 458 | + | |
| 459 | + private val subPanelB: JPanel = | |
| 460 | + JPanel(BorderLayout()).apply { | |
| 461 | + isOpaque = false | |
| 462 | + | |
| 463 | + val progressBar = JProgressBar().apply { isIndeterminate = true } | |
| 464 | + | |
| 465 | + add(progressBar, BorderLayout.CENTER) | |
| 466 | + border = JBUI.Borders.empty(0, 0, 16, 12) | |
| 467 | + } | |
| 468 | + | |
| 469 | + private val subPanelC: JPanel = | |
| 470 | + JPanel(MigLayout("insets 0, fillx")).apply { | |
| 471 | + val leftLabel = | |
| 472 | + JLabel("Type to re-prompt").apply { | |
| 473 | + foreground = Color(156, 163, 175) // text-gray-400 | |
| 474 | + font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11) | |
| 475 | + border = JBUI.Borders.emptyLeft(4) | |
| 476 | + } | |
| 477 | + | |
| 478 | + val leftButton = | |
| 479 | + CustomButton("Reject All (${getMetaKeyLabel()}${getShiftKeyLabel()}⌫)") { onReject() } | |
| 480 | + .apply { | |
| 481 | + background = Color(0, 0, 0, 0) | |
| 482 | + foreground = JBColor.foreground() | |
| 483 | + border = JBUI.Borders.empty(2, 6) | |
| 484 | + } | |
| 485 | + | |
| 486 | + val rightButton = | |
| 487 | + CustomButton("Accept All (${getMetaKeyLabel()}${getShiftKeyLabel()}⏎)") { onAccept() } | |
| 488 | + .apply { | |
| 489 | + background = JBColor.namedColor("Button.startBackground") | |
| 490 | + foreground = JBColor.namedColor("Button.foreground") | |
| 491 | + border = JBUI.Borders.empty(2, 6) | |
| 492 | + } | |
| 493 | + | |
| 494 | + val rightPanel = | |
| 495 | + JPanel(MigLayout("insets 0, fillx")).apply { | |
| 496 | + isOpaque = false | |
| 497 | + add(leftButton, "align right") | |
| 498 | + add(rightButton, "align right") | |
| 499 | + border = JBUI.Borders.empty() | |
| 500 | + } | |
| 501 | + | |
| 502 | + add(leftLabel, "align left") | |
| 503 | + add(rightPanel, "align right") | |
| 504 | + border = JBUI.Borders.empty(0, 0, 16, 12) | |
| 505 | + isOpaque = false | |
| 506 | + } | |
| 507 | + | |
| 508 | + fun setup() { | |
| 509 | + remove(subPanelB) | |
| 510 | + remove(subPanelC) | |
| 511 | + add(subPanelA, "grow, gap 0!") | |
| 512 | + isFinished = false | |
| 513 | + revalidate() | |
| 514 | + repaint() | |
| 515 | + textArea.foreground = originalTextColor | |
| 516 | + } | |
| 517 | + | |
| 518 | + fun enter() { | |
| 519 | + remove(subPanelA) | |
| 520 | + remove(subPanelC) | |
| 521 | + add(subPanelB, "grow, gap 0!") | |
| 522 | + revalidate() | |
| 523 | + repaint() | |
| 524 | + } | |
| 525 | + | |
| 526 | + fun finish() { | |
| 527 | + remove(subPanelB) | |
| 528 | + add(subPanelC, "grow, gap 0!") | |
| 529 | + revalidate() | |
| 530 | + repaint() | |
| 531 | + isFinished = true | |
| 532 | + textArea.foreground = greyTextColor | |
| 533 | + } | |
| 534 | + | |
| 535 | + override fun paintComponent(g: Graphics) { | |
| 536 | + super.paintComponent(g) | |
| 537 | + | |
| 538 | + val g2 = g as Graphics2D | |
| 539 | + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) | |
| 540 | + | |
| 541 | + val w = width - shadowSize | |
| 542 | + val h = height - shadowSize | |
| 543 | + | |
| 544 | + // Create the shape for the tooltip/triangle | |
| 545 | + val shape = Path2D.Double() | |
| 546 | + shape.moveTo(borderThickness / 2.0, cornerRadius.toDouble()) | |
| 547 | + shape.quadTo( | |
| 548 | + borderThickness / 2.0, | |
| 549 | + borderThickness / 2.0, | |
| 550 | + cornerRadius.toDouble(), | |
| 551 | + borderThickness / 2.0 | |
| 552 | + ) | |
| 553 | + shape.lineTo(w - cornerRadius.toDouble() - rightMargin, borderThickness / 2.0) | |
| 554 | + shape.quadTo( | |
| 555 | + w - borderThickness / 2.0 - rightMargin, | |
| 556 | + borderThickness / 2.0, | |
| 557 | + w - borderThickness / 2.0 - rightMargin, | |
| 558 | + cornerRadius.toDouble() | |
| 559 | + ) | |
| 560 | + shape.lineTo( | |
| 561 | + w - borderThickness / 2.0 - rightMargin, h - cornerRadius - triangleSize.toDouble() | |
| 562 | + ) | |
| 563 | + shape.quadTo( | |
| 564 | + w - borderThickness / 2.0 - rightMargin, | |
| 565 | + h - triangleSize.toDouble(), | |
| 566 | + w - cornerRadius.toDouble() - rightMargin, | |
| 567 | + h - triangleSize.toDouble() | |
| 568 | + ) | |
| 569 | + shape.lineTo(triangleSize.toDouble(), h - triangleSize.toDouble()) | |
| 570 | + shape.lineTo(borderThickness / 2.0, h.toDouble()) | |
| 571 | + shape.lineTo(borderThickness / 2.0, cornerRadius.toDouble()) | |
| 572 | + | |
| 573 | + // Draw shadow | |
| 574 | + g2.color = shadowColor | |
| 575 | + g2.fill( | |
| 576 | + shape.createTransformedShape( | |
| 577 | + AffineTransform.getTranslateInstance(shadowSize.toDouble(), shadowSize.toDouble()) | |
| 578 | + ) | |
| 579 | + ) | |
| 580 | + | |
| 581 | + // Draw main shape | |
| 582 | + g2.color = background | |
| 583 | + g2.fill(shape) | |
| 584 | + | |
| 585 | + // Draw border | |
| 586 | + g2.color = borderColor | |
| 587 | + g2.stroke = BasicStroke(borderThickness.toFloat()) | |
| 588 | + g2.draw(shape) | |
| 589 | + } | |
| 590 | +} | |
| 591 | + | |
| 592 | +class CustomButton(text: String, onClick: () -> Unit) : JLabel(text, CENTER) { | |
| 593 | + private var isHovered = false | |
| 594 | + | |
| 595 | + init { | |
| 596 | + isOpaque = false | |
| 597 | + cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) | |
| 598 | + addMouseListener( | |
| 599 | + object : MouseAdapter() { | |
| 600 | + override fun mouseEntered(e: MouseEvent?) { | |
| 601 | + isHovered = true | |
| 602 | + repaint() | |
| 603 | + } | |
| 604 | + | |
| 605 | + override fun mouseExited(e: MouseEvent?) { | |
| 606 | + isHovered = false | |
| 607 | + repaint() | |
| 608 | + } | |
| 609 | + | |
| 610 | + override fun mouseClicked(e: MouseEvent?) { | |
| 611 | + onClick() | |
| 612 | + } | |
| 613 | + }) | |
| 614 | + | |
| 615 | + font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11) | |
| 616 | + border = JBUI.Borders.empty(2, 6) | |
| 617 | + } | |
| 618 | + | |
| 619 | + override fun paintComponent(g: Graphics) { | |
| 620 | + val g2 = g as Graphics2D | |
| 621 | + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) | |
| 622 | + | |
| 623 | + val cornerRadius = 8 | |
| 624 | + val rect = Rectangle(0, 0, width, height) | |
| 625 | + val roundRect = | |
| 626 | + RoundRectangle2D.Float( | |
| 627 | + rect.x.toFloat(), | |
| 628 | + rect.y.toFloat(), | |
| 629 | + rect.width.toFloat(), | |
| 630 | + rect.height.toFloat(), | |
| 631 | + cornerRadius.toFloat(), | |
| 632 | + cornerRadius.toFloat() | |
| 633 | + ) | |
| 634 | + g2.color = background | |
| 635 | + g2.fill(roundRect) | |
| 636 | + g2.color = foreground | |
| 637 | + g2.drawString( | |
| 638 | + text, | |
| 639 | + (width / 2 - g.fontMetrics.stringWidth(text) / 2).toFloat(), | |
| 640 | + (height / 2 + g.fontMetrics.ascent / 2).toFloat() | |
| 641 | + ) | |
| 642 | + } | |
| 643 | +} | |
| 644 | + | |
| 645 | +class CustomTextArea(rows: Int, columns: Int) : JXTextArea("") { | |
| 646 | + init { | |
| 647 | + setRows(rows) | |
| 648 | + setColumns(columns) | |
| 649 | + } | |
| 650 | + | |
| 651 | + override fun paintComponent(g: Graphics) { | |
| 652 | + // Draw placeholder | |
| 653 | + if (text.isEmpty()) { | |
| 654 | + g.color = Color(128, 128, 128, 255) | |
| 655 | + g.font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE) | |
| 656 | + g.drawString("Enter instructions...", 8, 20) | |
| 657 | + } | |
| 658 | + | |
| 659 | + super.paintComponent(g) | |
| 660 | + } | |
| 661 | +} | |
| 662 | + | |
| 663 | +class ShadowPanel(layout: LayoutManager) : JXPanel(layout) { | |
| 664 | + override fun getPreferredSize(): Dimension { | |
| 665 | + val prefSize = super.getPreferredSize() | |
| 666 | + val insets = getInsets() | |
| 667 | + prefSize.width += insets.left + insets.right | |
| 668 | + prefSize.height += insets.top + insets.bottom | |
| 669 | + return prefSize | |
| 670 | + } | |
| 671 | + | |
| 672 | + override fun paintComponent(g: Graphics) { | |
| 673 | + super.paintComponent(g) | |
| 674 | + } | |
| 675 | +} | |
| 676 | + | |
| 677 | +class TransparentArrowButtonUI : BasicComboBoxUI() { | |
| 678 | + override fun createArrowButton() = | |
| 679 | + JButton().apply { | |
| 680 | + isVisible = false | |
| 681 | + preferredSize = Dimension(0, 0) | |
| 682 | + } | |
| 683 | + | |
| 684 | + override fun getInsets(): Insets { | |
| 685 | + return JBUI.insetsLeft(6) | |
| 686 | + } | |
| 687 | + | |
| 688 | + override fun installUI(c: JComponent?) { | |
| 689 | + super.installUI(c) | |
| 690 | + comboBox.isOpaque = false | |
| 691 | + val globalScheme = EditorColorsManager.getInstance().globalScheme | |
| 692 | + val defaultBackground = globalScheme.defaultBackground | |
| 693 | + comboBox.background = defaultBackground | |
| 694 | + | |
| 695 | + // Modify the ComboBoxModel to include the down symbol | |
| 696 | + val originalModel = comboBox.model | |
| 697 | + comboBox.model = | |
| 698 | + object : ComboBoxModel<Any> { | |
| 699 | + override fun getSize(): Int = originalModel.size | |
| 700 | + | |
| 701 | + override fun getElementAt(index: Int): Any? = originalModel.getElementAt(index) | |
| 702 | + | |
| 703 | + override fun setSelectedItem(anItem: Any?) { | |
| 704 | + originalModel.selectedItem = anItem | |
| 705 | + } | |
| 706 | + | |
| 707 | + override fun getSelectedItem(): Any? { | |
| 708 | + val item = originalModel.selectedItem | |
| 709 | + return "$item$DOWN_ARROW" | |
| 710 | + } | |
| 711 | + | |
| 712 | + override fun addListDataListener(l: ListDataListener?) { | |
| 713 | + originalModel.addListDataListener(l) | |
| 714 | + } | |
| 715 | + | |
| 716 | + override fun removeListDataListener(l: ListDataListener?) { | |
| 717 | + originalModel.removeListDataListener(l) | |
| 718 | + } | |
| 719 | + } | |
| 720 | + } | |
| 721 | + | |
| 722 | + override fun paintCurrentValueBackground(g: Graphics, bounds: Rectangle, hasFocus: Boolean) { | |
| 723 | + // Do nothing to prevent painting the background | |
| 724 | + } | |
| 725 | + | |
| 726 | + override fun paintCurrentValue(g: Graphics, bounds: Rectangle, hasFocus: Boolean) { | |
| 727 | + val renderer = comboBox.renderer | |
| 728 | + val item = comboBox.selectedItem | |
| 729 | + | |
| 730 | + if (item != null) { | |
| 731 | + val c = renderer.getListCellRendererComponent(listBox, item, -1, false, false) | |
| 732 | + c.font = comboBox.font | |
| 733 | + c.foreground = Color(156, 163, 175) // text-gray-400 | |
| 734 | + c.background = comboBox.background | |
| 735 | + | |
| 736 | + if (c is JComponent) { | |
| 737 | + c.isOpaque = false | |
| 738 | + } | |
| 739 | + | |
| 740 | + val currentValuePane = currentValuePane | |
| 741 | + currentValuePane.paintComponent( | |
| 742 | + g, c, comboBox, bounds.x, bounds.y, bounds.width, bounds.height, true | |
| 743 | + ) | |
| 744 | + } | |
| 745 | + } | |
| 746 | +} |
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/RangeInFileWithContents.kt +59 −11
| @@ -12,22 +12,43 @@ | ||
| 12 | 12 | class RangeInFileWithContents( |
| 13 | 13 | val filepath: String, |
| 14 | 14 | val range: Range, |
| 15 | - val contents: String | |
| 15 | + val contents: String, | |
| 16 | + val document: Document | |
| 17 | + | |
| 16 | 18 | ) { |
| 17 | 19 | /** |
| 18 | - * Returns the absolute document offset for the start position | |
| 20 | + * The absolute document offset for the start position | |
| 21 | + */ | |
| 22 | + val startOffset: Int | |
| 23 | + get() = document.getLineStartOffset(range.start.line) + range.start.character | |
| 24 | + | |
| 25 | + /** | |
| 26 | + * The absolute document offset for the end position | |
| 27 | + */ | |
| 28 | + val endOffset: Int | |
| 29 | + get() = document.getLineStartOffset(range.end.line) + range.end.character | |
| 30 | + | |
| 31 | + /** | |
| 32 | + * The line number where the highlighted range starts (zero-based) | |
| 33 | + */ | |
| 34 | + val startLine: Int | |
| 35 | + get() = range.start.line | |
| 36 | + | |
| 37 | + /** | |
| 38 | + * The line number where the highlighted range ends (zero-based) | |
| 39 | + * This already accounts for proper line ending calculations. | |
| 19 | 40 | */ |
| 20 | - fun getStartOffset(document: Document): Int { | |
| 21 | - return document.getLineStartOffset(range.start.line) + range.start.character | |
| 22 | - } | |
| 41 | + val endLine: Int | |
| 42 | + get() = range.end.line | |
| 23 | 43 | |
| 24 | 44 | /** |
| 25 | - * Returns the absolute document offset for the end position | |
| 45 | + * Both the start and end line numbers of the highlighted range as a pair | |
| 26 | 46 | */ |
| 27 | - fun getEndOffset(document: Document): Int { | |
| 28 | - return document.getLineStartOffset(range.end.line) + range.end.character | |
| 29 | - } | |
| 47 | + val lines: Pair<Int, Int> | |
| 48 | + get() = Pair(startLine, endLine) | |
| 30 | 49 | |
| 50 | + val offsets: Pair<Int, Int> | |
| 51 | + get() = Pair(startOffset, endOffset) | |
| 31 | 52 | |
| 32 | 53 | companion object { |
| 33 | 54 | /** |
| @@ -45,6 +66,13 @@ | ||
| 45 | 66 | val startChar = selectionStart - document.getLineStartOffset(startLine) |
| 46 | 67 | val endChar = selectionEnd - document.getLineStartOffset(endLine) |
| 47 | 68 | |
| 69 | + // Adjust end line if it's a single line selection with trailing newlines | |
| 70 | + val adjustedEndLine = if (isSelectionWithTrailingNewline(document, selectionStart, selectionEnd)) { | |
| 71 | + endLine - 1 | |
| 72 | + } else { | |
| 73 | + endLine | |
| 74 | + } | |
| 75 | + | |
| 48 | 76 | val selectedText = document.getText( |
| 49 | 77 | TextRange(selectionStart, selectionEnd) |
| 50 | 78 | ) |
| @@ -53,10 +81,30 @@ | ||
| 53 | 81 | filepath, |
| 54 | 82 | Range( |
| 55 | 83 | Position(startLine, startChar), |
| 56 | - Position(endLine, endChar) | |
| 84 | + Position(adjustedEndLine, endChar) | |
| 57 | 85 | ), |
| 58 | - selectedText | |
| 86 | + selectedText, | |
| 87 | + document | |
| 59 | 88 | ) |
| 60 | 89 | } |
| 90 | + | |
| 91 | + /** | |
| 92 | + * Checks if the selection spans to the next line only because of trailing newlines. | |
| 93 | + * This matters when a user double-clicks to highlight a full line. | |
| 94 | + * | |
| 95 | + * @return true if the selection is actually a single line selection with trailing newline | |
| 96 | + */ | |
| 97 | + fun isSelectionWithTrailingNewline( | |
| 98 | + document: Document, | |
| 99 | + selectionStart: Int, | |
| 100 | + selectionEnd: Int | |
| 101 | + ): Boolean { | |
| 102 | + val startLine = document.getLineNumber(selectionStart) | |
| 103 | + val endLine = document.getLineNumber(selectionEnd) | |
| 104 | + | |
| 105 | + return endLine > startLine && | |
| 106 | + endLine < document.lineCount && | |
| 107 | + document.getLineStartOffset(endLine) == selectionEnd | |
| 108 | + } | |
| 61 | 109 | } |
| 62 | 110 | } |
| No newline at the end of the file |
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffBlock.kt +3 −2
| @@ -166,7 +166,7 @@ | ||
| 166 | 166 | val rejectBtn = |
| 167 | 167 | createButton( |
| 168 | 168 | "${getAltKeyLabel()}${getShiftKeyLabel()}N", |
| 169 | - JBColor(0x77FF0000, 0x77FF0000) | |
| 169 | + JBColor(0xFF0000, 0xFF0000) | |
| 170 | 170 | ).apply { |
| 171 | 171 | addActionListener { |
| 172 | 172 | handleReject() |
| @@ -178,13 +178,14 @@ | ||
| 178 | 178 | createButton( |
| 179 | 179 | "${getAltKeyLabel()}${ |
| 180 | 180 | getShiftKeyLabel() |
| 181 | - }Y", JBColor(0x7700BB00, 0x7700BB00) | |
| 181 | + }Y", JBColor(0x00BB00, 0x00BB00) | |
| 182 | 182 | ).apply { |
| 183 | 183 | addActionListener { |
| 184 | 184 | handleAccept() |
| 185 | 185 | } |
| 186 | 186 | } |
| 187 | 187 | |
| 188 | + | |
| 188 | 189 | return Pair(acceptBtn, rejectBtn) |
| 189 | 190 | } |
| 190 | 191 |
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt +0 −10
| @@ -15,16 +15,6 @@ | ||
| 15 | 15 | val toolCallId: String? |
| 16 | 16 | ) |
| 17 | 17 | |
| 18 | -data class AcceptDiffParams( | |
| 19 | - val filepath: String, | |
| 20 | - val streamId: String | |
| 21 | -) | |
| 22 | - | |
| 23 | -data class RejectDiffParams( | |
| 24 | - val filepath: String, | |
| 25 | - val streamId: String | |
| 26 | -) | |
| 27 | - | |
| 28 | 18 | data class InsertAtCursorParams( |
| 29 | 19 | val text: String |
| 30 | 20 | ) |
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt +4 −0
| @@ -251,4 +251,8 @@ | ||
| 251 | 251 | data class AcceptOrRejectDiffPayload( |
| 252 | 252 | val filepath: String, |
| 253 | 253 | val streamId: String? = null |
| 254 | +) | |
| 255 | + | |
| 256 | +data class ShowFilePayload( | |
| 257 | + val filepath: String | |
| 254 | 258 | ) |
| No newline at the end of the file |
modified extensions/intellij/src/main/resources/META-INF/plugin.xml +2 −2
| @@ -78,9 +78,9 @@ | ||
| 78 | 78 | class="com.github.continuedev.continueintellijextension.actions.RejectDiffAction" |
| 79 | 79 | text="Reject Diff" description="Reject Diff"> |
| 80 | 80 | <keyboard-shortcut keymap="$default" |
| 81 | - first-keystroke="shift ctrl DELETE"/> | |
| 81 | + first-keystroke="shift ctrl BACK_SPACE"/> | |
| 82 | 82 | <keyboard-shortcut keymap="Mac OS X" |
| 83 | - first-keystroke="shift meta DELETE"/> | |
| 83 | + first-keystroke="shift meta BACK_SPACE"/> | |
| 84 | 84 | <override-text place="GoToAction" text="Continue: Reject Diff"/> |
| 85 | 85 | </action> |
| 86 | 86 |
modified extensions/vscode/package-lock.json +0 −0
Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.
modified extensions/vscode/package.json +3 −3
| @@ -2,7 +2,7 @@ | ||
| 2 | 2 | "name": "continue", |
| 3 | 3 | "icon": "media/icon.png", |
| 4 | 4 | "author": "Continue Dev, Inc", |
| 5 | - "version": "1.1.35", | |
| 5 | + "version": "1.1.39", | |
| 6 | 6 | "repository": { |
| 7 | 7 | "type": "git", |
| 8 | 8 | "url": "https://github.com/continuedev/continue" |
| @@ -105,7 +105,7 @@ | ||
| 105 | 105 | "continue.enableQuickActions": { |
| 106 | 106 | "type": "boolean", |
| 107 | 107 | "default": false, |
| 108 | - "markdownDescription": "Enable the experimental Quick Actions feature. Read our walkthrough to learn about configuration and how to share feedback: [continue.dev › Walkthrough: Quick Actions (experimental)](https://docs.continue.dev/features/quick-actions)" | |
| 108 | + "markdownDescription": "Enable the experimental Quick Actions feature. Read our walkthrough to learn about configuration and how to share feedback: [continue.dev › Walkthrough: Quick Actions (experimental)](https://docs.continue.dev/customize/deep-dives/vscode-actions#quick-actions)" | |
| 109 | 109 | }, |
| 110 | 110 | "continue.enableTabAutocomplete": { |
| 111 | 111 | "type": "boolean", |
| @@ -631,7 +631,7 @@ | ||
| 631 | 631 | "devDependencies": { |
| 632 | 632 | "@biomejs/biome": "1.6.4", |
| 633 | 633 | "@nestjs/common": "^11.0.16", |
| 634 | - "@openapitools/openapi-generator-cli": "^2.5.2", | |
| 634 | + "@openapitools/openapi-generator-cli": "^2.20.0", | |
| 635 | 635 | "@types/chai": "^5.0.1", |
| 636 | 636 | "@types/cors": "^2.8.17", |
| 637 | 637 | "@types/express": "^4.17.21", |
modified extensions/vscode/src/stubs/WorkOsAuthProvider.ts +36 −7
| @@ -1,6 +1,5 @@ | ||
| 1 | 1 | import crypto from "crypto"; |
| 2 | 2 | |
| 3 | -import { ControlPlaneSessionInfo } from "core/control-plane/client"; | |
| 4 | 3 | import { getControlPlaneEnvSync } from "core/control-plane/env"; |
| 5 | 4 | import fetch from "node-fetch"; |
| 6 | 5 | import { v4 as uuidv4 } from "uuid"; |
| @@ -18,6 +17,12 @@ | ||
| 18 | 17 | window, |
| 19 | 18 | } from "vscode"; |
| 20 | 19 | |
| 20 | +import { | |
| 21 | + AuthType, | |
| 22 | + ControlPlaneSessionInfo, | |
| 23 | + HubEnv, | |
| 24 | + isHubEnv, | |
| 25 | +} from "core/control-plane/AuthTypes"; | |
| 21 | 26 | import { PromiseAdapter, promiseFromEvent } from "./promiseUtils"; |
| 22 | 27 | import { SecretStorage } from "./SecretStorage"; |
| 23 | 28 | import { UriEventHandler } from "./uriHandler"; |
| @@ -280,12 +285,21 @@ | ||
| 280 | 285 | try { |
| 281 | 286 | const codeVerifier = generateRandomString(64); |
| 282 | 287 | const codeChallenge = await generateCodeChallenge(codeVerifier); |
| 283 | - const token = await this.login(codeChallenge, scopes); | |
| 288 | + | |
| 289 | + if (!isHubEnv(controlPlaneEnv)) { | |
| 290 | + throw new Error("Login is disabled"); | |
| 291 | + } | |
| 292 | + | |
| 293 | + const token = await this.login(codeChallenge, controlPlaneEnv, scopes); | |
| 284 | 294 | if (!token) { |
| 285 | 295 | throw new Error(`Continue login failure`); |
| 286 | 296 | } |
| 287 | 297 | |
| 288 | - const userInfo = (await this.getUserInfo(token, codeVerifier)) as any; | |
| 298 | + const userInfo = (await this.getUserInfo( | |
| 299 | + token, | |
| 300 | + codeVerifier, | |
| 301 | + controlPlaneEnv, | |
| 302 | + )) as any; | |
| 289 | 303 | const { user, access_token, refresh_token } = userInfo; |
| 290 | 304 | |
| 291 | 305 | const session: ContinueAuthenticationSession = { |
| @@ -352,7 +366,11 @@ | ||
| 352 | 366 | /** |
| 353 | 367 | * Log in to Continue |
| 354 | 368 | */ |
| 355 | - private async login(codeChallenge: string, scopes: string[] = []) { | |
| 369 | + private async login( | |
| 370 | + codeChallenge: string, | |
| 371 | + hubEnv: HubEnv, | |
| 372 | + scopes: string[] = [], | |
| 373 | + ) { | |
| 356 | 374 | return await window.withProgress<string>( |
| 357 | 375 | { |
| 358 | 376 | location: ProgressLocation.Notification, |
| @@ -369,7 +387,7 @@ | ||
| 369 | 387 | const url = new URL("https://api.workos.com/user_management/authorize"); |
| 370 | 388 | const params = { |
| 371 | 389 | response_type: "code", |
| 372 | - client_id: controlPlaneEnv.WORKOS_CLIENT_ID, | |
| 390 | + client_id: hubEnv.WORKOS_CLIENT_ID, | |
| 373 | 391 | redirect_uri: this.redirectUri, |
| 374 | 392 | state: stateId, |
| 375 | 393 | code_challenge: codeChallenge, |
| @@ -458,7 +476,11 @@ | ||
| 458 | 476 | * @param token |
| 459 | 477 | * @returns |
| 460 | 478 | */ |
| 461 | - private async getUserInfo(token: string, codeVerifier: string) { | |
| 479 | + private async getUserInfo( | |
| 480 | + token: string, | |
| 481 | + codeVerifier: string, | |
| 482 | + hubEnv: HubEnv, | |
| 483 | + ) { | |
| 462 | 484 | const resp = await fetch( |
| 463 | 485 | "https://api.workos.com/user_management/authenticate", |
| 464 | 486 | { |
| @@ -467,7 +489,7 @@ | ||
| 467 | 489 | "Content-Type": "application/json", |
| 468 | 490 | }, |
| 469 | 491 | body: JSON.stringify({ |
| 470 | - client_id: controlPlaneEnv.WORKOS_CLIENT_ID, | |
| 492 | + client_id: hubEnv.WORKOS_CLIENT_ID, | |
| 471 | 493 | code_verifier: codeVerifier, |
| 472 | 494 | grant_type: "authorization_code", |
| 473 | 495 | code: token, |
| @@ -484,6 +506,12 @@ | ||
| 484 | 506 | silent: boolean, |
| 485 | 507 | useOnboarding: boolean, |
| 486 | 508 | ): Promise<ControlPlaneSessionInfo | undefined> { |
| 509 | + if (!isHubEnv(controlPlaneEnv)) { | |
| 510 | + return { | |
| 511 | + AUTH_TYPE: AuthType.OnPrem, | |
| 512 | + }; | |
| 513 | + } | |
| 514 | + | |
| 487 | 515 | try { |
| 488 | 516 | if (useOnboarding) { |
| 489 | 517 | WorkOsAuthProvider.useOnboardingUri = true; |
| @@ -498,6 +526,7 @@ | ||
| 498 | 526 | return undefined; |
| 499 | 527 | } |
| 500 | 528 | return { |
| 529 | + AUTH_TYPE: controlPlaneEnv.AUTH_TYPE, | |
| 501 | 530 | accessToken: session.accessToken, |
| 502 | 531 | account: { |
| 503 | 532 | id: session.account.id, |
modified gui/package-lock.json +0 −0
Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.
modified gui/src/App.tsx +5 −0
| @@ -9,6 +9,7 @@ | ||
| 9 | 9 | import Chat from "./pages/gui"; |
| 10 | 10 | import History from "./pages/history"; |
| 11 | 11 | import Stats from "./pages/stats"; |
| 12 | +import ThemePage from "./styles/ThemePage"; | |
| 12 | 13 | import { ROUTES } from "./util/navigation"; |
| 13 | 14 | |
| 14 | 15 | const router = createMemoryRouter([ |
| @@ -37,6 +38,10 @@ | ||
| 37 | 38 | path: ROUTES.CONFIG, |
| 38 | 39 | element: <ConfigPage />, |
| 39 | 40 | }, |
| 41 | + { | |
| 42 | + path: ROUTES.THEME, | |
| 43 | + element: <ThemePage />, | |
| 44 | + }, | |
| 40 | 45 | ], |
| 41 | 46 | }, |
| 42 | 47 | ]); |
modified gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton.tsx +1 −12
| @@ -3,6 +3,7 @@ | ||
| 3 | 3 | import { lightGray, vscForeground } from "../.."; |
| 4 | 4 | import { IdeMessengerContext } from "../../../context/IdeMessenger"; |
| 5 | 5 | import { isJetBrains } from "../../../util"; |
| 6 | +import { extractCommand } from "../utils/commandExtractor"; | |
| 6 | 7 | |
| 7 | 8 | interface RunInTerminalButtonProps { |
| 8 | 9 | command: string; |
| @@ -16,18 +17,6 @@ | ||
| 16 | 17 | return null; |
| 17 | 18 | } |
| 18 | 19 | |
| 19 | - // Extract just the command line (the line after $ or the first line) | |
| 20 | - function extractCommand(cmd: string): string { | |
| 21 | - // If the command contains a $ prompt, extract the line after it | |
| 22 | - if (cmd.includes("$")) { | |
| 23 | - const match = cmd.match(/\$\s*([^\n]+)/); | |
| 24 | - return match ? match[1].trim() : ""; | |
| 25 | - } | |
| 26 | - | |
| 27 | - // Otherwise, just take the first line | |
| 28 | - return cmd.split("\n")[0].trim(); | |
| 29 | - } | |
| 30 | - | |
| 31 | 20 | function runInTerminal() { |
| 32 | 21 | // Extract just the command line |
| 33 | 22 | const extractedCommand = extractCommand(command); |
modified gui/src/components/StyledMarkdownPreview/SymbolLink.tsx +1 −8
| @@ -44,14 +44,7 @@ | ||
| 44 | 44 | data-tooltip-id={id} |
| 45 | 45 | data-tooltip-delay-show={500} |
| 46 | 46 | > |
| 47 | - <code | |
| 48 | - className="align-middle" | |
| 49 | - style={{ | |
| 50 | - color: "var(--vscode-textLink-foreground)", | |
| 51 | - }} | |
| 52 | - > | |
| 53 | - {content} | |
| 54 | - </code> | |
| 47 | + <code className="text-link align-middle">{content}</code> | |
| 55 | 48 | </span> |
| 56 | 49 | <ToolTip id={id} place="top" className="m-0 p-0"> |
| 57 | 50 | <pre className="text-left">{processedContent ?? symbol.filepath}</pre> |
modified gui/src/components/StyledMarkdownPreview/rehypeHighlightPlugin.ts +2 −0
| @@ -1,6 +1,7 @@ | ||
| 1 | 1 | // Feel free to add more! |
| 2 | 2 | // See gui/node_modules/highlight.js/lib/languages for the full available list |
| 3 | 3 | import clojure from "highlight.js/lib/languages/clojure"; |
| 4 | +import delphi from "highlight.js/lib/languages/delphi"; | |
| 4 | 5 | import elixir from "highlight.js/lib/languages/elixir"; |
| 5 | 6 | import julia from "highlight.js/lib/languages/julia"; |
| 6 | 7 | import lisp from "highlight.js/lib/languages/lisp"; |
| @@ -19,6 +20,7 @@ | ||
| 19 | 20 | languages: { |
| 20 | 21 | ...common, |
| 21 | 22 | clojure, |
| 23 | + delphi, | |
| 22 | 24 | elixir, |
| 23 | 25 | julia, |
| 24 | 26 | protobuf, |
added gui/src/components/StyledMarkdownPreview/utils/commandExtractor.test.ts +80 −0
| @@ -0,0 +1,80 @@ | ||
| 1 | +import { extractCommand } from './commandExtractor'; | |
| 2 | + | |
| 3 | +describe('extractCommand', () => { | |
| 4 | + // Test basic command extraction | |
| 5 | + it('should extract command from $ prompt', () => { | |
| 6 | + expect(extractCommand('$ echo hello')).toBe('echo hello'); | |
| 7 | + expect(extractCommand('$ echo hello')).toBe('echo hello'); | |
| 8 | + expect(extractCommand('$echo hello')).toBe('echo hello'); | |
| 9 | + }); | |
| 10 | + | |
| 11 | + // Test comment removal | |
| 12 | + it('should remove comments at beginning of lines', () => { | |
| 13 | + expect(extractCommand('# shell comment\necho hello')).toBe('echo hello'); | |
| 14 | + expect(extractCommand('// js comment\necho hello')).toBe('echo hello'); | |
| 15 | + expect(extractCommand('/* multi-line\ncomment */\necho hello')).toBe('echo hello'); | |
| 16 | + }); | |
| 17 | + | |
| 18 | + // Test multiline comment removal | |
| 19 | + it('should remove multiline comments anywhere in the text', () => { | |
| 20 | + expect(extractCommand('echo /* comment */ hello')).toBe('echo hello'); | |
| 21 | + expect(extractCommand('echo hello /* comment */')).toBe('echo hello'); | |
| 22 | + expect(extractCommand('echo /* multiple\nline\ncomment */ hello')).toBe('echo hello'); | |
| 23 | + }); | |
| 24 | + | |
| 25 | + // Test line continuation handling | |
| 26 | + it('should handle line continuations correctly', () => { | |
| 27 | + expect(extractCommand('echo hello && \\\necho world')).toBe('echo hello && echo world'); | |
| 28 | + expect(extractCommand('echo hello | \\\ngrep h')).toBe('echo hello | grep h'); | |
| 29 | + expect(extractCommand('echo hello \\\nworld')).toBe('echo hello world'); | |
| 30 | + }); | |
| 31 | + | |
| 32 | + // Test complex command combinations | |
| 33 | + it('should handle complex command combinations', () => { | |
| 34 | + expect(extractCommand(` | |
| 35 | + # shell comment | |
| 36 | + echo hello /* inline comment */ && \\ | |
| 37 | + // js comment | |
| 38 | + echo world | |
| 39 | + `)).toBe('echo hello && echo world'); | |
| 40 | + }); | |
| 41 | + | |
| 42 | + // Test empty and whitespace handling | |
| 43 | + it('should handle empty and whitespace inputs', () => { | |
| 44 | + expect(extractCommand('')).toBe(''); | |
| 45 | + expect(extractCommand(' \n \t ')).toBe(''); | |
| 46 | + }); | |
| 47 | + | |
| 48 | + // Test comment-only inputs | |
| 49 | + it('should handle comment-only inputs', () => { | |
| 50 | + expect(extractCommand('/* comment */')).toBe(''); | |
| 51 | + expect(extractCommand('# comment')).toBe(''); | |
| 52 | + expect(extractCommand('// comment')).toBe(''); | |
| 53 | + expect(extractCommand('/* multi\nline\ncomment */')).toBe(''); | |
| 54 | + }); | |
| 55 | + | |
| 56 | + // Test inline comments | |
| 57 | + it('should handle inline comments correctly according to implementation', () => { | |
| 58 | + // But removes multiline comments even when inline | |
| 59 | + expect(extractCommand('/* inline */ echo hello world')).toBe('echo hello world'); | |
| 60 | + }); | |
| 61 | + | |
| 62 | + // Test multiple line continuations | |
| 63 | + it('should handle multiple line continuations', () => { | |
| 64 | + expect(extractCommand(` | |
| 65 | + echo hello && \\ | |
| 66 | + echo world && \\ | |
| 67 | + echo test | |
| 68 | + `)).toBe('echo hello && echo world && echo test'); | |
| 69 | + }); | |
| 70 | + | |
| 71 | + // Test nested line continuations | |
| 72 | + it('should handle nested line continuations', () => { | |
| 73 | + expect(extractCommand(` | |
| 74 | + echo hello && \\ | |
| 75 | + (echo nested && \\ | |
| 76 | + echo more) && \\ | |
| 77 | + echo final | |
| 78 | + `)).toBe('echo hello && (echo nested && echo more) && echo final'); | |
| 79 | + }); | |
| 80 | +}); | |
| No newline at the end of the file |
added gui/src/components/StyledMarkdownPreview/utils/commandExtractor.ts +50 −0
| @@ -0,0 +1,50 @@ | ||
| 1 | +/** | |
| 2 | + * Extracts and processes command strings, handling comments and line continuations. | |
| 3 | + * @param cmd The command string to process | |
| 4 | + * @returns The processed command string | |
| 5 | + */ | |
| 6 | +export function extractCommand(cmd: string): string { | |
| 7 | + if (!cmd || cmd.trim() === '') { | |
| 8 | + return ''; | |
| 9 | + } | |
| 10 | + | |
| 11 | + // Remove multi-line comments (/* ... */) and replace with a single space | |
| 12 | + cmd = cmd.replace(/\/\*[\s\S]*?\*\//g, " "); | |
| 13 | + | |
| 14 | + // Handle the $ prompt case first | |
| 15 | + if (cmd.includes("$")) { | |
| 16 | + const match = cmd.match(/\$\s*([^\n]+)/); | |
| 17 | + if (match) { | |
| 18 | + // Return just the command after $ without further processing | |
| 19 | + return match[1].trim(); | |
| 20 | + } | |
| 21 | + } | |
| 22 | + | |
| 23 | + // Process lines - remove single-line comments only at beginning of lines | |
| 24 | + const lines = cmd.split('\n') | |
| 25 | + .map(line => line.replace(/^\s*#.*$/, '').replace(/^\s*\/\/.*$/, '')) | |
| 26 | + .map(line => line.trim()) | |
| 27 | + .filter(line => line); | |
| 28 | + | |
| 29 | + // Join lines with proper handling of continuations | |
| 30 | + let result = ''; | |
| 31 | + for (let i = 0; i < lines.length; i++) { | |
| 32 | + let line = lines[i]; | |
| 33 | + | |
| 34 | + // Remove trailing continuation characters and join with next line | |
| 35 | + while ( | |
| 36 | + (line.endsWith('&&') || line.endsWith('|') || line.endsWith('\\')) && | |
| 37 | + i < lines.length - 1 | |
| 38 | + ) { | |
| 39 | + // Remove the continuation character(s) and any trailing spaces | |
| 40 | + line = line.replace(/(&&|\||\\)\s*$/, '').trim(); | |
| 41 | + // Join with the next line | |
| 42 | + i++; | |
| 43 | + line += ' ' + lines[i]; | |
| 44 | + } | |
| 45 | + | |
| 46 | + result += line + ' '; | |
| 47 | + } | |
| 48 | + | |
| 49 | + return result.trim().replace(/\s+/g, ' '); | |
| 50 | +} | |
| No newline at the end of the file |
modified gui/src/components/TabBar/TabBar.tsx +35 −50
| @@ -1,5 +1,5 @@ | ||
| 1 | 1 | import { XMarkIcon } from "@heroicons/react/24/outline"; |
| 2 | -import { useCallback, useEffect } from "react"; | |
| 2 | +import React, { useCallback, useEffect } from "react"; | |
| 3 | 3 | import { useDispatch, useSelector } from "react-redux"; |
| 4 | 4 | import styled from "styled-components"; |
| 5 | 5 | import { defaultBorderRadius } from ".."; |
| @@ -13,16 +13,30 @@ | ||
| 13 | 13 | } from "../../redux/slices/tabsSlice"; |
| 14 | 14 | import { AppDispatch, RootState } from "../../redux/store"; |
| 15 | 15 | import { loadSession, saveCurrentSession } from "../../redux/thunks/session"; |
| 16 | +import { varWithFallback } from "../../styles/theme"; | |
| 17 | + | |
| 18 | +// Haven't set up theme colors for tabs yet | |
| 19 | +// Will keep it simple and choose from existing ones. Comments show vars we could use | |
| 20 | +const tabBorderVar = varWithFallback("border"); // --vscode-tab-border | |
| 21 | +const tabBackgroundVar = varWithFallback("background"); // --vscode-tab-inactiveBackground | |
| 22 | +const tabForegroundVar = varWithFallback("foreground"); // --vscode-tab-inactiveForeground | |
| 23 | +const tabHoverBackgroundVar = varWithFallback("list-hover"); // --vscode-tab-hoverBackground | |
| 24 | +const tabHoverForegroundVar = varWithFallback("foreground"); // --vscode-tab-hoverForeground | |
| 25 | +const tabSelectedBackgroundVar = varWithFallback("background"); // --vscode-tab-activeBackground | |
| 26 | +const tabSelectedForegroundVar = varWithFallback("foreground"); // --vscode-tab-activeForeground | |
| 27 | +const tabAccentVar = varWithFallback("accent"); // --vscode-tab-activeBorderTop | |
| 16 | 28 | |
| 17 | 29 | const TabBarContainer = styled.div` |
| 18 | 30 | display: flex; |
| 19 | 31 | flex-wrap: wrap; |
| 20 | 32 | flex-shrink: 0; |
| 21 | 33 | flex-grow: 0; |
| 22 | - background-color: var(--vscode-tab-inactiveBackground); | |
| 34 | + background-color: ${tabBackgroundVar}; | |
| 23 | 35 | border-bottom: none; |
| 24 | 36 | position: relative; |
| 25 | 37 | margin-top: 2px; |
| 38 | + max-height: 100px; | |
| 39 | + overflow: auto; | |
| 26 | 40 | |
| 27 | 41 | /* Hide scrollbar but keep functionality */ |
| 28 | 42 | scrollbar-width: none; |
| @@ -41,24 +55,18 @@ | ||
| 41 | 55 | max-width: 150px; |
| 42 | 56 | height: 25px; |
| 43 | 57 | background-color: ${(props) => |
| 44 | - props.isActive | |
| 45 | - ? "var(--vscode-tab-activeBackground)" | |
| 46 | - : "var(--vscode-tab-inactiveBackground)"}; | |
| 58 | + props.isActive ? tabSelectedBackgroundVar : tabBackgroundVar}; | |
| 47 | 59 | color: ${(props) => |
| 48 | - props.isActive | |
| 49 | - ? "var(--vscode-tab-activeForeground)" | |
| 50 | - : "var(--vscode-tab-inactiveForeground)"}; | |
| 60 | + props.isActive ? tabSelectedForegroundVar : tabForegroundVar}; | |
| 51 | 61 | cursor: pointer; |
| 52 | - border: 1px solid var(--vscode-tab-border); | |
| 62 | + border: 1px solid ${tabBorderVar}; | |
| 53 | 63 | border-bottom: ${(props) => |
| 54 | - props.isActive ? "none" : `1px solid var(--vscode-tab-border)`}; | |
| 64 | + props.isActive ? "none" : `1px solid ${tabBorderVar}`}; | |
| 55 | 65 | user-select: none; |
| 56 | 66 | position: relative; |
| 57 | 67 | transition: background-color 0.2s; |
| 58 | 68 | border-top: ${(props) => |
| 59 | - props.isActive | |
| 60 | - ? `1px solid var(--vscode-tab-activeBorderTop, --vscode-tab-border)` | |
| 61 | - : `1px solid var(--vscode-tab-border)`}; | |
| 69 | + props.isActive ? `1px solid ${tabAccentVar}` : `1px solid ${tabBorderVar}`}; | |
| 62 | 70 | &:first-child { |
| 63 | 71 | border-left: none; |
| 64 | 72 | } |
| @@ -68,13 +76,9 @@ | ||
| 68 | 76 | |
| 69 | 77 | &:hover { |
| 70 | 78 | background-color: ${(props) => |
| 71 | - props.isActive | |
| 72 | - ? "var(--vscode-tab-activeBackground)" | |
| 73 | - : "var(--vscode-tab-hoverBackground)"}; | |
| 79 | + props.isActive ? tabSelectedBackgroundVar : tabHoverBackgroundVar}; | |
| 74 | 80 | color: ${(props) => |
| 75 | - props.isActive | |
| 76 | - ? "var(--vscode-tab-activeForeground)" | |
| 77 | - : "var(--vscode-tab-hoverForeground)"}; | |
| 81 | + props.isActive ? tabSelectedForegroundVar : tabHoverForegroundVar}; | |
| 78 | 82 | } |
| 79 | 83 | `; |
| 80 | 84 | |
| @@ -104,7 +108,7 @@ | ||
| 104 | 108 | |
| 105 | 109 | &:hover { |
| 106 | 110 | opacity: 1; |
| 107 | - background-color: var(--vscode-tab-hoverBackground); | |
| 111 | + background-color: ${tabHoverBackgroundVar}; | |
| 108 | 112 | } |
| 109 | 113 | |
| 110 | 114 | ${Tab}:hover & { |
| @@ -119,33 +123,12 @@ | ||
| 119 | 123 | const TabBarSpace = styled.div` |
| 120 | 124 | flex: 1; |
| 121 | 125 | display: flex; |
| 122 | - border-bottom: 1px solid var(--vscode-tab-border); | |
| 123 | - background-color: var(--vscode-tab-inactiveBackground); | |
| 126 | + border-bottom: 1px solid ${tabBorderVar}; | |
| 127 | + background-color: ${tabBackgroundVar}; | |
| 124 | 128 | `; |
| 125 | 129 | |
| 126 | -const NewTabButton = styled.button` | |
| 127 | - display: flex; | |
| 128 | - align-items: center; | |
| 129 | - justify-content: center; | |
| 130 | - width: 35px; | |
| 131 | - height: 100%; | |
| 132 | - border: none; | |
| 133 | - background: transparent; | |
| 134 | - color: var(--vscode-tab-inactiveForeground); | |
| 135 | - cursor: pointer; | |
| 136 | - opacity: 0.7; | |
| 137 | - transition: opacity 0.2s; | |
| 138 | - | |
| 139 | - &:hover { | |
| 140 | - opacity: 1; | |
| 141 | - background-color: var(--vscode-tab-hoverBackground); | |
| 142 | - color: var(--vscode-tab-hoverForeground); | |
| 143 | - } | |
| 144 | -`; | |
| 145 | - | |
| 146 | -export function TabBar() { | |
| 130 | +export const TabBar = React.forwardRef<HTMLDivElement>((_, ref) => { | |
| 147 | 131 | const dispatch = useDispatch<AppDispatch>(); |
| 148 | - const currentSession = useSelector((state: RootState) => state.session); | |
| 149 | 132 | const currentSessionId = useSelector((state: RootState) => state.session.id); |
| 150 | 133 | const currentSessionTitle = useSelector( |
| 151 | 134 | (state: RootState) => state.session.title, |
| @@ -160,7 +143,6 @@ | ||
| 160 | 143 | return Date.now().toString(36) + Math.random().toString(36).substring(2); |
| 161 | 144 | }, []); |
| 162 | 145 | |
| 163 | - // Handle session changes | |
| 164 | 146 | useEffect(() => { |
| 165 | 147 | if (!currentSessionId) return; |
| 166 | 148 | |
| @@ -243,10 +225,13 @@ | ||
| 243 | 225 | } |
| 244 | 226 | }; |
| 245 | 227 | |
| 246 | - return tabs.length === 1 ? ( | |
| 247 | - <></> | |
| 248 | - ) : ( | |
| 249 | - <TabBarContainer> | |
| 228 | + return ( | |
| 229 | + <TabBarContainer | |
| 230 | + ref={ref} | |
| 231 | + style={{ | |
| 232 | + display: tabs.length === 1 ? "none" : "flex", | |
| 233 | + }} | |
| 234 | + > | |
| 250 | 235 | {tabs.map((tab) => ( |
| 251 | 236 | <Tab |
| 252 | 237 | key={tab.id} |
| @@ -272,4 +257,4 @@ | ||
| 272 | 257 | </TabBarSpace> |
| 273 | 258 | </TabBarContainer> |
| 274 | 259 | ); |
| 275 | -} | |
| 260 | +}); |
modified gui/src/components/console/Details.tsx +27 −9
| @@ -1,4 +1,4 @@ | ||
| 1 | -import { useEffect, useRef } from "react"; | |
| 1 | +import { useEffect, useRef, useState } from "react"; | |
| 2 | 2 | import { LLMInteraction } from "../../hooks/useLLMLog"; |
| 3 | 3 | import useLLMSummary from "../../hooks/useLLMSummary"; |
| 4 | 4 | import End from "./End"; |
| @@ -50,6 +50,18 @@ | ||
| 50 | 50 | const scrollTop = useRef<HTMLDivElement>(null); |
| 51 | 51 | const lastResult = useRef<any>(null); |
| 52 | 52 | const summary = useLLMSummary(interaction); |
| 53 | + const [isAtBottom, setIsAtBottom] = useState(true); | |
| 54 | + | |
| 55 | + // Handler to check if user is at the bottom | |
| 56 | + function handleScroll() { | |
| 57 | + const elt = scrollTop.current; | |
| 58 | + if (!elt) { | |
| 59 | + return; | |
| 60 | + } | |
| 61 | + // Allow a small threshold for floating point errors | |
| 62 | + const threshold = 5; | |
| 63 | + setIsAtBottom((elt.scrollHeight - elt.scrollTop - elt.clientHeight) < threshold); | |
| 64 | + } | |
| 53 | 65 | |
| 54 | 66 | useEffect(() => { |
| 55 | 67 | if (interaction.end) { |
| @@ -59,15 +71,17 @@ | ||
| 59 | 71 | const last = interaction.results[interaction.results.length - 1]; |
| 60 | 72 | if (last != lastResult.current) { |
| 61 | 73 | lastResult.current = last; |
| 62 | - const lastChild = scrollTop.current?.lastChild; | |
| 63 | - if (lastChild) { | |
| 64 | - (lastChild as HTMLElement).scrollIntoView({ | |
| 65 | - behavior: "auto", | |
| 66 | - block: "end", | |
| 67 | - }); | |
| 74 | + if (isAtBottom) { | |
| 75 | + const lastChild = scrollTop.current?.lastChild; | |
| 76 | + if (lastChild) { | |
| 77 | + (lastChild as HTMLElement).scrollIntoView({ | |
| 78 | + behavior: "auto", | |
| 79 | + block: "end", | |
| 80 | + }); | |
| 81 | + } | |
| 68 | 82 | } |
| 69 | 83 | } |
| 70 | - }); | |
| 84 | + }, [interaction, isAtBottom]); | |
| 71 | 85 | |
| 72 | 86 | return ( |
| 73 | 87 | <div className="m-0 flex min-w-0 flex-1 shrink grow flex-col"> |
| @@ -102,7 +116,11 @@ | ||
| 102 | 116 | ></Cell> |
| 103 | 117 | </div> |
| 104 | 118 | </div> |
| 105 | - <div ref={scrollTop} className="grow overflow-auto"> | |
| 119 | + <div | |
| 120 | + ref={scrollTop} | |
| 121 | + className="grow overflow-auto" | |
| 122 | + onScroll={handleScroll} | |
| 123 | + > | |
| 106 | 124 | {interaction.start ? <Start item={interaction.start}></Start> : ""} |
| 107 | 125 | <div className="whitespace-pre-wrap p-2"> |
| 108 | 126 | {interaction.results.map((group, i) => { |
modified gui/src/components/dialogs/index.tsx +2 −3
| @@ -4,12 +4,11 @@ | ||
| 4 | 4 | import styled from "styled-components"; |
| 5 | 5 | import { |
| 6 | 6 | CloseButton, |
| 7 | - VSC_BACKGROUND_VAR, | |
| 8 | 7 | defaultBorderRadius, |
| 9 | - parseColorForHex, | |
| 10 | 8 | vscBackground, |
| 11 | 9 | vscForeground, |
| 12 | 10 | } from ".."; |
| 11 | +import { varWithFallback } from "../../styles/theme"; | |
| 13 | 12 | |
| 14 | 13 | interface TextDialogProps { |
| 15 | 14 | showDialog: boolean; |
| @@ -22,7 +21,7 @@ | ||
| 22 | 21 | position: fixed; |
| 23 | 22 | width: 100%; |
| 24 | 23 | height: 100%; |
| 25 | - background-color: ${parseColorForHex(VSC_BACKGROUND_VAR)}aa; | |
| 24 | + background-color: ${varWithFallback("background")}aa; | |
| 26 | 25 | z-index: 100000; |
| 27 | 26 | flex-direction: column; |
| 28 | 27 | `; |
modified gui/src/components/find/FindWidget.tsx +126 −292
| @@ -13,35 +13,24 @@ | ||
| 13 | 13 | } from "react"; |
| 14 | 14 | import { HeaderButton, Input } from ".."; |
| 15 | 15 | import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; |
| 16 | -import { useAppSelector } from "../../redux/hooks"; | |
| 17 | - | |
| 18 | -interface SearchMatch { | |
| 19 | - index: number; | |
| 20 | - textNode: Text; | |
| 21 | - overlayRectangle: Rectangle; | |
| 22 | -} | |
| 23 | - | |
| 24 | -type ScrollToMatchOption = "closest" | "first" | "none"; | |
| 25 | - | |
| 26 | -const SEARCH_DEBOUNCE = 300; | |
| 27 | -const RESIZE_DEBOUNCE = 200; | |
| 28 | - | |
| 29 | -interface Rectangle { | |
| 30 | - top: number; | |
| 31 | - left: number; | |
| 32 | - width: number; | |
| 33 | - height: number; | |
| 34 | -} | |
| 35 | - | |
| 36 | -interface HighlightOverlayProps extends Rectangle { | |
| 16 | +import { | |
| 17 | + Rectangle, | |
| 18 | + SearchMatch, | |
| 19 | + searchWithinContainer, | |
| 20 | +} from "./findWidgetSearch"; | |
| 21 | +import useDebounceValue from "./useDebounce"; | |
| 22 | +import { useElementSize } from "./useElementSize"; | |
| 23 | + | |
| 24 | +interface HighlightOverlayProps { | |
| 25 | + rectangle: Rectangle; | |
| 37 | 26 | isCurrent: boolean; |
| 38 | 27 | } |
| 39 | 28 | |
| 40 | 29 | const HighlightOverlay = (props: HighlightOverlayProps) => { |
| 41 | - const { isCurrent, top, left, width, height } = props; | |
| 30 | + const { top, left, width, height } = props.rectangle; | |
| 42 | 31 | return ( |
| 43 | 32 | <div |
| 44 | - className={isCurrent ? "bg-find-match-selected" : "bg-blue-200/30"} // bg-vsc-find-match can"t get to work | |
| 33 | + className={props.isCurrent ? "bg-findMatch-selected" : "bg-findMatch"} | |
| 45 | 34 | key={`highlight-${top}-${left}`} |
| 46 | 35 | style={{ |
| 47 | 36 | position: "absolute", |
| @@ -56,6 +45,8 @@ | ||
| 56 | 45 | ); |
| 57 | 46 | }; |
| 58 | 47 | |
| 48 | +type ScrollToMatchOption = "closest" | "first" | "none"; | |
| 49 | + | |
| 59 | 50 | /* |
| 60 | 51 | useFindWidget takes a container ref and returns |
| 61 | 52 | 1. A widget that can be placed anywhere to search the contents of that container |
| @@ -64,18 +55,22 @@ | ||
| 64 | 55 | |
| 65 | 56 | Container must have relative positioning |
| 66 | 57 | */ |
| 67 | -export const useFindWidget = (searchRef: RefObject<HTMLDivElement>) => { | |
| 58 | +export const useFindWidget = ( | |
| 59 | + searchRef: RefObject<HTMLDivElement>, | |
| 60 | + headerRef: RefObject<HTMLDivElement>, | |
| 61 | + disabled: boolean, | |
| 62 | +) => { | |
| 68 | 63 | // Search input, debounced |
| 69 | - const [input, setInput] = useState<string>(""); | |
| 70 | - const debouncedInput = useRef<string>(""); | |
| 71 | 64 | const inputRef = useRef<HTMLInputElement>(null); |
| 65 | + const [currentValue, setCurrentValue] = useState<string>(""); | |
| 66 | + const searchTerm = useDebounceValue(currentValue, 300); | |
| 72 | 67 | |
| 73 | 68 | // Widget open/closed state |
| 74 | 69 | const [open, setOpen] = useState<boolean>(false); |
| 75 | 70 | const openWidget = useCallback(() => { |
| 76 | 71 | setOpen(true); |
| 77 | 72 | inputRef?.current?.select(); |
| 78 | - }, [setOpen, inputRef]); | |
| 73 | + }, [inputRef]); | |
| 79 | 74 | |
| 80 | 75 | // Search settings and results |
| 81 | 76 | const [caseSensitive, setCaseSensitive] = useState<boolean>(false); |
| @@ -97,7 +92,7 @@ | ||
| 97 | 92 | behavior: "smooth", |
| 98 | 93 | }); |
| 99 | 94 | }, |
| 100 | - [searchRef.current], | |
| 95 | + [searchRef], | |
| 101 | 96 | ); |
| 102 | 97 | |
| 103 | 98 | const nextMatch = useCallback(() => { |
| @@ -143,327 +138,166 @@ | ||
| 143 | 138 | }, [inputRef, matches, nextMatch]); |
| 144 | 139 | |
| 145 | 140 | // Handle container resize changes - highlight positions must adjust |
| 146 | - const [isResizing, setIsResizing] = useState(false); | |
| 147 | - useEffect(() => { | |
| 148 | - let timeoutId: NodeJS.Timeout | null = null; | |
| 149 | - if (!searchRef?.current) return; | |
| 150 | - | |
| 151 | - const resizeObserver = new ResizeObserver((entries) => { | |
| 152 | - if (timeoutId) { | |
| 153 | - clearTimeout(timeoutId); | |
| 154 | - } | |
| 155 | - setIsResizing(true); | |
| 156 | - timeoutId = setTimeout(() => { | |
| 157 | - setIsResizing(false); | |
| 158 | - }, RESIZE_DEBOUNCE); | |
| 159 | - }); | |
| 160 | - | |
| 161 | - resizeObserver.observe(searchRef.current); | |
| 162 | - return () => { | |
| 163 | - if (timeoutId) { | |
| 164 | - clearTimeout(timeoutId); | |
| 165 | - } | |
| 166 | - if (searchRef.current) resizeObserver.unobserve(searchRef.current); | |
| 167 | - }; | |
| 168 | - }, [searchRef.current]); | |
| 141 | + const { clientHeight: headerHeight, isResizing: headerResizing } = | |
| 142 | + useElementSize(headerRef); | |
| 143 | + const { isResizing: containerResizing } = useElementSize(searchRef); | |
| 144 | + const isResizing = useMemo(() => { | |
| 145 | + return containerResizing || headerResizing; | |
| 146 | + }, [containerResizing, headerResizing]); | |
| 169 | 147 | |
| 170 | 148 | // Main function for finding matches and generating highlight overlays |
| 171 | 149 | const refreshSearch = useCallback( |
| 172 | - (scrollTo: ScrollToMatchOption = "none", clearFirst = false) => { | |
| 173 | - if (clearFirst) setMatches([]); | |
| 174 | - | |
| 175 | - const searchContainer = searchRef.current; | |
| 176 | - | |
| 177 | - const _query = debouncedInput.current; // trimStart - decided no because spaces should be fully searchable | |
| 178 | - if (!searchContainer || !_query) { | |
| 179 | - setMatches([]); | |
| 180 | - return; | |
| 181 | - } | |
| 182 | - const query = caseSensitive ? _query : _query.toLowerCase(); | |
| 183 | - | |
| 184 | - // First grab all text nodes | |
| 185 | - // Skips any elements with the "find-widget-skip" class | |
| 186 | - const textNodes: Text[] = []; | |
| 187 | - const walker = document.createTreeWalker( | |
| 188 | - searchRef.current, | |
| 189 | - NodeFilter.SHOW_ALL, | |
| 150 | + (scrollTo: ScrollToMatchOption = "none") => { | |
| 151 | + const { results, closestToMiddle } = searchWithinContainer( | |
| 152 | + searchRef, | |
| 153 | + searchTerm, | |
| 190 | 154 | { |
| 191 | - acceptNode: (node) => { | |
| 192 | - if (node.nodeType === Node.ELEMENT_NODE) { | |
| 193 | - if ((node as Element).classList.contains("find-widget-skip")) | |
| 194 | - return NodeFilter.FILTER_REJECT; | |
| 195 | - return NodeFilter.FILTER_ACCEPT; | |
| 196 | - } else if (node.nodeType === Node.TEXT_NODE) { | |
| 197 | - if (!node.nodeValue) return NodeFilter.FILTER_REJECT; | |
| 198 | - const nodeValue = caseSensitive | |
| 199 | - ? node.nodeValue | |
| 200 | - : node.nodeValue.toLowerCase(); | |
| 201 | - if (nodeValue.includes(query)) return NodeFilter.FILTER_ACCEPT; | |
| 202 | - } | |
| 203 | - return NodeFilter.FILTER_REJECT; | |
| 204 | - }, | |
| 155 | + caseSensitive, | |
| 156 | + useRegex, | |
| 157 | + offsetHeight: headerHeight, | |
| 205 | 158 | }, |
| 206 | 159 | ); |
| 207 | - | |
| 208 | - while (walker.nextNode()) { | |
| 209 | - if (walker.currentNode.nodeType === Node.ELEMENT_NODE) continue; | |
| 210 | - textNodes.push(walker.currentNode as Text); | |
| 211 | - } | |
| 212 | - | |
| 213 | - // Now walk through each node match and extract search results | |
| 214 | - // One node can have several matches | |
| 215 | - const newMatches: SearchMatch[] = []; | |
| 216 | - textNodes.forEach((textNode, idx) => { | |
| 217 | - // Hacky way to detect code blocks that be wider than client and cause absolute positioning to fail | |
| 218 | - const highlightFullLine = | |
| 219 | - textNode.parentElement?.className.includes("hljs"); | |
| 220 | - | |
| 221 | - let nodeTextValue = caseSensitive | |
| 222 | - ? textNode.nodeValue | |
| 223 | - : textNode.nodeValue.toLowerCase(); | |
| 224 | - let startIndex = 0; | |
| 225 | - while ((startIndex = nodeTextValue.indexOf(query, startIndex)) !== -1) { | |
| 226 | - // Create a range to measure the size and position of the match | |
| 227 | - const range = document.createRange(); | |
| 228 | - range.setStart(textNode, startIndex); | |
| 229 | - const endIndex = startIndex + query.length; | |
| 230 | - range.setEnd(textNode, endIndex); | |
| 231 | - const rect = range.getBoundingClientRect(); | |
| 232 | - range.detach(); | |
| 233 | - startIndex = endIndex; | |
| 234 | - | |
| 235 | - const top = | |
| 236 | - rect.top + searchContainer.clientTop + searchContainer.scrollTop; | |
| 237 | - const left = | |
| 238 | - rect.left + searchContainer.clientLeft + searchContainer.scrollLeft; | |
| 239 | - | |
| 240 | - // Build a match result and push to matches | |
| 241 | - const newMatch: SearchMatch = { | |
| 242 | - index: 0, // will set later | |
| 243 | - textNode, | |
| 244 | - overlayRectangle: { | |
| 245 | - top, | |
| 246 | - left: highlightFullLine ? 2 : left, | |
| 247 | - width: highlightFullLine | |
| 248 | - ? searchContainer.clientWidth - 4 | |
| 249 | - : rect.width, // equivalent of adding 2 px x padding | |
| 250 | - height: rect.height, | |
| 251 | - }, | |
| 252 | - }; | |
| 253 | - newMatches.push(newMatch); | |
| 254 | - | |
| 255 | - if (highlightFullLine) { | |
| 256 | - break; // Since highlighting full line no need for multiple overlays, will cause darker highlight | |
| 257 | - } | |
| 258 | - } | |
| 259 | - }); | |
| 260 | - | |
| 261 | - // There will still be duplicate full lines when multiple text nodes are in the same line (e.g. Code highlights) | |
| 262 | - // Filter them out by using the overlay rectangle as a hash key | |
| 263 | - const matchHash = Object.fromEntries( | |
| 264 | - newMatches.map((match) => [ | |
| 265 | - JSON.stringify(match.overlayRectangle), | |
| 266 | - match, | |
| 267 | - ]), | |
| 268 | - ); | |
| 269 | - const filteredMatches = Object.values(matchHash).map((match, index) => ({ | |
| 270 | - ...match, | |
| 271 | - index, | |
| 272 | - })); | |
| 273 | - | |
| 160 | + setMatches(results); | |
| 274 | 161 | // Find match closest to the middle of the view |
| 275 | - const verticalMiddle = | |
| 276 | - searchRef.current.scrollTop + searchRef.current.clientHeight / 2; | |
| 277 | - let closestDist = Infinity; | |
| 278 | - let closestMatchToMiddle: SearchMatch | null = null; | |
| 279 | - filteredMatches.forEach((match) => { | |
| 280 | - const dist = Math.abs(verticalMiddle - match.overlayRectangle.top); | |
| 281 | - if (dist < closestDist) { | |
| 282 | - closestDist = dist; | |
| 283 | - closestMatchToMiddle = match; | |
| 284 | - } | |
| 285 | - }); | |
| 286 | - | |
| 287 | - // Update matches and scroll to the closest or first match | |
| 288 | - setMatches(filteredMatches); | |
| 289 | - if (query.length > 1 && filteredMatches.length) { | |
| 162 | + if (searchTerm.length > 1 && results.length) { | |
| 290 | 163 | if (scrollTo === "first") { |
| 291 | - scrollToMatch(filteredMatches[0]); | |
| 164 | + scrollToMatch(results[0]); | |
| 292 | 165 | } |
| 293 | 166 | if (scrollTo === "closest") { |
| 294 | - if (closestMatchToMiddle) { | |
| 295 | - scrollToMatch(closestMatchToMiddle); | |
| 167 | + if (closestToMiddle) { | |
| 168 | + scrollToMatch(closestToMiddle); | |
| 296 | 169 | } |
| 297 | 170 | } |
| 298 | 171 | if (scrollTo === "none") { |
| 299 | - if (closestMatchToMiddle) { | |
| 300 | - setCurrentMatch(closestMatchToMiddle); | |
| 172 | + if (closestToMiddle) { | |
| 173 | + setCurrentMatch(closestToMiddle); | |
| 301 | 174 | } else { |
| 302 | - setCurrentMatch(filteredMatches[0]); | |
| 175 | + setCurrentMatch(results[0]); | |
| 303 | 176 | } |
| 304 | 177 | } |
| 305 | 178 | } |
| 306 | 179 | }, |
| 307 | - [searchRef.current, debouncedInput, scrollToMatch, caseSensitive, useRegex], | |
| 180 | + [ | |
| 181 | + searchTerm, | |
| 182 | + caseSensitive, | |
| 183 | + useRegex, | |
| 184 | + searchRef, | |
| 185 | + headerHeight, | |
| 186 | + scrollToMatch, | |
| 187 | + ], | |
| 308 | 188 | ); |
| 309 | 189 | |
| 310 | 190 | // Triggers that should cause immediate refresh of results to closest search value: |
| 311 | - // Input change (debounced) and window click | |
| 312 | - const lastUpdateRef = useRef(0); | |
| 313 | 191 | useEffect(() => { |
| 314 | - const debounce = () => { | |
| 315 | - debouncedInput.current = input; | |
| 316 | - lastUpdateRef.current = Date.now(); | |
| 317 | - refreshSearch("closest"); | |
| 318 | - }; | |
| 319 | - const timeSinceLastUpdate = Date.now() - lastUpdateRef.current; | |
| 320 | - if (timeSinceLastUpdate >= SEARCH_DEBOUNCE) { | |
| 321 | - debounce(); | |
| 192 | + if (disabled || isResizing || !open) { | |
| 193 | + setMatches([]); | |
| 322 | 194 | } else { |
| 323 | - const handler = setTimeout(() => { | |
| 324 | - debounce(); | |
| 325 | - }, SEARCH_DEBOUNCE - timeSinceLastUpdate); | |
| 326 | - return () => { | |
| 327 | - clearTimeout(handler); | |
| 328 | - }; | |
| 195 | + refreshSearch("closest"); | |
| 329 | 196 | } |
| 330 | - }, [refreshSearch, input]); | |
| 197 | + }, [refreshSearch, open, disabled, isResizing]); | |
| 331 | 198 | |
| 332 | - // Could consider doing any window click but I only handled search div here | |
| 333 | - // Since usually only clicks in search div will cause content changes in search div | |
| 199 | + // Clicks in search div can cause content changes that for some reason don't trigger resize | |
| 200 | + // Refresh clicking within container | |
| 334 | 201 | useEffect(() => { |
| 335 | 202 | const searchContainer = searchRef.current; |
| 336 | 203 | if (!open || !searchContainer) return; |
| 337 | 204 | const handleSearchRefClick = () => { |
| 338 | - refreshSearch("none"); | |
| 205 | + setTimeout(() => { | |
| 206 | + refreshSearch("none"); | |
| 207 | + }, 150); | |
| 339 | 208 | }; |
| 340 | 209 | searchContainer.addEventListener("click", handleSearchRefClick); |
| 341 | 210 | return () => { |
| 342 | 211 | searchContainer.removeEventListener("click", handleSearchRefClick); |
| 343 | 212 | }; |
| 344 | - }, [searchRef.current, refreshSearch, open]); | |
| 345 | - | |
| 346 | - // Triggers that should cause results to temporarily disappear and then reload | |
| 347 | - // Active = LLM is generating, etc. | |
| 348 | - const active = useAppSelector((state) => state.session.isStreaming); | |
| 349 | - | |
| 350 | - useEffect(() => { | |
| 351 | - if (active || isResizing) setMatches([]); | |
| 352 | - else refreshSearch("none"); | |
| 353 | - }, [refreshSearch, active]); | |
| 354 | - | |
| 355 | - useEffect(() => { | |
| 356 | - if (!open) setMatches([]); | |
| 357 | - else refreshSearch("closest"); | |
| 358 | - }, [refreshSearch, open]); | |
| 359 | - | |
| 360 | - useEffect(() => { | |
| 361 | - refreshSearch("closest"); | |
| 362 | - }, [refreshSearch, caseSensitive, useRegex]); | |
| 213 | + }, [searchRef, refreshSearch, open]); | |
| 363 | 214 | |
| 364 | 215 | // Find widget component |
| 365 | - const widget = useMemo(() => { | |
| 366 | - return ( | |
| 367 | - <div | |
| 368 | - className={`fixed top-0 z-50 transition-all ${open ? "" : "-translate-y-full"} bg-vsc-background right-0 flex flex-row items-center gap-1.5 rounded-bl-lg border-0 border-b border-l border-solid border-zinc-700 pl-[3px] pr-3 sm:gap-2`} | |
| 369 | - > | |
| 370 | - <Input | |
| 371 | - disabled={active} | |
| 372 | - type="text" | |
| 373 | - ref={inputRef} | |
| 374 | - value={input} | |
| 375 | - onChange={(e) => { | |
| 376 | - setInput(e.target.value); | |
| 377 | - }} | |
| 378 | - placeholder="Search..." | |
| 379 | - /> | |
| 380 | - <p className="xs:block hidden min-w-12 whitespace-nowrap px-1 text-center text-xs"> | |
| 381 | - {matches.length === 0 | |
| 382 | - ? "No results" | |
| 383 | - : `${(currentMatch?.index ?? 0) + 1} of ${matches.length}`} | |
| 384 | - </p> | |
| 385 | - <div className="hidden flex-row gap-0.5 sm:flex"> | |
| 386 | - <HeaderButtonWithToolTip | |
| 387 | - tooltipPlacement="top-end" | |
| 388 | - text={"Previous Match"} | |
| 389 | - onClick={(e) => { | |
| 390 | - e.stopPropagation(); | |
| 391 | - previousMatch(); | |
| 392 | - }} | |
| 393 | - className="h-4 w-4 focus:ring" | |
| 394 | - disabled={matches.length < 2 || active} | |
| 395 | - > | |
| 396 | - <ArrowUpIcon className="h-4 w-4" /> | |
| 397 | - </HeaderButtonWithToolTip> | |
| 398 | - <HeaderButtonWithToolTip | |
| 399 | - tooltipPlacement="top-end" | |
| 400 | - text={"Next Match"} | |
| 401 | - onClick={(e) => { | |
| 402 | - e.stopPropagation(); | |
| 403 | - nextMatch(); | |
| 404 | - }} | |
| 405 | - className="h-4 w-4 focus:ring" | |
| 406 | - disabled={matches.length < 2 || active} | |
| 407 | - > | |
| 408 | - <ArrowDownIcon className="h-4 w-4" /> | |
| 409 | - </HeaderButtonWithToolTip> | |
| 410 | - </div> | |
| 216 | + const widget = ( | |
| 217 | + <div | |
| 218 | + className={`fixed top-0 z-50 transition-all ${open ? "" : "-translate-y-full"} bg-vsc-background right-0 flex flex-row items-center gap-1.5 rounded-bl-lg border-0 border-b border-l border-solid border-zinc-700 pl-[3px] pr-3 sm:gap-2`} | |
| 219 | + > | |
| 220 | + <Input | |
| 221 | + disabled={disabled} | |
| 222 | + type="text" | |
| 223 | + ref={inputRef} | |
| 224 | + value={currentValue} | |
| 225 | + onChange={(e) => { | |
| 226 | + setCurrentValue(e.target.value); | |
| 227 | + }} | |
| 228 | + placeholder="Search..." | |
| 229 | + /> | |
| 230 | + <p className="xs:block hidden min-w-12 whitespace-nowrap px-1 text-center text-xs"> | |
| 231 | + {matches.length === 0 | |
| 232 | + ? "No results" | |
| 233 | + : `${(currentMatch?.index ?? 0) + 1} of ${matches.length}`} | |
| 234 | + </p> | |
| 235 | + <div className="hidden flex-row gap-0.5 sm:flex"> | |
| 411 | 236 | <HeaderButtonWithToolTip |
| 412 | - disabled={active} | |
| 413 | - inverted={caseSensitive} | |
| 414 | 237 | tooltipPlacement="top-end" |
| 415 | - text={ | |
| 416 | - caseSensitive | |
| 417 | - ? "Turn off case sensitivity" | |
| 418 | - : "Turn on case sensitivity" | |
| 419 | - } | |
| 238 | + text={"Previous Match"} | |
| 420 | 239 | onClick={(e) => { |
| 421 | 240 | e.stopPropagation(); |
| 422 | - setCaseSensitive((curr) => !curr); | |
| 241 | + previousMatch(); | |
| 423 | 242 | }} |
| 424 | - className="h-5 w-6 rounded-full border text-xs focus:outline-none focus:ring" | |
| 243 | + className="h-4 w-4 focus:ring" | |
| 244 | + disabled={matches.length < 2 || disabled} | |
| 425 | 245 | > |
| 426 | - Aa | |
| 246 | + <ArrowUpIcon className="h-4 w-4" /> | |
| 427 | 247 | </HeaderButtonWithToolTip> |
| 428 | - {/* TODO - add useRegex functionality */} | |
| 429 | - <HeaderButton | |
| 430 | - inverted={false} | |
| 431 | - onClick={() => setOpen(false)} | |
| 432 | - className="focus:ring" | |
| 248 | + <HeaderButtonWithToolTip | |
| 249 | + tooltipPlacement="top-end" | |
| 250 | + text={"Next Match"} | |
| 251 | + onClick={(e) => { | |
| 252 | + e.stopPropagation(); | |
| 253 | + nextMatch(); | |
| 254 | + }} | |
| 255 | + className="h-4 w-4 focus:ring" | |
| 256 | + disabled={matches.length < 2 || disabled} | |
| 433 | 257 | > |
| 434 | - <XMarkIcon className="h-4 w-4" /> | |
| 435 | - </HeaderButton> | |
| 258 | + <ArrowDownIcon className="h-4 w-4" /> | |
| 259 | + </HeaderButtonWithToolTip> | |
| 436 | 260 | </div> |
| 437 | - ); | |
| 438 | - }, [ | |
| 439 | - open, | |
| 440 | - input, | |
| 441 | - inputRef, | |
| 442 | - caseSensitive, | |
| 443 | - matches, | |
| 444 | - currentMatch, | |
| 445 | - previousMatch, | |
| 446 | - nextMatch, | |
| 447 | - ]); | |
| 261 | + <HeaderButtonWithToolTip | |
| 262 | + disabled={disabled} | |
| 263 | + inverted={caseSensitive} | |
| 264 | + tooltipPlacement="top-end" | |
| 265 | + text={ | |
| 266 | + caseSensitive | |
| 267 | + ? "Turn off case sensitivity" | |
| 268 | + : "Turn on case sensitivity" | |
| 269 | + } | |
| 270 | + onClick={(e) => { | |
| 271 | + e.stopPropagation(); | |
| 272 | + setCaseSensitive((curr) => !curr); | |
| 273 | + }} | |
| 274 | + className="h-5 w-6 rounded-full border text-xs focus:outline-none focus:ring" | |
| 275 | + > | |
| 276 | + Aa | |
| 277 | + </HeaderButtonWithToolTip> | |
| 278 | + {/* TODO - add useRegex functionality */} | |
| 279 | + <HeaderButton | |
| 280 | + inverted={false} | |
| 281 | + onClick={() => setOpen(false)} | |
| 282 | + className="focus:ring" | |
| 283 | + > | |
| 284 | + <XMarkIcon className="h-4 w-4" /> | |
| 285 | + </HeaderButton> | |
| 286 | + </div> | |
| 287 | + ); | |
| 448 | 288 | |
| 449 | 289 | // Generate the highlight overlay elements |
| 450 | 290 | const highlights = useMemo(() => { |
| 451 | 291 | return matches.map((match) => ( |
| 452 | 292 | <HighlightOverlay |
| 453 | - {...match.overlayRectangle} | |
| 293 | + rectangle={match.overlayRectangle} | |
| 454 | 294 | isCurrent={currentMatch?.index === match.index} |
| 455 | 295 | /> |
| 456 | 296 | )); |
| 457 | 297 | }, [matches, currentMatch]); |
| 458 | 298 | |
| 459 | 299 | return { |
| 460 | - matches, | |
| 461 | 300 | highlights, |
| 462 | - inputRef, | |
| 463 | - input: debouncedInput, | |
| 464 | - setInput, | |
| 465 | - open, | |
| 466 | - setOpen, | |
| 467 | 301 | widget, |
| 468 | 302 | }; |
| 469 | 303 | }; |
added gui/src/components/find/findWidgetSearch.ts +146 −0
| @@ -0,0 +1,146 @@ | ||
| 1 | +export interface Rectangle { | |
| 2 | + top: number; | |
| 3 | + left: number; | |
| 4 | + width: number; | |
| 5 | + height: number; | |
| 6 | +} | |
| 7 | + | |
| 8 | +export interface SearchMatch { | |
| 9 | + index: number; | |
| 10 | + textNode: Text; | |
| 11 | + overlayRectangle: Rectangle; | |
| 12 | +} | |
| 13 | + | |
| 14 | +interface SearchOptions { | |
| 15 | + caseSensitive: boolean; | |
| 16 | + useRegex: boolean; | |
| 17 | + offsetHeight: number; | |
| 18 | +} | |
| 19 | + | |
| 20 | +export const searchWithinContainer = ( | |
| 21 | + containerRef: React.RefObject<HTMLDivElement>, | |
| 22 | + searchQuery: string, | |
| 23 | + options: SearchOptions, | |
| 24 | +): { | |
| 25 | + results: SearchMatch[]; | |
| 26 | + closestToMiddle: SearchMatch | null; | |
| 27 | +} => { | |
| 28 | + const searchContainer = containerRef.current; | |
| 29 | + | |
| 30 | + if (!searchContainer || !searchQuery) { | |
| 31 | + return { | |
| 32 | + results: [], | |
| 33 | + closestToMiddle: null, | |
| 34 | + }; | |
| 35 | + } | |
| 36 | + const query = options.caseSensitive ? searchQuery : searchQuery.toLowerCase(); | |
| 37 | + | |
| 38 | + // First grab all text nodes | |
| 39 | + // Skips any elements with the "find-widget-skip" class | |
| 40 | + const textNodes: Text[] = []; | |
| 41 | + const walker = document.createTreeWalker( | |
| 42 | + searchContainer, | |
| 43 | + NodeFilter.SHOW_ALL, | |
| 44 | + { | |
| 45 | + acceptNode: (node) => { | |
| 46 | + if (node.nodeType === Node.ELEMENT_NODE) { | |
| 47 | + if ((node as Element).classList.contains("find-widget-skip")) | |
| 48 | + return NodeFilter.FILTER_REJECT; | |
| 49 | + return NodeFilter.FILTER_ACCEPT; | |
| 50 | + } else if (node.nodeType === Node.TEXT_NODE) { | |
| 51 | + if (!node.nodeValue) return NodeFilter.FILTER_REJECT; | |
| 52 | + const nodeValue = options.caseSensitive | |
| 53 | + ? node.nodeValue | |
| 54 | + : node.nodeValue.toLowerCase(); | |
| 55 | + if (nodeValue.includes(query)) return NodeFilter.FILTER_ACCEPT; | |
| 56 | + } | |
| 57 | + return NodeFilter.FILTER_REJECT; | |
| 58 | + }, | |
| 59 | + }, | |
| 60 | + ); | |
| 61 | + | |
| 62 | + while (walker.nextNode()) { | |
| 63 | + if (walker.currentNode.nodeType === Node.ELEMENT_NODE) continue; | |
| 64 | + textNodes.push(walker.currentNode as Text); | |
| 65 | + } | |
| 66 | + | |
| 67 | + // Now walk through each node match and extract search results | |
| 68 | + // One node can have several matches | |
| 69 | + const newMatches: SearchMatch[] = []; | |
| 70 | + textNodes.forEach((textNode, idx) => { | |
| 71 | + // Hacky way to detect code blocks that be wider than client and cause absolute positioning to fail | |
| 72 | + const highlightFullLine = | |
| 73 | + textNode.parentElement?.className.includes("hljs"); | |
| 74 | + | |
| 75 | + let nodeTextValue = options.caseSensitive | |
| 76 | + ? textNode.nodeValue | |
| 77 | + : textNode.nodeValue.toLowerCase(); | |
| 78 | + let startIndex = 0; | |
| 79 | + while ((startIndex = nodeTextValue.indexOf(query, startIndex)) !== -1) { | |
| 80 | + // Create a range to measure the size and position of the match | |
| 81 | + const range = document.createRange(); | |
| 82 | + range.setStart(textNode, startIndex); | |
| 83 | + const endIndex = startIndex + query.length; | |
| 84 | + range.setEnd(textNode, endIndex); | |
| 85 | + const rect = range.getBoundingClientRect(); | |
| 86 | + range.detach(); | |
| 87 | + startIndex = endIndex; | |
| 88 | + | |
| 89 | + const top = | |
| 90 | + rect.top + | |
| 91 | + searchContainer.clientTop + | |
| 92 | + searchContainer.scrollTop - | |
| 93 | + options.offsetHeight; | |
| 94 | + | |
| 95 | + const left = | |
| 96 | + rect.left + searchContainer.clientLeft + searchContainer.scrollLeft; | |
| 97 | + | |
| 98 | + // Build a match result and push to matches | |
| 99 | + const newMatch: SearchMatch = { | |
| 100 | + index: 0, // will set later | |
| 101 | + textNode, | |
| 102 | + overlayRectangle: { | |
| 103 | + top, | |
| 104 | + left: highlightFullLine ? 2 : left, | |
| 105 | + width: highlightFullLine | |
| 106 | + ? searchContainer.clientWidth - 4 | |
| 107 | + : rect.width, // equivalent of adding 2 px x padding | |
| 108 | + height: rect.height, | |
| 109 | + }, | |
| 110 | + }; | |
| 111 | + newMatches.push(newMatch); | |
| 112 | + | |
| 113 | + if (highlightFullLine) { | |
| 114 | + break; // Since highlighting full line no need for multiple overlays, will cause darker highlight | |
| 115 | + } | |
| 116 | + } | |
| 117 | + }); | |
| 118 | + | |
| 119 | + // There will still be duplicate full lines when multiple text nodes are in the same line (e.g. Code highlights) | |
| 120 | + // Filter them out by using the overlay rectangle as a hash key | |
| 121 | + const matchHash = Object.fromEntries( | |
| 122 | + newMatches.map((match) => [JSON.stringify(match.overlayRectangle), match]), | |
| 123 | + ); | |
| 124 | + const filteredMatches = Object.values(matchHash).map((match, index) => ({ | |
| 125 | + ...match, | |
| 126 | + index, | |
| 127 | + })); | |
| 128 | + | |
| 129 | + // Find the match closest to the vertical middle of the container | |
| 130 | + const verticalMiddle = | |
| 131 | + searchContainer.scrollTop + searchContainer.clientHeight / 2; | |
| 132 | + let closestDist = Infinity; | |
| 133 | + let closestMatchToMiddle: SearchMatch | null = null; | |
| 134 | + filteredMatches.forEach((match) => { | |
| 135 | + const dist = Math.abs(verticalMiddle - match.overlayRectangle.top); | |
| 136 | + if (dist < closestDist) { | |
| 137 | + closestDist = dist; | |
| 138 | + closestMatchToMiddle = match; | |
| 139 | + } | |
| 140 | + }); | |
| 141 | + | |
| 142 | + return { | |
| 143 | + results: filteredMatches, | |
| 144 | + closestToMiddle: closestMatchToMiddle, | |
| 145 | + }; | |
| 146 | +}; |
added gui/src/components/find/useDebounce.ts +19 −0
| @@ -0,0 +1,19 @@ | ||
| 1 | +import { useEffect, useState } from "react"; | |
| 2 | + | |
| 3 | +function useDebounceValue<T>(value: T, delay: number = 500): T { | |
| 4 | + const [debouncedValue, setDebouncedValue] = useState<T>(value); | |
| 5 | + | |
| 6 | + useEffect(() => { | |
| 7 | + const timer = setTimeout(() => { | |
| 8 | + setDebouncedValue(value); | |
| 9 | + }, delay); | |
| 10 | + | |
| 11 | + return () => { | |
| 12 | + clearTimeout(timer); | |
| 13 | + }; | |
| 14 | + }, [value, delay]); | |
| 15 | + | |
| 16 | + return debouncedValue; | |
| 17 | +} | |
| 18 | + | |
| 19 | +export default useDebounceValue; |
added gui/src/components/find/useElementSize.ts +81 −0
| @@ -0,0 +1,81 @@ | ||
| 1 | +import { RefObject, useCallback, useEffect, useState } from "react"; | |
| 2 | + | |
| 3 | +interface ElementSize { | |
| 4 | + clientWidth: number; | |
| 5 | + clientHeight: number; | |
| 6 | + scrollWidth: number; | |
| 7 | + scrollHeight: number; | |
| 8 | + isResizing: boolean; | |
| 9 | +} | |
| 10 | + | |
| 11 | +interface UseElementSizeOptions { | |
| 12 | + debounceMs?: number; | |
| 13 | +} | |
| 14 | + | |
| 15 | +export const useElementSize = ( | |
| 16 | + ref: RefObject<HTMLElement>, | |
| 17 | + debounceMs = 250, | |
| 18 | +): ElementSize => { | |
| 19 | + const [size, setSize] = useState<ElementSize>({ | |
| 20 | + clientWidth: 0, | |
| 21 | + clientHeight: 0, | |
| 22 | + scrollWidth: 0, | |
| 23 | + scrollHeight: 0, | |
| 24 | + isResizing: false, | |
| 25 | + }); | |
| 26 | + | |
| 27 | + // Debounced update function | |
| 28 | + const debouncedSetSize = useCallback( | |
| 29 | + (measurements: Omit<ElementSize, "isResizing">) => { | |
| 30 | + let timeoutId: NodeJS.Timeout; | |
| 31 | + | |
| 32 | + setSize((prev) => ({ ...prev, isResizing: true })); | |
| 33 | + | |
| 34 | + timeoutId = setTimeout(() => { | |
| 35 | + setSize({ | |
| 36 | + ...measurements, | |
| 37 | + isResizing: false, | |
| 38 | + }); | |
| 39 | + }, debounceMs); | |
| 40 | + | |
| 41 | + return () => clearTimeout(timeoutId); | |
| 42 | + }, | |
| 43 | + [debounceMs], | |
| 44 | + ); | |
| 45 | + | |
| 46 | + useEffect(() => { | |
| 47 | + if (!ref.current) return; | |
| 48 | + | |
| 49 | + const updateSize = () => { | |
| 50 | + const element = ref.current; | |
| 51 | + if (!element) return; | |
| 52 | + | |
| 53 | + const measurements = { | |
| 54 | + clientWidth: element.clientWidth, | |
| 55 | + clientHeight: element.clientHeight, | |
| 56 | + scrollWidth: element.scrollWidth, | |
| 57 | + scrollHeight: element.scrollHeight, | |
| 58 | + }; | |
| 59 | + | |
| 60 | + debouncedSetSize(measurements); | |
| 61 | + }; | |
| 62 | + | |
| 63 | + // Create ResizeObserver instance | |
| 64 | + const resizeObserver = new ResizeObserver(() => { | |
| 65 | + updateSize(); | |
| 66 | + }); | |
| 67 | + | |
| 68 | + // Start observing the element | |
| 69 | + resizeObserver.observe(ref.current); | |
| 70 | + | |
| 71 | + // Initial size calculation | |
| 72 | + updateSize(); | |
| 73 | + | |
| 74 | + // Cleanup | |
| 75 | + return () => { | |
| 76 | + resizeObserver.disconnect(); | |
| 77 | + }; | |
| 78 | + }, [ref, debouncedSetSize]); | |
| 79 | + | |
| 80 | + return size; | |
| 81 | +}; |
modified gui/src/components/gui/Alert.tsx +1 −1
| @@ -39,7 +39,7 @@ | ||
| 39 | 39 | const { Icon } = ALERT_CONFIGS[type]; |
| 40 | 40 | |
| 41 | 41 | return ( |
| 42 | - <div className="rounded-lg border-l-4 bg-[color:var(--vscode-editor-foreground)] p-4 opacity-70 shadow-none"> | |
| 42 | + <div className="bg-editor-foreground rounded-lg border-l-4 p-4 opacity-70 shadow-none"> | |
| 43 | 43 | <div className="flex items-start"> |
| 44 | 44 | <Icon |
| 45 | 45 | className="h-6 min-h-5 w-6 min-w-5" |
modified gui/src/components/index.ts +23 −110
| @@ -1,114 +1,31 @@ | ||
| 1 | 1 | import styled from "styled-components"; |
| 2 | -import { getFontSize } from "../util"; | |
| 3 | - | |
| 4 | -export const VSC_INPUT_BACKGROUND_VAR = "--vscode-input-background"; | |
| 5 | -export const VSC_BACKGROUND_VAR = "--vscode-sideBar-background"; | |
| 6 | -export const VSC_FOREGROUND_VAR = "--vscode-editor-foreground"; | |
| 7 | -export const VSC_BUTTON_BACKGROUND_VAR = "--vscode-button-background"; | |
| 8 | -export const VSC_BUTTON_FOREGROUND_VAR = "--vscode-button-foreground"; | |
| 9 | -export const VSC_EDITOR_BACKGROUND_VAR = "--vscode-editor-background"; | |
| 10 | -export const VSC_LIST_SELECTION_BACKGROUND_VAR = | |
| 11 | - "--vscode-list-activeSelectionBackground"; | |
| 12 | -export const VSC_FOCUS_BORDER_VAR = "--vscode-focusBorder"; | |
| 13 | -export const VSC_LIST_ACTIVE_FOREGROUND_VAR = | |
| 14 | - "--vscode-quickInputList-focusForeground"; | |
| 15 | -export const VSC_QUICK_INPUT_BACKGROUND_VAR = "--vscode-quickInput-background"; | |
| 16 | -export const VSC_INPUT_BORDER_VAR = "--vscode-input-border"; | |
| 17 | -export const VSC_BADGE_BACKGROUND_VAR = "--vscode-badge-background"; | |
| 18 | -export const VSC_BADGE_FOREGROUND_VAR = "--vscode-badge-foreground"; | |
| 19 | -export const VSC_COMMAND_CENTER_ACTIVE_BORDER_VAR = | |
| 20 | - "--vscode-commandCenter-activeBorder"; | |
| 21 | -export const VSC_COMMAND_CENTER_INACTIVE_BORDER_VAR = | |
| 22 | - "--vscode-commandCenter-inactiveBorder"; | |
| 23 | -export const VSC_FIND_MATCH_SELECTED_VAR = | |
| 24 | - "--vscode-editor-findMatchHighlightBackground"; | |
| 25 | - | |
| 26 | -export const VSC_THEME_COLOR_VARS = [ | |
| 27 | - VSC_INPUT_BACKGROUND_VAR, | |
| 28 | - VSC_BACKGROUND_VAR, | |
| 29 | - VSC_FOREGROUND_VAR, | |
| 30 | - VSC_BUTTON_BACKGROUND_VAR, | |
| 31 | - VSC_BUTTON_FOREGROUND_VAR, | |
| 32 | - VSC_EDITOR_BACKGROUND_VAR, | |
| 33 | - VSC_LIST_SELECTION_BACKGROUND_VAR, | |
| 34 | - VSC_FOCUS_BORDER_VAR, | |
| 35 | - VSC_LIST_ACTIVE_FOREGROUND_VAR, | |
| 36 | - VSC_QUICK_INPUT_BACKGROUND_VAR, | |
| 37 | - VSC_INPUT_BORDER_VAR, | |
| 38 | - VSC_BADGE_BACKGROUND_VAR, | |
| 39 | - VSC_BADGE_FOREGROUND_VAR, | |
| 40 | - VSC_COMMAND_CENTER_ACTIVE_BORDER_VAR, | |
| 41 | - VSC_COMMAND_CENTER_INACTIVE_BORDER_VAR, | |
| 42 | - VSC_FIND_MATCH_SELECTED_VAR, | |
| 43 | -]; | |
| 2 | +import { varWithFallback } from "../styles/theme"; | |
| 44 | 3 | |
| 4 | +// DEPRECATED - avoid using these where possible, use tailwind classes instead | |
| 45 | 5 | export const defaultBorderRadius = "5px"; |
| 46 | 6 | export const lightGray = "#999998"; |
| 47 | 7 | export const greenButtonColor = "#189e72"; |
| 48 | 8 | |
| 49 | -export const vscInputBackground = `var(${VSC_INPUT_BACKGROUND_VAR}, rgb(45 45 45))`; | |
| 50 | -export const vscQuickInputBackground = `var(${VSC_QUICK_INPUT_BACKGROUND_VAR}, ${VSC_INPUT_BACKGROUND_VAR}, rgb(45 45 45))`; | |
| 51 | -export const vscBackground = `var(${VSC_BACKGROUND_VAR}, rgb(30 30 30))`; | |
| 52 | -export const vscForeground = `var(${VSC_FOREGROUND_VAR}, #fff)`; | |
| 53 | -export const vscButtonBackground = `var(${VSC_BUTTON_BACKGROUND_VAR}, #1bbe84)`; | |
| 54 | -export const vscButtonForeground = `var(${VSC_BUTTON_FOREGROUND_VAR}, #ffffff)`; | |
| 55 | -export const vscEditorBackground = `var(${VSC_EDITOR_BACKGROUND_VAR}, ${VSC_BACKGROUND_VAR}, rgb(30 30 30))`; | |
| 56 | -export const vscListActiveBackground = `var(${VSC_LIST_SELECTION_BACKGROUND_VAR}, #1bbe84)`; | |
| 57 | -export const vscFocusBorder = `var(${VSC_FOCUS_BORDER_VAR}, #1bbe84)`; | |
| 58 | -export const vscListActiveForeground = `var(${VSC_LIST_ACTIVE_FOREGROUND_VAR}, ${VSC_FOREGROUND_VAR})`; | |
| 59 | -export const vscInputBorder = `var(${VSC_INPUT_BORDER_VAR}, ${lightGray})`; | |
| 60 | -export const vscInputBorderFocus = `var(${VSC_FOCUS_BORDER_VAR}, ${lightGray})`; | |
| 61 | -export const vscBadgeBackground = `var(${VSC_BADGE_BACKGROUND_VAR}, #1bbe84)`; | |
| 62 | -export const vscBadgeForeground = `var(${VSC_BADGE_FOREGROUND_VAR}, #ffffff)`; | |
| 63 | -export const vscCommandCenterActiveBorder = `var(${VSC_COMMAND_CENTER_ACTIVE_BORDER_VAR}, #1bbe84)`; | |
| 64 | -export const vscCommandCenterInactiveBorder = `var(${VSC_COMMAND_CENTER_INACTIVE_BORDER_VAR}, #1bbe84)`; | |
| 65 | -export const vscFindMatchSelected = `var(${VSC_FIND_MATCH_SELECTED_VAR}, rgba(255, 223, 0))`; | |
| 66 | - | |
| 67 | -export function parseHexColor(hexColor: string): { | |
| 68 | - r: number; | |
| 69 | - g: number; | |
| 70 | - b: number; | |
| 71 | -} { | |
| 72 | - if (hexColor.startsWith("#")) { | |
| 73 | - hexColor = hexColor.slice(1); | |
| 74 | - } | |
| 75 | - | |
| 76 | - if (hexColor.length > 6) { | |
| 77 | - hexColor = hexColor.slice(0, 6); | |
| 78 | - } | |
| 79 | - | |
| 80 | - const r = parseInt(hexColor.substring(0, 2), 16); | |
| 81 | - const g = parseInt(hexColor.substring(2, 4), 16); | |
| 82 | - const b = parseInt(hexColor.substring(4, 6), 16); | |
| 83 | - | |
| 84 | - return { r, g, b }; | |
| 85 | -} | |
| 86 | - | |
| 87 | -export function parseColorForHex(colorVar: string): string { | |
| 88 | - const value = getComputedStyle(document.documentElement).getPropertyValue( | |
| 89 | - colorVar, | |
| 90 | - ); | |
| 91 | - if (value.startsWith("#")) { | |
| 92 | - return value.slice(0, 7); | |
| 93 | - } | |
| 94 | - | |
| 95 | - // Parse rgb/rgba | |
| 96 | - const rgbValues = value | |
| 97 | - .slice(value.startsWith("rgba") ? 5 : 4, -1) | |
| 98 | - .split(",") | |
| 99 | - .map((x) => x.trim()) | |
| 100 | - .filter((_, i) => i < 3) // Only take the first 3 values (RGB, ignore alpha) | |
| 101 | - .map((x) => parseInt(x, 10)); | |
| 102 | - | |
| 103 | - let hex = | |
| 104 | - "#" + | |
| 105 | - rgbValues | |
| 106 | - .map((x) => x.toString(16)) | |
| 107 | - .map((x) => (x.length === 1 ? "0" + x : x)) | |
| 108 | - .join(""); | |
| 109 | - | |
| 110 | - return hex; | |
| 111 | -} | |
| 9 | +export const vscInputBackground = varWithFallback("input-background"); | |
| 10 | +export const vscQuickInputBackground = varWithFallback("input-background"); | |
| 11 | +export const vscBackground = varWithFallback("background"); | |
| 12 | +export const vscForeground = varWithFallback("foreground"); | |
| 13 | +export const vscButtonBackground = varWithFallback("primary-background"); | |
| 14 | +export const vscButtonForeground = varWithFallback("primary-foreground"); | |
| 15 | +export const vscEditorBackground = varWithFallback("editor-background"); | |
| 16 | +export const vscListActiveBackground = varWithFallback("list-active"); | |
| 17 | +export const vscFocusBorder = varWithFallback("border-focus"); | |
| 18 | +export const vscListActiveForeground = varWithFallback( | |
| 19 | + "list-active-foreground", | |
| 20 | +); | |
| 21 | +export const vscInputBorder = varWithFallback("input-border"); | |
| 22 | +export const vscInputBorderFocus = varWithFallback("border-focus"); | |
| 23 | +export const vscBadgeBackground = varWithFallback("badge-background"); | |
| 24 | +export const vscBadgeForeground = varWithFallback("badge-foreground"); | |
| 25 | +export const vscCommandCenterActiveBorder = varWithFallback( | |
| 26 | + "command-border-focus", | |
| 27 | +); | |
| 28 | +export const vscCommandCenterInactiveBorder = varWithFallback("command-border"); | |
| 112 | 29 | |
| 113 | 30 | export const Button = styled.button` |
| 114 | 31 | padding: 6px 12px; |
| @@ -158,7 +75,7 @@ | ||
| 158 | 75 | |
| 159 | 76 | border: none; |
| 160 | 77 | color: ${vscForeground}; |
| 161 | - background-color: rgba(255, 255, 255, 0.08); | |
| 78 | + background-color: rgba(128, 128, 128, 0.4); | |
| 162 | 79 | &:disabled { |
| 163 | 80 | color: gray; |
| 164 | 81 | pointer-events: none; |
| @@ -226,10 +143,6 @@ | ||
| 226 | 143 | } |
| 227 | 144 | `; |
| 228 | 145 | |
| 229 | -export const Label = styled.label<{ fontSize?: number }>` | |
| 230 | - font-size: ${(props) => props.fontSize || getFontSize()}px; | |
| 231 | -`; | |
| 232 | - | |
| 233 | 146 | export const HeaderButton = styled.button<{ |
| 234 | 147 | inverted: boolean | undefined; |
| 235 | 148 | backgroundColor?: string; |
modified gui/src/components/mainInput/Lump/sections/ExploreBlocksButton.tsx +1 −1
| @@ -49,7 +49,7 @@ | ||
| 49 | 49 | |
| 50 | 50 | return ( |
| 51 | 51 | <GhostButton |
| 52 | - className="w-full cursor-pointer rounded px-2 py-0.5 text-center text-gray-400 hover:text-gray-300" | |
| 52 | + className="w-full cursor-pointer rounded px-2 py-0.5 text-center" | |
| 53 | 53 | style={{ |
| 54 | 54 | fontSize: fontSize(-3), |
| 55 | 55 | }} |
modified gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx +1 −1
| @@ -159,7 +159,7 @@ | ||
| 159 | 159 | contentEditable={false} |
| 160 | 160 | > |
| 161 | 161 | <div |
| 162 | - className="border-b-vsc-commandCenter-inactiveBorder m-0 flex cursor-pointer items-center justify-between break-all border-0 border-b-[1px] border-solid px-[5px] py-1.5 hover:opacity-90" | |
| 162 | + className="border-b-command-border m-0 flex cursor-pointer items-center justify-between break-all border-0 border-b-[1px] border-solid px-[5px] py-1.5 hover:opacity-90" | |
| 163 | 163 | style={{ |
| 164 | 164 | fontSize: getFontSize() - 3, |
| 165 | 165 | }} |
modified gui/src/context/Auth.tsx +1 −1
| @@ -2,7 +2,7 @@ | ||
| 2 | 2 | OrganizationDescription, |
| 3 | 3 | ProfileDescription, |
| 4 | 4 | } from "core/config/ProfileLifecycleManager"; |
| 5 | -import { ControlPlaneSessionInfo } from "core/control-plane/client"; | |
| 5 | +import { ControlPlaneSessionInfo } from "core/control-plane/AuthTypes"; | |
| 6 | 6 | import React, { |
| 7 | 7 | createContext, |
| 8 | 8 | useCallback, |
modified gui/src/context/MockIdeMessenger.ts +2 −0
| @@ -1,4 +1,5 @@ | ||
| 1 | 1 | import { IDE, PromptLog } from "core"; |
| 2 | +import { AuthType } from "core/control-plane/AuthTypes"; | |
| 2 | 3 | import { |
| 3 | 4 | FromIdeProtocol, |
| 4 | 5 | FromWebviewProtocol, |
| @@ -38,6 +39,7 @@ | ||
| 38 | 39 | ]); |
| 39 | 40 | case "getControlPlaneSessionInfo": |
| 40 | 41 | return returnFor("getControlPlaneSessionInfo", { |
| 42 | + AUTH_TYPE: AuthType.WorkOsStaging, | |
| 41 | 43 | accessToken: "", |
| 42 | 44 | account: { |
| 43 | 45 | label: "", |
modified gui/src/context/VscTheme.tsx +1 −1
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | import { createContext, useContext, useState } from "react"; |
| 2 | -import { parseHexColor } from "../components"; | |
| 3 | 2 | import { useWebviewListener } from "../hooks/useWebviewListener"; |
| 3 | +import { parseHexColor } from "../styles/utils"; | |
| 4 | 4 | |
| 5 | 5 | const hljsToTextMate: Record<string, string[]> = { |
| 6 | 6 | ".hljs-comment": ["comment"], |
modified gui/src/hooks/ParallelListeners.tsx +7 −34
| @@ -1,5 +1,4 @@ | ||
| 1 | 1 | import { useCallback, useContext, useEffect, useRef } from "react"; |
| 2 | -import { VSC_THEME_COLOR_VARS } from "../components"; | |
| 3 | 2 | import { IdeMessengerContext } from "../context/IdeMessenger"; |
| 4 | 3 | |
| 5 | 4 | import { EDIT_MODE_STREAM_ID } from "core/edit/constants"; |
| @@ -29,6 +28,10 @@ | ||
| 29 | 28 | import { refreshSessionMetadata } from "../redux/thunks/session"; |
| 30 | 29 | import { streamResponseThunk } from "../redux/thunks/streamResponse"; |
| 31 | 30 | import { updateFileSymbolsFromHistory } from "../redux/thunks/updateFileSymbols"; |
| 31 | +import { | |
| 32 | + setDocumentStylesFromLocalStorage, | |
| 33 | + setDocumentStylesFromTheme, | |
| 34 | +} from "../styles/theme"; | |
| 32 | 35 | import { isJetBrains } from "../util"; |
| 33 | 36 | import { setLocalStorage } from "../util/localStorage"; |
| 34 | 37 | import { useWebviewListener } from "./useWebviewListener"; |
| @@ -139,31 +142,13 @@ | ||
| 139 | 142 | dispatch(cancelStream()); |
| 140 | 143 | |
| 141 | 144 | const jetbrains = isJetBrains(); |
| 142 | - for (const colorVar of VSC_THEME_COLOR_VARS) { | |
| 143 | - if (jetbrains) { | |
| 144 | - const cached = localStorage.getItem(colorVar); | |
| 145 | - if (cached) { | |
| 146 | - document.body.style.setProperty(colorVar, cached); | |
| 147 | - } | |
| 148 | - } | |
| 149 | - | |
| 150 | - // Remove alpha channel from colors | |
| 151 | - const value = getComputedStyle(document.documentElement).getPropertyValue( | |
| 152 | - colorVar, | |
| 153 | - ); | |
| 154 | - if (colorVar.startsWith("#") && value.length > 7) { | |
| 155 | - document.body.style.setProperty(colorVar, value.slice(0, 7)); | |
| 156 | - } | |
| 157 | - } | |
| 145 | + setDocumentStylesFromLocalStorage(jetbrains); | |
| 158 | 146 | |
| 159 | 147 | if (jetbrains) { |
| 160 | 148 | // Save theme colors to local storage for immediate loading in JetBrains |
| 161 | 149 | ideMessenger.request("jetbrains/getColors", undefined).then((result) => { |
| 162 | 150 | if (result.status === "success") { |
| 163 | - Object.entries(result.content).forEach(([key, value]) => { | |
| 164 | - document.body.style.setProperty(key, value); | |
| 165 | - document.documentElement.style.setProperty(key, value); | |
| 166 | - }); | |
| 151 | + setDocumentStylesFromTheme(result.content); | |
| 167 | 152 | } |
| 168 | 153 | }); |
| 169 | 154 | |
| @@ -180,25 +165,13 @@ | ||
| 180 | 165 | (window as any).vscMachineId = msg.vscMachineId; |
| 181 | 166 | (window as any).vscMediaUrl = msg.vscMediaUrl; |
| 182 | 167 | }); |
| 183 | - | |
| 184 | - for (const colorVar of VSC_THEME_COLOR_VARS) { | |
| 185 | - if (document.body.style.getPropertyValue(colorVar)) { | |
| 186 | - localStorage.setItem( | |
| 187 | - colorVar, | |
| 188 | - document.body.style.getPropertyValue(colorVar), | |
| 189 | - ); | |
| 190 | - } | |
| 191 | - } | |
| 192 | 168 | } |
| 193 | 169 | }, []); |
| 194 | 170 | |
| 195 | 171 | useWebviewListener( |
| 196 | 172 | "jetbrains/setColors", |
| 197 | 173 | async (data) => { |
| 198 | - Object.entries(data).forEach(([key, value]) => { | |
| 199 | - document.body.style.setProperty(key, value); | |
| 200 | - document.documentElement.style.setProperty(key, value); | |
| 201 | - }); | |
| 174 | + setDocumentStylesFromTheme(data); | |
| 202 | 175 | }, |
| 203 | 176 | [], |
| 204 | 177 | ); |
modified gui/src/pages/config/AccountButton.tsx +6 −0
| @@ -1,5 +1,6 @@ | ||
| 1 | 1 | import { UserCircleIcon } from "@heroicons/react/24/solid"; |
| 2 | 2 | |
| 3 | +import { isHubSession } from "core/control-plane/AuthTypes"; | |
| 3 | 4 | import { SecondaryButton } from "../../components"; |
| 4 | 5 | import { |
| 5 | 6 | Popover, |
| @@ -27,6 +28,11 @@ | ||
| 27 | 28 | ); |
| 28 | 29 | } |
| 29 | 30 | |
| 31 | + // No login button for on-prem deployments | |
| 32 | + if (!isHubSession(session)) { | |
| 33 | + return null; | |
| 34 | + } | |
| 35 | + | |
| 30 | 36 | return ( |
| 31 | 37 | <Popover className="relative"> |
| 32 | 38 | {({ close }) => ( |
modified gui/src/pages/config/HelpCenterSection.tsx +12 −0
| @@ -1,6 +1,7 @@ | ||
| 1 | 1 | import { |
| 2 | 2 | ArrowTopRightOnSquareIcon, |
| 3 | 3 | DocumentArrowUpIcon, |
| 4 | + PaintBrushIcon, | |
| 4 | 5 | TableCellsIcon, |
| 5 | 6 | } from "@heroicons/react/24/outline"; |
| 6 | 7 | import { useContext } from "react"; |
| @@ -9,6 +10,7 @@ | ||
| 9 | 10 | import { useAppDispatch } from "../../redux/hooks"; |
| 10 | 11 | import { setOnboardingCard } from "../../redux/slices/uiSlice"; |
| 11 | 12 | import { saveCurrentSession } from "../../redux/thunks/session"; |
| 13 | +import { ROUTES } from "../../util/navigation"; | |
| 12 | 14 | import MoreHelpRow from "./MoreHelpRow"; |
| 13 | 15 | |
| 14 | 16 | export function HelpCenterSection() { |
| @@ -83,6 +85,16 @@ | ||
| 83 | 85 | ideMessenger.post("showTutorial", undefined); |
| 84 | 86 | }} |
| 85 | 87 | /> |
| 88 | + {process.env.NODE_ENV === "development" && ( | |
| 89 | + <MoreHelpRow | |
| 90 | + title="Theme Test Page" | |
| 91 | + description="Development page for testing themes" | |
| 92 | + Icon={PaintBrushIcon} | |
| 93 | + onClick={async () => { | |
| 94 | + navigate(ROUTES.THEME); | |
| 95 | + }} | |
| 96 | + /> | |
| 97 | + )} | |
| 86 | 98 | </div> |
| 87 | 99 | </div> |
| 88 | 100 | ); |
modified gui/src/pages/config/KeyboardShortcuts.tsx +1 −1
| @@ -11,7 +11,7 @@ | ||
| 11 | 11 | function KeyboardShortcut(props: KeyboardShortcutProps) { |
| 12 | 12 | return ( |
| 13 | 13 | <div |
| 14 | - className={`flex flex-col items-start p-2 py-2 sm:flex-row sm:items-center ${props.isEven ? "" : "bg-table-odd-rows"}`} | |
| 14 | + className={`flex flex-col items-start p-2 py-2 sm:flex-row sm:items-center ${props.isEven ? "" : "bg-table-oddRow"}`} | |
| 15 | 15 | > |
| 16 | 16 | <div className="w-full flex-grow pb-1 pr-4 sm:w-auto sm:pb-0"> |
| 17 | 17 | <span className="block break-words text-xs">{props.description}:</span> |
modified gui/src/pages/gui/Chat.tsx +10 −6
| @@ -44,16 +44,17 @@ | ||
| 44 | 44 | setDialogMessage, |
| 45 | 45 | setShowDialog, |
| 46 | 46 | } from "../../redux/slices/uiSlice"; |
| 47 | +import { streamResponseThunk } from "../../redux/thunks"; | |
| 47 | 48 | import { cancelStream } from "../../redux/thunks/cancelStream"; |
| 48 | 49 | import { streamEditThunk } from "../../redux/thunks/editMode"; |
| 49 | 50 | import { loadLastSession } from "../../redux/thunks/session"; |
| 50 | -import { streamResponseThunk } from "../../redux/thunks"; | |
| 51 | 51 | import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util"; |
| 52 | 52 | import { |
| 53 | 53 | FREE_TRIAL_LIMIT_REQUESTS, |
| 54 | 54 | incrementFreeTrialCount, |
| 55 | 55 | } from "../../util/freeTrial"; |
| 56 | 56 | |
| 57 | +import AcceptRejectDiffButtons from "../../components/AcceptRejectDiffButtons"; | |
| 57 | 58 | import CodeToEditCard from "../../components/mainInput/CodeToEditCard"; |
| 58 | 59 | import EditModeDetails from "../../components/mainInput/EditModeDetails"; |
| 59 | 60 | import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; |
| @@ -61,7 +62,6 @@ | ||
| 61 | 62 | import { ExploreDialogWatcher } from "./ExploreDialogWatcher"; |
| 62 | 63 | import { ToolCallDiv } from "./ToolCallDiv"; |
| 63 | 64 | import { useAutoScroll } from "./useAutoScroll"; |
| 64 | -import AcceptRejectDiffButtons from "../../components/AcceptRejectDiffButtons"; | |
| 65 | 65 | |
| 66 | 66 | const StepsDiv = styled.div` |
| 67 | 67 | position: relative; |
| @@ -113,6 +113,7 @@ | ||
| 113 | 113 | const [stepsOpen] = useState<(boolean | undefined)[]>([]); |
| 114 | 114 | const mainTextInputRef = useRef<HTMLInputElement>(null); |
| 115 | 115 | const stepsDivRef = useRef<HTMLDivElement>(null); |
| 116 | + const tabsRef = useRef<HTMLDivElement>(null); | |
| 116 | 117 | const history = useAppSelector((state) => state.session.history); |
| 117 | 118 | const showChatScrollbar = useAppSelector( |
| 118 | 119 | (state) => state.config.config.ui?.showChatScrollbar, |
| @@ -153,7 +154,11 @@ | ||
| 153 | 154 | }; |
| 154 | 155 | }, [isStreaming, jetbrains]); |
| 155 | 156 | |
| 156 | - const { widget, highlights } = useFindWidget(stepsDivRef); | |
| 157 | + const { widget, highlights } = useFindWidget( | |
| 158 | + stepsDivRef, | |
| 159 | + tabsRef, | |
| 160 | + isStreaming, | |
| 161 | + ); | |
| 157 | 162 | |
| 158 | 163 | const currentToolCallApplyState = useAppSelector( |
| 159 | 164 | selectCurrentToolCallApplyState, |
| @@ -287,13 +292,12 @@ | ||
| 287 | 292 | |
| 288 | 293 | return ( |
| 289 | 294 | <> |
| 295 | + {!!showSessionTabs && mode !== "edit" && <TabBar ref={tabsRef} />} | |
| 290 | 296 | {widget} |
| 291 | 297 | |
| 292 | - {!!showSessionTabs && mode !== "edit" && <TabBar />} | |
| 293 | - | |
| 294 | 298 | <StepsDiv |
| 295 | 299 | ref={stepsDivRef} |
| 296 | - className={`mt-3 overflow-y-scroll pt-[8px] ${showScrollbar ? "thin-scrollbar" : "no-scrollbar"} ${history.length > 0 ? "flex-1" : ""}`} | |
| 300 | + className={`overflow-y-scroll pt-[8px] ${showScrollbar ? "thin-scrollbar" : "no-scrollbar"} ${history.length > 0 ? "flex-1" : ""}`} | |
| 297 | 301 | > |
| 298 | 302 | {highlights} |
| 299 | 303 | {history.map((item, index: number) => ( |
modified gui/src/pages/gui/StreamError.tsx +86 −47
| @@ -1,12 +1,15 @@ | ||
| 1 | 1 | import { |
| 2 | 2 | ArrowTopRightOnSquareIcon, |
| 3 | - Cog8ToothIcon, | |
| 3 | + ClipboardIcon, | |
| 4 | + Cog6ToothIcon, | |
| 5 | + KeyIcon, | |
| 4 | 6 | } from "@heroicons/react/24/outline"; |
| 5 | 7 | import { DISCORD_LINK, GITHUB_LINK } from "core/util/constants"; |
| 6 | 8 | import { useContext, useMemo } from "react"; |
| 7 | -import { Button, SecondaryButton } from "../../components"; | |
| 9 | +import { GhostButton, SecondaryButton } from "../../components"; | |
| 8 | 10 | import { DiscordIcon } from "../../components/svg/DiscordIcon"; |
| 9 | 11 | import { GithubIcon } from "../../components/svg/GithubIcon"; |
| 12 | +import ToggleDiv from "../../components/ToggleDiv"; | |
| 10 | 13 | import { useAuth } from "../../context/Auth"; |
| 11 | 14 | import { IdeMessengerContext } from "../../context/IdeMessenger"; |
| 12 | 15 | import { selectSelectedProfile } from "../../redux/"; |
| @@ -48,11 +51,15 @@ | ||
| 48 | 51 | ); |
| 49 | 52 | |
| 50 | 53 | const handleRefreshProfiles = () => { |
| 51 | - refreshProfiles(); | |
| 54 | + void refreshProfiles(); | |
| 52 | 55 | dispatch(setShowDialog(false)); |
| 53 | 56 | dispatch(setDialogMessage(undefined)); |
| 54 | 57 | }; |
| 55 | 58 | |
| 59 | + const copyErrorToClipboard = () => { | |
| 60 | + void navigator.clipboard.writeText(parsedError); | |
| 61 | + }; | |
| 62 | + | |
| 56 | 63 | // Collect model information to display useful error info |
| 57 | 64 | let modelTitle = "Chat model"; |
| 58 | 65 | let providerName = "the model provider"; |
| @@ -99,30 +106,29 @@ | ||
| 99 | 106 | } |
| 100 | 107 | |
| 101 | 108 | const checkKeysButton = apiKeyUrl ? ( |
| 102 | - <Button | |
| 103 | - className="cursor-pointer hover:underline" | |
| 109 | + <GhostButton | |
| 110 | + className="flex items-center" | |
| 104 | 111 | onClick={() => { |
| 105 | 112 | ideMessenger.post("openUrl", apiKeyUrl!); |
| 106 | 113 | }} |
| 107 | 114 | > |
| 108 | - Check keys/usage | |
| 109 | - </Button> | |
| 115 | + <KeyIcon className="mr-1.5 h-3.5 w-3.5" /> | |
| 116 | + <span>View key</span> | |
| 117 | + </GhostButton> | |
| 110 | 118 | ) : null; |
| 111 | 119 | |
| 112 | 120 | const configButton = ( |
| 113 | - <SecondaryButton | |
| 114 | - className="flex flex-row items-center gap-1.5 hover:underline hover:opacity-70" | |
| 121 | + <GhostButton | |
| 122 | + className="flex items-center" | |
| 115 | 123 | onClick={() => { |
| 116 | 124 | ideMessenger.post("config/openProfile", { |
| 117 | 125 | profileId: undefined, |
| 118 | 126 | }); |
| 119 | 127 | }} |
| 120 | 128 | > |
| 121 | - <div> | |
| 122 | - <Cog8ToothIcon className="h-4 w-4" /> | |
| 123 | - </div> | |
| 124 | - <span>Open Assistant configuration</span> | |
| 125 | - </SecondaryButton> | |
| 129 | + <Cog6ToothIcon className="mr-1.5 h-3.5 w-3.5" /> | |
| 130 | + <span>View config</span> | |
| 131 | + </GhostButton> | |
| 126 | 132 | ); |
| 127 | 133 | |
| 128 | 134 | if ( |
| @@ -131,7 +137,20 @@ | ||
| 131 | 137 | return <ModelsAddOnLimitDialog />; |
| 132 | 138 | } |
| 133 | 139 | |
| 134 | - let errorContent: React.ReactNode = <></>; | |
| 140 | + let errorContent = ( | |
| 141 | + <div className="mb-3 mt-1"> | |
| 142 | + <div className="m-0 p-0"> | |
| 143 | + <p className="m-0 mb-2 p-0"> | |
| 144 | + There was an error handling the response from{" "} | |
| 145 | + {selectedModel?.title || "the model"}. | |
| 146 | + </p> | |
| 147 | + <p className="m-0 p-0"> | |
| 148 | + Please try to submit your message again, and if the error persists, | |
| 149 | + let us know by reporting the issue using the buttons below. | |
| 150 | + </p> | |
| 151 | + </div> | |
| 152 | + </div> | |
| 153 | + ); | |
| 135 | 154 | |
| 136 | 155 | // Display components for specific errors |
| 137 | 156 | if (statusCode === 429) { |
| @@ -141,7 +160,7 @@ | ||
| 141 | 160 | {`This might mean your ${modelTitle} usage has been rate limited |
| 142 | 161 | by ${providerName}.`} |
| 143 | 162 | </span> |
| 144 | - <div className="flex flex-row flex-wrap gap-2"> | |
| 163 | + <div className="flex flex-row flex-wrap justify-start gap-3 py-4"> | |
| 145 | 164 | {checkKeysButton} |
| 146 | 165 | {configButton} |
| 147 | 166 | </div> |
| @@ -230,51 +249,71 @@ | ||
| 230 | 249 | ); |
| 231 | 250 | } |
| 232 | 251 | |
| 252 | + console.log({ message }); | |
| 253 | + | |
| 233 | 254 | return ( |
| 234 | - <div className={`flex flex-col gap-1 px-3 pb-2 pt-3`}> | |
| 235 | - <p className="m-0 p-0 text-lg text-red-500"> | |
| 236 | - {statusCode ? `Error (status code ${statusCode})` : "Error"} | |
| 237 | - </p> | |
| 238 | - | |
| 239 | - {message ? ( | |
| 240 | - <div className="mt-2 flex flex-col gap-0 rounded-sm"> | |
| 241 | - <code className="max-h-20 overflow-y-auto p-2 font-mono"> | |
| 242 | - {parsedError} | |
| 243 | - </code> | |
| 244 | - <div | |
| 245 | - className="flex cursor-pointer flex-row items-center justify-end px-1 py-1 text-gray-500 hover:underline" | |
| 246 | - onClick={() => { | |
| 247 | - ideMessenger.post("toggleDevTools", undefined); | |
| 248 | - }} | |
| 249 | - > | |
| 250 | - <span className="px-2">View Logs</span> | |
| 251 | - <ArrowTopRightOnSquareIcon className="h-4 w-4" /> | |
| 252 | - </div> | |
| 255 | + <div className="flex flex-col gap-4 px-3 pb-3 pt-3"> | |
| 256 | + {/* Concise error title */} | |
| 257 | + <h3 className="text-error m-0 p-0 text-lg font-medium"> | |
| 258 | + Error handling model response | |
| 259 | + </h3> | |
| 260 | + | |
| 261 | + {errorContent} | |
| 262 | + | |
| 263 | + {/* Expandable technical details using ToggleDiv */} | |
| 264 | + {message && ( | |
| 265 | + <div className="mb-2"> | |
| 266 | + <ToggleDiv title="View error output" testId="error-output-toggle"> | |
| 267 | + <div className="flex flex-col gap-0 rounded-sm"> | |
| 268 | + <code className="text-editor-foreground block max-h-48 overflow-y-auto p-3 font-mono text-xs"> | |
| 269 | + {parsedError} | |
| 270 | + </code> | |
| 271 | + | |
| 272 | + <div className="flex flex-row items-center justify-end gap-2 p-2"> | |
| 273 | + <GhostButton | |
| 274 | + onClick={copyErrorToClipboard} | |
| 275 | + className="flex items-center" | |
| 276 | + > | |
| 277 | + <ClipboardIcon className="mr-1.5 h-3.5 w-3.5" /> | |
| 278 | + <span>Copy output</span> | |
| 279 | + </GhostButton> | |
| 280 | + | |
| 281 | + <GhostButton | |
| 282 | + onClick={() => { | |
| 283 | + ideMessenger.post("toggleDevTools", undefined); | |
| 284 | + }} | |
| 285 | + className="flex items-center" | |
| 286 | + > | |
| 287 | + <ArrowTopRightOnSquareIcon className="mr-1.5 h-4 w-4" /> | |
| 288 | + <span className="text-xs">View Logs</span> | |
| 289 | + </GhostButton> | |
| 290 | + </div> | |
| 291 | + </div> | |
| 292 | + </ToggleDiv> | |
| 253 | 293 | </div> |
| 254 | - ) : null} | |
| 255 | - <div className="mt-3">{errorContent}</div> | |
| 256 | - | |
| 257 | - <div className="mt-2 flex flex-col gap-1.5"> | |
| 258 | - <span>Report this error:</span> | |
| 259 | - <div className="flex flex-row flex-wrap items-center gap-2"> | |
| 260 | - <SecondaryButton | |
| 261 | - className="flex flex-row items-center gap-2 hover:opacity-70" | |
| 294 | + )} | |
| 295 | + | |
| 296 | + <div> | |
| 297 | + <span className="text-base font-medium">Report this error</span> | |
| 298 | + <div className="mt-2 flex flex-row flex-wrap items-center gap-2"> | |
| 299 | + <GhostButton | |
| 300 | + className="flex flex-row items-center gap-2 rounded px-3 py-1.5" | |
| 262 | 301 | onClick={() => { |
| 263 | 302 | ideMessenger.post("openUrl", GITHUB_LINK); |
| 264 | 303 | }} |
| 265 | 304 | > |
| 266 | 305 | <GithubIcon className="h-5 w-5" /> |
| 267 | 306 | <span className="xs:flex hidden">Github</span> |
| 268 | - </SecondaryButton> | |
| 269 | - <SecondaryButton | |
| 270 | - className="flex flex-row items-center gap-2 hover:opacity-70" | |
| 307 | + </GhostButton> | |
| 308 | + <GhostButton | |
| 309 | + className="flex flex-row items-center gap-2 rounded px-3 py-1.5" | |
| 271 | 310 | onClick={() => { |
| 272 | 311 | ideMessenger.post("openUrl", DISCORD_LINK); |
| 273 | 312 | }} |
| 274 | 313 | > |
| 275 | 314 | <DiscordIcon className="h-5 w-5" /> |
| 276 | 315 | <span className="xs:flex hidden">Discord</span> |
| 277 | - </SecondaryButton> | |
| 316 | + </GhostButton> | |
| 278 | 317 | </div> |
| 279 | 318 | </div> |
| 280 | 319 | </div> |
modified gui/src/redux/thunks/streamResponse.ts +1 −0
| @@ -100,6 +100,7 @@ | ||
| 100 | 100 | ? (userMsg as UserChatMessage | ToolResultChatMessage) |
| 101 | 101 | : undefined, |
| 102 | 102 | rules, |
| 103 | + selectedContextItems, | |
| 103 | 104 | ); |
| 104 | 105 | |
| 105 | 106 | // Store in history for UI display |
added gui/src/styles/ThemePage.tsx +232 −0
| @@ -0,0 +1,232 @@ | ||
| 1 | +import { | |
| 2 | + CheckCircleIcon, | |
| 3 | + ExclamationCircleIcon, | |
| 4 | + ExclamationTriangleIcon, | |
| 5 | +} from "@heroicons/react/24/outline"; | |
| 6 | +import { useContext, useEffect, useMemo, useState } from "react"; | |
| 7 | +import { useNavigate } from "react-router-dom"; | |
| 8 | +import { Button } from "../components"; | |
| 9 | +import { IdeMessengerContext } from "../context/IdeMessenger"; | |
| 10 | +import { isJetBrains } from "../util"; | |
| 11 | +import { ROUTES } from "../util/navigation"; | |
| 12 | +import { | |
| 13 | + clearThemeLocalCache, | |
| 14 | + setDocumentStylesFromTheme, | |
| 15 | + THEME_COLORS, | |
| 16 | + varWithFallback, | |
| 17 | +} from "./theme"; | |
| 18 | + | |
| 19 | +const ThemeTailwindClassExample = ({ | |
| 20 | + colorName, | |
| 21 | + varNames, | |
| 22 | + defaultColor, | |
| 23 | + isMissing, | |
| 24 | +}: { | |
| 25 | + colorName: string; | |
| 26 | + varNames: string[]; | |
| 27 | + defaultColor: string; | |
| 28 | + isMissing?: boolean; | |
| 29 | +}) => { | |
| 30 | + return ( | |
| 31 | + <> | |
| 32 | + <div className={`line-clamp-1 break-all px-2 text-right`}> | |
| 33 | + {colorName} | |
| 34 | + </div> | |
| 35 | + <div | |
| 36 | + className={`line-clamp-1 break-all p-1 text-[9px] ${isMissing ? "text-error" : ""}`} | |
| 37 | + style={{ | |
| 38 | + backgroundColor: varWithFallback( | |
| 39 | + colorName as keyof typeof THEME_COLORS, | |
| 40 | + ), | |
| 41 | + }} | |
| 42 | + > | |
| 43 | + {varNames.join(", ")} | |
| 44 | + </div> | |
| 45 | + <div | |
| 46 | + className={`line-clamp-1 break-all p-1 text-[9px]`} | |
| 47 | + style={{ | |
| 48 | + backgroundColor: defaultColor, | |
| 49 | + }} | |
| 50 | + > | |
| 51 | + {defaultColor} | |
| 52 | + </div> | |
| 53 | + </> | |
| 54 | + ); | |
| 55 | +}; | |
| 56 | + | |
| 57 | +function ThemePage() { | |
| 58 | + const navigate = useNavigate(); | |
| 59 | + const [listToggled, setListToggled] = useState(false); | |
| 60 | + const ideMessenger = useContext(IdeMessengerContext); | |
| 61 | + const jetbrains = useMemo(() => { | |
| 62 | + return isJetBrains(); | |
| 63 | + }, []); | |
| 64 | + | |
| 65 | + const [missingVars, setMissingVars] = useState<string[]>([]); | |
| 66 | + const refreshColors = () => { | |
| 67 | + if (jetbrains) { | |
| 68 | + // Jetbrains: get colors and check which ones are missing from theme | |
| 69 | + void ideMessenger | |
| 70 | + .request("jetbrains/getColors", undefined) | |
| 71 | + .then((result) => { | |
| 72 | + console.log(result); | |
| 73 | + if (result.status === "success") { | |
| 74 | + const missingColors = setDocumentStylesFromTheme(result.content); | |
| 75 | + setMissingVars(missingColors); | |
| 76 | + } | |
| 77 | + }); | |
| 78 | + } else { | |
| 79 | + // VS Code: find actual missing CSS variables | |
| 80 | + const notFound: string[] = []; | |
| 81 | + Object.entries(THEME_COLORS).forEach(([colorName, themeVals], idx) => { | |
| 82 | + let found = false; | |
| 83 | + themeVals.vars.forEach((cssVar) => { | |
| 84 | + const value = getComputedStyle( | |
| 85 | + document.documentElement, | |
| 86 | + ).getPropertyValue(cssVar); | |
| 87 | + if (!value) { | |
| 88 | + notFound.push(`cssVar (choice #${idx + 1} for color ${colorName}`); | |
| 89 | + } | |
| 90 | + }); | |
| 91 | + }); | |
| 92 | + setMissingVars(notFound); | |
| 93 | + } | |
| 94 | + }; | |
| 95 | + | |
| 96 | + useEffect(() => { | |
| 97 | + refreshColors(); | |
| 98 | + }, []); | |
| 99 | + | |
| 100 | + return ( | |
| 101 | + <div className="flex flex-1 flex-col gap-3 px-2 py-2"> | |
| 102 | + <span | |
| 103 | + className="flex cursor-pointer flex-row items-center gap-2" | |
| 104 | + onClick={() => navigate(ROUTES.HOME)} | |
| 105 | + > | |
| 106 | + <span className="">←</span> | |
| 107 | + Back to Chat | |
| 108 | + </span> | |
| 109 | + <h2 className="mb-2 mt-0 p-0 text-center text-xl font-semibold"> | |
| 110 | + Theme Tester | |
| 111 | + </h2> | |
| 112 | + <div className="bg-background border-border grid grid-cols-1 gap-4 rounded-md border border-solid p-4 md:grid-cols-2"> | |
| 113 | + <div className="col-span-2 flex gap-4"> | |
| 114 | + <p className="">Normal text</p> | |
| 115 | + <p className="text-description">Description text</p> | |
| 116 | + <p className="text-description-muted">Muted text</p> | |
| 117 | + </div> | |
| 118 | + | |
| 119 | + <button className="bg-primary text-primary-foreground hover:bg-primary-hover cursor-pointer rounded border-none px-4 py-2 disabled:cursor-not-allowed disabled:brightness-75"> | |
| 120 | + Primary Button | |
| 121 | + </button> | |
| 122 | + <button className="bg-secondary text-secondary-foreground hover:bg-secondary-hover cursor-pointer rounded border-none px-4 py-2 disabled:cursor-not-allowed disabled:brightness-75"> | |
| 123 | + Secondary Button | |
| 124 | + </button> | |
| 125 | + | |
| 126 | + <div className="border-border rounded-md border border-solid p-3"> | |
| 127 | + Normal border | |
| 128 | + </div> | |
| 129 | + | |
| 130 | + <div className="border-border-focus rounded-md border border-solid p-3"> | |
| 131 | + Focus border | |
| 132 | + </div> | |
| 133 | + | |
| 134 | + <input | |
| 135 | + className="bg-input text-input-foreground border-input-border placeholder:text-input-placeholder focus:border-border-focus rounded-md border border-solid p-2 focus:outline-none" | |
| 136 | + placeholder="Input example" | |
| 137 | + /> | |
| 138 | + | |
| 139 | + <div className="bg-badge text-badge-foreground border-border inline-block rounded-full border border-solid p-2"> | |
| 140 | + <span className="px-2">Badge</span> | |
| 141 | + </div> | |
| 142 | + | |
| 143 | + <div className="flex items-center gap-2"> | |
| 144 | + <CheckCircleIcon className="text-success h-4 w-4" /> | |
| 145 | + <span className="text-success">Success</span> | |
| 146 | + </div> | |
| 147 | + <div className="flex items-center gap-2"> | |
| 148 | + <ExclamationCircleIcon className="text-warning h-4 w-4" /> | |
| 149 | + <span className="text-warning">Warning</span> | |
| 150 | + </div> | |
| 151 | + <div className="flex items-center gap-2"> | |
| 152 | + <ExclamationTriangleIcon className="text-error h-4 w-4" /> | |
| 153 | + <span className="text-error">Error</span> | |
| 154 | + </div> | |
| 155 | + | |
| 156 | + <div | |
| 157 | + onClick={() => setListToggled(!listToggled)} | |
| 158 | + className={`cursor-pointer p-2 ${listToggled ? "bg-list-active text-list-active-foreground" : "bg-background text-foreground hover:bg-list-hover"}`} | |
| 159 | + > | |
| 160 | + List item (clickable) | |
| 161 | + </div> | |
| 162 | + <div className="bg-editor text-editor-foreground border-border rounded-sm border border-solid p-2"> | |
| 163 | + <span>Editor</span> | |
| 164 | + </div> | |
| 165 | + <table> | |
| 166 | + <tbody> | |
| 167 | + <tr> | |
| 168 | + <td className="border-border border-b border-solid p-2"> | |
| 169 | + <span>even table row</span> | |
| 170 | + </td> | |
| 171 | + </tr> | |
| 172 | + <tr className="bg-table-oddRow"> | |
| 173 | + <td className="border-border border-b border-solid p-2"> | |
| 174 | + <span>odd table row</span> | |
| 175 | + </td> | |
| 176 | + </tr> | |
| 177 | + </tbody> | |
| 178 | + </table> | |
| 179 | + <div> | |
| 180 | + <span className="text-link">Link</span> | |
| 181 | + </div> | |
| 182 | + <div className="flex items-center gap-2"> | |
| 183 | + <span className="bg-findMatch">find match</span> | |
| 184 | + <span className="bg-findMatch-selected">current match</span> | |
| 185 | + </div> | |
| 186 | + <div className="flex items-center gap-2"> | |
| 187 | + <span className="">Accent</span> | |
| 188 | + <div className="bg-accent h-3 w-3" /> | |
| 189 | + </div> | |
| 190 | + </div> | |
| 191 | + <h2 className="mb-2 mt-6 text-xl font-semibold">Manage Theme</h2> | |
| 192 | + <h2 className="mb-2 text-lg font-semibold">Missing Theme Colors</h2> | |
| 193 | + {missingVars.length > 0 ? ( | |
| 194 | + <div className="flex flex-col gap-1"> | |
| 195 | + {missingVars.map((varName) => ( | |
| 196 | + <div key={varName} className=""> | |
| 197 | + {varName} | |
| 198 | + </div> | |
| 199 | + ))} | |
| 200 | + </div> | |
| 201 | + ) : ( | |
| 202 | + <div className="">No missing variables</div> | |
| 203 | + )} | |
| 204 | + <Button onClick={refreshColors}>Refresh Missing Colors</Button> | |
| 205 | + {jetbrains ? ( | |
| 206 | + <Button onClick={clearThemeLocalCache}>Clear Theme Cache</Button> | |
| 207 | + ) : null} | |
| 208 | + <h2 className="mb-2 mt-6 text-xl font-semibold">All Theme Colors</h2> | |
| 209 | + <div className="grid grid-cols-3"> | |
| 210 | + <div className="p-1"> | |
| 211 | + <span className="font-bold">Theme Color</span> | |
| 212 | + </div> | |
| 213 | + <div className="p-1"> | |
| 214 | + <span className="font-bold">CSS Var</span> | |
| 215 | + </div> | |
| 216 | + <div className="p-1"> | |
| 217 | + <span className="font-bold">Default</span> | |
| 218 | + </div> | |
| 219 | + {Object.entries(THEME_COLORS).map(([colorName, val]) => ( | |
| 220 | + <ThemeTailwindClassExample | |
| 221 | + isMissing={missingVars.includes(colorName)} | |
| 222 | + key={colorName} | |
| 223 | + colorName={colorName} | |
| 224 | + defaultColor={val.default} | |
| 225 | + varNames={val.vars} | |
| 226 | + /> | |
| 227 | + ))} | |
| 228 | + </div> | |
| 229 | + </div> | |
| 230 | + ); | |
| 231 | +} | |
| 232 | +export default ThemePage; |
added gui/src/styles/theme.test.ts +24 −0
| @@ -0,0 +1,24 @@ | ||
| 1 | +import { getRecursiveVar } from "./theme"; | |
| 2 | + | |
| 3 | +test("getRecursiveVar returns single var with default for one variable", () => { | |
| 4 | + const vars = ["--test-var"]; | |
| 5 | + const defaultColor = "#ffffff"; | |
| 6 | + const result = getRecursiveVar(vars, defaultColor); | |
| 7 | + expect(result).toBe("var(--test-var, #ffffff)"); | |
| 8 | +}); | |
| 9 | + | |
| 10 | +test("getRecursiveVar returns nested vars in correct order for multiple variables", () => { | |
| 11 | + const vars = ["--first-var", "--second-var", "--third-var"]; | |
| 12 | + const defaultColor = "#000000"; | |
| 13 | + const result = getRecursiveVar(vars, defaultColor); | |
| 14 | + expect(result).toBe( | |
| 15 | + "var(--first-var, var(--second-var, var(--third-var, #000000)))", | |
| 16 | + ); | |
| 17 | +}); | |
| 18 | + | |
| 19 | +test("getRecursiveVar handles empty vars array", () => { | |
| 20 | + const vars: string[] = []; | |
| 21 | + const defaultColor = "#123456"; | |
| 22 | + const result = getRecursiveVar(vars, defaultColor); | |
| 23 | + expect(result).toBe("#123456"); | |
| 24 | +}); |
added gui/src/styles/theme.ts +271 −0
| @@ -0,0 +1,271 @@ | ||
| 1 | +// All vscode variables https://gist.github.com/estruyf/ba49203e1a7d6868e9320a4ea480c27a | |
| 2 | +// Examples for vscode https://github.com/githubocto/tailwind-vscode/blob/main/index.js | |
| 3 | + | |
| 4 | +// The current default theme is dark with blue accents | |
| 5 | +export const THEME_COLORS = { | |
| 6 | + background: { | |
| 7 | + vars: [ | |
| 8 | + "--vscode-sideBar-background", | |
| 9 | + "--vscode-editor-background", | |
| 10 | + "--vscode-panel-background", | |
| 11 | + ], | |
| 12 | + default: "#1e1e1e", // dark gray | |
| 13 | + }, | |
| 14 | + foreground: { | |
| 15 | + vars: [ | |
| 16 | + "--vscode-sideBar-foreground", | |
| 17 | + "--vscode-editor-foreground", | |
| 18 | + "--vscode-panel-foreground", | |
| 19 | + ], | |
| 20 | + default: "#e6e6e6", // light gray | |
| 21 | + }, | |
| 22 | + "editor-background": { | |
| 23 | + vars: ["--vscode-editor-background"], | |
| 24 | + default: "#1e1e1e", // dark gray | |
| 25 | + }, | |
| 26 | + "editor-foreground": { | |
| 27 | + vars: ["--vscode-editor-foreground"], | |
| 28 | + default: "#e6e6e6", // light gray | |
| 29 | + }, | |
| 30 | + "primary-background": { | |
| 31 | + vars: ["--vscode-button-background"], | |
| 32 | + default: "#2c5aa0", // medium blue | |
| 33 | + }, | |
| 34 | + "primary-foreground": { | |
| 35 | + vars: ["--vscode-button-foreground"], | |
| 36 | + default: "#ffffff", // white | |
| 37 | + }, | |
| 38 | + "primary-hover": { | |
| 39 | + vars: ["--vscode-button-hoverBackground"], | |
| 40 | + default: "#3a6db3", // lighter blue | |
| 41 | + }, | |
| 42 | + "secondary-background": { | |
| 43 | + vars: ["--vscode-button-secondaryBackground"], | |
| 44 | + default: "#303030", // medium dark gray | |
| 45 | + }, | |
| 46 | + "secondary-foreground": { | |
| 47 | + vars: ["--vscode-button-secondaryForeground"], | |
| 48 | + default: "#e6e6e6", // light gray | |
| 49 | + }, | |
| 50 | + "secondary-hover": { | |
| 51 | + vars: ["--vscode-button-secondaryHoverBackground"], | |
| 52 | + default: "#3a3a3a", // medium gray | |
| 53 | + }, | |
| 54 | + border: { | |
| 55 | + vars: ["--vscode-sideBar-border", "--vscode-panel-border"], | |
| 56 | + default: "#2a2a2a", // dark gray border | |
| 57 | + }, | |
| 58 | + "border-focus": { | |
| 59 | + vars: ["--vscode-focusBorder"], | |
| 60 | + default: "#3a6db3", // lighter blue | |
| 61 | + }, | |
| 62 | + // Command styles are used for tip-tap editor | |
| 63 | + "command-background": { | |
| 64 | + vars: ["--vscode-commandCenter-background"], | |
| 65 | + default: "#252525", // dark gray | |
| 66 | + }, | |
| 67 | + "command-foreground": { | |
| 68 | + vars: ["--vscode-commandCenter-foreground"], | |
| 69 | + default: "#e6e6e6", // light gray | |
| 70 | + }, | |
| 71 | + "command-border": { | |
| 72 | + vars: ["--vscode-commandCenter-inactiveBorder"], | |
| 73 | + default: "#555555", // medium gray | |
| 74 | + }, | |
| 75 | + "command-border-focus": { | |
| 76 | + vars: ["--vscode-commandCenter-activeBorder"], | |
| 77 | + default: "#4d8bf0", // bright blue | |
| 78 | + }, | |
| 79 | + description: { | |
| 80 | + vars: ["--vscode-descriptionForeground"], | |
| 81 | + default: "#b3b3b3", // medium light gray | |
| 82 | + }, | |
| 83 | + "description-muted": { | |
| 84 | + vars: ["--vscode-list-deemphasizedForeground"], | |
| 85 | + default: "#8c8c8c", // medium gray | |
| 86 | + }, | |
| 87 | + "input-background": { | |
| 88 | + vars: ["--vscode-input-background"], | |
| 89 | + default: "#2d2d2d", // dark gray | |
| 90 | + }, | |
| 91 | + "input-foreground": { | |
| 92 | + vars: ["--vscode-input-foreground"], | |
| 93 | + default: "#e6e6e6", // light gray | |
| 94 | + }, | |
| 95 | + "input-border": { | |
| 96 | + vars: [ | |
| 97 | + "--vscode-input-border", | |
| 98 | + "--vscode-commandCenter-inactiveBorder", | |
| 99 | + "vscode-border", | |
| 100 | + ], | |
| 101 | + default: "#555555", // medium gray | |
| 102 | + }, | |
| 103 | + "input-placeholder": { | |
| 104 | + vars: ["--vscode-input-placeholderForeground"], | |
| 105 | + default: "#9e9e9e", // medium light gray | |
| 106 | + }, | |
| 107 | + "table-oddRow": { | |
| 108 | + vars: ["--vscode-tree-tableOddRowsBackground"], | |
| 109 | + default: "#2d2d2d", // dark gray | |
| 110 | + }, | |
| 111 | + "badge-background": { | |
| 112 | + vars: ["--vscode-badge-background"], | |
| 113 | + default: "#4d4d4d", // medium dark gray | |
| 114 | + }, | |
| 115 | + "badge-foreground": { | |
| 116 | + vars: ["--vscode-badge-foreground"], | |
| 117 | + default: "#ffffff", // white | |
| 118 | + }, | |
| 119 | + success: { | |
| 120 | + vars: [ | |
| 121 | + "--vscode-notebookStatusSuccessIcon-foreground", | |
| 122 | + "--vscode-testing-iconPassed", | |
| 123 | + "--vscode-gitDecoration-addedResourceForeground", | |
| 124 | + "--vscode-charts-green", | |
| 125 | + ], | |
| 126 | + default: "#4caf50", // green | |
| 127 | + }, | |
| 128 | + warning: { | |
| 129 | + vars: [ | |
| 130 | + "--vscode-editorWarning-foreground", | |
| 131 | + "--vscode-list-warningForeground", | |
| 132 | + ], | |
| 133 | + default: "#ffb74d", // amber/yellow | |
| 134 | + }, | |
| 135 | + error: { | |
| 136 | + vars: ["--vscode-editorError-foreground", "--vscode-list-errorForeground"], | |
| 137 | + default: "#f44336", // red | |
| 138 | + }, | |
| 139 | + link: { | |
| 140 | + vars: ["--vscode-textLink-foreground"], | |
| 141 | + default: "#5c9ce6", // medium blue | |
| 142 | + }, | |
| 143 | + accent: { | |
| 144 | + vars: ["--vscode-tab-activeBorderTop", "--vscode-focusBorder"], | |
| 145 | + default: "#4d8bf0", // bright blue | |
| 146 | + }, | |
| 147 | + "find-match": { | |
| 148 | + vars: ["--vscode-editor-findMatchBackground"], // Can't get "var(--vscode-editor-findMatchBackground, rgba(237, 18, 146, 0.5))" to work | |
| 149 | + default: "#264f7840", // translucent blue | |
| 150 | + }, | |
| 151 | + "find-match-selected": { | |
| 152 | + vars: ["--vscode-editor-findMatchHighlightBackground"], | |
| 153 | + default: "#ffb74d40", // translucent amber | |
| 154 | + }, | |
| 155 | + "list-hover": { | |
| 156 | + // --vscode-tab-hoverBackground | |
| 157 | + vars: ["--vscode-list-hoverBackground"], | |
| 158 | + default: "#383838", // medium dark gray | |
| 159 | + }, | |
| 160 | + "list-active": { | |
| 161 | + vars: ["--vscode-list-activeSelectionBackground"], | |
| 162 | + default: "#2c5aa050", // translucent medium blue | |
| 163 | + }, | |
| 164 | + "list-active-foreground": { | |
| 165 | + vars: ["--vscode-list-activeSelectionForeground"], | |
| 166 | + default: "#ffffff", // white | |
| 167 | + }, | |
| 168 | +}; | |
| 169 | + | |
| 170 | +// TODO: add fonts - GUI fonts in jetbrains differ from IDE: | |
| 171 | +// --vscode-editor-font-family; | |
| 172 | +// --vscode-font-family; | |
| 173 | +export const THEME_CSS_VARS = Object.values(THEME_COLORS) | |
| 174 | + .map((value) => value.vars) | |
| 175 | + .flat(); | |
| 176 | + | |
| 177 | +export const THEME_CSS_VAR_DEFAULTS = Object.entries(THEME_COLORS).reduce( | |
| 178 | + (acc, [_, value]) => { | |
| 179 | + value.vars.forEach((varName) => { | |
| 180 | + acc[varName] = value.default; | |
| 181 | + }); | |
| 182 | + return acc; | |
| 183 | + }, | |
| 184 | + {} as Record<string, string>, | |
| 185 | +); | |
| 186 | + | |
| 187 | +export const THEME_DEFAULTS = Object.entries(THEME_COLORS).reduce( | |
| 188 | + (acc, [key, value]) => { | |
| 189 | + acc[key] = value.default; | |
| 190 | + return acc; | |
| 191 | + }, | |
| 192 | + {} as Record<string, string>, | |
| 193 | +); | |
| 194 | + | |
| 195 | +// Generates recursive CSS variable fallback for a given color name | |
| 196 | +// e.g. var(--vscode-button-background, var(--vscode-button-foreground, #ffffff)) | |
| 197 | +export const getRecursiveVar = (vars: string[], defaultColor: string) => { | |
| 198 | + return [...vars].reverse().reduce((curr, varName) => { | |
| 199 | + return `var(${varName}, ${curr})`; | |
| 200 | + }, defaultColor); | |
| 201 | +}; | |
| 202 | + | |
| 203 | +export const varWithFallback = (colorName: keyof typeof THEME_COLORS) => { | |
| 204 | + const themeVals = THEME_COLORS[colorName]; | |
| 205 | + if (!themeVals) { | |
| 206 | + throw new Error(`Invalid theme color name ${colorName}`); | |
| 207 | + } | |
| 208 | + return getRecursiveVar(themeVals.vars, themeVals.default); | |
| 209 | +}; | |
| 210 | + | |
| 211 | +export const setDocumentStylesFromTheme = ( | |
| 212 | + theme: Record<string, string | undefined | null>, | |
| 213 | +) => { | |
| 214 | + // Check for extraneous theme items | |
| 215 | + Object.entries(theme).forEach(([colorName, value]) => { | |
| 216 | + const themeVals = THEME_COLORS[colorName as keyof typeof THEME_COLORS]; | |
| 217 | + if (!themeVals) { | |
| 218 | + console.warn( | |
| 219 | + `Receieved theme color ${colorName} which is not used by the theme`, | |
| 220 | + ); | |
| 221 | + return; | |
| 222 | + } | |
| 223 | + }); | |
| 224 | + | |
| 225 | + // Write theme values to document | |
| 226 | + const missingColors: string[] = []; | |
| 227 | + Object.entries(THEME_COLORS).forEach(([colorName, settings]) => { | |
| 228 | + let colorVal = settings.default; | |
| 229 | + const newColor = theme[colorName]; | |
| 230 | + if (newColor) { | |
| 231 | + colorVal = newColor; | |
| 232 | + // Remove alpha channel from all hex colors (seems to cause bad colors) | |
| 233 | + if (newColor.startsWith("#") && newColor.length > 7) { | |
| 234 | + colorVal = colorVal.slice(0, 7); | |
| 235 | + } | |
| 236 | + } else { | |
| 237 | + missingColors.push(colorName); | |
| 238 | + // console.warn( | |
| 239 | + // `Missing theme color: ${colorName}. Falling back to default ${colorVal}`, | |
| 240 | + // ); | |
| 241 | + } | |
| 242 | + | |
| 243 | + localStorage.setItem(colorName, colorVal); | |
| 244 | + for (const cssVar of settings.vars) { | |
| 245 | + document.body.style.setProperty(cssVar, colorVal); | |
| 246 | + document.documentElement.style.setProperty(cssVar, colorVal); | |
| 247 | + } | |
| 248 | + }); | |
| 249 | + | |
| 250 | + return missingColors; | |
| 251 | +}; | |
| 252 | + | |
| 253 | +export const setDocumentStylesFromLocalStorage = (checkCache: boolean) => { | |
| 254 | + for (const [colorName, themeVals] of Object.entries(THEME_COLORS)) { | |
| 255 | + for (const cssVar of themeVals.vars) { | |
| 256 | + // Get cached values (for non-vscode IDEs) | |
| 257 | + if (checkCache) { | |
| 258 | + const cached = localStorage.getItem(colorName); | |
| 259 | + if (cached) { | |
| 260 | + document.body.style.setProperty(cssVar, cached); | |
| 261 | + } | |
| 262 | + } | |
| 263 | + } | |
| 264 | + } | |
| 265 | +}; | |
| 266 | + | |
| 267 | +export const clearThemeLocalCache = () => { | |
| 268 | + for (const colorName of Object.keys(THEME_COLORS)) { | |
| 269 | + localStorage.removeItem(colorName); | |
| 270 | + } | |
| 271 | +}; |
added gui/src/styles/utils.ts +45 −0
| @@ -0,0 +1,45 @@ | ||
| 1 | +export function parseHexColor(hexColor: string): { | |
| 2 | + r: number; | |
| 3 | + g: number; | |
| 4 | + b: number; | |
| 5 | +} { | |
| 6 | + if (hexColor.startsWith("#")) { | |
| 7 | + hexColor = hexColor.slice(1); | |
| 8 | + } | |
| 9 | + | |
| 10 | + if (hexColor.length > 6) { | |
| 11 | + hexColor = hexColor.slice(0, 6); | |
| 12 | + } | |
| 13 | + | |
| 14 | + const r = parseInt(hexColor.substring(0, 2), 16); | |
| 15 | + const g = parseInt(hexColor.substring(2, 4), 16); | |
| 16 | + const b = parseInt(hexColor.substring(4, 6), 16); | |
| 17 | + | |
| 18 | + return { r, g, b }; | |
| 19 | +} | |
| 20 | + | |
| 21 | +export function parseColorForHex(colorVar: string): string { | |
| 22 | + const value = getComputedStyle(document.documentElement).getPropertyValue( | |
| 23 | + colorVar, | |
| 24 | + ); | |
| 25 | + if (value.startsWith("#")) { | |
| 26 | + return value.slice(0, 7); | |
| 27 | + } | |
| 28 | + | |
| 29 | + // Parse rgb/rgba | |
| 30 | + const rgbValues = value | |
| 31 | + .slice(value.startsWith("rgba") ? 5 : 4, -1) | |
| 32 | + .split(",") | |
| 33 | + .map((x) => x.trim()) | |
| 34 | + .filter((_, i) => i < 3) // Only take the first 3 values (RGB, ignore alpha) | |
| 35 | + .map((x) => parseInt(x, 10)); | |
| 36 | + | |
| 37 | + let hex = | |
| 38 | + "#" + | |
| 39 | + rgbValues | |
| 40 | + .map((x) => x.toString(16)) | |
| 41 | + .map((x) => (x.length === 1 ? "0" + x : x)) | |
| 42 | + .join(""); | |
| 43 | + | |
| 44 | + return hex; | |
| 45 | +} |
modified gui/src/util/navigation.ts +1 −0
| @@ -2,5 +2,6 @@ | ||
| 2 | 2 | export const ROUTES = { |
| 3 | 3 | HOME: "/", |
| 4 | 4 | CONFIG: "/config", |
| 5 | + THEME: "/theme", | |
| 5 | 6 | // EXAMPLE_ROUTE_WITH_PARAMS: (params: ParamsType) => `/route/${params}`, |
| 6 | 7 | }; |
modified gui/tailwind.config.cjs +69 −18
| @@ -1,5 +1,6 @@ | ||
| 1 | 1 | /** @type {import('tailwindcss').Config} */ |
| 2 | 2 | const defaultTheme = require("tailwindcss/defaultTheme"); |
| 3 | +const { varWithFallback, THEME_COLORS } = require("./src/styles/theme"); | |
| 3 | 4 | |
| 4 | 5 | module.exports = { |
| 5 | 6 | content: [ |
| @@ -29,25 +30,75 @@ | ||
| 29 | 30 | default: "5px", |
| 30 | 31 | }, |
| 31 | 32 | colors: { |
| 32 | - lightgray: "#999998", | |
| 33 | - "vsc-input-background": "var(--vscode-input-background, rgb(45 45 45))", | |
| 34 | - "vsc-background": "var(--vscode-sideBar-background, rgb(30 30 30))", | |
| 35 | - "vsc-foreground": "var(--vscode-editor-foreground, #fff)", | |
| 36 | - "vsc-editor-background": | |
| 37 | - "var(--vscode-editor-background, var(--vscode-sideBar-background, rgb(30 30 30)))", | |
| 38 | - "vsc-input-border": "var(--vscode-input-border, #999998)", | |
| 39 | - "vsc-commandCenter-inactiveBorder": | |
| 40 | - "var(--vscode-commandCenter-inactiveBorder, #999998)", | |
| 33 | + background: varWithFallback("background"), | |
| 34 | + foreground: varWithFallback("foreground"), | |
| 35 | + editor: { | |
| 36 | + DEFAULT: varWithFallback("editor-background"), | |
| 37 | + foreground: varWithFallback("editor-foreground"), | |
| 38 | + }, | |
| 39 | + primary: { | |
| 40 | + DEFAULT: varWithFallback("primary-background"), | |
| 41 | + foreground: varWithFallback("primary-foreground"), | |
| 42 | + hover: varWithFallback("primary-hover"), | |
| 43 | + }, | |
| 44 | + secondary: { | |
| 45 | + DEFAULT: varWithFallback("secondary-background"), | |
| 46 | + foreground: varWithFallback("secondary-foreground"), | |
| 47 | + hover: varWithFallback("secondary-hover"), | |
| 48 | + }, | |
| 49 | + border: { | |
| 50 | + DEFAULT: varWithFallback("border"), | |
| 51 | + focus: varWithFallback("border-focus"), | |
| 52 | + }, | |
| 53 | + command: { | |
| 54 | + DEFAULT: varWithFallback("command-background"), | |
| 55 | + foreground: varWithFallback("command-foreground"), | |
| 56 | + border: { | |
| 57 | + DEFAULT: varWithFallback("command-border"), | |
| 58 | + focus: varWithFallback("command-border-focus"), | |
| 59 | + }, | |
| 60 | + }, | |
| 61 | + description: { | |
| 62 | + DEFAULT: varWithFallback("description"), | |
| 63 | + muted: varWithFallback("description-muted"), | |
| 64 | + }, | |
| 65 | + input: { | |
| 66 | + DEFAULT: varWithFallback("input-background"), | |
| 67 | + foreground: varWithFallback("input-foreground"), | |
| 68 | + border: varWithFallback("input-border"), | |
| 69 | + placeholder: varWithFallback("input-placeholder"), | |
| 70 | + }, | |
| 71 | + table: { | |
| 72 | + oddRow: varWithFallback("table-oddRow"), | |
| 73 | + }, | |
| 74 | + badge: { | |
| 75 | + DEFAULT: varWithFallback("badge-background"), | |
| 76 | + foreground: varWithFallback("badge-foreground"), | |
| 77 | + }, | |
| 78 | + success: varWithFallback("success"), | |
| 79 | + warning: varWithFallback("warning"), | |
| 80 | + error: varWithFallback("error"), | |
| 81 | + link: varWithFallback("link"), | |
| 82 | + accent: varWithFallback("accent"), | |
| 83 | + findMatch: { | |
| 84 | + DEFAULT: THEME_COLORS["find-match"].default, | |
| 85 | + selected: varWithFallback("find-match-selected"), | |
| 86 | + }, | |
| 87 | + list: { | |
| 88 | + hover: varWithFallback("list-hover"), | |
| 89 | + active: { | |
| 90 | + DEFAULT: varWithFallback("list-active"), | |
| 91 | + foreground: varWithFallback("list-active-foreground"), | |
| 92 | + }, | |
| 93 | + }, | |
| 41 | 94 | |
| 42 | - // Starting to make things less vsc-specific | |
| 43 | - // TODO make it all non-IDE-specific naming | |
| 44 | - "find-match-selected": | |
| 45 | - "var(--vscode-editor-findMatchHighlightBackground, rgba(255, 223, 0))", | |
| 46 | - "table-odd-rows":"var(--vscode-tree-tableOddRowsBackground, #1bbe84)", | |
| 47 | - "list-active": "var(--vscode-list-activeSelectionBackground, #1bbe84)", | |
| 48 | - "list-active-foreground": | |
| 49 | - "var(--vscode-quickInputList-focusForeground, var(--vscode-editor-foreground))", | |
| 50 | - badge: "var(--vscode-badge-background, #1bbe84)", | |
| 95 | + // DEPRECATED, slowly remove usages of these ide-named or explicit colors | |
| 96 | + lightgray: "#999998", // use border, description, or description-muted instead - AVOID | |
| 97 | + "vsc-input-background": varWithFallback("input-background"), // use "input-background" instead | |
| 98 | + "vsc-background": varWithFallback("background"), // use "background" instead | |
| 99 | + "vsc-foreground": varWithFallback("editor-foreground"), // use "foreground" instead | |
| 100 | + "vsc-editor-background": varWithFallback("editor-background"), // use "editor" instead | |
| 101 | + "vsc-input-border": varWithFallback("input-border"), // use "input-border" instead | |
| 51 | 102 | }, |
| 52 | 103 | }, |
| 53 | 104 | }, |
modified manual-testing-sandbox/test.ts +2 −2
| @@ -9,7 +9,7 @@ | ||
| 9 | 9 | this.result += number; |
| 10 | 10 | return this; |
| 11 | 11 | } |
| 12 | - | |
| 12 | + | |
| 13 | 13 | subtract(number: number): Calculator { |
| 14 | 14 | this.result -= number; |
| 15 | 15 | return this; |
| @@ -38,4 +38,4 @@ | ||
| 38 | 38 | } |
| 39 | 39 | } |
| 40 | 40 | |
| 41 | -export default Calculator; | |
| No newline at the end of the file | ||
| 41 | +export default Calculator; |
modified packages/config-yaml/package-lock.json +2 −2
| @@ -1,12 +1,12 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "name": "@continuedev/config-yaml", |
| 3 | - "version": "1.0.87", | |
| 3 | + "version": "1.0.88", | |
| 4 | 4 | "lockfileVersion": 3, |
| 5 | 5 | "requires": true, |
| 6 | 6 | "packages": { |
| 7 | 7 | "": { |
| 8 | 8 | "name": "@continuedev/config-yaml", |
| 9 | - "version": "1.0.87", | |
| 9 | + "version": "1.0.88", | |
| 10 | 10 | "license": "Apache-2.0", |
| 11 | 11 | "dependencies": { |
| 12 | 12 | "@continuedev/config-types": "^1.0.14", |
modified packages/config-yaml/package.json +1 −1
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "name": "@continuedev/config-yaml", |
| 3 | - "version": "1.0.87", | |
| 3 | + "version": "1.0.88", | |
| 4 | 4 | "description": "", |
| 5 | 5 | "main": "dist/index.js", |
| 6 | 6 | "types": "dist/index.d.ts", |
modified packages/config-yaml/src/load/clientRender.ts +1 −0
| @@ -160,6 +160,7 @@ | ||
| 160 | 160 | apiKeyLocation: z.string().optional(), |
| 161 | 161 | apiBase: z.string().optional(), |
| 162 | 162 | orgScopeId: z.string().nullable(), |
| 163 | + env: z.record(z.string(), z.any()).optional(), | |
| 163 | 164 | }); |
| 164 | 165 | |
| 165 | 166 | export type ContinueProperties = z.infer<typeof continuePropertiesSchema>; |
modified packages/config-yaml/src/schemas/index.ts +6 −2
| @@ -9,13 +9,16 @@ | ||
| 9 | 9 | params: z.any().optional(), |
| 10 | 10 | }); |
| 11 | 11 | |
| 12 | +// TODO: This should be a discriminated union by type | |
| 12 | 13 | const mcpServerSchema = z.object({ |
| 13 | 14 | name: z.string(), |
| 14 | - command: z.string(), | |
| 15 | + command: z.string().optional(), | |
| 16 | + type: z.enum(["sse", "stdio"]).optional(), | |
| 17 | + url: z.string().optional(), | |
| 15 | 18 | faviconUrl: z.string().optional(), |
| 16 | 19 | args: z.array(z.string()).optional(), |
| 17 | 20 | env: z.record(z.string()).optional(), |
| 18 | - connectionTimeout: z.number().gt(0).optional() | |
| 21 | + connectionTimeout: z.number().gt(0).optional(), | |
| 19 | 22 | }); |
| 20 | 23 | |
| 21 | 24 | export type MCPServer = z.infer<typeof mcpServerSchema>; |
| @@ -39,6 +42,7 @@ | ||
| 39 | 42 | const ruleObjectSchema = z.object({ |
| 40 | 43 | name: z.string(), |
| 41 | 44 | rule: z.string(), |
| 45 | + description: z.string().optional(), | |
| 42 | 46 | globs: z.union([z.string(), z.array(z.string())]).optional(), |
| 43 | 47 | }); |
| 44 | 48 | const ruleSchema = z.union([z.string(), ruleObjectSchema]); |
modified packages/config-yaml/src/schemas/models.ts +1 −0
| @@ -117,6 +117,7 @@ | ||
| 117 | 117 | model: z.string(), |
| 118 | 118 | apiKey: z.string().optional(), |
| 119 | 119 | apiBase: z.string().optional(), |
| 120 | + maxStopWords: z.number().optional(), | |
| 120 | 121 | roles: modelRolesSchema.array().optional(), |
| 121 | 122 | capabilities: modelCapabilitySchema.array().optional(), |
| 122 | 123 | defaultCompletionOptions: completionOptionsSchema.optional(), |
modified packages/openai-adapters/README.md +1 −1
| @@ -64,7 +64,7 @@ | ||
| 64 | 64 | - [x] Vllm |
| 65 | 65 | - [ ] Vertex AI |
| 66 | 66 | - [x] Voyage AI |
| 67 | -- [ ] WatsonX | |
| 67 | +- [x] WatsonX | |
| 68 | 68 | - [x] xAI |
| 69 | 69 | - [x] Fireworks |
| 70 | 70 | - [x] Moonshot |
modified packages/openai-adapters/package.json +1 −1
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "name": "@continuedev/openai-adapters", |
| 3 | - "version": "1.0.25", | |
| 3 | + "version": "1.0.26", | |
| 4 | 4 | "description": "", |
| 5 | 5 | "main": "dist/index.js", |
| 6 | 6 | "types": "dist/index.d.ts", |
added packages/openai-adapters/src/apis/WatsonX.ts +314 −0
| @@ -0,0 +1,314 @@ | ||
| 1 | +import { streamSse } from "@continuedev/fetch"; | |
| 2 | +import { OpenAI } from "openai/index"; | |
| 3 | +import { | |
| 4 | + ChatCompletion, | |
| 5 | + ChatCompletionChunk, | |
| 6 | + ChatCompletionCreateParamsNonStreaming, | |
| 7 | + ChatCompletionCreateParamsStreaming, | |
| 8 | + Completion, | |
| 9 | + CompletionCreateParamsNonStreaming, | |
| 10 | + CompletionCreateParamsStreaming, | |
| 11 | +} from "openai/resources/index"; | |
| 12 | +import { ChatCompletionCreateParams } from "openai/src/resources/index.js"; | |
| 13 | +import { WatsonXConfig } from "../types.js"; | |
| 14 | +import { chatCompletion, customFetch } from "../util.js"; | |
| 15 | +import { | |
| 16 | + BaseLlmApi, | |
| 17 | + CreateRerankResponse, | |
| 18 | + FimCreateParamsStreaming, | |
| 19 | + RerankCreateParams, | |
| 20 | +} from "./base.js"; | |
| 21 | + | |
| 22 | +export class WatsonXApi implements BaseLlmApi { | |
| 23 | + apiBase: string; | |
| 24 | + apiVersion: string = "2023-05-29"; | |
| 25 | + projectId?: string; | |
| 26 | + deploymentId?: string; | |
| 27 | + | |
| 28 | + constructor(protected config: WatsonXConfig) { | |
| 29 | + this.apiBase = config.apiBase ?? "https://us-south.ml.cloud.ibm.com"; | |
| 30 | + if (!this.apiBase.endsWith("/")) { | |
| 31 | + this.apiBase += "/"; | |
| 32 | + } | |
| 33 | + this.apiVersion = config.env.apiVersion ?? this.apiVersion; | |
| 34 | + this.projectId = config.env.projectId; | |
| 35 | + this.deploymentId = config.env.deploymentId; | |
| 36 | + } | |
| 37 | + | |
| 38 | + private async getHeaders(): Promise<Record<string, string>> { | |
| 39 | + const bearer = await this.getBearerToken(); | |
| 40 | + return { | |
| 41 | + "Content-Type": "application/json", | |
| 42 | + Authorization: `Bearer ${bearer.token}`, | |
| 43 | + }; | |
| 44 | + } | |
| 45 | + | |
| 46 | + async getBearerToken(): Promise<{ token: string; expiration: number }> { | |
| 47 | + if (this.apiBase?.includes("cloud.ibm.com")) { | |
| 48 | + // watsonx SaaS | |
| 49 | + const wxToken = (await ( | |
| 50 | + await customFetch(this.config.requestOptions)( | |
| 51 | + `https://iam.cloud.ibm.com/identity/token?apikey=${this.config.apiKey}&grant_type=urn:ibm:params:oauth:grant-type:apikey`, | |
| 52 | + { | |
| 53 | + method: "POST", | |
| 54 | + headers: { | |
| 55 | + "Content-Type": "application/x-www-form-urlencoded", | |
| 56 | + Accept: "application/json", | |
| 57 | + }, | |
| 58 | + }, | |
| 59 | + ) | |
| 60 | + ).json()) as any; | |
| 61 | + return { | |
| 62 | + token: wxToken["access_token"], | |
| 63 | + expiration: wxToken["expiration"], | |
| 64 | + }; | |
| 65 | + } else { | |
| 66 | + // watsonx Software | |
| 67 | + if (!this.config.apiKey?.includes(":")) { | |
| 68 | + // Using ZenApiKey auth | |
| 69 | + return { | |
| 70 | + token: this.config.apiKey ?? "", | |
| 71 | + expiration: -1, | |
| 72 | + }; | |
| 73 | + } else { | |
| 74 | + // Using username/password auth | |
| 75 | + const userPass = this.config.apiKey?.split(":"); | |
| 76 | + const wxToken = (await ( | |
| 77 | + await customFetch(this.config.requestOptions)( | |
| 78 | + `${this.apiBase}/icp4d-api/v1/authorize`, | |
| 79 | + { | |
| 80 | + method: "POST", | |
| 81 | + headers: { | |
| 82 | + "Content-Type": "application/json", | |
| 83 | + Accept: "application/json", | |
| 84 | + }, | |
| 85 | + body: JSON.stringify({ | |
| 86 | + username: userPass[0], | |
| 87 | + password: userPass[1], | |
| 88 | + }), | |
| 89 | + }, | |
| 90 | + ) | |
| 91 | + ).json()) as any; | |
| 92 | + const wxTokenExpiry = (await ( | |
| 93 | + await customFetch(this.config.requestOptions)( | |
| 94 | + `${this.apiBase}/usermgmt/v1/user/tokenExpiry`, | |
| 95 | + { | |
| 96 | + method: "GET", | |
| 97 | + headers: { | |
| 98 | + Accept: "application/json", | |
| 99 | + Authorization: `Bearer ${wxToken["token"]}`, | |
| 100 | + }, | |
| 101 | + }, | |
| 102 | + ) | |
| 103 | + ).json()) as any; | |
| 104 | + return { | |
| 105 | + token: wxToken["token"], | |
| 106 | + expiration: wxTokenExpiry["exp"], | |
| 107 | + }; | |
| 108 | + } | |
| 109 | + } | |
| 110 | + } | |
| 111 | + | |
| 112 | + private getEndpoint(endpoint: string): string { | |
| 113 | + return `${this.apiBase}ml/v1/${this.deploymentId ? `deployments/${this.deploymentId}/` : ""}text/${endpoint}_stream?version=${this.apiVersion}`; | |
| 114 | + } | |
| 115 | + | |
| 116 | + private _convertBody(oaiBody: ChatCompletionCreateParams) { | |
| 117 | + const stopSequences = oaiBody.stop | |
| 118 | + ? Array.isArray(oaiBody.stop) | |
| 119 | + ? oaiBody.stop.filter((s) => s.trim() !== "") | |
| 120 | + : [oaiBody.stop] | |
| 121 | + : undefined; | |
| 122 | + | |
| 123 | + const payload: any = { | |
| 124 | + messages: oaiBody.messages, | |
| 125 | + max_tokens: oaiBody.max_tokens ?? 1024, | |
| 126 | + stop: stopSequences, | |
| 127 | + frequency_penalty: oaiBody.frequency_penalty, | |
| 128 | + presence_penalty: oaiBody.presence_penalty, | |
| 129 | + }; | |
| 130 | + | |
| 131 | + if (!this.deploymentId) { | |
| 132 | + payload.model_id = oaiBody.model; | |
| 133 | + payload.project_id = this.projectId; | |
| 134 | + } | |
| 135 | + | |
| 136 | + if (oaiBody.temperature !== undefined) { | |
| 137 | + payload.temperature = oaiBody.temperature; | |
| 138 | + } | |
| 139 | + | |
| 140 | + if (oaiBody.top_p !== undefined) { | |
| 141 | + payload.top_p = oaiBody.top_p; | |
| 142 | + } | |
| 143 | + | |
| 144 | + if (oaiBody.tools) { | |
| 145 | + payload.tools = oaiBody.tools; | |
| 146 | + if (oaiBody.tool_choice) { | |
| 147 | + payload.tool_choice = oaiBody.tool_choice; | |
| 148 | + } else { | |
| 149 | + payload.tool_choice_option = "auto"; | |
| 150 | + } | |
| 151 | + } | |
| 152 | + | |
| 153 | + return payload; | |
| 154 | + } | |
| 155 | + | |
| 156 | + async chatCompletionNonStream( | |
| 157 | + body: ChatCompletionCreateParamsNonStreaming, | |
| 158 | + signal: AbortSignal, | |
| 159 | + ): Promise<ChatCompletion> { | |
| 160 | + const generator = this.chatCompletionStream( | |
| 161 | + { | |
| 162 | + ...body, | |
| 163 | + stream: true, | |
| 164 | + }, | |
| 165 | + signal, | |
| 166 | + ); | |
| 167 | + | |
| 168 | + let content = ""; | |
| 169 | + for await (const chunk of generator) { | |
| 170 | + content += chunk.choices[0].delta.content ?? ""; | |
| 171 | + } | |
| 172 | + return chatCompletion({ | |
| 173 | + content, | |
| 174 | + model: body.model, | |
| 175 | + }); | |
| 176 | + } | |
| 177 | + | |
| 178 | + async *chatCompletionStream( | |
| 179 | + body: ChatCompletionCreateParamsStreaming, | |
| 180 | + signal: AbortSignal, | |
| 181 | + ): AsyncGenerator<ChatCompletionChunk, any, unknown> { | |
| 182 | + const url = this.getEndpoint("chat"); | |
| 183 | + const headers = await this.getHeaders(); | |
| 184 | + const stringifiedBody = JSON.stringify(this._convertBody(body)); | |
| 185 | + const response = await customFetch(this.config.requestOptions)(url, { | |
| 186 | + method: "POST", | |
| 187 | + headers, | |
| 188 | + body: stringifiedBody, | |
| 189 | + signal, | |
| 190 | + }); | |
| 191 | + | |
| 192 | + if (!response.ok || !response.body) { | |
| 193 | + throw new Error( | |
| 194 | + `Failed to stream chat completion: ${await response.text()}`, | |
| 195 | + ); | |
| 196 | + } | |
| 197 | + | |
| 198 | + for await (const value of streamSse(response as any)) { | |
| 199 | + if (!value.choices?.[0]) { | |
| 200 | + continue; | |
| 201 | + } | |
| 202 | + yield value; | |
| 203 | + } | |
| 204 | + } | |
| 205 | + | |
| 206 | + async completionNonStream( | |
| 207 | + body: CompletionCreateParamsNonStreaming, | |
| 208 | + signal: AbortSignal, | |
| 209 | + ): Promise<Completion> { | |
| 210 | + throw new Error("Method not implemented."); | |
| 211 | + } | |
| 212 | + | |
| 213 | + async *completionStream( | |
| 214 | + body: CompletionCreateParamsStreaming, | |
| 215 | + signal: AbortSignal, | |
| 216 | + ): AsyncGenerator<Completion, any, unknown> { | |
| 217 | + const params = { | |
| 218 | + decoding_method: body.temperature ? "sample" : "greedy", | |
| 219 | + max_new_tokens: body.max_tokens ?? 1024, | |
| 220 | + min_new_tokens: 1, | |
| 221 | + stop_sequences: body.stop | |
| 222 | + ? Array.isArray(body.stop) | |
| 223 | + ? body.stop | |
| 224 | + : [body.stop] | |
| 225 | + : [], | |
| 226 | + include_stop_sequence: false, | |
| 227 | + repetition_penalty: body.frequency_penalty || 1, | |
| 228 | + temperature: body.temperature, | |
| 229 | + top_p: body.top_p, | |
| 230 | + top_k: 100, | |
| 231 | + }; | |
| 232 | + | |
| 233 | + const payload: any = { | |
| 234 | + input: body.prompt, | |
| 235 | + parameters: params, | |
| 236 | + }; | |
| 237 | + | |
| 238 | + if (!this.deploymentId) { | |
| 239 | + payload.model_id = body.model; | |
| 240 | + payload.project_id = this.projectId; | |
| 241 | + } | |
| 242 | + | |
| 243 | + const url = this.getEndpoint("generation"); | |
| 244 | + const response = await customFetch(this.config.requestOptions)(url, { | |
| 245 | + method: "POST", | |
| 246 | + headers: await this.getHeaders(), | |
| 247 | + body: JSON.stringify(payload), | |
| 248 | + signal, | |
| 249 | + }); | |
| 250 | + | |
| 251 | + if (!response.ok || !response.body) { | |
| 252 | + throw new Error(`Failed to stream completion: ${await response.text()}`); | |
| 253 | + } | |
| 254 | + | |
| 255 | + let generatedText = ""; | |
| 256 | + for await (const value of streamSse(response as any)) { | |
| 257 | + const lines = value.toString().split("\n"); | |
| 258 | + let generatedChunk = ""; | |
| 259 | + | |
| 260 | + lines.forEach((line: string) => { | |
| 261 | + if (line.startsWith("data:")) { | |
| 262 | + const dataStr = line.replace(/^data:\s+/, ""); | |
| 263 | + try { | |
| 264 | + const data = JSON.parse(dataStr); | |
| 265 | + data.results.forEach((result: any) => { | |
| 266 | + generatedChunk += result.generated_text || ""; | |
| 267 | + }); | |
| 268 | + } catch (e) { | |
| 269 | + // parsing error is expected with streaming response | |
| 270 | + } | |
| 271 | + } | |
| 272 | + }); | |
| 273 | + | |
| 274 | + if (generatedChunk) { | |
| 275 | + generatedText += generatedChunk; | |
| 276 | + yield { | |
| 277 | + id: `watsonx-${Date.now()}`, | |
| 278 | + object: "text_completion", | |
| 279 | + created: Date.now(), | |
| 280 | + model: body.model, | |
| 281 | + choices: [ | |
| 282 | + { | |
| 283 | + text: generatedChunk, | |
| 284 | + index: 0, | |
| 285 | + logprobs: null, | |
| 286 | + finish_reason: "stop", | |
| 287 | + }, | |
| 288 | + ], | |
| 289 | + }; | |
| 290 | + } | |
| 291 | + } | |
| 292 | + } | |
| 293 | + | |
| 294 | + async *fimStream( | |
| 295 | + body: FimCreateParamsStreaming, | |
| 296 | + signal: AbortSignal, | |
| 297 | + ): AsyncGenerator<ChatCompletionChunk, any, unknown> { | |
| 298 | + throw new Error("Method not implemented."); | |
| 299 | + } | |
| 300 | + | |
| 301 | + async embed( | |
| 302 | + body: OpenAI.Embeddings.EmbeddingCreateParams, | |
| 303 | + ): Promise<OpenAI.Embeddings.CreateEmbeddingResponse> { | |
| 304 | + throw new Error("Method not implemented."); | |
| 305 | + } | |
| 306 | + | |
| 307 | + async rerank(body: RerankCreateParams): Promise<CreateRerankResponse> { | |
| 308 | + throw new Error("Method not implemented."); | |
| 309 | + } | |
| 310 | + | |
| 311 | + async list(): Promise<OpenAI.Models.Model[]> { | |
| 312 | + throw new Error("Method not implemented."); | |
| 313 | + } | |
| 314 | +} |
modified packages/openai-adapters/src/index.ts +8 −3
| @@ -11,6 +11,7 @@ | ||
| 11 | 11 | import { MoonshotApi } from "./apis/Moonshot.js"; |
| 12 | 12 | import { OpenAIApi } from "./apis/OpenAI.js"; |
| 13 | 13 | import { RelaceApi } from "./apis/Relace.js"; |
| 14 | +import { WatsonXApi } from "./apis/WatsonX.js"; | |
| 14 | 15 | import { BaseLlmApi } from "./apis/base.js"; |
| 15 | 16 | import { LLMConfig, OpenAIConfigSchema } from "./types.js"; |
| 16 | 17 | |
| @@ -48,6 +49,8 @@ | ||
| 48 | 49 | return new RelaceApi(config); |
| 49 | 50 | case "inception": |
| 50 | 51 | return new InceptionApi(config); |
| 52 | + case "watsonx": | |
| 53 | + return new WatsonXApi(config); | |
| 51 | 54 | case "x-ai": |
| 52 | 55 | return openAICompatible("https://api.x.ai/v1/", config); |
| 53 | 56 | case "voyage": |
| @@ -75,7 +78,10 @@ | ||
| 75 | 78 | case "nvidia": |
| 76 | 79 | return openAICompatible("https://integrate.api.nvidia.com/v1/", config); |
| 77 | 80 | case "ovhcloud": |
| 78 | - return openAICompatible("https://oai.endpoints.kepler.ai.cloud.ovh.net/v1/", config); | |
| 81 | + return openAICompatible( | |
| 82 | + "https://oai.endpoints.kepler.ai.cloud.ovh.net/v1/", | |
| 83 | + config, | |
| 84 | + ); | |
| 79 | 85 | case "scaleway": |
| 80 | 86 | return openAICompatible("https://api.scaleway.ai/v1/", config); |
| 81 | 87 | case "fireworks": |
| @@ -111,10 +117,9 @@ | ||
| 111 | 117 | type Completion, |
| 112 | 118 | type CompletionCreateParams, |
| 113 | 119 | type CompletionCreateParamsNonStreaming, |
| 114 | - type CompletionCreateParamsStreaming | |
| 120 | + type CompletionCreateParamsStreaming, | |
| 115 | 121 | } from "openai/resources/index"; |
| 116 | 122 | |
| 117 | 123 | // export |
| 118 | 124 | export type { BaseLlmApi } from "./apis/base.js"; |
| 119 | 125 | export type { LLMConfig } from "./types.js"; |
| 120 | - |
modified packages/openai-adapters/src/test/main.test.ts +1 −0
| @@ -10,6 +10,7 @@ | ||
| 10 | 10 | provider: config.provider as any, |
| 11 | 11 | apiKey: config.apiKey, |
| 12 | 12 | apiBase: config.apiBase, |
| 13 | + env: config.env, | |
| 13 | 14 | }); |
| 14 | 15 | |
| 15 | 16 | if (false) { |
modified packages/openai-adapters/src/types.ts +12 −0
| @@ -99,6 +99,17 @@ | ||
| 99 | 99 | }); |
| 100 | 100 | export type AnthropicConfig = z.infer<typeof AnthropicConfigSchema>; |
| 101 | 101 | |
| 102 | +export const WatsonXConfigSchema = BasePlusConfig.extend({ | |
| 103 | + provider: z.literal("watsonx"), | |
| 104 | + apiKey: z.string(), | |
| 105 | + env: z.object({ | |
| 106 | + apiVersion: z.string().optional(), | |
| 107 | + projectId: z.string().optional(), | |
| 108 | + deploymentId: z.string().optional(), | |
| 109 | + }), | |
| 110 | +}); | |
| 111 | +export type WatsonXConfig = z.infer<typeof WatsonXConfigSchema>; | |
| 112 | + | |
| 102 | 113 | export const JinaConfigSchema = OpenAIConfigSchema.extend({ |
| 103 | 114 | provider: z.literal("jina"), |
| 104 | 115 | }); |
| @@ -118,6 +129,7 @@ | ||
| 118 | 129 | AzureConfigSchema, |
| 119 | 130 | GeminiConfigSchema, |
| 120 | 131 | AnthropicConfigSchema, |
| 132 | + WatsonXConfigSchema, | |
| 121 | 133 | JinaConfigSchema, |
| 122 | 134 | MockConfigSchema, |
| 123 | 135 | InceptionConfigSchema, |