Changesets · Branches · Tags · Compare
| Changeset | 58de0f436bd648beb3909c9f622ff9214577aa08e6de6eda335621e206450f18 |
|---|---|
| Author | uinstinct <61635505+uinstinct@users.noreply.github.com> · 2025-06-30 11:05 +05:30 |
| Committer | uinstinct <61635505+uinstinct@users.noreply.github.com> · 2025-06-30 11:05 +05:30 |
| Parents | 37bbf3e7899b, 68e8a01e26c2 |
164 files changed
added .continue/rules/new-protocol-message.md +35 −0
| @@ -0,0 +1,35 @@ | ||
| 1 | +--- | |
| 2 | +name: New protocol message | |
| 3 | +description: Create a new protocol message from core/gui/ide to core/gui/ide | |
| 4 | +--- | |
| 5 | + | |
| 6 | +Create a new protocol message by taking the following steps: | |
| 7 | + | |
| 8 | +## 1. Define the message type | |
| 9 | + | |
| 10 | +Add your new message type definition to the appropriate file in the `protocol/` directory with correct TypeScript typing. | |
| 11 | + | |
| 12 | +## 2. Check for duplicates | |
| 13 | + | |
| 14 | +Verify that no existing message type already provides the same functionality. | |
| 15 | + | |
| 16 | +## 3. Add to passThrough (if webview ↔ core) | |
| 17 | + | |
| 18 | +If your message is between webview and core, add it to `core/protocol/passThrough.ts`. | |
| 19 | + | |
| 20 | +## 4. Add to IntelliJ constants (if webview ↔ core) | |
| 21 | + | |
| 22 | +If your message is between webview and core, add it to `extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt`. | |
| 23 | + | |
| 24 | +## 5. Implement the message handler | |
| 25 | + | |
| 26 | +Implement the message in the appropriate location: | |
| 27 | + | |
| 28 | +- **Messages to core**: `core/core.ts` | |
| 29 | +- **Messages to GUI**: `useWebviewListener` hook | |
| 30 | +- **Messages to VS Code IDE**: `VsCodeMessenger.ts` | |
| 31 | +- **Messages to JetBrains IDE**: `IdeProtocolClient.kt` | |
| 32 | + | |
| 33 | +## 6. Test the implementation | |
| 34 | + | |
| 35 | +Verify that your message works correctly in both VS Code and JetBrains IDEs if applicable. |
added .continue/rules/overeager.md +5 −0
| @@ -0,0 +1,5 @@ | ||
| 1 | +--- | |
| 2 | +name: Don't be overeager | |
| 3 | +--- | |
| 4 | + | |
| 5 | +Avoid over-eagerly adding new features. You should solve the problem at hand and then can propose further work. |
modified .github/workflows/main.yaml +8 −0
| @@ -104,6 +104,14 @@ | ||
| 104 | 104 | path: gui/node_modules |
| 105 | 105 | key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }} |
| 106 | 106 | |
| 107 | + - name: Build packages (Windows) | |
| 108 | + run: ./scripts/build-packages.ps1 | |
| 109 | + if: matrix.os == 'windows-latest' | |
| 110 | + | |
| 111 | + - name: Build packages (Unix) | |
| 112 | + run: ./scripts/build-packages.sh | |
| 113 | + if: matrix.os != 'windows-latest' | |
| 114 | + | |
| 107 | 115 | - name: Install extension Dependencies |
| 108 | 116 | run: | |
| 109 | 117 | cd extensions/vscode |
modified .github/workflows/preview.yaml +8 −0
| @@ -99,6 +99,14 @@ | ||
| 99 | 99 | path: gui/node_modules |
| 100 | 100 | key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }} |
| 101 | 101 | |
| 102 | + - name: Build packages (Windows) | |
| 103 | + run: ./scripts/build-packages.ps1 | |
| 104 | + if: matrix.os == 'windows-latest' | |
| 105 | + | |
| 106 | + - name: Build packages (Unix) | |
| 107 | + run: ./scripts/build-packages.sh | |
| 108 | + if: matrix.os != 'windows-latest' | |
| 109 | + | |
| 102 | 110 | - name: Install extension Dependencies |
| 103 | 111 | run: | |
| 104 | 112 | cd extensions/vscode |
modified .github/workflows/release-config-yaml.yml +7 −35
| @@ -9,38 +9,10 @@ | ||
| 9 | 9 | |
| 10 | 10 | jobs: |
| 11 | 11 | release: |
| 12 | - name: Release | |
| 13 | - runs-on: ubuntu-latest | |
| 14 | - steps: | |
| 15 | - - name: Checkout | |
| 16 | - uses: actions/checkout@v4 | |
| 17 | - with: | |
| 18 | - fetch-depth: 0 | |
| 19 | - | |
| 20 | - - name: Use Node.js from .nvmrc | |
| 21 | - uses: actions/setup-node@v4 | |
| 22 | - with: | |
| 23 | - node-version-file: ".nvmrc" | |
| 24 | - | |
| 25 | - - name: Install dependencies | |
| 26 | - run: | | |
| 27 | - cd packages/config-yaml | |
| 28 | - npm ci | |
| 29 | - | |
| 30 | - - name: Build | |
| 31 | - run: | | |
| 32 | - cd packages/config-yaml | |
| 33 | - npm run build | |
| 34 | - | |
| 35 | - - name: Run tests | |
| 36 | - run: | | |
| 37 | - cd packages/config-yaml | |
| 38 | - npm test | |
| 39 | - | |
| 40 | - - name: Release | |
| 41 | - env: | |
| 42 | - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} | |
| 43 | - NPM_TOKEN: ${{ secrets.NPM_TOKEN }} | |
| 44 | - run: | | |
| 45 | - cd packages/config-yaml | |
| 46 | - npx semantic-release | |
| 12 | + uses: ./.github/workflows/reusable-release.yml | |
| 13 | + with: | |
| 14 | + package-name: "config-yaml" | |
| 15 | + package-path: "packages/config-yaml" | |
| 16 | + secrets: | |
| 17 | + SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }} | |
| 18 | + SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }} |
added .github/workflows/release-fetch.yml +18 −0
| @@ -0,0 +1,18 @@ | ||
| 1 | +name: Release @continuedev/fetch | |
| 2 | + | |
| 3 | +on: | |
| 4 | + push: | |
| 5 | + branches: | |
| 6 | + - main | |
| 7 | + paths: | |
| 8 | + - "packages/fetch/**" | |
| 9 | + | |
| 10 | +jobs: | |
| 11 | + release: | |
| 12 | + uses: ./.github/workflows/reusable-release.yml | |
| 13 | + with: | |
| 14 | + package-name: "fetch" | |
| 15 | + package-path: "packages/fetch" | |
| 16 | + secrets: | |
| 17 | + SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }} | |
| 18 | + SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }} |
added .github/workflows/release-llm-info.yml +18 −0
| @@ -0,0 +1,18 @@ | ||
| 1 | +name: Release @continuedev/llm-info | |
| 2 | + | |
| 3 | +on: | |
| 4 | + push: | |
| 5 | + branches: | |
| 6 | + - main | |
| 7 | + paths: | |
| 8 | + - "packages/llm-info/**" | |
| 9 | + | |
| 10 | +jobs: | |
| 11 | + release: | |
| 12 | + uses: ./.github/workflows/reusable-release.yml | |
| 13 | + with: | |
| 14 | + package-name: "llm-info" | |
| 15 | + package-path: "packages/llm-info" | |
| 16 | + secrets: | |
| 17 | + SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }} | |
| 18 | + SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }} |
added .github/workflows/release-openai-adapters.yml +18 −0
| @@ -0,0 +1,18 @@ | ||
| 1 | +name: Release @continuedev/openai-adapters | |
| 2 | + | |
| 3 | +on: | |
| 4 | + push: | |
| 5 | + branches: | |
| 6 | + - main | |
| 7 | + paths: | |
| 8 | + - "packages/openai-adapters/**" | |
| 9 | + | |
| 10 | +jobs: | |
| 11 | + release: | |
| 12 | + uses: ./.github/workflows/reusable-release.yml | |
| 13 | + with: | |
| 14 | + package-name: "openai-adapters" | |
| 15 | + package-path: "packages/openai-adapters" | |
| 16 | + secrets: | |
| 17 | + SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }} | |
| 18 | + SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }} |
added .github/workflows/reusable-release.yml +55 −0
| @@ -0,0 +1,55 @@ | ||
| 1 | +name: Reusable Release Workflow | |
| 2 | + | |
| 3 | +on: | |
| 4 | + workflow_call: | |
| 5 | + inputs: | |
| 6 | + package-name: | |
| 7 | + required: true | |
| 8 | + type: string | |
| 9 | + package-path: | |
| 10 | + required: true | |
| 11 | + type: string | |
| 12 | + secrets: | |
| 13 | + SEMANTIC_RELEASE_GITHUB_TOKEN: | |
| 14 | + required: true | |
| 15 | + SEMANTIC_RELEASE_NPM_TOKEN: | |
| 16 | + required: true | |
| 17 | + | |
| 18 | +permissions: | |
| 19 | + contents: write | |
| 20 | + issues: write | |
| 21 | + pull-requests: write | |
| 22 | + | |
| 23 | +jobs: | |
| 24 | + release: | |
| 25 | + name: Release ${{ inputs.package-name }} | |
| 26 | + runs-on: ubuntu-latest | |
| 27 | + defaults: | |
| 28 | + run: | |
| 29 | + working-directory: ${{ inputs.package-path }} | |
| 30 | + steps: | |
| 31 | + - name: Checkout | |
| 32 | + uses: actions/checkout@v4 | |
| 33 | + with: | |
| 34 | + fetch-depth: 0 | |
| 35 | + | |
| 36 | + - name: Use Node.js from .nvmrc | |
| 37 | + uses: actions/setup-node@v4 | |
| 38 | + with: | |
| 39 | + node-version-file: ".nvmrc" | |
| 40 | + | |
| 41 | + - name: Install dependencies | |
| 42 | + run: npm ci | |
| 43 | + | |
| 44 | + - name: Build | |
| 45 | + run: npm run build | |
| 46 | + | |
| 47 | + - name: Run tests | |
| 48 | + run: npm test | |
| 49 | + | |
| 50 | + - name: Release | |
| 51 | + env: | |
| 52 | + GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }} | |
| 53 | + NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }} | |
| 54 | + NODE_AUTH_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }} | |
| 55 | + run: npx semantic-release | |
| No newline at the end of the file |
modified .vscode/launch.json +0 −26
| @@ -73,32 +73,6 @@ | ||
| 73 | 73 | "sourceMaps": true |
| 74 | 74 | // "preLaunchTask": "gui:dev" |
| 75 | 75 | }, |
| 76 | - // Has to be run after starting the server (separately or using the compound configuration) | |
| 77 | - { | |
| 78 | - "name": "Run tests", | |
| 79 | - "type": "extensionHost", | |
| 80 | - "request": "launch", | |
| 81 | - "cwd": "${workspaceFolder}/extensions/vscode", | |
| 82 | - "runtimeExecutable": "${execPath}", | |
| 83 | - "args": [ | |
| 84 | - // Pass a directory to run tests in | |
| 85 | - "${workspaceFolder}/extensions/vscode/manual-testing-sandbox", | |
| 86 | - "--extensionDevelopmentPath=${workspaceFolder}/extensions/vscode", | |
| 87 | - "--extensionTestsPath=${workspaceFolder}/extensions/vscode/out/test/runner/mochaRunner" | |
| 88 | - ], | |
| 89 | - "outFiles": [ | |
| 90 | - // Allows setting breakpoints in test suites across the /src folder | |
| 91 | - "${workspaceFolder}/extensions/vscode/out/test/test-suites/**/*.js", | |
| 92 | - // Allows setting breakpoints in mocha test runner file | |
| 93 | - "${workspaceFolder}/extensions/vscode/out/test/runner/**/*.js" | |
| 94 | - ], | |
| 95 | - "internalConsoleOptions": "openOnSessionStart", | |
| 96 | - "preLaunchTask": "vscode-extension:tests:build", | |
| 97 | - "env": { | |
| 98 | - // Avoid timing out when stopping on breakpoints during debugging in VSCode | |
| 99 | - "MOCHA_TIMEOUT": "0" | |
| 100 | - } | |
| 101 | - }, | |
| 102 | 76 | { |
| 103 | 77 | "name": "[Core] Jest Test Debugger, Current Open File", |
| 104 | 78 | "type": "node", |
modified .vscode/tasks.json +3 −33
| @@ -103,42 +103,12 @@ | ||
| 103 | 103 | "clear": true |
| 104 | 104 | }, |
| 105 | 105 | "options": { |
| 106 | + "env": { | |
| 107 | + "SKIP_INSTALLS": "true" | |
| 108 | + }, | |
| 106 | 109 | "cwd": "${workspaceFolder}/extensions/vscode" |
| 107 | 110 | } |
| 108 | 111 | }, |
| 109 | - // | |
| 110 | - // Compile and bundle tests | |
| 111 | - { | |
| 112 | - "label": "vscode-extension:tests:build", | |
| 113 | - "dependsOn": [ | |
| 114 | - // Build the extension | |
| 115 | - "vscode-extension:build", | |
| 116 | - // To detect compile errors - this type checks both the extension and the tests | |
| 117 | - "tsc:watch", | |
| 118 | - "vscode-extension:tests:esbuild" | |
| 119 | - ] | |
| 120 | - }, | |
| 121 | - { | |
| 122 | - "label": "vscode-extension:tests:esbuild", | |
| 123 | - "type": "npm", | |
| 124 | - "script": "build-test", | |
| 125 | - "path": "extensions/vscode", | |
| 126 | - "problemMatcher": [ | |
| 127 | - { | |
| 128 | - "pattern": [ | |
| 129 | - { | |
| 130 | - "regexp": "> (.*?):([0-9]+):([0-9]+): (warning|error): (.+)$", | |
| 131 | - "file": 1, | |
| 132 | - "line": 2, | |
| 133 | - "column": 3, | |
| 134 | - "severity": 4, | |
| 135 | - "message": 5 | |
| 136 | - } | |
| 137 | - ] | |
| 138 | - } | |
| 139 | - ] | |
| 140 | - }, | |
| 141 | - // | |
| 142 | 112 | // Install or update all dependencies for all projects in the monrepo |
| 143 | 113 | { |
| 144 | 114 | "label": "install-all-dependencies", |
modified binary/build.js +26 −144
| @@ -3,13 +3,13 @@ | ||
| 3 | 3 | const path = require("path"); |
| 4 | 4 | const ncp = require("ncp").ncp; |
| 5 | 5 | const { rimrafSync } = require("rimraf"); |
| 6 | -const { | |
| 7 | - validateFilesPresent, | |
| 8 | - execCmdSync, | |
| 9 | - autodetectPlatformAndArch, | |
| 10 | -} = require("../scripts/util"); | |
| 11 | -const { downloadRipgrep } = require("./utils/ripgrep"); | |
| 6 | +const { validateFilesPresent } = require("../scripts/util"); | |
| 12 | 7 | const { ALL_TARGETS, TARGET_TO_LANCEDB } = require("./utils/targets"); |
| 8 | +const { fork } = require("child_process"); | |
| 9 | +const { | |
| 10 | + installAndCopyNodeModules, | |
| 11 | +} = require("../extensions/vscode/scripts/install-copy-nodemodule"); | |
| 12 | +const { bundleBinary } = require("./utils/bundle-binary"); | |
| 13 | 13 | |
| 14 | 14 | const bin = path.join(__dirname, "bin"); |
| 15 | 15 | const out = path.join(__dirname, "out"); |
| @@ -29,8 +29,6 @@ | ||
| 29 | 29 | const esbuildOutputFile = "out/index.js"; |
| 30 | 30 | let targets = [...ALL_TARGETS]; |
| 31 | 31 | |
| 32 | -const [currentPlatform, currentArch] = autodetectPlatformAndArch(); | |
| 33 | - | |
| 34 | 32 | const assetBackups = [ |
| 35 | 33 | "node_modules/win-ca/lib/crypt32-ia32.node.bak", |
| 36 | 34 | "node_modules/win-ca/lib/crypt32-x64.node.bak", |
| @@ -78,85 +76,6 @@ | ||
| 78 | 76 | }); |
| 79 | 77 | } |
| 80 | 78 | |
| 81 | -async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) { | |
| 82 | - console.log(`Copying ${packageName} to ${toCopy}`); | |
| 83 | - // This is a way to install only one package without npm trying to install all the dependencies | |
| 84 | - // Create a temporary directory for installing the package | |
| 85 | - const adjustedName = packageName.replace(/@/g, "").replace("/", "-"); | |
| 86 | - const tempDir = path.join( | |
| 87 | - __dirname, | |
| 88 | - "tmp", | |
| 89 | - `continue-node_modules-${adjustedName}`, | |
| 90 | - ); | |
| 91 | - const currentDir = process.cwd(); | |
| 92 | - | |
| 93 | - // // Remove the dir we will be copying to | |
| 94 | - // rimrafSync(`node_modules/${toCopy}`); | |
| 95 | - | |
| 96 | - // // Ensure the temporary directory exists | |
| 97 | - fs.mkdirSync(tempDir, { recursive: true }); | |
| 98 | - | |
| 99 | - try { | |
| 100 | - // Move to the temporary directory | |
| 101 | - process.chdir(tempDir); | |
| 102 | - | |
| 103 | - // Initialize a new package.json and install the package | |
| 104 | - execCmdSync(`npm init -y && npm i -f ${packageName} --no-save`); | |
| 105 | - | |
| 106 | - console.log( | |
| 107 | - `Contents of: ${packageName}`, | |
| 108 | - fs.readdirSync(path.join(tempDir, "node_modules", toCopy)), | |
| 109 | - ); | |
| 110 | - | |
| 111 | - // Without this it seems the file isn't completely written to disk | |
| 112 | - await new Promise((resolve) => setTimeout(resolve, 2000)); | |
| 113 | - | |
| 114 | - // Copy the installed package back to the current directory | |
| 115 | - await new Promise((resolve, reject) => { | |
| 116 | - ncp( | |
| 117 | - path.join(tempDir, "node_modules", toCopy), | |
| 118 | - path.join(currentDir, "node_modules", toCopy), | |
| 119 | - { dereference: true }, | |
| 120 | - (error) => { | |
| 121 | - if (error) { | |
| 122 | - console.error( | |
| 123 | - `[error] Error copying ${packageName} package`, | |
| 124 | - error, | |
| 125 | - ); | |
| 126 | - reject(error); | |
| 127 | - } else { | |
| 128 | - resolve(); | |
| 129 | - } | |
| 130 | - }, | |
| 131 | - ); | |
| 132 | - }); | |
| 133 | - } finally { | |
| 134 | - // Clean up the temporary directory | |
| 135 | - // rimrafSync(tempDir); | |
| 136 | - | |
| 137 | - // Return to the original directory | |
| 138 | - process.chdir(currentDir); | |
| 139 | - } | |
| 140 | -} | |
| 141 | - | |
| 142 | -/** | |
| 143 | - * Downloads and installs ripgrep binaries for the specified target | |
| 144 | - * | |
| 145 | - * @param {string} target - Target platform-arch (e.g., 'darwin-x64') | |
| 146 | - * @param {string} targetDir - Directory to install ripgrep to | |
| 147 | - * @returns {Promise<void>} | |
| 148 | - */ | |
| 149 | -async function downloadRipgrepForTarget(target, targetDir) { | |
| 150 | - console.log(`[info] Downloading ripgrep for ${target}...`); | |
| 151 | - try { | |
| 152 | - await downloadRipgrep(target, targetDir); | |
| 153 | - console.log(`[info] Successfully installed ripgrep for ${target}`); | |
| 154 | - } catch (error) { | |
| 155 | - console.error(`[error] Failed to download ripgrep for ${target}:`, error); | |
| 156 | - throw error; | |
| 157 | - } | |
| 158 | -} | |
| 159 | - | |
| 160 | 79 | (async () => { |
| 161 | 80 | if (esbuildOnly) { |
| 162 | 81 | await buildWithEsbuild(); |
| @@ -181,16 +100,21 @@ | ||
| 181 | 100 | ), |
| 182 | 101 | ); |
| 183 | 102 | |
| 184 | - console.log("[info] Downloading prebuilt lancedb..."); | |
| 103 | + const copyLanceDBPromises = []; | |
| 185 | 104 | for (const target of targets) { |
| 186 | - if (TARGET_TO_LANCEDB[target]) { | |
| 187 | - console.log(`[info] Downloading for ${target}...`); | |
| 188 | - await installNodeModuleInTempDirAndCopyToCurrent( | |
| 189 | - TARGET_TO_LANCEDB[target], | |
| 190 | - "@lancedb", | |
| 191 | - ); | |
| 105 | + if (!TARGET_TO_LANCEDB[target]) { | |
| 106 | + continue; | |
| 192 | 107 | } |
| 108 | + console.log(`[info] Downloading for ${target}...`); | |
| 109 | + copyLanceDBPromises.push( | |
| 110 | + installAndCopyNodeModules(TARGET_TO_LANCEDB[target], "@lancedb"), | |
| 111 | + ); | |
| 193 | 112 | } |
| 113 | + await Promise.all(copyLanceDBPromises).catch(() => { | |
| 114 | + console.error("[error] Failed to copy LanceDB"); | |
| 115 | + process.exit(1); | |
| 116 | + }); | |
| 117 | + console.log("[info] Copied all LanceDB"); | |
| 194 | 118 | |
| 195 | 119 | // tree-sitter-wasm |
| 196 | 120 | const treeSitterWasmsDir = path.join(out, "tree-sitter-wasms"); |
| @@ -252,59 +176,16 @@ | ||
| 252 | 176 | "out/llamaTokenizerWorkerPool.mjs", |
| 253 | 177 | ); |
| 254 | 178 | |
| 179 | + const buildBinaryPromises = []; | |
| 255 | 180 | console.log("[info] Building binaries with pkg..."); |
| 256 | 181 | for (const target of targets) { |
| 257 | - const targetDir = `bin/${target}`; | |
| 258 | - fs.mkdirSync(targetDir, { recursive: true }); | |
| 259 | - console.log(`[info] Building ${target}...`); | |
| 260 | - execCmdSync( | |
| 261 | - `npx pkg --no-bytecode --public-packages "*" --public --compress GZip pkgJson/${target} --out-path ${targetDir}`, | |
| 262 | - ); | |
| 263 | - | |
| 264 | - // Download and unzip prebuilt sqlite3 binary for the target | |
| 265 | - console.log("[info] Downloading node-sqlite3"); | |
| 266 | - | |
| 267 | - const downloadUrl = | |
| 268 | - // node-sqlite3 doesn't have a pre-built binary for win32-arm64 | |
| 269 | - target === "win32-arm64" | |
| 270 | - ? "https://continue-server-binaries.s3.us-west-1.amazonaws.com/win32-arm64/node_sqlite3.tar.gz" | |
| 271 | - : `https://github.com/TryGhost/node-sqlite3/releases/download/v5.1.7/sqlite3-v5.1.7-napi-v6-${ | |
| 272 | - target | |
| 273 | - }.tar.gz`; | |
| 274 | - | |
| 275 | - execCmdSync(`curl -L -o ${targetDir}/build.tar.gz ${downloadUrl}`); | |
| 276 | - execCmdSync(`cd ${targetDir} && tar -xvzf build.tar.gz`); | |
| 277 | - | |
| 278 | - // Copy to build directory for testing | |
| 279 | - try { | |
| 280 | - const [platform, arch] = target.split("-"); | |
| 281 | - if (platform === currentPlatform && arch === currentArch) { | |
| 282 | - fs.copyFileSync( | |
| 283 | - `${targetDir}/build/Release/node_sqlite3.node`, | |
| 284 | - `build/node_sqlite3.node`, | |
| 285 | - ); | |
| 286 | - } | |
| 287 | - } catch (error) { | |
| 288 | - console.log("[warn] Could not copy node_sqlite to build"); | |
| 289 | - console.log(error); | |
| 290 | - } | |
| 291 | - | |
| 292 | - fs.unlinkSync(`${targetDir}/build.tar.gz`); | |
| 293 | - | |
| 294 | - // copy @lancedb to bin folders | |
| 295 | - console.log("[info] Copying @lancedb files to bin"); | |
| 296 | - fs.copyFileSync( | |
| 297 | - `node_modules/${TARGET_TO_LANCEDB[target]}/index.node`, | |
| 298 | - `${targetDir}/index.node`, | |
| 299 | - ); | |
| 300 | - | |
| 301 | - // Download and install ripgrep for the target | |
| 302 | - await downloadRipgrepForTarget(target, targetDir); | |
| 303 | - | |
| 304 | - // Informs the `continue-binary` of where to look for node_sqlite3.node | |
| 305 | - // https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found | |
| 306 | - fs.writeFileSync(`${targetDir}/package.json`, ""); | |
| 182 | + buildBinaryPromises.push(bundleBinary(target)); | |
| 307 | 183 | } |
| 184 | + await Promise.all(buildBinaryPromises).catch(() => { | |
| 185 | + console.error("[error] Failed to build binaries"); | |
| 186 | + process.exit(1); | |
| 187 | + }); | |
| 188 | + console.log("[info] All binaries built"); | |
| 308 | 189 | |
| 309 | 190 | // Cleanup - this is needed when running locally |
| 310 | 191 | fs.rmSync("out/package.json"); |
| @@ -331,4 +212,5 @@ | ||
| 331 | 212 | validateFilesPresent(pathsToVerify); |
| 332 | 213 | |
| 333 | 214 | console.log("[info] Done!"); |
| 215 | + process.exit(0); | |
| 334 | 216 | })(); |
modified binary/package-lock.json +2 −4
| @@ -53,9 +53,9 @@ | ||
| 53 | 53 | "@aws-sdk/credential-providers": "^3.778.0", |
| 54 | 54 | "@continuedev/config-types": "^1.0.13", |
| 55 | 55 | "@continuedev/config-yaml": "file:../packages/config-yaml", |
| 56 | - "@continuedev/fetch": "^1.0.13", | |
| 56 | + "@continuedev/fetch": "^1.0.14", | |
| 57 | 57 | "@continuedev/llm-info": "^1.0.8", |
| 58 | - "@continuedev/openai-adapters": "^1.0.32", | |
| 58 | + "@continuedev/openai-adapters": "file:../packages/openai-adapters", | |
| 59 | 59 | "@modelcontextprotocol/sdk": "^1.12.0", |
| 60 | 60 | "@mozilla/readability": "^0.5.0", |
| 61 | 61 | "@octokit/rest": "^20.1.1", |
| @@ -106,7 +106,6 @@ | ||
| 106 | 106 | "sqlite3": "^5.1.7", |
| 107 | 107 | "system-ca": "^1.0.3", |
| 108 | 108 | "tar": "^7.4.3", |
| 109 | - "tree-sitter-structured-text": "^0.0.1", | |
| 110 | 109 | "tree-sitter-wasms": "^0.1.11", |
| 111 | 110 | "uuid": "^9.0.1", |
| 112 | 111 | "vectordb": "^0.4.20", |
| @@ -145,7 +144,6 @@ | ||
| 145 | 144 | "myers-diff": "^2.1.0", |
| 146 | 145 | "onnxruntime-common": "1.14.0", |
| 147 | 146 | "onnxruntime-web": "1.14.0", |
| 148 | - "tree-sitter-cli": "^0.22.5", | |
| 149 | 147 | "ts-jest": "^29.1.1", |
| 150 | 148 | "typescript": "^5.6.3", |
| 151 | 149 | "vitest": "^3.1.4" |
added binary/utils/bundle-binary.js +103 −0
| @@ -0,0 +1,103 @@ | ||
| 1 | +/** | |
| 2 | + * @file Builds the binary for the specified target. It is also intended to run as a child process. | |
| 3 | + */ | |
| 4 | + | |
| 5 | +const { | |
| 6 | + execCmdSync, | |
| 7 | + autodetectPlatformAndArch, | |
| 8 | +} = require("../../scripts/util"); | |
| 9 | +const { downloadRipgrep } = require("./ripgrep"); | |
| 10 | +const { TARGET_TO_LANCEDB } = require("../utils/targets"); | |
| 11 | +const fs = require("fs"); | |
| 12 | +const { | |
| 13 | + downloadSqlite, | |
| 14 | +} = require("../../extensions/vscode/scripts/download-copy-sqlite-esbuild"); | |
| 15 | +const { fork } = require("child_process"); | |
| 16 | + | |
| 17 | +async function downloadNodeSqlite(target, targetDir) { | |
| 18 | + const [currentPlatform, currentArch] = autodetectPlatformAndArch(); | |
| 19 | + | |
| 20 | + // Download and unzip prebuilt sqlite3 binary for the target | |
| 21 | + console.log("[info] Downloading node-sqlite3"); | |
| 22 | + | |
| 23 | + await downloadSqlite(target, `${targetDir}/build.tar.gz`); | |
| 24 | + | |
| 25 | + execCmdSync(`cd ${targetDir} && tar -xvzf build.tar.gz`); | |
| 26 | + | |
| 27 | + // Copy to build directory for testing | |
| 28 | + try { | |
| 29 | + const [platform, arch] = target.split("-"); | |
| 30 | + if (platform === currentPlatform && arch === currentArch) { | |
| 31 | + fs.copyFileSync( | |
| 32 | + `${targetDir}/build/Release/node_sqlite3.node`, | |
| 33 | + `build/node_sqlite3.node`, | |
| 34 | + ); | |
| 35 | + } | |
| 36 | + } catch (error) { | |
| 37 | + console.log("[warn] Could not copy node_sqlite to build"); | |
| 38 | + console.log(error); | |
| 39 | + } | |
| 40 | + fs.unlinkSync(`${targetDir}/build.tar.gz`); | |
| 41 | +} | |
| 42 | + | |
| 43 | +/** | |
| 44 | + * @param {string} target the platform to build for | |
| 45 | + */ | |
| 46 | +async function bundleForBinary(target) { | |
| 47 | + const targetDir = `bin/${target}`; | |
| 48 | + fs.mkdirSync(targetDir, { recursive: true }); | |
| 49 | + console.log(`[info] Building ${target}...`); | |
| 50 | + execCmdSync( | |
| 51 | + `npx pkg --no-bytecode --public-packages "*" --public --compress GZip pkgJson/${target} --out-path ${targetDir}`, | |
| 52 | + ); | |
| 53 | + | |
| 54 | + // copy @lancedb to bin folders | |
| 55 | + console.log("[info] Copying @lancedb files to bin"); | |
| 56 | + fs.copyFileSync( | |
| 57 | + `node_modules/${TARGET_TO_LANCEDB[target]}/index.node`, | |
| 58 | + `${targetDir}/index.node`, | |
| 59 | + ); | |
| 60 | + | |
| 61 | + const downloadPromises = []; | |
| 62 | + downloadPromises.push(downloadRipgrep(target, targetDir)); | |
| 63 | + downloadPromises.push(downloadNodeSqlite(target, targetDir)); | |
| 64 | + await Promise.all(downloadPromises); | |
| 65 | + | |
| 66 | + // Informs the `continue-binary` of where to look for node_sqlite3.node | |
| 67 | + // https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found | |
| 68 | + fs.writeFileSync(`${targetDir}/package.json`, ""); | |
| 69 | +} | |
| 70 | + | |
| 71 | +process.on("message", (msg) => { | |
| 72 | + bundleForBinary(msg.payload.target) | |
| 73 | + .then(() => process.send({ done: true })) | |
| 74 | + .catch((error) => { | |
| 75 | + console.error(error); // show the error in the parent process | |
| 76 | + process.send({ error: true }); | |
| 77 | + }); | |
| 78 | +}); | |
| 79 | + | |
| 80 | +/** | |
| 81 | + * @param {string} target the platform to bundle for | |
| 82 | + */ | |
| 83 | +async function bundleBinary(target) { | |
| 84 | + const child = fork(__filename, { stdio: "inherit" }); | |
| 85 | + child.send({ | |
| 86 | + payload: { | |
| 87 | + target, | |
| 88 | + }, | |
| 89 | + }); | |
| 90 | + return new Promise((resolve, reject) => { | |
| 91 | + child.on("message", (msg) => { | |
| 92 | + if (msg.error) { | |
| 93 | + reject(); | |
| 94 | + } else { | |
| 95 | + resolve(); | |
| 96 | + } | |
| 97 | + }); | |
| 98 | + }); | |
| 99 | +} | |
| 100 | + | |
| 101 | +module.exports = { | |
| 102 | + bundleBinary, | |
| 103 | +}; |
deleted core/commands/index.ts +0 −88
| @@ -1,88 +0,0 @@ | ||
| 1 | -import { CustomCommand, SlashCommand, SlashCommandDescription } from "../"; | |
| 2 | -import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString"; | |
| 3 | -import { replaceSlashCommandWithPromptInChatHistory } from "../promptFiles/v1/updateChatHistory"; | |
| 4 | -import { renderPromptFileV2 } from "../promptFiles/v2/renderPromptFile"; | |
| 5 | -import { renderChatMessage } from "../util/messageContent"; | |
| 6 | - | |
| 7 | -import SlashCommands from "./slash"; | |
| 8 | - | |
| 9 | -export function slashFromCustomCommand( | |
| 10 | - customCommand: CustomCommand, | |
| 11 | -): SlashCommand { | |
| 12 | - const commandName = customCommand.name.startsWith("/") | |
| 13 | - ? customCommand.name.substring(1) | |
| 14 | - : customCommand.name; | |
| 15 | - return { | |
| 16 | - name: commandName, | |
| 17 | - description: customCommand.description ?? "", | |
| 18 | - prompt: customCommand.prompt, | |
| 19 | - run: async function* ({ | |
| 20 | - input, | |
| 21 | - llm, | |
| 22 | - history, | |
| 23 | - ide, | |
| 24 | - completionOptions, | |
| 25 | - config, | |
| 26 | - selectedCode, | |
| 27 | - fetch, | |
| 28 | - abortController, | |
| 29 | - }) { | |
| 30 | - // Render prompt template | |
| 31 | - let renderedPrompt: string; | |
| 32 | - if (customCommand.prompt.includes("{{{ input }}}")) { | |
| 33 | - renderedPrompt = await renderTemplatedString( | |
| 34 | - customCommand.prompt, | |
| 35 | - ide.readFile.bind(ide), | |
| 36 | - { input }, | |
| 37 | - ); | |
| 38 | - } else { | |
| 39 | - const renderedPromptFile = await renderPromptFileV2( | |
| 40 | - customCommand.prompt, | |
| 41 | - { | |
| 42 | - config, | |
| 43 | - llm, | |
| 44 | - ide, | |
| 45 | - selectedCode, | |
| 46 | - fetch, | |
| 47 | - fullInput: input, | |
| 48 | - embeddingsProvider: config.modelsByRole.embed[0], | |
| 49 | - reranker: config.modelsByRole.rerank[0], | |
| 50 | - }, | |
| 51 | - ); | |
| 52 | - | |
| 53 | - renderedPrompt = renderedPromptFile[1]; | |
| 54 | - } | |
| 55 | - | |
| 56 | - // Replaces slash command messages with the rendered prompt | |
| 57 | - // which INCLUDES the input | |
| 58 | - const messages = replaceSlashCommandWithPromptInChatHistory( | |
| 59 | - history, | |
| 60 | - commandName, | |
| 61 | - renderedPrompt, | |
| 62 | - undefined, | |
| 63 | - ); | |
| 64 | - | |
| 65 | - for await (const chunk of llm.streamChat( | |
| 66 | - messages, | |
| 67 | - abortController.signal, | |
| 68 | - completionOptions, | |
| 69 | - )) { | |
| 70 | - yield renderChatMessage(chunk); | |
| 71 | - } | |
| 72 | - }, | |
| 73 | - }; | |
| 74 | -} | |
| 75 | - | |
| 76 | -export function slashCommandFromDescription( | |
| 77 | - desc: SlashCommandDescription, | |
| 78 | -): SlashCommand | undefined { | |
| 79 | - const cmd = SlashCommands.find((cmd) => cmd.name === desc.name); | |
| 80 | - if (!cmd) { | |
| 81 | - return undefined; | |
| 82 | - } | |
| 83 | - return { | |
| 84 | - ...cmd, | |
| 85 | - params: desc.params, | |
| 86 | - description: desc.description ?? cmd.description, | |
| 87 | - }; | |
| 88 | -} |
added core/commands/slash/built-in-legacy/cmd.ts +62 −0
| @@ -0,0 +1,62 @@ | ||
| 1 | +import { streamLines } from "../../../diff/util.js"; | |
| 2 | +import { SlashCommand } from "../../../index.js"; | |
| 3 | +import { removeQuotesAndEscapes } from "../../../util/index.js"; | |
| 4 | + | |
| 5 | +function commandIsPotentiallyDangerous(command: string) { | |
| 6 | + return ( | |
| 7 | + command.includes("rm -rf") || | |
| 8 | + command.includes("sudo") || | |
| 9 | + command.includes("cd / ") | |
| 10 | + ); | |
| 11 | +} | |
| 12 | + | |
| 13 | +const GenerateTerminalCommand: SlashCommand = { | |
| 14 | + name: "cmd", | |
| 15 | + description: "Generate a shell command", | |
| 16 | + run: async function* ({ ide, llm, input }) { | |
| 17 | + if (input.trim() === "") { | |
| 18 | + yield "Please provide a description of the shell command you want to generate. For example, '/cmd List all files in the current directory'."; | |
| 19 | + return; | |
| 20 | + } | |
| 21 | + | |
| 22 | + const gen = llm.streamComplete( | |
| 23 | + `The user has made a request to run a shell command. Their description of what it should do is: | |
| 24 | + | |
| 25 | +"${input}" | |
| 26 | + | |
| 27 | +Please write a shell command that will do what the user requested. Your output should consist of only the command itself, without any explanation or example output. Do not use any newlines. Only output the command that when inserted into the terminal will do precisely what was requested. Here is the command:`, | |
| 28 | + new AbortController().signal, | |
| 29 | + ); | |
| 30 | + | |
| 31 | + const lines = streamLines(gen); | |
| 32 | + let cmd = ""; | |
| 33 | + for await (const line of lines) { | |
| 34 | + console.log(line); | |
| 35 | + if (line.startsWith("```") && line.endsWith("```")) { | |
| 36 | + cmd = line.split(" ").slice(1).join(" ").slice(0, -3); | |
| 37 | + break; | |
| 38 | + } | |
| 39 | + | |
| 40 | + if ( | |
| 41 | + line.startsWith(">") || | |
| 42 | + line.startsWith("``") || | |
| 43 | + line.startsWith("\\begin{") || | |
| 44 | + line.trim() === "" | |
| 45 | + ) { | |
| 46 | + continue; | |
| 47 | + } | |
| 48 | + | |
| 49 | + cmd = removeQuotesAndEscapes(line.trim()); | |
| 50 | + break; | |
| 51 | + } | |
| 52 | + | |
| 53 | + yield `Generated shell command: ${cmd}`; | |
| 54 | + if (commandIsPotentiallyDangerous(cmd)) { | |
| 55 | + yield "\n\nWarning: This command may be potentially dangerous. Please double-check before pasting it in your terminal."; | |
| 56 | + } else { | |
| 57 | + await ide.runCommand(cmd); | |
| 58 | + } | |
| 59 | + }, | |
| 60 | +}; | |
| 61 | + | |
| 62 | +export default GenerateTerminalCommand; |
added core/commands/slash/built-in-legacy/commit.ts +26 −0
| @@ -0,0 +1,26 @@ | ||
| 1 | +import { SlashCommand } from "../../../index.js"; | |
| 2 | +import { renderChatMessage } from "../../../util/messageContent.js"; | |
| 3 | + | |
| 4 | +const CommitMessageCommand: SlashCommand = { | |
| 5 | + name: "commit", | |
| 6 | + description: "Generate a commit message for current changes", | |
| 7 | + run: async function* ({ ide, llm, params, abortController }) { | |
| 8 | + const includeUnstaged = params?.includeUnstaged ?? false; | |
| 9 | + const diff = await ide.getDiff(includeUnstaged); | |
| 10 | + | |
| 11 | + if (diff.length === 0) { | |
| 12 | + yield "No changes detected. Make sure you are in a git repository with current changes."; | |
| 13 | + return; | |
| 14 | + } | |
| 15 | + | |
| 16 | + const prompt = `${diff.join("\n")}\n\nGenerate a commit message for the above set of changes. First, give a single sentence, no more than 80 characters. Then, after 2 line breaks, give a list of no more than 5 short bullet points, each no more than 40 characters. Output nothing except for the commit message, and don't surround it in quotes.`; | |
| 17 | + for await (const chunk of llm.streamChat( | |
| 18 | + [{ role: "user", content: prompt }], | |
| 19 | + abortController.signal, | |
| 20 | + )) { | |
| 21 | + yield renderChatMessage(chunk); | |
| 22 | + } | |
| 23 | + }, | |
| 24 | +}; | |
| 25 | + | |
| 26 | +export default CommitMessageCommand; |
added core/commands/slash/built-in-legacy/draftIssue.ts +62 −0
| @@ -0,0 +1,62 @@ | ||
| 1 | +import { ChatMessage, SlashCommand } from "../../../index.js"; | |
| 2 | +import { removeQuotesAndEscapes } from "../../../util/index.js"; | |
| 3 | +import { renderChatMessage } from "../../../util/messageContent.js"; | |
| 4 | + | |
| 5 | +const PROMPT = ( | |
| 6 | + input: string, | |
| 7 | + title: string, | |
| 8 | +) => `You will be asked to generate the body of a GitHub issue given a user request. You should follow these rules: | |
| 9 | +- Be descriptive but do not make up details | |
| 10 | +- If the the user request includes any code snippets that are relevant, reference them in code blocks | |
| 11 | +- Describe step by step how to reproduce the problem | |
| 12 | +- Describe the ideal solution to the problem | |
| 13 | +- Describe the expected behavior after the issue has been resolved | |
| 14 | +- This issue will be read by a team member | |
| 15 | +- Use markdown formatting, but you do not need to surround the entire body with triple backticks | |
| 16 | +{additional_instructions} | |
| 17 | + | |
| 18 | +Here is the user request: '${input}' | |
| 19 | + | |
| 20 | +Title: ${title} | |
| 21 | + | |
| 22 | +Body:\n\n`; | |
| 23 | + | |
| 24 | +const DraftIssueCommand: SlashCommand = { | |
| 25 | + name: "issue", | |
| 26 | + description: "Draft a GitHub issue", | |
| 27 | + run: async function* ({ input, llm, history, params, abortController }) { | |
| 28 | + if (params?.repositoryUrl === undefined) { | |
| 29 | + yield "This command requires a repository URL to be set in the config file."; | |
| 30 | + return; | |
| 31 | + } | |
| 32 | + let title = await llm.complete( | |
| 33 | + `Generate a title for the GitHub issue requested in this user input: '${input}'. Use no more than 20 words and output nothing other than the title. Do not surround it with quotes. The title is: `, | |
| 34 | + new AbortController().signal, | |
| 35 | + { maxTokens: 30 }, | |
| 36 | + ); | |
| 37 | + | |
| 38 | + title = `${removeQuotesAndEscapes(title.trim())}\n\n`; | |
| 39 | + yield title; | |
| 40 | + | |
| 41 | + let body = ""; | |
| 42 | + const messages: ChatMessage[] = [ | |
| 43 | + ...history.filter((msg) => msg.role !== "system"), | |
| 44 | + { role: "user", content: PROMPT(input, title) }, | |
| 45 | + ]; | |
| 46 | + | |
| 47 | + for await (const chunk of llm.streamChat( | |
| 48 | + messages, | |
| 49 | + abortController.signal, | |
| 50 | + )) { | |
| 51 | + body += chunk.content; | |
| 52 | + yield renderChatMessage(chunk); | |
| 53 | + } | |
| 54 | + | |
| 55 | + const url = `${params.repositoryUrl}/issues/new?title=${encodeURIComponent( | |
| 56 | + title, | |
| 57 | + )}&body=${encodeURIComponent(body)}`; | |
| 58 | + yield `\n\n[Link to draft of issue](${url})`; | |
| 59 | + }, | |
| 60 | +}; | |
| 61 | + | |
| 62 | +export default DraftIssueCommand; |
added core/commands/slash/built-in-legacy/http.ts +33 −0
| @@ -0,0 +1,33 @@ | ||
| 1 | +import { streamResponse } from "@continuedev/fetch"; | |
| 2 | +import { SlashCommand } from "../../../index.js"; | |
| 3 | +import { removeQuotesAndEscapes } from "../../../util/index.js"; | |
| 4 | + | |
| 5 | +const HttpSlashCommand: SlashCommand = { | |
| 6 | + name: "http", | |
| 7 | + description: "Call an HTTP endpoint to serve response", | |
| 8 | + run: async function* ({ ide, llm, input, params, fetch }) { | |
| 9 | + const url = params?.url; | |
| 10 | + if (!url) { | |
| 11 | + throw new Error("URL is not defined in params"); | |
| 12 | + } | |
| 13 | + const response = await fetch(url, { | |
| 14 | + method: "POST", | |
| 15 | + headers: { | |
| 16 | + "Content-Type": "application/json", | |
| 17 | + }, | |
| 18 | + body: JSON.stringify({ | |
| 19 | + input: removeQuotesAndEscapes(input), | |
| 20 | + }), | |
| 21 | + }); | |
| 22 | + | |
| 23 | + // Stream the response | |
| 24 | + if (response.body === null) { | |
| 25 | + throw new Error("Response body is null"); | |
| 26 | + } | |
| 27 | + for await (const chunk of streamResponse(response)) { | |
| 28 | + yield chunk; | |
| 29 | + } | |
| 30 | + }, | |
| 31 | +}; | |
| 32 | + | |
| 33 | +export default HttpSlashCommand; |
added core/commands/slash/built-in-legacy/index.ts +37 −0
| @@ -0,0 +1,37 @@ | ||
| 1 | +import { | |
| 2 | + SlashCommand, | |
| 3 | + SlashCommandDescription, | |
| 4 | + SlashCommandWithSource, | |
| 5 | +} from "../../.."; | |
| 6 | +import GenerateTerminalCommand from "./cmd"; | |
| 7 | +import CommitMessageCommand from "./commit"; | |
| 8 | +import DraftIssueCommand from "./draftIssue"; | |
| 9 | +import HttpSlashCommand from "./http"; | |
| 10 | +import OnboardSlashCommand from "./onboard"; | |
| 11 | +import ReviewMessageCommand from "./review"; | |
| 12 | +import ShareSlashCommand from "./share"; | |
| 13 | + | |
| 14 | +const LegacyBuiltInSlashCommands: SlashCommand[] = [ | |
| 15 | + DraftIssueCommand, | |
| 16 | + ShareSlashCommand, | |
| 17 | + GenerateTerminalCommand, | |
| 18 | + HttpSlashCommand, | |
| 19 | + CommitMessageCommand, | |
| 20 | + ReviewMessageCommand, | |
| 21 | + OnboardSlashCommand, | |
| 22 | +]; | |
| 23 | + | |
| 24 | +export function getLegacyBuiltInSlashCommandFromDescription( | |
| 25 | + desc: SlashCommandDescription, | |
| 26 | +): SlashCommandWithSource | undefined { | |
| 27 | + const cmd = LegacyBuiltInSlashCommands.find((cmd) => cmd.name === desc.name); | |
| 28 | + if (!cmd) { | |
| 29 | + return undefined; | |
| 30 | + } | |
| 31 | + return { | |
| 32 | + ...cmd, | |
| 33 | + params: desc.params, | |
| 34 | + description: desc.description ?? cmd.description, | |
| 35 | + source: "built-in-legacy", | |
| 36 | + }; | |
| 37 | +} |
added core/commands/slash/built-in-legacy/onboard.ts +169 −0
| @@ -0,0 +1,169 @@ | ||
| 1 | +import ignore from "ignore"; | |
| 2 | + | |
| 3 | +import type { FileType, IDE, SlashCommand } from "../../.."; | |
| 4 | +import { | |
| 5 | + DEFAULT_IGNORE, | |
| 6 | + getGlobalContinueIgArray, | |
| 7 | + gitIgArrayFromFile, | |
| 8 | +} from "../../../indexing/ignore"; | |
| 9 | +import { renderChatMessage } from "../../../util/messageContent"; | |
| 10 | +import { | |
| 11 | + findUriInDirs, | |
| 12 | + getUriPathBasename, | |
| 13 | + joinPathsToUri, | |
| 14 | +} from "../../../util/uri"; | |
| 15 | + | |
| 16 | +const LANGUAGE_DEP_MGMT_FILENAMES = [ | |
| 17 | + "package.json", // JavaScript (Node.js) | |
| 18 | + "requirements.txt", // Python | |
| 19 | + "Gemfile", // Ruby | |
| 20 | + "pom.xml", // Java (Maven) | |
| 21 | + "build.gradle", // Java (Gradle) | |
| 22 | + "composer.json", // PHP | |
| 23 | + "Cargo.toml", // Rust | |
| 24 | + "go.mod", // Go | |
| 25 | + "packages.config", // C# (.NET) | |
| 26 | + "*.csproj", // C# (.NET Core) | |
| 27 | + "pubspec.yaml", // Dart | |
| 28 | + "Project.toml", // Julia | |
| 29 | + "mix.exs", // Elixir | |
| 30 | + "rebar.config", // Erlang | |
| 31 | + "shard.yml", // Crystal | |
| 32 | + "Package.swift", // Swift | |
| 33 | + "dependencies.gradle", // Kotlin (when using Gradle) | |
| 34 | + "Podfile", // Objective-C/Swift (CocoaPods) | |
| 35 | + "*.cabal", // Haskell | |
| 36 | + "dub.json", // D | |
| 37 | +]; | |
| 38 | + | |
| 39 | +const MAX_EXPLORE_DEPTH = 2; | |
| 40 | + | |
| 41 | +const OnboardSlashCommand: SlashCommand = { | |
| 42 | + name: "onboard", | |
| 43 | + description: "Familiarize yourself with the codebase", | |
| 44 | + run: async function* ({ llm, ide, abortController }) { | |
| 45 | + const [workspaceDir] = await ide.getWorkspaceDirs(); | |
| 46 | + | |
| 47 | + const context = await gatherProjectContext(workspaceDir, ide); | |
| 48 | + const prompt = createOnboardingPrompt(context); | |
| 49 | + | |
| 50 | + for await (const chunk of llm.streamChat( | |
| 51 | + [{ role: "user", content: prompt }], | |
| 52 | + abortController.signal, | |
| 53 | + )) { | |
| 54 | + yield renderChatMessage(chunk); | |
| 55 | + } | |
| 56 | + }, | |
| 57 | +}; | |
| 58 | + | |
| 59 | +async function getEntriesFilteredByIgnore(dir: string, ide: IDE) { | |
| 60 | + const ig = ignore().add(DEFAULT_IGNORE).add(getGlobalContinueIgArray()); | |
| 61 | + const entries = await ide.listDir(dir); | |
| 62 | + | |
| 63 | + const ignoreUri = joinPathsToUri(dir, ".gitignore"); | |
| 64 | + const fileExists = await ide.fileExists(ignoreUri); | |
| 65 | + | |
| 66 | + if (fileExists) { | |
| 67 | + const gitIgnore = await ide.readFile(ignoreUri); | |
| 68 | + const igPatterns = gitIgArrayFromFile(gitIgnore); | |
| 69 | + | |
| 70 | + ig.add(igPatterns); | |
| 71 | + } | |
| 72 | + | |
| 73 | + const workspaceDirs = await ide.getWorkspaceDirs(); | |
| 74 | + | |
| 75 | + const withRelativePaths = entries | |
| 76 | + .filter( | |
| 77 | + (entry) => | |
| 78 | + entry[1] === (1 as FileType.File) || | |
| 79 | + entry[1] === (2 as FileType.Directory), | |
| 80 | + ) | |
| 81 | + .map((entry) => { | |
| 82 | + const { relativePathOrBasename } = findUriInDirs(entry[0], workspaceDirs); | |
| 83 | + return { | |
| 84 | + uri: entry[0], | |
| 85 | + type: entry[1], | |
| 86 | + basename: getUriPathBasename(entry[0]), | |
| 87 | + relativePath: | |
| 88 | + relativePathOrBasename + | |
| 89 | + (entry[1] === (2 as FileType.Directory) ? "/" : ""), | |
| 90 | + }; | |
| 91 | + }); | |
| 92 | + | |
| 93 | + return withRelativePaths.filter((entry) => !ig.ignores(entry.relativePath)); | |
| 94 | +} | |
| 95 | + | |
| 96 | +async function gatherProjectContext( | |
| 97 | + workspaceDir: string, | |
| 98 | + ide: IDE, | |
| 99 | +): Promise<string> { | |
| 100 | + let context = ""; | |
| 101 | + async function exploreDirectory(dir: string, currentDepth: number = 0) { | |
| 102 | + if (currentDepth > MAX_EXPLORE_DEPTH) { | |
| 103 | + return; | |
| 104 | + } | |
| 105 | + | |
| 106 | + const entries = await getEntriesFilteredByIgnore(dir, ide); | |
| 107 | + | |
| 108 | + for (const entry of entries) { | |
| 109 | + if (entry.type === (2 as FileType.Directory)) { | |
| 110 | + context += `\nFolder: ${entry.relativePath}\n`; | |
| 111 | + await exploreDirectory(entry.uri, currentDepth + 1); | |
| 112 | + } else { | |
| 113 | + if (entry.basename.toLowerCase() === "readme.md") { | |
| 114 | + const content = await ide.readFile(entry.uri); | |
| 115 | + context += `README for ${entry.relativePath}:\n${content}\n\n`; | |
| 116 | + } else if (LANGUAGE_DEP_MGMT_FILENAMES.includes(entry.basename)) { | |
| 117 | + const content = await ide.readFile(entry.uri); | |
| 118 | + context += `${entry.basename} for ${entry.relativePath}:\n${content}\n\n`; | |
| 119 | + } | |
| 120 | + } | |
| 121 | + } | |
| 122 | + } | |
| 123 | + | |
| 124 | + await exploreDirectory(workspaceDir); | |
| 125 | + | |
| 126 | + return context; | |
| 127 | +} | |
| 128 | + | |
| 129 | +function createOnboardingPrompt(context: string): string { | |
| 130 | + return ` | |
| 131 | + As a helpful AI assistant, your task is to onboard a new developer to this project. | |
| 132 | + Use the following context about the project structure, READMEs, and dependency files to create a comprehensive overview: | |
| 133 | + | |
| 134 | + ${context} | |
| 135 | + | |
| 136 | + Please provide an overview of the project with the following guidelines: | |
| 137 | + - Determine the most important folders in the project, at most 10 | |
| 138 | + - Go through each important folder step-by-step: | |
| 139 | + - Explain what each folder does in isolation by summarzing the README or package.json file, if available | |
| 140 | + - Mention the most popular or common packages used in that folder and their roles. | |
| 141 | + - After covering individual folders, zoom out to explain at most 5 high-level insights about the project's architecture: | |
| 142 | + - How different parts of the codebase fit together. | |
| 143 | + - The overall project architecture or design patterns evident from the folder structure and dependencies. | |
| 144 | + - Provide at most 5 additional insights on the project's architecture that weren't covered in the folder-by-folder breakdown. | |
| 145 | + | |
| 146 | + Your response should be structured, clear, and focused on giving the new developer both a detailed understanding of individual components and a high-level overview of the project as a whole. | |
| 147 | + | |
| 148 | + Here is an example of a valid response: | |
| 149 | + | |
| 150 | + ## Important folders | |
| 151 | + | |
| 152 | + ### /folder1 | |
| 153 | + - Description: Contains the main application logic. | |
| 154 | + - Key packages: Express.js for routing, Mongoose for database operations. | |
| 155 | + | |
| 156 | + #### /folder1/folder2 | |
| 157 | + | |
| 158 | + ## Project Architecture | |
| 159 | + - The frontend is built using React and Redux for state management. | |
| 160 | + - The backend is a Node.js application using Express.js for routing and Mongoose for database operations. | |
| 161 | + - The application follows a Model-View-Controller (MVC) architecture. | |
| 162 | + | |
| 163 | + ## Additional Insights | |
| 164 | + - The project is using a monorepo structure. | |
| 165 | + - The project uses TypeScript for type checking. | |
| 166 | + `; | |
| 167 | +} | |
| 168 | + | |
| 169 | +export default OnboardSlashCommand; |
added core/commands/slash/built-in-legacy/review.ts +55 −0
| @@ -0,0 +1,55 @@ | ||
| 1 | +import { ChatMessage, SlashCommand } from "../../../index.js"; | |
| 2 | +import { renderChatMessage } from "../../../util/messageContent.js"; | |
| 3 | + | |
| 4 | +const prompt = ` | |
| 5 | + Review the following code, focusing on Readability, Maintainability, Code Smells, Speed, and Memory Performance. Provide feedback with these guidelines: | |
| 6 | + | |
| 7 | + Tone: Friendly casual tone of a fellow engineer, ensure the feedback is clear and focused on practical improvements. | |
| 8 | + Orderly Analysis: Address the code sequentially, from top to bottom, to ensure a thorough review without skipping any parts. | |
| 9 | + Descriptive Feedback: Avoid referencing line numbers directly, as they may vary. Instead, describe the code sections or specific constructs that need attention, explaining the reasons clearly. | |
| 10 | + Provide Examples: For each issue identified, offer an example of how the code could be improved or rewritten for better clarity, performance, or maintainability. | |
| 11 | + Your response should be structured to first identify the issue, then explain why it’s a problem, and finally, offer a solution with example code.`; | |
| 12 | + | |
| 13 | +function getLastUserHistory(history: ChatMessage[]): string { | |
| 14 | + const lastUserHistory = history | |
| 15 | + .reverse() | |
| 16 | + .find((message) => message.role === "user"); | |
| 17 | + | |
| 18 | + if (!lastUserHistory) { | |
| 19 | + return ""; | |
| 20 | + } | |
| 21 | + | |
| 22 | + if (Array.isArray(lastUserHistory.content)) { | |
| 23 | + return lastUserHistory.content.reduce( | |
| 24 | + (acc: string, current: { type: string; text?: string }) => { | |
| 25 | + return current.type === "text" && current.text | |
| 26 | + ? acc + current.text | |
| 27 | + : acc; | |
| 28 | + }, | |
| 29 | + "", | |
| 30 | + ); | |
| 31 | + } | |
| 32 | + | |
| 33 | + return typeof lastUserHistory.content === "string" | |
| 34 | + ? lastUserHistory.content | |
| 35 | + : ""; | |
| 36 | +} | |
| 37 | + | |
| 38 | +const ReviewMessageCommand: SlashCommand = { | |
| 39 | + name: "review", | |
| 40 | + description: "Review code and give feedback", | |
| 41 | + run: async function* ({ llm, history, abortController }) { | |
| 42 | + const reviewText = getLastUserHistory(history).replace("\\review", ""); | |
| 43 | + | |
| 44 | + const content = `${prompt} \r\n ${reviewText}`; | |
| 45 | + | |
| 46 | + for await (const chunk of llm.streamChat( | |
| 47 | + [{ role: "user", content: content }], | |
| 48 | + abortController.signal, | |
| 49 | + )) { | |
| 50 | + yield renderChatMessage(chunk); | |
| 51 | + } | |
| 52 | + }, | |
| 53 | +}; | |
| 54 | + | |
| 55 | +export default ReviewMessageCommand; |
added core/commands/slash/built-in-legacy/share.ts +101 −0
| @@ -0,0 +1,101 @@ | ||
| 1 | +import fs from "fs"; | |
| 2 | +import { homedir } from "node:os"; | |
| 3 | +import { fileURLToPath, pathToFileURL } from "node:url"; | |
| 4 | +import path from "path"; | |
| 5 | + | |
| 6 | +import { languageForFilepath } from "../../../autocomplete/constants/AutocompleteLanguageInfo.js"; | |
| 7 | +import { SlashCommand } from "../../../index.js"; | |
| 8 | +import { renderChatMessage } from "../../../util/messageContent.js"; | |
| 9 | +import { getContinueGlobalPath } from "../../../util/paths.js"; | |
| 10 | + | |
| 11 | +// If useful elsewhere, helper funcs should move to core/util/index.ts or similar | |
| 12 | +function getOffsetDatetime(date: Date): Date { | |
| 13 | + const offset = date.getTimezoneOffset(); | |
| 14 | + const offsetHours = Math.floor(offset / 60); | |
| 15 | + const offsetMinutes = offset % 60; | |
| 16 | + date.setHours(date.getHours() - offsetHours); | |
| 17 | + date.setMinutes(date.getMinutes() - offsetMinutes); | |
| 18 | + | |
| 19 | + return date; | |
| 20 | +} | |
| 21 | + | |
| 22 | +function asBasicISOString(date: Date): string { | |
| 23 | + const isoString = date.toISOString(); | |
| 24 | + | |
| 25 | + return isoString.replace(/[-:]|(\.\d+Z)/g, ""); | |
| 26 | +} | |
| 27 | + | |
| 28 | +function reformatCodeBlocks(msgText: string): string { | |
| 29 | + const codeBlockFenceRegex = /```((.*?\.(\w+))\s*.*)\n/g; | |
| 30 | + msgText = msgText.replace( | |
| 31 | + codeBlockFenceRegex, | |
| 32 | + (match, metadata, filename, extension) => { | |
| 33 | + const lang = languageForFilepath(filename); | |
| 34 | + return `\`\`\`${extension}\n${lang.singleLineComment} ${metadata}\n`; | |
| 35 | + }, | |
| 36 | + ); | |
| 37 | + // Appease the markdown linter | |
| 38 | + return msgText.replace(/```\n```/g, "```\n\n```"); | |
| 39 | +} | |
| 40 | + | |
| 41 | +const ShareSlashCommand: SlashCommand = { | |
| 42 | + name: "share", | |
| 43 | + description: "Export the current chat session to markdown", | |
| 44 | + run: async function* ({ ide, history, params }) { | |
| 45 | + const now = new Date(); | |
| 46 | + | |
| 47 | + let content = `### [Continue](https://continue.dev) session transcript\n Exported: ${now.toLocaleString()}`; | |
| 48 | + | |
| 49 | + // As currently implemented, the /share command is by definition the last | |
| 50 | + // message in the chat history, this will omit it | |
| 51 | + for (const msg of history.slice(0, history.length - 1)) { | |
| 52 | + let msgText = msg.content; | |
| 53 | + msgText = renderChatMessage(msg); | |
| 54 | + | |
| 55 | + if (msg.role === "user" && msgText.search("```") > -1) { | |
| 56 | + msgText = reformatCodeBlocks(msgText); | |
| 57 | + } | |
| 58 | + | |
| 59 | + // format messages as blockquotes | |
| 60 | + msgText = msgText.replace(/^/gm, "> "); | |
| 61 | + | |
| 62 | + content += `\n\n#### ${ | |
| 63 | + msg.role === "user" ? "_User_" : "_Assistant_" | |
| 64 | + }\n\n${msgText}`; | |
| 65 | + } | |
| 66 | + | |
| 67 | + let outputDir: string = params?.outputDir ?? getContinueGlobalPath(); | |
| 68 | + | |
| 69 | + if (outputDir.startsWith("~")) { | |
| 70 | + outputDir = outputDir.replace(/^~/, homedir); | |
| 71 | + } else if ( | |
| 72 | + outputDir.startsWith("./") || | |
| 73 | + outputDir.startsWith(".\\") || | |
| 74 | + outputDir === "." | |
| 75 | + ) { | |
| 76 | + const workspaceDirs = await ide.getWorkspaceDirs(); | |
| 77 | + // Although the most common situation is to have one directory open in a | |
| 78 | + // workspace it's also possible to have just a file open without an | |
| 79 | + // associated directory or to use multi-root workspaces in which multiple | |
| 80 | + // folders are included. We default to using the first item in the list, if | |
| 81 | + // it exists. | |
| 82 | + const workspaceDirectory = workspaceDirs?.[0] || ""; | |
| 83 | + outputDir = outputDir.replace(/^./, fileURLToPath(workspaceDirectory)); | |
| 84 | + } | |
| 85 | + | |
| 86 | + if (!fs.existsSync(outputDir)) { | |
| 87 | + fs.mkdirSync(outputDir, { recursive: true }); | |
| 88 | + } | |
| 89 | + | |
| 90 | + const dtString = asBasicISOString(getOffsetDatetime(now)); | |
| 91 | + const outPath = path.join(outputDir, `${dtString}_session.md`); //TODO: more flexible naming? | |
| 92 | + | |
| 93 | + const fileUrl = pathToFileURL(outPath).toString(); // TODO switch from path to URI above ^ | |
| 94 | + await ide.writeFile(fileUrl, content); | |
| 95 | + await ide.openFile(fileUrl); | |
| 96 | + | |
| 97 | + yield `The session transcript has been saved to a markdown file at \`${outPath}\`.`; | |
| 98 | + }, | |
| 99 | +}; | |
| 100 | + | |
| 101 | +export default ShareSlashCommand; |
deleted core/commands/slash/cmd.ts +0 −62
| @@ -1,62 +0,0 @@ | ||
| 1 | -import { streamLines } from "../../diff/util.js"; | |
| 2 | -import { SlashCommand } from "../../index.js"; | |
| 3 | -import { removeQuotesAndEscapes } from "../../util/index.js"; | |
| 4 | - | |
| 5 | -function commandIsPotentiallyDangerous(command: string) { | |
| 6 | - return ( | |
| 7 | - command.includes("rm -rf") || | |
| 8 | - command.includes("sudo") || | |
| 9 | - command.includes("cd / ") | |
| 10 | - ); | |
| 11 | -} | |
| 12 | - | |
| 13 | -const GenerateTerminalCommand: SlashCommand = { | |
| 14 | - name: "cmd", | |
| 15 | - description: "Generate a shell command", | |
| 16 | - run: async function* ({ ide, llm, input }) { | |
| 17 | - if (input.trim() === "") { | |
| 18 | - yield "Please provide a description of the shell command you want to generate. For example, '/cmd List all files in the current directory'."; | |
| 19 | - return; | |
| 20 | - } | |
| 21 | - | |
| 22 | - const gen = llm.streamComplete( | |
| 23 | - `The user has made a request to run a shell command. Their description of what it should do is: | |
| 24 | - | |
| 25 | -"${input}" | |
| 26 | - | |
| 27 | -Please write a shell command that will do what the user requested. Your output should consist of only the command itself, without any explanation or example output. Do not use any newlines. Only output the command that when inserted into the terminal will do precisely what was requested. Here is the command:`, | |
| 28 | - new AbortController().signal, | |
| 29 | - ); | |
| 30 | - | |
| 31 | - const lines = streamLines(gen); | |
| 32 | - let cmd = ""; | |
| 33 | - for await (const line of lines) { | |
| 34 | - console.log(line); | |
| 35 | - if (line.startsWith("```") && line.endsWith("```")) { | |
| 36 | - cmd = line.split(" ").slice(1).join(" ").slice(0, -3); | |
| 37 | - break; | |
| 38 | - } | |
| 39 | - | |
| 40 | - if ( | |
| 41 | - line.startsWith(">") || | |
| 42 | - line.startsWith("``") || | |
| 43 | - line.startsWith("\\begin{") || | |
| 44 | - line.trim() === "" | |
| 45 | - ) { | |
| 46 | - continue; | |
| 47 | - } | |
| 48 | - | |
| 49 | - cmd = removeQuotesAndEscapes(line.trim()); | |
| 50 | - break; | |
| 51 | - } | |
| 52 | - | |
| 53 | - yield `Generated shell command: ${cmd}`; | |
| 54 | - if (commandIsPotentiallyDangerous(cmd)) { | |
| 55 | - yield "\n\nWarning: This command may be potentially dangerous. Please double-check before pasting it in your terminal."; | |
| 56 | - } else { | |
| 57 | - await ide.runCommand(cmd); | |
| 58 | - } | |
| 59 | - }, | |
| 60 | -}; | |
| 61 | - | |
| 62 | -export default GenerateTerminalCommand; |
deleted core/commands/slash/commit.ts +0 −26
| @@ -1,26 +0,0 @@ | ||
| 1 | -import { SlashCommand } from "../../index.js"; | |
| 2 | -import { renderChatMessage } from "../../util/messageContent.js"; | |
| 3 | - | |
| 4 | -const CommitMessageCommand: SlashCommand = { | |
| 5 | - name: "commit", | |
| 6 | - description: "Generate a commit message for current changes", | |
| 7 | - run: async function* ({ ide, llm, params, abortController }) { | |
| 8 | - const includeUnstaged = params?.includeUnstaged ?? false; | |
| 9 | - const diff = await ide.getDiff(includeUnstaged); | |
| 10 | - | |
| 11 | - if (diff.length === 0) { | |
| 12 | - yield "No changes detected. Make sure you are in a git repository with current changes."; | |
| 13 | - return; | |
| 14 | - } | |
| 15 | - | |
| 16 | - const prompt = `${diff.join("\n")}\n\nGenerate a commit message for the above set of changes. First, give a single sentence, no more than 80 characters. Then, after 2 line breaks, give a list of no more than 5 short bullet points, each no more than 40 characters. Output nothing except for the commit message, and don't surround it in quotes.`; | |
| 17 | - for await (const chunk of llm.streamChat( | |
| 18 | - [{ role: "user", content: prompt }], | |
| 19 | - abortController.signal, | |
| 20 | - )) { | |
| 21 | - yield renderChatMessage(chunk); | |
| 22 | - } | |
| 23 | - }, | |
| 24 | -}; | |
| 25 | - | |
| 26 | -export default CommitMessageCommand; |
added core/commands/slash/customSlashCommand.ts +15 −0
| @@ -0,0 +1,15 @@ | ||
| 1 | +import { CustomCommand, SlashCommandWithSource } from "../.."; | |
| 2 | + | |
| 3 | +export function convertCustomCommandToSlashCommand( | |
| 4 | + customCommand: CustomCommand, | |
| 5 | +): SlashCommandWithSource { | |
| 6 | + const commandName = customCommand.name.startsWith("/") | |
| 7 | + ? customCommand.name.substring(1) | |
| 8 | + : customCommand.name; | |
| 9 | + return { | |
| 10 | + name: commandName, | |
| 11 | + description: customCommand.description ?? "", | |
| 12 | + prompt: customCommand.prompt, | |
| 13 | + source: "json-custom-command", | |
| 14 | + }; | |
| 15 | +} |
deleted core/commands/slash/draftIssue.ts +0 −62
| @@ -1,62 +0,0 @@ | ||
| 1 | -import { ChatMessage, SlashCommand } from "../../index.js"; | |
| 2 | -import { removeQuotesAndEscapes } from "../../util/index.js"; | |
| 3 | -import { renderChatMessage } from "../../util/messageContent.js"; | |
| 4 | - | |
| 5 | -const PROMPT = ( | |
| 6 | - input: string, | |
| 7 | - title: string, | |
| 8 | -) => `You will be asked to generate the body of a GitHub issue given a user request. You should follow these rules: | |
| 9 | -- Be descriptive but do not make up details | |
| 10 | -- If the the user request includes any code snippets that are relevant, reference them in code blocks | |
| 11 | -- Describe step by step how to reproduce the problem | |
| 12 | -- Describe the ideal solution to the problem | |
| 13 | -- Describe the expected behavior after the issue has been resolved | |
| 14 | -- This issue will be read by a team member | |
| 15 | -- Use markdown formatting, but you do not need to surround the entire body with triple backticks | |
| 16 | -{additional_instructions} | |
| 17 | - | |
| 18 | -Here is the user request: '${input}' | |
| 19 | - | |
| 20 | -Title: ${title} | |
| 21 | - | |
| 22 | -Body:\n\n`; | |
| 23 | - | |
| 24 | -const DraftIssueCommand: SlashCommand = { | |
| 25 | - name: "issue", | |
| 26 | - description: "Draft a GitHub issue", | |
| 27 | - run: async function* ({ input, llm, history, params, abortController }) { | |
| 28 | - if (params?.repositoryUrl === undefined) { | |
| 29 | - yield "This command requires a repository URL to be set in the config file."; | |
| 30 | - return; | |
| 31 | - } | |
| 32 | - let title = await llm.complete( | |
| 33 | - `Generate a title for the GitHub issue requested in this user input: '${input}'. Use no more than 20 words and output nothing other than the title. Do not surround it with quotes. The title is: `, | |
| 34 | - new AbortController().signal, | |
| 35 | - { maxTokens: 30 }, | |
| 36 | - ); | |
| 37 | - | |
| 38 | - title = `${removeQuotesAndEscapes(title.trim())}\n\n`; | |
| 39 | - yield title; | |
| 40 | - | |
| 41 | - let body = ""; | |
| 42 | - const messages: ChatMessage[] = [ | |
| 43 | - ...history.filter((msg) => msg.role !== "system"), | |
| 44 | - { role: "user", content: PROMPT(input, title) }, | |
| 45 | - ]; | |
| 46 | - | |
| 47 | - for await (const chunk of llm.streamChat( | |
| 48 | - messages, | |
| 49 | - abortController.signal, | |
| 50 | - )) { | |
| 51 | - body += chunk.content; | |
| 52 | - yield renderChatMessage(chunk); | |
| 53 | - } | |
| 54 | - | |
| 55 | - const url = `${params.repositoryUrl}/issues/new?title=${encodeURIComponent( | |
| 56 | - title, | |
| 57 | - )}&body=${encodeURIComponent(body)}`; | |
| 58 | - yield `\n\n[Link to draft of issue](${url})`; | |
| 59 | - }, | |
| 60 | -}; | |
| 61 | - | |
| 62 | -export default DraftIssueCommand; |
deleted core/commands/slash/http.ts +0 −33
| @@ -1,33 +0,0 @@ | ||
| 1 | -import { streamResponse } from "@continuedev/fetch"; | |
| 2 | -import { SlashCommand } from "../../index.js"; | |
| 3 | -import { removeQuotesAndEscapes } from "../../util/index.js"; | |
| 4 | - | |
| 5 | -const HttpSlashCommand: SlashCommand = { | |
| 6 | - name: "http", | |
| 7 | - description: "Call an HTTP endpoint to serve response", | |
| 8 | - run: async function* ({ ide, llm, input, params, fetch }) { | |
| 9 | - const url = params?.url; | |
| 10 | - if (!url) { | |
| 11 | - throw new Error("URL is not defined in params"); | |
| 12 | - } | |
| 13 | - const response = await fetch(url, { | |
| 14 | - method: "POST", | |
| 15 | - headers: { | |
| 16 | - "Content-Type": "application/json", | |
| 17 | - }, | |
| 18 | - body: JSON.stringify({ | |
| 19 | - input: removeQuotesAndEscapes(input), | |
| 20 | - }), | |
| 21 | - }); | |
| 22 | - | |
| 23 | - // Stream the response | |
| 24 | - if (response.body === null) { | |
| 25 | - throw new Error("Response body is null"); | |
| 26 | - } | |
| 27 | - for await (const chunk of streamResponse(response)) { | |
| 28 | - yield chunk; | |
| 29 | - } | |
| 30 | - }, | |
| 31 | -}; | |
| 32 | - | |
| 33 | -export default HttpSlashCommand; |
deleted core/commands/slash/index.ts +0 −17
| @@ -1,17 +0,0 @@ | ||
| 1 | -import GenerateTerminalCommand from "./cmd"; | |
| 2 | -import CommitMessageCommand from "./commit"; | |
| 3 | -import DraftIssueCommand from "./draftIssue"; | |
| 4 | -import HttpSlashCommand from "./http"; | |
| 5 | -import OnboardSlashCommand from "./onboard"; | |
| 6 | -import ReviewMessageCommand from "./review"; | |
| 7 | -import ShareSlashCommand from "./share"; | |
| 8 | - | |
| 9 | -export default [ | |
| 10 | - DraftIssueCommand, | |
| 11 | - ShareSlashCommand, | |
| 12 | - GenerateTerminalCommand, | |
| 13 | - HttpSlashCommand, | |
| 14 | - CommitMessageCommand, | |
| 15 | - ReviewMessageCommand, | |
| 16 | - OnboardSlashCommand, | |
| 17 | -]; |
deleted core/commands/slash/mcp.ts +0 −70
| @@ -1,70 +0,0 @@ | ||
| 1 | -import { Client } from "@modelcontextprotocol/sdk/client/index.js"; | |
| 2 | - | |
| 3 | -import { PromptMessage } from "@modelcontextprotocol/sdk/types.js"; | |
| 4 | -import { ChatMessage, SlashCommand } from "../../index.js"; | |
| 5 | -import { renderChatMessage } from "../../util/messageContent.js"; | |
| 6 | -export function constructMcpSlashCommand( | |
| 7 | - client: Client, | |
| 8 | - name: string, | |
| 9 | - description?: string, | |
| 10 | - args?: string[], | |
| 11 | -): SlashCommand { | |
| 12 | - return { | |
| 13 | - name, | |
| 14 | - description: description ?? "MCP Prompt", | |
| 15 | - params: {}, | |
| 16 | - run: async function* (context) { | |
| 17 | - const argsObject: { [key: string]: string } = {}; | |
| 18 | - const userInput = context.input.split(" ").slice(1).join(" "); | |
| 19 | - if (args) { | |
| 20 | - args.forEach((arg, i) => { | |
| 21 | - argsObject[arg] = ""; // userInput | |
| 22 | - }); | |
| 23 | - } | |
| 24 | - | |
| 25 | - const result = await client.getPrompt({ name, arguments: argsObject }); | |
| 26 | - const mcpMessages: PromptMessage[] = result.messages; | |
| 27 | - const messages: ChatMessage[] = mcpMessages.map((msg) => { | |
| 28 | - if (msg.content.type !== "text") { | |
| 29 | - throw new Error( | |
| 30 | - "Continue currently only supports text prompts through MCP", | |
| 31 | - ); | |
| 32 | - } | |
| 33 | - return { | |
| 34 | - content: msg.content.text, | |
| 35 | - role: msg.role, | |
| 36 | - }; | |
| 37 | - }); | |
| 38 | - | |
| 39 | - if (messages.length === 0) { | |
| 40 | - yield "The MCP prompt returned no messages"; | |
| 41 | - return; | |
| 42 | - } | |
| 43 | - | |
| 44 | - if (userInput) { | |
| 45 | - const lastMessage = messages.at(-1); | |
| 46 | - if (!lastMessage || lastMessage.role !== "user") { | |
| 47 | - messages.push({ | |
| 48 | - role: "user", | |
| 49 | - content: userInput, | |
| 50 | - }); | |
| 51 | - } else { | |
| 52 | - let newContent = renderChatMessage(lastMessage); | |
| 53 | - if (newContent) { | |
| 54 | - newContent += "\n\n"; | |
| 55 | - } | |
| 56 | - newContent += userInput; | |
| 57 | - lastMessage.content = newContent; | |
| 58 | - } | |
| 59 | - } | |
| 60 | - | |
| 61 | - for await (const chunk of context.llm.streamChat( | |
| 62 | - messages, | |
| 63 | - context.abortController.signal, | |
| 64 | - context.completionOptions, | |
| 65 | - )) { | |
| 66 | - yield renderChatMessage(chunk); | |
| 67 | - } | |
| 68 | - }, | |
| 69 | - }; | |
| 70 | -} |
added core/commands/slash/mcpSlashCommand.ts +34 −0
| @@ -0,0 +1,34 @@ | ||
| 1 | +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; | |
| 2 | + | |
| 3 | +import { SlashCommandWithSource } from "../../index.js"; | |
| 4 | + | |
| 5 | +export function constructMcpSlashCommand( | |
| 6 | + client: Client, | |
| 7 | + name: string, | |
| 8 | + description?: string, | |
| 9 | + args?: string[], | |
| 10 | +): SlashCommandWithSource { | |
| 11 | + return { | |
| 12 | + name, | |
| 13 | + description: description ?? "MCP Prompt", | |
| 14 | + source: "mcp-prompt", | |
| 15 | + params: {}, | |
| 16 | + }; | |
| 17 | +} | |
| 18 | + | |
| 19 | +export function stringifyMcpPrompt( | |
| 20 | + prompt: Awaited<ReturnType<typeof Client.prototype.getPrompt>>, | |
| 21 | +): string { | |
| 22 | + const { messages } = prompt; | |
| 23 | + let stringified = ""; | |
| 24 | + for (const message of messages) { | |
| 25 | + if (message.content.type === "text") { | |
| 26 | + stringified += `<${message.content.role}/>\n${message.content.text}\n<${message.content.role}/>`; | |
| 27 | + } else { | |
| 28 | + console.warn( | |
| 29 | + `MCP Prompt conversion warning: ${message.content.type} content is not yet supported, message skipped`, | |
| 30 | + ); | |
| 31 | + } | |
| 32 | + } | |
| 33 | + return stringified; | |
| 34 | +} |
deleted core/commands/slash/onboard.ts +0 −169
| @@ -1,169 +0,0 @@ | ||
| 1 | -import ignore from "ignore"; | |
| 2 | - | |
| 3 | -import type { FileType, IDE, SlashCommand } from "../.."; | |
| 4 | -import { | |
| 5 | - DEFAULT_IGNORE, | |
| 6 | - getGlobalContinueIgArray, | |
| 7 | - gitIgArrayFromFile, | |
| 8 | -} from "../../indexing/ignore"; | |
| 9 | -import { renderChatMessage } from "../../util/messageContent"; | |
| 10 | -import { | |
| 11 | - findUriInDirs, | |
| 12 | - getUriPathBasename, | |
| 13 | - joinPathsToUri, | |
| 14 | -} from "../../util/uri"; | |
| 15 | - | |
| 16 | -const LANGUAGE_DEP_MGMT_FILENAMES = [ | |
| 17 | - "package.json", // JavaScript (Node.js) | |
| 18 | - "requirements.txt", // Python | |
| 19 | - "Gemfile", // Ruby | |
| 20 | - "pom.xml", // Java (Maven) | |
| 21 | - "build.gradle", // Java (Gradle) | |
| 22 | - "composer.json", // PHP | |
| 23 | - "Cargo.toml", // Rust | |
| 24 | - "go.mod", // Go | |
| 25 | - "packages.config", // C# (.NET) | |
| 26 | - "*.csproj", // C# (.NET Core) | |
| 27 | - "pubspec.yaml", // Dart | |
| 28 | - "Project.toml", // Julia | |
| 29 | - "mix.exs", // Elixir | |
| 30 | - "rebar.config", // Erlang | |
| 31 | - "shard.yml", // Crystal | |
| 32 | - "Package.swift", // Swift | |
| 33 | - "dependencies.gradle", // Kotlin (when using Gradle) | |
| 34 | - "Podfile", // Objective-C/Swift (CocoaPods) | |
| 35 | - "*.cabal", // Haskell | |
| 36 | - "dub.json", // D | |
| 37 | -]; | |
| 38 | - | |
| 39 | -const MAX_EXPLORE_DEPTH = 2; | |
| 40 | - | |
| 41 | -const OnboardSlashCommand: SlashCommand = { | |
| 42 | - name: "onboard", | |
| 43 | - description: "Familiarize yourself with the codebase", | |
| 44 | - run: async function* ({ llm, ide, abortController }) { | |
| 45 | - const [workspaceDir] = await ide.getWorkspaceDirs(); | |
| 46 | - | |
| 47 | - const context = await gatherProjectContext(workspaceDir, ide); | |
| 48 | - const prompt = createOnboardingPrompt(context); | |
| 49 | - | |
| 50 | - for await (const chunk of llm.streamChat( | |
| 51 | - [{ role: "user", content: prompt }], | |
| 52 | - abortController.signal, | |
| 53 | - )) { | |
| 54 | - yield renderChatMessage(chunk); | |
| 55 | - } | |
| 56 | - }, | |
| 57 | -}; | |
| 58 | - | |
| 59 | -async function getEntriesFilteredByIgnore(dir: string, ide: IDE) { | |
| 60 | - const ig = ignore().add(DEFAULT_IGNORE).add(getGlobalContinueIgArray()); | |
| 61 | - const entries = await ide.listDir(dir); | |
| 62 | - | |
| 63 | - const ignoreUri = joinPathsToUri(dir, ".gitignore"); | |
| 64 | - const fileExists = await ide.fileExists(ignoreUri); | |
| 65 | - | |
| 66 | - if (fileExists) { | |
| 67 | - const gitIgnore = await ide.readFile(ignoreUri); | |
| 68 | - const igPatterns = gitIgArrayFromFile(gitIgnore); | |
| 69 | - | |
| 70 | - ig.add(igPatterns); | |
| 71 | - } | |
| 72 | - | |
| 73 | - const workspaceDirs = await ide.getWorkspaceDirs(); | |
| 74 | - | |
| 75 | - const withRelativePaths = entries | |
| 76 | - .filter( | |
| 77 | - (entry) => | |
| 78 | - entry[1] === (1 as FileType.File) || | |
| 79 | - entry[1] === (2 as FileType.Directory), | |
| 80 | - ) | |
| 81 | - .map((entry) => { | |
| 82 | - const { relativePathOrBasename } = findUriInDirs(entry[0], workspaceDirs); | |
| 83 | - return { | |
| 84 | - uri: entry[0], | |
| 85 | - type: entry[1], | |
| 86 | - basename: getUriPathBasename(entry[0]), | |
| 87 | - relativePath: | |
| 88 | - relativePathOrBasename + | |
| 89 | - (entry[1] === (2 as FileType.Directory) ? "/" : ""), | |
| 90 | - }; | |
| 91 | - }); | |
| 92 | - | |
| 93 | - return withRelativePaths.filter((entry) => !ig.ignores(entry.relativePath)); | |
| 94 | -} | |
| 95 | - | |
| 96 | -async function gatherProjectContext( | |
| 97 | - workspaceDir: string, | |
| 98 | - ide: IDE, | |
| 99 | -): Promise<string> { | |
| 100 | - let context = ""; | |
| 101 | - async function exploreDirectory(dir: string, currentDepth: number = 0) { | |
| 102 | - if (currentDepth > MAX_EXPLORE_DEPTH) { | |
| 103 | - return; | |
| 104 | - } | |
| 105 | - | |
| 106 | - const entries = await getEntriesFilteredByIgnore(dir, ide); | |
| 107 | - | |
| 108 | - for (const entry of entries) { | |
| 109 | - if (entry.type === (2 as FileType.Directory)) { | |
| 110 | - context += `\nFolder: ${entry.relativePath}\n`; | |
| 111 | - await exploreDirectory(entry.uri, currentDepth + 1); | |
| 112 | - } else { | |
| 113 | - if (entry.basename.toLowerCase() === "readme.md") { | |
| 114 | - const content = await ide.readFile(entry.uri); | |
| 115 | - context += `README for ${entry.relativePath}:\n${content}\n\n`; | |
| 116 | - } else if (LANGUAGE_DEP_MGMT_FILENAMES.includes(entry.basename)) { | |
| 117 | - const content = await ide.readFile(entry.uri); | |
| 118 | - context += `${entry.basename} for ${entry.relativePath}:\n${content}\n\n`; | |
| 119 | - } | |
| 120 | - } | |
| 121 | - } | |
| 122 | - } | |
| 123 | - | |
| 124 | - await exploreDirectory(workspaceDir); | |
| 125 | - | |
| 126 | - return context; | |
| 127 | -} | |
| 128 | - | |
| 129 | -function createOnboardingPrompt(context: string): string { | |
| 130 | - return ` | |
| 131 | - As a helpful AI assistant, your task is to onboard a new developer to this project. | |
| 132 | - Use the following context about the project structure, READMEs, and dependency files to create a comprehensive overview: | |
| 133 | - | |
| 134 | - ${context} | |
| 135 | - | |
| 136 | - Please provide an overview of the project with the following guidelines: | |
| 137 | - - Determine the most important folders in the project, at most 10 | |
| 138 | - - Go through each important folder step-by-step: | |
| 139 | - - Explain what each folder does in isolation by summarzing the README or package.json file, if available | |
| 140 | - - Mention the most popular or common packages used in that folder and their roles. | |
| 141 | - - After covering individual folders, zoom out to explain at most 5 high-level insights about the project's architecture: | |
| 142 | - - How different parts of the codebase fit together. | |
| 143 | - - The overall project architecture or design patterns evident from the folder structure and dependencies. | |
| 144 | - - Provide at most 5 additional insights on the project's architecture that weren't covered in the folder-by-folder breakdown. | |
| 145 | - | |
| 146 | - Your response should be structured, clear, and focused on giving the new developer both a detailed understanding of individual components and a high-level overview of the project as a whole. | |
| 147 | - | |
| 148 | - Here is an example of a valid response: | |
| 149 | - | |
| 150 | - ## Important folders | |
| 151 | - | |
| 152 | - ### /folder1 | |
| 153 | - - Description: Contains the main application logic. | |
| 154 | - - Key packages: Express.js for routing, Mongoose for database operations. | |
| 155 | - | |
| 156 | - #### /folder1/folder2 | |
| 157 | - | |
| 158 | - ## Project Architecture | |
| 159 | - - The frontend is built using React and Redux for state management. | |
| 160 | - - The backend is a Node.js application using Express.js for routing and Mongoose for database operations. | |
| 161 | - - The application follows a Model-View-Controller (MVC) architecture. | |
| 162 | - | |
| 163 | - ## Additional Insights | |
| 164 | - - The project is using a monorepo structure. | |
| 165 | - - The project uses TypeScript for type checking. | |
| 166 | - `; | |
| 167 | -} | |
| 168 | - | |
| 169 | -export default OnboardSlashCommand; |
added core/commands/slash/promptBlockSlashCommand.ts +13 −0
| @@ -0,0 +1,13 @@ | ||
| 1 | +import { Prompt } from "@continuedev/config-yaml"; | |
| 2 | +import { SlashCommandWithSource } from "../.."; | |
| 3 | + | |
| 4 | +export function convertPromptBlockToSlashCommand( | |
| 5 | + prompt: Prompt, | |
| 6 | +): SlashCommandWithSource { | |
| 7 | + return { | |
| 8 | + name: prompt.name, | |
| 9 | + description: prompt.description ?? "", | |
| 10 | + prompt: prompt.prompt, | |
| 11 | + source: "yaml-prompt-block", | |
| 12 | + }; | |
| 13 | +} |
added core/commands/slash/promptFileSlashCommand.ts +21 −0
| @@ -0,0 +1,21 @@ | ||
| 1 | +import { SlashCommandWithSource } from "../.."; | |
| 2 | +import { parsePromptFile } from "../../promptFiles/parsePromptFile"; | |
| 3 | + | |
| 4 | +export function slashCommandFromPromptFile( | |
| 5 | + path: string, | |
| 6 | + content: string, | |
| 7 | +): SlashCommandWithSource | null { | |
| 8 | + const { name, description, systemMessage, prompt, version } = parsePromptFile( | |
| 9 | + path, | |
| 10 | + content, | |
| 11 | + ); | |
| 12 | + | |
| 13 | + return { | |
| 14 | + name, | |
| 15 | + description, | |
| 16 | + prompt, | |
| 17 | + source: version === 1 ? "prompt-file-v1" : "prompt-file-v2", | |
| 18 | + promptFile: path, | |
| 19 | + overrideSystemMessage: systemMessage, | |
| 20 | + }; | |
| 21 | +} |
deleted core/commands/slash/review.ts +0 −55
| @@ -1,55 +0,0 @@ | ||
| 1 | -import { ChatMessage, SlashCommand } from "../../index.js"; | |
| 2 | -import { renderChatMessage } from "../../util/messageContent.js"; | |
| 3 | - | |
| 4 | -const prompt = ` | |
| 5 | - Review the following code, focusing on Readability, Maintainability, Code Smells, Speed, and Memory Performance. Provide feedback with these guidelines: | |
| 6 | - | |
| 7 | - Tone: Friendly casual tone of a fellow engineer, ensure the feedback is clear and focused on practical improvements. | |
| 8 | - Orderly Analysis: Address the code sequentially, from top to bottom, to ensure a thorough review without skipping any parts. | |
| 9 | - Descriptive Feedback: Avoid referencing line numbers directly, as they may vary. Instead, describe the code sections or specific constructs that need attention, explaining the reasons clearly. | |
| 10 | - Provide Examples: For each issue identified, offer an example of how the code could be improved or rewritten for better clarity, performance, or maintainability. | |
| 11 | - Your response should be structured to first identify the issue, then explain why it’s a problem, and finally, offer a solution with example code.`; | |
| 12 | - | |
| 13 | -function getLastUserHistory(history: ChatMessage[]): string { | |
| 14 | - const lastUserHistory = history | |
| 15 | - .reverse() | |
| 16 | - .find((message) => message.role === "user"); | |
| 17 | - | |
| 18 | - if (!lastUserHistory) { | |
| 19 | - return ""; | |
| 20 | - } | |
| 21 | - | |
| 22 | - if (Array.isArray(lastUserHistory.content)) { | |
| 23 | - return lastUserHistory.content.reduce( | |
| 24 | - (acc: string, current: { type: string; text?: string }) => { | |
| 25 | - return current.type === "text" && current.text | |
| 26 | - ? acc + current.text | |
| 27 | - : acc; | |
| 28 | - }, | |
| 29 | - "", | |
| 30 | - ); | |
| 31 | - } | |
| 32 | - | |
| 33 | - return typeof lastUserHistory.content === "string" | |
| 34 | - ? lastUserHistory.content | |
| 35 | - : ""; | |
| 36 | -} | |
| 37 | - | |
| 38 | -const ReviewMessageCommand: SlashCommand = { | |
| 39 | - name: "review", | |
| 40 | - description: "Review code and give feedback", | |
| 41 | - run: async function* ({ llm, history, abortController }) { | |
| 42 | - const reviewText = getLastUserHistory(history).replace("\\review", ""); | |
| 43 | - | |
| 44 | - const content = `${prompt} \r\n ${reviewText}`; | |
| 45 | - | |
| 46 | - for await (const chunk of llm.streamChat( | |
| 47 | - [{ role: "user", content: content }], | |
| 48 | - abortController.signal, | |
| 49 | - )) { | |
| 50 | - yield renderChatMessage(chunk); | |
| 51 | - } | |
| 52 | - }, | |
| 53 | -}; | |
| 54 | - | |
| 55 | -export default ReviewMessageCommand; |
deleted core/commands/slash/share.ts +0 −101
| @@ -1,101 +0,0 @@ | ||
| 1 | -import fs from "fs"; | |
| 2 | -import { homedir } from "node:os"; | |
| 3 | -import { fileURLToPath, pathToFileURL } from "node:url"; | |
| 4 | -import path from "path"; | |
| 5 | - | |
| 6 | -import { languageForFilepath } from "../../autocomplete/constants/AutocompleteLanguageInfo.js"; | |
| 7 | -import { SlashCommand } from "../../index.js"; | |
| 8 | -import { renderChatMessage } from "../../util/messageContent.js"; | |
| 9 | -import { getContinueGlobalPath } from "../../util/paths.js"; | |
| 10 | - | |
| 11 | -// If useful elsewhere, helper funcs should move to core/util/index.ts or similar | |
| 12 | -function getOffsetDatetime(date: Date): Date { | |
| 13 | - const offset = date.getTimezoneOffset(); | |
| 14 | - const offsetHours = Math.floor(offset / 60); | |
| 15 | - const offsetMinutes = offset % 60; | |
| 16 | - date.setHours(date.getHours() - offsetHours); | |
| 17 | - date.setMinutes(date.getMinutes() - offsetMinutes); | |
| 18 | - | |
| 19 | - return date; | |
| 20 | -} | |
| 21 | - | |
| 22 | -function asBasicISOString(date: Date): string { | |
| 23 | - const isoString = date.toISOString(); | |
| 24 | - | |
| 25 | - return isoString.replace(/[-:]|(\.\d+Z)/g, ""); | |
| 26 | -} | |
| 27 | - | |
| 28 | -function reformatCodeBlocks(msgText: string): string { | |
| 29 | - const codeBlockFenceRegex = /```((.*?\.(\w+))\s*.*)\n/g; | |
| 30 | - msgText = msgText.replace( | |
| 31 | - codeBlockFenceRegex, | |
| 32 | - (match, metadata, filename, extension) => { | |
| 33 | - const lang = languageForFilepath(filename); | |
| 34 | - return `\`\`\`${extension}\n${lang.singleLineComment} ${metadata}\n`; | |
| 35 | - }, | |
| 36 | - ); | |
| 37 | - // Appease the markdown linter | |
| 38 | - return msgText.replace(/```\n```/g, "```\n\n```"); | |
| 39 | -} | |
| 40 | - | |
| 41 | -const ShareSlashCommand: SlashCommand = { | |
| 42 | - name: "share", | |
| 43 | - description: "Export the current chat session to markdown", | |
| 44 | - run: async function* ({ ide, history, params }) { | |
| 45 | - const now = new Date(); | |
| 46 | - | |
| 47 | - let content = `### [Continue](https://continue.dev) session transcript\n Exported: ${now.toLocaleString()}`; | |
| 48 | - | |
| 49 | - // As currently implemented, the /share command is by definition the last | |
| 50 | - // message in the chat history, this will omit it | |
| 51 | - for (const msg of history.slice(0, history.length - 1)) { | |
| 52 | - let msgText = msg.content; | |
| 53 | - msgText = renderChatMessage(msg); | |
| 54 | - | |
| 55 | - if (msg.role === "user" && msgText.search("```") > -1) { | |
| 56 | - msgText = reformatCodeBlocks(msgText); | |
| 57 | - } | |
| 58 | - | |
| 59 | - // format messages as blockquotes | |
| 60 | - msgText = msgText.replace(/^/gm, "> "); | |
| 61 | - | |
| 62 | - content += `\n\n#### ${ | |
| 63 | - msg.role === "user" ? "_User_" : "_Assistant_" | |
| 64 | - }\n\n${msgText}`; | |
| 65 | - } | |
| 66 | - | |
| 67 | - let outputDir: string = params?.outputDir ?? getContinueGlobalPath(); | |
| 68 | - | |
| 69 | - if (outputDir.startsWith("~")) { | |
| 70 | - outputDir = outputDir.replace(/^~/, homedir); | |
| 71 | - } else if ( | |
| 72 | - outputDir.startsWith("./") || | |
| 73 | - outputDir.startsWith(".\\") || | |
| 74 | - outputDir === "." | |
| 75 | - ) { | |
| 76 | - const workspaceDirs = await ide.getWorkspaceDirs(); | |
| 77 | - // Although the most common situation is to have one directory open in a | |
| 78 | - // workspace it's also possible to have just a file open without an | |
| 79 | - // associated directory or to use multi-root workspaces in which multiple | |
| 80 | - // folders are included. We default to using the first item in the list, if | |
| 81 | - // it exists. | |
| 82 | - const workspaceDirectory = workspaceDirs?.[0] || ""; | |
| 83 | - outputDir = outputDir.replace(/^./, fileURLToPath(workspaceDirectory)); | |
| 84 | - } | |
| 85 | - | |
| 86 | - if (!fs.existsSync(outputDir)) { | |
| 87 | - fs.mkdirSync(outputDir, { recursive: true }); | |
| 88 | - } | |
| 89 | - | |
| 90 | - const dtString = asBasicISOString(getOffsetDatetime(now)); | |
| 91 | - const outPath = path.join(outputDir, `${dtString}_session.md`); //TODO: more flexible naming? | |
| 92 | - | |
| 93 | - const fileUrl = pathToFileURL(outPath).toString(); // TODO switch from path to URI above ^ | |
| 94 | - await ide.writeFile(fileUrl, content); | |
| 95 | - await ide.openFile(fileUrl); | |
| 96 | - | |
| 97 | - yield `The session transcript has been saved to a markdown file at \`${outPath}\`.`; | |
| 98 | - }, | |
| 99 | -}; | |
| 100 | - | |
| 101 | -export default ShareSlashCommand; |
modified core/commands/util.ts +1 −1
| @@ -16,7 +16,7 @@ | ||
| 16 | 16 | return { |
| 17 | 17 | content: rif.contents, |
| 18 | 18 | name: `${basename} ${rangeStr}`, |
| 19 | - description: `${relativePathOrBasename} ${rangeStr}`, // This is passed to the LLM - do not pass full URI | |
| 19 | + description: `${relativePathOrBasename} ${rangeStr}`, | |
| 20 | 20 | id: { |
| 21 | 21 | providerTitle: "code", |
| 22 | 22 | itemId: uuidv4(), |
modified core/config/load.ts +33 −17
| @@ -30,12 +30,11 @@ | ||
| 30 | 30 | ModelDescription, |
| 31 | 31 | RerankerDescription, |
| 32 | 32 | SerializedContinueConfig, |
| 33 | - SlashCommand, | |
| 33 | + SlashCommandWithSource, | |
| 34 | 34 | } from ".."; |
| 35 | -import { | |
| 36 | - slashCommandFromDescription, | |
| 37 | - slashFromCustomCommand, | |
| 38 | -} from "../commands/index"; | |
| 35 | +import { getLegacyBuiltInSlashCommandFromDescription } from "../commands/slash/built-in-legacy"; | |
| 36 | +import { convertCustomCommandToSlashCommand } from "../commands/slash/customSlashCommand"; | |
| 37 | +import { slashCommandFromPromptFile } from "../commands/slash/promptFileSlashCommand"; | |
| 39 | 38 | import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton"; |
| 40 | 39 | import CodebaseContextProvider from "../context/providers/CodebaseContextProvider"; |
| 41 | 40 | import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider"; |
| @@ -48,8 +47,7 @@ | ||
| 48 | 47 | import CustomLLMClass from "../llm/llms/CustomLLM"; |
| 49 | 48 | import { LLMReranker } from "../llm/llms/llm"; |
| 50 | 49 | import TransformersJsEmbeddingsProvider from "../llm/llms/TransformersJsEmbeddingsProvider"; |
| 51 | -import { slashCommandFromPromptFileV1 } from "../promptFiles/v1/slashCommandFromPromptFile"; | |
| 52 | -import { getAllPromptFiles } from "../promptFiles/v2/getPromptFiles"; | |
| 50 | +import { getAllPromptFiles } from "../promptFiles/getPromptFiles"; | |
| 53 | 51 | import { copyOf } from "../util"; |
| 54 | 52 | import { GlobalContext } from "../util/GlobalContext"; |
| 55 | 53 | import mergeJson from "../util/merge"; |
| @@ -66,6 +64,7 @@ | ||
| 66 | 64 | import { localPathToUri } from "../util/pathToUri"; |
| 67 | 65 | |
| 68 | 66 | import { baseToolDefinitions } from "../tools"; |
| 67 | +import { resolveRelativePathInDir } from "../util/ideUtils"; | |
| 69 | 68 | import { modifyAnyConfigWithSharedConfig } from "./sharedConfig"; |
| 70 | 69 | import { |
| 71 | 70 | getModelByRole, |
| @@ -174,15 +173,15 @@ | ||
| 174 | 173 | ide: IDE, |
| 175 | 174 | ): Promise<Config> { |
| 176 | 175 | // DEPRECATED - load custom slash commands |
| 177 | - const slashCommands: SlashCommand[] = []; | |
| 176 | + const slashCommands: SlashCommandWithSource[] = []; | |
| 178 | 177 | for (const command of initial.slashCommands || []) { |
| 179 | - const newCommand = slashCommandFromDescription(command); | |
| 178 | + const newCommand = getLegacyBuiltInSlashCommandFromDescription(command); | |
| 180 | 179 | if (newCommand) { |
| 181 | 180 | slashCommands.push(newCommand); |
| 182 | 181 | } |
| 183 | 182 | } |
| 184 | 183 | for (const command of initial.customCommands || []) { |
| 185 | - slashCommands.push(slashFromCustomCommand(command)); | |
| 184 | + slashCommands.push(convertCustomCommandToSlashCommand(command)); | |
| 186 | 185 | } |
| 187 | 186 | |
| 188 | 187 | // DEPRECATED - load slash commands from v1 prompt files |
| @@ -194,7 +193,7 @@ | ||
| 194 | 193 | ); |
| 195 | 194 | |
| 196 | 195 | for (const file of promptFiles) { |
| 197 | - const slashCommand = slashCommandFromPromptFileV1(file.path, file.content); | |
| 196 | + const slashCommand = slashCommandFromPromptFile(file.path, file.content); | |
| 198 | 197 | if (slashCommand) { |
| 199 | 198 | slashCommands.push(slashCommand); |
| 200 | 199 | } |
| @@ -254,7 +253,10 @@ | ||
| 254 | 253 | loadPromptFiles?: boolean; |
| 255 | 254 | }): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> { |
| 256 | 255 | const errors: ConfigValidationError[] = []; |
| 257 | - | |
| 256 | + const workspaceDirs = await ide.getWorkspaceDirs(); | |
| 257 | + const getUriFromPath = (path: string) => { | |
| 258 | + return resolveRelativePathInDir(path, ide, workspaceDirs); | |
| 259 | + }; | |
| 258 | 260 | // Auto-detect models |
| 259 | 261 | let models: BaseLLM[] = []; |
| 260 | 262 | await Promise.all( |
| @@ -263,6 +265,7 @@ | ||
| 263 | 265 | const llm = await llmFromDescription( |
| 264 | 266 | desc, |
| 265 | 267 | ide.readFile.bind(ide), |
| 268 | + getUriFromPath, | |
| 266 | 269 | uniqueId, |
| 267 | 270 | ideSettings, |
| 268 | 271 | llmLogger, |
| @@ -284,6 +287,7 @@ | ||
| 284 | 287 | title: modelName, |
| 285 | 288 | }, |
| 286 | 289 | ide.readFile.bind(ide), |
| 290 | + getUriFromPath, | |
| 287 | 291 | uniqueId, |
| 288 | 292 | ideSettings, |
| 289 | 293 | llmLogger, |
| @@ -360,6 +364,7 @@ | ||
| 360 | 364 | const llm = await llmFromDescription( |
| 361 | 365 | desc, |
| 362 | 366 | ide.readFile.bind(ide), |
| 367 | + getUriFromPath, | |
| 363 | 368 | uniqueId, |
| 364 | 369 | ideSettings, |
| 365 | 370 | llmLogger, |
| @@ -529,7 +534,7 @@ | ||
| 529 | 534 | contextProviders, |
| 530 | 535 | tools: [...baseToolDefinitions], |
| 531 | 536 | mcpServerStatuses: [], |
| 532 | - slashCommands: config.slashCommands ?? [], | |
| 537 | + slashCommands: [], | |
| 533 | 538 | modelsByRole: { |
| 534 | 539 | chat: models, |
| 535 | 540 | edit: models, |
| @@ -551,6 +556,17 @@ | ||
| 551 | 556 | rules: [], |
| 552 | 557 | }; |
| 553 | 558 | |
| 559 | + for (const cmd of config.slashCommands ?? []) { | |
| 560 | + if ("source" in cmd) { | |
| 561 | + continueConfig.slashCommands.push(cmd); | |
| 562 | + } else { | |
| 563 | + continueConfig.slashCommands.push({ | |
| 564 | + ...cmd, | |
| 565 | + source: "config-ts-slash-command", | |
| 566 | + }); | |
| 567 | + } | |
| 568 | + } | |
| 569 | + | |
| 554 | 570 | if (config.systemMessage) { |
| 555 | 571 | continueConfig.rules.unshift({ |
| 556 | 572 | rule: config.systemMessage, |
| @@ -651,9 +667,10 @@ | ||
| 651 | 667 | return { |
| 652 | 668 | allowAnonymousTelemetry: final.allowAnonymousTelemetry, |
| 653 | 669 | completionOptions: final.completionOptions, |
| 654 | - slashCommands: final.slashCommands?.map( | |
| 655 | - ({ run, ...slashCommandDescription }) => slashCommandDescription, | |
| 656 | - ), | |
| 670 | + slashCommands: final.slashCommands?.map(({ run, ...rest }) => ({ | |
| 671 | + ...rest, | |
| 672 | + isLegacy: !!run, | |
| 673 | + })), | |
| 657 | 674 | contextProviders: final.contextProviders?.map((c) => c.description), |
| 658 | 675 | disableIndexing: final.disableIndexing, |
| 659 | 676 | disableSessionTitles: final.disableSessionTitles, |
| @@ -975,7 +992,6 @@ | ||
| 975 | 992 | |
| 976 | 993 | export { |
| 977 | 994 | finalToBrowserConfig, |
| 978 | - intermediateToFinalConfig, | |
| 979 | 995 | loadContinueConfigFromJson, |
| 980 | 996 | type BrowserSerializedContinueConfig, |
| 981 | 997 | }; |
modified core/config/profile/doLoadConfig.ts +10 −9
| @@ -16,9 +16,9 @@ | ||
| 16 | 16 | ILLMLogger, |
| 17 | 17 | RuleWithSource, |
| 18 | 18 | SerializedContinueConfig, |
| 19 | + SlashCommandDescWithSource, | |
| 19 | 20 | Tool, |
| 20 | 21 | } from "../../"; |
| 21 | -import { constructMcpSlashCommand } from "../../commands/slash/mcp"; | |
| 22 | 22 | import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton"; |
| 23 | 23 | import MCPContextProvider from "../../context/providers/MCPContextProvider"; |
| 24 | 24 | import RulesContextProvider from "../../context/providers/RulesContextProvider"; |
| @@ -190,14 +190,15 @@ | ||
| 190 | 190 | })); |
| 191 | 191 | newConfig.tools.push(...serverTools); |
| 192 | 192 | |
| 193 | - const serverSlashCommands = server.prompts.map((prompt) => | |
| 194 | - constructMcpSlashCommand( | |
| 195 | - server.client, | |
| 196 | - prompt.name, | |
| 197 | - prompt.description, | |
| 198 | - prompt.arguments?.map((a: any) => a.name), | |
| 199 | - ), | |
| 200 | - ); | |
| 193 | + const serverSlashCommands: SlashCommandDescWithSource[] = | |
| 194 | + server.prompts.map((prompt) => ({ | |
| 195 | + name: prompt.name, | |
| 196 | + description: prompt.description ?? "MCP Prompt", | |
| 197 | + source: "mcp-prompt", | |
| 198 | + isLegacy: false, | |
| 199 | + mcpServerName: server.name, // Used in client to retrieve prompt | |
| 200 | + mcpArgs: prompt.arguments, | |
| 201 | + })); | |
| 201 | 202 | newConfig.slashCommands.push(...serverSlashCommands); |
| 202 | 203 | |
| 203 | 204 | const submenuItems = server.resources |
modified core/config/yaml/loadYaml.ts +7 −7
| @@ -25,7 +25,6 @@ | ||
| 25 | 25 | ILLMLogger, |
| 26 | 26 | RuleWithSource, |
| 27 | 27 | } from "../.."; |
| 28 | -import { slashFromCustomCommand } from "../../commands"; | |
| 29 | 28 | import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton"; |
| 30 | 29 | import CodebaseContextProvider from "../../context/providers/CodebaseContextProvider"; |
| 31 | 30 | import DocsContextProvider from "../../context/providers/DocsContextProvider"; |
| @@ -33,13 +32,14 @@ | ||
| 33 | 32 | import { contextProviderClassFromName } from "../../context/providers/index"; |
| 34 | 33 | import { ControlPlaneClient } from "../../control-plane/client"; |
| 35 | 34 | import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider"; |
| 36 | -import { slashCommandFromPromptFileV1 } from "../../promptFiles/v1/slashCommandFromPromptFile"; | |
| 37 | -import { getAllPromptFiles } from "../../promptFiles/v2/getPromptFiles"; | |
| 35 | +import { getAllPromptFiles } from "../../promptFiles/getPromptFiles"; | |
| 38 | 36 | import { GlobalContext } from "../../util/GlobalContext"; |
| 39 | 37 | import { modifyAnyConfigWithSharedConfig } from "../sharedConfig"; |
| 40 | 38 | |
| 39 | +import { convertPromptBlockToSlashCommand } from "../../commands/slash/promptBlockSlashCommand"; | |
| 40 | +import { slashCommandFromPromptFile } from "../../commands/slash/promptFileSlashCommand"; | |
| 41 | 41 | import { getControlPlaneEnvSync } from "../../control-plane/env"; |
| 42 | -import { baseToolDefinitions } from "../../tools"; | |
| 42 | +import { getToolsForIde } from "../../tools"; | |
| 43 | 43 | import { getCleanUriPath } from "../../util/uri"; |
| 44 | 44 | import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants"; |
| 45 | 45 | import { LocalPlatformClient } from "./LocalPlatformClient"; |
| @@ -187,7 +187,7 @@ | ||
| 187 | 187 | |
| 188 | 188 | const continueConfig: ContinueConfig = { |
| 189 | 189 | slashCommands: [], |
| 190 | - tools: [...baseToolDefinitions], | |
| 190 | + tools: await getToolsForIde(ide), | |
| 191 | 191 | mcpServerStatuses: [], |
| 192 | 192 | contextProviders: [], |
| 193 | 193 | modelsByRole: { |
| @@ -263,7 +263,7 @@ | ||
| 263 | 263 | |
| 264 | 264 | promptFiles.forEach((file) => { |
| 265 | 265 | try { |
| 266 | - const slashCommand = slashCommandFromPromptFileV1( | |
| 266 | + const slashCommand = slashCommandFromPromptFile( | |
| 267 | 267 | file.path, |
| 268 | 268 | file.content, |
| 269 | 269 | ); |
| @@ -286,7 +286,7 @@ | ||
| 286 | 286 | |
| 287 | 287 | config.prompts?.forEach((prompt) => { |
| 288 | 288 | try { |
| 289 | - const slashCommand = slashFromCustomCommand(prompt); | |
| 289 | + const slashCommand = convertPromptBlockToSlashCommand(prompt); | |
| 290 | 290 | continueConfig.slashCommands?.push(slashCommand); |
| 291 | 291 | } catch (e) { |
| 292 | 292 | localErrors.push({ |
modified core/context/mcp/MCPManagerSingleton.ts +17 −0
| @@ -161,4 +161,21 @@ | ||
| 161 | 161 | client: connection.client, |
| 162 | 162 | })); |
| 163 | 163 | } |
| 164 | + | |
| 165 | + async getPrompt( | |
| 166 | + serverName: string, | |
| 167 | + promptName: string, | |
| 168 | + args: Record<string, string> = {}, | |
| 169 | + ) { | |
| 170 | + const connection = this.connections.get(serverName); | |
| 171 | + if (!connection) { | |
| 172 | + throw new Error( | |
| 173 | + `Error getting prompt: MCP Connection ${serverName} not found`, | |
| 174 | + ); | |
| 175 | + } | |
| 176 | + return await connection.client.getPrompt({ | |
| 177 | + name: promptName, | |
| 178 | + arguments: args, | |
| 179 | + }); | |
| 180 | + } | |
| 164 | 181 | } |
modified core/context/providers/TerminalContextProvider.ts +3 −1
| @@ -21,7 +21,9 @@ | ||
| 21 | 21 | return [ |
| 22 | 22 | { |
| 23 | 23 | description: "The contents of the terminal", |
| 24 | - content: `Current terminal contents:\n\n${content}`, | |
| 24 | + content: `Current terminal contents:\n\n${ | |
| 25 | + content || "The terminal is empty." | |
| 26 | + }`, | |
| 25 | 27 | name: "Terminal", |
| 26 | 28 | }, |
| 27 | 29 | ]; |
modified core/core.ts +15 −1
| @@ -21,7 +21,7 @@ | ||
| 21 | 21 | import DocsService from "./indexing/docs/DocsService"; |
| 22 | 22 | import { countTokens } from "./llm/countTokens"; |
| 23 | 23 | import Ollama from "./llm/llms/Ollama"; |
| 24 | -import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile"; | |
| 24 | +import { createNewPromptFileV2 } from "./promptFiles/createNewPromptFile"; | |
| 25 | 25 | import { callTool } from "./tools/callTool"; |
| 26 | 26 | import { ChatDescriber } from "./util/chatDescriber"; |
| 27 | 27 | import { clipboardCache } from "./util/clipboardCache"; |
| @@ -50,6 +50,7 @@ | ||
| 50 | 50 | |
| 51 | 51 | import { BLOCK_TYPES, ConfigYaml } from "@continuedev/config-yaml"; |
| 52 | 52 | import { getDiffFn, GitDiffCache } from "./autocomplete/snippets/gitDiffCache"; |
| 53 | +import { stringifyMcpPrompt } from "./commands/slash/mcpSlashCommand"; | |
| 53 | 54 | import { isLocalDefinitionFile } from "./config/loadLocalAssistants"; |
| 54 | 55 | import { |
| 55 | 56 | setupLocalConfig, |
| @@ -381,6 +382,19 @@ | ||
| 381 | 382 | on("mcp/reloadServer", async (msg) => { |
| 382 | 383 | await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id); |
| 383 | 384 | }); |
| 385 | + on("mcp/getPrompt", async (msg) => { | |
| 386 | + const { serverName, promptName, args } = msg.data; | |
| 387 | + const prompt = await MCPManagerSingleton.getInstance().getPrompt( | |
| 388 | + serverName, | |
| 389 | + promptName, | |
| 390 | + args, | |
| 391 | + ); | |
| 392 | + const stringifiedPrompt = stringifyMcpPrompt(prompt); | |
| 393 | + return { | |
| 394 | + prompt: stringifiedPrompt, | |
| 395 | + description: prompt.description, | |
| 396 | + }; | |
| 397 | + }); | |
| 384 | 398 | // Context providers |
| 385 | 399 | on("context/addDocs", async (msg) => { |
| 386 | 400 | void this.docsService.indexAndAdd(msg.data); |
modified core/index.d.ts +43 −12
| @@ -731,6 +731,8 @@ | ||
| 731 | 731 | |
| 732 | 732 | isTelemetryEnabled(): Promise<boolean>; |
| 733 | 733 | |
| 734 | + isWorkspaceRemote(): Promise<boolean>; | |
| 735 | + | |
| 734 | 736 | getUniqueId(): Promise<string>; |
| 735 | 737 | |
| 736 | 738 | getTerminalContents(): Promise<string>; |
| @@ -836,15 +838,44 @@ | ||
| 836 | 838 | abortController: AbortController; |
| 837 | 839 | } |
| 838 | 840 | |
| 839 | -export interface SlashCommand { | |
| 841 | +/* Be careful changing SlashCommand or SlashCommandDescription, config.ts can break */ | |
| 842 | +export interface SlashCommandDescription { | |
| 840 | 843 | name: string; |
| 841 | 844 | description: string; |
| 842 | 845 | prompt?: string; |
| 843 | 846 | params?: { [key: string]: any }; |
| 844 | - promptFile?: string; | |
| 847 | +} | |
| 848 | + | |
| 849 | +export interface SlashCommand extends SlashCommandDescription { | |
| 845 | 850 | run: (sdk: ContinueSDK) => AsyncGenerator<string | undefined>; |
| 846 | 851 | } |
| 847 | 852 | |
| 853 | +export interface SlashCommandWithSource extends SlashCommandDescription { | |
| 854 | + run?: (sdk: ContinueSDK) => AsyncGenerator<string | undefined>; // Optional - only needed for legacy | |
| 855 | + source: SlashCommandSource; | |
| 856 | + promptFile?: string; | |
| 857 | + overrideSystemMessage?: string; | |
| 858 | +} | |
| 859 | + | |
| 860 | +export type SlashCommandSource = | |
| 861 | + | "built-in-legacy" | |
| 862 | + | "built-in" | |
| 863 | + | "json-custom-command" | |
| 864 | + | "config-ts-slash-command" | |
| 865 | + | "yaml-prompt-block" | |
| 866 | + | "mcp-prompt" | |
| 867 | + | "prompt-file-v1" | |
| 868 | + | "prompt-file-v2" | |
| 869 | + | "invokable-rule"; | |
| 870 | + | |
| 871 | +export interface SlashCommandDescWithSource extends SlashCommandDescription { | |
| 872 | + isLegacy: boolean; // Maps to if slashcommand.run exists | |
| 873 | + source: SlashCommandSource; | |
| 874 | + promptFile?: string; | |
| 875 | + mcpServerName?: string; | |
| 876 | + mcpArgs?: MCPPromptArgs; | |
| 877 | +} | |
| 878 | + | |
| 848 | 879 | // Config |
| 849 | 880 | |
| 850 | 881 | export type StepName = |
| @@ -945,8 +976,6 @@ | ||
| 945 | 976 | params: { [key: string]: any }; |
| 946 | 977 | } |
| 947 | 978 | |
| 948 | -export type SlashCommandDescription = Omit<SlashCommand, "run">; | |
| 949 | - | |
| 950 | 979 | export interface CustomCommand { |
| 951 | 980 | name: string; |
| 952 | 981 | prompt: string; |
| @@ -1170,14 +1199,16 @@ | ||
| 1170 | 1199 | | "error" |
| 1171 | 1200 | | "not-connected"; |
| 1172 | 1201 | |
| 1202 | +export type MCPPromptArgs = { | |
| 1203 | + name: string; | |
| 1204 | + description?: string; | |
| 1205 | + required?: boolean; | |
| 1206 | +}[]; | |
| 1207 | + | |
| 1173 | 1208 | export interface MCPPrompt { |
| 1174 | 1209 | name: string; |
| 1175 | 1210 | description?: string; |
| 1176 | - arguments?: { | |
| 1177 | - name: string; | |
| 1178 | - description?: string; | |
| 1179 | - required?: boolean; | |
| 1180 | - }[]; | |
| 1211 | + arguments?: MCPPromptArgs; | |
| 1181 | 1212 | } |
| 1182 | 1213 | |
| 1183 | 1214 | // Leaving here to ideate on |
| @@ -1442,7 +1473,7 @@ | ||
| 1442 | 1473 | /** Request options that will be applied to all models and context providers */ |
| 1443 | 1474 | requestOptions?: RequestOptions; |
| 1444 | 1475 | /** The list of slash commands that will be available in the sidebar */ |
| 1445 | - slashCommands?: SlashCommand[]; | |
| 1476 | + slashCommands?: (SlashCommand | SlashCommandWithSource)[]; | |
| 1446 | 1477 | /** Each entry in this array will originally be a ContextProviderWithParams, the same object from your config.json, but you may add CustomContextProviders. |
| 1447 | 1478 | * A CustomContextProvider requires you only to define a title and getContextItems function. When you type '@title <query>', Continue will call `getContextItems(query)`. |
| 1448 | 1479 | */ |
| @@ -1479,7 +1510,7 @@ | ||
| 1479 | 1510 | // systemMessage?: string; |
| 1480 | 1511 | completionOptions?: BaseCompletionOptions; |
| 1481 | 1512 | requestOptions?: RequestOptions; |
| 1482 | - slashCommands: SlashCommand[]; | |
| 1513 | + slashCommands: SlashCommandWithSource[]; | |
| 1483 | 1514 | contextProviders: IContextProvider[]; |
| 1484 | 1515 | disableSessionTitles?: boolean; |
| 1485 | 1516 | disableIndexing?: boolean; |
| @@ -1502,7 +1533,7 @@ | ||
| 1502 | 1533 | // systemMessage?: string; |
| 1503 | 1534 | completionOptions?: BaseCompletionOptions; |
| 1504 | 1535 | requestOptions?: RequestOptions; |
| 1505 | - slashCommands: SlashCommandDescription[]; | |
| 1536 | + slashCommands: SlashCommandDescWithSource[]; | |
| 1506 | 1537 | contextProviders: ContextProviderDescription[]; |
| 1507 | 1538 | disableIndexing?: boolean; |
| 1508 | 1539 | disableSessionTitles?: boolean; |
modified core/llm/llms/index.ts +7 −3
| @@ -1,3 +1,4 @@ | ||
| 1 | +import Handlebars from "handlebars"; | |
| 1 | 2 | import { |
| 2 | 3 | BaseCompletionOptions, |
| 3 | 4 | IdeSettings, |
| @@ -6,10 +7,9 @@ | ||
| 6 | 7 | JSONModelDescription, |
| 7 | 8 | LLMOptions, |
| 8 | 9 | } from "../.."; |
| 9 | -import { renderTemplatedString } from "../../promptFiles/v1/renderTemplatedString"; | |
| 10 | +import { renderTemplatedString } from "../../util/handlebars/renderTemplatedString"; | |
| 10 | 11 | import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../constructMessages"; |
| 11 | 12 | import { BaseLLM } from "../index"; |
| 12 | - | |
| 13 | 13 | import Anthropic from "./Anthropic"; |
| 14 | 14 | import Asksage from "./Asksage"; |
| 15 | 15 | import Azure from "./Azure"; |
| @@ -121,6 +121,7 @@ | ||
| 121 | 121 | export async function llmFromDescription( |
| 122 | 122 | desc: JSONModelDescription, |
| 123 | 123 | readFile: (filepath: string) => Promise<string>, |
| 124 | + getUriFromPath: (path: string) => Promise<string | undefined>, | |
| 124 | 125 | uniqueId: string, |
| 125 | 126 | ideSettings: IdeSettings, |
| 126 | 127 | llmLogger: ILLMLogger, |
| @@ -142,9 +143,12 @@ | ||
| 142 | 143 | baseChatSystemMessage = DEFAULT_CHAT_SYSTEM_MESSAGE; |
| 143 | 144 | baseChatSystemMessage += "\n\n"; |
| 144 | 145 | baseChatSystemMessage += await renderTemplatedString( |
| 146 | + Handlebars, | |
| 145 | 147 | desc.systemMessage, |
| 146 | - readFile, | |
| 147 | 148 | {}, |
| 149 | + [], | |
| 150 | + readFile, | |
| 151 | + getUriFromPath, | |
| 148 | 152 | ); |
| 149 | 153 | } |
| 150 | 154 |
modified core/llm/streamChat.ts +6 −0
| @@ -59,6 +59,12 @@ | ||
| 59 | 59 | }, |
| 60 | 60 | true, |
| 61 | 61 | ); |
| 62 | + if (!slashCommand.run) { | |
| 63 | + console.error( | |
| 64 | + `Slash command ${command.name} (${command.source}) has no run function`, | |
| 65 | + ); | |
| 66 | + throw new Error(`Slash command not found`); | |
| 67 | + } | |
| 62 | 68 | |
| 63 | 69 | const gen = slashCommand.run({ |
| 64 | 70 | input, |
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.
added core/promptFiles/createNewPromptFile.ts +76 −0
| @@ -0,0 +1,76 @@ | ||
| 1 | +import { IDE } from ".."; | |
| 2 | +import { GlobalContext } from "../util/GlobalContext"; | |
| 3 | +import { joinPathsToUri } from "../util/uri"; | |
| 4 | + | |
| 5 | +const FIRST_TIME_DEFAULT_PROMPT_FILE = `# This is an example ".prompt" file | |
| 6 | +# It is used to define and reuse prompts within Continue | |
| 7 | +# Each .prompt file can be accessed by typing "@prompts" in the Chat input | |
| 8 | + | |
| 9 | +# A prompt file consists of two parts: | |
| 10 | +# 1. Everything above the "---" is YAML. Here you can set "temperature", "description", and other options | |
| 11 | +# 2. Everything below the "---" is the prompt body | |
| 12 | + | |
| 13 | +# If you do not want to set any options, you do not need to include the "---" | |
| 14 | + | |
| 15 | +# In the body, you can reference: | |
| 16 | +# 1. Files, using either absolute or relative paths (based on the workspace root) | |
| 17 | + # @README.md | |
| 18 | + # @src/test/test.py | |
| 19 | + # @/Users/me/Desktop/my-project/src/test/test.py | |
| 20 | +# 2. URLs, for example | |
| 21 | + # @https://example.com | |
| 22 | +# 3. Context providers, for example | |
| 23 | + # @currentFile | |
| 24 | + # @os | |
| 25 | + # @repo-map | |
| 26 | + | |
| 27 | +# To learn more, see the full .prompt file reference: https://docs.continue.dev/features/prompt-files | |
| 28 | +name: Example | |
| 29 | +description: Example prompt file | |
| 30 | +--- | |
| 31 | + | |
| 32 | +Here is information about the current repo: | |
| 33 | + | |
| 34 | +@README.md`; | |
| 35 | + | |
| 36 | +const DEFAULT_PROMPT_FILE = ""; | |
| 37 | + | |
| 38 | +export async function createNewPromptFileV2( | |
| 39 | + ide: IDE, | |
| 40 | + promptPath: string | undefined, | |
| 41 | +): Promise<void> { | |
| 42 | + const workspaceDirs = await ide.getWorkspaceDirs(); | |
| 43 | + if (workspaceDirs.length === 0) { | |
| 44 | + throw new Error( | |
| 45 | + "No workspace directories found. Make sure you've opened a folder in your IDE.", | |
| 46 | + ); | |
| 47 | + } | |
| 48 | + | |
| 49 | + const baseDirUri = joinPathsToUri( | |
| 50 | + workspaceDirs[0], | |
| 51 | + promptPath ?? ".continue/prompts", | |
| 52 | + ); | |
| 53 | + | |
| 54 | + // Find the first available filename | |
| 55 | + let counter = 0; | |
| 56 | + let promptFileUri: string; | |
| 57 | + do { | |
| 58 | + const suffix = counter === 0 ? "" : `-${counter}`; | |
| 59 | + promptFileUri = joinPathsToUri( | |
| 60 | + baseDirUri, | |
| 61 | + `new-prompt-file${suffix}.prompt`, | |
| 62 | + ); | |
| 63 | + counter++; | |
| 64 | + } while (await ide.fileExists(promptFileUri)); | |
| 65 | + | |
| 66 | + const globalContext = new GlobalContext(); | |
| 67 | + const PROMPT_FILE = | |
| 68 | + globalContext.get("hasAlreadyCreatedAPromptFile") === true | |
| 69 | + ? DEFAULT_PROMPT_FILE | |
| 70 | + : FIRST_TIME_DEFAULT_PROMPT_FILE; | |
| 71 | + | |
| 72 | + globalContext.update("hasAlreadyCreatedAPromptFile", true); | |
| 73 | + | |
| 74 | + await ide.writeFile(promptFileUri, PROMPT_FILE); | |
| 75 | + await ide.openFile(promptFileUri); | |
| 76 | +} |
added core/promptFiles/getPromptFiles.ts +66 −0
| @@ -0,0 +1,66 @@ | ||
| 1 | +import { DEFAULT_PROMPTS_FOLDER_V1, DEFAULT_PROMPTS_FOLDER_V2 } from "."; | |
| 2 | +import { IDE } from ".."; | |
| 3 | +import { walkDir } from "../indexing/walkDir"; | |
| 4 | +import { readAllGlobalPromptFiles } from "../util/paths"; | |
| 5 | +import { joinPathsToUri } from "../util/uri"; | |
| 6 | + | |
| 7 | +export async function getPromptFilesFromDir( | |
| 8 | + ide: IDE, | |
| 9 | + dir: string, | |
| 10 | +): Promise<{ path: string; content: string }[]> { | |
| 11 | + try { | |
| 12 | + const exists = await ide.fileExists(dir); | |
| 13 | + | |
| 14 | + if (!exists) { | |
| 15 | + return []; | |
| 16 | + } | |
| 17 | + | |
| 18 | + const uris = await walkDir(dir, ide, { | |
| 19 | + source: "get dir prompt files", | |
| 20 | + }); | |
| 21 | + const promptFilePaths = uris.filter((p) => p.endsWith(".prompt")); | |
| 22 | + const results = promptFilePaths.map(async (uri) => { | |
| 23 | + const content = await ide.readFile(uri); // make a try catch | |
| 24 | + return { path: uri, content }; | |
| 25 | + }); | |
| 26 | + return Promise.all(results); | |
| 27 | + } catch (e) { | |
| 28 | + console.error(e); | |
| 29 | + return []; | |
| 30 | + } | |
| 31 | +} | |
| 32 | + | |
| 33 | +export async function getAllPromptFiles( | |
| 34 | + ide: IDE, | |
| 35 | + overridePromptFolder?: string, | |
| 36 | + checkV1DefaultFolder: boolean = false, | |
| 37 | +): Promise<{ path: string; content: string }[]> { | |
| 38 | + const workspaceDirs = await ide.getWorkspaceDirs(); | |
| 39 | + let promptFiles: { path: string; content: string }[] = []; | |
| 40 | + | |
| 41 | + let dirsToCheck = [DEFAULT_PROMPTS_FOLDER_V2]; | |
| 42 | + if (checkV1DefaultFolder) { | |
| 43 | + dirsToCheck.push(DEFAULT_PROMPTS_FOLDER_V1); | |
| 44 | + } | |
| 45 | + if (overridePromptFolder) { | |
| 46 | + dirsToCheck = [overridePromptFolder]; | |
| 47 | + } | |
| 48 | + | |
| 49 | + const fullDirs = workspaceDirs | |
| 50 | + .map((dir) => dirsToCheck.map((d) => joinPathsToUri(dir, d))) | |
| 51 | + .flat(); | |
| 52 | + | |
| 53 | + promptFiles = ( | |
| 54 | + await Promise.all(fullDirs.map((dir) => getPromptFilesFromDir(ide, dir))) | |
| 55 | + ).flat(); | |
| 56 | + | |
| 57 | + // Also read from ~/.continue/.prompts | |
| 58 | + promptFiles.push(...readAllGlobalPromptFiles()); | |
| 59 | + | |
| 60 | + return await Promise.all( | |
| 61 | + promptFiles.map(async (file) => { | |
| 62 | + const content = await ide.readFile(file.path); | |
| 63 | + return { path: file.path, content }; | |
| 64 | + }), | |
| 65 | + ); | |
| 66 | +} |
added core/promptFiles/index.ts +19 −0
| @@ -0,0 +1,19 @@ | ||
| 1 | +import { ContextProviderName } from ".."; | |
| 2 | + | |
| 3 | +export const DEFAULT_PROMPTS_FOLDER_V1 = ".prompts"; | |
| 4 | +export const DEFAULT_PROMPTS_FOLDER_V2 = ".continue/prompts"; | |
| 5 | + | |
| 6 | +export const SUPPORTED_PROMPT_CONTEXT_PROVIDERS: ContextProviderName[] = [ | |
| 7 | + "file", | |
| 8 | + "clipboard", | |
| 9 | + "repo-map", | |
| 10 | + "currentFile", | |
| 11 | + "os", | |
| 12 | + "problems", | |
| 13 | + "codebase", | |
| 14 | + "tree", | |
| 15 | + "open", | |
| 16 | + "debugger", | |
| 17 | + "terminal", | |
| 18 | + "diff", | |
| 19 | +]; |
added core/promptFiles/parsePromptFile.ts +24 −0
| @@ -0,0 +1,24 @@ | ||
| 1 | +import * as YAML from "yaml"; | |
| 2 | + | |
| 3 | +import { getLastNPathParts } from "../util/uri"; | |
| 4 | + | |
| 5 | +export function parsePromptFile(path: string, content: string) { | |
| 6 | + let [preambleRaw, prompt] = content.split("\n---\n"); | |
| 7 | + if (prompt === undefined) { | |
| 8 | + prompt = preambleRaw; | |
| 9 | + preambleRaw = ""; | |
| 10 | + } | |
| 11 | + | |
| 12 | + const preamble = YAML.parse(preambleRaw) ?? {}; | |
| 13 | + const name = preamble.name ?? getLastNPathParts(path, 1).split(".prompt")[0]; | |
| 14 | + const description = preamble.description ?? name; | |
| 15 | + const version = preamble.version ?? 2; | |
| 16 | + | |
| 17 | + let systemMessage: string | undefined = undefined; | |
| 18 | + if (prompt.includes("<system>")) { | |
| 19 | + systemMessage = prompt.split("<system>")[1].split("</system>")[0].trim(); | |
| 20 | + prompt = prompt.split("</system>")[1].trim(); | |
| 21 | + } | |
| 22 | + | |
| 23 | + return { name, description, systemMessage, prompt, version }; | |
| 24 | +} |
deleted core/promptFiles/v1/getContextProviderHelpers.ts +0 −38
| @@ -1,38 +0,0 @@ | ||
| 1 | -import Handlebars from "handlebars"; | |
| 2 | -import { ContextItem, ContinueSDK, IContextProvider } from "../.."; | |
| 3 | - | |
| 4 | -function createContextItem(item: ContextItem, provider: IContextProvider) { | |
| 5 | - return { | |
| 6 | - ...item, | |
| 7 | - id: { | |
| 8 | - itemId: item.description, | |
| 9 | - providerTitle: provider.description.title, | |
| 10 | - }, | |
| 11 | - }; | |
| 12 | -} | |
| 13 | - | |
| 14 | -export function getContextProviderHelpers( | |
| 15 | - context: ContinueSDK, | |
| 16 | -): Array<[string, Handlebars.HelperDelegate]> | undefined { | |
| 17 | - return context.config.contextProviders?.map((provider: IContextProvider) => [ | |
| 18 | - provider.description.title, | |
| 19 | - async (helperContext: any) => { | |
| 20 | - const items = await provider.getContextItems(helperContext, { | |
| 21 | - config: context.config, | |
| 22 | - embeddingsProvider: context.config.selectedModelByRole.embed, | |
| 23 | - fetch: context.fetch, | |
| 24 | - fullInput: context.input, | |
| 25 | - ide: context.ide, | |
| 26 | - llm: context.llm, | |
| 27 | - reranker: context.config.selectedModelByRole.rerank, | |
| 28 | - selectedCode: context.selectedCode, | |
| 29 | - }); | |
| 30 | - | |
| 31 | - items.forEach((item) => | |
| 32 | - context.addContextItem(createContextItem(item, provider)), | |
| 33 | - ); | |
| 34 | - | |
| 35 | - return items.map((item) => item.content).join("\n\n"); | |
| 36 | - }, | |
| 37 | - ]); | |
| 38 | -} |
deleted core/promptFiles/v1/handlebarUtils.ts +0 −117
| @@ -1,117 +0,0 @@ | ||
| 1 | -import Handlebars from "handlebars"; | |
| 2 | -import { v4 as uuidv4 } from "uuid"; | |
| 3 | - | |
| 4 | -function convertToLetter(num: number): string { | |
| 5 | - let result = ""; | |
| 6 | - while (num > 0) { | |
| 7 | - const remainder = (num - 1) % 26; | |
| 8 | - result = String.fromCharCode(97 + remainder) + result; | |
| 9 | - num = Math.floor((num - 1) / 26); | |
| 10 | - } | |
| 11 | - return result; | |
| 12 | -} | |
| 13 | - | |
| 14 | -/** | |
| 15 | - * We replace filepaths with alphabetic characters to handle | |
| 16 | - * escaping issues. | |
| 17 | - */ | |
| 18 | -const replaceFilepaths = ( | |
| 19 | - value: string, | |
| 20 | - ctxProviderNames: string[], | |
| 21 | -): [string, { [key: string]: string }] => { | |
| 22 | - const ast = Handlebars.parse(value); | |
| 23 | - | |
| 24 | - const keysToFilepath: { [key: string]: string } = {}; | |
| 25 | - | |
| 26 | - let keyIndex = 1; | |
| 27 | - | |
| 28 | - for (const i in ast.body) { | |
| 29 | - const node = ast.body[i] as any; | |
| 30 | - | |
| 31 | - if (node.type === "MustacheStatement") { | |
| 32 | - const originalNodeVal = node.path.original; | |
| 33 | - const isFilepath = !ctxProviderNames.includes(originalNodeVal); | |
| 34 | - | |
| 35 | - if (isFilepath) { | |
| 36 | - const letter = convertToLetter(keyIndex); | |
| 37 | - | |
| 38 | - keysToFilepath[letter] = originalNodeVal; | |
| 39 | - | |
| 40 | - value = value.replace( | |
| 41 | - new RegExp(`{{\\s*${originalNodeVal}\\s*}}`), | |
| 42 | - `{{${letter}}}`, | |
| 43 | - ); | |
| 44 | - | |
| 45 | - keyIndex++; | |
| 46 | - } | |
| 47 | - } | |
| 48 | - } | |
| 49 | - | |
| 50 | - return [value, keysToFilepath]; | |
| 51 | -}; | |
| 52 | - | |
| 53 | -export function registerHelpers( | |
| 54 | - helpers: Array<[string, Handlebars.HelperDelegate]>, | |
| 55 | -): { | |
| 56 | - [key: string]: Promise<string>; | |
| 57 | -} { | |
| 58 | - const promises: { [key: string]: Promise<string> } = {}; | |
| 59 | - | |
| 60 | - for (const [name, helper] of helpers) { | |
| 61 | - Handlebars.registerHelper(name, (...args) => { | |
| 62 | - const id = uuidv4(); | |
| 63 | - promises[id] = helper(...args); | |
| 64 | - return `__${id}__`; | |
| 65 | - }); | |
| 66 | - } | |
| 67 | - | |
| 68 | - return promises; | |
| 69 | -} | |
| 70 | - | |
| 71 | -export async function prepareTemplateAndData( | |
| 72 | - template: string, | |
| 73 | - readFile: (filepath: string) => Promise<string>, | |
| 74 | - inputData: Record<string, string>, | |
| 75 | - ctxProviderNames: string[], | |
| 76 | -): Promise<[string, any]> { | |
| 77 | - const [newTemplate, vars] = replaceFilepaths(template, ctxProviderNames); | |
| 78 | - | |
| 79 | - const data: any = { ...inputData }; | |
| 80 | - | |
| 81 | - for (const [replacedName, originalCtxProviderName] of Object.entries(vars)) { | |
| 82 | - data[replacedName] = | |
| 83 | - inputData[originalCtxProviderName] ?? originalCtxProviderName; | |
| 84 | - | |
| 85 | - // If it's not a context provider, assume it's a filepath. | |
| 86 | - if (!ctxProviderNames.includes(originalCtxProviderName)) { | |
| 87 | - const fileContents = await readFile(vars[replacedName]); | |
| 88 | - | |
| 89 | - if (fileContents) { | |
| 90 | - data[replacedName] = fileContents; | |
| 91 | - } | |
| 92 | - } | |
| 93 | - } | |
| 94 | - | |
| 95 | - return [newTemplate, data]; | |
| 96 | -} | |
| 97 | - | |
| 98 | -export function compileAndRenderTemplate( | |
| 99 | - template: string, | |
| 100 | - data: Record<string, string>, | |
| 101 | -): string { | |
| 102 | - const templateFn = Handlebars.compile(template); | |
| 103 | - return templateFn(data); | |
| 104 | -} | |
| 105 | - | |
| 106 | -export async function resolveHelperPromises( | |
| 107 | - renderedString: string, | |
| 108 | - promises: { [key: string]: Promise<string> }, | |
| 109 | -): Promise<string> { | |
| 110 | - await Promise.all(Object.values(promises)); | |
| 111 | - | |
| 112 | - for (const id in promises) { | |
| 113 | - renderedString = renderedString.replace(`__${id}__`, await promises[id]); | |
| 114 | - } | |
| 115 | - | |
| 116 | - return renderedString; | |
| 117 | -} |
deleted core/promptFiles/v1/index.ts +0 −1
| @@ -1,1 +0,0 @@ | ||
| 1 | -export const DEFAULT_PROMPTS_FOLDER_V1 = ".prompts"; |
deleted core/promptFiles/v1/renderTemplatedString.ts +0 −30
| @@ -1,30 +0,0 @@ | ||
| 1 | -import { | |
| 2 | - compileAndRenderTemplate, | |
| 3 | - prepareTemplateAndData, | |
| 4 | - registerHelpers, | |
| 5 | - resolveHelperPromises, | |
| 6 | -} from "./handlebarUtils"; | |
| 7 | - | |
| 8 | -export async function renderTemplatedString( | |
| 9 | - template: string, | |
| 10 | - readFile: (filepath: string) => Promise<string>, | |
| 11 | - inputData: Record<string, string>, | |
| 12 | - availableHelpers?: Array<[string, Handlebars.HelperDelegate]>, | |
| 13 | -): Promise<string> { | |
| 14 | - const helperPromises = availableHelpers | |
| 15 | - ? registerHelpers(availableHelpers) | |
| 16 | - : {}; | |
| 17 | - | |
| 18 | - const ctxProviderNames = availableHelpers?.map((h) => h[0]) ?? []; | |
| 19 | - | |
| 20 | - const [newTemplate, data] = await prepareTemplateAndData( | |
| 21 | - template, | |
| 22 | - readFile, | |
| 23 | - inputData, | |
| 24 | - ctxProviderNames, | |
| 25 | - ); | |
| 26 | - | |
| 27 | - let renderedString = compileAndRenderTemplate(newTemplate, data); | |
| 28 | - | |
| 29 | - return resolveHelperPromises(renderedString, helperPromises); | |
| 30 | -} |
deleted core/promptFiles/v1/slashCommandFromPromptFile.ts +0 −89
| @@ -1,89 +0,0 @@ | ||
| 1 | -import { ContinueSDK, SlashCommand } from "../.."; | |
| 2 | -import { getDiffsFromCache } from "../../autocomplete/snippets/gitDiffCache"; | |
| 3 | -import { renderChatMessage } from "../../util/messageContent"; | |
| 4 | -import { getLastNPathParts } from "../../util/uri"; | |
| 5 | -import { parsePromptFileV1V2 } from "../v2/parsePromptFileV1V2"; | |
| 6 | -import { renderPromptFileV2 } from "../v2/renderPromptFile"; | |
| 7 | - | |
| 8 | -import { getContextProviderHelpers } from "./getContextProviderHelpers"; | |
| 9 | -import { renderTemplatedString } from "./renderTemplatedString"; | |
| 10 | -import { replaceSlashCommandWithPromptInChatHistory } from "./updateChatHistory"; | |
| 11 | - | |
| 12 | -export function extractName(preamble: { name?: string }, path: string): string { | |
| 13 | - return preamble.name ?? getLastNPathParts(path, 1).split(".prompt")[0]; | |
| 14 | -} | |
| 15 | - | |
| 16 | -async function renderPromptV1( | |
| 17 | - prompt: string, | |
| 18 | - context: ContinueSDK, | |
| 19 | - userInput: string, | |
| 20 | -) { | |
| 21 | - const helpers = getContextProviderHelpers(context); | |
| 22 | - | |
| 23 | - const inputData: Record<string, string> = { | |
| 24 | - input: userInput, | |
| 25 | - }; | |
| 26 | - | |
| 27 | - // A few context providers that don't need to be in config.json to work in .prompt files | |
| 28 | - if (helpers?.find((helper) => helper[0] === "diff")) { | |
| 29 | - const diffs = await getDiffsFromCache(context.ide); | |
| 30 | - inputData.diff = diffs.join("\n"); | |
| 31 | - } | |
| 32 | - if (helpers?.find((helper) => helper[0] === "currentFile")) { | |
| 33 | - const currentFile = await context.ide.getCurrentFile(); | |
| 34 | - if (currentFile) { | |
| 35 | - inputData.currentFile = currentFile.path; | |
| 36 | - } | |
| 37 | - } | |
| 38 | - | |
| 39 | - return renderTemplatedString( | |
| 40 | - prompt, | |
| 41 | - context.ide.readFile.bind(context.ide), | |
| 42 | - inputData, | |
| 43 | - helpers, | |
| 44 | - ); | |
| 45 | -} | |
| 46 | - | |
| 47 | -export function slashCommandFromPromptFileV1( | |
| 48 | - path: string, | |
| 49 | - content: string, | |
| 50 | -): SlashCommand | null { | |
| 51 | - const { name, description, systemMessage, prompt } = parsePromptFileV1V2( | |
| 52 | - path, | |
| 53 | - content, | |
| 54 | - ); | |
| 55 | - | |
| 56 | - return { | |
| 57 | - name, | |
| 58 | - description, | |
| 59 | - prompt, | |
| 60 | - promptFile: path, | |
| 61 | - run: async function* (context) { | |
| 62 | - const [_, renderedPrompt] = await renderPromptFileV2(prompt, { | |
| 63 | - config: context.config, | |
| 64 | - fullInput: context.input, | |
| 65 | - embeddingsProvider: context.config.modelsByRole.embed[0], | |
| 66 | - reranker: context.config.modelsByRole.rerank[0], | |
| 67 | - llm: context.llm, | |
| 68 | - ide: context.ide, | |
| 69 | - selectedCode: context.selectedCode, | |
| 70 | - fetch: context.fetch, | |
| 71 | - }); | |
| 72 | - | |
| 73 | - const messages = replaceSlashCommandWithPromptInChatHistory( | |
| 74 | - context.history, | |
| 75 | - name, | |
| 76 | - renderedPrompt, | |
| 77 | - systemMessage, | |
| 78 | - ); | |
| 79 | - | |
| 80 | - for await (const chunk of context.llm.streamChat( | |
| 81 | - messages, | |
| 82 | - context.abortController.signal, | |
| 83 | - context.completionOptions, | |
| 84 | - )) { | |
| 85 | - yield renderChatMessage(chunk); | |
| 86 | - } | |
| 87 | - }, | |
| 88 | - }; | |
| 89 | -} |
deleted core/promptFiles/v1/updateChatHistory.ts +0 −64
| @@ -1,64 +0,0 @@ | ||
| 1 | -import { ChatMessage } from "../.."; | |
| 2 | - | |
| 3 | -export function replaceSlashCommandWithPromptInChatHistory( | |
| 4 | - history: ChatMessage[], | |
| 5 | - commandName: string, | |
| 6 | - renderedPrompt: string, | |
| 7 | - systemMessageOverride?: string, | |
| 8 | -): ChatMessage[] { | |
| 9 | - const messages = [...history]; | |
| 10 | - | |
| 11 | - for (let i = messages.length - 1; i >= 0; i--) { | |
| 12 | - const { role, content } = messages[i]; | |
| 13 | - if (role !== "user") { | |
| 14 | - continue; | |
| 15 | - } | |
| 16 | - | |
| 17 | - if (Array.isArray(content)) { | |
| 18 | - if ( | |
| 19 | - content.some( | |
| 20 | - (part) => | |
| 21 | - part.type === "text" && part.text?.startsWith(`/${commandName}`), | |
| 22 | - ) | |
| 23 | - ) { | |
| 24 | - messages[i] = updateArrayContent( | |
| 25 | - messages[i], | |
| 26 | - commandName, | |
| 27 | - renderedPrompt, | |
| 28 | - ); | |
| 29 | - break; | |
| 30 | - } | |
| 31 | - } else if ( | |
| 32 | - typeof content === "string" && | |
| 33 | - content.startsWith(`/${commandName}`) | |
| 34 | - ) { | |
| 35 | - messages[i] = { ...messages[i], content: renderedPrompt }; | |
| 36 | - break; | |
| 37 | - } | |
| 38 | - } | |
| 39 | - | |
| 40 | - if (systemMessageOverride) { | |
| 41 | - if (messages[0]?.role === "system") { | |
| 42 | - messages[0].content = systemMessageOverride; | |
| 43 | - } else { | |
| 44 | - messages.unshift({ role: "system", content: systemMessageOverride }); | |
| 45 | - } | |
| 46 | - } | |
| 47 | - | |
| 48 | - return messages; | |
| 49 | -} | |
| 50 | - | |
| 51 | -function updateArrayContent( | |
| 52 | - message: any, | |
| 53 | - commandName: string, | |
| 54 | - renderedPrompt: string, | |
| 55 | -) { | |
| 56 | - return { | |
| 57 | - ...message, | |
| 58 | - content: message.content.map((part: any) => | |
| 59 | - part.text?.startsWith(`/${commandName}`) | |
| 60 | - ? { ...part, text: renderedPrompt } | |
| 61 | - : part, | |
| 62 | - ), | |
| 63 | - }; | |
| 64 | -} |
deleted core/promptFiles/v2/createNewPromptFile.ts +0 −76
| @@ -1,76 +0,0 @@ | ||
| 1 | -import { IDE } from "../.."; | |
| 2 | -import { GlobalContext } from "../../util/GlobalContext"; | |
| 3 | -import { joinPathsToUri } from "../../util/uri"; | |
| 4 | - | |
| 5 | -const FIRST_TIME_DEFAULT_PROMPT_FILE = `# This is an example ".prompt" file | |
| 6 | -# It is used to define and reuse prompts within Continue | |
| 7 | -# Each .prompt file can be accessed by typing "@prompts" in the Chat input | |
| 8 | - | |
| 9 | -# A prompt file consists of two parts: | |
| 10 | -# 1. Everything above the "---" is YAML. Here you can set "temperature", "description", and other options | |
| 11 | -# 2. Everything below the "---" is the prompt body | |
| 12 | - | |
| 13 | -# If you do not want to set any options, you do not need to include the "---" | |
| 14 | - | |
| 15 | -# In the body, you can reference: | |
| 16 | -# 1. Files, using either absolute or relative paths (based on the workspace root) | |
| 17 | - # @README.md | |
| 18 | - # @src/test/test.py | |
| 19 | - # @/Users/me/Desktop/my-project/src/test/test.py | |
| 20 | -# 2. URLs, for example | |
| 21 | - # @https://example.com | |
| 22 | -# 3. Context providers, for example | |
| 23 | - # @currentFile | |
| 24 | - # @os | |
| 25 | - # @repo-map | |
| 26 | - | |
| 27 | -# To learn more, see the full .prompt file reference: https://docs.continue.dev/features/prompt-files | |
| 28 | -name: Example | |
| 29 | -description: Example prompt file | |
| 30 | ---- | |
| 31 | - | |
| 32 | -Here is information about the current repo: | |
| 33 | - | |
| 34 | -@README.md`; | |
| 35 | - | |
| 36 | -const DEFAULT_PROMPT_FILE = ""; | |
| 37 | - | |
| 38 | -export async function createNewPromptFileV2( | |
| 39 | - ide: IDE, | |
| 40 | - promptPath: string | undefined, | |
| 41 | -): Promise<void> { | |
| 42 | - const workspaceDirs = await ide.getWorkspaceDirs(); | |
| 43 | - if (workspaceDirs.length === 0) { | |
| 44 | - throw new Error( | |
| 45 | - "No workspace directories found. Make sure you've opened a folder in your IDE.", | |
| 46 | - ); | |
| 47 | - } | |
| 48 | - | |
| 49 | - const baseDirUri = joinPathsToUri( | |
| 50 | - workspaceDirs[0], | |
| 51 | - promptPath ?? ".continue/prompts", | |
| 52 | - ); | |
| 53 | - | |
| 54 | - // Find the first available filename | |
| 55 | - let counter = 0; | |
| 56 | - let promptFileUri: string; | |
| 57 | - do { | |
| 58 | - const suffix = counter === 0 ? "" : `-${counter}`; | |
| 59 | - promptFileUri = joinPathsToUri( | |
| 60 | - baseDirUri, | |
| 61 | - `new-prompt-file${suffix}.prompt`, | |
| 62 | - ); | |
| 63 | - counter++; | |
| 64 | - } while (await ide.fileExists(promptFileUri)); | |
| 65 | - | |
| 66 | - const globalContext = new GlobalContext(); | |
| 67 | - const PROMPT_FILE = | |
| 68 | - globalContext.get("hasAlreadyCreatedAPromptFile") === true | |
| 69 | - ? DEFAULT_PROMPT_FILE | |
| 70 | - : FIRST_TIME_DEFAULT_PROMPT_FILE; | |
| 71 | - | |
| 72 | - globalContext.update("hasAlreadyCreatedAPromptFile", true); | |
| 73 | - | |
| 74 | - await ide.writeFile(promptFileUri, PROMPT_FILE); | |
| 75 | - await ide.openFile(promptFileUri); | |
| 76 | -} |
deleted core/promptFiles/v2/getPromptFiles.ts +0 −67
| @@ -1,67 +0,0 @@ | ||
| 1 | -import { IDE } from "../.."; | |
| 2 | -import { walkDir } from "../../indexing/walkDir"; | |
| 3 | -import { readAllGlobalPromptFiles } from "../../util/paths"; | |
| 4 | -import { joinPathsToUri } from "../../util/uri"; | |
| 5 | -import { DEFAULT_PROMPTS_FOLDER_V1 } from "../v1"; | |
| 6 | - | |
| 7 | -export const DEFAULT_PROMPTS_FOLDER_V2 = ".continue/prompts"; | |
| 8 | -export async function getPromptFilesFromDir( | |
| 9 | - ide: IDE, | |
| 10 | - dir: string, | |
| 11 | -): Promise<{ path: string; content: string }[]> { | |
| 12 | - try { | |
| 13 | - const exists = await ide.fileExists(dir); | |
| 14 | - | |
| 15 | - if (!exists) { | |
| 16 | - return []; | |
| 17 | - } | |
| 18 | - | |
| 19 | - const uris = await walkDir(dir, ide, { | |
| 20 | - source: "get dir prompt files", | |
| 21 | - }); | |
| 22 | - const promptFilePaths = uris.filter((p) => p.endsWith(".prompt")); | |
| 23 | - const results = promptFilePaths.map(async (uri) => { | |
| 24 | - const content = await ide.readFile(uri); // make a try catch | |
| 25 | - return { path: uri, content }; | |
| 26 | - }); | |
| 27 | - return Promise.all(results); | |
| 28 | - } catch (e) { | |
| 29 | - console.error(e); | |
| 30 | - return []; | |
| 31 | - } | |
| 32 | -} | |
| 33 | - | |
| 34 | -export async function getAllPromptFiles( | |
| 35 | - ide: IDE, | |
| 36 | - overridePromptFolder?: string, | |
| 37 | - checkV1DefaultFolder: boolean = false, | |
| 38 | -): Promise<{ path: string; content: string }[]> { | |
| 39 | - const workspaceDirs = await ide.getWorkspaceDirs(); | |
| 40 | - let promptFiles: { path: string; content: string }[] = []; | |
| 41 | - | |
| 42 | - let dirsToCheck = [DEFAULT_PROMPTS_FOLDER_V2]; | |
| 43 | - if (checkV1DefaultFolder) { | |
| 44 | - dirsToCheck.push(DEFAULT_PROMPTS_FOLDER_V1); | |
| 45 | - } | |
| 46 | - if (overridePromptFolder) { | |
| 47 | - dirsToCheck = [overridePromptFolder]; | |
| 48 | - } | |
| 49 | - | |
| 50 | - const fullDirs = workspaceDirs | |
| 51 | - .map((dir) => dirsToCheck.map((d) => joinPathsToUri(dir, d))) | |
| 52 | - .flat(); | |
| 53 | - | |
| 54 | - promptFiles = ( | |
| 55 | - await Promise.all(fullDirs.map((dir) => getPromptFilesFromDir(ide, dir))) | |
| 56 | - ).flat(); | |
| 57 | - | |
| 58 | - // Also read from ~/.continue/.prompts | |
| 59 | - promptFiles.push(...readAllGlobalPromptFiles()); | |
| 60 | - | |
| 61 | - return await Promise.all( | |
| 62 | - promptFiles.map(async (file) => { | |
| 63 | - const content = await ide.readFile(file.path); | |
| 64 | - return { path: file.path, content }; | |
| 65 | - }), | |
| 66 | - ); | |
| 67 | -} |
deleted core/promptFiles/v2/parse.ts +0 −34
| @@ -1,34 +0,0 @@ | ||
| 1 | -import * as YAML from "yaml"; | |
| 2 | - | |
| 3 | -import { getLastNPathParts } from "../../util/uri"; | |
| 4 | - | |
| 5 | -export function extractName(preamble: { name?: string }, path: string): string { | |
| 6 | - return preamble.name ?? getLastNPathParts(path, 1).split(".prompt")[0]; | |
| 7 | -} | |
| 8 | - | |
| 9 | -export function getPreambleAndBody(content: string): [string, string] { | |
| 10 | - let [preamble, body] = content.split("\n---\n"); | |
| 11 | - if (body === undefined) { | |
| 12 | - // This means there is no preamble | |
| 13 | - body = preamble; | |
| 14 | - preamble = ""; | |
| 15 | - } | |
| 16 | - return [preamble, body]; | |
| 17 | -} | |
| 18 | - | |
| 19 | -export function parsePreamble( | |
| 20 | - path: string, | |
| 21 | - content: string, | |
| 22 | -): { [key: string]: any; name: string; description: string } { | |
| 23 | - const [preambleRaw, _] = getPreambleAndBody(content); | |
| 24 | - | |
| 25 | - const preamble = YAML.parse(preambleRaw) ?? {}; | |
| 26 | - const name = extractName(preamble, path); | |
| 27 | - const description = preamble.description ?? name; | |
| 28 | - | |
| 29 | - return { | |
| 30 | - ...preamble, | |
| 31 | - name, | |
| 32 | - description, | |
| 33 | - }; | |
| 34 | -} |
deleted core/promptFiles/v2/parsePromptFileV1V2.ts +0 −24
| @@ -1,24 +0,0 @@ | ||
| 1 | -import * as YAML from "yaml"; | |
| 2 | - | |
| 3 | -import { getLastNPathParts } from "../../util/uri"; | |
| 4 | - | |
| 5 | -export function parsePromptFileV1V2(path: string, content: string) { | |
| 6 | - let [preambleRaw, prompt] = content.split("\n---\n"); | |
| 7 | - if (prompt === undefined) { | |
| 8 | - prompt = preambleRaw; | |
| 9 | - preambleRaw = ""; | |
| 10 | - } | |
| 11 | - | |
| 12 | - const preamble = YAML.parse(preambleRaw) ?? {}; | |
| 13 | - const name = preamble.name ?? getLastNPathParts(path, 1).split(".prompt")[0]; | |
| 14 | - const description = preamble.description ?? name; | |
| 15 | - const version = preamble.version ?? 2; | |
| 16 | - | |
| 17 | - let systemMessage: string | undefined = undefined; | |
| 18 | - if (prompt.includes("<system>")) { | |
| 19 | - systemMessage = prompt.split("<system>")[1].split("</system>")[0].trim(); | |
| 20 | - prompt = prompt.split("</system>")[1].trim(); | |
| 21 | - } | |
| 22 | - | |
| 23 | - return { name, description, systemMessage, prompt, version }; | |
| 24 | -} |
deleted core/promptFiles/v2/renderPromptFile.ts +0 −84
| @@ -1,84 +0,0 @@ | ||
| 1 | -import { ContextItem, ContextProviderExtras } from "../.."; | |
| 2 | -import { contextProviderClassFromName } from "../../context/providers"; | |
| 3 | -import { getUrlContextItems } from "../../context/providers/URLContextProvider"; | |
| 4 | -import { resolveRelativePathInDir } from "../../util/ideUtils"; | |
| 5 | -import { getUriPathBasename } from "../../util/uri"; | |
| 6 | - | |
| 7 | -import { getPreambleAndBody } from "./parse"; | |
| 8 | - | |
| 9 | -async function resolveAttachment( | |
| 10 | - name: string, | |
| 11 | - extras: ContextProviderExtras, | |
| 12 | -): Promise<ContextItem[]> { | |
| 13 | - // Context providers | |
| 14 | - const contextProvider = extras.config.contextProviders?.find( | |
| 15 | - (provider) => provider.description.title === name, | |
| 16 | - ); | |
| 17 | - if (contextProvider) { | |
| 18 | - const items = await contextProvider.getContextItems("", extras); | |
| 19 | - return items; | |
| 20 | - } else { | |
| 21 | - // Just instantiate it here | |
| 22 | - const providerClass = contextProviderClassFromName(name) as any; | |
| 23 | - if (providerClass) { | |
| 24 | - const providerInstance = new providerClass({}); | |
| 25 | - return providerInstance.getContextItems("", extras); | |
| 26 | - } | |
| 27 | - } | |
| 28 | - | |
| 29 | - // Files | |
| 30 | - const resolvedFileUri = await resolveRelativePathInDir(name, extras.ide); | |
| 31 | - if (resolvedFileUri) { | |
| 32 | - let subItems: ContextItem[] = []; | |
| 33 | - if (name.endsWith(".prompt")) { | |
| 34 | - // Recurse | |
| 35 | - const [items, _] = await renderPromptFileV2( | |
| 36 | - await extras.ide.readFile(resolvedFileUri), | |
| 37 | - extras, | |
| 38 | - ); | |
| 39 | - subItems.push(...items); | |
| 40 | - } | |
| 41 | - | |
| 42 | - const content = `\`\`\`${name}\n${await extras.ide.readFile(resolvedFileUri)}\n\`\`\``; | |
| 43 | - return [ | |
| 44 | - ...subItems, | |
| 45 | - { | |
| 46 | - name: getUriPathBasename(resolvedFileUri), | |
| 47 | - content, | |
| 48 | - description: resolvedFileUri, | |
| 49 | - }, | |
| 50 | - ]; | |
| 51 | - } | |
| 52 | - | |
| 53 | - // URLs | |
| 54 | - if (name.startsWith("http")) { | |
| 55 | - const items = getUrlContextItems(name, extras.fetch); | |
| 56 | - return items; | |
| 57 | - } | |
| 58 | - | |
| 59 | - return []; | |
| 60 | -} | |
| 61 | - | |
| 62 | -export async function renderPromptFileV2( | |
| 63 | - rawContent: string, | |
| 64 | - extras: ContextProviderExtras, | |
| 65 | -): Promise<[ContextItem[], string]> { | |
| 66 | - const [_, body] = getPreambleAndBody(rawContent); | |
| 67 | - | |
| 68 | - const contextItemsPromises: Promise<ContextItem[]>[] = []; | |
| 69 | - const renderedBody = body.replace(/@([^\s]+)/g, (match, name) => { | |
| 70 | - contextItemsPromises.push(resolveAttachment(name, extras)); | |
| 71 | - return match; | |
| 72 | - }); | |
| 73 | - | |
| 74 | - const contextItems = (await Promise.all(contextItemsPromises)).flat(); | |
| 75 | - const renderedPrompt = [ | |
| 76 | - ...contextItems.map((item) => item.content), | |
| 77 | - renderedBody, | |
| 78 | - extras.fullInput, | |
| 79 | - ] | |
| 80 | - .join("\n\n") | |
| 81 | - .trim(); | |
| 82 | - | |
| 83 | - return [contextItems, renderedPrompt]; | |
| 84 | -} |
deleted core/promptFiles/v2/renderPromptFile.vitest.ts +0 −175
| @@ -1,175 +0,0 @@ | ||
| 1 | -import { ContextProviderExtras, ILLM, RangeInFile } from "../.."; | |
| 2 | -import { testConfigHandler, testIde } from "../../test/fixtures"; | |
| 3 | -import { | |
| 4 | - addToTestDir, | |
| 5 | - setUpTestDir, | |
| 6 | - tearDownTestDir, | |
| 7 | -} from "../../test/testDir"; | |
| 8 | -import { renderPromptFileV2 } from "./renderPromptFile"; | |
| 9 | - | |
| 10 | -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; | |
| 11 | - | |
| 12 | -vi.mock( | |
| 13 | - import("../../context/providers/URLContextProvider"), | |
| 14 | - async (importOriginal) => { | |
| 15 | - const actual = await importOriginal(); | |
| 16 | - return { | |
| 17 | - ...actual, | |
| 18 | - getUrlContextItems: vi.fn().mockResolvedValue([ | |
| 19 | - { | |
| 20 | - description: "https://example.com", | |
| 21 | - content: "Example Content", | |
| 22 | - name: "Example site", | |
| 23 | - uri: { | |
| 24 | - type: "url", | |
| 25 | - value: "https://example.com", | |
| 26 | - }, | |
| 27 | - }, | |
| 28 | - ]), | |
| 29 | - }; | |
| 30 | - }, | |
| 31 | -); | |
| 32 | - | |
| 33 | -describe("renderPromptFileV2", () => { | |
| 34 | - let extras: ContextProviderExtras; | |
| 35 | - const mockGetContextItems = vi.fn().mockResolvedValue([ | |
| 36 | - { | |
| 37 | - name: "custom", | |
| 38 | - content: "Custom provider content", | |
| 39 | - description: "Custom provider", | |
| 40 | - }, | |
| 41 | - ]); | |
| 42 | - beforeEach(async () => { | |
| 43 | - const { config } = await testConfigHandler.loadConfig(); | |
| 44 | - | |
| 45 | - // Setup mock extras | |
| 46 | - extras = { | |
| 47 | - config: { | |
| 48 | - ...config!, | |
| 49 | - contextProviders: [ | |
| 50 | - { | |
| 51 | - description: { | |
| 52 | - type: "normal", | |
| 53 | - title: "CustomProvider", | |
| 54 | - displayTitle: "Custom Provider", | |
| 55 | - description: "A custom context provider", | |
| 56 | - }, | |
| 57 | - loadSubmenuItems: vi.fn().mockResolvedValue([]), | |
| 58 | - getContextItems: mockGetContextItems, | |
| 59 | - }, | |
| 60 | - ], | |
| 61 | - }, | |
| 62 | - fullInput: "User input", | |
| 63 | - embeddingsProvider: null, | |
| 64 | - reranker: null, | |
| 65 | - llm: {} as ILLM, | |
| 66 | - ide: testIde, | |
| 67 | - selectedCode: [] as RangeInFile[], | |
| 68 | - fetch: vi.fn(), | |
| 69 | - }; | |
| 70 | - | |
| 71 | - // Clear all mocks | |
| 72 | - vi.clearAllMocks(); | |
| 73 | - setUpTestDir(); | |
| 74 | - }); | |
| 75 | - | |
| 76 | - afterEach(() => { | |
| 77 | - tearDownTestDir(); | |
| 78 | - }); | |
| 79 | - | |
| 80 | - it("should render a prompt file with no attachments", async () => { | |
| 81 | - const rawContent = "Simple prompt with no attachments"; | |
| 82 | - const [contextItems, renderedPrompt] = await renderPromptFileV2( | |
| 83 | - rawContent, | |
| 84 | - extras, | |
| 85 | - ); | |
| 86 | - | |
| 87 | - expect(contextItems).toHaveLength(0); | |
| 88 | - expect(renderedPrompt).toBe( | |
| 89 | - "Simple prompt with no attachments\n\nUser input", | |
| 90 | - ); | |
| 91 | - }); | |
| 92 | - | |
| 93 | - it("should handle URL attachments", async () => { | |
| 94 | - const rawContent = "Content with URL @https://example.com"; | |
| 95 | - | |
| 96 | - const [contextItems, renderedPrompt] = await renderPromptFileV2( | |
| 97 | - rawContent, | |
| 98 | - extras, | |
| 99 | - ); | |
| 100 | - | |
| 101 | - expect(contextItems).toHaveLength(1); | |
| 102 | - expect(renderedPrompt).toContain("Example Content"); | |
| 103 | - }); | |
| 104 | - | |
| 105 | - it("should resolve file attachments", async () => { | |
| 106 | - const rawContent = "Content with file attachment @test.txt"; | |
| 107 | - | |
| 108 | - addToTestDir([["test.txt", "File content"]]); | |
| 109 | - | |
| 110 | - const [contextItems, renderedPrompt] = await renderPromptFileV2( | |
| 111 | - rawContent, | |
| 112 | - extras, | |
| 113 | - ); | |
| 114 | - | |
| 115 | - expect(contextItems).toHaveLength(1); | |
| 116 | - expect(renderedPrompt).toContain("```test.txt\nFile content\n```"); | |
| 117 | - expect(renderedPrompt).toContain("Content with file attachment @test.txt"); | |
| 118 | - }); | |
| 119 | - | |
| 120 | - it("should handle nested prompt files", async () => { | |
| 121 | - const rawContent = "Main prompt with nested @nested.prompt"; | |
| 122 | - addToTestDir([ | |
| 123 | - ["nested.prompt", "Nested prompt content with @CustomProvider"], | |
| 124 | - ]); | |
| 125 | - | |
| 126 | - const [contextItems, renderedPrompt] = await renderPromptFileV2( | |
| 127 | - rawContent, | |
| 128 | - extras, | |
| 129 | - ); | |
| 130 | - | |
| 131 | - expect(renderedPrompt).toContain("Custom provider content"); | |
| 132 | - }); | |
| 133 | - | |
| 134 | - it("should handle custom context providers", async () => { | |
| 135 | - const rawContent = "Content with custom provider @CustomProvider"; | |
| 136 | - | |
| 137 | - const [contextItems, renderedPrompt] = await renderPromptFileV2( | |
| 138 | - rawContent, | |
| 139 | - extras, | |
| 140 | - ); | |
| 141 | - | |
| 142 | - expect(contextItems).toHaveLength(1); | |
| 143 | - expect(renderedPrompt).toContain("Custom provider content"); | |
| 144 | - expect(mockGetContextItems).toHaveBeenCalled(); | |
| 145 | - }); | |
| 146 | - | |
| 147 | - it("should handle multiple attachments", async () => { | |
| 148 | - const rawContent = "Content with @file1.txt and @file2.txt"; | |
| 149 | - addToTestDir([ | |
| 150 | - ["file1.txt", "Content 1"], | |
| 151 | - ["file2.txt", "Content 2"], | |
| 152 | - ]); | |
| 153 | - | |
| 154 | - const [contextItems, renderedPrompt] = await renderPromptFileV2( | |
| 155 | - rawContent, | |
| 156 | - extras, | |
| 157 | - ); | |
| 158 | - | |
| 159 | - expect(contextItems).toHaveLength(2); | |
| 160 | - expect(renderedPrompt).toContain("```file1.txt\nContent 1\n```"); | |
| 161 | - expect(renderedPrompt).toContain("```file2.txt\nContent 2\n```"); | |
| 162 | - }); | |
| 163 | - | |
| 164 | - it("should handle failed attachment resolutions gracefully", async () => { | |
| 165 | - const rawContent = "Content with @nonexistent"; | |
| 166 | - | |
| 167 | - const [contextItems, renderedPrompt] = await renderPromptFileV2( | |
| 168 | - rawContent, | |
| 169 | - extras, | |
| 170 | - ); | |
| 171 | - | |
| 172 | - expect(contextItems).toHaveLength(0); | |
| 173 | - expect(renderedPrompt).toBe("Content with @nonexistent\n\nUser input"); | |
| 174 | - }); | |
| 175 | -}); |
modified core/protocol/core.ts +13 −2
| @@ -29,7 +29,7 @@ | ||
| 29 | 29 | Session, |
| 30 | 30 | SessionMetadata, |
| 31 | 31 | SiteIndexingConfig, |
| 32 | - SlashCommandDescription, | |
| 32 | + SlashCommandDescWithSource, | |
| 33 | 33 | StreamDiffLinesPayload, |
| 34 | 34 | ToolCall, |
| 35 | 35 | } from "../"; |
| @@ -118,6 +118,17 @@ | ||
| 118 | 118 | }, |
| 119 | 119 | void, |
| 120 | 120 | ]; |
| 121 | + "mcp/getPrompt": [ | |
| 122 | + { | |
| 123 | + serverName: string; | |
| 124 | + promptName: string; | |
| 125 | + args?: Record<string, string>; | |
| 126 | + }, | |
| 127 | + { | |
| 128 | + prompt: string; | |
| 129 | + description: string | undefined; | |
| 130 | + }, | |
| 131 | + ]; | |
| 121 | 132 | "context/getSymbolsForFiles": [{ uris: string[] }, FileSymbolMap]; |
| 122 | 133 | "context/loadSubmenuItems": [{ title: string }, ContextSubmenuItem[]]; |
| 123 | 134 | "autocomplete/complete": [AutocompleteInput, string[]]; |
| @@ -141,7 +152,7 @@ | ||
| 141 | 152 | completionOptions: LLMFullCompletionOptions; |
| 142 | 153 | title: string; |
| 143 | 154 | legacySlashCommandData?: { |
| 144 | - command: SlashCommandDescription; | |
| 155 | + command: SlashCommandDescWithSource; | |
| 145 | 156 | input: string; |
| 146 | 157 | contextItems: ContextItemWithId[]; |
| 147 | 158 | historyIndex: number; |
modified core/protocol/ide.ts +1 −0
| @@ -70,6 +70,7 @@ | ||
| 70 | 70 | ]; |
| 71 | 71 | getAvailableThreads: [undefined, Thread[]]; |
| 72 | 72 | isTelemetryEnabled: [undefined, boolean]; |
| 73 | + isWorkspaceRemote: [undefined, boolean]; | |
| 73 | 74 | getUniqueId: [undefined, string]; |
| 74 | 75 | getTags: [string, IndexTag[]]; |
| 75 | 76 | readSecrets: [{ keys: string[] }, Record<string, string>]; |
modified core/protocol/messenger/messageIde.ts +4 −0
| @@ -106,6 +106,10 @@ | ||
| 106 | 106 | return this.request("isTelemetryEnabled", undefined); |
| 107 | 107 | } |
| 108 | 108 | |
| 109 | + isWorkspaceRemote(): Promise<boolean> { | |
| 110 | + return this.request("isWorkspaceRemote", undefined); | |
| 111 | + } | |
| 112 | + | |
| 109 | 113 | getUniqueId(): Promise<string> { |
| 110 | 114 | return this.request("getUniqueId", undefined); |
| 111 | 115 | } |
modified core/protocol/passThrough.ts +1 −0
| @@ -27,6 +27,7 @@ | ||
| 27 | 27 | "config/updateSharedConfig", |
| 28 | 28 | "config/updateSelectedModel", |
| 29 | 29 | "mcp/reloadServer", |
| 30 | + "mcp/getPrompt", | |
| 30 | 31 | "context/getContextItems", |
| 31 | 32 | "context/getSymbolsForFiles", |
| 32 | 33 | "context/loadSubmenuItems", |
added core/rules.md +10 −0
| @@ -0,0 +1,10 @@ | ||
| 1 | +# `core` rules | |
| 2 | + | |
| 3 | +Whenever a new protocol message is added to the `protocol/` directory, check the following: | |
| 4 | + | |
| 5 | +- It's type is defined correctly | |
| 6 | +- If it is a message from webview to core or vice versa: | |
| 7 | + - It has been added to `core/protocol/passThrough.ts` | |
| 8 | + - It has been added to `extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt` | |
| 9 | +- It is implemented in either `core/core.ts` (for messages to the core), in a `useWebviewListener` (for messages to the gui), or in `VsCodeMessenger.ts` for VS Code or `IdeProtocolClient.kt` for JetBriains (for messages to the IDE). | |
| 10 | +- It does not duplicate functionality from another message type that already exists. |
modified core/tools/index.ts +9 −2
| @@ -1,4 +1,4 @@ | ||
| 1 | -import { ConfigDependentToolParams, Tool } from ".."; | |
| 1 | +import { ConfigDependentToolParams, IDE, Tool } from ".."; | |
| 2 | 2 | import { createNewFileTool } from "./definitions/createNewFile"; |
| 3 | 3 | import { createRuleBlock } from "./definitions/createRuleBlock"; |
| 4 | 4 | import { editFileTool } from "./definitions/editFile"; |
| @@ -13,12 +13,14 @@ | ||
| 13 | 13 | import { searchWebTool } from "./definitions/searchWeb"; |
| 14 | 14 | import { viewDiffTool } from "./definitions/viewDiff"; |
| 15 | 15 | |
| 16 | +// missing support for remote os calls: https://github.com/microsoft/vscode/issues/252269 | |
| 17 | +export const localOnlyToolDefinitions = [grepSearchTool]; | |
| 18 | + | |
| 16 | 19 | export const baseToolDefinitions = [ |
| 17 | 20 | readFileTool, |
| 18 | 21 | editFileTool, |
| 19 | 22 | createNewFileTool, |
| 20 | 23 | runTerminalCommandTool, |
| 21 | - grepSearchTool, | |
| 22 | 24 | globSearchTool, |
| 23 | 25 | searchWebTool, |
| 24 | 26 | viewDiffTool, |
| @@ -34,3 +36,8 @@ | ||
| 34 | 36 | export const getConfigDependentToolDefinitions = ( |
| 35 | 37 | params: ConfigDependentToolParams, |
| 36 | 38 | ): Tool[] => [requestRuleTool(params)]; |
| 39 | + | |
| 40 | +export const getToolsForIde = async (ide: IDE) => | |
| 41 | + (await ide.isWorkspaceRemote()) | |
| 42 | + ? baseToolDefinitions | |
| 43 | + : [...baseToolDefinitions, ...localOnlyToolDefinitions]; |
modified core/tools/parseArgs.ts +1 −1
| @@ -4,7 +4,7 @@ | ||
| 4 | 4 | toolCall: ToolCallDelta, |
| 5 | 5 | ): Record<string, any> { |
| 6 | 6 | try { |
| 7 | - return JSON.parse(toolCall.function?.arguments ?? "{}"); | |
| 7 | + return JSON.parse(toolCall.function?.arguments?.trim() || "{}"); | |
| 8 | 8 | } catch (e) { |
| 9 | 9 | console.error( |
| 10 | 10 | `Failed to parse tool call arguments:\nTool call: ${toolCall.function?.name + " " + toolCall.id}\nArgs:${toolCall.function?.arguments}\n`, |
modified core/util/filesystem.ts +4 −0
| @@ -48,6 +48,10 @@ | ||
| 48 | 48 | return; |
| 49 | 49 | } |
| 50 | 50 | |
| 51 | + isWorkspaceRemote(): Promise<boolean> { | |
| 52 | + return Promise.resolve(false); | |
| 53 | + } | |
| 54 | + | |
| 51 | 55 | async getIdeSettings(): Promise<IdeSettings> { |
| 52 | 56 | return { |
| 53 | 57 | remoteConfigServerUrl: undefined, |
added core/util/handlebars/handlebarUtils.ts +111 −0
| @@ -0,0 +1,111 @@ | ||
| 1 | +import { v4 as uuidv4 } from "uuid"; | |
| 2 | + | |
| 3 | +export type HandlebarsType = typeof import("handlebars"); | |
| 4 | + | |
| 5 | +function convertToLetter(num: number): string { | |
| 6 | + let result = ""; | |
| 7 | + while (num > 0) { | |
| 8 | + const remainder = (num - 1) % 26; | |
| 9 | + result = String.fromCharCode(97 + remainder) + result; | |
| 10 | + num = Math.floor((num - 1) / 26); | |
| 11 | + } | |
| 12 | + return result; | |
| 13 | +} | |
| 14 | + | |
| 15 | +export function registerHelpers( | |
| 16 | + handlebars: HandlebarsType, | |
| 17 | + helpers: Array<[string, Handlebars.HelperDelegate]>, | |
| 18 | +): { | |
| 19 | + [key: string]: Promise<string>; | |
| 20 | +} { | |
| 21 | + const promises: { [key: string]: Promise<string> } = {}; | |
| 22 | + | |
| 23 | + for (const [name, helper] of helpers) { | |
| 24 | + handlebars.registerHelper(name, (...args) => { | |
| 25 | + const id = uuidv4(); | |
| 26 | + promises[id] = helper(...args); | |
| 27 | + return `__${id}__`; | |
| 28 | + }); | |
| 29 | + } | |
| 30 | + | |
| 31 | + return promises; | |
| 32 | +} | |
| 33 | + | |
| 34 | +export async function prepareTemplatedFilepaths( | |
| 35 | + handlebars: HandlebarsType, | |
| 36 | + template: string, | |
| 37 | + inputData: Record<string, string>, | |
| 38 | + ctxProviderNames: string[], | |
| 39 | + readFile: (filepath: string) => Promise<string>, | |
| 40 | + getUriFromPath: (path: string) => Promise<string | undefined>, | |
| 41 | +) { | |
| 42 | + // First, replace filepaths with letters to avoid escaping issues | |
| 43 | + const ast = handlebars.parse(template); | |
| 44 | + | |
| 45 | + const filepathLetters: Map<string, string> = new Map(); | |
| 46 | + const requiredContextProviders: Set<string> = new Set(); | |
| 47 | + let withLetterKeys = template; | |
| 48 | + | |
| 49 | + let letterIndex = 1; | |
| 50 | + | |
| 51 | + for (const i in ast.body) { | |
| 52 | + const node = ast.body[i] as any; | |
| 53 | + | |
| 54 | + if (node.type === "MustacheStatement") { | |
| 55 | + const originalNodeVal = node.path.original; | |
| 56 | + if (originalNodeVal.toLowerCase() === "input") { | |
| 57 | + continue; | |
| 58 | + } | |
| 59 | + const isFilepath = !ctxProviderNames.includes(originalNodeVal); | |
| 60 | + | |
| 61 | + if (isFilepath) { | |
| 62 | + const letter = convertToLetter(letterIndex); | |
| 63 | + | |
| 64 | + filepathLetters.set(letter, originalNodeVal); | |
| 65 | + | |
| 66 | + withLetterKeys = withLetterKeys.replace( | |
| 67 | + new RegExp(`{{\\s*${originalNodeVal}\\s*}}`), | |
| 68 | + `{{${letter}}}`, | |
| 69 | + ); | |
| 70 | + | |
| 71 | + letterIndex++; | |
| 72 | + } else { | |
| 73 | + requiredContextProviders.add(originalNodeVal); | |
| 74 | + } | |
| 75 | + } | |
| 76 | + } | |
| 77 | + | |
| 78 | + // Then, resolve the filepaths to their actual content and add to template data | |
| 79 | + // Fallback to simple error string if file read fails | |
| 80 | + const templateData = { ...inputData }; | |
| 81 | + | |
| 82 | + for (const [letter, filepath] of filepathLetters.entries()) { | |
| 83 | + try { | |
| 84 | + const uri = await getUriFromPath(filepath); | |
| 85 | + if (uri) { | |
| 86 | + const fileContents = await readFile(uri); | |
| 87 | + templateData[letter] = fileContents; | |
| 88 | + } else { | |
| 89 | + throw new Error(`File not found: ${filepath}`); | |
| 90 | + } | |
| 91 | + } catch (e) { | |
| 92 | + console.error(`Error reading file in prompt file ${filepath}:`, e); | |
| 93 | + templateData[letter] = `[Error reading file "${filepath}"]`; | |
| 94 | + } | |
| 95 | + } | |
| 96 | + | |
| 97 | + return { withLetterKeys, templateData, requiredContextProviders }; | |
| 98 | +} | |
| 99 | + | |
| 100 | +export async function resolveHelperPromises( | |
| 101 | + renderedString: string, | |
| 102 | + promises: { [key: string]: Promise<string> }, | |
| 103 | +): Promise<string> { | |
| 104 | + await Promise.all(Object.values(promises)); | |
| 105 | + | |
| 106 | + for (const id in promises) { | |
| 107 | + renderedString = renderedString.replace(`__${id}__`, await promises[id]); | |
| 108 | + } | |
| 109 | + | |
| 110 | + return renderedString; | |
| 111 | +} |
added core/util/handlebars/renderTemplatedString.ts +35 −0
| @@ -0,0 +1,35 @@ | ||
| 1 | +import { | |
| 2 | + prepareTemplatedFilepaths, | |
| 3 | + registerHelpers, | |
| 4 | + resolveHelperPromises, | |
| 5 | + type HandlebarsType, | |
| 6 | +} from "./handlebarUtils"; | |
| 7 | + | |
| 8 | +export async function renderTemplatedString( | |
| 9 | + handlebars: HandlebarsType, | |
| 10 | + template: string, | |
| 11 | + inputData: Record<string, string>, | |
| 12 | + availableHelpers: Array<[string, Handlebars.HelperDelegate]>, | |
| 13 | + readFile: (filepath: string) => Promise<string>, | |
| 14 | + getUriFromPath: (path: string) => Promise<string | undefined>, | |
| 15 | +): Promise<string> { | |
| 16 | + const helperPromises = availableHelpers | |
| 17 | + ? registerHelpers(handlebars, availableHelpers) | |
| 18 | + : {}; | |
| 19 | + | |
| 20 | + const ctxProviderNames = availableHelpers?.map((h) => h[0]) ?? []; | |
| 21 | + | |
| 22 | + const { withLetterKeys, templateData } = await prepareTemplatedFilepaths( | |
| 23 | + handlebars, | |
| 24 | + template, | |
| 25 | + inputData, | |
| 26 | + ctxProviderNames, | |
| 27 | + readFile, | |
| 28 | + getUriFromPath, | |
| 29 | + ); | |
| 30 | + | |
| 31 | + const templateFn = handlebars.compile(withLetterKeys); | |
| 32 | + const renderedString = templateFn(templateData); | |
| 33 | + | |
| 34 | + return resolveHelperPromises(renderedString, helperPromises); | |
| 35 | +} |
modified core/util/uri.ts +2 −0
| @@ -188,6 +188,7 @@ | ||
| 188 | 188 | dirUriCandidates, |
| 189 | 189 | ); |
| 190 | 190 | const baseName = getUriPathBasename(uri); |
| 191 | + const extension = getFileExtensionFromBasename(baseName); | |
| 191 | 192 | const last2Parts = getLastNUriRelativePathParts(dirUriCandidates, uri, 2); |
| 192 | 193 | return { |
| 193 | 194 | uri, |
| @@ -195,5 +196,6 @@ | ||
| 195 | 196 | foundInDir, |
| 196 | 197 | last2Parts, |
| 197 | 198 | baseName, |
| 199 | + extension, | |
| 198 | 200 | }; |
| 199 | 201 | } |
modified docs/docs/customize/deep-dives/prompts.md +33 −72
| @@ -5,93 +5,54 @@ | ||
| 5 | 5 | Prompts are reusable instructions that can be referenced at any time during chat. They are especially useful as context for repetitive and/or complex tasks. |
| 6 | 6 | |
| 7 | 7 | :::info |
| 8 | -Visit the Hub to [explore prompts](https://hub.continue.dev/explore/prompts) or [create your own](https://hub.continue.dev/new?type=block&blockType=prompts) | |
| 8 | +Prompts were previously defined in a `.prompt` file format, but for consistency we now recommend using the same Markdown format as [rules](./rules.mdx) and adding `alwaysApply: false` to the frontmatter so that they are manually triggered. | |
| 9 | 9 | ::: |
| 10 | 10 | |
| 11 | -## Examples | |
| 12 | - | |
| 13 | -Below are some examples to get you started. | |
| 14 | - | |
| 15 | -### Security review | |
| 16 | - | |
| 17 | -```text title="Security best practices review" | |
| 18 | -@open - Review these files for the following security best practices: | |
| 19 | -- Does the architecture follow security-by-design principles? | |
| 20 | -- Are there potential security vulnerabilities in the system design? | |
| 21 | -- Is sensitive data handled appropriately throughout the lifecycle? | |
| 22 | -``` | |
| 23 | - | |
| 24 | -### Reference best practice guides | |
| 25 | - | |
| 26 | -```text title="Redux best practices review" | |
| 27 | -@https://redux.js.org/style-guide/ | |
| 28 | -@currentFile | |
| 11 | +### Quick Start | |
| 29 | 12 | |
| 30 | -Review this code for adherence to Redux best practices. | |
| 31 | -``` | |
| 13 | +Below is a quick example of setting up a prompt file: | |
| 32 | 14 | |
| 33 | -### Pull in commonly used files for tasks | |
| 15 | +1. Create a folder called `.continue/rules` at the top level of your workspace | |
| 16 | +2. Add a file called `review-prompt.md` to this folder. | |
| 17 | +3. Write the following contents to `review-prompt.md` and save. | |
| 34 | 18 | |
| 35 | -```text title="Generate a new TypeORM entity" | |
| 36 | -@src/db/dataSource.ts @src/db/entity/SampleEntity.ts | |
| 19 | +```md title="review-prompt.md" | |
| 20 | +--- | |
| 21 | +name: Redux best practices review | |
| 22 | +alwaysApply: false | |
| 23 | +--- | |
| 37 | 24 | |
| 38 | -Use these files to generate a new TypeORM entity based on the following requirements: | |
| 25 | +Review the currently open file for adherence to Redux best practices, as explained in their style guide at https://redux.js.org/style-guide/. | |
| 39 | 26 | ``` |
| 40 | 27 | |
| 41 | -## Including Context Providers in your prompts | |
| 42 | - | |
| 43 | -Many [context providers](../context-providers.mdx) can be referenced by typing "@" followed by the name of the context provider. The currently supported list is: | |
| 44 | - | |
| 45 | -- `@terminal` - The contents of the terminal | |
| 46 | -- `@currentFile` - The currently active file | |
| 47 | -- `@open` - All open files | |
| 48 | -- `@os` - Information about the operating system | |
| 49 | -- `@problems` - Problems reported by the language server in the active file | |
| 50 | -- `@repo-map` - A map of files in the repository | |
| 51 | -- `@tree` - A tree view of the repository structure | |
| 52 | - | |
| 53 | -Or you can directly type URLs and file paths: | |
| 54 | - | |
| 55 | -- `@https://github.com/continuedev/continue` - The contents of a URL | |
| 56 | -- `@src/index.ts` - The contents of a file (VS Code only) | |
| 28 | +Now to use this prompt, you can open Chat, type <kbd>/</kbd>, select the prompt, and type out any additional instructions you'd like to add. | |
| 57 | 29 | |
| 58 | -All references will be attached as context items, rather than injected directly inline. | |
| 30 | +## Further Examples | |
| 59 | 31 | |
| 60 | -## Local `.prompt` files | |
| 32 | +Below are more examples to get you started. You can also visit the Hub to [explore prompts](https://hub.continue.dev/explore/prompts) or [create your own](https://hub.continue.dev/new?type=block&blockType=prompts). | |
| 61 | 33 | |
| 62 | -In addition to Prompt blocks on the Hub, you can also define prompts in local `.prompt` files, located in the `.continue/prompts` folder at the top level of your workspace. This is useful for quick iteration on prompts to test them out before pushing up to the Hub. | |
| 63 | - | |
| 64 | -### Quick Start | |
| 65 | - | |
| 66 | -Below is a quick example of setting up a prompt file: | |
| 67 | - | |
| 68 | -1. Create a folder called `.continue/prompts` at the top level of your workspace | |
| 69 | -2. Add a file called `test.prompt` to this folder. | |
| 70 | -3. Write the following contents to `test.prompt` and save. | |
| 34 | +### Security review | |
| 71 | 35 | |
| 72 | -```.prompt | |
| 73 | -name: Current file prompt | |
| 74 | -description: A test prompt using the current file context provider | |
| 36 | +```md title="security-review.md" | |
| 37 | +--- | |
| 38 | +name: Security best practices review | |
| 39 | +alwaysApply: false | |
| 75 | 40 | --- |
| 76 | -@currentFile | |
| 77 | -``` | |
| 78 | - | |
| 79 | -Now to use this prompt, you can open Chat, type <kbd>/</kbd>, select the prompt, and add type out some additional text such as "Review the code for any issues". | |
| 80 | - | |
| 81 | -### Format | |
| 82 | - | |
| 83 | -The format is inspired by [HumanLoops's .prompt file](https://docs.humanloop.com/docs/prompt-file-format), with additional templating to reference files, URLs, and context providers. | |
| 84 | 41 | |
| 85 | -:::info | |
| 86 | -The current state of this format is experimental and subject to change | |
| 87 | -::: | |
| 42 | +Review the changes in the current git diff for these security best practices: | |
| 88 | 43 | |
| 89 | -### Preamble | |
| 44 | +- Does the architecture follow security-by-design principles? | |
| 45 | +- Are there potential security vulnerabilities in the system design? | |
| 46 | +- Is sensitive data handled appropriately throughout the lifecycle? | |
| 47 | +``` | |
| 90 | 48 | |
| 91 | -The "preamble" is everything above the `---` separator, and lets you specify model parameters. It uses YAML syntax and currently supports the following parameters: | |
| 49 | +### Pull in commonly used files for tasks | |
| 92 | 50 | |
| 93 | -- `name` - The display title | |
| 94 | -- `description` - The description you will see in the dropdown | |
| 95 | -- `version` - Can be either "1" (for legacy prompt files) or "2" (this is the default and does not need to be set) | |
| 51 | +```md title="typeorm-entity-generator.md" | |
| 52 | +--- | |
| 53 | +name: Generate a new TypeORM entity | |
| 54 | +alwaysApply: false | |
| 55 | +--- | |
| 96 | 56 | |
| 97 | -If you don't need any of these parameters, you can leave out the preamble and do not need to include the `---` separator. | |
| 57 | +Referencing `src/db/dataSource.ts` and `src/db/entity/SampleEntity.ts`, generate a new TypeORM entity based on the following requirements: | |
| 58 | +``` |
modified docs/docs/customize/deep-dives/rules.mdx +18 −8
| @@ -55,19 +55,26 @@ | ||
| 55 | 55 | |
| 56 | 56 | Rules can also be added to an Assistant on the Continue Hub. |
| 57 | 57 | |
| 58 | -Explore available rules [here](https://hub.continue.dev/explore/rules), or [create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub. These blocks are defined using the [`config.yaml` syntax](../../reference.md#rules) and can also be created locally. | |
| 58 | +Explore available rules [here](https://hub.continue.dev), or [create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub. | |
| 59 | 59 | |
| 60 | 60 | ### Syntax |
| 61 | 61 | |
| 62 | +:::info | |
| 63 | + | |
| 64 | +Rules were originally defined in YAML format (demonstrated below), but we introduced Markdown for easier editing. While both are still supported, we recommend Markdown. | |
| 65 | + | |
| 66 | +::: | |
| 67 | + | |
| 62 | 68 | Rules blocks can be simple text, written in YAML configuration files, or as Markdown (`.md`) files. They can have the following properties: |
| 63 | 69 | |
| 64 | 70 | - `name` (**required** for YAML): A display name/title for the rule |
| 65 | 71 | - `globs` (optional): When files are provided as context that match this glob pattern, the rule will be included. This can be either a single pattern (e.g., `"**/*.{ts,tsx}"`) or an array of patterns (e.g., `["src/**/*.ts", "tests/**/*.ts"]`). |
| 66 | 72 | - `regex` (optional): When files are provided as context and their content matches this regex pattern, the rule will be included. This can be either a single pattern (e.g., `"^import .* from '.*';$"`) or an array of patterns (e.g., `["^import .* from '.*';$", "^export .* from '.*';$"]`). |
| 67 | 73 | - `description` (optional): A description for the rule. Agents may read this description when `alwaysApply` is false to determine whether the rule should be pulled into context. |
| 68 | -- `alwaysApply`: true - Always include the rule, regardless of file context | |
| 69 | -- `alwaysApply`: false - Included if globs exist AND match file context, or the agent decides to pull the rule into context based on it's description | |
| 70 | -- `alwaysApply`: undefined - Default behavior: include if no globs exist OR globs exist and match | |
| 74 | +- `alwaysApply`: Determines whether the rule is always included. Behavior is described below: | |
| 75 | + - `true`: Always included, regardless of file context | |
| 76 | + - `false`: Included if globs exist AND match file context, or the agent decides to pull the rule into context based on it's description | |
| 77 | + - `undefined` (default behavior): Included if no globs exist OR globs exist and match | |
| 71 | 78 | |
| 72 | 79 | <Tabs groupId="rules-example"> |
| 73 | 80 | <TabItem value="md" label="Markdown"> |
| @@ -97,10 +104,13 @@ | ||
| 97 | 104 | |
| 98 | 105 | ```yaml title="doc-standards.yaml" |
| 99 | 106 | name: Documentation Standards |
| 100 | - globs: docs/**/*.{md,mdx} | |
| 101 | - alwaysApply: false | |
| 107 | + version: 1.0.0 | |
| 108 | + schema: v1 | |
| 109 | + | |
| 102 | 110 | rules: |
| 103 | 111 | - name: Documentation Standards |
| 112 | + globs: docs/**/*.{md,mdx} | |
| 113 | + alwaysApply: false | |
| 104 | 114 | rule: > |
| 105 | 115 | - Follow Docusaurus documentation standards |
| 106 | 116 | - Include YAML frontmatter with title, description, and keywords |
| @@ -164,7 +174,7 @@ | ||
| 164 | 174 | |
| 165 | 175 | Continue includes a simple default system message for [Chat](../../chat/how-to-use-it.md) and [Agent](../../agent/how-to-use-it.md) requests, to help the model provide reliable codeblock formats in its output. |
| 166 | 176 | |
| 167 | -This can be viewed in the rules section of the toolbar (see above), or visit the source code [here](https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts#L4) | |
| 177 | +This can be viewed in the rules section of the toolbar (see above), or in the source code [here](https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts#L4). | |
| 168 | 178 | |
| 169 | 179 | Advanced users can override this system message for a specific model if needed by using `chatOptions.baseSystemMessage`. See the [`config.yaml` reference](../../reference.md#models). |
| 170 | 180 | |
| @@ -172,7 +182,7 @@ | ||
| 172 | 182 | |
| 173 | 183 | :::warning |
| 174 | 184 | |
| 175 | -`.contninuerules` will be deprecated in a future release. Please use the `.continue/rules` folder instead. | |
| 185 | +`.continuerules` will be deprecated in a future release. Please use the `.continue/rules` folder instead. | |
| 176 | 186 | |
| 177 | 187 | ::: |
| 178 | 188 |
modified extensions/intellij/gradle.properties +1 −1
| @@ -3,7 +3,7 @@ | ||
| 3 | 3 | pluginName=continue-intellij-extension |
| 4 | 4 | pluginRepositoryUrl=https://github.com/continuedev/continue |
| 5 | 5 | # SemVer format -> https://semver.org |
| 6 | -pluginVersion=1.0.25 | |
| 6 | +pluginVersion=1.0.26 | |
| 7 | 7 | # Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html |
| 8 | 8 | pluginSinceBuild=223 |
| 9 | 9 | # IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension |
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt +2 −2
| @@ -2,9 +2,9 @@ | ||
| 2 | 2 | |
| 3 | 3 | import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings |
| 4 | 4 | import com.github.continuedev.continueintellijextension.services.ContinuePluginService |
| 5 | -import com.github.continuedev.continueintellijextension.utils.Desktop | |
| 6 | 5 | import com.google.gson.Gson |
| 7 | 6 | import com.intellij.credentialStore.Credentials |
| 7 | +import com.intellij.ide.BrowserUtil | |
| 8 | 8 | import com.intellij.ide.passwordSafe.PasswordSafe |
| 9 | 9 | import com.intellij.ide.util.PropertiesComponent |
| 10 | 10 | import com.intellij.openapi.application.ApplicationManager |
| @@ -165,7 +165,7 @@ | ||
| 165 | 165 | |
| 166 | 166 | // Still open the URL in the browser (keeping existing behavior) |
| 167 | 167 | if (authUrl != null) { |
| 168 | - Desktop.browse(java.net.URI(authUrl)) | |
| 168 | + BrowserUtil.open(authUrl!!) | |
| 169 | 169 | } |
| 170 | 170 | |
| 171 | 171 | return authUrl |
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt +1 −0
| @@ -92,6 +92,7 @@ | ||
| 92 | 92 | "config/updateSharedConfig", |
| 93 | 93 | "config/updateSelectedModel", |
| 94 | 94 | "mcp/reloadServer", |
| 95 | + "mcp/getPrompt", | |
| 95 | 96 | "context/getContextItems", |
| 96 | 97 | "context/getSymbolsForFiles", |
| 97 | 98 | "context/loadSubmenuItems", |
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +6 −1
| @@ -10,6 +10,7 @@ | ||
| 10 | 10 | import com.intellij.codeInsight.daemon.impl.HighlightInfo |
| 11 | 11 | import com.intellij.execution.configurations.GeneralCommandLine |
| 12 | 12 | import com.intellij.execution.util.ExecUtil |
| 13 | +import com.intellij.ide.BrowserUtil | |
| 13 | 14 | import com.intellij.ide.plugins.PluginManager |
| 14 | 15 | import com.intellij.ide.plugins.PluginManagerCore |
| 15 | 16 | import com.intellij.lang.annotation.HighlightSeverity |
| @@ -125,6 +126,10 @@ | ||
| 125 | 126 | return true |
| 126 | 127 | } |
| 127 | 128 | |
| 129 | + override suspend fun isWorkspaceRemote(): Boolean { | |
| 130 | + return this.getIdeInfo().remoteName != "local" | |
| 131 | + } | |
| 132 | + | |
| 128 | 133 | override suspend fun getUniqueId(): String { |
| 129 | 134 | return getMachineUniqueID() |
| 130 | 135 | } |
| @@ -211,7 +216,7 @@ | ||
| 211 | 216 | |
| 212 | 217 | override suspend fun openUrl(url: String) { |
| 213 | 218 | withContext(Dispatchers.IO) { |
| 214 | - Desktop.browse(URI(url)) | |
| 219 | + BrowserUtil.browse(url) | |
| 215 | 220 | } |
| 216 | 221 | } |
| 217 | 222 |
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt +2 −0
| @@ -102,6 +102,8 @@ | ||
| 102 | 102 | |
| 103 | 103 | suspend fun isTelemetryEnabled(): Boolean |
| 104 | 104 | |
| 105 | + suspend fun isWorkspaceRemote(): Boolean | |
| 106 | + | |
| 105 | 107 | suspend fun getUniqueId(): String |
| 106 | 108 | |
| 107 | 109 | suspend fun getTerminalContents(): String |
deleted extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/Desktop.kt +0 −214
| @@ -1,214 +0,0 @@ | ||
| 1 | -/* | |
| 2 | - * Copyright © 2017 jjYBdx4IL (https://github.com/jjYBdx4IL) | |
| 3 | - * | |
| 4 | - * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | - * you may not use this file except in compliance with the License. | |
| 6 | - * You may obtain a copy of the License at | |
| 7 | - * | |
| 8 | - * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | - * | |
| 10 | - * Unless required by applicable law or agreed to in writing, software | |
| 11 | - * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | - * See the License for the specific language governing permissions and | |
| 14 | - * limitations under the License. | |
| 15 | - */ | |
| 16 | -package com.github.continuedev.continueintellijextension.utils | |
| 17 | - | |
| 18 | -import org.apache.commons.lang3.SystemUtils | |
| 19 | -import org.slf4j.LoggerFactory | |
| 20 | -import java.io.File | |
| 21 | -import java.io.IOException | |
| 22 | -import java.net.URI | |
| 23 | - | |
| 24 | -object Desktop { | |
| 25 | - private val LOG = LoggerFactory.getLogger(Desktop::class.java) | |
| 26 | - | |
| 27 | - fun browse(uri: URI): Boolean { | |
| 28 | - if (browseDESKTOP(uri)) { | |
| 29 | - return true | |
| 30 | - } | |
| 31 | - | |
| 32 | - if (openSystemSpecific(uri.toString())) { | |
| 33 | - return true | |
| 34 | - } | |
| 35 | - | |
| 36 | - LOG.warn("failed to browse {}", uri) | |
| 37 | - return false | |
| 38 | - } | |
| 39 | - | |
| 40 | - fun open(file: File): Boolean { | |
| 41 | - if (openDESKTOP(file)) { | |
| 42 | - return true | |
| 43 | - } | |
| 44 | - | |
| 45 | - if (openSystemSpecific(file.path)) { | |
| 46 | - return true | |
| 47 | - } | |
| 48 | - | |
| 49 | - LOG.warn("failed to open {}", file.absolutePath) | |
| 50 | - return false | |
| 51 | - } | |
| 52 | - | |
| 53 | - fun edit(file: File): Boolean { | |
| 54 | - if (editDESKTOP(file)) { | |
| 55 | - return true | |
| 56 | - } | |
| 57 | - | |
| 58 | - if (openSystemSpecific(file.path)) { | |
| 59 | - return true | |
| 60 | - } | |
| 61 | - | |
| 62 | - LOG.warn("failed to edit {}", file.absolutePath) | |
| 63 | - return false | |
| 64 | - } | |
| 65 | - | |
| 66 | - private fun openSystemSpecific(what: String): Boolean { | |
| 67 | - if (SystemUtils.IS_OS_LINUX) { | |
| 68 | - if (isXDG() && runCommand("xdg-open", "%s", what)) { | |
| 69 | - return true | |
| 70 | - } | |
| 71 | - if (isKDE() && runCommand("kde-open", "%s", what)) { | |
| 72 | - return true | |
| 73 | - } | |
| 74 | - if (isGNOME() && runCommand("gnome-open", "%s", what)) { | |
| 75 | - return true | |
| 76 | - } | |
| 77 | - if (runCommand("kde-open", "%s", what)) { | |
| 78 | - return true | |
| 79 | - } | |
| 80 | - if (runCommand("gnome-open", "%s", what)) { | |
| 81 | - return true | |
| 82 | - } | |
| 83 | - } | |
| 84 | - | |
| 85 | - if (SystemUtils.IS_OS_MAC && runCommand("open", "%s", what)) { | |
| 86 | - return true | |
| 87 | - } | |
| 88 | - | |
| 89 | - if (SystemUtils.IS_OS_WINDOWS && runCommand("explorer", "%s", what)) { | |
| 90 | - return true | |
| 91 | - } | |
| 92 | - | |
| 93 | - return false | |
| 94 | - } | |
| 95 | - | |
| 96 | - private fun browseDESKTOP(uri: URI): Boolean { | |
| 97 | - return try { | |
| 98 | - if (!java.awt.Desktop.isDesktopSupported()) { | |
| 99 | - LOG.debug("Platform is not supported.") | |
| 100 | - return false | |
| 101 | - } | |
| 102 | - | |
| 103 | - if (!java.awt.Desktop.getDesktop().isSupported(java.awt.Desktop.Action.BROWSE)) { | |
| 104 | - LOG.debug("BROWSE is not supported.") | |
| 105 | - return false | |
| 106 | - } | |
| 107 | - | |
| 108 | - LOG.info("Trying to use Desktop.getDesktop().browse() with {}", uri.toString()) | |
| 109 | - java.awt.Desktop.getDesktop().browse(uri) | |
| 110 | - true | |
| 111 | - } catch (t: Throwable) { | |
| 112 | - LOG.error("Error using desktop browse.", t) | |
| 113 | - false | |
| 114 | - } | |
| 115 | - } | |
| 116 | - | |
| 117 | - private fun openDESKTOP(file: File): Boolean { | |
| 118 | - return try { | |
| 119 | - if (!java.awt.Desktop.isDesktopSupported()) { | |
| 120 | - LOG.debug("Platform is not supported.") | |
| 121 | - return false | |
| 122 | - } | |
| 123 | - | |
| 124 | - if (!java.awt.Desktop.getDesktop().isSupported(java.awt.Desktop.Action.OPEN)) { | |
| 125 | - LOG.debug("OPEN is not supported.") | |
| 126 | - return false | |
| 127 | - } | |
| 128 | - | |
| 129 | - LOG.info("Trying to use Desktop.getDesktop().open() with {}", file.toString()) | |
| 130 | - java.awt.Desktop.getDesktop().open(file) | |
| 131 | - true | |
| 132 | - } catch (t: Throwable) { | |
| 133 | - LOG.error("Error using desktop open.", t) | |
| 134 | - false | |
| 135 | - } | |
| 136 | - } | |
| 137 | - | |
| 138 | - private fun editDESKTOP(file: File): Boolean { | |
| 139 | - return try { | |
| 140 | - if (!java.awt.Desktop.isDesktopSupported()) { | |
| 141 | - LOG.debug("Platform is not supported.") | |
| 142 | - return false | |
| 143 | - } | |
| 144 | - | |
| 145 | - if (!java.awt.Desktop.getDesktop().isSupported(java.awt.Desktop.Action.EDIT)) { | |
| 146 | - LOG.debug("EDIT is not supported.") | |
| 147 | - return false | |
| 148 | - } | |
| 149 | - | |
| 150 | - LOG.info("Trying to use Desktop.getDesktop().edit() with {}", file) | |
| 151 | - java.awt.Desktop.getDesktop().edit(file) | |
| 152 | - true | |
| 153 | - } catch (t: Throwable) { | |
| 154 | - LOG.error("Error using desktop edit.", t) | |
| 155 | - false | |
| 156 | - } | |
| 157 | - } | |
| 158 | - | |
| 159 | - private fun runCommand(command: String, args: String, file: String): Boolean { | |
| 160 | - LOG.info("Trying to exec:\n cmd = {}\n args = {}\n %s = {}", command, args, file) | |
| 161 | - | |
| 162 | - val parts = prepareCommand(command, args, file) | |
| 163 | - | |
| 164 | - return try { | |
| 165 | - val p = Runtime.getRuntime().exec(parts) | |
| 166 | - if (p == null) { | |
| 167 | - false | |
| 168 | - } else { | |
| 169 | - try { | |
| 170 | - val retval = p.exitValue() | |
| 171 | - if (retval == 0) { | |
| 172 | - LOG.error("Process ended immediately.") | |
| 173 | - false | |
| 174 | - } else { | |
| 175 | - LOG.error("Process crashed.") | |
| 176 | - false | |
| 177 | - } | |
| 178 | - } catch (itse: IllegalThreadStateException) { | |
| 179 | - LOG.error("Process is running.") | |
| 180 | - true | |
| 181 | - } | |
| 182 | - } | |
| 183 | - } catch (e: IOException) { | |
| 184 | - LOG.error("Error running command.", e) | |
| 185 | - false | |
| 186 | - } | |
| 187 | - } | |
| 188 | - | |
| 189 | - private fun prepareCommand(command: String, args: String?, file: String): Array<String> { | |
| 190 | - val parts = mutableListOf<String>() | |
| 191 | - parts.add(command) | |
| 192 | - | |
| 193 | - args?.split(" ")?.forEach { s -> | |
| 194 | - parts.add(String.format(s, file).trim()) | |
| 195 | - } | |
| 196 | - | |
| 197 | - return parts.toTypedArray() | |
| 198 | - } | |
| 199 | - | |
| 200 | - private fun isXDG(): Boolean { | |
| 201 | - val xdgSessionId = System.getenv("XDG_SESSION_ID") | |
| 202 | - return !xdgSessionId.isNullOrEmpty() | |
| 203 | - } | |
| 204 | - | |
| 205 | - private fun isGNOME(): Boolean { | |
| 206 | - val gdmSession = System.getenv("GDMSESSION") | |
| 207 | - return gdmSession?.lowercase()?.contains("gnome") == true | |
| 208 | - } | |
| 209 | - | |
| 210 | - private fun isKDE(): Boolean { | |
| 211 | - val gdmSession = System.getenv("GDMSESSION") | |
| 212 | - return gdmSession?.lowercase()?.contains("kde") == true | |
| 213 | - } | |
| 214 | -} | |
| No newline at the end of the file |
modified extensions/vscode/.gitignore +1 −0
| @@ -9,6 +9,7 @@ | ||
| 9 | 9 | exe |
| 10 | 10 | bin |
| 11 | 11 | assets |
| 12 | +tmp | |
| 12 | 13 | |
| 13 | 14 | gui/** |
| 14 | 15 |
modified extensions/vscode/.vscodeignore +0 −1
| @@ -18,7 +18,6 @@ | ||
| 18 | 18 | |
| 19 | 19 | manual-testing-sandbox |
| 20 | 20 | esbuild.js |
| 21 | -esbuild.test.mjs | |
| 22 | 21 | importMetaUrl.js |
| 23 | 22 | scripts |
| 24 | 23 | e2e |
deleted extensions/vscode/esbuild.test.mjs +0 −67
| @@ -1,67 +0,0 @@ | ||
| 1 | -import * as esbuild from "esbuild"; | |
| 2 | -import glob from "glob"; | |
| 3 | - | |
| 4 | -/** | |
| 5 | - * Bundles tests into multiple files, runTestOnVSCodeHost is then run using node runTestOnVSCodeHost.js | |
| 6 | - * It downloads vscode, starts it and passes test file to run - mochaRunner.js | |
| 7 | - * mochaRunner.js then runs tests using Mocha class | |
| 8 | - */ | |
| 9 | - | |
| 10 | -console.log("Bundling tests..."); | |
| 11 | - | |
| 12 | -// Bundles script to run tests on VSCode host + mocha runner that will be invoked from within VSCode host | |
| 13 | -await esbuild.build({ | |
| 14 | - entryPoints: [ | |
| 15 | - // Runs mocha runner on VSCode host using runTests from @vscode/test-electron | |
| 16 | - "src/test/runner/runTestOnVSCodeHost.ts", | |
| 17 | - | |
| 18 | - // Runs the bundled tests using Mocha class | |
| 19 | - "src/test/runner/mochaRunner.ts", | |
| 20 | - ], | |
| 21 | - bundle: true, | |
| 22 | - outdir: "out", | |
| 23 | - | |
| 24 | - external: [ | |
| 25 | - "vscode", | |
| 26 | - | |
| 27 | - // Its important to externalize mocha, otherwise mocha seems to be not initialized properly when running tests | |
| 28 | - // Example warning by esbuild when mocha is not externalized: | |
| 29 | - // [WARNING] "./reporters/parallel-buffered" should be marked as external for use with "require.resolve" [require-resolve-not-external] | |
| 30 | - "mocha", | |
| 31 | - ], | |
| 32 | - format: "cjs", | |
| 33 | - platform: "node", | |
| 34 | - sourcemap: true, | |
| 35 | - loader: { | |
| 36 | - // eslint-disable-next-line @typescript-eslint/naming-convention | |
| 37 | - ".node": "file", | |
| 38 | - }, | |
| 39 | -}); | |
| 40 | - | |
| 41 | -/** | |
| 42 | - * Note: Bundling is done to work around import issues, for example with fkill that does not provide cjs module. | |
| 43 | - * Rather than figuring out a combination of tsconfig.json that would work, I decided to bundle tests instead. | |
| 44 | - */ | |
| 45 | -await esbuild.build({ | |
| 46 | - // Tests can be added anywhere in src folder | |
| 47 | - entryPoints: glob.sync("src/**/*.test.ts"), | |
| 48 | - bundle: true, | |
| 49 | - outdir: "out", | |
| 50 | - external: [ | |
| 51 | - "vscode", | |
| 52 | - | |
| 53 | - // Its important to externalize mocha, otherwise mocha seems to be not initialized properly when running tests | |
| 54 | - "mocha", | |
| 55 | - ], | |
| 56 | - format: "cjs", | |
| 57 | - platform: "node", | |
| 58 | - sourcemap: true, | |
| 59 | - loader: { | |
| 60 | - // eslint-disable-next-line @typescript-eslint/naming-convention | |
| 61 | - ".node": "file", | |
| 62 | - }, | |
| 63 | - // To allow import.meta.path for transformers.js | |
| 64 | - // https://github.com/evanw/esbuild/issues/1492#issuecomment-893144483 | |
| 65 | - inject: ["./scripts/importMetaUrl.js"], | |
| 66 | - define: { "import.meta.url": "importMetaUrl" }, | |
| 67 | -}); |
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 +6 −11
| @@ -2,7 +2,7 @@ | ||
| 2 | 2 | "name": "continue", |
| 3 | 3 | "icon": "media/icon.png", |
| 4 | 4 | "author": "Continue Dev, Inc", |
| 5 | - "version": "1.1.51", | |
| 5 | + "version": "1.1.52", | |
| 6 | 6 | "repository": { |
| 7 | 7 | "type": "git", |
| 8 | 8 | "url": "https://github.com/continuedev/continue" |
| @@ -622,10 +622,8 @@ | ||
| 622 | 622 | "rebuild": "electron-rebuild -v 19.1.8 node-pty", |
| 623 | 623 | "lint": "eslint src --ext ts", |
| 624 | 624 | "lint:fix": "eslint . --ext ts --fix", |
| 625 | - "build-test": "npm run esbuild && node esbuild.test.mjs", | |
| 626 | - "test": "npm run build-test && node ./out/runTestOnVSCodeHost.js", | |
| 625 | + "test": "vitest run", | |
| 627 | 626 | "vitest": "vitest run", |
| 628 | - "quick-test": "npm run build-test && node ./out/runTestOnVSCodeHost.js", | |
| 629 | 627 | "write-build-timestamp": "node scripts/write-build-timestamp.js", |
| 630 | 628 | "prepackage": "node scripts/prepackage.js", |
| 631 | 629 | "package": "node scripts/package.js", |
| @@ -661,11 +659,12 @@ | ||
| 661 | 659 | "@types/cors": "^2.8.17", |
| 662 | 660 | "@types/express": "^4.17.21", |
| 663 | 661 | "@types/follow-redirects": "^1.14.4", |
| 664 | - "@types/glob": "^8.0.0", | |
| 665 | - "@types/mocha": "^10.0.6", | |
| 662 | + "@types/mocha": "^10.0.10", | |
| 666 | 663 | "@types/node": "16.x", |
| 664 | + "@types/node-fetch": "^2.6.12", | |
| 667 | 665 | "@types/react-dom": "^18.2.4", |
| 668 | 666 | "@types/request": "^2.48.8", |
| 667 | + "@types/uuid": "^10.0.0", | |
| 669 | 668 | "@types/vscode": "1.70", |
| 670 | 669 | "@types/ws": "^8.5.4", |
| 671 | 670 | "@typescript-eslint/eslint-plugin": "^5.45.0", |
| @@ -675,9 +674,7 @@ | ||
| 675 | 674 | "esbuild": "0.17.19", |
| 676 | 675 | "esbuild-visualizer": "^0.6.0", |
| 677 | 676 | "eslint": "^8.28.0", |
| 678 | - "glob": "^8.0.3", | |
| 679 | 677 | "json-schema-to-typescript": "^12.0.0", |
| 680 | - "mocha": "^10.4.0", | |
| 681 | 678 | "ovsx": "^0.8.3", |
| 682 | 679 | "rimraf": "^5.0.5", |
| 683 | 680 | "typescript": "^5.6.3", |
| @@ -689,10 +686,7 @@ | ||
| 689 | 686 | "@continuedev/fetch": "^1.0.10", |
| 690 | 687 | "@electron/rebuild": "^3.2.10", |
| 691 | 688 | "@reduxjs/toolkit": "^1.9.3", |
| 692 | - "@types/node-fetch": "^2.6.11", | |
| 693 | - "@types/uuid": "^9.0.8", | |
| 694 | 689 | "@vscode/ripgrep": "^1.15.9", |
| 695 | - "@vscode/test-electron": "^2.3.9", | |
| 696 | 690 | "axios": "^1.2.5", |
| 697 | 691 | "core": "file:../../core", |
| 698 | 692 | "cors": "^2.8.5", |
| @@ -714,6 +708,7 @@ | ||
| 714 | 708 | "jsdom": "^24.0.0", |
| 715 | 709 | "lru-cache": "^11.0.2", |
| 716 | 710 | "minisearch": "^7.0.0", |
| 711 | + "mocha": "^11.7.1", | |
| 717 | 712 | "monaco-editor": "^0.45.0", |
| 718 | 713 | "monaco-vscode-textmate-theme-converter": "^0.1.7", |
| 719 | 714 | "ncp": "^2.0.0", |
added extensions/vscode/scripts/download-copy-sqlite-esbuild.js +191 −0
| @@ -0,0 +1,191 @@ | ||
| 1 | +const { fork } = require("child_process"); | |
| 2 | +const fs = require("fs"); | |
| 3 | +const https = require("https"); | |
| 4 | +const path = require("path"); | |
| 5 | + | |
| 6 | +const { rimrafSync } = require("rimraf"); | |
| 7 | + | |
| 8 | +const { execCmdSync } = require("../../../scripts/util"); | |
| 9 | + | |
| 10 | +/** | |
| 11 | + * download a file using nodejs http | |
| 12 | + * @param {string} url | |
| 13 | + * @param {string} outputPath | |
| 14 | + * @param {number} maxRedirects | |
| 15 | + */ | |
| 16 | +async function downloadFile(url, outputPath, maxRedirects = 5) { | |
| 17 | + return new Promise((resolve, reject) => { | |
| 18 | + const downloadWithRedirects = (currentUrl, redirectCount = 0) => { | |
| 19 | + if (redirectCount > maxRedirects) { | |
| 20 | + return reject(new Error(`Too many redirects (${maxRedirects})`)); | |
| 21 | + } | |
| 22 | + | |
| 23 | + const request = https.get(currentUrl, (response) => { | |
| 24 | + if ( | |
| 25 | + response.statusCode >= 300 && | |
| 26 | + response.statusCode < 400 && | |
| 27 | + response.headers.location | |
| 28 | + ) { | |
| 29 | + return downloadWithRedirects( | |
| 30 | + response.headers.location, | |
| 31 | + redirectCount + 1, | |
| 32 | + ); | |
| 33 | + } | |
| 34 | + | |
| 35 | + if (response.statusCode !== 200) { | |
| 36 | + return reject( | |
| 37 | + new Error(`HTTP ${response.statusCode}: ${response.statusMessage}`), | |
| 38 | + ); | |
| 39 | + } | |
| 40 | + | |
| 41 | + const outputDir = path.dirname(outputPath); | |
| 42 | + if (!fs.existsSync(outputDir)) { | |
| 43 | + fs.mkdirSync(outputDir, { recursive: true }); | |
| 44 | + } | |
| 45 | + | |
| 46 | + const writeStream = fs.createWriteStream(outputPath); | |
| 47 | + | |
| 48 | + const totalSize = parseInt(response.headers["content-length"], 10); | |
| 49 | + let downloadedSize = 0; | |
| 50 | + | |
| 51 | + response.on("data", (chunk) => { | |
| 52 | + downloadedSize += chunk.length; | |
| 53 | + if (totalSize) { | |
| 54 | + const percent = ((downloadedSize / totalSize) * 100).toFixed(1); | |
| 55 | + process.stdout.write( | |
| 56 | + `\rDownloading: ${percent}% (${downloadedSize}/${totalSize} bytes)`, | |
| 57 | + ); | |
| 58 | + } | |
| 59 | + }); | |
| 60 | + | |
| 61 | + response.pipe(writeStream); | |
| 62 | + | |
| 63 | + writeStream.on("finish", () => { | |
| 64 | + console.log(`\nDownload completed: ${outputPath}`); | |
| 65 | + resolve(outputPath); | |
| 66 | + }); | |
| 67 | + | |
| 68 | + writeStream.on("error", reject); | |
| 69 | + response.on("error", reject); | |
| 70 | + }); | |
| 71 | + | |
| 72 | + request.on("error", reject); | |
| 73 | + request.setTimeout(30000, () => { | |
| 74 | + request.destroy(); | |
| 75 | + reject(new Error("Request timeout")); | |
| 76 | + }); | |
| 77 | + }; | |
| 78 | + | |
| 79 | + downloadWithRedirects(url); | |
| 80 | + }); | |
| 81 | +} | |
| 82 | + | |
| 83 | +/** | |
| 84 | + * | |
| 85 | + * @param {string} target platform specific target | |
| 86 | + * @param {string} targetDir the directory to download into | |
| 87 | + */ | |
| 88 | +async function downloadSqlite(target, targetDir) { | |
| 89 | + const downloadUrl = | |
| 90 | + // node-sqlite3 doesn't have a pre-built binary for win32-arm64 | |
| 91 | + target === "win32-arm64" | |
| 92 | + ? "https://continue-server-binaries.s3.us-west-1.amazonaws.com/win32-arm64/node_sqlite3.tar.gz" | |
| 93 | + : `https://github.com/TryGhost/node-sqlite3/releases/download/v5.1.7/sqlite3-v5.1.7-napi-v6-${ | |
| 94 | + target | |
| 95 | + }.tar.gz`; | |
| 96 | + await downloadFile(downloadUrl, targetDir); | |
| 97 | +} | |
| 98 | + | |
| 99 | +async function installAndCopySqlite(target) { | |
| 100 | + // Replace the installed with pre-built | |
| 101 | + console.log("[info] Downloading pre-built sqlite3 binary"); | |
| 102 | + rimrafSync("../../core/node_modules/sqlite3/build"); | |
| 103 | + await downloadSqlite(target, "../../core/node_modules/sqlite3/build.tar.gz"); | |
| 104 | + execCmdSync("cd ../../core/node_modules/sqlite3 && tar -xvzf build.tar.gz"); | |
| 105 | + fs.unlinkSync("../../core/node_modules/sqlite3/build.tar.gz"); | |
| 106 | +} | |
| 107 | + | |
| 108 | +async function installAndCopyEsbuild(target) { | |
| 109 | + // Download and unzip esbuild | |
| 110 | + console.log("[info] Downloading pre-built esbuild binary"); | |
| 111 | + rimrafSync("node_modules/@esbuild"); | |
| 112 | + fs.mkdirSync("node_modules/@esbuild", { recursive: true }); | |
| 113 | + await downloadFile( | |
| 114 | + `https://continue-server-binaries.s3.us-west-1.amazonaws.com/${target}/esbuild.zip`, | |
| 115 | + "node_modules/@esbuild/esbuild.zip", | |
| 116 | + ); | |
| 117 | + execCmdSync("cd node_modules/@esbuild && unzip esbuild.zip"); | |
| 118 | + fs.unlinkSync("node_modules/@esbuild/esbuild.zip"); | |
| 119 | +} | |
| 120 | + | |
| 121 | +process.on("message", (msg) => { | |
| 122 | + const { operation, target } = msg.payload; | |
| 123 | + if (operation === "sqlite") { | |
| 124 | + installAndCopySqlite(target) | |
| 125 | + .then(() => process.send({ done: true })) | |
| 126 | + .catch((error) => { | |
| 127 | + console.error(error); // show the error in the parent process | |
| 128 | + process.send({ error: true }); | |
| 129 | + }); | |
| 130 | + } | |
| 131 | + if (operation === "esbuild") { | |
| 132 | + installAndCopyEsbuild(target) | |
| 133 | + .then(() => process.send({ done: true })) | |
| 134 | + .catch((error) => { | |
| 135 | + console.error(error); // show the error in the parent process | |
| 136 | + process.send({ error: true }); | |
| 137 | + }); | |
| 138 | + } | |
| 139 | +}); | |
| 140 | + | |
| 141 | +/** | |
| 142 | + * @param {string} target the platform to build for | |
| 143 | + */ | |
| 144 | +async function copySqlite(target) { | |
| 145 | + const child = fork(__filename, { stdio: "inherit", cwd: process.cwd() }); | |
| 146 | + child.send({ | |
| 147 | + payload: { | |
| 148 | + operation: "sqlite", | |
| 149 | + target, | |
| 150 | + }, | |
| 151 | + }); | |
| 152 | + | |
| 153 | + return new Promise((resolve, reject) => { | |
| 154 | + child.on("message", (msg) => { | |
| 155 | + if (msg.error) { | |
| 156 | + reject(); | |
| 157 | + } else { | |
| 158 | + resolve(); | |
| 159 | + } | |
| 160 | + }); | |
| 161 | + }); | |
| 162 | +} | |
| 163 | + | |
| 164 | +/** | |
| 165 | + * @param {string} target the platform to build for | |
| 166 | + */ | |
| 167 | +async function copyEsbuild(target) { | |
| 168 | + const child = fork(__filename, { stdio: "inherit", cwd: process.cwd() }); | |
| 169 | + child.send({ | |
| 170 | + payload: { | |
| 171 | + operation: "esbuild", | |
| 172 | + target, | |
| 173 | + }, | |
| 174 | + }); | |
| 175 | + | |
| 176 | + return new Promise((resolve, reject) => { | |
| 177 | + child.on("message", (msg) => { | |
| 178 | + if (msg.error) { | |
| 179 | + reject(); | |
| 180 | + } else { | |
| 181 | + resolve(); | |
| 182 | + } | |
| 183 | + }); | |
| 184 | + }); | |
| 185 | +} | |
| 186 | + | |
| 187 | +module.exports = { | |
| 188 | + downloadSqlite, | |
| 189 | + copySqlite, | |
| 190 | + copyEsbuild, | |
| 191 | +}; |
modified extensions/vscode/scripts/esbuild.js +2 −1
| @@ -1,4 +1,5 @@ | ||
| 1 | 1 | const fs = require("fs"); |
| 2 | + | |
| 2 | 3 | const { writeBuildTimestamp } = require("./utils"); |
| 3 | 4 | |
| 4 | 5 | const esbuild = require("esbuild"); |
| @@ -49,7 +50,7 @@ | ||
| 49 | 50 | ], |
| 50 | 51 | }; |
| 51 | 52 | |
| 52 | -(async () => { | |
| 53 | +void (async () => { | |
| 53 | 54 | // Create .buildTimestamp.js before starting the first build |
| 54 | 55 | writeBuildTimestamp(); |
| 55 | 56 | // Bundles the extension into one file |
added extensions/vscode/scripts/generate-copy-config.js +126 −0
| @@ -0,0 +1,126 @@ | ||
| 1 | +/** | |
| 2 | + * @file Generate config.yaml file from template. Also intended to run as a child process. | |
| 3 | + */ | |
| 4 | + | |
| 5 | +const { fork } = require("child_process"); | |
| 6 | +const fs = require("fs"); | |
| 7 | +const path = require("path"); | |
| 8 | + | |
| 9 | +const { execCmdSync } = require("../../../scripts/util"); | |
| 10 | + | |
| 11 | +const { continueDir } = require("./utils"); | |
| 12 | + | |
| 13 | +async function generateConfigYamlSchema() { | |
| 14 | + process.chdir(path.join(continueDir, "packages", "config-yaml")); | |
| 15 | + execCmdSync("npm install"); | |
| 16 | + execCmdSync("npm run build"); | |
| 17 | + execCmdSync("npm run generate-schema"); | |
| 18 | + fs.copyFileSync( | |
| 19 | + path.join("schema", "config-yaml-schema.json"), | |
| 20 | + path.join(continueDir, "extensions", "vscode", "config-yaml-schema.json"), | |
| 21 | + ); | |
| 22 | + console.log("[info] Generated config.yaml schema"); | |
| 23 | +} | |
| 24 | + | |
| 25 | +async function copyConfigSchema() { | |
| 26 | + process.chdir(path.join(continueDir, "extensions", "vscode")); | |
| 27 | + // Modify and copy for .continuerc.json | |
| 28 | + const schema = JSON.parse(fs.readFileSync("config_schema.json", "utf8")); | |
| 29 | + schema.$defs.SerializedContinueConfig.properties.mergeBehavior = { | |
| 30 | + type: "string", | |
| 31 | + enum: ["merge", "overwrite"], | |
| 32 | + default: "merge", | |
| 33 | + title: "Merge behavior", | |
| 34 | + markdownDescription: | |
| 35 | + "If set to 'merge', .continuerc.json will be applied on top of config.json (arrays and objects are merged). If set to 'overwrite', then every top-level property of .continuerc.json will overwrite that property from config.json.", | |
| 36 | + "x-intellij-html-description": | |
| 37 | + "<p>If set to <code>merge</code>, <code>.continuerc.json</code> will be applied on top of <code>config.json</code> (arrays and objects are merged). If set to <code>overwrite</code>, then every top-level property of <code>.continuerc.json</code> will overwrite that property from <code>config.json</code>.</p>", | |
| 38 | + }; | |
| 39 | + fs.writeFileSync("continue_rc_schema.json", JSON.stringify(schema, null, 2)); | |
| 40 | + | |
| 41 | + // Copy config schemas to intellij | |
| 42 | + fs.copyFileSync( | |
| 43 | + "config_schema.json", | |
| 44 | + path.join( | |
| 45 | + "..", | |
| 46 | + "intellij", | |
| 47 | + "src", | |
| 48 | + "main", | |
| 49 | + "resources", | |
| 50 | + "config_schema.json", | |
| 51 | + ), | |
| 52 | + ); | |
| 53 | + fs.copyFileSync( | |
| 54 | + "continue_rc_schema.json", | |
| 55 | + path.join( | |
| 56 | + "..", | |
| 57 | + "intellij", | |
| 58 | + "src", | |
| 59 | + "main", | |
| 60 | + "resources", | |
| 61 | + "continue_rc_schema.json", | |
| 62 | + ), | |
| 63 | + ); | |
| 64 | +} | |
| 65 | + | |
| 66 | +process.on("message", (msg) => { | |
| 67 | + const { operation } = msg.payload; | |
| 68 | + if (operation === "generate") { | |
| 69 | + generateConfigYamlSchema() | |
| 70 | + .then(() => process.send({ done: true })) | |
| 71 | + .catch((error) => { | |
| 72 | + console.error(error); // show the error in the parent process | |
| 73 | + process.send({ error: true }); | |
| 74 | + }); | |
| 75 | + } | |
| 76 | + if (operation === "copy") { | |
| 77 | + copyConfigSchema() | |
| 78 | + .then(() => process.send({ done: true })) | |
| 79 | + .catch((error) => { | |
| 80 | + console.error(error); // show the error in the parent process | |
| 81 | + process.send({ error: true }); | |
| 82 | + }); | |
| 83 | + } | |
| 84 | +}); | |
| 85 | + | |
| 86 | +async function generateAndCopyConfigYamlSchema() { | |
| 87 | + // Generate and copy over config-yaml-schema.json | |
| 88 | + const generateConfigYamlChild = fork( | |
| 89 | + path.join(__dirname, "generate-copy-config.js"), | |
| 90 | + { | |
| 91 | + stdio: "inherit", | |
| 92 | + }, | |
| 93 | + ); | |
| 94 | + generateConfigYamlChild.send({ payload: { operation: "generate" } }); | |
| 95 | + | |
| 96 | + await new Promise((resolve, reject) => { | |
| 97 | + generateConfigYamlChild.on("message", (msg) => { | |
| 98 | + if (msg.error) { | |
| 99 | + reject(); | |
| 100 | + } | |
| 101 | + resolve(); | |
| 102 | + }); | |
| 103 | + }); | |
| 104 | + | |
| 105 | + // Copy config schemas to intellij | |
| 106 | + const copyConfigSchemaChild = fork( | |
| 107 | + path.join(__dirname, "generate-copy-config.js"), | |
| 108 | + { | |
| 109 | + stdio: "inherit", | |
| 110 | + }, | |
| 111 | + ); | |
| 112 | + copyConfigSchemaChild.send({ payload: { operation: "copy" } }); | |
| 113 | + | |
| 114 | + await new Promise((resolve, reject) => { | |
| 115 | + copyConfigSchemaChild.on("message", (msg) => { | |
| 116 | + if (msg.error) { | |
| 117 | + reject(); | |
| 118 | + } | |
| 119 | + resolve(); | |
| 120 | + }); | |
| 121 | + }); | |
| 122 | +} | |
| 123 | + | |
| 124 | +module.exports = { | |
| 125 | + generateAndCopyConfigYamlSchema, | |
| 126 | +}; |
added extensions/vscode/scripts/install-copy-nodemodule.js +113 −0
| @@ -0,0 +1,113 @@ | ||
| 1 | +/** | |
| 2 | + * @file Copy lancedb to the current directory. It is also intended to run as a child process. | |
| 3 | + */ | |
| 4 | + | |
| 5 | +const { fork } = require("child_process"); | |
| 6 | +const fs = require("fs"); | |
| 7 | +const path = require("path"); | |
| 8 | + | |
| 9 | +const ncp = require("ncp").ncp; | |
| 10 | + | |
| 11 | +const { execCmdSync } = require("../../../scripts/util"); | |
| 12 | + | |
| 13 | +async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) { | |
| 14 | + console.log(`Copying ${packageName} to ${toCopy}`); | |
| 15 | + // This is a way to install only one package without npm trying to install all the dependencies | |
| 16 | + // Create a temporary directory for installing the package | |
| 17 | + const adjustedName = packageName.replace(/@/g, "").replace("/", "-"); | |
| 18 | + const currentDir = process.cwd(); | |
| 19 | + const tempDir = path.join( | |
| 20 | + currentDir, | |
| 21 | + "tmp", | |
| 22 | + `continue-node_modules-${adjustedName}`, | |
| 23 | + ); | |
| 24 | + | |
| 25 | + // // Remove the dir we will be copying to | |
| 26 | + // rimrafSync(`node_modules/${toCopy}`); | |
| 27 | + | |
| 28 | + // // Ensure the temporary directory exists | |
| 29 | + fs.mkdirSync(tempDir, { recursive: true }); | |
| 30 | + | |
| 31 | + try { | |
| 32 | + // Move to the temporary directory | |
| 33 | + process.chdir(tempDir); | |
| 34 | + | |
| 35 | + // Initialize a new package.json and install the package | |
| 36 | + execCmdSync(`npm init -y && npm i -f ${packageName} --no-save`); | |
| 37 | + | |
| 38 | + console.log( | |
| 39 | + `Contents of: ${packageName}`, | |
| 40 | + fs.readdirSync(path.join(tempDir, "node_modules", toCopy)), | |
| 41 | + ); | |
| 42 | + | |
| 43 | + // Without this it seems the file isn't completely written to disk | |
| 44 | + await new Promise((resolve) => setTimeout(resolve, 2000)); | |
| 45 | + | |
| 46 | + // Copy the installed package back to the current directory | |
| 47 | + await new Promise((resolve, reject) => { | |
| 48 | + ncp( | |
| 49 | + path.join(tempDir, "node_modules", toCopy), | |
| 50 | + path.join(currentDir, "node_modules", toCopy), | |
| 51 | + { dereference: true }, | |
| 52 | + (error) => { | |
| 53 | + if (error) { | |
| 54 | + console.error( | |
| 55 | + `[error] Error copying ${packageName} package`, | |
| 56 | + error, | |
| 57 | + ); | |
| 58 | + reject(error); | |
| 59 | + } else { | |
| 60 | + resolve(); | |
| 61 | + } | |
| 62 | + }, | |
| 63 | + ); | |
| 64 | + }); | |
| 65 | + } finally { | |
| 66 | + // Clean up the temporary directory | |
| 67 | + // rimrafSync(tempDir); | |
| 68 | + | |
| 69 | + // Return to the original directory | |
| 70 | + process.chdir(currentDir); | |
| 71 | + } | |
| 72 | +} | |
| 73 | + | |
| 74 | +process.on("message", (msg) => { | |
| 75 | + installNodeModuleInTempDirAndCopyToCurrent( | |
| 76 | + msg.payload.packageName, | |
| 77 | + msg.payload.toCopy, | |
| 78 | + ) | |
| 79 | + .then(() => process.send({ done: true })) | |
| 80 | + .catch((error) => { | |
| 81 | + console.error(error); // show the error in the parent process | |
| 82 | + process.send({ error: true }); | |
| 83 | + }); | |
| 84 | +}); | |
| 85 | + | |
| 86 | +/** | |
| 87 | + * invoke a child process to install a node module into temporary directory and copy it over into node modules | |
| 88 | + * @param {string} packageName the module to install and copy | |
| 89 | + * @param {string} toCopy directory to copy into inside node modules | |
| 90 | + */ | |
| 91 | +async function installAndCopyNodeModules(packageName, toCopy) { | |
| 92 | + const child = fork(__filename, { stdio: "inherit", cwd: process.cwd() }); | |
| 93 | + child.send({ | |
| 94 | + payload: { | |
| 95 | + packageName, | |
| 96 | + toCopy, | |
| 97 | + }, | |
| 98 | + }); | |
| 99 | + | |
| 100 | + return new Promise((resolve, reject) => { | |
| 101 | + child.on("message", (msg) => { | |
| 102 | + if (msg.error) { | |
| 103 | + reject(); | |
| 104 | + } else { | |
| 105 | + resolve(); | |
| 106 | + } | |
| 107 | + }); | |
| 108 | + }); | |
| 109 | +} | |
| 110 | + | |
| 111 | +module.exports = { | |
| 112 | + installAndCopyNodeModules, | |
| 113 | +}; |
added extensions/vscode/scripts/npm-install.js +79 −0
| @@ -0,0 +1,79 @@ | ||
| 1 | +/** | |
| 2 | + * @file Install node modules for the VS Code extension and gui. This is also intended to run as a child process. | |
| 3 | + */ | |
| 4 | + | |
| 5 | +const { fork } = require("child_process"); | |
| 6 | +const path = require("path"); | |
| 7 | + | |
| 8 | +const { execCmdSync } = require("../../../scripts/util"); | |
| 9 | + | |
| 10 | +const { continueDir } = require("./utils"); | |
| 11 | + | |
| 12 | +async function installNodeModulesInGui() { | |
| 13 | + process.chdir(path.join(continueDir, "gui")); | |
| 14 | + execCmdSync("npm install"); | |
| 15 | + console.log("[info] npm install in gui completed"); | |
| 16 | +} | |
| 17 | + | |
| 18 | +async function installNodeModulesInVscode() { | |
| 19 | + process.chdir(path.join(continueDir, "extensions", "vscode")); | |
| 20 | + execCmdSync("npm install"); | |
| 21 | + console.log("[info] npm install in extensions/vscode completed"); | |
| 22 | +} | |
| 23 | + | |
| 24 | +process.on("message", (msg) => { | |
| 25 | + const { targetDir } = msg.payload; | |
| 26 | + if (targetDir === "gui") { | |
| 27 | + installNodeModulesInGui() | |
| 28 | + .then(() => process.send({ done: true })) | |
| 29 | + .catch((error) => { | |
| 30 | + console.error(error); // show the error in the parent process | |
| 31 | + process.send({ error: true }); | |
| 32 | + }); | |
| 33 | + } else if (targetDir === "vscode") { | |
| 34 | + installNodeModulesInVscode() | |
| 35 | + .then(() => process.send({ done: true })) | |
| 36 | + .catch((error) => { | |
| 37 | + console.error(error); // show the error in the parent process | |
| 38 | + process.send({ error: true }); | |
| 39 | + }); | |
| 40 | + } | |
| 41 | +}); | |
| 42 | + | |
| 43 | +async function npmInstall() { | |
| 44 | + const installVscodeChild = fork(__filename, { | |
| 45 | + stdio: "inherit", | |
| 46 | + }); | |
| 47 | + installVscodeChild.send({ payload: { targetDir: "vscode" } }); | |
| 48 | + | |
| 49 | + const installGuiChild = fork(__filename, { | |
| 50 | + stdio: "inherit", | |
| 51 | + }); | |
| 52 | + installGuiChild.send({ payload: { targetDir: "gui" } }); | |
| 53 | + | |
| 54 | + await Promise.all([ | |
| 55 | + new Promise((resolve, reject) => { | |
| 56 | + installVscodeChild.on("message", (msg) => { | |
| 57 | + if (msg.error) { | |
| 58 | + reject(); | |
| 59 | + } | |
| 60 | + resolve(); | |
| 61 | + }); | |
| 62 | + }), | |
| 63 | + new Promise((resolve, reject) => { | |
| 64 | + installGuiChild.on("message", (msg) => { | |
| 65 | + if (msg.error) { | |
| 66 | + reject(); | |
| 67 | + } | |
| 68 | + resolve(); | |
| 69 | + }); | |
| 70 | + }), | |
| 71 | + ]).catch((error) => { | |
| 72 | + console.error(error); | |
| 73 | + process.exit(1); | |
| 74 | + }); | |
| 75 | +} | |
| 76 | + | |
| 77 | +module.exports = { | |
| 78 | + npmInstall, | |
| 79 | +}; |
modified extensions/vscode/scripts/prepackage.js +37 −137
| @@ -10,11 +10,11 @@ | ||
| 10 | 10 | autodetectPlatformAndArch, |
| 11 | 11 | } = require("../../../scripts/util/index"); |
| 12 | 12 | |
| 13 | -const { | |
| 14 | - copyConfigSchema, | |
| 15 | - writeBuildTimestamp, | |
| 16 | - generateConfigYamlSchema, | |
| 17 | -} = require("./utils"); | |
| 13 | +const { copySqlite, copyEsbuild } = require("./download-copy-sqlite-esbuild"); | |
| 14 | +const { generateAndCopyConfigYamlSchema } = require("./generate-copy-config"); | |
| 15 | +const { installAndCopyNodeModules } = require("./install-copy-nodemodule"); | |
| 16 | +const { npmInstall } = require("./npm-install"); | |
| 17 | +const { writeBuildTimestamp, continueDir } = require("./utils"); | |
| 18 | 18 | |
| 19 | 19 | // Clear folders that will be packaged to ensure clean slate |
| 20 | 20 | rimrafSync(path.join(__dirname, "..", "bin")); |
| @@ -27,6 +27,8 @@ | ||
| 27 | 27 | fs.mkdirSync(guiDist, { recursive: true }); |
| 28 | 28 | } |
| 29 | 29 | |
| 30 | +const skipInstalls = process.env.SKIP_INSTALLS === "true"; | |
| 31 | + | |
| 30 | 32 | // Get the target to package for |
| 31 | 33 | let target = undefined; |
| 32 | 34 | const args = process.argv; |
| @@ -36,10 +38,10 @@ | ||
| 36 | 38 | |
| 37 | 39 | let os; |
| 38 | 40 | let arch; |
| 39 | -if (!target) { | |
| 40 | - [os, arch] = autodetectPlatformAndArch(); | |
| 41 | -} else { | |
| 41 | +if (target) { | |
| 42 | 42 | [os, arch] = target.split("-"); |
| 43 | +} else { | |
| 44 | + [os, arch] = autodetectPlatformAndArch(); | |
| 43 | 45 | } |
| 44 | 46 | |
| 45 | 47 | if (os === "alpine") { |
| @@ -67,28 +69,14 @@ | ||
| 67 | 69 | void (async () => { |
| 68 | 70 | console.log("[info] Packaging extension for target ", target); |
| 69 | 71 | |
| 70 | - // Generate and copy over config-yaml-schema.json | |
| 71 | - generateConfigYamlSchema(); | |
| 72 | - | |
| 73 | - // Copy config schemas to intellij | |
| 74 | - copyConfigSchema(); | |
| 75 | - | |
| 76 | - if (!process.cwd().endsWith("vscode")) { | |
| 77 | - // This is sometimes run from root dir instead (e.g. in VS Code tasks) | |
| 78 | - process.chdir("extensions/vscode"); | |
| 79 | - } | |
| 80 | - | |
| 81 | 72 | // Make sure we have an initial timestamp file |
| 82 | 73 | writeBuildTimestamp(); |
| 83 | 74 | |
| 84 | - // Install node_modules // | |
| 85 | - execCmdSync("npm install"); | |
| 86 | - console.log("[info] npm install in extensions/vscode completed"); | |
| 87 | - | |
| 88 | - process.chdir("../../gui"); | |
| 75 | + if (!skipInstalls) { | |
| 76 | + await Promise.all([generateAndCopyConfigYamlSchema(), npmInstall()]); | |
| 77 | + } | |
| 89 | 78 | |
| 90 | - execCmdSync("npm install"); | |
| 91 | - console.log("[info] npm install in gui completed"); | |
| 79 | + process.chdir(path.join(continueDir, "gui")); | |
| 92 | 80 | |
| 93 | 81 | if (isInGitHubAction) { |
| 94 | 82 | execCmdSync("npm run build"); |
| @@ -280,122 +268,32 @@ | ||
| 280 | 268 | ); |
| 281 | 269 | }); |
| 282 | 270 | |
| 283 | - async function installNodeModuleInTempDirAndCopyToCurrent( | |
| 284 | - packageName, | |
| 285 | - toCopy, | |
| 286 | - ) { | |
| 287 | - console.log(`Copying ${packageName} to ${toCopy}`); | |
| 288 | - // This is a way to install only one package without npm trying to install all the dependencies | |
| 289 | - // Create a temporary directory for installing the package | |
| 290 | - const adjustedName = packageName.replace(/@/g, "").replace("/", "-"); | |
| 291 | - | |
| 292 | - const tempDir = `/tmp/continue-node_modules-${adjustedName}`; | |
| 293 | - const currentDir = process.cwd(); | |
| 294 | - | |
| 295 | - // Remove the dir we will be copying to | |
| 296 | - rimrafSync(`node_modules/${toCopy}`); | |
| 297 | - | |
| 298 | - // Ensure the temporary directory exists | |
| 299 | - fs.mkdirSync(tempDir, { recursive: true }); | |
| 300 | - | |
| 301 | - try { | |
| 302 | - // Move to the temporary directory | |
| 303 | - process.chdir(tempDir); | |
| 304 | - | |
| 305 | - // Initialize a new package.json and install the package | |
| 306 | - execCmdSync(`npm init -y && npm i -f ${packageName} --no-save`); | |
| 307 | - | |
| 271 | + if (!skipInstalls) { | |
| 272 | + // GitHub Actions doesn't support ARM, so we need to download pre-saved binaries | |
| 273 | + // 02/07/25 - the above comment is out of date, there is now support for ARM runners on GitHub Actions | |
| 274 | + if (isArmTarget) { | |
| 275 | + // lancedb binary | |
| 276 | + const packageToInstall = { | |
| 277 | + "darwin-arm64": "@lancedb/vectordb-darwin-arm64", | |
| 278 | + "linux-arm64": "@lancedb/vectordb-linux-arm64-gnu", | |
| 279 | + "win32-arm64": "@lancedb/vectordb-win32-arm64-msvc", | |
| 280 | + }[target]; | |
| 308 | 281 | console.log( |
| 309 | - `Contents of: ${packageName}`, | |
| 310 | - fs.readdirSync(path.join(tempDir, "node_modules", toCopy)), | |
| 282 | + "[info] Downloading pre-built lancedb binary: " + packageToInstall, | |
| 311 | 283 | ); |
| 312 | 284 | |
| 313 | - // Without this it seems the file isn't completely written to disk | |
| 314 | - // Ideally we validate file integrity in the validation at the end | |
| 315 | - await new Promise((resolve) => setTimeout(resolve, 2000)); | |
| 316 | - | |
| 317 | - // Copy the installed package back to the current directory | |
| 318 | - await new Promise((resolve, reject) => { | |
| 319 | - ncp( | |
| 320 | - path.join(tempDir, "node_modules", toCopy), | |
| 321 | - path.join(currentDir, "node_modules", toCopy), | |
| 322 | - { dereference: true }, | |
| 323 | - (error) => { | |
| 324 | - if (error) { | |
| 325 | - console.error( | |
| 326 | - `[error] Error copying ${packageName} package`, | |
| 327 | - error, | |
| 328 | - ); | |
| 329 | - reject(error); | |
| 330 | - } else { | |
| 331 | - resolve(); | |
| 332 | - } | |
| 333 | - }, | |
| 334 | - ); | |
| 335 | - }); | |
| 336 | - } finally { | |
| 337 | - // Clean up the temporary directory | |
| 338 | - // rimrafSync(tempDir); | |
| 339 | - | |
| 340 | - // Return to the original directory | |
| 341 | - process.chdir(currentDir); | |
| 285 | + await Promise.all([ | |
| 286 | + copyEsbuild(target), | |
| 287 | + copySqlite(target), | |
| 288 | + installAndCopyNodeModules(packageToInstall, "@lancedb"), | |
| 289 | + ]); | |
| 290 | + } else { | |
| 291 | + // Download esbuild from npm in tmp and copy over | |
| 292 | + console.log("[info] npm installing esbuild binary"); | |
| 293 | + await installAndCopyNodeModules("esbuild@0.17.19", "@esbuild"); | |
| 342 | 294 | } |
| 343 | 295 | } |
| 344 | 296 | |
| 345 | - // GitHub Actions doesn't support ARM, so we need to download pre-saved binaries | |
| 346 | - // 02/07/25 - the above comment is out of date, there is now support for ARM runners on GitHub Actions | |
| 347 | - if (isArmTarget) { | |
| 348 | - // lancedb binary | |
| 349 | - const packageToInstall = { | |
| 350 | - "darwin-arm64": "@lancedb/vectordb-darwin-arm64", | |
| 351 | - "linux-arm64": "@lancedb/vectordb-linux-arm64-gnu", | |
| 352 | - "win32-arm64": "@lancedb/vectordb-win32-arm64-msvc", | |
| 353 | - }[target]; | |
| 354 | - console.log( | |
| 355 | - "[info] Downloading pre-built lancedb binary: " + packageToInstall, | |
| 356 | - ); | |
| 357 | - | |
| 358 | - await installNodeModuleInTempDirAndCopyToCurrent( | |
| 359 | - packageToInstall, | |
| 360 | - "@lancedb", | |
| 361 | - ); | |
| 362 | - | |
| 363 | - // Replace the installed with pre-built | |
| 364 | - console.log("[info] Downloading pre-built sqlite3 binary"); | |
| 365 | - rimrafSync("../../core/node_modules/sqlite3/build"); | |
| 366 | - const downloadUrl = { | |
| 367 | - "darwin-arm64": | |
| 368 | - "https://github.com/TryGhost/node-sqlite3/releases/download/v5.1.7/sqlite3-v5.1.7-napi-v6-darwin-arm64.tar.gz", | |
| 369 | - "linux-arm64": | |
| 370 | - "https://github.com/TryGhost/node-sqlite3/releases/download/v5.1.7/sqlite3-v5.1.7-napi-v3-linux-arm64.tar.gz", | |
| 371 | - // node-sqlite3 doesn't have a pre-built binary for win32-arm64 | |
| 372 | - "win32-arm64": | |
| 373 | - "https://continue-server-binaries.s3.us-west-1.amazonaws.com/win32-arm64/node_sqlite3.tar.gz", | |
| 374 | - }[target]; | |
| 375 | - execCmdSync( | |
| 376 | - `curl -L -o ../../core/node_modules/sqlite3/build.tar.gz ${downloadUrl}`, | |
| 377 | - ); | |
| 378 | - execCmdSync("cd ../../core/node_modules/sqlite3 && tar -xvzf build.tar.gz"); | |
| 379 | - fs.unlinkSync("../../core/node_modules/sqlite3/build.tar.gz"); | |
| 380 | - | |
| 381 | - // Download and unzip esbuild | |
| 382 | - console.log("[info] Downloading pre-built esbuild binary"); | |
| 383 | - rimrafSync("node_modules/@esbuild"); | |
| 384 | - fs.mkdirSync("node_modules/@esbuild", { recursive: true }); | |
| 385 | - execCmdSync( | |
| 386 | - `curl -o node_modules/@esbuild/esbuild.zip https://continue-server-binaries.s3.us-west-1.amazonaws.com/${target}/esbuild.zip`, | |
| 387 | - ); | |
| 388 | - execCmdSync(`cd node_modules/@esbuild && unzip esbuild.zip`); | |
| 389 | - fs.unlinkSync("node_modules/@esbuild/esbuild.zip"); | |
| 390 | - } else { | |
| 391 | - // Download esbuild from npm in tmp and copy over | |
| 392 | - console.log("npm installing esbuild binary"); | |
| 393 | - await installNodeModuleInTempDirAndCopyToCurrent( | |
| 394 | - "esbuild@0.17.19", | |
| 395 | - "@esbuild", | |
| 396 | - ); | |
| 397 | - } | |
| 398 | - | |
| 399 | 297 | console.log("[info] Copying sqlite node binding from core"); |
| 400 | 298 | await new Promise((resolve, reject) => { |
| 401 | 299 | ncp( |
| @@ -465,7 +363,7 @@ | ||
| 465 | 363 | ); |
| 466 | 364 | |
| 467 | 365 | // delete esbuild/bin because platform-specific @esbuild is downloaded |
| 468 | - fs.rmdirSync(`out/node_modules/esbuild/bin`, { recursive: true }); | |
| 366 | + fs.rmSync(`out/node_modules/esbuild/bin`, { recursive: true }); | |
| 469 | 367 | |
| 470 | 368 | console.log(`[info] Copied ${NODE_MODULES_TO_COPY.join(", ")}`); |
| 471 | 369 | |
| @@ -534,4 +432,6 @@ | ||
| 534 | 432 | `out/node_modules/@lancedb/vectordb-${target}${isWinTarget ? "-msvc" : ""}${isLinuxTarget ? "-gnu" : ""}/index.node`, |
| 535 | 433 | `out/node_modules/esbuild/lib/main.js`, |
| 536 | 434 | ]); |
| 435 | + | |
| 436 | + process.exit(0); | |
| 537 | 437 | })(); |
modified extensions/vscode/scripts/utils.js +6 −79
| @@ -1,67 +1,12 @@ | ||
| 1 | 1 | const fs = require("fs"); |
| 2 | -const ncp = require("ncp").ncp; | |
| 3 | 2 | const path = require("path"); |
| 4 | -const { rimrafSync } = require("rimraf"); | |
| 5 | -const { | |
| 6 | - validateFilesPresent, | |
| 7 | - execCmdSync, | |
| 8 | - autodetectPlatformAndArch, | |
| 9 | -} = require("../../../scripts/util/index"); | |
| 10 | 3 | |
| 11 | -const continueDir = path.join(__dirname, "..", "..", ".."); | |
| 4 | +const ncp = require("ncp").ncp; | |
| 5 | +const { rimrafSync } = require("rimraf"); | |
| 12 | 6 | |
| 13 | -function generateConfigYamlSchema() { | |
| 14 | - process.chdir(path.join(continueDir, "packages", "config-yaml")); | |
| 15 | - execCmdSync("npm install"); | |
| 16 | - execCmdSync("npm run build"); | |
| 17 | - execCmdSync("npm run generate-schema"); | |
| 18 | - fs.copyFileSync( | |
| 19 | - path.join("schema", "config-yaml-schema.json"), | |
| 20 | - path.join(continueDir, "extensions", "vscode", "config-yaml-schema.json"), | |
| 21 | - ); | |
| 22 | - console.log("[info] Generated config.yaml schema"); | |
| 23 | -} | |
| 7 | +const { execCmdSync } = require("../../../scripts/util/index"); | |
| 24 | 8 | |
| 25 | -function copyConfigSchema() { | |
| 26 | - process.chdir(path.join(continueDir, "extensions", "vscode")); | |
| 27 | - // Modify and copy for .continuerc.json | |
| 28 | - const schema = JSON.parse(fs.readFileSync("config_schema.json", "utf8")); | |
| 29 | - schema.$defs.SerializedContinueConfig.properties.mergeBehavior = { | |
| 30 | - type: "string", | |
| 31 | - enum: ["merge", "overwrite"], | |
| 32 | - default: "merge", | |
| 33 | - title: "Merge behavior", | |
| 34 | - markdownDescription: | |
| 35 | - "If set to 'merge', .continuerc.json will be applied on top of config.json (arrays and objects are merged). If set to 'overwrite', then every top-level property of .continuerc.json will overwrite that property from config.json.", | |
| 36 | - "x-intellij-html-description": | |
| 37 | - "<p>If set to <code>merge</code>, <code>.continuerc.json</code> will be applied on top of <code>config.json</code> (arrays and objects are merged). If set to <code>overwrite</code>, then every top-level property of <code>.continuerc.json</code> will overwrite that property from <code>config.json</code>.</p>", | |
| 38 | - }; | |
| 39 | - fs.writeFileSync("continue_rc_schema.json", JSON.stringify(schema, null, 2)); | |
| 40 | - | |
| 41 | - // Copy config schemas to intellij | |
| 42 | - fs.copyFileSync( | |
| 43 | - "config_schema.json", | |
| 44 | - path.join( | |
| 45 | - "..", | |
| 46 | - "intellij", | |
| 47 | - "src", | |
| 48 | - "main", | |
| 49 | - "resources", | |
| 50 | - "config_schema.json", | |
| 51 | - ), | |
| 52 | - ); | |
| 53 | - fs.copyFileSync( | |
| 54 | - "continue_rc_schema.json", | |
| 55 | - path.join( | |
| 56 | - "..", | |
| 57 | - "intellij", | |
| 58 | - "src", | |
| 59 | - "main", | |
| 60 | - "resources", | |
| 61 | - "continue_rc_schema.json", | |
| 62 | - ), | |
| 63 | - ); | |
| 64 | -} | |
| 9 | +const continueDir = path.join(__dirname, "..", "..", ".."); | |
| 65 | 10 | |
| 66 | 11 | function copyTokenizers() { |
| 67 | 12 | fs.copyFileSync( |
| @@ -77,22 +22,6 @@ | ||
| 77 | 22 | console.log("[info] Copied llamaTokenizer"); |
| 78 | 23 | } |
| 79 | 24 | |
| 80 | -function installNodeModules() { | |
| 81 | - // Make sure we are in the right directory | |
| 82 | - if (!process.cwd().endsWith("vscode")) { | |
| 83 | - process.chdir(path.join(continueDir, "extensions", "vscode")); | |
| 84 | - } | |
| 85 | - | |
| 86 | - // Install node_modules // | |
| 87 | - execCmdSync("npm install"); | |
| 88 | - console.log("[info] npm install in extensions/vscode completed"); | |
| 89 | - | |
| 90 | - process.chdir(path.join(continueDir, "gui")); | |
| 91 | - | |
| 92 | - execCmdSync("npm install"); | |
| 93 | - console.log("[info] npm install in gui completed"); | |
| 94 | -} | |
| 95 | - | |
| 96 | 25 | async function buildGui(isGhAction) { |
| 97 | 26 | // Make sure we are in the right directory |
| 98 | 27 | if (!process.cwd().endsWith("gui")) { |
| @@ -536,15 +465,13 @@ | ||
| 536 | 465 | // in the build |
| 537 | 466 | function writeBuildTimestamp() { |
| 538 | 467 | fs.writeFileSync( |
| 539 | - "src/.buildTimestamp.ts", | |
| 468 | + path.join(continueDir, "extensions/vscode", "src/.buildTimestamp.ts"), | |
| 540 | 469 | `export default "${new Date().toISOString()}";\n`, |
| 541 | 470 | ); |
| 542 | 471 | } |
| 543 | 472 | |
| 544 | 473 | module.exports = { |
| 545 | - generateConfigYamlSchema, | |
| 546 | - copyConfigSchema, | |
| 547 | - installNodeModules, | |
| 474 | + continueDir, | |
| 548 | 475 | buildGui, |
| 549 | 476 | copyOnnxRuntimeFromNodeModules, |
| 550 | 477 | copyTreeSitterWasms, |
modified extensions/vscode/src/VsCodeIde.ts +4 −0
| @@ -200,6 +200,10 @@ | ||
| 200 | 200 | return globalEnabled && continueEnabled; |
| 201 | 201 | } |
| 202 | 202 | |
| 203 | + isWorkspaceRemote(): Promise<boolean> { | |
| 204 | + return Promise.resolve(vscode.env.remoteName !== undefined); | |
| 205 | + } | |
| 206 | + | |
| 203 | 207 | getUniqueId(): Promise<string> { |
| 204 | 208 | return Promise.resolve(vscode.env.machineId); |
| 205 | 209 | } |
deleted extensions/vscode/src/test/runner/mochaRunner.ts +0 −49
| @@ -1,49 +0,0 @@ | ||
| 1 | -import * as path from "node:path"; | |
| 2 | - | |
| 3 | -import * as glob from "glob"; | |
| 4 | -import Mocha from "mocha"; | |
| 5 | - | |
| 6 | -export function run() { | |
| 7 | - // Avoid timing out when stopping on breakpoints during debugging in VSCode | |
| 8 | - const timeoutOption = process.env.MOCHA_TIMEOUT | |
| 9 | - ? Number.parseInt(process.env.MOCHA_TIMEOUT) | |
| 10 | - : // : undefined; | |
| 11 | - 30_000; | |
| 12 | - | |
| 13 | - // Create the mocha test | |
| 14 | - const mocha = new Mocha({ | |
| 15 | - ui: "tdd", | |
| 16 | - color: true, | |
| 17 | - timeout: timeoutOption, | |
| 18 | - }); | |
| 19 | - | |
| 20 | - // See esbuild.test.mjs for more details | |
| 21 | - // Assumes this file is in out/test/runner/mochaRunner.js | |
| 22 | - const compiledTestSuitesDirectory = path.resolve(__dirname); | |
| 23 | - | |
| 24 | - glob | |
| 25 | - .sync("**/**.test.js", { cwd: compiledTestSuitesDirectory }) | |
| 26 | - .forEach((file) => { | |
| 27 | - mocha.addFile(path.resolve(compiledTestSuitesDirectory, file)); | |
| 28 | - }); | |
| 29 | - | |
| 30 | - console.log( | |
| 31 | - `Testing files in ${compiledTestSuitesDirectory}: ${mocha.files}`, | |
| 32 | - ); | |
| 33 | - | |
| 34 | - return new Promise<void>((resolve, reject) => { | |
| 35 | - try { | |
| 36 | - // Run the mocha test | |
| 37 | - mocha.run((failures) => { | |
| 38 | - if (failures > 0) { | |
| 39 | - reject(new Error(`${failures} tests failed.`)); | |
| 40 | - } else { | |
| 41 | - resolve(); | |
| 42 | - } | |
| 43 | - }); | |
| 44 | - } catch (err) { | |
| 45 | - console.error(err); | |
| 46 | - reject(err); | |
| 47 | - } | |
| 48 | - }); | |
| 49 | -} |
deleted extensions/vscode/src/test/runner/runTestOnVSCodeHost.ts +0 −127
| @@ -1,127 +0,0 @@ | ||
| 1 | -import fs from "node:fs"; | |
| 2 | -import * as path from "node:path"; | |
| 3 | - | |
| 4 | -import { runTests } from "@vscode/test-electron"; | |
| 5 | -import { defaultConfig } from "core/config/default"; | |
| 6 | - | |
| 7 | -export const testWorkspacePath = path.resolve( | |
| 8 | - __dirname, | |
| 9 | - "..", | |
| 10 | - "src", | |
| 11 | - "test", | |
| 12 | - "fixtures", | |
| 13 | - "test-workspace", | |
| 14 | -); | |
| 15 | - | |
| 16 | -const continueGlobalDir = path.resolve( | |
| 17 | - __dirname, | |
| 18 | - "..", | |
| 19 | - "src", | |
| 20 | - "test", | |
| 21 | - "fixtures", | |
| 22 | - ".continue", | |
| 23 | -); | |
| 24 | - | |
| 25 | -function setupTestWorkspace() { | |
| 26 | - if (fs.existsSync(testWorkspacePath)) { | |
| 27 | - fs.rmSync(testWorkspacePath, { recursive: true }); | |
| 28 | - } | |
| 29 | - fs.mkdirSync(testWorkspacePath, { | |
| 30 | - recursive: true, | |
| 31 | - }); | |
| 32 | - | |
| 33 | - fs.writeFileSync( | |
| 34 | - path.join(testWorkspacePath, "test.py"), | |
| 35 | - "print('Hello World!')", | |
| 36 | - ); | |
| 37 | - fs.writeFileSync( | |
| 38 | - path.join(testWorkspacePath, "index.js"), | |
| 39 | - "console.log('Hello World!')", | |
| 40 | - ); | |
| 41 | - fs.writeFileSync( | |
| 42 | - path.join(testWorkspacePath, "test.py"), | |
| 43 | - "print('Hello World!')", | |
| 44 | - ); | |
| 45 | - fs.mkdirSync(path.join(testWorkspacePath, "test-folder")); | |
| 46 | - fs.writeFileSync( | |
| 47 | - path.join(testWorkspacePath, "test-folder", "test.js"), | |
| 48 | - "console.log('Hello World!')", | |
| 49 | - ); | |
| 50 | -} | |
| 51 | - | |
| 52 | -function setupContinueGlobalDir() { | |
| 53 | - if (fs.existsSync(continueGlobalDir)) { | |
| 54 | - fs.rmSync(continueGlobalDir, { recursive: true }); | |
| 55 | - } | |
| 56 | - fs.mkdirSync(continueGlobalDir, { | |
| 57 | - recursive: true, | |
| 58 | - }); | |
| 59 | - fs.writeFileSync( | |
| 60 | - path.join(continueGlobalDir, "config.json"), | |
| 61 | - JSON.stringify({ | |
| 62 | - ...defaultConfig, | |
| 63 | - models: [ | |
| 64 | - { | |
| 65 | - title: "Test Model", | |
| 66 | - provider: "openai", | |
| 67 | - model: "gpt-3.5-turbo", | |
| 68 | - apiKey: "API_KEY", | |
| 69 | - }, | |
| 70 | - ], | |
| 71 | - }), | |
| 72 | - ); | |
| 73 | -} | |
| 74 | - | |
| 75 | -function cleanupTestWorkspace() { | |
| 76 | - if (fs.existsSync(testWorkspacePath)) { | |
| 77 | - fs.rmSync(testWorkspacePath, { recursive: true }); | |
| 78 | - } | |
| 79 | -} | |
| 80 | - | |
| 81 | -function cleanupContinueGlobalDir() { | |
| 82 | - if (fs.existsSync(continueGlobalDir)) { | |
| 83 | - fs.rmSync(continueGlobalDir, { recursive: true }); | |
| 84 | - } | |
| 85 | -} | |
| 86 | - | |
| 87 | -async function main() { | |
| 88 | - try { | |
| 89 | - // The folder containing the Extension Manifest package.json | |
| 90 | - // Passed to `--extensionDevelopmentPath` | |
| 91 | - | |
| 92 | - // Assumes this file is in out/runTestOnVSCodeHost.js | |
| 93 | - const extensionDevelopmentPath = path.resolve(__dirname, "../"); | |
| 94 | - console.log("extensionDevelopmentPath", extensionDevelopmentPath); | |
| 95 | - | |
| 96 | - // The path to test runner | |
| 97 | - // Passed to --extensionTestsPath | |
| 98 | - const extensionTestsPath = path.resolve( | |
| 99 | - extensionDevelopmentPath, | |
| 100 | - "out/mochaRunner", | |
| 101 | - ); | |
| 102 | - | |
| 103 | - const extensionTestsEnv = { | |
| 104 | - NODE_ENV: "test", | |
| 105 | - CONTINUE_GLOBAL_DIR: continueGlobalDir, | |
| 106 | - }; | |
| 107 | - | |
| 108 | - setupTestWorkspace(); | |
| 109 | - setupContinueGlobalDir(); | |
| 110 | - | |
| 111 | - // Download VS Code, unzip it and run the integration test | |
| 112 | - await runTests({ | |
| 113 | - extensionDevelopmentPath, | |
| 114 | - extensionTestsPath, | |
| 115 | - extensionTestsEnv, | |
| 116 | - launchArgs: [testWorkspacePath], | |
| 117 | - }); | |
| 118 | - } catch (err) { | |
| 119 | - console.error("Failed to run tests", err); | |
| 120 | - process.exit(1); | |
| 121 | - } finally { | |
| 122 | - cleanupTestWorkspace(); | |
| 123 | - cleanupContinueGlobalDir(); | |
| 124 | - } | |
| 125 | -} | |
| 126 | - | |
| 127 | -main(); |
deleted extensions/vscode/src/test/test-suites/ideUtils.test.ts +0 −89
| @@ -1,89 +0,0 @@ | ||
| 1 | -import assert from "node:assert"; | |
| 2 | -import path from "node:path"; | |
| 3 | - | |
| 4 | -import { describe, test } from "mocha"; | |
| 5 | -import * as vscode from "vscode"; | |
| 6 | - | |
| 7 | -import { VsCodeIdeUtils } from "../../util/ideUtils"; | |
| 8 | -import { testWorkspacePath } from "../runner/runTestOnVSCodeHost"; | |
| 9 | - | |
| 10 | -const util = require("node:util"); | |
| 11 | -const asyncExec = util.promisify(require("node:child_process").exec); | |
| 12 | - | |
| 13 | -/* | |
| 14 | - TODO check uri => path assumptions, will only work in some environments. | |
| 15 | -*/ | |
| 16 | -describe("IDE Utils", () => { | |
| 17 | - const utils = new VsCodeIdeUtils(); | |
| 18 | - const testPyPath = path.join(testWorkspacePath, "test.py"); | |
| 19 | - const testJsPath = path.join(testWorkspacePath, "test-folder", "test.js"); | |
| 20 | - | |
| 21 | - test("getWorkspaceDirectories", async () => { | |
| 22 | - const [dir] = utils.getWorkspaceDirectories(); | |
| 23 | - assert(dir.toString().endsWith("test-workspace")); | |
| 24 | - }); | |
| 25 | - | |
| 26 | - test("fileExists", async () => { | |
| 27 | - const exists2 = await utils.fileExists( | |
| 28 | - vscode.Uri.file(path.join(testWorkspacePath, "test.py")), | |
| 29 | - ); | |
| 30 | - assert(exists2); | |
| 31 | - }); | |
| 32 | - | |
| 33 | - test("getOpenFiles", async () => { | |
| 34 | - let openFiles = utils.getOpenFiles(); | |
| 35 | - assert(openFiles.length === 0); | |
| 36 | - // await utils.openFile(testPyPath); | |
| 37 | - let document = await vscode.workspace.openTextDocument(testPyPath); | |
| 38 | - await vscode.window.showTextDocument(document, { | |
| 39 | - preview: false, | |
| 40 | - }); | |
| 41 | - openFiles = utils.getOpenFiles(); | |
| 42 | - assert(openFiles.length === 1); | |
| 43 | - assert(openFiles[0].fsPath === testPyPath); | |
| 44 | - | |
| 45 | - document = await vscode.workspace.openTextDocument(testJsPath); | |
| 46 | - await vscode.window.showTextDocument(document, { | |
| 47 | - preview: false, | |
| 48 | - }); | |
| 49 | - openFiles = utils.getOpenFiles(); | |
| 50 | - assert(openFiles.length === 2); | |
| 51 | - assert(openFiles.find((f) => f.fsPath === testPyPath)); | |
| 52 | - assert(openFiles.find((f) => f.fsPath === testJsPath)); | |
| 53 | - }); | |
| 54 | - | |
| 55 | - test("getUniqueId", async () => { | |
| 56 | - const uniqueId = utils.getUniqueId(); | |
| 57 | - assert(uniqueId.length === 64); | |
| 58 | - const regex = /^[a-z0-9]+$/; | |
| 59 | - assert(regex.test(uniqueId)); | |
| 60 | - }); | |
| 61 | - | |
| 62 | - test.skip("getTerminalContents", async () => { | |
| 63 | - await new Promise((resolve) => setTimeout(resolve, 1000)); | |
| 64 | - const terminal = vscode.window.createTerminal(); | |
| 65 | - await new Promise((resolve) => setTimeout(resolve, 1000)); | |
| 66 | - terminal.show(); | |
| 67 | - await new Promise((resolve) => setTimeout(resolve, 1000)); | |
| 68 | - terminal.sendText("echo abcdefg", true); | |
| 69 | - const contents = await utils.getTerminalContents(1); | |
| 70 | - console.log("TERMINAL CONTENTS: ", contents); | |
| 71 | - assert(contents.includes("abcdefg")); | |
| 72 | - terminal.dispose(); | |
| 73 | - }); | |
| 74 | - | |
| 75 | - test("noDiff", async () => { | |
| 76 | - const noDiff = await utils.getDiff(false); | |
| 77 | - assert(noDiff.length === 0); | |
| 78 | - }); | |
| 79 | - | |
| 80 | - test.skip("getBranch", async () => { | |
| 81 | - const uri = vscode.Uri.file(testWorkspacePath); | |
| 82 | - const branch = await utils.getBranch(uri); | |
| 83 | - assert(typeof branch === "string"); | |
| 84 | - const { stdout } = await asyncExec("git rev-parse --abbrev-ref HEAD", { | |
| 85 | - cwd: __dirname, | |
| 86 | - }); | |
| 87 | - assert(branch === stdout?.trim()); | |
| 88 | - }); | |
| 89 | -}); |
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/package.json +1 −0
| @@ -40,6 +40,7 @@ | ||
| 40 | 40 | "dompurify": "^3.0.6", |
| 41 | 41 | "downshift": "^7.6.0", |
| 42 | 42 | "escape-carriage": "^1.3.1", |
| 43 | + "handlebars": "^4.7.8", | |
| 43 | 44 | "lodash": "^4.17.21", |
| 44 | 45 | "lowlight": "^3.3.0", |
| 45 | 46 | "minisearch": "^7.0.2", |
modified gui/src/components/ConversationStarters/ConversationStarterCard.tsx +3 −3
| @@ -1,9 +1,9 @@ | ||
| 1 | 1 | import { ChatBubbleLeftIcon } from "@heroicons/react/24/outline"; |
| 2 | -import { SlashCommandDescription } from "core"; | |
| 2 | +import { SlashCommandDescWithSource } from "core"; | |
| 3 | 3 | |
| 4 | 4 | interface ConversationStarterCardProps { |
| 5 | - command: SlashCommandDescription; | |
| 6 | - onClick: (command: SlashCommandDescription) => void; | |
| 5 | + command: SlashCommandDescWithSource; | |
| 6 | + onClick: (command: SlashCommandDescWithSource) => void; | |
| 7 | 7 | } |
| 8 | 8 | |
| 9 | 9 | export function ConversationStarterCard({ |
modified gui/src/components/ConversationStarters/ConversationStarterCards.tsx +7 −3
| @@ -1,4 +1,4 @@ | ||
| 1 | -import { SlashCommandDescription } from "core"; | |
| 1 | +import { SlashCommandDescWithSource } from "core"; | |
| 2 | 2 | import { useState } from "react"; |
| 3 | 3 | import { useBookmarkedSlashCommands } from "../../hooks/useBookmarkedSlashCommands"; |
| 4 | 4 | import { useAppDispatch, useAppSelector } from "../../redux/hooks"; |
| @@ -23,8 +23,12 @@ | ||
| 23 | 23 | isCommandBookmarked(command.name), |
| 24 | 24 | ); |
| 25 | 25 | |
| 26 | - function onClick(command: SlashCommandDescription) { | |
| 27 | - mainEditor?.commands.insertPrompt(command); | |
| 26 | + function onClick(command: SlashCommandDescWithSource) { | |
| 27 | + mainEditor?.commands.insertPrompt({ | |
| 28 | + description: command.description, | |
| 29 | + title: command.name, | |
| 30 | + content: command.prompt, | |
| 31 | + }); | |
| 28 | 32 | } |
| 29 | 33 | |
| 30 | 34 | if (bookmarkedSlashCommands.length === 0) { |
modified gui/src/components/ConversationStarters/__tests__/utils.test.ts +10 −2
| @@ -1,27 +1,35 @@ | ||
| 1 | -import { SlashCommandDescription } from "core"; | |
| 1 | +import { SlashCommandDescWithSource } from "core"; | |
| 2 | 2 | import { sortCommandsByBookmarkStatus } from "../utils"; |
| 3 | 3 | |
| 4 | 4 | describe("sortCommandsByBookmarkStatus", () => { |
| 5 | - const mockCommands: SlashCommandDescription[] = [ | |
| 5 | + const mockCommands: SlashCommandDescWithSource[] = [ | |
| 6 | 6 | { |
| 7 | 7 | name: "command1", |
| 8 | 8 | description: "First command", |
| 9 | 9 | prompt: "This is command 1", |
| 10 | + source: "built-in", | |
| 11 | + isLegacy: false, | |
| 10 | 12 | }, |
| 11 | 13 | { |
| 12 | 14 | name: "command2", |
| 13 | 15 | description: "Second command", |
| 14 | 16 | prompt: "This is command 2", |
| 17 | + source: "built-in", | |
| 18 | + isLegacy: false, | |
| 15 | 19 | }, |
| 16 | 20 | { |
| 17 | 21 | name: "command3", |
| 18 | 22 | description: "Third command", |
| 19 | 23 | prompt: "This is command 3", |
| 24 | + source: "built-in", | |
| 25 | + isLegacy: false, | |
| 20 | 26 | }, |
| 21 | 27 | { |
| 22 | 28 | name: "command4", |
| 23 | 29 | description: "Fourth command", |
| 24 | 30 | prompt: "This is command 4", |
| 31 | + source: "built-in", | |
| 32 | + isLegacy: false, | |
| 25 | 33 | }, |
| 26 | 34 | ]; |
| 27 | 35 |
modified gui/src/components/ConversationStarters/utils.ts +3 −3
| @@ -1,4 +1,4 @@ | ||
| 1 | -import { SlashCommandDescription } from "core"; | |
| 1 | +import { SlashCommandDescWithSource } from "core"; | |
| 2 | 2 | import {} from "core/config/default"; |
| 3 | 3 | |
| 4 | 4 | /** |
| @@ -8,9 +8,9 @@ | ||
| 8 | 8 | * @returns A new sorted array with bookmarked commands first |
| 9 | 9 | */ |
| 10 | 10 | export function sortCommandsByBookmarkStatus( |
| 11 | - commands: SlashCommandDescription[], | |
| 11 | + commands: SlashCommandDescWithSource[], | |
| 12 | 12 | bookmarkedCommands: string[], |
| 13 | -): SlashCommandDescription[] { | |
| 13 | +): SlashCommandDescWithSource[] { | |
| 14 | 14 | return [...commands].sort((a, b) => { |
| 15 | 15 | const aIsBookmarked = bookmarkedCommands.includes(a.name); |
| 16 | 16 | const bIsBookmarked = bookmarkedCommands.includes(b.name); |
modified gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx +15 −13
| @@ -11,8 +11,10 @@ | ||
| 11 | 11 | import { useIdeMessengerRequest } from "../../../hooks/useIdeMessengerRequest"; |
| 12 | 12 | import { useWebviewListener } from "../../../hooks/useWebviewListener"; |
| 13 | 13 | import { useAppSelector } from "../../../redux/hooks"; |
| 14 | -import { selectCurrentToolCallApplyState } from "../../../redux/selectors/selectCurrentToolCall"; | |
| 15 | -import { selectApplyStateByStreamId } from "../../../redux/slices/sessionSlice"; | |
| 14 | +import { | |
| 15 | + selectApplyStateByStreamId, | |
| 16 | + selectApplyStateByToolCallId, | |
| 17 | +} from "../../../redux/slices/sessionSlice"; | |
| 16 | 18 | import { getFontSize } from "../../../util"; |
| 17 | 19 | import Spinner from "../../gui/Spinner"; |
| 18 | 20 | import { isTerminalCodeBlock } from "../utils"; |
| @@ -54,6 +56,7 @@ | ||
| 54 | 56 | codeBlockIndex: number; // To track which codeblock we are applying |
| 55 | 57 | isLastCodeblock: boolean; |
| 56 | 58 | codeBlockStreamId: string; |
| 59 | + forceToolCallId?: string; // If this is defined, we will use this streamId instead of the one from the codeBlock | |
| 57 | 60 | range?: string; |
| 58 | 61 | children: any; |
| 59 | 62 | expanded?: boolean; |
| @@ -68,6 +71,7 @@ | ||
| 68 | 71 | codeBlockIndex, |
| 69 | 72 | isLastCodeblock, |
| 70 | 73 | codeBlockStreamId, |
| 74 | + forceToolCallId, | |
| 71 | 75 | range, |
| 72 | 76 | children, |
| 73 | 77 | expanded, |
| @@ -99,8 +103,8 @@ | ||
| 99 | 103 | const applyState = useAppSelector((state) => |
| 100 | 104 | selectApplyStateByStreamId(state, codeBlockStreamId), |
| 101 | 105 | ); |
| 102 | - const currentToolCallApplyState = useAppSelector( | |
| 103 | - selectCurrentToolCallApplyState, | |
| 106 | + const toolCallApplyState = useAppSelector((state) => | |
| 107 | + selectApplyStateByToolCallId(state, forceToolCallId), | |
| 104 | 108 | ); |
| 105 | 109 | |
| 106 | 110 | /** |
| @@ -147,7 +151,7 @@ | ||
| 147 | 151 | setRelativeFilepathUri(resolvedUri); |
| 148 | 152 | } |
| 149 | 153 | }; |
| 150 | - getRelativeFilepathUri(); | |
| 154 | + void getRelativeFilepathUri(); | |
| 151 | 155 | }, [relativeFilepath, ideMessenger.ide]); |
| 152 | 156 | |
| 153 | 157 | async function getFileUriToApplyTo() { |
| @@ -173,7 +177,7 @@ | ||
| 173 | 177 | async function onClickApply() { |
| 174 | 178 | const fileUri = await getFileUriToApplyTo(); |
| 175 | 179 | if (!fileUri) { |
| 176 | - ideMessenger.ide.showToast( | |
| 180 | + void ideMessenger.ide.showToast( | |
| 177 | 181 | "error", |
| 178 | 182 | "Could not resolve filepath to apply changes", |
| 179 | 183 | ); |
| @@ -188,7 +192,7 @@ | ||
| 188 | 192 | }); |
| 189 | 193 | |
| 190 | 194 | setAppliedFileUri(fileUri); |
| 191 | - refreshFileExists(); | |
| 195 | + void refreshFileExists(); | |
| 192 | 196 | } |
| 193 | 197 | |
| 194 | 198 | function onClickInsertAtCursor() { |
| @@ -198,7 +202,7 @@ | ||
| 198 | 202 | async function handleDiffAction(action: "accept" | "reject") { |
| 199 | 203 | const filepath = await getFileUriToApplyTo(); |
| 200 | 204 | if (!filepath) { |
| 201 | - ideMessenger.ide.showToast( | |
| 205 | + void ideMessenger.ide.showToast( | |
| 202 | 206 | "error", |
| 203 | 207 | `Could not resolve filepath to ${action} changes`, |
| 204 | 208 | ); |
| @@ -233,10 +237,7 @@ | ||
| 233 | 237 | } |
| 234 | 238 | |
| 235 | 239 | const renderActionButtons = () => { |
| 236 | - const isPendingToolCall = | |
| 237 | - currentToolCallApplyState && | |
| 238 | - currentToolCallApplyState.streamId === applyState?.streamId && | |
| 239 | - currentToolCallApplyState.status === "not-started"; | |
| 240 | + const isPendingToolCall = toolCallApplyState?.status === "not-started"; | |
| 240 | 241 | |
| 241 | 242 | if (isGeneratingCodeBlock || isPendingToolCall) { |
| 242 | 243 | const numLines = codeBlockContent.split("\n").length; |
| @@ -271,7 +272,7 @@ | ||
| 271 | 272 | return ( |
| 272 | 273 | <ApplyActions |
| 273 | 274 | disableManualApply={disableManualApply} |
| 274 | - applyState={applyState} | |
| 275 | + applyState={toolCallApplyState ?? applyState} | |
| 275 | 276 | onClickApply={onClickApply} |
| 276 | 277 | onClickAccept={() => handleDiffAction("accept")} |
| 277 | 278 | onClickReject={() => handleDiffAction("reject")} |
| @@ -293,6 +294,7 @@ | ||
| 293 | 294 | <ToolbarDiv isExpanded={isExpanded} className="find-widget-skip gap-3"> |
| 294 | 295 | <div className="max-w-[50% flex flex-row items-center"> |
| 295 | 296 | <ChevronDownIcon |
| 297 | + data-testid="toggle-codeblock" | |
| 296 | 298 | onClick={() => setIsExpanded(!isExpanded)} |
| 297 | 299 | className={`text-lightgray h-3.5 w-3.5 flex-shrink-0 cursor-pointer hover:brightness-125 ${ |
| 298 | 300 | isExpanded ? "rotate-0" : "-rotate-90" |
modified gui/src/components/StyledMarkdownPreview/index.tsx +4 −9
| @@ -126,7 +126,7 @@ | ||
| 126 | 126 | itemIndex?: number; |
| 127 | 127 | useParentBackgroundColor?: boolean; |
| 128 | 128 | disableManualApply?: boolean; |
| 129 | - forceStreamId?: string; | |
| 129 | + toolCallId?: string; | |
| 130 | 130 | expandCodeblocks?: boolean; |
| 131 | 131 | } |
| 132 | 132 | |
| @@ -196,11 +196,6 @@ | ||
| 196 | 196 | const itemIndexRef = useUpdatingRef(props.itemIndex); |
| 197 | 197 | |
| 198 | 198 | const codeblockStreamIds = useRef<string[]>([]); |
| 199 | - useEffect(() => { | |
| 200 | - if (props.forceStreamId) { | |
| 201 | - codeblockStreamIds.current = [props.forceStreamId]; | |
| 202 | - } | |
| 203 | - }, [props.forceStreamId, codeblockStreamIds]); | |
| 204 | 199 | |
| 205 | 200 | const [reactContent, setMarkdownSource] = useRemark({ |
| 206 | 201 | remarkPlugins: [ |
| @@ -295,8 +290,7 @@ | ||
| 295 | 290 | const isLastCodeblock = preChildProps["data-islastcodeblock"]; |
| 296 | 291 | |
| 297 | 292 | if (codeblockStreamIds.current[codeBlockIndex] === undefined) { |
| 298 | - codeblockStreamIds.current[codeBlockIndex] = | |
| 299 | - props.forceStreamId ?? uuidv4(); | |
| 293 | + codeblockStreamIds.current[codeBlockIndex] = uuidv4(); | |
| 300 | 294 | } |
| 301 | 295 | |
| 302 | 296 | return ( |
| @@ -308,7 +302,8 @@ | ||
| 308 | 302 | relativeFilepath={relativeFilePath} |
| 309 | 303 | isLastCodeblock={isLastCodeblock} |
| 310 | 304 | range={range} |
| 311 | - codeBlockStreamId={codeblockStreamIds.current[codeBlockIndex]} | |
| 305 | + codeBlockStreamId={codeblockStreamIds.current[codeBlockIndex]} // ignored if toolCallId stream state is found | |
| 306 | + forceToolCallId={props.toolCallId} | |
| 312 | 307 | expanded={props.expandCodeblocks} |
| 313 | 308 | disableManualApply={props.disableManualApply} |
| 314 | 309 | > |
modified gui/src/components/console/ResultGroup.tsx +5 −1
| @@ -10,7 +10,11 @@ | ||
| 10 | 10 | return ( |
| 11 | 11 | <> |
| 12 | 12 | {group.map((result, i) => ( |
| 13 | - <Result key={i} result={result} prevResult={group[i - 1]}></Result> | |
| 13 | + <Result | |
| 14 | + key={`${result.timestamp}-${i}`} | |
| 15 | + result={result} | |
| 16 | + prevResult={group[i - 1]} | |
| 17 | + ></Result> | |
| 14 | 18 | ))} |
| 15 | 19 | </> |
| 16 | 20 | ); |
modified gui/src/components/mainInput/Lump/sections/PromptsSection.tsx +17 −10
| @@ -4,7 +4,7 @@ | ||
| 4 | 4 | PencilIcon, |
| 5 | 5 | } from "@heroicons/react/24/outline"; |
| 6 | 6 | import { BookmarkIcon as BookmarkSolid } from "@heroicons/react/24/solid"; |
| 7 | -import { SlashCommandDescription } from "core"; | |
| 7 | +import { SlashCommandDescWithSource } from "core"; | |
| 8 | 8 | import { useContext, useMemo } from "react"; |
| 9 | 9 | import { useAuth } from "../../../../context/Auth"; |
| 10 | 10 | import { IdeMessengerContext } from "../../../../context/IdeMessenger"; |
| @@ -15,10 +15,12 @@ | ||
| 15 | 15 | import { useLump } from "../LumpContext"; |
| 16 | 16 | import { ExploreBlocksButton } from "./ExploreBlocksButton"; |
| 17 | 17 | |
| 18 | -type PromptWithSlug = SlashCommandDescription & { slug?: string }; | |
| 18 | +interface PromptCommandWithSlug extends SlashCommandDescWithSource { | |
| 19 | + slug?: string; | |
| 20 | +} | |
| 19 | 21 | |
| 20 | 22 | interface PromptRowProps { |
| 21 | - prompt: PromptWithSlug; | |
| 23 | + prompt: PromptCommandWithSlug; | |
| 22 | 24 | isBookmarked: boolean; |
| 23 | 25 | setIsBookmarked: (isBookmarked: boolean) => void; |
| 24 | 26 | onEdit?: () => void; |
| @@ -38,7 +40,11 @@ | ||
| 38 | 40 | |
| 39 | 41 | const handlePromptClick = (e: React.MouseEvent) => { |
| 40 | 42 | e.stopPropagation(); |
| 41 | - mainEditor?.commands.insertPrompt(prompt); | |
| 43 | + mainEditor?.commands.insertPrompt({ | |
| 44 | + title: prompt.name, | |
| 45 | + description: prompt.description, | |
| 46 | + content: prompt.prompt, | |
| 47 | + }); | |
| 42 | 48 | hideLump(); |
| 43 | 49 | }; |
| 44 | 50 | |
| @@ -102,7 +108,7 @@ | ||
| 102 | 108 | (state) => state.config.config.slashCommands ?? [], |
| 103 | 109 | ); |
| 104 | 110 | |
| 105 | - const handleEdit = (prompt: PromptWithSlug) => { | |
| 111 | + const handleEdit = (prompt: PromptCommandWithSlug) => { | |
| 106 | 112 | if (prompt.promptFile) { |
| 107 | 113 | ideMessenger.post("openFile", { |
| 108 | 114 | path: prompt.promptFile, |
| @@ -120,23 +126,24 @@ | ||
| 120 | 126 | }; |
| 121 | 127 | |
| 122 | 128 | const sortedCommands = useMemo(() => { |
| 123 | - const promptsWithSlug: PromptWithSlug[] = structuredClone(slashCommands); | |
| 129 | + const promptsWithSlug: PromptCommandWithSlug[] = | |
| 130 | + structuredClone(slashCommands); | |
| 124 | 131 | // get the slugs from rawYaml |
| 125 | 132 | if (selectedProfile?.rawYaml) { |
| 126 | 133 | const parsed = parseConfigYaml(selectedProfile.rawYaml); |
| 127 | 134 | const parsedPrompts = parsed.prompts ?? []; |
| 128 | 135 | |
| 129 | 136 | let index = 0; |
| 130 | - for (const prompt of promptsWithSlug) { | |
| 137 | + for (const commandWithSlug of promptsWithSlug) { | |
| 131 | 138 | // skip for local prompt files |
| 132 | - if (prompt.promptFile) continue; | |
| 139 | + if (commandWithSlug.promptFile) continue; | |
| 133 | 140 | |
| 134 | 141 | const yamlPrompt = parsedPrompts[index]; |
| 135 | 142 | if (yamlPrompt) { |
| 136 | 143 | if ("uses" in yamlPrompt) { |
| 137 | - prompt.slug = yamlPrompt.uses; | |
| 144 | + commandWithSlug.slug = yamlPrompt.uses; | |
| 138 | 145 | } else { |
| 139 | - prompt.slug = `${selectedProfile?.fullSlug.ownerSlug}/${selectedProfile?.fullSlug.packageSlug}`; | |
| 146 | + commandWithSlug.slug = `${selectedProfile?.fullSlug.ownerSlug}/${selectedProfile?.fullSlug.packageSlug}`; | |
| 140 | 147 | } |
| 141 | 148 | } |
| 142 | 149 | index = index + 1; |
modified gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlock.ts +12 −9
| @@ -1,8 +1,9 @@ | ||
| 1 | 1 | import { mergeAttributes, Node } from "@tiptap/core"; |
| 2 | 2 | import { Node as ProseMirrorNode } from "@tiptap/pm/model"; |
| 3 | 3 | import { ReactNodeViewRenderer } from "@tiptap/react"; |
| 4 | -import { ContextItemWithId, SlashCommandDescription } from "core"; | |
| 4 | +import { ContextItemWithId } from "core"; | |
| 5 | 5 | import { MAIN_EDITOR_INPUT_ID } from "../../../../../pages/gui/Chat"; |
| 6 | +import { ComboBoxItem } from "../../../types"; | |
| 6 | 7 | import { PromptBlockPreview } from "./PromptBlockPreview"; |
| 7 | 8 | |
| 8 | 9 | export interface PromptBlockOptions { |
| @@ -20,7 +21,9 @@ | ||
| 20 | 21 | /** |
| 21 | 22 | * Insert a prompt block into the editor |
| 22 | 23 | */ |
| 23 | - insertPrompt: (item: SlashCommandDescription) => ReturnType; | |
| 24 | + insertPrompt: ( | |
| 25 | + item: Pick<ComboBoxItem, "title" | "content" | "description">, | |
| 26 | + ) => ReturnType; | |
| 24 | 27 | |
| 25 | 28 | /** |
| 26 | 29 | * Clear all prompt blocks from the editor |
| @@ -76,15 +79,15 @@ | ||
| 76 | 79 | addCommands() { |
| 77 | 80 | return { |
| 78 | 81 | insertPrompt: |
| 79 | - (prompt: SlashCommandDescription) => | |
| 82 | + (item) => | |
| 80 | 83 | ({ chain }) => { |
| 81 | - const item: ContextItemWithId = { | |
| 82 | - content: prompt.prompt ?? "", | |
| 83 | - name: prompt.name, | |
| 84 | - description: prompt.description, | |
| 84 | + const contextItem: ContextItemWithId = { | |
| 85 | + content: item.content ?? "", | |
| 86 | + name: item.title, | |
| 87 | + description: item.description, | |
| 85 | 88 | id: { |
| 86 | 89 | providerTitle: "prompt", |
| 87 | - itemId: prompt.name, | |
| 90 | + itemId: item.title, | |
| 88 | 91 | }, |
| 89 | 92 | }; |
| 90 | 93 | |
| @@ -93,7 +96,7 @@ | ||
| 93 | 96 | .insertContentAt(0, { |
| 94 | 97 | type: this.name, |
| 95 | 98 | attrs: { |
| 96 | - item, | |
| 99 | + item: contextItem, | |
| 97 | 100 | inputId: MAIN_EDITOR_INPUT_ID, |
| 98 | 101 | }, |
| 99 | 102 | }) |
modified gui/src/components/mainInput/TipTapEditor/extensions/SlashCommand.ts +1 −5
| @@ -22,11 +22,7 @@ | ||
| 22 | 22 | // First delete the slash character and any text after it |
| 23 | 23 | editor.chain().focus().deleteRange(range).run(); |
| 24 | 24 | |
| 25 | - editor.commands.insertPrompt({ | |
| 26 | - name: props.title, | |
| 27 | - description: props.description, | |
| 28 | - prompt: props.content, | |
| 29 | - }); | |
| 25 | + editor.commands.insertPrompt(props); | |
| 30 | 26 | }, |
| 31 | 27 | }, |
| 32 | 28 | }; |
modified gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts +4 −1
| @@ -330,7 +330,10 @@ | ||
| 330 | 330 | ], |
| 331 | 331 | editorProps: { |
| 332 | 332 | attributes: { |
| 333 | - class: "outline-none overflow-hidden", | |
| 333 | + "data-testid": props.isMainInput | |
| 334 | + ? "editor-input-main" | |
| 335 | + : `editor-input-${props.inputId}`, | |
| 336 | + class: "ProseMirror outline-none overflow-hidden", | |
| 334 | 337 | style: `font-size: ${getFontSize()}px;`, |
| 335 | 338 | }, |
| 336 | 339 | }, |
added gui/src/components/mainInput/TipTapEditor/utils/processEditorContent.test.ts +536 −0
| @@ -0,0 +1,536 @@ | ||
| 1 | +import { JSONContent } from "@tiptap/react"; | |
| 2 | +import { ContextItemWithId } from "core"; | |
| 3 | +import { expect, test, vi } from "vitest"; | |
| 4 | +import { processEditorContent } from "./processEditorContent"; | |
| 5 | + | |
| 6 | +describe("processEditorContent", () => { | |
| 7 | + // Create some reusable test data | |
| 8 | + const createContextItem = ( | |
| 9 | + content: string, | |
| 10 | + description: string, | |
| 11 | + fileUri?: string, | |
| 12 | + editing?: boolean, | |
| 13 | + ): ContextItemWithId => ({ | |
| 14 | + id: { providerTitle: "test", itemId: "test-id" }, | |
| 15 | + content, | |
| 16 | + description, | |
| 17 | + name: "Test Item", | |
| 18 | + editing, | |
| 19 | + uri: fileUri ? { type: "file", value: fileUri } : undefined, | |
| 20 | + }); | |
| 21 | + | |
| 22 | + test("processEditorContent should return empty arrays when content is empty", () => { | |
| 23 | + // Empty editor state | |
| 24 | + const emptyEditorState: JSONContent = { | |
| 25 | + type: "doc", | |
| 26 | + content: [], | |
| 27 | + }; | |
| 28 | + | |
| 29 | + const result = processEditorContent(emptyEditorState); | |
| 30 | + | |
| 31 | + expect(result.parts).toEqual([]); | |
| 32 | + expect(result.contextRequests).toEqual([]); | |
| 33 | + expect(result.selectedCode).toEqual([]); | |
| 34 | + expect(result.slashCommandName).toBeUndefined(); | |
| 35 | + }); | |
| 36 | + | |
| 37 | + test("processEditorContent should process text paragraphs", () => { | |
| 38 | + const editorState: JSONContent = { | |
| 39 | + type: "doc", | |
| 40 | + content: [ | |
| 41 | + { | |
| 42 | + type: "paragraph", | |
| 43 | + content: [ | |
| 44 | + { | |
| 45 | + type: "text", | |
| 46 | + text: "Hello world", | |
| 47 | + }, | |
| 48 | + ], | |
| 49 | + }, | |
| 50 | + { | |
| 51 | + type: "paragraph", | |
| 52 | + content: [ | |
| 53 | + { | |
| 54 | + type: "text", | |
| 55 | + text: "This is another paragraph", | |
| 56 | + }, | |
| 57 | + ], | |
| 58 | + }, | |
| 59 | + ], | |
| 60 | + }; | |
| 61 | + | |
| 62 | + const result = processEditorContent(editorState); | |
| 63 | + | |
| 64 | + expect(result.parts).toEqual([ | |
| 65 | + { | |
| 66 | + type: "text", | |
| 67 | + text: "Hello world\nThis is another paragraph", | |
| 68 | + }, | |
| 69 | + ]); | |
| 70 | + expect(result.contextRequests).toEqual([]); | |
| 71 | + expect(result.selectedCode).toEqual([]); | |
| 72 | + }); | |
| 73 | + | |
| 74 | + test("processEditorContent should detect slash commands", () => { | |
| 75 | + const editorState: JSONContent = { | |
| 76 | + type: "doc", | |
| 77 | + content: [ | |
| 78 | + { | |
| 79 | + type: "prompt-block", | |
| 80 | + attrs: { | |
| 81 | + item: { | |
| 82 | + name: "test-command", | |
| 83 | + }, | |
| 84 | + }, | |
| 85 | + }, | |
| 86 | + { | |
| 87 | + type: "paragraph", | |
| 88 | + content: [ | |
| 89 | + { | |
| 90 | + type: "text", | |
| 91 | + text: "Some text after the prompt", | |
| 92 | + }, | |
| 93 | + ], | |
| 94 | + }, | |
| 95 | + ], | |
| 96 | + }; | |
| 97 | + | |
| 98 | + const result = processEditorContent(editorState); | |
| 99 | + | |
| 100 | + expect(result.slashCommandName).toBe("test-command"); | |
| 101 | + expect(result.parts).toEqual([ | |
| 102 | + { | |
| 103 | + type: "text", | |
| 104 | + text: "Some text after the prompt", | |
| 105 | + }, | |
| 106 | + ]); | |
| 107 | + }); | |
| 108 | + | |
| 109 | + test("processEditorContent should handle mentions and collect context requests", () => { | |
| 110 | + const editorState: JSONContent = { | |
| 111 | + type: "doc", | |
| 112 | + content: [ | |
| 113 | + { | |
| 114 | + type: "paragraph", | |
| 115 | + content: [ | |
| 116 | + { | |
| 117 | + type: "text", | |
| 118 | + text: "Hello ", | |
| 119 | + }, | |
| 120 | + { | |
| 121 | + type: "mention", | |
| 122 | + attrs: { | |
| 123 | + id: "fileSearch", | |
| 124 | + label: "@fileSearch", | |
| 125 | + itemType: "contextProvider", | |
| 126 | + }, | |
| 127 | + }, | |
| 128 | + { | |
| 129 | + type: "text", | |
| 130 | + text: " and also ", | |
| 131 | + }, | |
| 132 | + { | |
| 133 | + type: "mention", | |
| 134 | + attrs: { | |
| 135 | + id: "github", | |
| 136 | + label: "@github", | |
| 137 | + itemType: "contextProvider", | |
| 138 | + }, | |
| 139 | + }, | |
| 140 | + ], | |
| 141 | + }, | |
| 142 | + ], | |
| 143 | + }; | |
| 144 | + | |
| 145 | + const result = processEditorContent(editorState); | |
| 146 | + | |
| 147 | + expect(result.parts).toEqual([ | |
| 148 | + { | |
| 149 | + type: "text", | |
| 150 | + text: "Hello @fileSearch and also @github", | |
| 151 | + }, | |
| 152 | + ]); | |
| 153 | + expect(result.contextRequests).toEqual([ | |
| 154 | + { provider: "fileSearch" }, | |
| 155 | + { provider: "github" }, | |
| 156 | + ]); | |
| 157 | + }); | |
| 158 | + | |
| 159 | + test("processEditorContent should handle code blocks", () => { | |
| 160 | + const codeItem = createContextItem( | |
| 161 | + "function test() {\n return 'hello';\n}", | |
| 162 | + "a description", | |
| 163 | + "file:///example.js", | |
| 164 | + ); | |
| 165 | + | |
| 166 | + const editorState: JSONContent = { | |
| 167 | + type: "doc", | |
| 168 | + content: [ | |
| 169 | + { | |
| 170 | + type: "paragraph", | |
| 171 | + content: [ | |
| 172 | + { | |
| 173 | + type: "text", | |
| 174 | + text: "Check this code:", | |
| 175 | + }, | |
| 176 | + ], | |
| 177 | + }, | |
| 178 | + { | |
| 179 | + type: "code-block", | |
| 180 | + attrs: { | |
| 181 | + item: codeItem, | |
| 182 | + }, | |
| 183 | + }, | |
| 184 | + ], | |
| 185 | + }; | |
| 186 | + | |
| 187 | + const result = processEditorContent(editorState); | |
| 188 | + | |
| 189 | + expect(result.parts).toEqual([ | |
| 190 | + { | |
| 191 | + type: "text", | |
| 192 | + text: "Check this code:\n\n```js example.js\nfunction test() {\n return 'hello';\n}\n```\n", | |
| 193 | + }, | |
| 194 | + ]); | |
| 195 | + expect(result.selectedCode).toHaveLength(1); | |
| 196 | + expect(result.selectedCode[0].filepath).toBe("file:///example.js"); | |
| 197 | + }); | |
| 198 | + | |
| 199 | + test("processEditorContent should not include editing code blocks in the text", () => { | |
| 200 | + const editingCodeItem = createContextItem( | |
| 201 | + "function test() {\n return 'hello';\n}", | |
| 202 | + "a description", | |
| 203 | + "file:///editing.js", | |
| 204 | + true, // Set editing to true | |
| 205 | + ); | |
| 206 | + | |
| 207 | + const editorState: JSONContent = { | |
| 208 | + type: "doc", | |
| 209 | + content: [ | |
| 210 | + { | |
| 211 | + type: "paragraph", | |
| 212 | + content: [ | |
| 213 | + { | |
| 214 | + type: "text", | |
| 215 | + text: "Edit this code:", | |
| 216 | + }, | |
| 217 | + ], | |
| 218 | + }, | |
| 219 | + { | |
| 220 | + type: "code-block", | |
| 221 | + attrs: { | |
| 222 | + item: editingCodeItem, | |
| 223 | + }, | |
| 224 | + }, | |
| 225 | + ], | |
| 226 | + }; | |
| 227 | + | |
| 228 | + const result = processEditorContent(editorState); | |
| 229 | + | |
| 230 | + // The code block should not be included in parts because it's marked as editing | |
| 231 | + expect(result.parts).toEqual([ | |
| 232 | + { | |
| 233 | + type: "text", | |
| 234 | + text: "Edit this code:", | |
| 235 | + }, | |
| 236 | + ]); | |
| 237 | + | |
| 238 | + // But it should still be in selectedCode | |
| 239 | + expect(result.selectedCode).toHaveLength(1); | |
| 240 | + expect(result.selectedCode[0].filepath).toBe("file:///editing.js"); | |
| 241 | + }); | |
| 242 | + | |
| 243 | + test("processEditorContent should handle images", () => { | |
| 244 | + const editorState: JSONContent = { | |
| 245 | + type: "doc", | |
| 246 | + content: [ | |
| 247 | + { | |
| 248 | + type: "paragraph", | |
| 249 | + content: [ | |
| 250 | + { | |
| 251 | + type: "text", | |
| 252 | + text: "Here's an image:", | |
| 253 | + }, | |
| 254 | + ], | |
| 255 | + }, | |
| 256 | + { | |
| 257 | + type: "image", | |
| 258 | + attrs: { | |
| 259 | + src: "https://example.com/image.png", | |
| 260 | + }, | |
| 261 | + }, | |
| 262 | + ], | |
| 263 | + }; | |
| 264 | + | |
| 265 | + const result = processEditorContent(editorState); | |
| 266 | + | |
| 267 | + expect(result.parts).toEqual([ | |
| 268 | + { | |
| 269 | + type: "text", | |
| 270 | + text: "Here's an image:", | |
| 271 | + }, | |
| 272 | + { | |
| 273 | + type: "imageUrl", | |
| 274 | + imageUrl: { url: "https://example.com/image.png" }, | |
| 275 | + }, | |
| 276 | + ]); | |
| 277 | + }); | |
| 278 | + | |
| 279 | + test("processEditorContent should handle complex content with multiple elements", () => { | |
| 280 | + const codeItem = createContextItem( | |
| 281 | + "const x = 42;", | |
| 282 | + "a description", | |
| 283 | + "file:///script.ts", | |
| 284 | + ); | |
| 285 | + | |
| 286 | + const editorState: JSONContent = { | |
| 287 | + type: "doc", | |
| 288 | + content: [ | |
| 289 | + { | |
| 290 | + type: "prompt-block", | |
| 291 | + attrs: { | |
| 292 | + item: { | |
| 293 | + name: "explain", | |
| 294 | + }, | |
| 295 | + }, | |
| 296 | + }, | |
| 297 | + { | |
| 298 | + type: "paragraph", | |
| 299 | + content: [ | |
| 300 | + { | |
| 301 | + type: "text", | |
| 302 | + text: "Please explain this code and also check ", | |
| 303 | + }, | |
| 304 | + { | |
| 305 | + type: "mention", | |
| 306 | + attrs: { | |
| 307 | + id: "related", | |
| 308 | + label: "@related", | |
| 309 | + itemType: "similarFiles", | |
| 310 | + }, | |
| 311 | + }, | |
| 312 | + ], | |
| 313 | + }, | |
| 314 | + { | |
| 315 | + type: "code-block", | |
| 316 | + attrs: { | |
| 317 | + item: codeItem, | |
| 318 | + }, | |
| 319 | + }, | |
| 320 | + { | |
| 321 | + type: "paragraph", | |
| 322 | + content: [ | |
| 323 | + { | |
| 324 | + type: "text", | |
| 325 | + text: "What does this constant do?", | |
| 326 | + }, | |
| 327 | + ], | |
| 328 | + }, | |
| 329 | + { | |
| 330 | + type: "image", | |
| 331 | + attrs: { | |
| 332 | + src: "https://example.com/diagram.png", | |
| 333 | + }, | |
| 334 | + }, | |
| 335 | + ], | |
| 336 | + }; | |
| 337 | + | |
| 338 | + const result = processEditorContent(editorState); | |
| 339 | + | |
| 340 | + expect(result.slashCommandName).toBe("explain"); | |
| 341 | + expect(result.contextRequests).toEqual([{ provider: "similarFiles" }]); | |
| 342 | + expect(result.selectedCode).toHaveLength(1); | |
| 343 | + expect(result.selectedCode[0].filepath).toBe("file:///script.ts"); | |
| 344 | + | |
| 345 | + // `\n\n\`\`\`${extension} ${relativePathOrBasename}\n${contextItem.content}\n\`\`\`\n`; | |
| 346 | + | |
| 347 | + expect(result.parts).toEqual([ | |
| 348 | + { | |
| 349 | + type: "text", | |
| 350 | + text: "Please explain this code and also check @related\n\n```ts script.ts\nconst x = 42;\n```\n\nWhat does this constant do?", | |
| 351 | + }, | |
| 352 | + { | |
| 353 | + type: "imageUrl", | |
| 354 | + imageUrl: { url: "https://example.com/diagram.png" }, | |
| 355 | + }, | |
| 356 | + ]); | |
| 357 | + }); | |
| 358 | + | |
| 359 | + test("processEditorContent should merge consecutive text parts", () => { | |
| 360 | + const editorState: JSONContent = { | |
| 361 | + type: "doc", | |
| 362 | + content: [ | |
| 363 | + { | |
| 364 | + type: "paragraph", | |
| 365 | + content: [ | |
| 366 | + { | |
| 367 | + type: "text", | |
| 368 | + text: "First paragraph", | |
| 369 | + }, | |
| 370 | + ], | |
| 371 | + }, | |
| 372 | + { | |
| 373 | + type: "paragraph", | |
| 374 | + content: [ | |
| 375 | + { | |
| 376 | + type: "text", | |
| 377 | + text: "Second paragraph", | |
| 378 | + }, | |
| 379 | + ], | |
| 380 | + }, | |
| 381 | + { | |
| 382 | + type: "image", | |
| 383 | + attrs: { | |
| 384 | + src: "https://example.com/image.png", | |
| 385 | + }, | |
| 386 | + }, | |
| 387 | + { | |
| 388 | + type: "paragraph", | |
| 389 | + content: [ | |
| 390 | + { | |
| 391 | + type: "text", | |
| 392 | + text: "Third paragraph", | |
| 393 | + }, | |
| 394 | + ], | |
| 395 | + }, | |
| 396 | + ], | |
| 397 | + }; | |
| 398 | + | |
| 399 | + const result = processEditorContent(editorState); | |
| 400 | + | |
| 401 | + // First two paragraphs should be merged, but the third should be separate | |
| 402 | + // because there's an image in between | |
| 403 | + expect(result.parts).toEqual([ | |
| 404 | + { | |
| 405 | + type: "text", | |
| 406 | + text: "First paragraph\nSecond paragraph", | |
| 407 | + }, | |
| 408 | + { | |
| 409 | + type: "imageUrl", | |
| 410 | + imageUrl: { url: "https://example.com/image.png" }, | |
| 411 | + }, | |
| 412 | + { | |
| 413 | + type: "text", | |
| 414 | + text: "Third paragraph", | |
| 415 | + }, | |
| 416 | + ]); | |
| 417 | + }); | |
| 418 | + | |
| 419 | + test("processEditorContent should handle unexpected content types gracefully", () => { | |
| 420 | + // Testing with an unknown node type | |
| 421 | + const editorState: JSONContent = { | |
| 422 | + type: "doc", | |
| 423 | + content: [ | |
| 424 | + { | |
| 425 | + type: "paragraph", | |
| 426 | + content: [ | |
| 427 | + { | |
| 428 | + type: "text", | |
| 429 | + text: "Normal text", | |
| 430 | + }, | |
| 431 | + ], | |
| 432 | + }, | |
| 433 | + { | |
| 434 | + type: "unknown-type", // This type doesn't exist | |
| 435 | + content: [ | |
| 436 | + { | |
| 437 | + type: "text", | |
| 438 | + text: "This should be ignored", | |
| 439 | + }, | |
| 440 | + ], | |
| 441 | + }, | |
| 442 | + ], | |
| 443 | + }; | |
| 444 | + | |
| 445 | + // Spy on console.warn to verify it's called | |
| 446 | + const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}); | |
| 447 | + | |
| 448 | + const result = processEditorContent(editorState); | |
| 449 | + | |
| 450 | + // Only the normal paragraph should be processed | |
| 451 | + expect(result.parts).toEqual([ | |
| 452 | + { | |
| 453 | + type: "text", | |
| 454 | + text: "Normal text", | |
| 455 | + }, | |
| 456 | + ]); | |
| 457 | + | |
| 458 | + // Console.warn should be called for the unknown type | |
| 459 | + expect(warnSpy).toHaveBeenCalledWith( | |
| 460 | + "Unexpected content type", | |
| 461 | + "unknown-type", | |
| 462 | + ); | |
| 463 | + | |
| 464 | + warnSpy.mockRestore(); | |
| 465 | + }); | |
| 466 | + | |
| 467 | + test("processEditorContent should handle missing attrs in code blocks", () => { | |
| 468 | + // Testing with a code block that has no item attribute | |
| 469 | + const editorState: JSONContent = { | |
| 470 | + type: "doc", | |
| 471 | + content: [ | |
| 472 | + { | |
| 473 | + type: "code-block", | |
| 474 | + // Missing attrs property | |
| 475 | + }, | |
| 476 | + ], | |
| 477 | + }; | |
| 478 | + | |
| 479 | + // Spy on console.warn to verify it's called | |
| 480 | + const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}); | |
| 481 | + | |
| 482 | + const result = processEditorContent(editorState); | |
| 483 | + | |
| 484 | + // No parts should be created | |
| 485 | + expect(result.parts).toEqual([]); | |
| 486 | + expect(result.selectedCode).toEqual([]); | |
| 487 | + | |
| 488 | + // Console.warn should be called for the missing item attribute | |
| 489 | + expect(warnSpy).toHaveBeenCalledWith("codeBlock has no item attribute"); | |
| 490 | + | |
| 491 | + warnSpy.mockRestore(); | |
| 492 | + }); | |
| 493 | + | |
| 494 | + test("processEditorContent should handle paragraphs with unexpected child types", () => { | |
| 495 | + // Testing with a paragraph that has an unknown child type | |
| 496 | + const editorState: JSONContent = { | |
| 497 | + type: "doc", | |
| 498 | + content: [ | |
| 499 | + { | |
| 500 | + type: "paragraph", | |
| 501 | + content: [ | |
| 502 | + { | |
| 503 | + type: "text", | |
| 504 | + text: "Normal text ", | |
| 505 | + }, | |
| 506 | + { | |
| 507 | + type: "unknown-child", // This type doesn't exist | |
| 508 | + text: "This should be ignored", | |
| 509 | + }, | |
| 510 | + ], | |
| 511 | + }, | |
| 512 | + ], | |
| 513 | + }; | |
| 514 | + | |
| 515 | + // Spy on console.warn to verify it's called | |
| 516 | + const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}); | |
| 517 | + | |
| 518 | + const result = processEditorContent(editorState); | |
| 519 | + | |
| 520 | + // Only the normal text should be processed | |
| 521 | + expect(result.parts).toEqual([ | |
| 522 | + { | |
| 523 | + type: "text", | |
| 524 | + text: "Normal text ", | |
| 525 | + }, | |
| 526 | + ]); | |
| 527 | + | |
| 528 | + // Console.warn should be called for the unknown child type | |
| 529 | + expect(warnSpy).toHaveBeenCalledWith( | |
| 530 | + "Unexpected child type", | |
| 531 | + "unknown-child", | |
| 532 | + ); | |
| 533 | + | |
| 534 | + warnSpy.mockRestore(); | |
| 535 | + }); | |
| 536 | +}); |
added gui/src/components/mainInput/TipTapEditor/utils/processEditorContent.ts +119 −0
| @@ -0,0 +1,119 @@ | ||
| 1 | +import Image from "@tiptap/extension-image"; | |
| 2 | +import { Paragraph } from "@tiptap/extension-paragraph"; | |
| 3 | +import { Text } from "@tiptap/extension-text"; | |
| 4 | +import { JSONContent } from "@tiptap/react"; | |
| 5 | +import { | |
| 6 | + ContextItemWithId, | |
| 7 | + MessagePart, | |
| 8 | + RangeInFile, | |
| 9 | + TextMessagePart, | |
| 10 | +} from "core"; | |
| 11 | +import { ctxItemToRifWithContents } from "core/commands/util"; | |
| 12 | +import { getUriDescription } from "core/util/uri"; | |
| 13 | +import { CodeBlock, Mention, PromptBlock } from "../extensions"; | |
| 14 | +import { GetContextRequest } from "./types"; | |
| 15 | + | |
| 16 | +interface MentionAttrs { | |
| 17 | + label: string; | |
| 18 | + id: string; | |
| 19 | + itemType?: string; | |
| 20 | + query?: string; | |
| 21 | +} | |
| 22 | + | |
| 23 | +function resolvePromptBlock(p: JSONContent): string | undefined { | |
| 24 | + return p.attrs?.item.name; | |
| 25 | +} | |
| 26 | + | |
| 27 | +function resolveParagraph(p: JSONContent): [string, GetContextRequest[]] { | |
| 28 | + const contextRequests: GetContextRequest[] = []; | |
| 29 | + | |
| 30 | + const text = (p.content || []) | |
| 31 | + .map((child) => { | |
| 32 | + switch (child.type) { | |
| 33 | + case Text.name: | |
| 34 | + return child.text; | |
| 35 | + case Mention.name: | |
| 36 | + const attrs = child.attrs as MentionAttrs; | |
| 37 | + contextRequests.push({ | |
| 38 | + provider: | |
| 39 | + attrs.itemType === "contextProvider" ? attrs.id : attrs.itemType!, | |
| 40 | + }); | |
| 41 | + return child.attrs?.renderInlineAs ?? child.attrs?.label; | |
| 42 | + | |
| 43 | + default: | |
| 44 | + console.warn("Unexpected child type", child.type); | |
| 45 | + return ""; | |
| 46 | + } | |
| 47 | + }) | |
| 48 | + .join("") | |
| 49 | + .trimStart(); | |
| 50 | + | |
| 51 | + return [text, contextRequests]; | |
| 52 | +} | |
| 53 | + | |
| 54 | +export function processEditorContent(editorState: JSONContent) { | |
| 55 | + const contextRequests: GetContextRequest[] = []; | |
| 56 | + const selectedCode: RangeInFile[] = []; | |
| 57 | + let slashCommandName: string | undefined; | |
| 58 | + | |
| 59 | + const parts: MessagePart[] = []; | |
| 60 | + for (const p of editorState?.content || []) { | |
| 61 | + switch (p.type) { | |
| 62 | + case PromptBlock.name: | |
| 63 | + slashCommandName = resolvePromptBlock(p); | |
| 64 | + break; | |
| 65 | + case Paragraph.name: | |
| 66 | + const [text, ctxItems] = resolveParagraph(p); | |
| 67 | + | |
| 68 | + contextRequests.push(...ctxItems); | |
| 69 | + | |
| 70 | + if (text) { | |
| 71 | + // Merge with previous text part if possible | |
| 72 | + if (parts[parts.length - 1]?.type === "text") { | |
| 73 | + (parts[parts.length - 1] as TextMessagePart).text += "\n" + text; | |
| 74 | + } else { | |
| 75 | + parts.push({ type: "text", text }); | |
| 76 | + } | |
| 77 | + } | |
| 78 | + break; | |
| 79 | + case CodeBlock.name: | |
| 80 | + if (!p.attrs?.item) { | |
| 81 | + console.warn("codeBlock has no item attribute"); | |
| 82 | + break; | |
| 83 | + } | |
| 84 | + | |
| 85 | + const contextItem = p.attrs.item as ContextItemWithId; | |
| 86 | + const rif = ctxItemToRifWithContents(contextItem, true); | |
| 87 | + selectedCode.push(rif); | |
| 88 | + | |
| 89 | + // If editing, only include in selectedCode | |
| 90 | + if (contextItem.editing) { | |
| 91 | + break; | |
| 92 | + } | |
| 93 | + | |
| 94 | + const { extension, relativePathOrBasename } = getUriDescription( | |
| 95 | + rif.filepath, | |
| 96 | + window.workspacePaths ?? [], | |
| 97 | + ); | |
| 98 | + const codeText = `\n\`\`\`${extension} ${relativePathOrBasename}\n${contextItem.content}\n\`\`\`\n`; | |
| 99 | + | |
| 100 | + if (parts[parts.length - 1]?.type === "text") { | |
| 101 | + (parts[parts.length - 1] as TextMessagePart).text += "\n" + codeText; | |
| 102 | + } else { | |
| 103 | + parts.push({ type: "text", text: codeText }); | |
| 104 | + } | |
| 105 | + break; | |
| 106 | + case Image.name: | |
| 107 | + parts.push({ | |
| 108 | + type: "imageUrl", | |
| 109 | + imageUrl: { url: p.attrs?.src }, | |
| 110 | + }); | |
| 111 | + break; | |
| 112 | + default: { | |
| 113 | + console.warn("Unexpected content type", p.type); | |
| 114 | + } | |
| 115 | + } | |
| 116 | + } | |
| 117 | + | |
| 118 | + return { parts, contextRequests, selectedCode, slashCommandName }; | |
| 119 | +} |
added gui/src/components/mainInput/TipTapEditor/utils/renderMcpPrompt.ts +32 −0
| @@ -0,0 +1,32 @@ | ||
| 1 | +import { SlashCommandDescWithSource } from "core"; | |
| 2 | +import { IIdeMessenger } from "../../../../context/IdeMessenger"; | |
| 3 | + | |
| 4 | +export async function renderMcpPrompt( | |
| 5 | + command: SlashCommandDescWithSource, | |
| 6 | + ideMessenger: IIdeMessenger, | |
| 7 | + userInput?: string, | |
| 8 | +) { | |
| 9 | + // TODO add support for mcp prompt args using command.mcpArgs | |
| 10 | + const args: { [key: string]: string } = {}; | |
| 11 | + if (command.mcpArgs) { | |
| 12 | + command.mcpArgs.forEach((arg, i) => { | |
| 13 | + args[arg.name] = ""; | |
| 14 | + }); | |
| 15 | + } | |
| 16 | + const response = await ideMessenger.request("mcp/getPrompt", { | |
| 17 | + serverName: command.mcpServerName!, | |
| 18 | + promptName: command.name, | |
| 19 | + args: args, | |
| 20 | + }); | |
| 21 | + if (response.status === "success") { | |
| 22 | + let renderedPrompt = response.content.prompt; | |
| 23 | + if (userInput) { | |
| 24 | + renderedPrompt += `\n\n${userInput}`; | |
| 25 | + } | |
| 26 | + return renderedPrompt; | |
| 27 | + } else { | |
| 28 | + throw new Error( | |
| 29 | + `Failed to get MCP prompt for slash command ${command.name}`, | |
| 30 | + ); | |
| 31 | + } | |
| 32 | +} |
added gui/src/components/mainInput/TipTapEditor/utils/renderPromptv1.test.ts +128 −0
| @@ -0,0 +1,128 @@ | ||
| 1 | +import { SlashCommandDescWithSource } from "core"; | |
| 2 | +import { beforeEach, describe, it, vi } from "vitest"; | |
| 3 | +import { | |
| 4 | + MockIdeMessenger, | |
| 5 | + MockResponseHandler, | |
| 6 | +} from "../../../../context/MockIdeMessenger"; | |
| 7 | +import { getRenderedV1Prompt } from "./renderPromptv1"; | |
| 8 | + | |
| 9 | +function getTestPromptV1Command(body: string): SlashCommandDescWithSource { | |
| 10 | + return { | |
| 11 | + prompt: body, | |
| 12 | + name: "test-prompt-name", | |
| 13 | + description: "test-prompt-description", | |
| 14 | + isLegacy: false, | |
| 15 | + source: "prompt-file-v1", | |
| 16 | + }; | |
| 17 | +} | |
| 18 | +describe("get rendered v1 prompt file", () => { | |
| 19 | + const ideMessenger = new MockIdeMessenger(); | |
| 20 | + const firstDir = ideMessenger.responses["getWorkspaceDirs"]?.[0] ?? ""; | |
| 21 | + const customGetContextItems: MockResponseHandler< | |
| 22 | + "context/getContextItems" | |
| 23 | + > = async ({ name }) => { | |
| 24 | + if (name === "diff") { | |
| 25 | + return [ | |
| 26 | + { | |
| 27 | + id: { | |
| 28 | + itemId: "id", | |
| 29 | + providerTitle: "diff", | |
| 30 | + }, | |
| 31 | + name: "name", | |
| 32 | + description: "description", | |
| 33 | + content: "Diff provider content", | |
| 34 | + }, | |
| 35 | + ]; | |
| 36 | + } | |
| 37 | + return []; | |
| 38 | + }; | |
| 39 | + beforeEach(async () => { | |
| 40 | + vi.clearAllMocks(); | |
| 41 | + ideMessenger.resetMocks(); | |
| 42 | + }); | |
| 43 | + | |
| 44 | + it("should render a prompt file with no attachments or templated input", async () => { | |
| 45 | + const rawContent = "Simple prompt with no attachments"; | |
| 46 | + const command = getTestPromptV1Command(rawContent); | |
| 47 | + const rendered = await getRenderedV1Prompt( | |
| 48 | + ideMessenger, | |
| 49 | + command, | |
| 50 | + "User input", | |
| 51 | + [], | |
| 52 | + ); | |
| 53 | + expect(rendered).toBe("Simple prompt with no attachments\n\nUser input"); | |
| 54 | + }); | |
| 55 | + | |
| 56 | + it("should render a prompt file templated input", async () => { | |
| 57 | + const rawContent = "{{{ input }}} Simple prompt with no attachments"; | |
| 58 | + const command = getTestPromptV1Command(rawContent); | |
| 59 | + const rendered = await getRenderedV1Prompt( | |
| 60 | + ideMessenger, | |
| 61 | + command, | |
| 62 | + "User input", | |
| 63 | + [], | |
| 64 | + ); | |
| 65 | + expect(rendered).toBe("User input Simple prompt with no attachments"); | |
| 66 | + }); | |
| 67 | + | |
| 68 | + it("Should handle file attachments", async () => { | |
| 69 | + ideMessenger.responses["readFile"] = "Test file content"; | |
| 70 | + const rawContent = "Content with URL {{{ testFile.txt }}}"; | |
| 71 | + const command = getTestPromptV1Command(rawContent); | |
| 72 | + const rendered = await getRenderedV1Prompt( | |
| 73 | + ideMessenger, | |
| 74 | + command, | |
| 75 | + "User input", | |
| 76 | + [], | |
| 77 | + ); | |
| 78 | + expect(rendered).toBe("Content with URL Test file content\n\nUser input"); | |
| 79 | + }); | |
| 80 | + | |
| 81 | + it("should handle supported providers", async () => { | |
| 82 | + ideMessenger.responseHandlers["context/getContextItems"] = | |
| 83 | + customGetContextItems; | |
| 84 | + const rawContent = "Tell me about {{{ diff }}} please"; | |
| 85 | + const command = getTestPromptV1Command(rawContent); | |
| 86 | + const rendered = await getRenderedV1Prompt( | |
| 87 | + ideMessenger, | |
| 88 | + command, | |
| 89 | + "User input", | |
| 90 | + [], | |
| 91 | + ); | |
| 92 | + expect(rendered).toBe( | |
| 93 | + "Tell me about Diff provider content please\n\nUser input", | |
| 94 | + ); | |
| 95 | + }); | |
| 96 | + | |
| 97 | + it("should render file read errors within prompt", async () => { | |
| 98 | + ideMessenger.responses["fileExists"] = false; | |
| 99 | + const rawContent = "Content with provider {{{ nonexistent }}}"; | |
| 100 | + const command = getTestPromptV1Command(rawContent); | |
| 101 | + const rendered = await getRenderedV1Prompt( | |
| 102 | + ideMessenger, | |
| 103 | + command, | |
| 104 | + "User input", | |
| 105 | + [], | |
| 106 | + ); | |
| 107 | + expect(rendered).toBe( | |
| 108 | + `Content with provider [Error reading file "nonexistent"]\n\nUser input`, | |
| 109 | + ); | |
| 110 | + }); | |
| 111 | + | |
| 112 | + it("should handle multiple attachments", async () => { | |
| 113 | + ideMessenger.responseHandlers["context/getContextItems"] = | |
| 114 | + customGetContextItems; | |
| 115 | + ideMessenger.responses["readFile"] = "Test file content"; | |
| 116 | + const rawContent = "Content with {{{ diff }}} and {{{ file.txt }}}"; | |
| 117 | + const command = getTestPromptV1Command(rawContent); | |
| 118 | + const rendered = await getRenderedV1Prompt( | |
| 119 | + ideMessenger, | |
| 120 | + command, | |
| 121 | + "User input", | |
| 122 | + [], | |
| 123 | + ); | |
| 124 | + expect(rendered).toBe( | |
| 125 | + "Content with Diff provider content and Test file content\n\nUser input", | |
| 126 | + ); | |
| 127 | + }); | |
| 128 | +}); |
added gui/src/components/mainInput/TipTapEditor/utils/renderPromptv1.ts +58 −0
| @@ -0,0 +1,58 @@ | ||
| 1 | +import { | |
| 2 | + ContextProviderName, | |
| 3 | + RangeInFile, | |
| 4 | + SlashCommandDescWithSource, | |
| 5 | +} from "core"; | |
| 6 | +import { SUPPORTED_PROMPT_CONTEXT_PROVIDERS } from "core/promptFiles"; | |
| 7 | +import { renderTemplatedString } from "core/util/handlebars/renderTemplatedString"; | |
| 8 | +import { resolveRelativePathInDir } from "core/util/ideUtils"; | |
| 9 | +import { IIdeMessenger } from "../../../../context/IdeMessenger"; | |
| 10 | + | |
| 11 | +export async function getRenderedV1Prompt( | |
| 12 | + ideMessenger: IIdeMessenger, | |
| 13 | + command: SlashCommandDescWithSource, | |
| 14 | + userInput: string, | |
| 15 | + selectedCode: RangeInFile[], | |
| 16 | +): Promise<string> { | |
| 17 | + if (!command.prompt) { | |
| 18 | + return ""; | |
| 19 | + } | |
| 20 | + const handleBarHelpers = SUPPORTED_PROMPT_CONTEXT_PROVIDERS.map( | |
| 21 | + (name: ContextProviderName): [string, Handlebars.HelperDelegate] => [ | |
| 22 | + name, | |
| 23 | + async (helperContext: any) => { | |
| 24 | + const response = await ideMessenger.request("context/getContextItems", { | |
| 25 | + fullInput: userInput, | |
| 26 | + name, | |
| 27 | + query: "", | |
| 28 | + selectedCode, | |
| 29 | + }); | |
| 30 | + if (response.status === "success") { | |
| 31 | + return response.content.map((item) => item.content).join("\n\n"); | |
| 32 | + } else { | |
| 33 | + throw new Error( | |
| 34 | + `Failed to get context items from provider "${name}": ${response.error}`, | |
| 35 | + ); | |
| 36 | + } | |
| 37 | + }, | |
| 38 | + ], | |
| 39 | + ); | |
| 40 | + const workspaceDirs = await ideMessenger.ide.getWorkspaceDirs(); | |
| 41 | + const getUriFromPath = (path: string) => { | |
| 42 | + return resolveRelativePathInDir(path, ideMessenger.ide, workspaceDirs); | |
| 43 | + }; | |
| 44 | + const handlebars = await import("handlebars"); | |
| 45 | + let rendered = await renderTemplatedString( | |
| 46 | + handlebars, | |
| 47 | + command.prompt, | |
| 48 | + { input: userInput }, | |
| 49 | + handleBarHelpers, | |
| 50 | + ideMessenger.ide.readFile.bind(ideMessenger.ide), | |
| 51 | + getUriFromPath, | |
| 52 | + ); | |
| 53 | + // For prompt file append the input if it isn't rendered | |
| 54 | + if (!rendered.includes(userInput)) { | |
| 55 | + rendered = rendered + `\n\n${userInput}`; | |
| 56 | + } | |
| 57 | + return rendered.trim(); | |
| 58 | +} |
added gui/src/components/mainInput/TipTapEditor/utils/renderPromptv2.test.ts +80 −0
| @@ -0,0 +1,80 @@ | ||
| 1 | +import { SlashCommandDescWithSource } from "core"; | |
| 2 | +import { beforeEach, describe, expect, it, vi } from "vitest"; | |
| 3 | +import { MockIdeMessenger } from "../../../../context/MockIdeMessenger"; | |
| 4 | +import { getPromptV2ContextRequests } from "./renderPromptv2"; | |
| 5 | + | |
| 6 | +function getTestPromptV2Command(body: string): SlashCommandDescWithSource { | |
| 7 | + return { | |
| 8 | + prompt: body, | |
| 9 | + name: "test-prompt-name", | |
| 10 | + description: "test-prompt-description", | |
| 11 | + isLegacy: false, | |
| 12 | + source: "prompt-file-v2", | |
| 13 | + }; | |
| 14 | +} | |
| 15 | +describe("getPromptV2ContextRequests", () => { | |
| 16 | + const ideMessenger = new MockIdeMessenger(); | |
| 17 | + const firstDir = ideMessenger.responses["getWorkspaceDirs"]?.[0] ?? ""; | |
| 18 | + beforeEach(async () => { | |
| 19 | + vi.clearAllMocks(); | |
| 20 | + ideMessenger.resetMocks(); | |
| 21 | + }); | |
| 22 | + | |
| 23 | + it("should render a prompt file with no attachments", async () => { | |
| 24 | + const rawContent = "Simple prompt with no attachments"; | |
| 25 | + const command = getTestPromptV2Command(rawContent); | |
| 26 | + const requests = await getPromptV2ContextRequests(ideMessenger, command); | |
| 27 | + expect(requests).toHaveLength(0); | |
| 28 | + }); | |
| 29 | + | |
| 30 | + it("should handle URL attachments", async () => { | |
| 31 | + const rawContent = "Content with URL @https://example.com"; | |
| 32 | + const command = getTestPromptV2Command(rawContent); | |
| 33 | + const requests = await getPromptV2ContextRequests(ideMessenger, command); | |
| 34 | + expect(requests).toHaveLength(1); | |
| 35 | + expect(requests[0].provider).toBe("url"); | |
| 36 | + expect(requests[0].query).toBe("https://example.com"); | |
| 37 | + }); | |
| 38 | + | |
| 39 | + it("should resolve file attachments", async () => { | |
| 40 | + const rawContent = "Content with file attachment @test.txt"; | |
| 41 | + const command = getTestPromptV2Command(rawContent); | |
| 42 | + const requests = await getPromptV2ContextRequests(ideMessenger, command); | |
| 43 | + | |
| 44 | + expect(requests).toHaveLength(1); | |
| 45 | + expect(requests[0].provider).toBe("file"); | |
| 46 | + expect(requests[0].query).toBe(`${firstDir}/test.txt`); | |
| 47 | + }); | |
| 48 | + | |
| 49 | + it("should handle nested prompt files", async () => { | |
| 50 | + ideMessenger.responses["readFile"] = "Contents @myfile.txt"; | |
| 51 | + const rawContent = "Main prompt with nested @test.prompt"; | |
| 52 | + const command = getTestPromptV2Command(rawContent); | |
| 53 | + const requests = await getPromptV2ContextRequests(ideMessenger, command); | |
| 54 | + expect(requests).toHaveLength(2); | |
| 55 | + expect(requests[0].provider).toBe("file"); | |
| 56 | + expect(requests[0].query).toBe(`${firstDir}/myfile.txt`); | |
| 57 | + expect(requests[1].provider).toBe("file"); | |
| 58 | + expect(requests[1].query).toBe(`${firstDir}/test.prompt`); | |
| 59 | + }); | |
| 60 | + | |
| 61 | + it("should ignore unsupported providers", async () => { | |
| 62 | + ideMessenger.responses["fileExists"] = false; | |
| 63 | + const rawContent = "Content with custom provider @unsupported"; | |
| 64 | + const command = getTestPromptV2Command(rawContent); | |
| 65 | + const requests = await getPromptV2ContextRequests(ideMessenger, command); | |
| 66 | + expect(requests).toHaveLength(0); | |
| 67 | + }); | |
| 68 | + | |
| 69 | + it("should handle multiple attachments", async () => { | |
| 70 | + const rawContent = "Content with @file1.txt and @file2.txt"; | |
| 71 | + const command = getTestPromptV2Command(rawContent); | |
| 72 | + const requests = await getPromptV2ContextRequests(ideMessenger, command); | |
| 73 | + | |
| 74 | + expect(requests).toHaveLength(2); | |
| 75 | + expect(requests[0].provider).toBe("file"); | |
| 76 | + expect(requests[0].query).toBe(`${firstDir}/file1.txt`); | |
| 77 | + expect(requests[1].provider).toBe("file"); | |
| 78 | + expect(requests[1].query).toBe(`${firstDir}/file2.txt`); | |
| 79 | + }); | |
| 80 | +}); |
added gui/src/components/mainInput/TipTapEditor/utils/renderPromptv2.ts +69 −0
| @@ -0,0 +1,69 @@ | ||
| 1 | +import { SlashCommandDescWithSource } from "core"; | |
| 2 | +import { SUPPORTED_PROMPT_CONTEXT_PROVIDERS } from "core/promptFiles"; | |
| 3 | +import { resolveRelativePathInDir } from "core/util/ideUtils"; | |
| 4 | +import { IIdeMessenger } from "../../../../context/IdeMessenger"; | |
| 5 | +import { GetContextRequest } from "./types"; | |
| 6 | + | |
| 7 | +export async function getPromptV2ContextRequests( | |
| 8 | + ideMessenger: IIdeMessenger, | |
| 9 | + command: SlashCommandDescWithSource, | |
| 10 | +): Promise<GetContextRequest[]> { | |
| 11 | + if (!command.prompt) { | |
| 12 | + return []; | |
| 13 | + } | |
| 14 | + const workspaceDirs = await ideMessenger.ide.getWorkspaceDirs(); | |
| 15 | + const visitedFiles = new Set<string>(); | |
| 16 | + if (command.promptFile) { | |
| 17 | + visitedFiles.add(command.promptFile); | |
| 18 | + } | |
| 19 | + | |
| 20 | + const contextRequests: GetContextRequest[] = []; | |
| 21 | + | |
| 22 | + async function addContextRequestsRecursive(promptBody: string) { | |
| 23 | + // Files | |
| 24 | + const templateMatches = promptBody.matchAll(/@([^\s]+)/g); | |
| 25 | + for (const match of templateMatches) { | |
| 26 | + const name = match[1]; | |
| 27 | + | |
| 28 | + if (SUPPORTED_PROMPT_CONTEXT_PROVIDERS.includes(name)) { | |
| 29 | + contextRequests.push({ | |
| 30 | + provider: name, | |
| 31 | + }); | |
| 32 | + continue; | |
| 33 | + } | |
| 34 | + | |
| 35 | + // URLs | |
| 36 | + if (name.startsWith("http")) { | |
| 37 | + contextRequests.push({ | |
| 38 | + provider: "url", | |
| 39 | + query: name, | |
| 40 | + }); | |
| 41 | + continue; | |
| 42 | + } | |
| 43 | + | |
| 44 | + // Files | |
| 45 | + const resolvedFileUri = await resolveRelativePathInDir( | |
| 46 | + match[1], | |
| 47 | + ideMessenger.ide, | |
| 48 | + workspaceDirs, | |
| 49 | + ); | |
| 50 | + if (resolvedFileUri) { | |
| 51 | + const contents = await ideMessenger.ide.readFile(resolvedFileUri); | |
| 52 | + if (name.endsWith(".prompt")) { | |
| 53 | + if (visitedFiles.has(resolvedFileUri)) { | |
| 54 | + return []; | |
| 55 | + } | |
| 56 | + visitedFiles.add(resolvedFileUri); | |
| 57 | + // As well as any context providers it references | |
| 58 | + await addContextRequestsRecursive(contents); | |
| 59 | + } | |
| 60 | + contextRequests.push({ | |
| 61 | + provider: "file", | |
| 62 | + query: resolvedFileUri, | |
| 63 | + }); | |
| 64 | + } | |
| 65 | + } | |
| 66 | + } | |
| 67 | + await addContextRequestsRecursive(command.prompt); | |
| 68 | + return contextRequests; | |
| 69 | +} |
added gui/src/components/mainInput/TipTapEditor/utils/renderSlashCommand.ts +145 −0
| @@ -0,0 +1,145 @@ | ||
| 1 | +import { MessagePart, RangeInFile, SlashCommandDescWithSource } from "core"; | |
| 2 | +import { stripImages } from "core/util/messageContent"; | |
| 3 | +import { IIdeMessenger } from "../../../../context/IdeMessenger"; | |
| 4 | +import { renderMcpPrompt } from "./renderMcpPrompt"; | |
| 5 | +import { getRenderedV1Prompt } from "./renderPromptv1"; | |
| 6 | +import { getPromptV2ContextRequests } from "./renderPromptv2"; | |
| 7 | +import { GetContextRequest } from "./types"; | |
| 8 | + | |
| 9 | +/* | |
| 10 | +Slash commands can come from many sources. Render based on the source. | |
| 11 | +*/ | |
| 12 | +export async function renderSlashCommandPrompt( | |
| 13 | + ideMessenger: IIdeMessenger, | |
| 14 | + commandName: string | undefined, | |
| 15 | + parts: MessagePart[], | |
| 16 | + availableSlashCommands: SlashCommandDescWithSource[], | |
| 17 | + selectedCode: RangeInFile[], | |
| 18 | +): Promise<{ | |
| 19 | + slashedParts: MessagePart[]; | |
| 20 | + legacyCommandWithInput?: { | |
| 21 | + command: SlashCommandDescWithSource; | |
| 22 | + input: string; | |
| 23 | + }; | |
| 24 | + contextRequests: GetContextRequest[]; | |
| 25 | +}> { | |
| 26 | + const NO_COMMAND = { | |
| 27 | + slashedParts: parts, | |
| 28 | + legacyCommandWithInput: undefined, | |
| 29 | + contextRequests: [], | |
| 30 | + }; | |
| 31 | + if (!commandName) { | |
| 32 | + return NO_COMMAND; | |
| 33 | + } | |
| 34 | + const command = availableSlashCommands.find((c) => c.name === commandName); | |
| 35 | + if (!command) { | |
| 36 | + return NO_COMMAND; | |
| 37 | + } | |
| 38 | + | |
| 39 | + const nonTextParts = parts.filter((part) => part.type !== "text"); | |
| 40 | + const textParts = parts.filter((part) => part.type === "text"); | |
| 41 | + const slashedParts: MessagePart[] = [...nonTextParts]; | |
| 42 | + | |
| 43 | + const userInput = stripImages(textParts).trimStart(); | |
| 44 | + | |
| 45 | + const legacyCommandWithInput = command.isLegacy | |
| 46 | + ? { | |
| 47 | + command, | |
| 48 | + input: userInput, | |
| 49 | + } | |
| 50 | + : undefined; | |
| 51 | + | |
| 52 | + const contextRequests: GetContextRequest[] = []; | |
| 53 | + | |
| 54 | + switch (command.source) { | |
| 55 | + case "built-in-legacy": | |
| 56 | + case "config-ts-slash-command": | |
| 57 | + /** | |
| 58 | + * For legacy slash commands, we simply insert the text "/{name}" in front of the message | |
| 59 | + * And then parsing for this is done in core | |
| 60 | + */ | |
| 61 | + slashedParts.push({ | |
| 62 | + type: "text", | |
| 63 | + text: `/${command.name}${command.prompt ? " " + command.prompt : ""}${userInput ? " " + userInput : ""}`, | |
| 64 | + }); | |
| 65 | + break; | |
| 66 | + case "mcp-prompt": | |
| 67 | + const renderedMcpPrompt = await renderMcpPrompt( | |
| 68 | + command, | |
| 69 | + ideMessenger, | |
| 70 | + userInput, | |
| 71 | + ); | |
| 72 | + slashedParts.push({ | |
| 73 | + type: "text", | |
| 74 | + text: renderedMcpPrompt, | |
| 75 | + }); | |
| 76 | + break; | |
| 77 | + case "prompt-file-v1": | |
| 78 | + case "prompt-file-v2": | |
| 79 | + case "yaml-prompt-block": | |
| 80 | + case "invokable-rule": | |
| 81 | + if (!command.prompt) { | |
| 82 | + console.warn(`Invalid/empty prompt from slash command ${command.name}`); | |
| 83 | + break; | |
| 84 | + } | |
| 85 | + let renderedPrompt: string; | |
| 86 | + if ( | |
| 87 | + command.source === "prompt-file-v1" || | |
| 88 | + command.prompt.includes("{{{ input }}}") | |
| 89 | + ) { | |
| 90 | + renderedPrompt = await getRenderedV1Prompt( | |
| 91 | + ideMessenger, | |
| 92 | + command, | |
| 93 | + userInput, | |
| 94 | + selectedCode, | |
| 95 | + ); | |
| 96 | + } else { | |
| 97 | + const promptFileCtxRequests = await getPromptV2ContextRequests( | |
| 98 | + ideMessenger, | |
| 99 | + command, | |
| 100 | + ); | |
| 101 | + contextRequests.push(...promptFileCtxRequests); | |
| 102 | + renderedPrompt = [command.prompt, userInput].join("\n\n").trim(); | |
| 103 | + } | |
| 104 | + | |
| 105 | + if (renderedPrompt) { | |
| 106 | + slashedParts.push({ | |
| 107 | + type: "text", | |
| 108 | + text: renderedPrompt, // Includes user input | |
| 109 | + }); | |
| 110 | + } else { | |
| 111 | + console.warn( | |
| 112 | + `Invalid/empty prompt + input from slash command ${command.name}`, | |
| 113 | + ); | |
| 114 | + } | |
| 115 | + | |
| 116 | + break; | |
| 117 | + case "built-in": | |
| 118 | + case "json-custom-command": | |
| 119 | + if (!command.prompt) { | |
| 120 | + console.warn(`Slash command ${command.name} is missing prompt`); | |
| 121 | + break; | |
| 122 | + } | |
| 123 | + let rendered = command.prompt; | |
| 124 | + if (userInput) { | |
| 125 | + rendered += `\n\n${userInput}`; | |
| 126 | + } | |
| 127 | + if (rendered) { | |
| 128 | + slashedParts.push({ | |
| 129 | + type: "text", | |
| 130 | + text: rendered, | |
| 131 | + }); | |
| 132 | + } else { | |
| 133 | + console.warn( | |
| 134 | + `Invalid/empty prompt + input from slash command ${command.name}`, | |
| 135 | + ); | |
| 136 | + } | |
| 137 | + default: | |
| 138 | + break; | |
| 139 | + } | |
| 140 | + return { | |
| 141 | + slashedParts, | |
| 142 | + legacyCommandWithInput, | |
| 143 | + contextRequests, | |
| 144 | + }; | |
| 145 | +} |
modified gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts +112 −226
| @@ -1,7 +1,4 @@ | ||
| 1 | 1 | import { Dispatch } from "@reduxjs/toolkit"; |
| 2 | -import Image from "@tiptap/extension-image"; | |
| 3 | -import { Paragraph } from "@tiptap/extension-paragraph"; | |
| 4 | -import { Text } from "@tiptap/extension-text"; | |
| 5 | 2 | import { JSONContent } from "@tiptap/react"; |
| 6 | 3 | import { |
| 7 | 4 | ContextItemWithId, |
| @@ -10,44 +7,35 @@ | ||
| 10 | 7 | MessageContent, |
| 11 | 8 | MessagePart, |
| 12 | 9 | RangeInFile, |
| 13 | - SlashCommandDescription, | |
| 14 | - TextMessagePart, | |
| 10 | + SlashCommandDescWithSource, | |
| 15 | 11 | } from "core"; |
| 16 | -import { ctxItemToRifWithContents } from "core/commands/util"; | |
| 17 | -import { renderChatMessage, stripImages } from "core/util/messageContent"; | |
| 18 | -import { getUriFileExtension } from "core/util/uri"; | |
| 12 | +import { stripImages } from "core/util/messageContent"; | |
| 19 | 13 | import { IIdeMessenger } from "../../../../context/IdeMessenger"; |
| 20 | 14 | import { setIsGatheringContext } from "../../../../redux/slices/sessionSlice"; |
| 21 | -import { CodeBlock, Mention, PromptBlock } from "../extensions"; | |
| 22 | - | |
| 23 | -interface MentionAttrs { | |
| 24 | - label: string; | |
| 25 | - id: string; | |
| 26 | - itemType?: string; | |
| 27 | - query?: string; | |
| 28 | -} | |
| 15 | +import { processEditorContent } from "./processEditorContent"; | |
| 16 | +import { renderSlashCommandPrompt } from "./renderSlashCommand"; | |
| 17 | +import { GetContextRequest } from "./types"; | |
| 29 | 18 | |
| 30 | 19 | interface ResolveEditorContentInput { |
| 31 | 20 | editorState: JSONContent; |
| 32 | 21 | modifiers: InputModifiers; |
| 33 | 22 | ideMessenger: IIdeMessenger; |
| 34 | 23 | defaultContextProviders: DefaultContextProvider[]; |
| 35 | - availableSlashCommands: SlashCommandDescription[]; | |
| 24 | + availableSlashCommands: SlashCommandDescWithSource[]; | |
| 36 | 25 | dispatch: Dispatch; |
| 37 | 26 | } |
| 38 | 27 | |
| 39 | -type ResolveEditorContentOutput = [ | |
| 40 | - ContextItemWithId[], | |
| 41 | - RangeInFile[], | |
| 42 | - MessageContent, | |
| 43 | - ( | |
| 28 | +interface ResolveEditorContentOutput { | |
| 29 | + selectedContextItems: ContextItemWithId[]; | |
| 30 | + selectedCode: RangeInFile[]; | |
| 31 | + content: MessageContent; | |
| 32 | + legacyCommandWithInput: | |
| 44 | 33 | | { |
| 45 | - command: SlashCommandDescription; | |
| 34 | + command: SlashCommandDescWithSource; | |
| 46 | 35 | input: string; |
| 47 | 36 | } |
| 48 | - | undefined | |
| 49 | - ), | |
| 50 | -]; | |
| 37 | + | undefined; | |
| 38 | +} | |
| 51 | 39 | |
| 52 | 40 | /** |
| 53 | 41 | * This function converts the input from the editor to a string, resolving any context items |
| @@ -61,26 +49,43 @@ | ||
| 61 | 49 | availableSlashCommands, |
| 62 | 50 | dispatch, |
| 63 | 51 | }: ResolveEditorContentInput): Promise<ResolveEditorContentOutput> { |
| 64 | - const { parts, contextItemAttrs, selectedCode, slashCommandName } = | |
| 65 | - processEditorContent(editorState); | |
| 66 | - | |
| 67 | - const slashCommandWithInput = processSlashCommand( | |
| 52 | + const { | |
| 53 | + parts, | |
| 54 | + contextRequests: editorContextRequests, | |
| 55 | + selectedCode, | |
| 56 | + slashCommandName, | |
| 57 | + } = processEditorContent(editorState); | |
| 58 | + | |
| 59 | + const { | |
| 60 | + slashedParts, | |
| 61 | + contextRequests: slashContextRequests, | |
| 62 | + legacyCommandWithInput, | |
| 63 | + } = await renderSlashCommandPrompt( | |
| 64 | + ideMessenger, | |
| 68 | 65 | slashCommandName, |
| 69 | - availableSlashCommands, | |
| 70 | 66 | parts, |
| 67 | + availableSlashCommands, | |
| 68 | + selectedCode, | |
| 71 | 69 | ); |
| 72 | 70 | |
| 73 | - const shouldGatherContext = modifiers.useCodebase || slashCommandWithInput; | |
| 71 | + const contextRequests = [...editorContextRequests, ...slashContextRequests]; | |
| 72 | + | |
| 73 | + const shouldGatherContext = | |
| 74 | + defaultContextProviders.length > 0 || | |
| 75 | + modifiers.useCodebase || | |
| 76 | + !modifiers.noContext || | |
| 77 | + contextRequests.length > 0; | |
| 78 | + | |
| 74 | 79 | if (shouldGatherContext) { |
| 75 | 80 | dispatch(setIsGatheringContext(true)); |
| 76 | 81 | } |
| 77 | 82 | |
| 78 | - const contextItems = await gatherContextItems({ | |
| 79 | - contextItemAttrs, | |
| 83 | + const selectedContextItems = await gatherContextItems({ | |
| 84 | + contextRequests, | |
| 80 | 85 | modifiers, |
| 81 | 86 | ideMessenger, |
| 82 | 87 | defaultContextProviders, |
| 83 | - parts, | |
| 88 | + parts: slashedParts, | |
| 84 | 89 | selectedCode, |
| 85 | 90 | }); |
| 86 | 91 | |
| @@ -88,140 +93,11 @@ | ||
| 88 | 93 | dispatch(setIsGatheringContext(false)); |
| 89 | 94 | } |
| 90 | 95 | |
| 91 | - return [contextItems, selectedCode, parts, slashCommandWithInput]; | |
| 92 | -} | |
| 93 | - | |
| 94 | -/** | |
| 95 | - * Processes editor content and extracts parts, context items, code, and slash commands | |
| 96 | - */ | |
| 97 | -function processEditorContent(editorState: JSONContent) { | |
| 98 | - const contextItemAttrs: MentionAttrs[] = []; | |
| 99 | - const selectedCode: RangeInFile[] = []; | |
| 100 | - let slashCommandName: string | undefined; | |
| 101 | - | |
| 102 | - const parts = (editorState?.content || []).reduce<MessagePart[]>( | |
| 103 | - (parts, p) => { | |
| 104 | - switch (p.type) { | |
| 105 | - case PromptBlock.name: { | |
| 106 | - slashCommandName = resvolePromptBlock(p); | |
| 107 | - } | |
| 108 | - | |
| 109 | - case Paragraph.name: { | |
| 110 | - const [text, ctxItems] = resolveParagraph(p); | |
| 111 | - | |
| 112 | - contextItemAttrs.push(...ctxItems); | |
| 113 | - | |
| 114 | - if (!text) return parts; | |
| 115 | - | |
| 116 | - // Merge with previous text part if possible | |
| 117 | - if (parts[parts.length - 1]?.type === "text") { | |
| 118 | - (parts[parts.length - 1] as TextMessagePart).text += "\n" + text; | |
| 119 | - return parts; | |
| 120 | - } | |
| 121 | - | |
| 122 | - return [...parts, { type: "text", text }]; | |
| 123 | - } | |
| 124 | - | |
| 125 | - case CodeBlock.name: { | |
| 126 | - if (!p.attrs?.item) { | |
| 127 | - console.warn("codeBlock has no item attribute"); | |
| 128 | - return parts; | |
| 129 | - } | |
| 130 | - | |
| 131 | - const contextItem = p.attrs.item as ContextItemWithId; | |
| 132 | - const rif = ctxItemToRifWithContents(contextItem, true); | |
| 133 | - selectedCode.push(rif); | |
| 134 | - | |
| 135 | - // If editing, only include in selectedCode | |
| 136 | - if (contextItem.editing) { | |
| 137 | - return parts; | |
| 138 | - } | |
| 139 | - | |
| 140 | - const fileExtension = getUriFileExtension(rif.filepath); | |
| 141 | - const codeText = [ | |
| 142 | - "\n\n```", | |
| 143 | - fileExtension, | |
| 144 | - " ", | |
| 145 | - contextItem.description, | |
| 146 | - "\n", | |
| 147 | - contextItem.content, | |
| 148 | - "\n```", | |
| 149 | - ].join(""); | |
| 150 | - | |
| 151 | - if (parts[parts.length - 1]?.type === "text") { | |
| 152 | - (parts[parts.length - 1] as TextMessagePart).text += | |
| 153 | - "\n" + codeText; | |
| 154 | - return parts; | |
| 155 | - } | |
| 156 | - | |
| 157 | - return [...parts, { type: "text", text: codeText }]; | |
| 158 | - } | |
| 159 | - | |
| 160 | - case Image.name: { | |
| 161 | - return [ | |
| 162 | - ...parts, | |
| 163 | - { | |
| 164 | - type: "imageUrl", | |
| 165 | - imageUrl: { url: p.attrs?.src }, | |
| 166 | - }, | |
| 167 | - ]; | |
| 168 | - } | |
| 169 | - | |
| 170 | - default: { | |
| 171 | - console.warn("Unexpected content type", p.type); | |
| 172 | - return parts; | |
| 173 | - } | |
| 174 | - } | |
| 175 | - }, | |
| 176 | - [], | |
| 177 | - ); | |
| 178 | - | |
| 179 | - return { parts, contextItemAttrs, selectedCode, slashCommandName }; | |
| 180 | -} | |
| 181 | - | |
| 182 | -/** | |
| 183 | - * Processes slash commands and prepares the command with input | |
| 184 | - */ | |
| 185 | -function processSlashCommand( | |
| 186 | - slashCommandName: string | undefined, | |
| 187 | - availableSlashCommands: SlashCommandDescription[], | |
| 188 | - parts: MessagePart[], | |
| 189 | -): { command: SlashCommandDescription; input: string } | undefined { | |
| 190 | - if (!slashCommandName) return; | |
| 191 | - | |
| 192 | - const command = availableSlashCommands.find( | |
| 193 | - (c) => c.name === slashCommandName, | |
| 194 | - ); | |
| 195 | - | |
| 196 | - if (!command) return; | |
| 197 | - | |
| 198 | - const lastTextIndex = findLastIndex(parts, (part) => part.type === "text"); | |
| 199 | - const lastTextPart = parts[lastTextIndex] as TextMessagePart; | |
| 200 | - | |
| 201 | - const originalPrompt = command.prompt ? " " + command.prompt : ""; | |
| 202 | - | |
| 203 | - let input: string; | |
| 204 | - | |
| 205 | - /** | |
| 206 | - * Although we no longer render slash command <span /> tags from the editor, | |
| 207 | - * we are inserting a slash command style text back into the text here. | |
| 208 | - * This is a a hack, but there's a number of assumptions in `core` that there | |
| 209 | - * is slash command text at the beginning of the text in order to process slash commands. | |
| 210 | - */ | |
| 211 | - if (lastTextPart) { | |
| 212 | - input = renderChatMessage({ | |
| 213 | - role: "user", | |
| 214 | - content: lastTextPart.text, | |
| 215 | - }).trimStart(); | |
| 216 | - lastTextPart.text = `/${command.name}${originalPrompt} ${lastTextPart.text}`; | |
| 217 | - } else { | |
| 218 | - input = ""; | |
| 219 | - parts.push({ type: "text", text: `/${command.name}${originalPrompt}` }); | |
| 220 | - } | |
| 221 | - | |
| 222 | 96 | return { |
| 223 | - command, | |
| 224 | - input, | |
| 97 | + selectedContextItems, | |
| 98 | + selectedCode, | |
| 99 | + content: slashedParts, | |
| 100 | + legacyCommandWithInput, | |
| 225 | 101 | }; |
| 226 | 102 | } |
| 227 | 103 | |
| @@ -229,26 +105,44 @@ | ||
| 229 | 105 | * Gathers context items from various sources |
| 230 | 106 | */ |
| 231 | 107 | async function gatherContextItems({ |
| 232 | - contextItemAttrs, | |
| 108 | + contextRequests, | |
| 233 | 109 | modifiers, |
| 234 | 110 | ideMessenger, |
| 235 | 111 | defaultContextProviders, |
| 236 | 112 | parts, |
| 237 | 113 | selectedCode, |
| 238 | 114 | }: { |
| 239 | - contextItemAttrs: MentionAttrs[]; | |
| 115 | + contextRequests: GetContextRequest[]; | |
| 240 | 116 | modifiers: InputModifiers; |
| 241 | 117 | ideMessenger: IIdeMessenger; |
| 242 | 118 | defaultContextProviders: DefaultContextProvider[]; |
| 243 | 119 | parts: MessagePart[]; |
| 244 | 120 | selectedCode: RangeInFile[]; |
| 245 | 121 | }): Promise<ContextItemWithId[]> { |
| 122 | + const defaultRequests: GetContextRequest[] = defaultContextProviders.map( | |
| 123 | + (def) => ({ | |
| 124 | + provider: def.name, | |
| 125 | + query: def.query, | |
| 126 | + }), | |
| 127 | + ); | |
| 128 | + const withDefaults = [...contextRequests, ...defaultRequests]; | |
| 129 | + const deduplicatedInputs = withDefaults.reduce<GetContextRequest[]>( | |
| 130 | + (acc, item) => { | |
| 131 | + if ( | |
| 132 | + !acc.some((i) => i.provider === item.provider && i.query === item.query) | |
| 133 | + ) { | |
| 134 | + acc.push(item); | |
| 135 | + } | |
| 136 | + return acc; | |
| 137 | + }, | |
| 138 | + [], | |
| 139 | + ); | |
| 246 | 140 | let contextItems: ContextItemWithId[] = []; |
| 247 | 141 | |
| 248 | 142 | // Process context item attributes |
| 249 | - for (const item of contextItemAttrs) { | |
| 143 | + for (const item of deduplicatedInputs) { | |
| 250 | 144 | const result = await ideMessenger.request("context/getContextItems", { |
| 251 | - name: item.itemType === "contextProvider" ? item.id : item.itemType!, | |
| 145 | + name: item.provider, | |
| 252 | 146 | query: item.query ?? "", |
| 253 | 147 | fullInput: stripImages(parts), |
| 254 | 148 | selectedCode, |
| @@ -259,7 +153,10 @@ | ||
| 259 | 153 | } |
| 260 | 154 | |
| 261 | 155 | // cmd+enter to use codebase |
| 262 | - if (modifiers.useCodebase) { | |
| 156 | + if ( | |
| 157 | + modifiers.useCodebase && | |
| 158 | + !deduplicatedInputs.some((item) => item.provider === "codebase") | |
| 159 | + ) { | |
| 263 | 160 | const result = await ideMessenger.request("context/getContextItems", { |
| 264 | 161 | name: "codebase", |
| 265 | 162 | query: "", |
| @@ -272,62 +169,51 @@ | ||
| 272 | 169 | } |
| 273 | 170 | } |
| 274 | 171 | |
| 275 | - // Include default context providers | |
| 276 | - const defaultContextItems = await Promise.all( | |
| 277 | - defaultContextProviders.map(async (provider) => { | |
| 278 | - const result = await ideMessenger.request("context/getContextItems", { | |
| 279 | - name: provider.name, | |
| 280 | - query: provider.query ?? "", | |
| 281 | - fullInput: stripImages(parts), | |
| 282 | - selectedCode, | |
| 283 | - }); | |
| 284 | - if (result.status === "success") { | |
| 285 | - return result.content; | |
| 286 | - } else { | |
| 287 | - return []; | |
| 172 | + // noContext modifier adds currently open file if it's not already present | |
| 173 | + if ( | |
| 174 | + !modifiers.noContext && | |
| 175 | + !deduplicatedInputs.some((item) => item.provider === "currentFile") | |
| 176 | + ) { | |
| 177 | + const currentFileResponse = await ideMessenger.request( | |
| 178 | + "context/getContextItems", | |
| 179 | + { | |
| 180 | + name: "currentFile", | |
| 181 | + query: "non-mention-usage", | |
| 182 | + fullInput: "", | |
| 183 | + selectedCode: [], | |
| 184 | + }, | |
| 185 | + ); | |
| 186 | + if (currentFileResponse.status === "success") { | |
| 187 | + const currentFile = currentFileResponse.content[0]; | |
| 188 | + if (currentFile.uri?.value) { | |
| 189 | + currentFile.id = { | |
| 190 | + providerTitle: "file", | |
| 191 | + itemId: currentFile.uri.value, | |
| 192 | + }; | |
| 193 | + contextItems.unshift(currentFile); | |
| 288 | 194 | } |
| 289 | - }), | |
| 290 | - ); | |
| 291 | - contextItems.push(...defaultContextItems.flat()); | |
| 292 | - | |
| 293 | - return contextItems; | |
| 294 | -} | |
| 295 | - | |
| 296 | -function findLastIndex<T>( | |
| 297 | - array: T[], | |
| 298 | - predicate: (value: T, index: number, obj: T[]) => boolean, | |
| 299 | -): number { | |
| 300 | - for (let i = array.length - 1; i >= 0; i--) { | |
| 301 | - if (predicate(array[i], i, array)) { | |
| 302 | - return i; | |
| 303 | 195 | } |
| 304 | 196 | } |
| 305 | - return -1; // if no element satisfies the predicate | |
| 306 | -} | |
| 307 | - | |
| 308 | -function resvolePromptBlock(p: JSONContent): string | undefined { | |
| 309 | - return p.attrs?.item.name; | |
| 310 | -} | |
| 311 | 197 | |
| 312 | -function resolveParagraph(p: JSONContent): [string, MentionAttrs[]] { | |
| 313 | - const contextItems: MentionAttrs[] = []; | |
| 314 | - | |
| 315 | - const text = (p.content || []) | |
| 316 | - .map((child) => { | |
| 317 | - switch (child.type) { | |
| 318 | - case Text.name: | |
| 319 | - return child.text; | |
| 320 | - case Mention.name: | |
| 321 | - contextItems.push(child.attrs as MentionAttrs); | |
| 322 | - return child.attrs?.renderInlineAs ?? child.attrs?.label; | |
| 323 | - | |
| 324 | - default: | |
| 325 | - console.warn("Unexpected child type", child.type); | |
| 326 | - return ""; | |
| 198 | + // Deduplicates based on either providerTitle + itemId or uri type + value | |
| 199 | + const deduplicatedOutputs = contextItems.reduce<ContextItemWithId[]>( | |
| 200 | + (acc, item) => { | |
| 201 | + if ( | |
| 202 | + !acc.some( | |
| 203 | + (i) => | |
| 204 | + (i.id.providerTitle === item.id.providerTitle && | |
| 205 | + i.id.itemId === item.id.itemId) || | |
| 206 | + (i.uri && | |
| 207 | + item.uri && | |
| 208 | + i.uri.type === item.uri.type && | |
| 209 | + i.uri.value === item.uri.value), | |
| 210 | + ) | |
| 211 | + ) { | |
| 212 | + acc.push(item); | |
| 327 | 213 | } |
| 328 | - }) | |
| 329 | - .join("") | |
| 330 | - .trimStart(); | |
| 331 | - | |
| 332 | - return [text, contextItems]; | |
| 214 | + return acc; | |
| 215 | + }, | |
| 216 | + [], | |
| 217 | + ); | |
| 218 | + return deduplicatedOutputs; | |
| 333 | 219 | } |
added gui/src/components/mainInput/TipTapEditor/utils/types.ts +4 −0
| @@ -0,0 +1,4 @@ | ||
| 1 | +export interface GetContextRequest { | |
| 2 | + provider: string; | |
| 3 | + query?: string; | |
| 4 | +} |
modified gui/src/context/MockIdeMessenger.ts +133 −70
| @@ -1,7 +1,6 @@ | ||
| 1 | -import { IDE, PromptLog } from "core"; | |
| 1 | +import { ChatMessage, IDE, PromptLog } from "core"; | |
| 2 | 2 | import { AuthType } from "core/control-plane/AuthTypes"; |
| 3 | 3 | import { |
| 4 | - FromIdeProtocol, | |
| 5 | 4 | FromWebviewProtocol, |
| 6 | 5 | ToCoreProtocol, |
| 7 | 6 | ToWebviewProtocol, |
| @@ -13,73 +12,92 @@ | ||
| 13 | 12 | GeneratorYieldType, |
| 14 | 13 | WebviewSingleProtocolMessage, |
| 15 | 14 | } from "core/protocol/util"; |
| 16 | -import { ChatMessage } from "../redux/store"; | |
| 17 | 15 | import { IIdeMessenger } from "./IdeMessenger"; |
| 18 | 16 | |
| 19 | -async function defaultMockHandleMessage<T extends keyof FromWebviewProtocol>( | |
| 20 | - messageType: T, | |
| 21 | - data: FromWebviewProtocol[T][0], | |
| 22 | -): Promise<FromWebviewProtocol[T][1]> { | |
| 23 | - function returnFor<K extends keyof FromWebviewProtocol>( | |
| 24 | - _: K, | |
| 25 | - value: FromWebviewProtocol[K][1], | |
| 26 | - ): FromWebviewProtocol[T][1] { | |
| 27 | - return value as unknown as FromWebviewProtocol[T][1]; | |
| 28 | - } | |
| 17 | +type MockResponses = Partial<{ | |
| 18 | + [K in keyof FromWebviewProtocol]: FromWebviewProtocol[K][1]; | |
| 19 | +}>; | |
| 29 | 20 | |
| 30 | - switch (messageType) { | |
| 31 | - case "history/list": | |
| 32 | - return returnFor("history/list", [ | |
| 33 | - { | |
| 34 | - title: "Session 1", | |
| 35 | - sessionId: "session-1", | |
| 36 | - dateCreated: new Date().toString(), | |
| 37 | - workspaceDirectory: "/tmp", | |
| 38 | - }, | |
| 39 | - ]); | |
| 40 | - case "getControlPlaneSessionInfo": | |
| 41 | - return returnFor("getControlPlaneSessionInfo", { | |
| 42 | - AUTH_TYPE: AuthType.WorkOsStaging, | |
| 43 | - accessToken: "", | |
| 44 | - account: { | |
| 45 | - label: "", | |
| 46 | - id: "", | |
| 47 | - }, | |
| 48 | - }); | |
| 49 | - case "config/getSerializedProfileInfo": | |
| 50 | - return returnFor("config/getSerializedProfileInfo", { | |
| 51 | - organizations: [], | |
| 52 | - profileId: "test-profile", | |
| 53 | - result: { | |
| 54 | - config: undefined, | |
| 55 | - errors: [], | |
| 56 | - configLoadInterrupted: false, | |
| 57 | - }, | |
| 58 | - selectedOrgId: "local", | |
| 59 | - }); | |
| 60 | - default: | |
| 61 | - throw new Error(`Unknown message type ${messageType}`); | |
| 62 | - } | |
| 63 | -} | |
| 21 | +export type MockResponseHandler<T extends keyof FromWebviewProtocol> = ( | |
| 22 | + input: FromWebviewProtocol[T][0], | |
| 23 | +) => Promise<FromWebviewProtocol[T][1]>; | |
| 64 | 24 | |
| 25 | +type MockResponseHandlers = Partial<{ | |
| 26 | + [K in keyof FromWebviewProtocol]: MockResponseHandler<K>; | |
| 27 | +}>; | |
| 28 | + | |
| 29 | +const DEFAULT_MOCK_CORE_RESPONSES: MockResponses = { | |
| 30 | + fileExists: true, | |
| 31 | + getCurrentFile: { | |
| 32 | + isUntitled: false, | |
| 33 | + contents: "Current file contents", | |
| 34 | + path: "file:///Users/user/workspace1/current_file.py", | |
| 35 | + }, | |
| 36 | + "controlPlane/getFreeTrialStatus": { | |
| 37 | + autocompleteLimit: 1000, | |
| 38 | + optedInToFreeTrial: false, | |
| 39 | + chatLimit: 1000, | |
| 40 | + autocompleteCount: 0, | |
| 41 | + chatCount: 0, | |
| 42 | + }, | |
| 43 | + getWorkspaceDirs: [ | |
| 44 | + "file:///Users/user/workspace1", | |
| 45 | + "file:///Users/user/workspace2", | |
| 46 | + ], | |
| 47 | + "history/list": [ | |
| 48 | + { | |
| 49 | + title: "Session 1", | |
| 50 | + sessionId: "session-1", | |
| 51 | + dateCreated: new Date().toString(), | |
| 52 | + workspaceDirectory: "/tmp", | |
| 53 | + }, | |
| 54 | + ], | |
| 55 | + "history/save": undefined, | |
| 56 | + getControlPlaneSessionInfo: { | |
| 57 | + AUTH_TYPE: AuthType.WorkOsStaging, | |
| 58 | + accessToken: "", | |
| 59 | + account: { | |
| 60 | + label: "", | |
| 61 | + id: "", | |
| 62 | + }, | |
| 63 | + }, | |
| 64 | + "config/getSerializedProfileInfo": { | |
| 65 | + organizations: [], | |
| 66 | + profileId: "test-profile", | |
| 67 | + result: { | |
| 68 | + config: undefined, | |
| 69 | + errors: [], | |
| 70 | + configLoadInterrupted: false, | |
| 71 | + }, | |
| 72 | + selectedOrgId: "local", | |
| 73 | + }, | |
| 74 | + "chatDescriber/describe": "Session summary", | |
| 75 | + applyToFile: undefined, | |
| 76 | + acceptDiff: undefined, | |
| 77 | + readFile: "File contents", | |
| 78 | +}; | |
| 79 | + | |
| 80 | +const DEFAULT_CHAT_RESPONSE: ChatMessage[] = [ | |
| 81 | + { | |
| 82 | + role: "assistant", | |
| 83 | + content: "This is a test", | |
| 84 | + }, | |
| 85 | +]; | |
| 65 | 86 | export class MockIdeMessenger implements IIdeMessenger { |
| 66 | 87 | ide: IDE; |
| 67 | - private messageHandlers: Map< | |
| 68 | - keyof FromIdeProtocol, | |
| 69 | - Array<(data: any) => void> | |
| 70 | - > = new Map(); | |
| 71 | 88 | |
| 72 | 89 | constructor() { |
| 73 | 90 | this.ide = new MessageIde( |
| 74 | - (messageType, data) => { | |
| 75 | - throw new Error("Not implemented"); | |
| 91 | + async (messageType, data) => { | |
| 92 | + const response = await this.request.bind(this)(messageType, data); | |
| 93 | + if (response.status === "error") { | |
| 94 | + throw new Error(response.error); | |
| 95 | + } else { | |
| 96 | + return response.content; | |
| 97 | + } | |
| 76 | 98 | }, |
| 77 | 99 | (messageType, callback) => { |
| 78 | - // Store the callback in our handlers map | |
| 79 | - if (!this.messageHandlers.has(messageType)) { | |
| 80 | - this.messageHandlers.set(messageType, []); | |
| 81 | - } | |
| 82 | - this.messageHandlers.get(messageType)?.push(callback); | |
| 100 | + return; | |
| 83 | 101 | }, |
| 84 | 102 | ); |
| 85 | 103 | } |
| @@ -109,16 +127,39 @@ | ||
| 109 | 127 | ); |
| 110 | 128 | } |
| 111 | 129 | |
| 112 | - async *llmStreamChat( | |
| 113 | - msg: ToCoreProtocol["llm/streamChat"][0], | |
| 114 | - cancelToken: AbortSignal, | |
| 115 | - ): AsyncGenerator<ChatMessage[], PromptLog | undefined> { | |
| 116 | - yield [ | |
| 130 | + responses: MockResponses = { ...DEFAULT_MOCK_CORE_RESPONSES }; | |
| 131 | + responseHandlers: MockResponseHandlers = {}; | |
| 132 | + chatResponse: ChatMessage[] = DEFAULT_CHAT_RESPONSE; | |
| 133 | + chatStreamDelay: number = 0; | |
| 134 | + setChatResponseText(text: string): void { | |
| 135 | + this.chatResponse = [ | |
| 117 | 136 | { |
| 118 | 137 | role: "assistant", |
| 119 | - content: "This is a test", | |
| 138 | + content: text, | |
| 120 | 139 | }, |
| 121 | 140 | ]; |
| 141 | + } | |
| 142 | + | |
| 143 | + async *llmStreamChat( | |
| 144 | + msg: ToCoreProtocol["llm/streamChat"][0], | |
| 145 | + cancelToken: AbortSignal, | |
| 146 | + ): AsyncGenerator<ChatMessage[], PromptLog | undefined> { | |
| 147 | + for (const response of this.chatResponse) { | |
| 148 | + if (cancelToken.aborted) { | |
| 149 | + console.log("MockIdeMessenger: Stream aborted"); | |
| 150 | + return undefined; | |
| 151 | + } | |
| 152 | + console.log( | |
| 153 | + "MockIdeMessenger: Yielding chunk", | |
| 154 | + JSON.stringify(response, null, 2), | |
| 155 | + ); | |
| 156 | + yield [response]; | |
| 157 | + if (this.chatStreamDelay > 0) { | |
| 158 | + await new Promise((resolve) => | |
| 159 | + setTimeout(resolve, this.chatStreamDelay), | |
| 160 | + ); | |
| 161 | + } | |
| 162 | + } | |
| 122 | 163 | return undefined; |
| 123 | 164 | } |
| 124 | 165 | |
| @@ -133,12 +174,27 @@ | ||
| 133 | 174 | messageType: T, |
| 134 | 175 | data: FromWebviewProtocol[T][0], |
| 135 | 176 | ): Promise<WebviewSingleProtocolMessage<T>> { |
| 136 | - const content = await defaultMockHandleMessage(messageType, data); | |
| 137 | - return { | |
| 138 | - status: "success", | |
| 139 | - content, | |
| 140 | - done: true, | |
| 141 | - }; | |
| 177 | + if (this.responseHandlers[messageType]) { | |
| 178 | + const content = await this.responseHandlers[messageType](data); | |
| 179 | + return { | |
| 180 | + status: "success", | |
| 181 | + content, | |
| 182 | + done: true, | |
| 183 | + }; | |
| 184 | + } | |
| 185 | + if (messageType in this.responses) { | |
| 186 | + const content = this.responses[messageType]; | |
| 187 | + return { | |
| 188 | + status: "success", | |
| 189 | + content, | |
| 190 | + done: true, | |
| 191 | + }; | |
| 192 | + } | |
| 193 | + console.error(messageType); | |
| 194 | + throw new Error( | |
| 195 | + "MockIdeMessenger: No response handler or response defined for " + | |
| 196 | + messageType, | |
| 197 | + ); | |
| 142 | 198 | } |
| 143 | 199 | |
| 144 | 200 | respond<T extends keyof ToWebviewProtocol>( |
| @@ -157,4 +213,11 @@ | ||
| 157 | 213 | > { |
| 158 | 214 | return undefined; |
| 159 | 215 | } |
| 216 | + | |
| 217 | + resetMocks(): void { | |
| 218 | + this.responses = { ...DEFAULT_MOCK_CORE_RESPONSES }; | |
| 219 | + this.responseHandlers = {}; | |
| 220 | + this.chatResponse = DEFAULT_CHAT_RESPONSE; | |
| 221 | + this.chatStreamDelay = 0; | |
| 222 | + } | |
| 160 | 223 | } |
modified gui/src/hooks/ParallelListeners.tsx +38 −18
| @@ -20,6 +20,7 @@ | ||
| 20 | 20 | import { |
| 21 | 21 | acceptToolCall, |
| 22 | 22 | addContextItemsAtIndex, |
| 23 | + selectCurrentToolCall, | |
| 23 | 24 | setHasReasoningEnabled, |
| 24 | 25 | updateApplyState, |
| 25 | 26 | } from "../redux/slices/sessionSlice"; |
| @@ -244,6 +245,10 @@ | ||
| 244 | 245 | dispatch(updateIndexingStatus(data)); |
| 245 | 246 | }); |
| 246 | 247 | |
| 248 | + const autoAcceptEditToolDiffs = useAppSelector( | |
| 249 | + (store) => store.config.config.ui?.autoAcceptEditToolDiffs, | |
| 250 | + ); | |
| 251 | + const currentToolCall = useAppSelector(selectCurrentToolCall); | |
| 247 | 252 | useWebviewListener( |
| 248 | 253 | "updateApplyState", |
| 249 | 254 | async (state) => { |
| @@ -259,30 +264,45 @@ | ||
| 259 | 264 | |
| 260 | 265 | // Handle apply status updates that are associated with current tool call |
| 261 | 266 | if ( |
| 262 | - state.status === "closed" && | |
| 263 | 267 | currentToolCallApplyState && |
| 264 | 268 | currentToolCallApplyState.streamId === state.streamId |
| 265 | 269 | ) { |
| 266 | - // const output: ContextItem = { | |
| 267 | - // name: "Edit tool output", | |
| 268 | - // content: "Completed edit", | |
| 269 | - // description: "", | |
| 270 | - // }; | |
| 271 | - dispatch( | |
| 272 | - acceptToolCall({ | |
| 273 | - toolCallId: currentToolCallApplyState.toolCallId!, | |
| 274 | - }), | |
| 275 | - ); | |
| 276 | - // dispatch(setToolCallOutput([])); | |
| 277 | - void dispatch( | |
| 278 | - streamResponseAfterToolCall({ | |
| 279 | - toolCallId: currentToolCallApplyState.toolCallId!, | |
| 280 | - }), | |
| 281 | - ); | |
| 270 | + if (state.status === "done" && autoAcceptEditToolDiffs) { | |
| 271 | + console.log("AUTO ACCEPTED"); | |
| 272 | + ideMessenger.post("acceptDiff", { | |
| 273 | + streamId: state.streamId, | |
| 274 | + filepath: state.filepath, | |
| 275 | + }); | |
| 276 | + } | |
| 277 | + if (state.status === "closed") { | |
| 278 | + if (currentToolCall?.status !== "canceled") { | |
| 279 | + dispatch( | |
| 280 | + acceptToolCall({ | |
| 281 | + toolCallId: currentToolCallApplyState.toolCallId!, | |
| 282 | + }), | |
| 283 | + ); | |
| 284 | + } | |
| 285 | + // const output: ContextItem = { | |
| 286 | + // name: "Edit tool output", | |
| 287 | + // content: "Completed edit", | |
| 288 | + // description: "", | |
| 289 | + // }; | |
| 290 | + // dispatch(setToolCallOutput([])); | |
| 291 | + void dispatch( | |
| 292 | + streamResponseAfterToolCall({ | |
| 293 | + toolCallId: currentToolCallApplyState.toolCallId!, | |
| 294 | + }), | |
| 295 | + ); | |
| 296 | + } | |
| 282 | 297 | } |
| 283 | 298 | } |
| 284 | 299 | }, |
| 285 | - [currentToolCallApplyState, history], | |
| 300 | + [ | |
| 301 | + currentToolCall, | |
| 302 | + currentToolCallApplyState, | |
| 303 | + autoAcceptEditToolDiffs, | |
| 304 | + ideMessenger, | |
| 305 | + ], | |
| 286 | 306 | ); |
| 287 | 307 | |
| 288 | 308 | useEffect(() => { |
modified gui/src/hooks/useBookmarkedSlashCommands.ts +2 −2
| @@ -1,4 +1,4 @@ | ||
| 1 | -import { SlashCommandDescription } from "core"; | |
| 1 | +import { SlashCommandDescWithSource } from "core"; | |
| 2 | 2 | import { usePostHog } from "posthog-js/react"; |
| 3 | 3 | |
| 4 | 4 | import { useAppDispatch, useAppSelector } from "../redux/hooks"; |
| @@ -17,7 +17,7 @@ | ||
| 17 | 17 | return bookmarkedCommands.includes(commandName); |
| 18 | 18 | }; |
| 19 | 19 | |
| 20 | - const toggleBookmark = (command: SlashCommandDescription) => { | |
| 20 | + const toggleBookmark = (command: SlashCommandDescWithSource) => { | |
| 21 | 21 | const isBookmarked = isCommandBookmarked(command.name); |
| 22 | 22 | |
| 23 | 23 | posthog.capture("toggle_bookmarked_slash_command", { |
deleted gui/src/pages/gui/Chat.test.tsx +0 −161
| @@ -1,161 +0,0 @@ | ||
| 1 | -import { screen, waitFor } from "@testing-library/dom"; | |
| 2 | -import { act } from "@testing-library/react"; | |
| 3 | -import { renderWithProviders } from "../../util/test/render"; | |
| 4 | -import { Chat } from "./Chat"; | |
| 5 | - | |
| 6 | -describe("Chat page test", () => { | |
| 7 | - it("should render input box", async () => { | |
| 8 | - await renderWithProviders(<Chat />); | |
| 9 | - expect(await screen.findByTestId("continue-input-box")).toBeInTheDocument(); | |
| 10 | - }); | |
| 11 | - | |
| 12 | - it("should be able to toggle modes", async () => { | |
| 13 | - await renderWithProviders(<Chat />); | |
| 14 | - expect(screen.getByText("Chat")).toBeInTheDocument(); | |
| 15 | - | |
| 16 | - // Simulate cmd+. keyboard shortcut to toggle modes | |
| 17 | - act(() => { | |
| 18 | - document.dispatchEvent( | |
| 19 | - new KeyboardEvent("keydown", { | |
| 20 | - key: ".", | |
| 21 | - metaKey: true, // cmd key on Mac | |
| 22 | - }), | |
| 23 | - ); | |
| 24 | - }); | |
| 25 | - | |
| 26 | - // Check that it switched to Agent mode | |
| 27 | - expect(await screen.findByText("Agent")).toBeInTheDocument(); | |
| 28 | - | |
| 29 | - act(() => { | |
| 30 | - document.dispatchEvent( | |
| 31 | - new KeyboardEvent("keydown", { | |
| 32 | - key: ".", | |
| 33 | - metaKey: true, // cmd key on Mac | |
| 34 | - }), | |
| 35 | - ); | |
| 36 | - }); | |
| 37 | - | |
| 38 | - // Check that it switched back to Chat mode | |
| 39 | - expect(await screen.findByText("Chat")).toBeInTheDocument(); | |
| 40 | - }); | |
| 41 | - | |
| 42 | - it.skip("should send a message and receive a response", async () => { | |
| 43 | - const { user, container } = await renderWithProviders(<Chat />); | |
| 44 | - const inputBox = await waitFor(() => | |
| 45 | - container.querySelector(".ProseMirror")!.querySelector("p"), | |
| 46 | - ); | |
| 47 | - expect(inputBox).toBeDefined(); | |
| 48 | - | |
| 49 | - const sendButton = await screen.findByTestId("submit-input-button"); | |
| 50 | - | |
| 51 | - await act(async () => { | |
| 52 | - // Focus input box | |
| 53 | - inputBox!.focus(); | |
| 54 | - | |
| 55 | - // Type message | |
| 56 | - await user.type(inputBox!, "Hello, world!"); | |
| 57 | - | |
| 58 | - sendButton.click(); | |
| 59 | - }); | |
| 60 | - expect(await screen.findByText("Hello, world!")).toBeInTheDocument(); | |
| 61 | - }); | |
| 62 | - | |
| 63 | - it("should handle apply updates and display the accept / reject all buttons", async () => { | |
| 64 | - const { ideMessenger } = await renderWithProviders(<Chat />); | |
| 65 | - | |
| 66 | - // Use queryByText which returns null when element isn't found | |
| 67 | - const acceptAllButton = screen.queryByText("Accept All"); | |
| 68 | - const rejectAllButton = screen.queryByText("Reject All"); | |
| 69 | - | |
| 70 | - // Assert that the buttons don't exist | |
| 71 | - expect(acceptAllButton).not.toBeInTheDocument(); | |
| 72 | - expect(rejectAllButton).not.toBeInTheDocument(); | |
| 73 | - | |
| 74 | - for (let i = 0; i < 5; i++) { | |
| 75 | - ideMessenger.mockMessageToWebview("updateApplyState", { | |
| 76 | - status: "streaming", | |
| 77 | - streamId: `12345`, | |
| 78 | - }); | |
| 79 | - } | |
| 80 | - | |
| 81 | - ideMessenger.mockMessageToWebview("updateApplyState", { | |
| 82 | - status: "done", | |
| 83 | - streamId: "12345", | |
| 84 | - }); | |
| 85 | - | |
| 86 | - // Wait for the buttons to appear | |
| 87 | - await waitFor(() => { | |
| 88 | - expect( | |
| 89 | - screen.getByTestId("accept-reject-all-buttons"), | |
| 90 | - ).toBeInTheDocument(); | |
| 91 | - }); | |
| 92 | - | |
| 93 | - // IDE sends back message that it is done | |
| 94 | - ideMessenger.mockMessageToWebview("updateApplyState", { | |
| 95 | - status: "closed", | |
| 96 | - streamId: "12345", | |
| 97 | - }); | |
| 98 | - | |
| 99 | - // Wait for the buttons to disappear | |
| 100 | - await waitFor(() => { | |
| 101 | - expect( | |
| 102 | - screen.queryByTestId("edit-accept-button"), | |
| 103 | - ).not.toBeInTheDocument(); | |
| 104 | - expect( | |
| 105 | - screen.queryByTestId("edit-reject-button"), | |
| 106 | - ).not.toBeInTheDocument(); | |
| 107 | - }); | |
| 108 | - }); | |
| 109 | - | |
| 110 | - it("should show apply cancellation", async () => { | |
| 111 | - const { ideMessenger } = await renderWithProviders(<Chat />); | |
| 112 | - | |
| 113 | - // Spy on the request method of ideMessenger | |
| 114 | - const messengerPostSpy = vi.spyOn(ideMessenger, "post"); | |
| 115 | - | |
| 116 | - for (let i = 0; i < 5; i++) { | |
| 117 | - ideMessenger.mockMessageToWebview("updateApplyState", { | |
| 118 | - status: "streaming", | |
| 119 | - streamId: `12345`, | |
| 120 | - }); | |
| 121 | - } | |
| 122 | - | |
| 123 | - // Wait for applying toolbar to appear | |
| 124 | - await waitFor(() => { | |
| 125 | - const cancelApplyButton = screen.getByTestId( | |
| 126 | - "notch-applying-cancel-button", | |
| 127 | - ); | |
| 128 | - const applyingText = screen.getByTestId("notch-applying-text"); | |
| 129 | - | |
| 130 | - expect(cancelApplyButton).toBeInTheDocument(); | |
| 131 | - expect(applyingText).toBeInTheDocument(); | |
| 132 | - }); | |
| 133 | - | |
| 134 | - const cancelApplyButton = screen.getByTestId( | |
| 135 | - "notch-applying-cancel-button", | |
| 136 | - ); | |
| 137 | - cancelApplyButton.click(); | |
| 138 | - | |
| 139 | - // Verify that rejectDiff message has been posted to ideMessenger | |
| 140 | - expect(messengerPostSpy).toHaveBeenCalledWith("rejectDiff", {}); | |
| 141 | - | |
| 142 | - // Now simulate the IDE sending back a message that the apply state is closed | |
| 143 | - ideMessenger.mockMessageToWebview("updateApplyState", { | |
| 144 | - status: "closed", | |
| 145 | - streamId: "12345", | |
| 146 | - }); | |
| 147 | - | |
| 148 | - await waitFor(() => { | |
| 149 | - const cancelApplyButton = screen.queryByTestId( | |
| 150 | - "notch-applying-cancel-button", | |
| 151 | - ); | |
| 152 | - const applyingText = screen.queryByTestId("notch-applying-text"); | |
| 153 | - | |
| 154 | - expect(cancelApplyButton).not.toBeInTheDocument(); | |
| 155 | - expect(applyingText).not.toBeInTheDocument(); | |
| 156 | - }); | |
| 157 | - | |
| 158 | - // Cleanup spy | |
| 159 | - messengerPostSpy.mockRestore(); | |
| 160 | - }); | |
| 161 | -}); |
modified gui/src/pages/gui/Chat.tsx +5 −5
| @@ -42,12 +42,12 @@ | ||
| 42 | 42 | setDialogMessage, |
| 43 | 43 | setShowDialog, |
| 44 | 44 | } from "../../redux/slices/uiSlice"; |
| 45 | -import { cancelStream } from "../../redux/thunks/cancelStream"; | |
| 46 | 45 | import { streamEditThunk } from "../../redux/thunks/edit"; |
| 47 | 46 | import { loadLastSession } from "../../redux/thunks/session"; |
| 48 | 47 | import { streamResponseThunk } from "../../redux/thunks/streamResponse"; |
| 49 | 48 | import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util"; |
| 50 | 49 | |
| 50 | +import { cancelStream } from "../../redux/thunks/cancelStream"; | |
| 51 | 51 | import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; |
| 52 | 52 | import { EmptyChatBody } from "./EmptyChatBody"; |
| 53 | 53 | import { ExploreDialogWatcher } from "./ExploreDialogWatcher"; |
| @@ -125,14 +125,14 @@ | ||
| 125 | 125 | |
| 126 | 126 | useEffect(() => { |
| 127 | 127 | // Cmd + Backspace to delete current step |
| 128 | - const listener = (e: any) => { | |
| 128 | + const listener = (e: KeyboardEvent) => { | |
| 129 | 129 | if ( |
| 130 | 130 | e.key === "Backspace" && |
| 131 | 131 | (jetbrains ? e.altKey : isMetaEquivalentKeyPressed(e)) && |
| 132 | 132 | !e.shiftKey |
| 133 | 133 | ) { |
| 134 | - dispatch(cancelStream()); | |
| 135 | - ideMessenger.post("rejectDiff", {}); // just always cancel, if not in applying won't matter | |
| 134 | + void dispatch(cancelStream()); | |
| 135 | + if (isInEdit) ideMessenger.post("rejectDiff", {}); | |
| 136 | 136 | } |
| 137 | 137 | }; |
| 138 | 138 | window.addEventListener("keydown", listener); |
| @@ -140,7 +140,7 @@ | ||
| 140 | 140 | return () => { |
| 141 | 141 | window.removeEventListener("keydown", listener); |
| 142 | 142 | }; |
| 143 | - }, [isStreaming, jetbrains]); | |
| 143 | + }, [isStreaming, jetbrains, isInEdit]); | |
| 144 | 144 | |
| 145 | 145 | const { widget, highlights } = useFindWidget( |
| 146 | 146 | stepsDivRef, |
modified gui/src/pages/gui/ToolCallDiv/EditFile.tsx +1 −26
| @@ -1,12 +1,5 @@ | ||
| 1 | 1 | import { getMarkdownLanguageTagForFile } from "core/util"; |
| 2 | -import { useEffect } from "react"; | |
| 3 | -import { v4 as uuidv4 } from "uuid"; | |
| 4 | 2 | import StyledMarkdownPreview from "../../../components/StyledMarkdownPreview"; |
| 5 | -import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; | |
| 6 | -import { | |
| 7 | - selectApplyStateByToolCallId, | |
| 8 | - updateApplyState, | |
| 9 | -} from "../../../redux/slices/sessionSlice"; | |
| 10 | 3 | |
| 11 | 4 | type EditToolCallProps = { |
| 12 | 5 | relativeFilePath: string; |
| @@ -16,24 +9,6 @@ | ||
| 16 | 9 | }; |
| 17 | 10 | |
| 18 | 11 | export function EditFile(props: EditToolCallProps) { |
| 19 | - const dispatch = useAppDispatch(); | |
| 20 | - | |
| 21 | - const applyState = useAppSelector((state) => | |
| 22 | - selectApplyStateByToolCallId(state, props.toolCallId), | |
| 23 | - ); | |
| 24 | - | |
| 25 | - useEffect(() => { | |
| 26 | - if (!applyState) { | |
| 27 | - dispatch( | |
| 28 | - updateApplyState({ | |
| 29 | - streamId: uuidv4(), | |
| 30 | - toolCallId: props.toolCallId, | |
| 31 | - status: "not-started", | |
| 32 | - }), | |
| 33 | - ); | |
| 34 | - } | |
| 35 | - }, [applyState, props.toolCallId]); | |
| 36 | - | |
| 37 | 12 | if (!props.relativeFilePath || !props.changes) { |
| 38 | 13 | return null; |
| 39 | 14 | } |
| @@ -45,7 +20,7 @@ | ||
| 45 | 20 | isRenderingInStepContainer |
| 46 | 21 | disableManualApply |
| 47 | 22 | source={src} |
| 48 | - forceStreamId={applyState?.streamId} | |
| 23 | + toolCallId={props.toolCallId} | |
| 49 | 24 | expandCodeblocks={false} |
| 50 | 25 | itemIndex={props.historyIndex} |
| 51 | 26 | /> |
added gui/src/pages/gui/chat-tests/ApplyScenarios.test.tsx +80 −0
| @@ -0,0 +1,80 @@ | ||
| 1 | +import { act } from "@testing-library/react"; | |
| 2 | +import { renderWithProviders } from "../../../util/test/render"; | |
| 3 | +import { | |
| 4 | + getElementByTestId, | |
| 5 | + verifyNotPresentByTestId, | |
| 6 | + verifyNotPresentByText, | |
| 7 | +} from "../../../util/test/utils"; | |
| 8 | +import { Chat } from "../Chat"; | |
| 9 | + | |
| 10 | +test("Chat apply scenarios: handle apply updates and display the accept / reject all buttons", async () => { | |
| 11 | + const { ideMessenger } = await renderWithProviders(<Chat />); | |
| 12 | + | |
| 13 | + // Use queryByText which returns null when element isn't found | |
| 14 | + await verifyNotPresentByText("Accept All"); | |
| 15 | + await verifyNotPresentByText("Reject All"); | |
| 16 | + | |
| 17 | + for (let i = 0; i < 5; i++) { | |
| 18 | + ideMessenger.mockMessageToWebview("updateApplyState", { | |
| 19 | + status: "streaming", | |
| 20 | + streamId: `12345`, | |
| 21 | + }); | |
| 22 | + } | |
| 23 | + | |
| 24 | + ideMessenger.mockMessageToWebview("updateApplyState", { | |
| 25 | + status: "done", | |
| 26 | + streamId: "12345", | |
| 27 | + }); | |
| 28 | + | |
| 29 | + // Wait for the buttons to appear | |
| 30 | + await getElementByTestId("accept-reject-all-buttons"); | |
| 31 | + | |
| 32 | + // IDE sends back message that it is done | |
| 33 | + ideMessenger.mockMessageToWebview("updateApplyState", { | |
| 34 | + status: "closed", | |
| 35 | + streamId: "12345", | |
| 36 | + }); | |
| 37 | + | |
| 38 | + // Wait for the buttons to disappear | |
| 39 | + await verifyNotPresentByTestId("edit-accept-button"); | |
| 40 | + await verifyNotPresentByTestId("edit-reject-button"); | |
| 41 | +}); | |
| 42 | + | |
| 43 | +test("Chat apply scenarios: show apply cancellation", async () => { | |
| 44 | + const { ideMessenger } = await renderWithProviders(<Chat />); | |
| 45 | + | |
| 46 | + // Spy on the request method of ideMessenger | |
| 47 | + const messengerPostSpy = vi.spyOn(ideMessenger, "post"); | |
| 48 | + | |
| 49 | + for (let i = 0; i < 5; i++) { | |
| 50 | + ideMessenger.mockMessageToWebview("updateApplyState", { | |
| 51 | + status: "streaming", | |
| 52 | + streamId: `12345`, | |
| 53 | + }); | |
| 54 | + } | |
| 55 | + | |
| 56 | + // Wait for applying toolbar to appear | |
| 57 | + await getElementByTestId("notch-applying-text"); | |
| 58 | + | |
| 59 | + await act(async () => { | |
| 60 | + const cancelApplyButton = await getElementByTestId( | |
| 61 | + "notch-applying-cancel-button", | |
| 62 | + ); | |
| 63 | + cancelApplyButton.click(); | |
| 64 | + }); | |
| 65 | + | |
| 66 | + // Verify that rejectDiff message has been posted to ideMessenger | |
| 67 | + expect(messengerPostSpy).toHaveBeenCalledWith("rejectDiff", {}); | |
| 68 | + | |
| 69 | + // Now simulate the IDE sending back a message that the apply state is closed | |
| 70 | + ideMessenger.mockMessageToWebview("updateApplyState", { | |
| 71 | + status: "closed", | |
| 72 | + streamId: "12345", | |
| 73 | + }); | |
| 74 | + | |
| 75 | + await verifyNotPresentByTestId("notch-applying-text"); | |
| 76 | + await verifyNotPresentByTestId("notch-applying-cancel-button"); | |
| 77 | + | |
| 78 | + // Cleanup spy | |
| 79 | + messengerPostSpy.mockRestore(); | |
| 80 | +}); |
added gui/src/pages/gui/chat-tests/Chat.test.tsx +61 −0
| @@ -0,0 +1,61 @@ | ||
| 1 | +import { act } from "@testing-library/react"; | |
| 2 | +import { addAndSelectMockLlm } from "../../../util/test/config"; | |
| 3 | +import { renderWithProviders } from "../../../util/test/render"; | |
| 4 | +import { | |
| 5 | + getElementByTestId, | |
| 6 | + getElementByText, | |
| 7 | + sendInputWithMockedResponse, | |
| 8 | +} from "../../../util/test/utils"; | |
| 9 | +import { Chat } from "../Chat"; | |
| 10 | + | |
| 11 | +test("should render input box", async () => { | |
| 12 | + await renderWithProviders(<Chat />); | |
| 13 | + await getElementByTestId("continue-input-box"); | |
| 14 | +}); | |
| 15 | + | |
| 16 | +test("should be able to toggle modes", async () => { | |
| 17 | + await renderWithProviders(<Chat />); | |
| 18 | + await getElementByText("Chat"); | |
| 19 | + | |
| 20 | + // Simulate cmd+. keyboard shortcut to toggle modes | |
| 21 | + act(() => { | |
| 22 | + document.dispatchEvent( | |
| 23 | + new KeyboardEvent("keydown", { | |
| 24 | + key: ".", | |
| 25 | + metaKey: true, // cmd key on Mac | |
| 26 | + }), | |
| 27 | + ); | |
| 28 | + }); | |
| 29 | + | |
| 30 | + // Check that it switched to Agent mode | |
| 31 | + await getElementByText("Agent"); | |
| 32 | + | |
| 33 | + act(() => { | |
| 34 | + document.dispatchEvent( | |
| 35 | + new KeyboardEvent("keydown", { | |
| 36 | + key: ".", | |
| 37 | + metaKey: true, // cmd key on Mac | |
| 38 | + }), | |
| 39 | + ); | |
| 40 | + }); | |
| 41 | + | |
| 42 | + await getElementByText("Chat"); | |
| 43 | +}); | |
| 44 | + | |
| 45 | +test("should send a message and receive a response", async () => { | |
| 46 | + const { ideMessenger, store } = await renderWithProviders(<Chat />); | |
| 47 | + | |
| 48 | + // First add and select the mock LLM | |
| 49 | + await act(async () => { | |
| 50 | + addAndSelectMockLlm(store, ideMessenger); | |
| 51 | + }); | |
| 52 | + | |
| 53 | + const CONTENT = "Expected response"; | |
| 54 | + const INPUT = "User input"; | |
| 55 | + | |
| 56 | + await sendInputWithMockedResponse(ideMessenger, INPUT, [ | |
| 57 | + { role: "assistant", content: CONTENT }, | |
| 58 | + ]); | |
| 59 | + | |
| 60 | + await getElementByText(CONTENT); | |
| 61 | +}); |
added gui/src/pages/gui/chat-tests/EditToolScenarios.test.tsx +231 −0
| @@ -0,0 +1,231 @@ | ||
| 1 | +import { BuiltInToolNames } from "core/tools/builtIn"; | |
| 2 | +import { | |
| 3 | + addAndSelectMockLlm, | |
| 4 | + triggerConfigUpdate, | |
| 5 | +} from "../../../util/test/config"; | |
| 6 | +import { renderWithProviders } from "../../../util/test/render"; | |
| 7 | +import { Chat } from "../Chat"; | |
| 8 | + | |
| 9 | +import { waitFor } from "@testing-library/dom"; | |
| 10 | +import { ChatMessage } from "core"; | |
| 11 | +import { toggleToolSetting } from "../../../redux/slices/uiSlice"; | |
| 12 | +import { | |
| 13 | + getElementByTestId, | |
| 14 | + getElementByText, | |
| 15 | + sendInputWithMockedResponse, | |
| 16 | + verifyNotPresentByTestId, | |
| 17 | +} from "../../../util/test/utils"; | |
| 18 | + | |
| 19 | +const EDIT_WORKSPACE_DIR = "file:///workspace"; | |
| 20 | +const EDIT_FILEPATH = "test.txt"; | |
| 21 | +const EDIT_FILE_URI = `${EDIT_WORKSPACE_DIR}/${EDIT_FILEPATH}`; | |
| 22 | +const EDIT_CHANGES = "New content"; | |
| 23 | +const EDIT_TOOL_CALL_ID = "known-id"; | |
| 24 | +const EDIT_MESSAGES: ChatMessage[] = [ | |
| 25 | + { | |
| 26 | + role: "assistant", | |
| 27 | + content: "", | |
| 28 | + toolCalls: [ | |
| 29 | + { | |
| 30 | + id: EDIT_TOOL_CALL_ID, | |
| 31 | + function: { | |
| 32 | + name: BuiltInToolNames.EditExistingFile, | |
| 33 | + arguments: JSON.stringify({ | |
| 34 | + filepath: EDIT_FILEPATH, | |
| 35 | + changes: EDIT_CHANGES, | |
| 36 | + }), | |
| 37 | + }, | |
| 38 | + }, | |
| 39 | + ], | |
| 40 | + }, | |
| 41 | +]; | |
| 42 | + | |
| 43 | +const POST_EDIT_RESPONSE = "Edit applied successfully"; | |
| 44 | +beforeEach(() => { | |
| 45 | + vi.clearAllMocks(); | |
| 46 | +}); | |
| 47 | + | |
| 48 | +test("Edit run with ask first policy and no auto apply", async () => { | |
| 49 | + // Setup | |
| 50 | + const { ideMessenger, store, user } = await renderWithProviders(<Chat />); | |
| 51 | + | |
| 52 | + ideMessenger.responses["getWorkspaceDirs"] = [EDIT_WORKSPACE_DIR]; | |
| 53 | + const messengerPostSpy = vi.spyOn(ideMessenger, "post"); | |
| 54 | + | |
| 55 | + addAndSelectMockLlm(store, ideMessenger); | |
| 56 | + | |
| 57 | + // Send the input that will respond with an edit tool call | |
| 58 | + await sendInputWithMockedResponse( | |
| 59 | + ideMessenger, | |
| 60 | + "Edit this file", | |
| 61 | + EDIT_MESSAGES, | |
| 62 | + ); | |
| 63 | + | |
| 64 | + // Toggle the codeblock and make sure the changes show | |
| 65 | + const toggleCodeblockChevron = await getElementByTestId("toggle-codeblock"); | |
| 66 | + | |
| 67 | + await user.click(toggleCodeblockChevron); | |
| 68 | + await getElementByText(EDIT_CHANGES); | |
| 69 | + | |
| 70 | + // Pending tool call - find and click the accept button | |
| 71 | + const acceptToolCallButton = await getElementByTestId( | |
| 72 | + "accept-tool-call-button", | |
| 73 | + ); | |
| 74 | + await user.click(acceptToolCallButton); | |
| 75 | + | |
| 76 | + // Tool call, check that applyToFile was called for edit | |
| 77 | + await waitFor(() => { | |
| 78 | + expect(messengerPostSpy).toHaveBeenCalledWith("applyToFile", { | |
| 79 | + streamId: expect.any(String), | |
| 80 | + filepath: EDIT_FILE_URI, | |
| 81 | + text: EDIT_CHANGES, | |
| 82 | + toolCallId: EDIT_TOOL_CALL_ID, | |
| 83 | + }); | |
| 84 | + }); | |
| 85 | + | |
| 86 | + // Extract stream ID and initiate mock streaming | |
| 87 | + const streamId = messengerPostSpy.mock.calls.find( | |
| 88 | + (call) => call[0] === "applyToFile", | |
| 89 | + )?.[1]?.streamId; | |
| 90 | + expect(streamId).toBeDefined(); | |
| 91 | + | |
| 92 | + ideMessenger.mockMessageToWebview("updateApplyState", { | |
| 93 | + status: "streaming", | |
| 94 | + streamId, | |
| 95 | + toolCallId: EDIT_TOOL_CALL_ID, | |
| 96 | + filepath: EDIT_FILE_URI, | |
| 97 | + }); | |
| 98 | + | |
| 99 | + // Mid stream, should show applying in notch | |
| 100 | + await getElementByTestId("notch-applying-text"); | |
| 101 | + await getElementByTestId("notch-applying-cancel-button"); | |
| 102 | + | |
| 103 | + // Close the stream | |
| 104 | + ideMessenger.mockMessageToWebview("updateApplyState", { | |
| 105 | + status: "done", | |
| 106 | + streamId, | |
| 107 | + toolCallId: EDIT_TOOL_CALL_ID, | |
| 108 | + filepath: EDIT_FILE_URI, | |
| 109 | + }); | |
| 110 | + | |
| 111 | + // Verify accept/reject buttons are present | |
| 112 | + const acceptButton = await getElementByTestId("edit-accept-button"); | |
| 113 | + await getElementByTestId("edit-reject-button"); | |
| 114 | + | |
| 115 | + // Accept the changes, which should trigger a response after the tool call | |
| 116 | + await user.click(acceptButton); | |
| 117 | + | |
| 118 | + expect(messengerPostSpy).toHaveBeenCalledWith("acceptDiff", { | |
| 119 | + streamId, | |
| 120 | + filepath: EDIT_FILE_URI, | |
| 121 | + }); | |
| 122 | + | |
| 123 | + ideMessenger.setChatResponseText(POST_EDIT_RESPONSE); | |
| 124 | + ideMessenger.mockMessageToWebview("updateApplyState", { | |
| 125 | + status: "closed", | |
| 126 | + streamId, | |
| 127 | + toolCallId: EDIT_TOOL_CALL_ID, | |
| 128 | + filepath: EDIT_FILE_URI, | |
| 129 | + }); | |
| 130 | + | |
| 131 | + await verifyNotPresentByTestId("edit-accept-button"); | |
| 132 | + await verifyNotPresentByTestId("edit-reject-button"); | |
| 133 | + | |
| 134 | + await getElementByText(POST_EDIT_RESPONSE); | |
| 135 | +}); | |
| 136 | + | |
| 137 | +test("Edit run with no policy and yolo mode", async () => { | |
| 138 | + // Setup | |
| 139 | + const { ideMessenger, store, user } = await renderWithProviders(<Chat />); | |
| 140 | + | |
| 141 | + ideMessenger.responses["getWorkspaceDirs"] = [EDIT_WORKSPACE_DIR]; | |
| 142 | + const messengerPostSpy = vi.spyOn(ideMessenger, "post"); | |
| 143 | + | |
| 144 | + addAndSelectMockLlm(store, ideMessenger); | |
| 145 | + | |
| 146 | + // Enable automatic edit and yolo mode | |
| 147 | + store.dispatch(toggleToolSetting(BuiltInToolNames.EditExistingFile)); | |
| 148 | + triggerConfigUpdate({ | |
| 149 | + store, | |
| 150 | + ideMessenger, | |
| 151 | + editConfig: (current) => { | |
| 152 | + current.ui = { | |
| 153 | + ...current.ui, | |
| 154 | + autoAcceptEditToolDiffs: true, // Enable auto-accept for edit tool diffs | |
| 155 | + }; | |
| 156 | + return current; | |
| 157 | + }, | |
| 158 | + }); | |
| 159 | + expect(store.getState().config.config.ui?.autoAcceptEditToolDiffs).toBe(true); | |
| 160 | + | |
| 161 | + // Send the input that will respond with an edit tool call | |
| 162 | + await sendInputWithMockedResponse( | |
| 163 | + ideMessenger, | |
| 164 | + "Edit this file", | |
| 165 | + EDIT_MESSAGES, | |
| 166 | + ); | |
| 167 | + | |
| 168 | + // Toggle the codeblock and make sure the changes show | |
| 169 | + const toggleCodeblockChevron = await getElementByTestId("toggle-codeblock"); | |
| 170 | + | |
| 171 | + await user.click(toggleCodeblockChevron); | |
| 172 | + await getElementByText(EDIT_CHANGES); | |
| 173 | + | |
| 174 | + // Make sure there's no pending tool call | |
| 175 | + verifyNotPresentByTestId("accept-tool-call-button"); | |
| 176 | + // Tool call, check that applyToFile was called for edit | |
| 177 | + await waitFor(() => { | |
| 178 | + expect(messengerPostSpy).toHaveBeenCalledWith("applyToFile", { | |
| 179 | + streamId: expect.any(String), | |
| 180 | + filepath: EDIT_FILE_URI, | |
| 181 | + text: EDIT_CHANGES, | |
| 182 | + toolCallId: EDIT_TOOL_CALL_ID, | |
| 183 | + }); | |
| 184 | + }); | |
| 185 | + | |
| 186 | + // Extract stream ID and initiate mock streaming | |
| 187 | + const streamId = messengerPostSpy.mock.calls.find( | |
| 188 | + (call) => call[0] === "applyToFile", | |
| 189 | + )?.[1]?.streamId; | |
| 190 | + expect(streamId).toBeDefined(); | |
| 191 | + | |
| 192 | + ideMessenger.mockMessageToWebview("updateApplyState", { | |
| 193 | + status: "streaming", | |
| 194 | + streamId, | |
| 195 | + toolCallId: EDIT_TOOL_CALL_ID, | |
| 196 | + filepath: EDIT_FILE_URI, | |
| 197 | + }); | |
| 198 | + | |
| 199 | + // Mid stream, should show applying in notch | |
| 200 | + await getElementByTestId("notch-applying-text"); | |
| 201 | + await getElementByTestId("notch-applying-cancel-button"); | |
| 202 | + | |
| 203 | + // Close the stream | |
| 204 | + ideMessenger.mockMessageToWebview("updateApplyState", { | |
| 205 | + status: "done", | |
| 206 | + streamId, | |
| 207 | + toolCallId: EDIT_TOOL_CALL_ID, | |
| 208 | + filepath: EDIT_FILE_URI, | |
| 209 | + }); | |
| 210 | + | |
| 211 | + await waitFor(() => { | |
| 212 | + expect(messengerPostSpy).toHaveBeenCalledWith("acceptDiff", { | |
| 213 | + streamId, | |
| 214 | + filepath: EDIT_FILE_URI, | |
| 215 | + }); | |
| 216 | + }); | |
| 217 | + | |
| 218 | + // Close the stream, ensure response is shown and diff buttons are not present | |
| 219 | + ideMessenger.setChatResponseText(POST_EDIT_RESPONSE); | |
| 220 | + ideMessenger.mockMessageToWebview("updateApplyState", { | |
| 221 | + status: "closed", | |
| 222 | + streamId, | |
| 223 | + toolCallId: EDIT_TOOL_CALL_ID, | |
| 224 | + filepath: EDIT_FILE_URI, | |
| 225 | + }); | |
| 226 | + | |
| 227 | + await verifyNotPresentByTestId("edit-accept-button"); | |
| 228 | + await verifyNotPresentByTestId("edit-reject-button"); | |
| 229 | + | |
| 230 | + await getElementByText(POST_EDIT_RESPONSE); | |
| 231 | +}); |
modified gui/src/redux/slices/configSlice.ts +1 −10
| @@ -10,16 +10,7 @@ | ||
| 10 | 10 | }; |
| 11 | 11 | |
| 12 | 12 | export const EMPTY_CONFIG: BrowserSerializedContinueConfig = { |
| 13 | - slashCommands: [ | |
| 14 | - { | |
| 15 | - name: "share", | |
| 16 | - description: "Export the current chat session to markdown", | |
| 17 | - }, | |
| 18 | - { | |
| 19 | - name: "cmd", | |
| 20 | - description: "Generate a shell command", | |
| 21 | - }, | |
| 22 | - ], | |
| 13 | + slashCommands: [], | |
| 23 | 14 | contextProviders: [], |
| 24 | 15 | tools: [], |
| 25 | 16 | mcpServerStatuses: [], |
modified gui/src/redux/slices/profilesSlice.ts +2 −2
| @@ -1,5 +1,5 @@ | ||
| 1 | 1 | import { createSlice, PayloadAction } from "@reduxjs/toolkit"; |
| 2 | -import { SlashCommandDescription } from "core"; | |
| 2 | +import { SlashCommandDescWithSource } from "core"; | |
| 3 | 3 | import { SerializedOrgWithProfiles } from "core/config/ProfileLifecycleManager"; |
| 4 | 4 | |
| 5 | 5 | const DEFAULT_SLASH_COMMANDS_BOOKMARKS_COUNT = 5; |
| @@ -81,7 +81,7 @@ | ||
| 81 | 81 | state, |
| 82 | 82 | action: PayloadAction<{ |
| 83 | 83 | profileId: string; |
| 84 | - defaultSlashCommands?: SlashCommandDescription[]; | |
| 84 | + defaultSlashCommands?: SlashCommandDescWithSource[]; | |
| 85 | 85 | }>, |
| 86 | 86 | ) => { |
| 87 | 87 | const { profileId, defaultSlashCommands = [] } = action.payload; |
modified gui/src/redux/slices/sessionSlice.ts +3 −1
| @@ -657,7 +657,9 @@ | ||
| 657 | 657 | (state: RootState, toolCallId?: string) => toolCallId, |
| 658 | 658 | ], |
| 659 | 659 | (states, toolCallId) => { |
| 660 | - return states.find((state) => state.toolCallId === toolCallId); | |
| 660 | + if (toolCallId) { | |
| 661 | + return states.find((state) => state.toolCallId === toolCallId); | |
| 662 | + } | |
| 661 | 663 | }, |
| 662 | 664 | ); |
| 663 | 665 |
modified gui/src/redux/store.ts +0 −5
| @@ -23,11 +23,6 @@ | ||
| 23 | 23 | import tabsReducer from "./slices/tabsSlice"; |
| 24 | 24 | import uiReducer from "./slices/uiSlice"; |
| 25 | 25 | |
| 26 | -export interface ChatMessage { | |
| 27 | - role: "system" | "user" | "assistant"; | |
| 28 | - content: string; | |
| 29 | -} | |
| 30 | - | |
| 31 | 26 | const rootReducer = combineReducers({ |
| 32 | 27 | session: sessionReducer, |
| 33 | 28 | ui: uiReducer, |
modified gui/src/redux/thunks/callCurrentTool.ts +2 −7
| @@ -19,7 +19,6 @@ | ||
| 19 | 19 | async (_, { dispatch, extra, getState }) => { |
| 20 | 20 | const state = getState(); |
| 21 | 21 | const toolCallState = selectCurrentToolCall(state); |
| 22 | - | |
| 23 | 22 | if (!toolCallState) { |
| 24 | 23 | return; |
| 25 | 24 | } |
| @@ -61,19 +60,15 @@ | ||
| 61 | 60 | ) { |
| 62 | 61 | // Tool is called on client side |
| 63 | 62 | const { |
| 64 | - output: clientToolOuput, | |
| 63 | + output: clientToolOutput, | |
| 65 | 64 | respondImmediately, |
| 66 | 65 | errorMessage: clientToolError, |
| 67 | 66 | } = await callClientTool(toolCallState, { |
| 68 | 67 | dispatch, |
| 69 | 68 | ideMessenger: extra.ideMessenger, |
| 70 | - streamId: state.session.codeBlockApplyStates.states.find( | |
| 71 | - (state) => | |
| 72 | - state.toolCallId && state.toolCallId === toolCallState.toolCallId, | |
| 73 | - )?.streamId, | |
| 74 | 69 | getState, |
| 75 | 70 | }); |
| 76 | - output = clientToolOuput; | |
| 71 | + output = clientToolOutput; | |
| 77 | 72 | errorMessage = clientToolError; |
| 78 | 73 | streamResponse = respondImmediately; |
| 79 | 74 | } else { |
modified gui/src/redux/thunks/edit.ts +17 −15
| @@ -17,6 +17,7 @@ | ||
| 17 | 17 | import { |
| 18 | 18 | newSession, |
| 19 | 19 | setActive, |
| 20 | + setInactive, | |
| 20 | 21 | setIsInEdit, |
| 21 | 22 | setMainEditorContentTrigger, |
| 22 | 23 | setMode, |
| @@ -33,27 +34,26 @@ | ||
| 33 | 34 | }, |
| 34 | 35 | ThunkApiType |
| 35 | 36 | >( |
| 36 | - "chat/streamResponse", | |
| 37 | + "edit/streamResponse", | |
| 37 | 38 | async ({ editorState, codeToEdit }, { dispatch, extra }) => { |
| 38 | 39 | await dispatch( |
| 39 | 40 | streamThunkWrapper(async () => { |
| 40 | 41 | dispatch(setActive()); |
| 41 | - const [contextItems, __, userInstructions, _] = | |
| 42 | - await resolveEditorContent({ | |
| 43 | - editorState, | |
| 44 | - modifiers: { | |
| 45 | - noContext: true, | |
| 46 | - useCodebase: false, | |
| 47 | - }, | |
| 48 | - ideMessenger: extra.ideMessenger, | |
| 49 | - defaultContextProviders: [], | |
| 50 | - availableSlashCommands: [], | |
| 51 | - dispatch, | |
| 52 | - }); | |
| 42 | + const { selectedContextItems, content } = await resolveEditorContent({ | |
| 43 | + editorState, | |
| 44 | + modifiers: { | |
| 45 | + noContext: true, | |
| 46 | + useCodebase: false, | |
| 47 | + }, | |
| 48 | + ideMessenger: extra.ideMessenger, | |
| 49 | + defaultContextProviders: [], | |
| 50 | + availableSlashCommands: [], | |
| 51 | + dispatch, | |
| 52 | + }); | |
| 53 | 53 | |
| 54 | 54 | const prompt = [ |
| 55 | - ...contextItems.map((item) => item.content), | |
| 56 | - stripImages(userInstructions), | |
| 55 | + ...selectedContextItems.map((item) => item.content), | |
| 56 | + stripImages(content), | |
| 57 | 57 | ].join("\n\n"); |
| 58 | 58 | |
| 59 | 59 | const response = await extra.ideMessenger.request("edit/sendPrompt", { |
| @@ -61,6 +61,8 @@ | ||
| 61 | 61 | range: codeToEdit[0] as RangeInFileWithContents, |
| 62 | 62 | }); |
| 63 | 63 | |
| 64 | + dispatch(setInactive()); | |
| 65 | + | |
| 64 | 66 | if (response.status === "error") { |
| 65 | 67 | throw new Error(response.error); |
| 66 | 68 | } |
deleted gui/src/redux/thunks/gatherContext.ts +0 −124
| @@ -1,124 +0,0 @@ | ||
| 1 | -import { createAsyncThunk } from "@reduxjs/toolkit"; | |
| 2 | -import { JSONContent } from "@tiptap/core"; | |
| 3 | -import { | |
| 4 | - ContextItemWithId, | |
| 5 | - InputModifiers, | |
| 6 | - MessageContent, | |
| 7 | - RangeInFile, | |
| 8 | - SlashCommandDescription, | |
| 9 | -} from "core"; | |
| 10 | -import * as URI from "uri-js"; | |
| 11 | -import { resolveEditorContent } from "../../components/mainInput/TipTapEditor"; | |
| 12 | -import { selectSelectedChatModel } from "../slices/configSlice"; | |
| 13 | -import { ThunkApiType } from "../store"; | |
| 14 | - | |
| 15 | -export const gatherContext = createAsyncThunk< | |
| 16 | - { | |
| 17 | - selectedContextItems: ContextItemWithId[]; | |
| 18 | - selectedCode: RangeInFile[]; | |
| 19 | - content: MessageContent; | |
| 20 | - slashCommandWithInput: | |
| 21 | - | { | |
| 22 | - command: SlashCommandDescription; | |
| 23 | - input: string; | |
| 24 | - } | |
| 25 | - | undefined; | |
| 26 | - }, | |
| 27 | - { | |
| 28 | - editorState: JSONContent; | |
| 29 | - modifiers: InputModifiers; | |
| 30 | - promptPreamble?: string; | |
| 31 | - }, | |
| 32 | - ThunkApiType | |
| 33 | ->( | |
| 34 | - "chat/gatherContext", | |
| 35 | - async ( | |
| 36 | - { modifiers, editorState, promptPreamble }, | |
| 37 | - { dispatch, extra, getState }, | |
| 38 | - ) => { | |
| 39 | - const state = getState(); | |
| 40 | - const selectedChatModel = selectSelectedChatModel(state); | |
| 41 | - | |
| 42 | - const defaultContextProviders = | |
| 43 | - state.config.config.experimental?.defaultContext ?? []; | |
| 44 | - | |
| 45 | - if (!selectedChatModel) { | |
| 46 | - console.error( | |
| 47 | - "gatherContext thunk: Cannot gather context, no model selected", | |
| 48 | - ); | |
| 49 | - throw new Error("No chat model selected"); | |
| 50 | - } | |
| 51 | - | |
| 52 | - // Resolve context providers and construct new history | |
| 53 | - let [selectedContextItems, selectedCode, content, slashCommandWithInput] = | |
| 54 | - await resolveEditorContent({ | |
| 55 | - editorState, | |
| 56 | - modifiers, | |
| 57 | - ideMessenger: extra.ideMessenger, | |
| 58 | - defaultContextProviders, | |
| 59 | - availableSlashCommands: state.config.config.slashCommands, | |
| 60 | - dispatch, | |
| 61 | - }); | |
| 62 | - | |
| 63 | - // Automatically use currently open file | |
| 64 | - if (!modifiers.noContext) { | |
| 65 | - const usingFreeTrial = false; // TODO no longer tracking free trial count, need to hook up to hub | |
| 66 | - | |
| 67 | - const currentFileResponse = await extra.ideMessenger.request( | |
| 68 | - "context/getContextItems", | |
| 69 | - { | |
| 70 | - name: "currentFile", | |
| 71 | - query: "non-mention-usage", | |
| 72 | - fullInput: "", | |
| 73 | - selectedCode: [], | |
| 74 | - }, | |
| 75 | - ); | |
| 76 | - if (currentFileResponse.status === "success") { | |
| 77 | - const items = currentFileResponse.content; | |
| 78 | - if (items.length > 0) { | |
| 79 | - const currentFile = items[0]; | |
| 80 | - const uri = currentFile.uri?.value; | |
| 81 | - | |
| 82 | - // don't add the file if it's already in the context items | |
| 83 | - if ( | |
| 84 | - uri && | |
| 85 | - !selectedContextItems.find( | |
| 86 | - (item) => item.uri?.value && URI.equal(item.uri.value, uri), | |
| 87 | - ) | |
| 88 | - ) { | |
| 89 | - // Limit to 1000 lines if using free trial | |
| 90 | - if (usingFreeTrial) { | |
| 91 | - currentFile.content = currentFile.content | |
| 92 | - .split("\n") | |
| 93 | - .slice(0, 1000) | |
| 94 | - .join("\n"); | |
| 95 | - if (!currentFile.content.endsWith("```")) { | |
| 96 | - currentFile.content += "\n```"; | |
| 97 | - } | |
| 98 | - } | |
| 99 | - currentFile.id = { | |
| 100 | - providerTitle: "file", | |
| 101 | - itemId: uri, | |
| 102 | - }; | |
| 103 | - selectedContextItems.unshift(currentFile); | |
| 104 | - } | |
| 105 | - } | |
| 106 | - } | |
| 107 | - } | |
| 108 | - | |
| 109 | - if (promptPreamble) { | |
| 110 | - if (typeof content === "string") { | |
| 111 | - content = promptPreamble + content; | |
| 112 | - } else if (content[0].type === "text") { | |
| 113 | - content[0].text = promptPreamble + content[0].text; | |
| 114 | - } | |
| 115 | - } | |
| 116 | - | |
| 117 | - return { | |
| 118 | - selectedContextItems, | |
| 119 | - selectedCode, | |
| 120 | - content, | |
| 121 | - slashCommandWithInput, | |
| 122 | - }; | |
| 123 | - }, | |
| 124 | -); |
modified gui/src/redux/thunks/streamNormalInput.ts +6 −0
| @@ -8,6 +8,8 @@ | ||
| 8 | 8 | import { |
| 9 | 9 | abortStream, |
| 10 | 10 | addPromptCompletionPair, |
| 11 | + setActive, | |
| 12 | + setInactive, | |
| 11 | 13 | setToolGenerated, |
| 12 | 14 | streamUpdate, |
| 13 | 15 | } from "../slices/sessionSlice"; |
| @@ -53,6 +55,8 @@ | ||
| 53 | 55 | }; |
| 54 | 56 | } |
| 55 | 57 | |
| 58 | + dispatch(setActive()); | |
| 59 | + | |
| 56 | 60 | // Send request |
| 57 | 61 | const gen = extra.ideMessenger.llmStreamChat( |
| 58 | 62 | { |
| @@ -76,6 +80,8 @@ | ||
| 76 | 80 | next = await gen.next(); |
| 77 | 81 | } |
| 78 | 82 | |
| 83 | + dispatch(setInactive()); | |
| 84 | + | |
| 79 | 85 | // Attach prompt log and end thinking for reasoning models |
| 80 | 86 | if (next.done && next.value) { |
| 81 | 87 | dispatch(addPromptCompletionPair([next.value])); |
modified gui/src/redux/thunks/streamResponse.ts +27 −20
| @@ -5,6 +5,7 @@ | ||
| 5 | 5 | import { getApplicableRules } from "core/llm/rules/getSystemMessageWithRules"; |
| 6 | 6 | import posthog from "posthog-js"; |
| 7 | 7 | import { v4 as uuidv4 } from "uuid"; |
| 8 | +import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils/resolveEditorContent"; | |
| 8 | 9 | import { getBaseSystemMessage } from "../../util"; |
| 9 | 10 | import { selectSelectedChatModel } from "../slices/configSlice"; |
| 10 | 11 | import { |
| @@ -13,7 +14,6 @@ | ||
| 13 | 14 | updateHistoryItemAtIndex, |
| 14 | 15 | } from "../slices/sessionSlice"; |
| 15 | 16 | import { ThunkApiType } from "../store"; |
| 16 | -import { gatherContext } from "./gatherContext"; | |
| 17 | 17 | import { resetStateForNewMessage } from "./resetStateForNewMessage"; |
| 18 | 18 | import { streamNormalInput } from "./streamNormalInput"; |
| 19 | 19 | import { streamThunkWrapper } from "./streamThunkWrapper"; |
| @@ -25,15 +25,11 @@ | ||
| 25 | 25 | editorState: JSONContent; |
| 26 | 26 | modifiers: InputModifiers; |
| 27 | 27 | index?: number; |
| 28 | - promptPreamble?: string; | |
| 29 | 28 | }, |
| 30 | 29 | ThunkApiType |
| 31 | 30 | >( |
| 32 | 31 | "chat/streamResponse", |
| 33 | - async ( | |
| 34 | - { editorState, modifiers, index, promptPreamble }, | |
| 35 | - { dispatch, extra, getState }, | |
| 36 | - ) => { | |
| 32 | + async ({ editorState, modifiers, index }, { dispatch, extra, getState }) => { | |
| 37 | 33 | await dispatch( |
| 38 | 34 | streamThunkWrapper(async () => { |
| 39 | 35 | const state = getState(); |
| @@ -49,19 +45,30 @@ | ||
| 49 | 45 | ); |
| 50 | 46 | resetStateForNewMessage(); |
| 51 | 47 | |
| 52 | - const result = await dispatch( | |
| 53 | - gatherContext({ | |
| 54 | - editorState, | |
| 55 | - modifiers, | |
| 56 | - promptPreamble, | |
| 57 | - }), | |
| 58 | - ); | |
| 48 | + const defaultContextProviders = | |
| 49 | + state.config.config.experimental?.defaultContext ?? []; | |
| 50 | + | |
| 51 | + if (!selectedChatModel) { | |
| 52 | + console.error( | |
| 53 | + "gatherContext thunk: Cannot gather context, no model selected", | |
| 54 | + ); | |
| 55 | + throw new Error("No chat model selected"); | |
| 56 | + } | |
| 57 | + | |
| 58 | + // Resolve context providers and construct new history | |
| 59 | 59 | const { |
| 60 | 60 | selectedContextItems, |
| 61 | 61 | selectedCode, |
| 62 | 62 | content, |
| 63 | - slashCommandWithInput, | |
| 64 | - } = unwrapResult(result); | |
| 63 | + legacyCommandWithInput, | |
| 64 | + } = await resolveEditorContent({ | |
| 65 | + editorState, | |
| 66 | + modifiers, | |
| 67 | + ideMessenger: extra.ideMessenger, | |
| 68 | + defaultContextProviders, | |
| 69 | + availableSlashCommands: state.config.config.slashCommands, | |
| 70 | + dispatch, | |
| 71 | + }); | |
| 65 | 72 | |
| 66 | 73 | // symbols for both context items AND selected codeblocks |
| 67 | 74 | const filesForSymbols = [ |
| @@ -133,9 +140,9 @@ | ||
| 133 | 140 | }); |
| 134 | 141 | posthog.capture("userInput", {}); |
| 135 | 142 | |
| 136 | - if (slashCommandWithInput) { | |
| 143 | + if (legacyCommandWithInput) { | |
| 137 | 144 | posthog.capture("step run", { |
| 138 | - step_name: slashCommandWithInput.command.name, | |
| 145 | + step_name: legacyCommandWithInput.command.name, | |
| 139 | 146 | params: {}, |
| 140 | 147 | }); |
| 141 | 148 | } |
| @@ -144,12 +151,12 @@ | ||
| 144 | 151 | await dispatch( |
| 145 | 152 | streamNormalInput({ |
| 146 | 153 | messages, |
| 147 | - legacySlashCommandData: slashCommandWithInput | |
| 154 | + legacySlashCommandData: legacyCommandWithInput | |
| 148 | 155 | ? { |
| 149 | - command: slashCommandWithInput.command, | |
| 156 | + command: legacyCommandWithInput.command, | |
| 150 | 157 | contextItems: selectedContextItems, |
| 151 | 158 | historyIndex: inputIndex, |
| 152 | - input: slashCommandWithInput.input, | |
| 159 | + input: legacyCommandWithInput.input, | |
| 153 | 160 | selectedCode, |
| 154 | 161 | } |
| 155 | 162 | : undefined, |
modified gui/src/redux/thunks/streamResponseAfterToolCall.ts +1 −7
| @@ -4,11 +4,7 @@ | ||
| 4 | 4 | import { renderContextItems } from "core/util/messageContent"; |
| 5 | 5 | import { getBaseSystemMessage } from "../../util"; |
| 6 | 6 | import { selectSelectedChatModel } from "../slices/configSlice"; |
| 7 | -import { | |
| 8 | - addContextItemsAtIndex, | |
| 9 | - setActive, | |
| 10 | - streamUpdate, | |
| 11 | -} from "../slices/sessionSlice"; | |
| 7 | +import { addContextItemsAtIndex, streamUpdate } from "../slices/sessionSlice"; | |
| 12 | 8 | import { ThunkApiType } from "../store"; |
| 13 | 9 | import { findToolCall } from "../util"; |
| 14 | 10 | import { resetStateForNewMessage } from "./resetStateForNewMessage"; |
| @@ -63,8 +59,6 @@ | ||
| 63 | 59 | }), |
| 64 | 60 | ); |
| 65 | 61 | |
| 66 | - dispatch(setActive()); | |
| 67 | - | |
| 68 | 62 | const updatedHistory = getState().session.history; |
| 69 | 63 | const messageMode = getState().session.mode; |
| 70 | 64 |
modified gui/src/redux/thunks/streamThunkWrapper.tsx +0 −2
| @@ -1,6 +1,5 @@ | ||
| 1 | 1 | import { createAsyncThunk } from "@reduxjs/toolkit"; |
| 2 | 2 | import StreamErrorDialog from "../../pages/gui/StreamError"; |
| 3 | -import { setInactive } from "../slices/sessionSlice"; | |
| 4 | 3 | import { setDialogMessage, setShowDialog } from "../slices/uiSlice"; |
| 5 | 4 | import { ThunkApiType } from "../store"; |
| 6 | 5 | import { cancelStream } from "./cancelStream"; |
| @@ -22,7 +21,6 @@ | ||
| 22 | 21 | }), |
| 23 | 22 | ); |
| 24 | 23 | } |
| 25 | - dispatch(setInactive()); | |
| 26 | 24 | } catch (e) { |
| 27 | 25 | dispatch(cancelStream()); |
| 28 | 26 | dispatch(setDialogMessage(<StreamErrorDialog error={e} />)); |
modified gui/src/util/clientTools/callClientTool.ts +0 −1
| @@ -8,7 +8,6 @@ | ||
| 8 | 8 | getState: () => RootState; |
| 9 | 9 | dispatch: AppThunkDispatch; |
| 10 | 10 | ideMessenger: IIdeMessenger; |
| 11 | - streamId?: string; | |
| 12 | 11 | } |
| 13 | 12 | |
| 14 | 13 | export interface ClientToolOutput { |
modified gui/src/util/clientTools/editImpl.ts +5 −24
| @@ -1,14 +1,11 @@ | ||
| 1 | 1 | import { resolveRelativePathInDir } from "core/util/ideUtils"; |
| 2 | +import { v4 as uuid } from "uuid"; | |
| 2 | 3 | import { ClientToolImpl } from "./callClientTool"; |
| 3 | - | |
| 4 | 4 | export const editToolImpl: ClientToolImpl = async ( |
| 5 | 5 | args, |
| 6 | 6 | toolCallId, |
| 7 | 7 | extras, |
| 8 | 8 | ) => { |
| 9 | - if (!extras.streamId) { | |
| 10 | - throw new Error("Invalid apply state"); | |
| 11 | - } | |
| 12 | 9 | const firstUriMatch = await resolveRelativePathInDir( |
| 13 | 10 | args.filepath, |
| 14 | 11 | extras.ideMessenger.ide, |
| @@ -16,30 +13,14 @@ | ||
| 16 | 13 | if (!firstUriMatch) { |
| 17 | 14 | throw new Error(`${args.filepath} does not exist`); |
| 18 | 15 | } |
| 19 | - const apply = await extras.ideMessenger.request("applyToFile", { | |
| 20 | - streamId: extras.streamId, | |
| 16 | + const streamId = uuid(); | |
| 17 | + extras.ideMessenger.post("applyToFile", { | |
| 18 | + streamId, | |
| 21 | 19 | text: args.changes, |
| 22 | 20 | toolCallId, |
| 23 | 21 | filepath: firstUriMatch, |
| 24 | 22 | }); |
| 25 | - if (apply.status === "error") { | |
| 26 | - throw new Error(apply.error); | |
| 27 | - } | |
| 28 | - const state = extras.getState(); | |
| 29 | - const autoAccept = !!state.config.config.ui?.autoAcceptEditToolDiffs; | |
| 30 | - if (autoAccept) { | |
| 31 | - const out = await extras.ideMessenger.request("acceptDiff", { | |
| 32 | - streamId: extras.streamId, | |
| 33 | - filepath: firstUriMatch, | |
| 34 | - }); | |
| 35 | - if (out.status === "error") { | |
| 36 | - throw new Error(out.error); | |
| 37 | - } | |
| 38 | - return { | |
| 39 | - respondImmediately: true, | |
| 40 | - output: undefined, // TODO - feed edit results back to model (also in parallel listeners) | |
| 41 | - }; | |
| 42 | - } | |
| 23 | + | |
| 43 | 24 | return { |
| 44 | 25 | respondImmediately: false, |
| 45 | 26 | output: undefined, // No immediate output. |
modified gui/src/util/index.ts +5 −5
| @@ -1,12 +1,12 @@ | ||
| 1 | 1 | import { MessageModes, ModelDescription } from "core"; |
| 2 | 2 | import { ProfileDescription } from "core/config/ProfileLifecycleManager"; |
| 3 | -import _ from "lodash"; | |
| 4 | -import { KeyboardEvent } from "react"; | |
| 5 | -import { getLocalStorage } from "./localStorage"; | |
| 6 | 3 | import { |
| 7 | - DEFAULT_CHAT_SYSTEM_MESSAGE, | |
| 8 | 4 | DEFAULT_AGENT_SYSTEM_MESSAGE, |
| 5 | + DEFAULT_CHAT_SYSTEM_MESSAGE, | |
| 9 | 6 | } from "core/llm/constructMessages"; |
| 7 | +import _ from "lodash"; | |
| 8 | +import { KeyboardEvent as ReactKeyboardEvent } from "react"; | |
| 9 | +import { getLocalStorage } from "./localStorage"; | |
| 10 | 10 | |
| 11 | 11 | export type Platform = "mac" | "linux" | "windows" | "unknown"; |
| 12 | 12 | |
| @@ -26,7 +26,7 @@ | ||
| 26 | 26 | export function isMetaEquivalentKeyPressed({ |
| 27 | 27 | metaKey, |
| 28 | 28 | ctrlKey, |
| 29 | -}: KeyboardEvent): boolean { | |
| 29 | +}: KeyboardEvent | ReactKeyboardEvent): boolean { | |
| 30 | 30 | const platform = getPlatform(); |
| 31 | 31 | switch (platform) { |
| 32 | 32 | case "mac": |
added gui/src/util/test/config.ts +67 −0
| @@ -0,0 +1,67 @@ | ||
| 1 | +import { EnhancedStore } from "@reduxjs/toolkit"; | |
| 2 | +import { BrowserSerializedContinueConfig, ModelDescription } from "core"; | |
| 3 | +import { SerializedOrgWithProfiles } from "core/config/ProfileLifecycleManager"; | |
| 4 | +import { copyOf } from "core/util"; | |
| 5 | +import { MockIdeMessenger } from "../../context/MockIdeMessenger"; | |
| 6 | + | |
| 7 | +interface TestConfigUpdateParams { | |
| 8 | + store: EnhancedStore; | |
| 9 | + ideMessenger: MockIdeMessenger; | |
| 10 | + newProfileId?: string; | |
| 11 | + newOrgId?: string; | |
| 12 | + newOrgs?: SerializedOrgWithProfiles[]; | |
| 13 | + editConfig?: ( | |
| 14 | + current: BrowserSerializedContinueConfig, | |
| 15 | + ) => BrowserSerializedContinueConfig; | |
| 16 | +} | |
| 17 | + | |
| 18 | +export function triggerConfigUpdate({ | |
| 19 | + store, | |
| 20 | + ideMessenger, | |
| 21 | + editConfig, | |
| 22 | + newOrgs, | |
| 23 | + newOrgId, | |
| 24 | + newProfileId, | |
| 25 | +}: TestConfigUpdateParams) { | |
| 26 | + const state = store.getState(); | |
| 27 | + ideMessenger.mockMessageToWebview("configUpdate", { | |
| 28 | + organizations: newOrgs ?? state.profiles.organizations, | |
| 29 | + selectedOrgId: newOrgId ?? state.profiles.selectedOrganizationId, | |
| 30 | + profileId: newProfileId ?? state.profiles.selectedProfileId, | |
| 31 | + result: { | |
| 32 | + config: editConfig | |
| 33 | + ? editConfig(copyOf(state.config.config)) | |
| 34 | + : state.config.config, | |
| 35 | + configLoadInterrupted: false, | |
| 36 | + errors: [], | |
| 37 | + }, | |
| 38 | + }); | |
| 39 | +} | |
| 40 | + | |
| 41 | +export function addAndSelectChatModel( | |
| 42 | + store: EnhancedStore, | |
| 43 | + ideMessenger: MockIdeMessenger, | |
| 44 | + llmDesc: ModelDescription, | |
| 45 | +) { | |
| 46 | + triggerConfigUpdate({ | |
| 47 | + store, | |
| 48 | + ideMessenger, | |
| 49 | + editConfig(current) { | |
| 50 | + current.modelsByRole.chat.push(llmDesc); | |
| 51 | + current.selectedModelByRole.chat = llmDesc; | |
| 52 | + return current; | |
| 53 | + }, | |
| 54 | + }); | |
| 55 | +} | |
| 56 | + | |
| 57 | +export function addAndSelectMockLlm( | |
| 58 | + store: EnhancedStore, | |
| 59 | + ideMessenger: MockIdeMessenger, | |
| 60 | +) { | |
| 61 | + addAndSelectChatModel(store, ideMessenger, { | |
| 62 | + model: "mock", | |
| 63 | + provider: "mock", | |
| 64 | + title: "Mock LLM", | |
| 65 | + underlyingProviderName: "mock", | |
| 66 | + }); | |
| 67 | +} |
added gui/src/util/test/utils.ts +102 −0
| @@ -0,0 +1,102 @@ | ||
| 1 | +import { screen, waitFor } from "@testing-library/dom"; | |
| 2 | +import { act } from "@testing-library/react"; | |
| 3 | +import { Editor } from "@tiptap/core"; | |
| 4 | +import { ChatMessage } from "core"; | |
| 5 | +import { MockIdeMessenger } from "../../context/MockIdeMessenger"; | |
| 6 | + | |
| 7 | +function logDomText() { | |
| 8 | + const bodyText = document.body.innerHTML; | |
| 9 | + const parser = new DOMParser(); | |
| 10 | + const doc = parser.parseFromString(bodyText, "text/html"); | |
| 11 | + let cleaned = doc.body.textContent ?? ""; | |
| 12 | + cleaned = cleaned?.replace( | |
| 13 | + "No resultsAaModelsRulesDocsPromptsToolsMCPCreate your first assistant", | |
| 14 | + "", | |
| 15 | + ); | |
| 16 | + cleaned = cleaned?.replace( | |
| 17 | + "Alt⏎ Active file⏎ Enter⏎Log in to access a free trial of theModels Add-OnLog in to Continue HubOr, configure your own models", | |
| 18 | + "", | |
| 19 | + ); | |
| 20 | + cleaned = cleaned.replaceAll("Select model", ""); | |
| 21 | + cleaned = cleaned.replaceAll("Mock LLM", ""); | |
| 22 | + cleaned = cleaned.replaceAll(/^Chat|Chat$/g, ""); | |
| 23 | + console.log(cleaned || "No body content"); | |
| 24 | +} | |
| 25 | + | |
| 26 | +export function logAllTestIds() { | |
| 27 | + const elements = document.querySelectorAll("*"); | |
| 28 | + | |
| 29 | + const testIds = Array.from(elements) | |
| 30 | + .map((el) => Array.from(el.attributes)) | |
| 31 | + .flat() | |
| 32 | + .filter((a) => a.name === "data-testid") | |
| 33 | + .map((a) => a.value); | |
| 34 | + console.log("Available test ids", testIds); | |
| 35 | +} | |
| 36 | +export async function getElementByTestId(testId: string): Promise<HTMLElement> { | |
| 37 | + try { | |
| 38 | + const testIdElement = await waitFor(() => screen.findByTestId(testId)); | |
| 39 | + expect(testIdElement).toBeInTheDocument(); | |
| 40 | + return testIdElement; | |
| 41 | + } catch (e) { | |
| 42 | + logAllTestIds(); | |
| 43 | + throw new Error(`Element with testId "${testId}" not found`); | |
| 44 | + } | |
| 45 | +} | |
| 46 | + | |
| 47 | +export async function verifyNotPresentByTestId(testId: string): Promise<void> { | |
| 48 | + const element = await waitFor(() => screen.queryByTestId(testId)); | |
| 49 | + expect(element).not.toBeInTheDocument(); | |
| 50 | +} | |
| 51 | + | |
| 52 | +export async function verifyNotPresentByText(text: string): Promise<void> { | |
| 53 | + const element = screen.queryByText(text); | |
| 54 | + expect(element).not.toBeInTheDocument(); | |
| 55 | +} | |
| 56 | + | |
| 57 | +export async function getElementByText(text: string): Promise<HTMLElement> { | |
| 58 | + try { | |
| 59 | + const textElement = await waitFor(() => screen.findByText(text)); | |
| 60 | + expect(textElement).toBeInTheDocument(); | |
| 61 | + return textElement; | |
| 62 | + } catch (e) { | |
| 63 | + logDomText(); | |
| 64 | + throw new Error(`Element with text "${text}" not found.`); | |
| 65 | + } | |
| 66 | +} | |
| 67 | + | |
| 68 | +export async function getMainEditor(): Promise<Editor> { | |
| 69 | + const editorElement = await getElementByTestId("editor-input-main"); | |
| 70 | + if ("editor" in editorElement) { | |
| 71 | + return editorElement.editor as Editor; | |
| 72 | + } else { | |
| 73 | + throw new Error("Main editor not found within editor container"); | |
| 74 | + } | |
| 75 | +} | |
| 76 | + | |
| 77 | +export async function sendInputWithMockedResponse( | |
| 78 | + ideMessenger: MockIdeMessenger, | |
| 79 | + input: string, | |
| 80 | + response: ChatMessage[], | |
| 81 | +): Promise<void> { | |
| 82 | + // Setup the mock response before any actions | |
| 83 | + ideMessenger.chatResponse = response; | |
| 84 | + | |
| 85 | + // Wait for the editor to be in the document | |
| 86 | + const editor = await getMainEditor(); | |
| 87 | + | |
| 88 | + // Find the submit button | |
| 89 | + const sendButton = await getElementByTestId("submit-input-button"); | |
| 90 | + | |
| 91 | + // Insert content into the editor | |
| 92 | + await act(async () => { | |
| 93 | + editor.commands.insertContent(input); | |
| 94 | + }); | |
| 95 | + | |
| 96 | + await getElementByText(input); | |
| 97 | + | |
| 98 | + // Click the send button | |
| 99 | + await act(async () => { | |
| 100 | + sendButton.click(); | |
| 101 | + }); | |
| 102 | +} |
modified gui/vite.config.ts +13 −0
| @@ -32,5 +32,18 @@ | ||
| 32 | 32 | globals: true, |
| 33 | 33 | environment: "jsdom", |
| 34 | 34 | setupFiles: "./src/util/test/setupTests.ts", |
| 35 | + onConsoleLog(log, type) { | |
| 36 | + if (type === "stderr") { | |
| 37 | + if ( | |
| 38 | + [ | |
| 39 | + "contentEditable", | |
| 40 | + "An update to Chat inside a test was not wrapped in act", | |
| 41 | + ].some((text) => log.includes(text)) | |
| 42 | + ) { | |
| 43 | + return false; | |
| 44 | + } | |
| 45 | + } | |
| 46 | + return true; | |
| 47 | + }, | |
| 35 | 48 | }, |
| 36 | 49 | }); |
added packages/config-yaml/CHANGELOG.md +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 packages/config-yaml/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 packages/config-yaml/package.json +8 −3
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "name": "@continuedev/config-yaml", |
| 3 | - "version": "1.0.94", | |
| 3 | + "version": "1.0.95", | |
| 4 | 4 | "description": "", |
| 5 | 5 | "main": "dist/index.js", |
| 6 | 6 | "types": "dist/index.d.ts", |
| @@ -13,7 +13,7 @@ | ||
| 13 | 13 | } |
| 14 | 14 | }, |
| 15 | 15 | "bin": { |
| 16 | - "@continuedev/config-yaml": "./dist/cli.js" | |
| 16 | + "config-yaml": "./dist/cli.js" | |
| 17 | 17 | }, |
| 18 | 18 | "scripts": { |
| 19 | 19 | "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest", |
| @@ -34,6 +34,11 @@ | ||
| 34 | 34 | "jest": "^29.7.0", |
| 35 | 35 | "ts-jest": "^29.2.3", |
| 36 | 36 | "ts-node": "^10.9.2", |
| 37 | - "zod-to-json-schema": "^3.24.5" | |
| 37 | + "zod-to-json-schema": "^3.24.5", | |
| 38 | + "@semantic-release/changelog": "^6.0.3", | |
| 39 | + "@semantic-release/git": "^10.0.1", | |
| 40 | + "@semantic-release/github": "^9.2.6", | |
| 41 | + "@semantic-release/npm": "^10.0.6", | |
| 42 | + "semantic-release": "^21.1.2" | |
| 38 | 43 | } |
| 39 | 44 | } |
modified packages/config-yaml/release.config.js +3 −9
| @@ -1,9 +1,3 @@ | ||
| 1 | -export default { | |
| 2 | - branches: ["main"], | |
| 3 | - plugins: [ | |
| 4 | - "@semantic-release/commit-analyzer", | |
| 5 | - "@semantic-release/release-notes-generator", | |
| 6 | - "@semantic-release/npm", | |
| 7 | - "@semantic-release/github", | |
| 8 | - ], | |
| 9 | -}; | |
| 1 | +import createReleaseConfig from "../shared-release.config.js"; | |
| 2 | + | |
| 3 | +export default createReleaseConfig("config-yaml"); |
added packages/fetch/release.config.js +3 −0
| @@ -0,0 +1,3 @@ | ||
| 1 | +import createReleaseConfig from "../shared-release.config.js"; | |
| 2 | + | |
| 3 | +export default createReleaseConfig("fetch"); |
added packages/llm-info/release.config.js +3 −0
| @@ -0,0 +1,3 @@ | ||
| 1 | +import createReleaseConfig from "../shared-release.config.js"; | |
| 2 | + | |
| 3 | +export default createReleaseConfig("llm-info"); |
modified packages/openai-adapters/package-lock.json +2 −2
| @@ -1,12 +1,12 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "name": "@continuedev/openai-adapters", |
| 3 | - "version": "1.0.40", | |
| 3 | + "version": "1.0.42", | |
| 4 | 4 | "lockfileVersion": 3, |
| 5 | 5 | "requires": true, |
| 6 | 6 | "packages": { |
| 7 | 7 | "": { |
| 8 | 8 | "name": "@continuedev/openai-adapters", |
| 9 | - "version": "1.0.40", | |
| 9 | + "version": "1.0.42", | |
| 10 | 10 | "license": "Apache-2.0", |
| 11 | 11 | "dependencies": { |
| 12 | 12 | "@continuedev/config-types": "^1.0.5", |
modified packages/openai-adapters/package.json +1 −1
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "name": "@continuedev/openai-adapters", |
| 3 | - "version": "1.0.40", | |
| 3 | + "version": "1.0.42", | |
| 4 | 4 | "description": "", |
| 5 | 5 | "main": "dist/index.js", |
| 6 | 6 | "types": "dist/index.d.ts", |
added packages/openai-adapters/release.config.js +3 −0
| @@ -0,0 +1,3 @@ | ||
| 1 | +import createReleaseConfig from "../shared-release.config.js"; | |
| 2 | + | |
| 3 | +export default createReleaseConfig("openai-adapters"); |
modified packages/openai-adapters/src/apis/Azure.ts +5 −1
| @@ -63,7 +63,11 @@ | ||
| 63 | 63 | "`env.apiVersion` is a required configuration property for Azure OpenAI", |
| 64 | 64 | ); |
| 65 | 65 | } |
| 66 | - url.pathname = `${url.pathname}/openai/deployments/${config.env.deployment}`; | |
| 66 | + | |
| 67 | + const basePathname = `openai/deployments/${config.env.deployment}`; | |
| 68 | + | |
| 69 | + url.pathname = | |
| 70 | + url.pathname === "/" ? basePathname : `${url.pathname}/${basePathname}`; | |
| 67 | 71 | |
| 68 | 72 | queryParams["api-version"] = config.env.apiVersion; |
| 69 | 73 | } |
modified packages/openai-adapters/src/test/main.test.ts +76 −0
| @@ -173,4 +173,80 @@ | ||
| 173 | 173 | "https://api.example.com", |
| 174 | 174 | ); |
| 175 | 175 | }); |
| 176 | + | |
| 177 | + it("should configure Azure OpenAI client with root URL and trailing slash", () => { | |
| 178 | + const azure = constructLlmApi({ | |
| 179 | + provider: "azure", | |
| 180 | + apiKey: "sk-xxx", | |
| 181 | + apiBase: "https://test-azure-openai.azure.com/", | |
| 182 | + env: { | |
| 183 | + deployment: "gpt-4.1", | |
| 184 | + apiType: "azure-openai", | |
| 185 | + apiVersion: "2023-05-15", | |
| 186 | + }, | |
| 187 | + }); | |
| 188 | + | |
| 189 | + // The Azure client modifies the baseURL to include the deployment | |
| 190 | + expect((azure as OpenAIApi).openai.baseURL).toBe( | |
| 191 | + "https://test-azure-openai.azure.com/openai/deployments/gpt-4.1", | |
| 192 | + ); | |
| 193 | + expect((azure as OpenAIApi).openai.apiKey).toBe("sk-xxx"); | |
| 194 | + }); | |
| 195 | + | |
| 196 | + it("should configure Azure OpenAI client with path and trailing slash", () => { | |
| 197 | + const azure = constructLlmApi({ | |
| 198 | + provider: "azure", | |
| 199 | + apiKey: "sk-xxx", | |
| 200 | + apiBase: "https://test-azure-openai.azure.com/v1/", | |
| 201 | + env: { | |
| 202 | + deployment: "gpt-4.1", | |
| 203 | + apiType: "azure-openai", | |
| 204 | + apiVersion: "2023-05-15", | |
| 205 | + }, | |
| 206 | + }); | |
| 207 | + | |
| 208 | + // The Azure client modifies the baseURL to include the deployment | |
| 209 | + expect((azure as OpenAIApi).openai.baseURL).toBe( | |
| 210 | + "https://test-azure-openai.azure.com/v1/openai/deployments/gpt-4.1", | |
| 211 | + ); | |
| 212 | + expect((azure as OpenAIApi).openai.apiKey).toBe("sk-xxx"); | |
| 213 | + }); | |
| 214 | + | |
| 215 | + it("should configure Azure OpenAI client with root URL and no trailing slash", () => { | |
| 216 | + const azure = constructLlmApi({ | |
| 217 | + provider: "azure", | |
| 218 | + apiKey: "sk-xxx", | |
| 219 | + apiBase: "https://test-azure-openai.azure.com", | |
| 220 | + env: { | |
| 221 | + deployment: "gpt-4.1", | |
| 222 | + apiType: "azure-openai", | |
| 223 | + apiVersion: "2023-05-15", | |
| 224 | + }, | |
| 225 | + }); | |
| 226 | + | |
| 227 | + // The Azure client modifies the baseURL to include the deployment | |
| 228 | + expect((azure as OpenAIApi).openai.baseURL).toBe( | |
| 229 | + "https://test-azure-openai.azure.com/openai/deployments/gpt-4.1", | |
| 230 | + ); | |
| 231 | + expect((azure as OpenAIApi).openai.apiKey).toBe("sk-xxx"); | |
| 232 | + }); | |
| 233 | + | |
| 234 | + it("should configure Azure OpenAI client with path and no trailing slash", () => { | |
| 235 | + const azure = constructLlmApi({ | |
| 236 | + provider: "azure", | |
| 237 | + apiKey: "sk-xxx", | |
| 238 | + apiBase: "https://test-azure-openai.azure.com/v1", | |
| 239 | + env: { | |
| 240 | + deployment: "gpt-4.1", | |
| 241 | + apiType: "azure-openai", | |
| 242 | + apiVersion: "2023-05-15", | |
| 243 | + }, | |
| 244 | + }); | |
| 245 | + | |
| 246 | + // The Azure client modifies the baseURL to include the deployment | |
| 247 | + expect((azure as OpenAIApi).openai.baseURL).toBe( | |
| 248 | + "https://test-azure-openai.azure.com/v1/openai/deployments/gpt-4.1", | |
| 249 | + ); | |
| 250 | + expect((azure as OpenAIApi).openai.apiKey).toBe("sk-xxx"); | |
| 251 | + }); | |
| 176 | 252 | }); |
modified packages/openai-adapters/src/util/parseArgs.ts +1 −1
| @@ -3,7 +3,7 @@ | ||
| 3 | 3 | errorId?: string, |
| 4 | 4 | ): Record<string, any> { |
| 5 | 5 | try { |
| 6 | - return JSON.parse(args ?? "{}"); | |
| 6 | + return JSON.parse(args?.trim() || "{}"); | |
| 7 | 7 | } catch (e) { |
| 8 | 8 | const identifier = errorId ? `Call: ${errorId}\nArgs:${args}\n` : ""; |
| 9 | 9 | console.error( |
added packages/shared-release.config.js +34 −0
| @@ -0,0 +1,34 @@ | ||
| 1 | +export default function createReleaseConfig(packageName) { | |
| 2 | + return { | |
| 3 | + branches: ["main"], | |
| 4 | + tagFormat: `@continuedev/${packageName}@\${version}`, | |
| 5 | + plugins: [ | |
| 6 | + [ | |
| 7 | + "@semantic-release/commit-analyzer", | |
| 8 | + { | |
| 9 | + releaseRules: [ | |
| 10 | + { scope: `packages/${packageName}`, release: "patch" }, | |
| 11 | + { scope: `packages/${packageName}`, type: "fix", release: "patch" }, | |
| 12 | + { scope: "packages/config-yaml", type: "feat", release: "minor" }, | |
| 13 | + { | |
| 14 | + scope: `packages/${packageName}`, | |
| 15 | + breaking: true, | |
| 16 | + release: "major", | |
| 17 | + }, | |
| 18 | + ], | |
| 19 | + }, | |
| 20 | + ], | |
| 21 | + "@semantic-release/release-notes-generator", | |
| 22 | + "@semantic-release/changelog", | |
| 23 | + "@semantic-release/npm", | |
| 24 | + [ | |
| 25 | + "@semantic-release/git", | |
| 26 | + { | |
| 27 | + assets: ["CHANGELOG.md", "package.json"], | |
| 28 | + message: `chore(release): @continuedev/${packageName}@\${nextRelease.version} [skip ci]`, | |
| 29 | + }, | |
| 30 | + ], | |
| 31 | + "@semantic-release/github", | |
| 32 | + ], | |
| 33 | + }; | |
| 34 | +} |
added scripts/build-packages.ps1 +13 −0
| @@ -0,0 +1,13 @@ | ||
| 1 | +Push-Location packages | |
| 2 | + | |
| 3 | +Push-Location "openai-adapters" | |
| 4 | +npm ci | |
| 5 | +npm run build | |
| 6 | +Pop-Location | |
| 7 | + | |
| 8 | +Push-Location "config-yaml" | |
| 9 | +npm ci | |
| 10 | +npm run build | |
| 11 | +Pop-Location | |
| 12 | + | |
| 13 | +Pop-Location | |
| No newline at the end of the file |
added scripts/build-packages.sh +13 −0
| @@ -0,0 +1,13 @@ | ||
| 1 | +# Build @continuedev packages for monorepo style linking | |
| 2 | + | |
| 3 | +cd packages | |
| 4 | +cd openai-adapters | |
| 5 | + | |
| 6 | +npm ci | |
| 7 | +npm run build | |
| 8 | + | |
| 9 | +cd .. | |
| 10 | +cd config-yaml | |
| 11 | + | |
| 12 | +npm ci | |
| 13 | +npm run build |
added scripts/create-docker-ssh-container.sh +35 −0
| @@ -0,0 +1,35 @@ | ||
| 1 | +# create the docker file | |
| 2 | + | |
| 3 | +cat > Dockerfile << 'EOF' | |
| 4 | +FROM ubuntu:latest | |
| 5 | +ENV DEBIAN_FRONTEND=noninteractive | |
| 6 | +# Install SSH server | |
| 7 | +RUN apt-get update && apt-get install -y openssh-server | |
| 8 | +# Configure SSH | |
| 9 | +RUN mkdir /var/run/sshd | |
| 10 | +RUN echo 'root:my_password' | chpasswd | |
| 11 | +# Allow root login | |
| 12 | +RUN sed -i 's/#PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config | |
| 13 | +# SSH login fix | |
| 14 | +RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd | |
| 15 | +EXPOSE 22 | |
| 16 | +CMD ["/usr/sbin/sshd", "-D"] | |
| 17 | +EOF | |
| 18 | + | |
| 19 | +docker build -t continue-ubuntu-ssh . # build the image | |
| 20 | + | |
| 21 | +rm Dockerfile # remove the created Dockerfile | |
| 22 | + | |
| 23 | +container_name="continue-ssh-container" | |
| 24 | + | |
| 25 | +docker run -d -p 2222:22 --name $container_name continue-ubuntu-ssh # run the container | |
| 26 | + | |
| 27 | +echo "docker container ${container_name} running on port 2222" | |
| 28 | + | |
| 29 | +# add the instructions | |
| 30 | +bold=$(tput bold) | |
| 31 | +normal=$(tput sgr0) | |
| 32 | + | |
| 33 | +echo "\n--------------------------------------" | |
| 34 | +echo "now ssh into vscode (using remote explorer) with the following command: ${bold}ssh root@localhost -p 2222${normal}" | |
| 35 | +echo "use the following password - \"${bold}my_password${normal}\"" |
modified scripts/install-dependencies.sh +1 −1
| @@ -57,7 +57,7 @@ | ||
| 57 | 57 | # This does way too many things inline but is the common denominator between many of the scripts |
| 58 | 58 | npm install |
| 59 | 59 | npm link @continuedev/core |
| 60 | -npm run prepackage | |
| 60 | +# npm run prepackage # not required since npm run package has prescript of prepackage | |
| 61 | 61 | npm run package |
| 62 | 62 | popd |
| 63 | 63 |