diff --git a/.github/actions/run-jetbrains-tests/action.yml b/.github/actions/run-jetbrains-tests/action.yml index e05437f77..77f6ceff3 100644 --- a/.github/actions/run-jetbrains-tests/action.yml +++ b/.github/actions/run-jetbrains-tests/action.yml @@ -44,6 +44,7 @@ runs: - name: Setup FFmpeg uses: AnimMouse/setup-ffmpeg@v1 with: + version: 7.1 token: ${{ inputs.github-token }} - name: Setup Gradle @@ -135,14 +136,22 @@ runs: shell: bash run: | cd extensions/intellij - mv video build/reports + if [ -d "video" ]; then + mv video build/reports + else + echo "No video directory found to move" + fi - name: Copy logs if: ${{ failure() }} shell: bash run: | cd extensions/intellij - mv build/idea-sandbox/system/log/ build/reports + if [ -d "build/idea-sandbox/system/log/" ]; then + mv build/idea-sandbox/system/log/ build/reports + else + echo "No log directory found to copy" + fi - name: Save fails report if: ${{ failure() }} diff --git a/.github/actions/track-rerun/action.yml b/.github/actions/track-rerun/action.yml new file mode 100644 index 000000000..d9bcb2423 --- /dev/null +++ b/.github/actions/track-rerun/action.yml @@ -0,0 +1,19 @@ +name: Track Workflow Rerun +description: Track when GitHub Actions workflows are rerun (attempt > 1) + +runs: + using: composite + steps: + # Eventually we can start logging this to monitor codebase health (e.g. to Slack, PostHog, etc.) + - name: Track workflow rerun + if: github.run_attempt > 1 + shell: bash + run: | + echo "🔄 Workflow rerun detected - Attempt #${{ github.run_attempt }}" + echo "📊 Workflow: ${{ github.workflow }}" + echo "🔀 PR: ${{ github.event.pull_request.number || 'N/A' }}" + echo "📝 Commit: ${{ github.sha }}" + echo "👤 Actor: ${{ github.actor }}" + echo "⏰ Timestamp: $(date -u +%Y-%m-%dT%H:%M:%SZ)" + echo "" + echo "::notice title=Workflow Rerun Detected::This is attempt #${{ github.run_attempt }} of workflow '${{ github.workflow }}'" diff --git a/.github/workflows/cli-pr-checks.yml b/.github/workflows/cli-pr-checks.yml index b08207074..bd58ad7c6 100644 --- a/.github/workflows/cli-pr-checks.yml +++ b/.github/workflows/cli-pr-checks.yml @@ -3,8 +3,6 @@ name: CLI PR Checks on: pull_request: branches: [main] - paths: - - "extensions/cli/**" permissions: contents: read @@ -12,6 +10,14 @@ permissions: issues: write jobs: + track-rerun: + runs-on: ubuntu-latest + if: github.run_attempt > 1 + steps: + - uses: actions/checkout@v4 + - name: Track workflow rerun + uses: ./.github/actions/track-rerun + lint: runs-on: ubuntu-latest steps: @@ -90,19 +96,18 @@ jobs: cd extensions/cli npm run test:smoke - # e2e tests are failing on Windows specifically - likely due to stdout flush issues - name: Run tests - if: matrix.os != 'windows-latest' run: | cd extensions/cli npm test - - name: Run tests (excluding e2e on Windows) - if: matrix.os == 'windows-latest' - shell: bash + # e2e tests are failing on Windows specifically - likely due to stdout flush issues + - name: Run e2e tests + if: matrix.os != 'windows-latest' run: | cd extensions/cli - npm test -- --exclude='**/*.e2e.*' --exclude='**/e2e/**' + npm run test:e2e + # GitHub does not have a way of requiring that all checks pass (you must manually select each job) # This action at least lets us manage the list of required tests via source control diff --git a/.github/workflows/compliance.yaml b/.github/workflows/compliance.yaml index 6ab98b27e..76c21d6b1 100644 --- a/.github/workflows/compliance.yaml +++ b/.github/workflows/compliance.yaml @@ -36,7 +36,7 @@ jobs: else echo "❌ PR title does not follow conventional commit format" echo "valid=false" >> $GITHUB_OUTPUT - exit 1 + # Don't exit with failure - just mark as invalid for comment fi - name: Add PR title guidance comment diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 317f6355a..23e434ff3 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -257,6 +257,7 @@ jobs: # Publish the plugin to JetBrains Marketplace - name: Publish EAP Plugin if: github.event_name == 'release' || (github.event.inputs.eap_channel == 'true' && github.event.inputs.build_only != 'true') + continue-on-error: true env: PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }} CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }} @@ -267,6 +268,7 @@ jobs: - name: Publish Stable Plugin if: github.event_name == 'release' || (github.event.inputs.stable_channel == 'true' && github.event.inputs.build_only != 'true') + continue-on-error: true env: PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }} CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }} @@ -458,12 +460,6 @@ jobs: name: tests-result path: ${{ github.workspace }}/extensions/intellij/build/reports/tests - # Upload the Kover report to CodeCov - # - name: Upload Code Coverage Report - # uses: codecov/codecov-action@v4 - # with: - # files: ${{ github.workspace }}/build/reports/kover/report.xml - # Run Qodana inspections and provide report inspectCode: if: false diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index cf276f360..785044868 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -9,7 +9,7 @@ on: publish_build: description: "Whether or not to publish the built extension to the VS Code marketplace" required: true - default: false + default: "false" jobs: check_release_name: diff --git a/.github/workflows/pr-checks.yaml b/.github/workflows/pr-checks.yaml index fb91e8d97..e37127d1f 100644 --- a/.github/workflows/pr-checks.yaml +++ b/.github/workflows/pr-checks.yaml @@ -11,6 +11,14 @@ on: - main jobs: + track-rerun: + runs-on: ubuntu-latest + if: github.run_attempt > 1 + steps: + - uses: actions/checkout@v5 + - name: Track workflow rerun + uses: ./.github/actions/track-rerun + prettier-check: runs-on: ubuntu-latest steps: diff --git a/.github/workflows/preview.yaml b/.github/workflows/preview.yaml index 289381034..7e054eb59 100644 --- a/.github/workflows/preview.yaml +++ b/.github/workflows/preview.yaml @@ -9,7 +9,7 @@ on: publish_build: description: "Whether or not to publish the built extension to the VS Code marketplace" required: true - default: false + default: "false" jobs: check_release_name: diff --git a/binary/package-lock.json b/binary/package-lock.json index 6dca092e8..37f2d865d 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -64,7 +64,6 @@ "@sentry/esbuild-plugin": "^4.0.2", "@sentry/node": "^9.43.0", "@sentry/vite-plugin": "^4.0.2", - "@typescript-eslint/eslint-plugin": "^7.8.0", "@xenova/transformers": "2.14.0", "adf-to-md": "^1.1.0", "async-mutex": "^0.5.0", @@ -144,6 +143,8 @@ "@types/tar": "^6.1.13", "@types/uuid": "^9.0.7", "@types/win-ca": "^3.5.4", + "@typescript-eslint/eslint-plugin": "^8.40.0", + "@typescript-eslint/parser": "^8.40.0", "cross-env": "^7.0.3", "esbuild": "0.17.19", "eslint": "^8", @@ -2895,6 +2896,19 @@ "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", "dev": true }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/callsites": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", @@ -3368,6 +3382,20 @@ "node": ">=8" } }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/eastasianwidth": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", @@ -3416,6 +3444,51 @@ "is-arrayish": "^0.2.1" } }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/esbuild": { "version": "0.19.11", "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.19.11.tgz", @@ -3695,12 +3768,15 @@ } }, "node_modules/form-data": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", - "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz", + "integrity": "sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==", + "license": "MIT", "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.2", "mime-types": "^2.1.12" }, "engines": { @@ -3773,7 +3849,6 @@ "version": "1.1.2", "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", - "dev": true, "funding": { "url": "https://github.com/sponsors/ljharb" } @@ -3796,6 +3871,30 @@ "node": "6.* || 8.* || >= 10.*" } }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/get-package-type": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz", @@ -3805,6 +3904,19 @@ "node": ">=8.0.0" } }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/get-stream": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", @@ -3886,6 +3998,18 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/graceful-fs": { "version": "4.2.11", "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", @@ -3909,11 +4033,37 @@ "node": ">=8" } }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/hasown": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", - "dev": true, "dependencies": { "function-bind": "^1.1.2" }, @@ -5184,6 +5334,15 @@ "tmpl": "1.0.5" } }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/merge-stream": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", diff --git a/core/config/load.ts b/core/config/load.ts index f7bb01834..065842052 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -58,7 +58,7 @@ import { import { localPathToUri } from "../util/pathToUri"; import CustomContextProviderClass from "../context/providers/CustomContextProvider"; -import { getToolsForIde } from "../tools"; +import { getBaseToolDefinitions } from "../tools"; import { resolveRelativePathInDir } from "../util/ideUtils"; import { getWorkspaceRcConfigs } from "./json/loadRcConfigs"; import { loadConfigContextProviders } from "./loadContextProviders"; @@ -282,6 +282,7 @@ async function intermediateToFinalConfig({ ...desc, model: modelName, title: modelName, + isFromAutoDetect: true, }, ide.readFile.bind(ide), getUriFromPath, @@ -319,6 +320,7 @@ async function intermediateToFinalConfig({ ...desc.options, model: modelName, logger: llmLogger, + isFromAutoDetect: true, }, }), ); @@ -498,7 +500,7 @@ async function intermediateToFinalConfig({ const continueConfig: ContinueConfig = { ...config, contextProviders, - tools: await getToolsForIde(ide), + tools: getBaseToolDefinitions(), mcpServerStatuses: [], slashCommands: [], modelsByRole: { @@ -626,6 +628,7 @@ function llmToSerializedModelDescription(llm: ILLM): ModelDescription { apiKeyLocation: llm.apiKeyLocation, envSecretLocations: llm.envSecretLocations, sourceFile: llm.sourceFile, + isFromAutoDetect: llm.isFromAutoDetect, }; } diff --git a/core/config/loadLocalAssistants.ts b/core/config/loadLocalAssistants.ts index b6a29212d..2a8135dc1 100644 --- a/core/config/loadLocalAssistants.ts +++ b/core/config/loadLocalAssistants.ts @@ -35,7 +35,11 @@ async function getDefinitionFilesInDir( } const overrideDefaultIgnores = ignore() - .add(DEFAULT_IGNORE_FILETYPES.filter((t) => t !== "config.yaml")) + .add( + DEFAULT_IGNORE_FILETYPES.filter( + (t) => t !== "config.yaml" && t !== "config.yml", + ), + ) .add(DEFAULT_IGNORE_DIRS); const uris = await walkDir(dir, ide, { diff --git a/core/config/loadLocalAssistants.vitest.ts b/core/config/loadLocalAssistants.vitest.ts index 8527eada5..316687db1 100644 --- a/core/config/loadLocalAssistants.vitest.ts +++ b/core/config/loadLocalAssistants.vitest.ts @@ -18,6 +18,8 @@ describe("ASSISTANTS getAllDotContinueDefinitionFiles with fileExtType option", [".continue/assistants/assistant2.yml", "yaml content 2"], [".continue/assistants/assistant3.md", "markdown content 1"], [".continue/assistants/assistant4.txt", "txt content"], + [".continue/assistants/config.yaml", "txt content"], + [".continue/assistants/config.yml", "txt content"], ]); }); @@ -38,9 +40,14 @@ describe("ASSISTANTS getAllDotContinueDefinitionFiles with fileExtType option", options, "assistants", ); - expect(result).toHaveLength(2); + expect(result).toHaveLength(4); expect(result.map((f) => f.path.split("/").pop())).toEqual( - expect.arrayContaining(["assistant1.yaml", "assistant2.yml"]), + expect.arrayContaining([ + "assistant1.yaml", + "assistant2.yml", + "config.yaml", + "config.yml", + ]), ); expect(result.map((f) => f.path.split("/").pop())).not.toContain( "assistant3.md", @@ -69,6 +76,12 @@ describe("ASSISTANTS getAllDotContinueDefinitionFiles with fileExtType option", expect(result.map((f) => f.path.split("/").pop())).not.toContain( "assistant2.yml", ); + expect(result.map((f) => f.path.split("/").pop())).not.toContain( + "config.yml", + ); + expect(result.map((f) => f.path.split("/").pop())).not.toContain( + "config.yaml", + ); }); it("should return all supported files when fileExtType is not specified", async () => { @@ -83,11 +96,13 @@ describe("ASSISTANTS getAllDotContinueDefinitionFiles with fileExtType option", options, "assistants", ); - expect(result).toHaveLength(3); + expect(result).toHaveLength(5); expect(result.map((f) => f.path.split("/").pop())).toEqual( expect.arrayContaining([ "assistant1.yaml", "assistant2.yml", + "config.yml", + "config.yaml", "assistant3.md", ]), ); @@ -124,9 +139,14 @@ describe("ASSISTANTS getAllDotContinueDefinitionFiles with fileExtType option", workspaceOnOptions, "assistants", ); - expect(workspaceResult).toHaveLength(2); + expect(workspaceResult).toHaveLength(4); expect(workspaceResult.map((f) => f.path.split("/").pop())).toEqual( - expect.arrayContaining(["assistant1.yaml", "assistant2.yml"]), + expect.arrayContaining([ + "assistant1.yaml", + "assistant2.yml", + "config.yaml", + "config.yml", + ]), ); }); @@ -187,7 +207,7 @@ describe("ASSISTANTS getAllDotContinueDefinitionFiles with fileExtType option", options, "assistants", ); - expect(result).toHaveLength(2); + expect(result).toHaveLength(4); const yamlFile = result.find((f) => f.path.includes("assistant1.yaml")); expect(yamlFile?.content).toBe("yaml content 1"); }); @@ -212,9 +232,14 @@ describe("ASSISTANTS getAllDotContinueDefinitionFiles with fileExtType option", "assistants", ); // Should only get lowercase extensions (current implementation) - expect(yamlResult).toHaveLength(2); + expect(yamlResult).toHaveLength(4); expect(yamlResult.map((f) => f.path.split("/").pop())).toEqual( - expect.arrayContaining(["assistant1.yaml", "assistant2.yml"]), + expect.arrayContaining([ + "assistant1.yaml", + "assistant2.yml", + "config.yaml", + "config.yml", + ]), ); expect(yamlResult.map((f) => f.path.split("/").pop())).not.toContain( "assistant5.YAML", diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 4b0f64500..0b39489eb 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -282,6 +282,8 @@ export default async function doLoadConfig(options: { enableExperimentalTools: newConfig.experimental?.enableExperimentalTools ?? false, isSignedIn, + isRemote: await ide.isWorkspaceRemote(), + modelName: newConfig.selectedModelByRole.chat?.model, }), ); diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index 694c9e4da..7a9c9f634 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -25,7 +25,7 @@ import { modifyAnyConfigWithSharedConfig } from "../sharedConfig"; import { convertPromptBlockToSlashCommand } from "../../commands/slash/promptBlockSlashCommand"; import { slashCommandFromPromptFile } from "../../commands/slash/promptFileSlashCommand"; import { getControlPlaneEnvSync } from "../../control-plane/env"; -import { getToolsForIde } from "../../tools"; +import { getBaseToolDefinitions } from "../../tools"; import { getCleanUriPath } from "../../util/uri"; import { loadConfigContextProviders } from "../loadContextProviders"; import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants"; @@ -168,7 +168,7 @@ async function configYamlToContinueConfig(options: { const continueConfig: ContinueConfig = { slashCommands: [], - tools: await getToolsForIde(ide), + tools: getBaseToolDefinitions(), mcpServerStatuses: [], contextProviders: [], modelsByRole: { diff --git a/core/config/yaml/models.ts b/core/config/yaml/models.ts index 102e4152b..45cbdcbfb 100644 --- a/core/config/yaml/models.ts +++ b/core/config/yaml/models.ts @@ -32,12 +32,14 @@ async function modelConfigToBaseLLM({ ideSettings, llmLogger, config, + isFromAutoDetect, }: { model: ModelConfig; uniqueId: string; ideSettings: IdeSettings; llmLogger: ILLMLogger; config: ContinueConfig; + isFromAutoDetect?: boolean; }): Promise { const cls = getModelClass(model); @@ -71,6 +73,7 @@ async function modelConfigToBaseLLM({ nextEdit: model.capabilities?.includes("next_edit"), }, autocompleteOptions: model.autocompleteOptions, + isFromAutoDetect, }; // Model capabilities - need to be undefined if not found @@ -173,7 +176,6 @@ async function autodetectModels({ if (modelName === AUTODETECT) { return undefined; } - return await modelConfigToBaseLLM({ model: { ...model, @@ -184,6 +186,7 @@ async function autodetectModels({ ideSettings, llmLogger, config, + isFromAutoDetect: true, }); }), ); diff --git a/core/index.d.ts b/core/index.d.ts index 90039f025..10966f084 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -666,6 +666,7 @@ export interface LLMOptions { env?: Record; sourceFile?: string; + isFromAutoDetect?: boolean; } type RequireAtLeastOne = Pick< @@ -1112,6 +1113,8 @@ export interface ConfigDependentToolParams { rules: RuleWithSource[]; enableExperimentalTools: boolean; isSignedIn: boolean; + isRemote: boolean; + modelName: string | undefined; } export type GetTool = (params: ConfigDependentToolParams) => Tool; @@ -1175,6 +1178,7 @@ export interface ModelDescription { configurationStatus?: LLMConfigurationStatuses; sourceFile?: string; + isFromAutoDetect?: boolean; } export interface JSONEmbedOptions { @@ -1605,6 +1609,7 @@ export interface JSONModelDescription { aiGatewaySlug?: string; useLegacyCompletionsEndpoint?: boolean; deploymentId?: string; + isFromAutoDetect?: boolean; } // config.json diff --git a/core/indexing/chunk/chunk.ts b/core/indexing/chunk/chunk.ts index de9a33f9c..73108bf40 100644 --- a/core/indexing/chunk/chunk.ts +++ b/core/indexing/chunk/chunk.ts @@ -22,7 +22,22 @@ export async function* chunkDocumentWithoutId( return; } const extension = getUriFileExtension(fileUri); - if (extension in supportedLanguages) { + // Files that should use basicChunker despite having tree-sitter support + // These files don't have code structure (classes/functions) that codeChunker expects + const NON_CODE_EXTENSIONS = [ + "css", + "html", + "htm", + "json", + "toml", + "yaml", + "yml", + ]; + + if ( + extension in supportedLanguages && + !NON_CODE_EXTENSIONS.includes(extension) + ) { try { for await (const chunk of codeChunker(fileUri, contents, maxChunkSize)) { yield chunk; diff --git a/core/llm/index.ts b/core/llm/index.ts index edbfecbdb..1a0330eaa 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -9,7 +9,6 @@ import { import Handlebars from "handlebars"; import { DevDataSqliteDb } from "../data/devdataSqlite.js"; -import { Logger } from "../util/Logger.js"; import { DataLogger } from "../data/log.js"; import { CacheBehavior, @@ -31,6 +30,7 @@ import { TemplateType, Usage, } from "../index.js"; +import { Logger } from "../util/Logger.js"; import mergeJson from "../util/merge.js"; import { renderChatMessage } from "../util/messageContent.js"; import { isOllamaInstalled } from "../util/ollamaHelper.js"; @@ -191,6 +191,8 @@ export abstract class BaseLLM implements ILLM { //URI to local block defining this LLM sourceFile?: string; + isFromAutoDetect?: boolean; + private _llmOptions: LLMOptions; protected openaiAdapter?: BaseLlmApi; @@ -294,6 +296,7 @@ export abstract class BaseLLM implements ILLM { this.autocompleteOptions = options.autocompleteOptions; this.sourceFile = options.sourceFile; + this.isFromAutoDetect = options.isFromAutoDetect; } get contextLength() { diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index a944f90f9..a1c4c2046 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -148,7 +148,7 @@ class Ollama extends BaseLLM implements ModelInstaller { constructor(options: LLMOptions) { super(options); - if (options.model === "AUTODETECT") { + if (options.isFromAutoDetect) { return; } const headers: Record = { diff --git a/core/llm/llms/Vllm.ts b/core/llm/llms/Vllm.ts index 97bd936cb..66f9b84c4 100644 --- a/core/llm/llms/Vllm.ts +++ b/core/llm/llms/Vllm.ts @@ -25,7 +25,7 @@ class Vllm extends OpenAI { constructor(options: LLMOptions) { super(options); - if (options.model === "AUTODETECT") { + if (options.isFromAutoDetect) { this._setupCompletionOptions(); } } @@ -45,7 +45,7 @@ class Vllm extends OpenAI { // vLLM uses 'results' array instead of 'data' if (results.results && Array.isArray(results.results)) { const sortedResults = results.results.sort((a, b) => a.index - b.index); - return sortedResults.map((result) => result.index); + return sortedResults.map((result) => result.relevance_score); } throw new Error( diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index ad8ece0d6..ed40733a5 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -375,6 +375,7 @@ export function isRecommendedAgentModel(modelName: string): boolean { [/deepseek/, /r1|reasoner/], [/gemini/, /2\.5/, /pro/], [/gpt/, /4/], + [/gpt-5/], [/claude/, /sonnet/, /3\.5|3\.7|3-5|3-7|-4/], [/claude/, /opus/, /-4/], ]; diff --git a/core/tools/builtIn.ts b/core/tools/builtIn.ts index c5c5da16c..6e8ed1062 100644 --- a/core/tools/builtIn.ts +++ b/core/tools/builtIn.ts @@ -2,6 +2,8 @@ export enum BuiltInToolNames { ReadFile = "read_file", EditExistingFile = "edit_existing_file", SearchAndReplaceInFile = "search_and_replace_in_file", + SingleFindAndReplace = "single_find_and_replace", + MultiEdit = "multi_edit", ReadCurrentlyOpenFile = "read_currently_open_file", CreateNewFile = "create_new_file", RunTerminalCommand = "run_terminal_command", @@ -25,4 +27,6 @@ export const BUILT_IN_GROUP_NAME = "Built-In"; export const CLIENT_TOOLS_IMPLS = [ BuiltInToolNames.EditExistingFile, BuiltInToolNames.SearchAndReplaceInFile, + BuiltInToolNames.SingleFindAndReplace, + BuiltInToolNames.MultiEdit, ]; diff --git a/core/tools/definitions/index.ts b/core/tools/definitions/index.ts index c1998444c..6313eb9fc 100644 --- a/core/tools/definitions/index.ts +++ b/core/tools/definitions/index.ts @@ -6,12 +6,14 @@ export { fetchUrlContentTool } from "./fetchUrlContent"; export { globSearchTool } from "./globSearch"; export { grepSearchTool } from "./grepSearch"; export { lsTool } from "./ls"; +export { multiEditTool } from "./multiEdit"; export { readCurrentlyOpenFileTool } from "./readCurrentlyOpenFile"; export { readFileTool } from "./readFile"; export { requestRuleTool } from "./requestRule"; export { runTerminalCommandTool } from "./runTerminalCommand"; export { searchAndReplaceInFileTool } from "./searchAndReplaceInFile"; export { searchWebTool } from "./searchWeb"; +export { singleFindAndReplaceTool } from "./singleFindAndReplace"; export { viewDiffTool } from "./viewDiff"; export { viewRepoMapTool } from "./viewRepoMap"; export { viewSubdirectoryTool } from "./viewSubdirectory"; diff --git a/core/tools/definitions/multiEdit.ts b/core/tools/definitions/multiEdit.ts new file mode 100644 index 000000000..300312000 --- /dev/null +++ b/core/tools/definitions/multiEdit.ts @@ -0,0 +1,131 @@ +import { Tool } from "../.."; +import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; + +export interface EditOperation { + old_string: string; + new_string: string; + replace_all?: boolean; +} + +export interface MultiEditArgs { + filepath: string; + edits: EditOperation[]; +} + +export const multiEditTool: Tool = { + type: "function", + displayTitle: "Multi Edit", + wouldLikeTo: "edit {{{ filepath }}}", + isCurrently: "editing {{{ filepath }}}", + hasAlready: "edited {{{ filepath }}}", + group: BUILT_IN_GROUP_NAME, + readonly: false, + isInstant: false, + function: { + name: BuiltInToolNames.MultiEdit, + description: `This is a tool for making multiple edits to a single file in one operation. It +is built on top of the single find and replace tool and allows you to perform multiple +find-and-replace operations efficiently. Prefer this tool over the single find and replace tool +when you need to make multiple edits to the same file. + +Before using this tool: + +1. Use the read_file tool to understand the file's contents and context +2. Verify the directory path is correct + +To make multiple file edits, provide the following: + +1. filepath: The path to the file to modify (relative to the root of the workspace) +2. edits: An array of edit operations to perform, where each edit contains: + - old_string: The text to replace (must match the file contents exactly, including all whitespace and indentation) + - new_string: The edited text to replace the old_string + - replace_all: Replace all occurrences of old_string. This parameter is optional and defaults to false. + +IMPORTANT: +- All edits are applied in sequence, in the order they are provided +- Each edit operates on the result of the previous edit +- All edits must be valid for the operation to succeed - if any edit fails, +none will be applied +- This tool is ideal when you need to make several changes to different parts +of the same file + +CRITICAL REQUIREMENTS: + +1. All edits follow the same requirements as the single find and replace tool +2. The edits are atomic - either all succeed or none are applied +3. Plan your edits carefully to avoid conflicts between sequential operations + +WARNING: + +- The tool will fail if edits.old_string doesn't match the file contents +exactly (including whitespace) +- The tool will fail if edits.old_string and edits.new_string are the same +- Since edits are applied in sequence, ensure that earlier edits don't affect +the text that later edits are trying to find + +When making edits: + +- Ensure all edits result in idiomatic, correct code +- Do not leave the code in a broken state +- Only use emojis if the user explicitly requests it. Avoid adding emojis to +files unless asked. +- Use replace_all for replacing and renaming strings across the file. This +parameter is useful if you want to rename a variable for instance. + +If you want to create a new file, use: +- A new file path +- First edit: empty old_string and the new file's contents as new_string +- Subsequent edits are not allowed - there is no need since you are creating`, + parameters: { + type: "object", + required: ["filepath", "edits"], + properties: { + filepath: { + type: "string", + description: + "The path to the file to modify, relative to the root of the workspace", + }, + edits: { + type: "array", + description: + "Array of edit operations to perform sequentially on the file", + items: { + type: "object", + required: ["old_string", "new_string"], + properties: { + old_string: { + type: "string", + description: "The text to replace", + }, + new_string: { + type: "string", + description: "The text to replace it with", + }, + replace_all: { + type: "boolean", + description: + "Replace all occurrences of old_string (default false)", + }, + }, + }, + }, + }, + }, + }, + systemMessageDescription: { + prefix: `To make multiple edits to a single file, use the ${BuiltInToolNames.MultiEdit} tool with a filepath (relative to the root of the workspace) and an array of edit operations. + + For example, you could respond with:`, + exampleArgs: [ + ["filepath", "path/to/file.ts"], + [ + "edits", + `[ + { "old_string": "const oldVar = 'value'", "new_string": "const newVar = 'updated'" }, + { "old_string": "oldFunction()", "new_string": "newFunction()", "replace_all": true } +]`, + ], + ], + }, + defaultToolPolicy: "allowedWithPermission", +}; diff --git a/core/tools/definitions/singleFindAndReplace.ts b/core/tools/definitions/singleFindAndReplace.ts new file mode 100644 index 000000000..b5537d775 --- /dev/null +++ b/core/tools/definitions/singleFindAndReplace.ts @@ -0,0 +1,84 @@ +import { Tool } from "../.."; +import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; + +export interface SingleFindAndReplaceArgs { + filepath: string; + old_string: string; + new_string: string; + replace_all?: boolean; +} + +export const singleFindAndReplaceTool: Tool = { + type: "function", + displayTitle: "Find and Replace", + wouldLikeTo: "find and replace in {{{ filepath }}}", + isCurrently: "finding and replacing in {{{ filepath }}}", + hasAlready: "found and replaced in {{{ filepath }}}", + group: BUILT_IN_GROUP_NAME, + readonly: false, + isInstant: false, + function: { + name: BuiltInToolNames.SingleFindAndReplace, + description: `Performs exact string replacements in files. + +Usage: + +- You must use your \`read_file\` tool at least once in the conversation before +editing. This tool will error if you attempt an edit without reading the file. + +- When editing text from read_file tool output, ensure you preserve the exact +indentation (tabs/spaces) as it appears AFTER the line number prefix. The line +number prefix format is: spaces + line number + tab. Everything after that tab +is the actual file content to match. Never include any part of the line number +prefix in the old_string or new_string. + +- ALWAYS prefer editing existing files in the codebase. NEVER write new files +unless explicitly required. + +- Only use emojis if the user explicitly requests it. Avoid adding emojis to +files unless asked. + +- The edit will FAIL if \`old_string\` is not unique in the file. Either provide +a larger string with more surrounding context to make it unique or use +\`replace_all\` to change every instance of \`old_string\`. + +- Use \`replace_all\` for replacing and renaming strings across the file. This +parameter is useful if you want to rename a variable for instance.`, + parameters: { + type: "object", + required: ["filepath", "old_string", "new_string"], + properties: { + filepath: { + type: "string", + description: + "The path to the file to modify, relative to the root of the workspace", + }, + old_string: { + type: "string", + description: "The text to replace", + }, + new_string: { + type: "string", + description: + "The text to replace it with (must be different from old_string)", + }, + replace_all: { + type: "boolean", + description: "Replace all occurrences of old_string (default false)", + }, + }, + }, + }, + systemMessageDescription: { + prefix: `To perform exact string replacements in files, use the ${BuiltInToolNames.SingleFindAndReplace} tool with a filepath (relative to the root of the workspace) and the strings to find and replace. + + For example, you could respond with:`, + exampleArgs: [ + ["filepath", "path/to/file.ts"], + ["old_string", "const oldVariable = 'value'"], + ["new_string", "const newVariable = 'updated'"], + ["replace_all", "false"], + ], + }, + defaultToolPolicy: "allowedWithPermission", +}; diff --git a/core/tools/definitions/toolDefinitions.test.ts b/core/tools/definitions/toolDefinitions.test.ts index abeac08ef..265ebe5e1 100644 --- a/core/tools/definitions/toolDefinitions.test.ts +++ b/core/tools/definitions/toolDefinitions.test.ts @@ -8,6 +8,8 @@ describe("Tool Definitions", () => { rules: [], enableExperimentalTools: false, isSignedIn: false, + isRemote: false, + modelName: "a model", }; // Helper function to get the actual tool object diff --git a/core/tools/implementations/fetchUrlContent.ts b/core/tools/implementations/fetchUrlContent.ts index 95b5b216b..15809e4f3 100644 --- a/core/tools/implementations/fetchUrlContent.ts +++ b/core/tools/implementations/fetchUrlContent.ts @@ -27,8 +27,8 @@ export const fetchUrlContentImpl: ToolImpl = async (args, extras) => { // Add truncation warning if needed if (truncatedUrls.length > 0) { processedItems.push({ - name: "URL content truncation warning", - description: "Informs that URL content was truncated", + name: "Truncation warning", + description: "", content: `The content from ${truncatedUrls.join(", ")} was truncated because it exceeded the ${DEFAULT_FETCH_URL_CHAR_LIMIT} character limit. If you need more content, consider fetching specific sections or using a more targeted approach.`, }); } diff --git a/core/tools/implementations/fetchUrlContent.vitest.ts b/core/tools/implementations/fetchUrlContent.vitest.ts index 9d103893d..0c8efb81b 100644 --- a/core/tools/implementations/fetchUrlContent.vitest.ts +++ b/core/tools/implementations/fetchUrlContent.vitest.ts @@ -54,7 +54,7 @@ test("fetchUrlContent should truncate content exceeding character limit", async expect(result).toHaveLength(2); // Original item + warning expect(result[0].content.length).toBe(DEFAULT_FETCH_URL_CHAR_LIMIT); - expect(result[1].name).toBe("URL content truncation warning"); + expect(result[1].name).toBe("Truncation warning"); expect(result[1].content).toContain("was truncated"); expect(result[1].content).toContain("20000 character limit"); }); @@ -87,5 +87,5 @@ test("fetchUrlContent should add truncation warning with multiple truncated item expect(result).toHaveLength(3); // Two original items + warning expect(result[0].content.length).toBe(DEFAULT_FETCH_URL_CHAR_LIMIT); expect(result[1].content.length).toBe(DEFAULT_FETCH_URL_CHAR_LIMIT); - expect(result[2].name).toBe("URL content truncation warning"); + expect(result[2].name).toBe("Truncation warning"); }); diff --git a/core/tools/implementations/globSearch.ts b/core/tools/implementations/globSearch.ts index 04a105556..2e40ac06d 100644 --- a/core/tools/implementations/globSearch.ts +++ b/core/tools/implementations/globSearch.ts @@ -10,10 +10,20 @@ export const fileGlobSearchImpl: ToolImpl = async (args, extras) => { pattern, MAX_AGENT_GLOB_RESULTS, ); + + if (results.length === 0) { + return [ + { + name: "File results", + description: "glob search", + content: "The glob search returned no results.", + }, + ]; + } const contextItems: ContextItem[] = [ { name: "File results", - description: "Results from file glob search", + description: "glob search", content: results.join("\n"), }, ]; @@ -22,7 +32,7 @@ export const fileGlobSearchImpl: ToolImpl = async (args, extras) => { if (results.length === MAX_AGENT_GLOB_RESULTS) { contextItems.push({ name: "Truncation warning", - description: "Inform the model that results were truncated", + description: "", content: `Warning: the results above were truncated to the first ${MAX_AGENT_GLOB_RESULTS} files. If the results are not satisfactory, refine your search pattern`, }); } diff --git a/core/tools/implementations/grepSearch.ts b/core/tools/implementations/grepSearch.ts index b75c21891..727b5c560 100644 --- a/core/tools/implementations/grepSearch.ts +++ b/core/tools/implementations/grepSearch.ts @@ -1,18 +1,15 @@ import { ToolImpl } from "."; import { ContextItem } from "../.."; import { formatGrepSearchResults } from "../../util/grepSearch"; +import { prepareQueryForRipgrep } from "../../util/regexValidator"; import { getStringArg } from "../parseArgs"; const DEFAULT_GREP_SEARCH_RESULTS_LIMIT = 100; -const DEFAULT_GREP_SEARCH_CHAR_LIMIT = 5000; // ~1000 tokens, will keep truncation simply for now +const DEFAULT_GREP_SEARCH_CHAR_LIMIT = 7500; // ~1500 tokens, will keep truncation simply for now function splitGrepResultsByFile(content: string): ContextItem[] { const matches = [...content.matchAll(/^\.\/([^\n]+)$/gm)]; - if (matches.length === 0) { - return []; - } - const contextItems: ContextItem[] = []; for (let i = 0; i < matches.length; i++) { @@ -42,16 +39,48 @@ function splitGrepResultsByFile(content: string): ContextItem[] { } export const grepSearchImpl: ToolImpl = async (args, extras) => { - const query = getStringArg(args, "query"); + const rawQuery = getStringArg(args, "query"); + + const { query, warning } = prepareQueryForRipgrep(rawQuery); + + let results: string; + try { + results = await extras.ide.getSearchResults( + query, + DEFAULT_GREP_SEARCH_RESULTS_LIMIT, + ); + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + + // Helpful error for common ripgrep exit code + if (errorMessage.includes("Process exited with code 2")) { + return [ + { + name: "Search error", + description: "The search query could not be processed", + content: `The search failed due to an invalid regex pattern.\n\nOriginal query: ${rawQuery}\nProcessed query: ${query}\n\nError: ${errorMessage}\n\nTip: If you're searching for literal text with special characters, the query was automatically escaped. If you need regex patterns, ensure they use proper regex syntax.`, + }, + ]; + } + + throw error; + } - const results = await extras.ide.getSearchResults( - query, - DEFAULT_GREP_SEARCH_RESULTS_LIMIT, - ); const { formatted, numResults, truncated } = formatGrepSearchResults( results, DEFAULT_GREP_SEARCH_CHAR_LIMIT, ); + + if (numResults === 0) { + return [ + { + name: "Search results", + description: "Results from grep search", + content: "The search returned no results.", + }, + ]; + } + const truncationReasons: string[] = []; if (numResults === DEFAULT_GREP_SEARCH_RESULTS_LIMIT) { truncationReasons.push( @@ -64,7 +93,7 @@ export const grepSearchImpl: ToolImpl = async (args, extras) => { ); } - let contextItems: ContextItem[] = []; + let contextItems: ContextItem[]; const splitByFile: boolean = args?.splitByFile || false; if (splitByFile) { @@ -79,10 +108,21 @@ export const grepSearchImpl: ToolImpl = async (args, extras) => { ]; } + // Add warnings about query modifications or truncation + const warnings: string[] = []; + if (warning) { + warnings.push(warning); + } + if (truncationReasons.length > 0) { + warnings.push( + `Results were truncated because ${truncationReasons.join(" and ")}`, + ); + } + if (truncationReasons.length > 0) { contextItems.push({ - name: "Search truncation warning", - description: "Informs the model that search results were truncated", + name: "Truncation warning", + description: "", content: `The above search results were truncated because ${truncationReasons.join(" and ")}. If the results are not satisfactory, try refining your search query.`, }); } diff --git a/core/tools/implementations/lsTool.ts b/core/tools/implementations/lsTool.ts index 7e5f49856..67122f082 100644 --- a/core/tools/implementations/lsTool.ts +++ b/core/tools/implementations/lsTool.ts @@ -53,8 +53,8 @@ export const lsToolImpl: ToolImpl = async (args, extras) => { warningContent += ". Try using a non-recursive search"; } contextItems.push({ - name: "ls truncation warning", - description: "Informs the model that ls results were truncated", + name: "Truncation warning", + description: "", content: warningContent, }); } diff --git a/core/tools/implementations/searchWeb.ts b/core/tools/implementations/searchWeb.ts index 3d331ebfd..51e817fae 100644 --- a/core/tools/implementations/searchWeb.ts +++ b/core/tools/implementations/searchWeb.ts @@ -29,8 +29,8 @@ export const searchWebImpl: ToolImpl = async (args, extras) => { // Add truncation warning if needed if (truncatedResults.length > 0) { processedResults.push({ - name: "Web search truncation warning", - description: "Informs that search results were truncated", + name: "Truncation warning", + description: "", content: `The content from the following search results was truncated because it exceeded the ${DEFAULT_WEB_SEARCH_CHAR_LIMIT} character limit: ${truncatedResults.join(", ")}. For more detailed information, consider refining your search query.`, }); } diff --git a/core/tools/implementations/searchWeb.vitest.ts b/core/tools/implementations/searchWeb.vitest.ts index 17ddd4925..5ac02ac32 100644 --- a/core/tools/implementations/searchWeb.vitest.ts +++ b/core/tools/implementations/searchWeb.vitest.ts @@ -62,7 +62,7 @@ test("searchWeb should truncate results exceeding character limit", async () => expect(result).toHaveLength(3); // Two results + warning expect(result[0].content.length).toBe(DEFAULT_WEB_SEARCH_CHAR_LIMIT); expect(result[1].content).toBe(shortContent); - expect(result[2].name).toBe("Web search truncation warning"); + expect(result[2].name).toBe("Truncation warning"); expect(result[2].content).toContain("truncated"); expect(result[2].content).toContain("Result 1"); expect(result[2].content).not.toContain("Result 2"); @@ -100,7 +100,7 @@ test("searchWeb should include all truncated results in the warning", async () = expect(result[0].content.length).toBe(DEFAULT_WEB_SEARCH_CHAR_LIMIT); expect(result[1].content.length).toBe(DEFAULT_WEB_SEARCH_CHAR_LIMIT); expect(result[2].content).toBe(shortContent); - expect(result[3].name).toBe("Web search truncation warning"); + expect(result[3].name).toBe("Truncation warning"); expect(result[3].content).toContain("Result 1"); expect(result[3].content).toContain("Result 2"); expect(result[3].content).not.toContain("Result 3"); diff --git a/core/tools/implementations/viewDiff.ts b/core/tools/implementations/viewDiff.ts index 2b5da1ab8..9df82e78d 100644 --- a/core/tools/implementations/viewDiff.ts +++ b/core/tools/implementations/viewDiff.ts @@ -29,8 +29,8 @@ export const viewDiffImpl: ToolImpl = async (args, extras) => { if (truncated) { contextItems.push({ - name: "Diff truncation warning", - description: "Informs that git diff was truncated", + name: "Truncation warning", + description: "", content: `The git diff was truncated because it exceeded ${DEFAULT_GIT_DIFF_LINE_LIMIT} lines. Consider viewing specific files or focusing on smaller changes.`, }); } diff --git a/core/tools/implementations/viewDiff.vitest.ts b/core/tools/implementations/viewDiff.vitest.ts index 914e3a014..4c9aa5d63 100644 --- a/core/tools/implementations/viewDiff.vitest.ts +++ b/core/tools/implementations/viewDiff.vitest.ts @@ -58,7 +58,7 @@ test("viewDiff should truncate diffs exceeding line limit", async () => { expect(resultLines.length).toBe(DEFAULT_GIT_DIFF_LINE_LIMIT); // Check the warning - expect(result[1].name).toBe("Diff truncation warning"); + expect(result[1].name).toBe("Truncation warning"); expect(result[1].content).toContain("truncated"); expect(result[1].content).toContain(`${DEFAULT_GIT_DIFF_LINE_LIMIT} lines`); }); @@ -83,5 +83,5 @@ test("viewDiff should handle multiple diffs correctly", async () => { expect(resultLines.length).toBe(DEFAULT_GIT_DIFF_LINE_LIMIT); // Check the warning - expect(result[1].name).toBe("Diff truncation warning"); + expect(result[1].name).toBe("Truncation warning"); }); diff --git a/core/tools/index.ts b/core/tools/index.ts index 850d89349..fa66c4c91 100644 --- a/core/tools/index.ts +++ b/core/tools/index.ts @@ -1,12 +1,8 @@ -import { ConfigDependentToolParams, IDE, Tool } from ".."; +import { ConfigDependentToolParams, Tool } from ".."; import * as toolDefinitions from "./definitions"; // I'm writing these as functions because we've messed up 3 TIMES by pushing to const, causing duplicate tool definitions on subsequent config loads. - -// missing support for remote os calls: https://github.com/microsoft/vscode/issues/252269 -const getLocalOnlyToolDefinitions = () => [toolDefinitions.grepSearchTool]; - -const getBaseToolDefinitions = () => [ +export const getBaseToolDefinitions = () => [ toolDefinitions.readFileTool, toolDefinitions.createNewFileTool, toolDefinitions.runTerminalCommandTool, @@ -16,28 +12,42 @@ const getBaseToolDefinitions = () => [ toolDefinitions.lsTool, toolDefinitions.createRuleBlock, toolDefinitions.fetchUrlContentTool, + toolDefinitions.singleFindAndReplaceTool, ]; export const getConfigDependentToolDefinitions = ( params: ConfigDependentToolParams, -): Tool[] => [ - toolDefinitions.requestRuleTool(params), - // Search and replace is now generally available - toolDefinitions.searchAndReplaceInFileTool, - // Keep edit file tool available for models that need it - toolDefinitions.editFileTool, - // Web search is only available for signed-in users - ...(params.isSignedIn ? [toolDefinitions.searchWebTool] : []), - ...(params.enableExperimentalTools - ? [ - toolDefinitions.viewRepoMapTool, - toolDefinitions.viewSubdirectoryTool, - toolDefinitions.codebaseTool, - ] - : []), -]; +): Tool[] => { + const { modelName, isSignedIn, enableExperimentalTools, isRemote } = params; + const tools: Tool[] = []; -export const getToolsForIde = async (ide: IDE): Promise => - (await ide.isWorkspaceRemote()) - ? getBaseToolDefinitions() - : [...getBaseToolDefinitions(), ...getLocalOnlyToolDefinitions()]; + tools.push(toolDefinitions.requestRuleTool(params)); + + if (isSignedIn) { + // Web search is only available for signed-in users + tools.push(toolDefinitions.searchWebTool); + } + + if (enableExperimentalTools) { + tools.push( + toolDefinitions.viewRepoMapTool, + toolDefinitions.viewSubdirectoryTool, + toolDefinitions.codebaseTool, + ); + } + + // OLD SEARCH AND REPLACE IS CURRENTLY NOT USED + // toolDefinitions.searchAndReplaceInFileTool + if (modelName?.includes("claude") || modelName?.includes("gpt-5")) { + tools.push(toolDefinitions.multiEditTool); + } else { + tools.push(toolDefinitions.editFileTool); + } + + // missing support for remote os calls: https://github.com/microsoft/vscode/issues/252269 + if (!isRemote) { + tools.push(toolDefinitions.grepSearchTool); + } + + return tools; +}; diff --git a/core/tools/parseArgs.ts b/core/tools/parseArgs.ts index 1e7709ddc..a31267854 100644 --- a/core/tools/parseArgs.ts +++ b/core/tools/parseArgs.ts @@ -20,11 +20,11 @@ export function getStringArg( ): string { if (!args || !(argName in args) || typeof args[argName] !== "string") { throw new Error( - `\`${argName}\` argument is required${allowEmpty ? "" : " and must not be empty"}. (type string)`, + `\`${argName}\` argument is required${allowEmpty ? "" : " and must not be empty or whitespace-only"}. (type string)`, ); } if (!allowEmpty && !args[argName].trim()) { - throw new Error(`Argument ${argName} must not be empty`); + throw new Error(`Argument ${argName} must not be empty or whitespace-only`); } return args[argName]; } diff --git a/core/tools/parseArgs.vitest.ts b/core/tools/parseArgs.vitest.ts index b501191f0..b2cee9fc5 100644 --- a/core/tools/parseArgs.vitest.ts +++ b/core/tools/parseArgs.vitest.ts @@ -102,26 +102,26 @@ describe("getStringArg", () => { it("should throw error when argument is missing", () => { const args = { otherArg: "test" }; expect(() => getStringArg(args, "name")).toThrowError( - "`name` argument is required and must not be empty. (type string)", + "`name` argument is required and must not be empty or whitespace-only. (type string)", ); }); it("should throw error when argument is not a string", () => { const args = { name: 123 }; expect(() => getStringArg(args, "name")).toThrowError( - "`name` argument is required and must not be empty. (type string)", + "`name` argument is required and must not be empty or whitespace-only. (type string)", ); }); it("should throw error when argument is empty and empty not allowed", () => { const args = { name: "" }; expect(() => getStringArg(args, "name")).toThrowError( - "Argument name must not be empty", + "Argument name must not be empty or whitespace-only", ); const argsWithSpace = { name: " " }; expect(() => getStringArg(argsWithSpace, "name")).toThrowError( - "Argument name must not be empty", + "Argument name must not be empty or whitespace-only", ); }); @@ -137,10 +137,10 @@ describe("getStringArg", () => { it("should handle null or undefined args", () => { expect(() => getStringArg(null, "name")).toThrowError( - "`name` argument is required and must not be empty. (type string)", + "`name` argument is required and must not be empty or whitespace-only. (type string)", ); expect(() => getStringArg(undefined, "name")).toThrowError( - "`name` argument is required and must not be empty. (type string)", + "`name` argument is required and must not be empty or whitespace-only. (type string)", ); }); }); @@ -161,14 +161,14 @@ describe("getOptionalStringArg", () => { it("should throw error when argument is not a string", () => { const args = { name: 123 }; expect(() => getOptionalStringArg(args, "name")).toThrowError( - "`name` argument is required and must not be empty. (type string)", + "`name` argument is required and must not be empty or whitespace-only. (type string)", ); }); it("should throw error when argument is empty and empty not allowed", () => { const args = { name: "" }; expect(() => getOptionalStringArg(args, "name")).toThrowError( - "Argument name must not be empty", + "Argument name must not be empty or whitespace-only", ); }); diff --git a/core/tools/searchWebGating.vitest.ts b/core/tools/searchWebGating.vitest.ts index e68acdd52..4ebb6e5b4 100644 --- a/core/tools/searchWebGating.vitest.ts +++ b/core/tools/searchWebGating.vitest.ts @@ -1,6 +1,6 @@ -import { test, expect } from "vitest"; -import { getConfigDependentToolDefinitions } from "./index"; +import { expect, test } from "vitest"; import { BuiltInToolNames } from "./builtIn"; +import { getConfigDependentToolDefinitions } from "./index"; test("searchWeb tool is only available when user is signed in", () => { // Test with signed-in user @@ -8,6 +8,8 @@ test("searchWeb tool is only available when user is signed in", () => { rules: [], enableExperimentalTools: false, isSignedIn: true, + isRemote: false, + modelName: "", }); const searchWebToolSignedIn = signedInTools.find( @@ -21,6 +23,8 @@ test("searchWeb tool is only available when user is signed in", () => { rules: [], enableExperimentalTools: false, isSignedIn: false, + isRemote: false, + modelName: "", }); const searchWebToolNotSignedIn = notSignedInTools.find( diff --git a/core/util/regexValidator.ts b/core/util/regexValidator.ts new file mode 100644 index 000000000..f65520a94 --- /dev/null +++ b/core/util/regexValidator.ts @@ -0,0 +1,169 @@ +/** + * Validates and sanitizes regex patterns for use with ripgrep + */ + +export interface RegexValidationResult { + isValid: boolean; + sanitizedQuery?: string; + error?: string; + warning?: string; +} + +/** + * Validates a regex pattern and attempts to sanitize common issues + * @param query The regex pattern to validate + * @returns Validation result with sanitized query if possible + */ +export function validateAndSanitizeRegex(query: string): RegexValidationResult { + // Check for common problematic patterns that often fail with ripgrep + const problematicPatterns = [ + { + // Triple-escaped quotes + pattern: /\\\\\\/g, + issue: "Triple backslash sequences may cause parsing errors", + fix: (s: string) => s.replace(/\\\\\\/g, "\\\\"), + }, + { + // Unescaped brackets/parentheses that are NOT part of valid regex constructs + pattern: /(? + s.replace(/\t/g, "\\t").replace(/\n/g, "\\n").replace(/\r/g, "\\r"), + }, + ]; + + let sanitizedQuery = query; + let warnings: string[] = []; + + // Apply fixes for known issues + for (const check of problematicPatterns) { + if (check.pattern.test(query)) { + if (check.fix) { + sanitizedQuery = check.fix(sanitizedQuery); + warnings.push(`Fixed: ${check.issue}`); + } else { + warnings.push(`Warning: ${check.issue}`); + } + } + } + + // Try to compile as a JavaScript regex to catch basic syntax errors + try { + new RegExp(sanitizedQuery); + } catch (e) { + let errorMessage = e instanceof Error ? e.message : "Unknown error"; + // If it fails as a JS regex, it might still be valid for ripgrep + // (ripgrep supports some patterns JS doesn't), but warn the user + warnings.push(`Pattern may have syntax issues: ${errorMessage}`); + } + + // Check for patterns that are valid regex but might not work as expected with ripgrep + const ripgrepSpecificIssues = [ + { + pattern: /\\[0-7]{3}/g, + warning: "Octal escape sequences may not work as expected in ripgrep", + }, + { + pattern: /\(\?[ 0 ? warnings.join("; ") : undefined, + }; +} + +/** + * Escapes a literal string to be used as a regex pattern + * @param literal The literal string to escape + * @returns Escaped string safe for regex use + */ +export function escapeLiteralForRegex(literal: string): string { + // Escape all regex metacharacters + return literal.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} + +/** + * Detects if a query looks like it's meant to be a literal search + * rather than a regex pattern + * @param query The search query + * @returns true if it appears to be a literal search + */ +export function looksLikeLiteralSearch(query: string): boolean { + // If it contains regex metacharacters but they're not escaped, + // and it doesn't look like an intentional regex pattern + const hasUnescapedMetachars = /[.*+?^${}()|[\]]/g.test(query); + const hasEscapedMetachars = /\\[.*+?^${}()|[\]\\]/g.test(query); + + // Check for regex constructs, but be more specific about what we consider regex + const hasEscapeSequences = /\\[dws]/g.test(query); // \d, \w, \s + const hasQuantifiers = /\{[0-9,]+\}/g.test(query); // {2,4}, {3} + + // Check for bracket patterns and distinguish between character classes and array access + const bracketPattern = /\[[^\]]*\]/g; + const brackets = query.match(bracketPattern); + let hasCharacterClasses = false; + + if (brackets) { + hasCharacterClasses = brackets.some((bracket) => { + const inside = bracket.slice(1, -1); // Remove [ ] + // Character class indicators: ranges (a-z), multiple chars, negation (^) + return /-/.test(inside) || inside.length > 1 || inside.startsWith("^"); + }); + } + + const hasRegexConstructs = + hasEscapeSequences || hasQuantifiers || hasCharacterClasses; + + // Likely a literal search if it has unescaped metachars but no regex constructs + return hasUnescapedMetachars && !hasEscapedMetachars && !hasRegexConstructs; +} + +/** + * Prepares a query for ripgrep by sanitizing problematic patterns + * @param query The search query + * @returns Object with sanitized query and any warnings + */ +export function prepareQueryForRipgrep(query: string): { + query: string; + warning?: string; +} { + // Check if it looks like a literal search that should be escaped + if (looksLikeLiteralSearch(query)) { + return { + query: escapeLiteralForRegex(query), + warning: + "Query contained special regex characters and was escaped for literal text search", + }; + } + + // Otherwise validate and sanitize as regex + const validation = validateAndSanitizeRegex(query); + + return { + query: validation.sanitizedQuery || query, + warning: validation.warning, + }; +} diff --git a/core/util/regexValidator.vitest.ts b/core/util/regexValidator.vitest.ts new file mode 100644 index 000000000..5c0bbd34d --- /dev/null +++ b/core/util/regexValidator.vitest.ts @@ -0,0 +1,310 @@ +import { describe, expect, it } from "vitest"; +import { + escapeLiteralForRegex, + looksLikeLiteralSearch, + prepareQueryForRipgrep, + validateAndSanitizeRegex, +} from "./regexValidator"; + +describe("validateAndSanitizeRegex", () => { + it("should accept valid basic regex patterns", () => { + const result = validateAndSanitizeRegex("function\\s+\\w+"); + expect(result.isValid).toBe(true); + expect(result.sanitizedQuery).toBe("function\\s+\\w+"); + expect(result.error).toBeUndefined(); + expect(result.warning).toBeUndefined(); + }); + + it("should fix triple-escaped sequences", () => { + const result = validateAndSanitizeRegex("\\\\\\"); + expect(result.isValid).toBe(true); + expect(result.sanitizedQuery).toBe("\\\\"); + expect(result.warning).toContain("Fixed: Triple backslash sequences"); + }); + + it("should fix raw tab characters", () => { + const result = validateAndSanitizeRegex("hello\tworld"); + expect(result.isValid).toBe(true); + expect(result.sanitizedQuery).toBe("hello\\tworld"); + expect(result.warning).toContain("Fixed: Raw whitespace characters"); + }); + + it("should fix raw newline characters", () => { + const result = validateAndSanitizeRegex("line1\nline2"); + expect(result.isValid).toBe(true); + expect(result.sanitizedQuery).toBe("line1\\nline2"); + expect(result.warning).toContain("Fixed: Raw whitespace characters"); + }); + + it("should warn about unescaped brackets without fixing", () => { + const result = validateAndSanitizeRegex("hello[world]"); + expect(result.isValid).toBe(true); + expect(result.sanitizedQuery).toBe("hello[world]"); + expect(result.warning).toContain( + "Warning: Unescaped brackets or parentheses", + ); + }); + + it("should handle multiple issues", () => { + const result = validateAndSanitizeRegex("function()\t\\\\\\"); + expect(result.isValid).toBe(true); + expect(result.sanitizedQuery).toBe("function()\\t\\\\"); + expect(result.warning).toContain("Fixed: Raw whitespace characters"); + expect(result.warning).toContain("Fixed: Triple backslash sequences"); + }); + + it("should warn about lookbehind assertions", () => { + const result = validateAndSanitizeRegex("(?<=foo)bar"); + expect(result.isValid).toBe(true); + expect(result.warning).toContain( + "Lookahead/lookbehind assertions require ripgrep to be compiled with PCRE2", + ); + }); +}); + +describe("escapeLiteralForRegex", () => { + it("should escape basic regex metacharacters", () => { + expect(escapeLiteralForRegex("hello.world")).toBe("hello\\.world"); + expect(escapeLiteralForRegex("test*")).toBe("test\\*"); + expect(escapeLiteralForRegex("file+")).toBe("file\\+"); + expect(escapeLiteralForRegex("query?")).toBe("query\\?"); + }); + + it("should escape brackets and braces", () => { + expect(escapeLiteralForRegex("array[0]")).toBe("array\\[0\\]"); + expect(escapeLiteralForRegex("{key}")).toBe("\\{key\\}"); + expect(escapeLiteralForRegex("func()")).toBe("func\\(\\)"); + }); + + it("should handle multiple metacharacters", () => { + expect(escapeLiteralForRegex("$regex.test(input)")).toBe( + "\\$regex\\.test\\(input\\)", + ); + }); + + it("should not escape normal characters", () => { + expect(escapeLiteralForRegex("hello world")).toBe("hello world"); + }); +}); + +describe("looksLikeLiteralSearch", () => { + it("should identify literal searches with unescaped metacharacters", () => { + expect(looksLikeLiteralSearch("hello.world")).toBe(true); + expect(looksLikeLiteralSearch("test*")).toBe(true); + expect(looksLikeLiteralSearch("func()")).toBe(true); + expect(looksLikeLiteralSearch("array[0]")).toBe(true); + }); + + it("should not identify regex patterns as literal", () => { + expect(looksLikeLiteralSearch("hello\\.world")).toBe(false); + expect(looksLikeLiteralSearch("\\d+")).toBe(false); + expect(looksLikeLiteralSearch("[a-z]+")).toBe(false); + expect(looksLikeLiteralSearch("a{2,4}")).toBe(false); + }); + + it("should handle plain text", () => { + expect(looksLikeLiteralSearch("hello world")).toBe(false); + expect(looksLikeLiteralSearch("simple text")).toBe(false); + }); +}); + +describe("prepareQueryForRipgrep", () => { + it("should escape literal-looking queries", () => { + const result = prepareQueryForRipgrep("hello.world"); + expect(result.query).toBe("hello\\.world"); + expect(result.warning).toContain("escaped for literal text search"); + }); + + it("should sanitize regex patterns", () => { + const result = prepareQueryForRipgrep("function\t\\\\\\"); + expect(result.query).toBe("function\\t\\\\"); + expect(result.warning).toContain("Fixed:"); + }); + + it("should handle plain text without changes", () => { + const result = prepareQueryForRipgrep("hello world"); + expect(result.query).toBe("hello world"); + expect(result.warning).toBeUndefined(); + }); + + describe("real-world examples", () => { + it("should escape file patterns", () => { + const result = prepareQueryForRipgrep("*.js"); + expect(result.query).toBe("\\*\\.js"); + expect(result.warning).toContain("escaped for literal text search"); + }); + + it("should escape function calls", () => { + const result = prepareQueryForRipgrep("console.log()"); + expect(result.query).toBe("console\\.log\\(\\)"); + expect(result.warning).toContain("escaped for literal text search"); + }); + + it("should not escape proper regex patterns", () => { + const result = prepareQueryForRipgrep("function\\s+\\w+"); + expect(result.query).toBe("function\\s+\\w+"); + expect(result.warning).toBeUndefined(); + }); + }); +}); + +describe("problematic patterns that originally failed", () => { + it("should handle triple-escaped quotes", () => { + const result = prepareQueryForRipgrep('\\\\\\"'); + expect(result.query).toBe('\\\\"'); // Triple backslash -> double backslash, quote stays + expect(result.warning).toContain("Fixed:"); + }); + + it("should handle newline-tab sequences", () => { + const result = prepareQueryForRipgrep("\n\t"); + expect(result.query).toBe("\\n\\t"); + expect(result.warning).toContain("Fixed:"); + }); + + it("should handle dollar signs in shell patterns", () => { + const result = prepareQueryForRipgrep("$(command)"); + expect(result.query).toBe("\\$\\(command\\)"); + expect(result.warning).toContain("escaped for literal text search"); + }); + + it("should handle escaped dollar signs", () => { + const result = prepareQueryForRipgrep("\\$\\("); + expect(result.query).toBe("\\$\\("); + expect(result.warning).toBeUndefined(); + }); +}); + +describe("patterns that should NOT be over-sanitized", () => { + describe("valid regex patterns that contain suspicious sequences", () => { + it("should not escape properly formed character classes", () => { + const result = prepareQueryForRipgrep("[a-zA-Z0-9_-]+"); + expect(result.query).toBe("[a-zA-Z0-9_-]+"); + expect(result.warning).toContain("Warning: Unescaped brackets"); // Warn but don't break + }); + + it("should not escape quantifiers in regex patterns", () => { + const result = prepareQueryForRipgrep("\\w{2,5}"); + expect(result.query).toBe("\\w{2,5}"); + expect(result.warning).toBeUndefined(); + }); + + it("should not escape properly formed lookarounds", () => { + const result = prepareQueryForRipgrep("(? { + const result = prepareQueryForRipgrep("console\\.log\\(\\)"); + expect(result.query).toBe("console\\.log\\(\\)"); + expect(result.warning).toBeUndefined(); + }); + }); + + describe("patterns that look problematic but are intentional", () => { + it("should not over-escape already escaped sequences", () => { + const result = prepareQueryForRipgrep("\\\\t"); // Already escaped tab + expect(result.query).toBe("\\\\t"); + expect(result.warning).toBeUndefined(); + }); + + it("should not double-escape backslashes in Windows paths", () => { + const result = prepareQueryForRipgrep("C:\\\\Users\\\\file"); + expect(result.query).toBe("C:\\\\Users\\\\file"); + expect(result.warning).toBeUndefined(); + }); + + it("should not break raw strings that contain regex-like patterns", () => { + const result = prepareQueryForRipgrep('"\\d+\\s+\\w+"'); + expect(result.query).toBe('"\\d+\\s+\\w+"'); // Escaped sequences in quotes should stay + expect(result.warning).toBeUndefined(); + }); + + it("should not break JSON with escaped quotes", () => { + const result = prepareQueryForRipgrep('"key": "value"'); + expect(result.query).toBe('"key": "value"'); + expect(result.warning).toBeUndefined(); + }); + }); + + describe("complex patterns that mix literal and regex", () => { + it("should not break URLs with query parameters", () => { + const result = prepareQueryForRipgrep( + "https://api\\.example\\.com\\?param=\\w+", + ); + expect(result.query).toBe("https://api\\.example\\.com\\?param=\\w+"); + expect(result.warning).toBeUndefined(); + }); + + it("should not break file paths with regex metacharacters", () => { + const result = prepareQueryForRipgrep("/path/to/file\\.[jt]sx?"); + expect(result.query).toBe("/path/to/file\\.[jt]sx?"); + expect(result.warning).toContain("Warning: Unescaped brackets"); // Warn but preserve + }); + + it("should handle mixed escaped and unescaped patterns correctly", () => { + // This is a regex that matches function calls with optional whitespace + const result = prepareQueryForRipgrep("\\w+\\s*\\("); + expect(result.query).toBe("\\w+\\s*\\("); + expect(result.warning).toBeUndefined(); + }); + }); + + describe("edge cases that could trigger false positives", () => { + it("should not treat mathematical expressions as problematic", () => { + const result = prepareQueryForRipgrep("a + b * c"); + expect(result.query).toBe("a \\+ b \\* c"); // Should be escaped as literal + expect(result.warning).toContain("escaped for literal text search"); + }); + + it("should not break regex that uses word boundaries", () => { + const result = prepareQueryForRipgrep("\\bclass\\b"); + expect(result.query).toBe("\\bclass\\b"); + expect(result.warning).toBeUndefined(); + }); + + it("should not break negated character classes", () => { + const result = prepareQueryForRipgrep("[^a-z]+"); + expect(result.query).toBe("[^a-z]+"); + expect(result.warning).toContain("Warning: Unescaped brackets"); // Warn but preserve + }); + + it("should not treat IPv4 addresses as problematic regex", () => { + const result = prepareQueryForRipgrep("192.168.1.1"); + expect(result.query).toBe("192\\.168\\.1\\.1"); // Should be escaped as literal + expect(result.warning).toContain("escaped for literal text search"); + }); + + it("should not break hex color codes", () => { + const result = prepareQueryForRipgrep("#[0-9a-fA-F]{6}"); + expect(result.query).toBe("#[0-9a-fA-F]{6}"); + expect(result.warning).toContain("Warning: Unescaped brackets"); // Warn but preserve regex + }); + }); + + describe("patterns that should preserve user intent", () => { + it("should not sanitize intentional regex alternation", () => { + const result = prepareQueryForRipgrep("(foo|bar)"); + expect(result.query).toBe("\\(foo\\|bar\\)"); // Should be escaped as literal since unescaped + expect(result.warning).toContain("escaped for literal text search"); + }); + + it("should preserve escaped alternation in regex", () => { + const result = prepareQueryForRipgrep("\\(foo\\|bar\\)"); + expect(result.query).toBe("\\(foo\\|bar\\)"); + expect(result.warning).toBeUndefined(); + }); + + it("should not break SQL LIKE patterns when used as literal search", () => { + const result = prepareQueryForRipgrep("name LIKE '%john%'"); + expect(result.query).toBe("name LIKE '%john%'"); // No regex metacharacters here + expect(result.warning).toBeUndefined(); + }); + + it("should not break CSS selectors when used as literal search", () => { + const result = prepareQueryForRipgrep(".class-name > div:nth-child(2)"); + expect(result.query).toBe("\\.class-name > div:nth-child\\(2\\)"); + expect(result.warning).toContain("escaped for literal text search"); + }); + }); +}); diff --git a/docs/customization/models.mdx b/docs/customization/models.mdx index 2b63f40d5..a05c22177 100644 --- a/docs/customization/models.mdx +++ b/docs/customization/models.mdx @@ -16,18 +16,18 @@ description: "These blocks form the foundation of the entire assistant experienc ### Best Models by Role -| Model role | Best open models | Best closed models | Notes | -|:------------|:------------------|:-------------------|:--------| -| Agent / Plan | Qwen 3 Coder (480B), Qwen 3 Coder (30B), Qwen2.5-Coder (32B), Devstral (27B), Devstral (24B), GLM 4.5 (355B), GLM 4.5 Air (106B), Kimi K2 (1T), gpt-oss (120B), gpt-oss (20B) | [Claude Opus 4.1](https://hub.continue.dev/anthropic/claude-4-1-opus), [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet), GPT-4, [GPT-5](https://hub.continue.dev/openai/gpt-5), [Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro), DeepSeek models | Closed models are slightly better than open models | -| Chat / Edit | Qwen 3 Coder (480B), Qwen 3 Coder (30B), gpt-oss (120B), gpt-oss (20B), DeepSeek Chat | [Claude Opus 4.1](https://hub.continue.dev/anthropic/claude-4-1-opus), [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet), [GPT-5](https://hub.continue.dev/openai/gpt-5), [Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro) | Closed and open models have pretty similar performance | -| Autocomplete | [QwenCoder2.5 (1.5B)](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b), QwenCoder2.5 (7B) | [Codestral](https://hub.continue.dev/mistral/codestral), Mercury Coder, Mercury Coder Small, DeepSeek Coder | Closed models are slightly better than open models | -| Apply | N/A | [Relace Instant Apply](https://hub.continue.dev/relace/instant-apply), [Morph Fast Apply](https://hub.continue.dev/morphllm/morph-v2) | Open models are basically non-existent / not good enough for this model role | -| Embed | Nomic Embed Text | [Voyage Code 3](https://hub.continue.dev/voyageai/voyage-code-3), [Morph Embeddings](https://hub.continue.dev/morphllm/morph-embedding-v2), Codestral Embed, text-embedding-3-large, text-embedding-004 | Open embeddings models are emerging but closed models still perform better | -| Rerank | zerank-1, zerank-1-small | rerank-2.5, Relace Code Rerank, [Morph Rerank](https://hub.continue.dev/morphllm/morph-rerank-v2) | Open models are beginning to emerge for this model role | -| Next Edit | Zeta | Mercury Coder | Closed models are significantly better than open models | +| Model role | Best open models | Best closed models | Notes | +| :----------- | :------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------- | +| Agent / Plan | Qwen 3 Coder (480B), Qwen 3 Coder (30B), Devstral (27B), Devstral, GLM 4.5 (355B), GLM 4.5 Air (106B), Kimi K2 (1T), gpt-oss (120B), gpt-oss (20B) | [Claude Opus 4.1](https://hub.continue.dev/anthropic/claude-4-1-opus), [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet), [GPT-5](https://hub.continue.dev/openai/gpt-5), [Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro) | Closed models are slightly better than open models | +| Chat / Edit | Qwen 3 Coder (480B), Qwen 3 Coder (30B), gpt-oss (120B), gpt-oss (20B) | [Claude Opus 4.1](https://hub.continue.dev/anthropic/claude-4-1-opus), [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet), [GPT-5](https://hub.continue.dev/openai/gpt-5), [Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro) | Closed and open models have pretty similar performance | +| Autocomplete | [QwenCoder2.5 (1.5B)](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b), QwenCoder2.5 (7B) | [Codestral](https://hub.continue.dev/mistral/codestral), Mercury Coder | Closed models are slightly better than open models | +| Apply | N/A | [Relace Instant Apply](https://hub.continue.dev/relace/instant-apply), [Morph Fast Apply](https://hub.continue.dev/morphllm/morph-v2) | Open models are basically non-existent / not good enough for this model role | +| Embed | Nomic Embed Text | [Voyage Code 3](https://hub.continue.dev/voyageai/voyage-code-3), [Morph Embeddings](https://hub.continue.dev/morphllm/morph-embedding-v2), Codestral Embed, | Open embeddings models are emerging but closed models still perform better | +| Rerank | zerank-1, zerank-1-small | rerank-2.5, Relace Code Rerank, [Morph Rerank](https://hub.continue.dev/morphllm/morph-rerank-v2) | Open models are beginning to emerge for this model role | +| Next Edit | Zeta | Mercury Coder | Closed models are significantly better than open models | ## Learn More About Model Blocks -Continue supports [many model providers](/customize/model-providers/top-level/openai), including Anthropic, OpenAI, Gemini, Ollama, Amazon Bedrock, Azure, xAI, DeepSeek, and more. Models can have various roles like `chat`, `edit`, `apply`, `autocomplete`, `embed`, and `rerank`. +Continue supports [many model providers](/customize/model-providers/top-level/openai), including Anthropic, OpenAI, Gemini, Ollama, Amazon Bedrock, Azure, xAI, and more. Models can have various roles like `chat`, `edit`, `apply`, `autocomplete`, `embed`, and `rerank`. Read more about roles [here](/customize/model-roles) and view [`models`](/reference#models) in the YAML Reference. diff --git a/extensions/cli/build.mjs b/extensions/cli/build.mjs index 8cf88d40d..f5f20778c 100644 --- a/extensions/cli/build.mjs +++ b/extensions/cli/build.mjs @@ -1,8 +1,8 @@ #!/usr/bin/env node import * as esbuild from "esbuild"; -import { writeFileSync, chmodSync } from "fs"; -import { resolve, dirname } from "path"; +import { chmodSync, writeFileSync } from "fs"; +import { dirname, resolve } from "path"; import { fileURLToPath } from "url"; const __dirname = dirname(fileURLToPath(import.meta.url)); @@ -59,9 +59,15 @@ try { __dirname, "../../packages/config-types/dist/index.js", ), - "core": resolve(__dirname, "../../core"), - "@continuedev/fetch": resolve(__dirname, "../../packages/fetch/dist/index.js"), - "@continuedev/llm-info": resolve(__dirname, "../../packages/llm-info/dist/index.js"), + core: resolve(__dirname, "../../core"), + "@continuedev/fetch": resolve( + __dirname, + "../../packages/fetch/dist/index.js", + ), + "@continuedev/llm-info": resolve( + __dirname, + "../../packages/llm-info/dist/index.js", + ), }, // Add banner to create require for CommonJS packages @@ -76,7 +82,7 @@ const require = createRequire(import.meta.url);`, // Create wrapper script with shebang writeFileSync("dist/cn.js", "#!/usr/bin/env node\nimport('./index.js');"); - + // Make the wrapper script executable chmodSync("dist/cn.js", 0o755); diff --git a/extensions/cli/src/__mocks__/args.ts b/extensions/cli/src/__mocks__/args.ts index b0d25ffad..f982bdd09 100644 --- a/extensions/cli/src/__mocks__/args.ts +++ b/extensions/cli/src/__mocks__/args.ts @@ -1,3 +1,5 @@ import { vi } from "vitest"; -export const processRule = vi.fn<(rule: string) => Promise>(); +export const processPromptOrRule = vi.fn<(spec: string) => Promise>(); + +export const processPrompt = vi.fn<(prompt: string) => Promise>(); diff --git a/extensions/cli/src/args-mcp.test.ts b/extensions/cli/src/args-mcp.test.ts new file mode 100644 index 000000000..95f77cc7d --- /dev/null +++ b/extensions/cli/src/args-mcp.test.ts @@ -0,0 +1,75 @@ +import { beforeEach, describe, expect, it } from "vitest"; + +import { parseArgs } from "./args.js"; + +describe("parseArgs --mcp flag", () => { + beforeEach(() => { + // Clear process.argv before each test + process.argv = ["node", "test"]; + }); + + it("should parse single MCP from --mcp flag", () => { + process.argv = ["node", "test", "--mcp", "my-org/my-mcp"]; + const result = parseArgs(); + expect(result.mcps).toEqual(["my-org/my-mcp"]); + }); + + it("should parse multiple MCPs from multiple --mcp flags", () => { + process.argv = ["node", "test", "--mcp", "org1/mcp1", "--mcp", "org2/mcp2"]; + const result = parseArgs(); + expect(result.mcps).toEqual(["org1/mcp1", "org2/mcp2"]); + }); + + it("should handle MCP flag with other flags", () => { + process.argv = [ + "node", + "test", + "--config", + "my-config.yaml", + "--mcp", + "my-org/my-mcp", + "--org", + "test-org", + ]; + const result = parseArgs(); + expect(result.configPath).toBe("my-config.yaml"); + expect(result.mcps).toEqual(["my-org/my-mcp"]); + expect(result.organizationSlug).toBe("test-org"); + }); + + it("should handle MCP flag with prompt", () => { + process.argv = ["node", "test", "--mcp", "my-org/my-mcp", "hello world"]; + const result = parseArgs(); + expect(result.mcps).toEqual(["my-org/my-mcp"]); + expect(result.prompt).toBe("hello world"); + }); + + it("should ignore MCP and rule flag values when extracting prompt", () => { + process.argv = [ + "node", + "test", + "actual prompt", + "--rule", + "my-rule", + "--mcp", + "my-org/my-mcp", + ]; + const result = parseArgs(); + expect(result.prompt).toBe("actual prompt"); + expect(result.rules).toEqual(["my-rule"]); + expect(result.mcps).toEqual(["my-org/my-mcp"]); + }); + + it("should handle MCP flag without value", () => { + process.argv = ["node", "test", "--mcp"]; + const result = parseArgs(); + expect(result.mcps).toEqual([]); + }); + + it("should handle MCP flag at the end without value", () => { + process.argv = ["node", "test", "my prompt", "--mcp"]; + const result = parseArgs(); + expect(result.prompt).toBe("my prompt"); + expect(result.mcps).toEqual([]); + }); +}); diff --git a/extensions/cli/src/args.prompt.test.ts b/extensions/cli/src/args.prompt.test.ts new file mode 100644 index 000000000..46b70b4db --- /dev/null +++ b/extensions/cli/src/args.prompt.test.ts @@ -0,0 +1,84 @@ +import { describe, it, expect, beforeEach, afterAll } from "vitest"; + +import { parseArgs, processPromptOrRule } from "./args.js"; + +describe("args --prompt flag", () => { + const originalArgv = process.argv; + + beforeEach(() => { + // Reset process.argv for each test + process.argv = ["node", "script.js"]; + }); + + afterAll(() => { + // Restore original process.argv after all tests + process.argv = originalArgv; + }); + + it("should parse single prompt from --prompt flag", () => { + process.argv = ["node", "script.js", "--prompt", "my-prompt"]; + const result = parseArgs(); + expect(result.prompts).toEqual(["my-prompt"]); + }); + + it("should parse multiple prompts from multiple --prompt flags", () => { + process.argv = [ + "node", + "script.js", + "--prompt", + "prompt1", + "--prompt", + "prompt2", + ]; + const result = parseArgs(); + expect(result.prompts).toEqual(["prompt1", "prompt2"]); + }); + + it("should handle mixed flags including --prompt", () => { + process.argv = [ + "node", + "script.js", + "--config", + "myconfig", + "--prompt", + "myprompt", + "--resume", + ]; + const result = parseArgs(); + expect(result.configPath).toBe("myconfig"); + expect(result.prompts).toEqual(["myprompt"]); + expect(result.resume).toBe(true); + }); + + it("should not include --prompt value in non-flag arguments", () => { + process.argv = [ + "node", + "script.js", + "--prompt", + "prompt-value", + "actual-prompt", + ]; + const result = parseArgs(); + expect(result.prompts).toEqual(["prompt-value"]); + expect(result.prompt).toBe("actual-prompt"); + }); + + it("should handle both --rule and --prompt flags", () => { + process.argv = [ + "node", + "script.js", + "--rule", + "my-rule", + "--prompt", + "my-prompt", + ]; + const result = parseArgs(); + expect(result.rules).toEqual(["my-rule"]); + expect(result.prompts).toEqual(["my-prompt"]); + }); + + it("should process direct string content", async () => { + const result = await processPromptOrRule("This is a direct prompt"); + expect(result).toBe("This is a direct prompt"); + }); +}); diff --git a/extensions/cli/src/args.test.ts b/extensions/cli/src/args.test.ts index 3db340f73..d22333c05 100644 --- a/extensions/cli/src/args.test.ts +++ b/extensions/cli/src/args.test.ts @@ -1,6 +1,6 @@ import { vi } from "vitest"; -import { parseArgs, processRule } from "./args.js"; +import { parseArgs, processPromptOrRule } from "./args.js"; describe("parseArgs", () => { const originalArgv = process.argv; @@ -217,7 +217,7 @@ describe("parseArgs", () => { }); }); -describe("processRule (loadRuleFromHub integration)", () => { +describe("processPromptOrRule (loadRuleFromHub integration)", () => { // Mock fetch for hub tests const originalFetch = global.fetch; const mockFetch = vi.fn() as any; @@ -251,7 +251,7 @@ describe("processRule (loadRuleFromHub integration)", () => { arrayBuffer: () => Promise.resolve(zipBuffer), } as Response); - const result = await processRule("continuedev/sentry-nextjs"); + const result = await processPromptOrRule("continuedev/sentry-nextjs"); expect(result).toBe(ruleContent); expect(mockFetch).toHaveBeenCalledWith( @@ -269,7 +269,9 @@ describe("processRule (loadRuleFromHub integration)", () => { statusText: "Not Found", } as Response); - await expect(processRule("continuedev/nonexistent-rule")).rejects.toThrow( + await expect( + processPromptOrRule("continuedev/nonexistent-rule"), + ).rejects.toThrow( 'Failed to load rule from hub "continuedev/nonexistent-rule": HTTP 404: Not Found', ); }); @@ -277,7 +279,9 @@ describe("processRule (loadRuleFromHub integration)", () => { it("should handle network errors when loading from hub", async () => { mockFetch.mockRejectedValue(new Error("Network error")); - await expect(processRule("continuedev/sentry-nextjs")).rejects.toThrow( + await expect( + processPromptOrRule("continuedev/sentry-nextjs"), + ).rejects.toThrow( 'Failed to load rule from hub "continuedev/sentry-nextjs": Network error', ); }); @@ -285,7 +289,9 @@ describe("processRule (loadRuleFromHub integration)", () => { it("should handle invalid slug format", async () => { // "invalid-slug" doesn't contain "/" so it's treated as direct content, not a hub slug // Let's test with a slug that has wrong format but contains "/" - await expect(processRule("invalid/slug/too/many/parts")).rejects.toThrow( + await expect( + processPromptOrRule("invalid/slug/too/many/parts"), + ).rejects.toThrow( 'Invalid hub slug format. Expected "owner/package", got: invalid/slug/too/many/parts', ); }); @@ -300,7 +306,9 @@ describe("processRule (loadRuleFromHub integration)", () => { arrayBuffer: () => Promise.resolve(zipBuffer), } as Response); - await expect(processRule("continuedev/empty-rule")).rejects.toThrow( + await expect( + processPromptOrRule("continuedev/empty-rule"), + ).rejects.toThrow( 'Failed to load rule from hub "continuedev/empty-rule": No rule content found in downloaded zip file', ); }); @@ -316,7 +324,9 @@ describe("processRule (loadRuleFromHub integration)", () => { arrayBuffer: () => Promise.resolve(zipBuffer), } as Response); - await expect(processRule("continuedev/directory-only")).rejects.toThrow( + await expect( + processPromptOrRule("continuedev/directory-only"), + ).rejects.toThrow( 'Failed to load rule from hub "continuedev/directory-only": No rule content found in downloaded zip file', ); }); @@ -338,7 +348,7 @@ describe("processRule (loadRuleFromHub integration)", () => { arrayBuffer: () => Promise.resolve(zipBuffer), } as Response); - const result = await processRule("continuedev/mixed-files"); + const result = await processPromptOrRule("continuedev/mixed-files"); expect(result).toBe(mdContent); }); @@ -359,7 +369,7 @@ describe("processRule (loadRuleFromHub integration)", () => { arrayBuffer: () => Promise.resolve(zipBuffer), } as Response); - const result = await processRule("continuedev/multiple-rules"); + const result = await processPromptOrRule("continuedev/multiple-rules"); // Should use the first markdown file found (alphabetically) expect(result).toBe(rule1Content); @@ -373,13 +383,15 @@ describe("processRule (loadRuleFromHub integration)", () => { arrayBuffer: () => Promise.resolve(invalidZipBuffer), } as Response); - await expect(processRule("continuedev/corrupted-zip")).rejects.toThrow( + await expect( + processPromptOrRule("continuedev/corrupted-zip"), + ).rejects.toThrow( 'Failed to load rule from hub "continuedev/corrupted-zip"', ); }); }); - describe("processRule logic", () => { + describe("processPromptOrRule logic", () => { it("should identify hub slugs correctly", async () => { const JSZip = (await import("jszip")).default; const zip = new JSZip(); @@ -391,14 +403,14 @@ describe("processRule (loadRuleFromHub integration)", () => { arrayBuffer: () => Promise.resolve(zipBuffer), } as Response); - const result = await processRule("owner/package"); + const result = await processPromptOrRule("owner/package"); expect(result).toBe("# Hub Rule"); expect(mockFetch).toHaveBeenCalled(); }); it("should treat direct strings as content", async () => { const directContent = "This is direct rule content"; - const result = await processRule(directContent); + const result = await processPromptOrRule(directContent); expect(result).toBe(directContent); expect(mockFetch).not.toHaveBeenCalled(); }); @@ -406,7 +418,7 @@ describe("processRule (loadRuleFromHub integration)", () => { it("should distinguish between hub slugs and file paths", async () => { // This would be treated as a file path, not a hub slug // since it starts with "." - await expect(processRule("./owner/package")).rejects.toThrow( + await expect(processPromptOrRule("./owner/package")).rejects.toThrow( 'Failed to read rule file "./owner/package": Rule file not found', ); expect(mockFetch).not.toHaveBeenCalled(); diff --git a/extensions/cli/src/args.ts b/extensions/cli/src/args.ts index 1d46ee40f..fca0c86e5 100644 --- a/extensions/cli/src/args.ts +++ b/extensions/cli/src/args.ts @@ -1,10 +1,3 @@ -import * as fs from "fs"; -import * as path from "path"; - -import JSZip from "jszip"; - -import { env } from "./env.js"; - export interface CommandLineArgs { configPath?: string; organizationSlug?: string; // Organization slug to use for this session @@ -12,102 +5,53 @@ export interface CommandLineArgs { resume?: boolean; // Resume from last session readonly?: boolean; // Start in plan mode (backward compatibility) rules?: string[]; // Array of rule specifications + mcps?: string[]; // Array of MCP server slugs from the hub + models?: string[]; // Array of model slugs from the hub + prompts?: string[]; // Array of prompt slugs from the hub format?: "json"; // Output format for headless mode } +// Re-export hub loader functions for backward compatibility +export { loadMcpFromHub, processRule } from "./hubLoader.js"; +// Alias processRule as processPromptOrRule for backward compatibility +export { processRule as processPromptOrRule } from "./hubLoader.js"; + /** - * Load rule content from a file path - * @param filePath - Path to the rule file - * @returns The content of the rule file + * Extract values for a specific flag that can appear multiple times */ -function loadRuleFromFile(filePath: string): string { - try { - const absolutePath = path.resolve(filePath); - if (!fs.existsSync(absolutePath)) { - throw new Error(`Rule file not found: ${filePath}`); +function extractMultipleFlags(args: string[], flagName: string): string[] { + const indices: number[] = []; + for (let i = 0; i < args.length; i++) { + if (args[i] === flagName) { + indices.push(i); } - return fs.readFileSync(absolutePath, "utf-8"); - } catch (error: any) { - throw new Error(`Failed to read rule file "${filePath}": ${error.message}`); } + + const values: string[] = []; + for (const index of indices) { + if (index + 1 < args.length && !args[index + 1].startsWith("--")) { + values.push(args[index + 1]); + } + } + return values; } /** - * Load rule content from hub.continue.dev - * @param slug - The slug in format "owner/package" - * @returns The rule content from the hub + * Extract value for a single-value flag */ -async function loadRuleFromHub(slug: string): Promise { - const parts = slug.split("/"); - if (parts.length !== 2) { - throw new Error( - `Invalid hub slug format. Expected "owner/package", got: ${slug}`, - ); - } - - const [ownerSlug, ruleSlug] = parts; - const downloadUrl = new URL( - `v0/${ownerSlug}/${ruleSlug}/latest/download`, - env.apiBase, - ); - - try { - const response = await fetch(downloadUrl); - - if (!response.ok) { - throw new Error(`HTTP ${response.status}: ${response.statusText}`); - } - - // The API returns a zip file, so we need to extract the rule content - const arrayBuffer = await response.arrayBuffer(); - const zip = new JSZip(); - const zipContents = await zip.loadAsync(arrayBuffer); - - // Find the first .md or .txt file (rule content) - const ruleFiles = Object.keys(zipContents.files).filter( - (filename) => - filename.endsWith(".md") && !zipContents.files[filename].dir, - ); - - if (ruleFiles.length === 0) { - throw new Error("No rule content found in downloaded zip file"); - } - - // Use the first rule file found - TODO support multiple rules and parse frontmatter - const ruleFile = zipContents.files[ruleFiles[0]]; - const content = await ruleFile.async("text"); - return content; - } catch (error: any) { - throw new Error(`Failed to load rule from hub "${slug}": ${error.message}`); - } -} - -/** - * Process a rule specification and return its content - * @param ruleSpec - Can be a file path, hub slug, or direct string content - * @returns The processed rule content - */ -export async function processRule(ruleSpec: string): Promise { - // If it looks like a hub slug (contains / but doesn't start with . or /) +function extractSingleFlag( + args: string[], + flagName: string, +): string | undefined { + const index = args.indexOf(flagName); if ( - ruleSpec.includes("/") && - !ruleSpec.startsWith(".") && - !ruleSpec.startsWith("/") + index !== -1 && + index + 1 < args.length && + !args[index + 1].startsWith("--") ) { - return await loadRuleFromHub(ruleSpec); + return args[index + 1]; } - - // If it looks like a file path (contains . or / or ends with common file extensions) - if ( - ruleSpec.includes(".") || - ruleSpec.includes("/") || - ruleSpec.includes("\\") - ) { - return loadRuleFromFile(ruleSpec); - } - - // Otherwise, treat it as direct string content - return ruleSpec; + return undefined; } /** @@ -117,73 +61,76 @@ export async function processRule(ruleSpec: string): Promise { */ export function parseArgs(): CommandLineArgs { const args = process.argv.slice(2); - - // Default values const result: CommandLineArgs = {}; + // Parse boolean flags if (args.includes("--resume")) { result.resume = true; } - if (args.includes("--readonly")) { result.readonly = true; } - // Get format from --format flag - const formatIndex = args.indexOf("--format"); - if (formatIndex !== -1 && formatIndex + 1 < args.length) { - const formatValue = args[formatIndex + 1]; - if (formatValue === "json") { - result.format = "json"; - } + // Parse single-value flags + const formatValue = extractSingleFlag(args, "--format"); + if (formatValue === "json") { + result.format = "json"; } - // Get config path from --config flag - const configIndex = args.indexOf("--config"); - if (configIndex !== -1 && configIndex + 1 < args.length) { - result.configPath = args[configIndex + 1]; - } + result.configPath = extractSingleFlag(args, "--config"); - // Get organization slug from --org flag - const orgIndex = args.indexOf("--org"); - if (orgIndex !== -1 && orgIndex + 1 < args.length) { - const orgValue = args[orgIndex + 1]; - // Convert "personal" to undefined right away to simplify downstream logic + const orgValue = extractSingleFlag(args, "--org"); + if (orgValue) { result.organizationSlug = orgValue.toLowerCase() === "personal" ? undefined : orgValue; } - // Get rules from --rule flags (can be specified multiple times) - const ruleIndices: number[] = []; - for (let i = 0; i < args.length; i++) { - if (args[i] === "--rule") { - ruleIndices.push(i); - } - } - - if (ruleIndices.length > 0) { + // Parse multi-value flags + const rules = extractMultipleFlags(args, "--rule"); + if (rules.length > 0) { + result.rules = rules; + } else if (args.includes("--rule")) { result.rules = []; - for (const ruleIndex of ruleIndices) { - if (ruleIndex + 1 < args.length) { - result.rules.push(args[ruleIndex + 1]); - } - } } - // Find the last argument that's not a flag or a flag value - const flagsWithValues = ["--config", "--org", "--rule", "--format"]; + const mcps = extractMultipleFlags(args, "--mcp"); + if (mcps.length > 0) { + result.mcps = mcps; + } else if (args.includes("--mcp")) { + // Ensure we have an empty array if --mcp flag is present but has no values + result.mcps = []; + } + + const models = extractMultipleFlags(args, "--model"); + if (models.length > 0) { + result.models = models; + } else if (args.includes("--model")) { + result.models = []; + } + + const prompts = extractMultipleFlags(args, "--prompt"); + if (prompts.length > 0) { + result.prompts = prompts; + } else if (args.includes("--prompt")) { + result.prompts = []; + } + + // Extract prompt from non-flag arguments + const flagsWithValues = [ + "--config", + "--org", + "--rule", + "--mcp", + "--model", + "--prompt", + "--format", + ]; const nonFlagArgs = args.filter((arg, index) => { - // Skip flags (starting with --) if (arg.startsWith("--") || arg === "-p") return false; - - // Skip flag values const prevArg = index > 0 ? args[index - 1] : ""; - if (flagsWithValues.includes(prevArg)) return false; - - return true; + return !flagsWithValues.includes(prevArg); }); - // If there are any non-flag arguments, use the last one as the prompt if (nonFlagArgs.length > 0) { result.prompt = nonFlagArgs[nonFlagArgs.length - 1]; } diff --git a/extensions/cli/src/auth/workos-org.test.ts b/extensions/cli/src/auth/workos-org.test.ts index bfca02089..ba0de72b2 100644 --- a/extensions/cli/src/auth/workos-org.test.ts +++ b/extensions/cli/src/auth/workos-org.test.ts @@ -13,6 +13,10 @@ vi.mock("../config.js", () => ({ })), })); +vi.mock("../init.js", () => ({ + safeStderr: vi.fn(), +})); + vi.mock("fs", () => ({ default: { existsSync: vi.fn(() => false), @@ -91,7 +95,8 @@ describe("ensureOrganization with CLI organization slug", () => { describe("Mode restriction", () => { test("should reject --org flag in interactive mode", async () => { - const consoleErrorSpy = vi.spyOn(console, "error"); + const { safeStderr } = await import("../init.js"); + const safeStderrSpy = vi.mocked(safeStderr); const processExitSpy = vi .spyOn(process, "exit") .mockImplementation(() => { @@ -102,9 +107,9 @@ describe("ensureOrganization with CLI organization slug", () => { ensureOrganization(mockAuthConfig, false, "org-one"), ).rejects.toThrow("Process exit"); - expect(consoleErrorSpy).toHaveBeenCalledWith( + expect(safeStderrSpy).toHaveBeenCalledWith( chalk.red( - "The --org flag is only supported in headless mode (with -p/--print flag)", + "The --org flag is only supported in headless mode (with -p/--print flag)\n", ), ); expect(processExitSpy).toHaveBeenCalledWith(1); diff --git a/extensions/cli/src/auth/workos.helpers.ts b/extensions/cli/src/auth/workos.helpers.ts index 67dac76c9..efd2151cc 100644 --- a/extensions/cli/src/auth/workos.helpers.ts +++ b/extensions/cli/src/auth/workos.helpers.ts @@ -1,6 +1,7 @@ import chalk from "chalk"; import { getApiClient } from "../config.js"; +import { safeStderr } from "../init.js"; import type { AuthConfig, @@ -70,9 +71,9 @@ export async function handleCliOrgForEnvironmentAuth( ): Promise { // Only allow --org flag in headless mode if (!isHeadless) { - console.error( + safeStderr( chalk.red( - "The --org flag is only supported in headless mode (with -p/--print flag)", + "The --org flag is only supported in headless mode (with -p/--print flag)\n", ), ); process.exit(1); @@ -101,9 +102,9 @@ export async function handleCliOrgForAuthenticatedConfig( ): Promise { // Only allow --org flag in headless mode if (!isHeadless) { - console.error( + safeStderr( chalk.red( - "The --org flag is only supported in headless mode (with -p/--print flag)", + "The --org flag is only supported in headless mode (with -p/--print flag)\n", ), ); process.exit(1); diff --git a/extensions/cli/src/commands/BaseCommandOptions.ts b/extensions/cli/src/commands/BaseCommandOptions.ts index 46a5d84d5..0d0808ea3 100644 --- a/extensions/cli/src/commands/BaseCommandOptions.ts +++ b/extensions/cli/src/commands/BaseCommandOptions.ts @@ -1,16 +1,25 @@ /** * Base interface for command options that are shared across multiple commands + * Uses command-line flag names for direct compatibility */ export interface BaseCommandOptions { - /** Path to configuration file */ + /** Path to configuration file (--config) */ config?: string; - /** Array of rule specifications (can be file paths, hub slugs, or string content) */ + /** Organization slug to use for this session (--org) */ + org?: string; + /** Array of rule specifications (--rule) */ rule?: string[]; - /** Array of tools to allow (overrides default policies) */ + /** Array of MCP server slugs from the hub (--mcp) */ + mcp?: string[]; + /** Array of model slugs from the hub (--model) */ + model?: string[]; + /** Array of prompt slugs from the hub (--prompt) */ + prompt?: string[]; + /** Array of tools to allow (--allow) */ allow?: string[]; - /** Array of tools to ask permission for (overrides default policies) */ + /** Array of tools to ask permission for (--ask) */ ask?: string[]; - /** Array of tools to exclude from use (overrides default policies) */ + /** Array of tools to exclude from use (--exclude) */ exclude?: string[]; } diff --git a/extensions/cli/src/commands/chat.ts b/extensions/cli/src/commands/chat.ts index c3177a10a..773a214e6 100644 --- a/extensions/cli/src/commands/chat.ts +++ b/extensions/cli/src/commands/chat.ts @@ -77,10 +77,8 @@ function stripThinkTags(response: string): string { export interface ChatOptions extends ExtendedCommandOptions { headless?: boolean; resume?: boolean; - rule?: string[]; // Array of rule specifications format?: "json"; // Output format for headless mode silent?: boolean; // Strip tags and excess whitespace - org?: string; // Organization slug to use for this session } export async function initializeChatHistory( @@ -159,7 +157,7 @@ async function handleManualCompaction( } } -// Helper function to handle auto-compaction +// Helper function to handle auto-compaction for headless mode async function handleAutoCompaction( chatHistory: ChatCompletionMessageParam[], model: ModelConfig, @@ -167,64 +165,71 @@ async function handleAutoCompaction( isHeadless: boolean, format?: "json", ): Promise { - logger.info("Auto-compacting triggered due to context limit"); + const { handleAutoCompaction: coreAutoCompaction } = await import( + "../streamChatResponse.autoCompaction.js" + ); - if (!isHeadless) { - console.info( - chalk.yellow( - "\nApproaching context limit. Auto-compacting chat history...", - ), - ); - } else if (format === "json") { - safeStdout( - JSON.stringify({ - status: "info", - message: "Auto-compacting triggered", - contextUsage: - calculateContextUsagePercentage( - countChatHistoryTokens(chatHistory), - model, - ) + "%", - }) + "\n", - ); - } + // Custom callbacks for headless mode console output + const callbacks = { + onSystemMessage: (message: string) => { + if ( + message.includes("Auto-compacting") || + message.includes("Approaching") + ) { + if (!isHeadless) { + console.info(chalk.yellow(`\n${message}`)); + } else if (format === "json") { + safeStdout( + JSON.stringify({ + status: "info", + message: "Auto-compacting triggered", + contextUsage: + calculateContextUsagePercentage( + countChatHistoryTokens(chatHistory), + model, + ) + "%", + }) + "\n", + ); + } + } else if (message.includes("✓")) { + if (!isHeadless) { + console.info(chalk.green(message)); + } else if (format === "json") { + safeStdout( + JSON.stringify({ + status: "success", + message: "Auto-compacted successfully", + historyLength: chatHistory.length, + }) + "\n", + ); + } + } else if (message.includes("Warning:")) { + if (!isHeadless) { + console.error(chalk.red(message)); + console.info(chalk.yellow("Continuing without compaction...")); + } else if (format === "json") { + safeStdout( + JSON.stringify({ + status: "warning", + message: "Auto-compaction failed, continuing without compaction", + }) + "\n", + ); + } + } + }, + }; - try { - const result = await compactChatHistory(chatHistory, model, llmApi); - chatHistory.length = 0; - chatHistory.push(...result.compactedHistory); - saveSession(chatHistory); + const result = await coreAutoCompaction(chatHistory, model, llmApi, { + isHeadless, + format, + callbacks, + }); - if (!isHeadless) { - console.info(chalk.green("✓ Chat history auto-compacted successfully.")); - } else if (format === "json") { - safeStdout( - JSON.stringify({ - status: "success", - message: "Auto-compacted successfully", - historyLength: chatHistory.length, - }) + "\n", - ); - } + // Update the original array reference for headless mode + chatHistory.length = 0; + chatHistory.push(...result.chatHistory); - return result.compactionIndex; - } catch (error) { - const errorMsg = `Auto-compaction error: ${formatError(error)}`; - logger.error(errorMsg); - - if (!isHeadless) { - console.error(chalk.red(`Warning: ${errorMsg}`)); - console.info(chalk.yellow("Continuing without compaction...")); - } else if (format === "json") { - safeStdout( - JSON.stringify({ - status: "warning", - message: "Auto-compaction failed, continuing without compaction", - }) + "\n", - ); - } - return null; - } + return result.compactionIndex; } interface ProcessMessageOptions { @@ -362,9 +367,7 @@ async function runHeadlessMode( const { permissionOverrides } = processCommandFlags(options); await initializeServices({ - configPath: options.config, - organizationSlug: options.org, - rules: options.rule, + options, headless: true, toolPermissionOverrides: permissionOverrides, }); @@ -388,17 +391,26 @@ async function runHeadlessMode( compactionIndex = findCompactionIndex(chatHistory); } + // Handle additional prompts from --prompt flags + const { processAndCombinePrompts } = await import( + "../util/promptProcessor.js" + ); + const initialUserInput = await processAndCombinePrompts( + options.prompt, + prompt, + ); + let isFirstMessage = true; while (true) { // When in headless mode, don't ask for user input - if (!isFirstMessage && prompt && options.headless) { + if (!isFirstMessage && initialUserInput && options.headless) { break; } // Get user input const userInput = - isFirstMessage && prompt - ? prompt + isFirstMessage && initialUserInput + ? initialUserInput : readlineSync.question(`\n${chalk.bold.green("You:")} `); isFirstMessage = false; @@ -443,9 +455,7 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { // Initialize services with onboarding handled internally const initResult = await initializeServices({ - configPath: options.config, - organizationSlug: options.org, - rules: options.rule, + options, headless: false, toolPermissionOverrides: permissionOverrides, }); @@ -462,9 +472,10 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { const tuiOptions: any = { initialPrompt: prompt, resume: options.resume, - configPath: options.config, - organizationSlug: options.org, - additionalRules: options.rule, + config: options.config, + org: options.org, + rule: options.rule, + prompt: options.prompt, toolPermissionOverrides: permissionOverrides, skipOnboarding: true, }; diff --git a/extensions/cli/src/commands/commands.ts b/extensions/cli/src/commands/commands.ts index 07e893935..d1e6325e9 100644 --- a/extensions/cli/src/commands/commands.ts +++ b/extensions/cli/src/commands/commands.ts @@ -4,9 +4,9 @@ import { type AssistantConfig } from "@continuedev/sdk"; export { chat } from "./chat.js"; export { login } from "./login.js"; export { logout } from "./logout.js"; +export { listSessionsCommand } from "./ls.js"; export { remote } from "./remote.js"; export { serve } from "./serve.js"; -export { listSessionsCommand } from "./ls.js"; export interface SlashCommand { name: string; @@ -45,6 +45,11 @@ export const SYSTEM_SLASH_COMMANDS: SystemCommand[] = [ description: "Check who you're currently logged in as", category: "system", }, + { + name: "info", + description: "Show session information", + category: "system", + }, { name: "model", description: "Switch between available chat models", diff --git a/extensions/cli/src/commands/serve.test.ts b/extensions/cli/src/commands/serve.test.ts index 06ee924af..2bc8428bd 100644 --- a/extensions/cli/src/commands/serve.test.ts +++ b/extensions/cli/src/commands/serve.test.ts @@ -137,7 +137,9 @@ describe("serve command", () => { expect(initializeServicesSpy).toHaveBeenCalled(); expect(initializeServicesSpy).toHaveBeenCalledWith( expect.objectContaining({ - organizationSlug: "test-organization-slug", + options: expect.objectContaining({ + org: "test-organization-slug", + }), }), ); diff --git a/extensions/cli/src/commands/serve.ts b/extensions/cli/src/commands/serve.ts index c946046cf..70ff6738e 100644 --- a/extensions/cli/src/commands/serve.ts +++ b/extensions/cli/src/commands/serve.ts @@ -37,7 +37,6 @@ const execAsync = promisify(exec); interface ServeOptions extends ExtendedCommandOptions { timeout?: string; port?: string; - org?: string; } interface PendingPermission { @@ -80,10 +79,8 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { const { permissionOverrides } = processCommandFlags(options); await initializeServices({ + options, toolPermissionOverrides: permissionOverrides, - configPath: options.config, - rules: options.rule, - organizationSlug: options.org, headless: true, // Skip onboarding in serve mode }); diff --git a/extensions/cli/src/compaction.infiniteLoop.test.ts b/extensions/cli/src/compaction.infiniteLoop.test.ts new file mode 100644 index 000000000..c0f1127cd --- /dev/null +++ b/extensions/cli/src/compaction.infiniteLoop.test.ts @@ -0,0 +1,138 @@ +import { ModelConfig } from "@continuedev/config-yaml"; +import { BaseLlmApi } from "@continuedev/openai-adapters"; +import { ChatCompletionMessageParam } from "openai/resources.mjs"; +import { describe, it, expect, vi } from "vitest"; + +import { compactChatHistory } from "./compaction.js"; +import { streamChatResponse } from "./streamChatResponse.js"; + +// Mock the dependencies +vi.mock("./streamChatResponse.js", () => ({ + streamChatResponse: vi.fn(), +})); + +vi.mock("./util/tokenizer.js", () => ({ + countChatHistoryTokens: vi.fn(), + getModelContextLimit: vi.fn(), +})); + +describe("compaction infinite loop prevention", () => { + const mockModel: ModelConfig = { + name: "test-model", + provider: "test", + model: "test-model", + defaultCompletionOptions: { + maxTokens: 1000, + contextLength: 4000, + }, + } as ModelConfig; + + const mockLlmApi = {} as BaseLlmApi; + + it("should not loop infinitely when pruning doesn't reduce history size", async () => { + const { countChatHistoryTokens, getModelContextLimit } = await import( + "./util/tokenizer.js" + ); + const mockStreamResponse = vi.mocked(streamChatResponse); + const mockCountTokens = vi.mocked(countChatHistoryTokens); + const mockGetContextLimit = vi.mocked(getModelContextLimit); + + // Setup mocks + mockGetContextLimit.mockReturnValue(4000); + mockCountTokens.mockReturnValue(5000); // Always too big + mockStreamResponse.mockImplementation( + async (history, model, api, controller, callbacks) => { + callbacks?.onContent?.("Summary"); + callbacks?.onContentComplete?.("Summary"); + return "Summary"; + }, + ); + + // History that can't be pruned further (only system message) + const history: ChatCompletionMessageParam[] = [ + { role: "system", content: "System message" }, + ]; + + // This should not hang - it should break out of the loop + const result = await compactChatHistory(history, mockModel, mockLlmApi, {}); + + // Should complete successfully even though token count is still too high + expect(result.compactedHistory).toBeDefined(); + expect(mockCountTokens).toHaveBeenCalled(); + }); + + it("should not loop infinitely with history ending in assistant message", async () => { + const { countChatHistoryTokens, getModelContextLimit } = await import( + "./util/tokenizer.js" + ); + const mockStreamResponse = vi.mocked(streamChatResponse); + const mockCountTokens = vi.mocked(countChatHistoryTokens); + const mockGetContextLimit = vi.mocked(getModelContextLimit); + + // Setup mocks + mockGetContextLimit.mockReturnValue(4000); + mockCountTokens.mockReturnValue(5000); // Always too big + mockStreamResponse.mockImplementation( + async (history, model, api, controller, callbacks) => { + callbacks?.onContent?.("Summary"); + callbacks?.onContentComplete?.("Summary"); + return "Summary"; + }, + ); + + // History that ends with assistant - pruning won't change it + const history: ChatCompletionMessageParam[] = [ + { role: "system", content: "System message" }, + { role: "user", content: "Hello" }, + { role: "assistant", content: "Hi there" }, + ]; + + // This should not hang + const result = await compactChatHistory(history, mockModel, mockLlmApi, {}); + + expect(result.compactedHistory).toBeDefined(); + }); + + it("should successfully prune when pruning actually reduces size", async () => { + const { countChatHistoryTokens, getModelContextLimit } = await import( + "./util/tokenizer.js" + ); + const mockStreamResponse = vi.mocked(streamChatResponse); + const mockCountTokens = vi.mocked(countChatHistoryTokens); + const mockGetContextLimit = vi.mocked(getModelContextLimit); + + // Setup mocks + mockGetContextLimit.mockReturnValue(4000); + + // Mock token counting to show reduction after pruning + let callCount = 0; + mockCountTokens.mockImplementation(() => { + callCount++; + if (callCount === 1) return 5000; // Initial too big + if (callCount === 2) return 3000; // After pruning, fits + return 2000; // Subsequent calls + }); + + mockStreamResponse.mockImplementation( + async (history, model, api, controller, callbacks) => { + callbacks?.onContent?.("Summary"); + callbacks?.onContentComplete?.("Summary"); + return "Summary"; + }, + ); + + // History that can be successfully pruned + const history: ChatCompletionMessageParam[] = [ + { role: "system", content: "System message" }, + { role: "user", content: "Hello" }, + { role: "assistant", content: "Hi there" }, + { role: "user", content: "Another question" }, + ]; + + const result = await compactChatHistory(history, mockModel, mockLlmApi, {}); + + expect(result.compactedHistory).toBeDefined(); + // The function will call countTokens multiple times during the process + expect(mockCountTokens).toHaveBeenCalled(); + }); +}); diff --git a/extensions/cli/src/compaction.pruneLastMessage.test.ts b/extensions/cli/src/compaction.pruneLastMessage.test.ts new file mode 100644 index 000000000..40e10949d --- /dev/null +++ b/extensions/cli/src/compaction.pruneLastMessage.test.ts @@ -0,0 +1,185 @@ +import { ChatCompletionMessageParam } from "openai/resources.mjs"; +import { describe, it, expect } from "vitest"; + +import { pruneLastMessage } from "./compaction.js"; + +describe("pruneLastMessage", () => { + it("should return empty array for empty input", () => { + const result = pruneLastMessage([]); + expect(result).toEqual([]); + }); + + it("should remove single user message", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "user", content: "Hello" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual([]); + }); + + it("should return empty array for single system message", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "system", content: "System" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual([]); + }); + + it("should return empty array for single assistant message", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "assistant", content: "Hello" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual([]); + }); + + it("should return empty array for single tool message", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "tool", content: "Tool output", tool_call_id: "1" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual([]); + }); + + it("should remove last message when second-to-last is user", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "system", content: "System" }, + { role: "user", content: "Hello" }, + { role: "assistant", content: "Hi there" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual([{ role: "system", content: "System" }]); + }); + + it("should remove assistant+tool sequence when second-to-last is assistant with tool calls", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "system", content: "System" }, + { role: "user", content: "Run command" }, + { + role: "assistant", + content: "Running...", + tool_calls: [{ id: "1" } as any], + }, + { role: "tool", content: "Command output", tool_call_id: "1" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual([ + { role: "system", content: "System" }, + { role: "user", content: "Run command" }, + ]); + }); + + it("should prune last message when second-to-last is not user or assistant with tool calls", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "system", content: "System" }, + { role: "assistant", content: "Hi there" }, + { role: "user", content: "Another question" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual([ + { role: "system", content: "System" }, + { role: "assistant", content: "Hi there" }, + ]); + }); + + it("should handle multiple user messages by removing two at a time", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "system", content: "System" }, + { role: "user", content: "Question 1" }, + { role: "user", content: "Question 2" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual([{ role: "system", content: "System" }]); + }); + + it("should handle tool call sequences by removing user after tool", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "system", content: "System" }, + { role: "user", content: "Do something" }, + { + role: "assistant", + content: "I'll help", + tool_calls: [{ id: "1" } as any], + }, + { role: "tool", content: "Tool result", tool_call_id: "1" }, + { role: "user", content: "Follow up question" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual([ + { role: "system", content: "System" }, + { role: "user", content: "Do something" }, + { + role: "assistant", + content: "I'll help", + tool_calls: [{ id: "1" } as any], + }, + { role: "tool", content: "Tool result", tool_call_id: "1" }, + ]); + }); + + it("should remove both user messages when consecutive", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "user", content: "Hello" }, + { role: "user", content: "Another message" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual([]); + }); + + it("should handle complex conversation flow", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "system", content: "System" }, + { role: "user", content: "Request 1" }, + { role: "assistant", content: "Response 1" }, + { role: "user", content: "Request 2" }, + { + role: "assistant", + content: "Using tool", + tool_calls: [{ id: "1" } as any], + }, + { role: "tool", content: "Tool result", tool_call_id: "1" }, + { role: "assistant", content: "Final response" }, + { role: "user", content: "Follow up 1" }, + { role: "user", content: "Follow up 2" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual([ + { role: "system", content: "System" }, + { role: "user", content: "Request 1" }, + { role: "assistant", content: "Response 1" }, + { role: "user", content: "Request 2" }, + { + role: "assistant", + content: "Using tool", + tool_calls: [{ id: "1" } as any], + }, + { role: "tool", content: "Tool result", tool_call_id: "1" }, + { role: "assistant", content: "Final response" }, + ]); + }); + + it("should handle history starting with non-system message", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "user", content: "Hello" }, + { role: "assistant", content: "Hi" }, + { role: "user", content: "Follow up" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual([ + { role: "user", content: "Hello" }, + { role: "assistant", content: "Hi" }, + ]); + }); +}); diff --git a/extensions/cli/src/compaction.ts b/extensions/cli/src/compaction.ts index c60f814a7..920f754d7 100644 --- a/extensions/cli/src/compaction.ts +++ b/extensions/cli/src/compaction.ts @@ -5,6 +5,10 @@ import { ChatCompletionMessageParam } from "openai/resources.mjs"; import { streamChatResponse } from "./streamChatResponse.js"; import { StreamCallbacks } from "./streamChatResponse.types.js"; import { logger } from "./util/logger.js"; +import { + countChatHistoryTokens, + getModelContextLimit, +} from "./util/tokenizer.js"; export const COMPACTION_MARKER = "[COMPACTED HISTORY]"; @@ -41,8 +45,39 @@ export async function compactChatHistory( "Please provide a concise summary of our conversation so far, capturing the key context, decisions made, and current state. Format this as a single comprehensive message that preserves all important information needed to continue our work. You do not need to recap the system message, as this will remain.", }; - // Get the current history for compaction - const historyForCompaction = [...chatHistory, compactionPrompt]; + // Check if the history with compaction prompt is too long, prune if necessary + let historyToUse = chatHistory; + let historyForCompaction = [...historyToUse, compactionPrompt]; + + const contextLimit = getModelContextLimit(model); + const maxTokens = model.defaultCompletionOptions?.maxTokens || 0; + const reservedForOutput = + maxTokens > 0 ? maxTokens : Math.ceil(contextLimit * 0.35); + const availableForInput = contextLimit - reservedForOutput; + + // Check if we need to prune to fit within context + while ( + countChatHistoryTokens(historyForCompaction) > availableForInput && + historyToUse.length > 0 + ) { + logger.debug("Compaction history too long, pruning last message", { + tokenCount: countChatHistoryTokens(historyForCompaction), + availableForInput, + historyLength: historyToUse.length, + }); + const prunedHistory = pruneLastMessage(historyToUse); + + // Break if pruning didn't change the history (prevents infinite loop) + if (prunedHistory.length === historyToUse.length) { + logger.warn( + "Cannot prune history further while maintaining valid conversation structure", + ); + break; + } + + historyToUse = prunedHistory; + historyForCompaction = [...historyToUse, compactionPrompt]; + } // Stream the compaction response const controller = new AbortController(); @@ -121,6 +156,39 @@ export function findCompactionIndex( * @param compactionIndex The index of the compaction message, if any * @returns The history to send to the LLM */ +/** + * Prunes chat history by removing messages from the end while ensuring + * the history ends with either an assistant message or a tool result message + * @param chatHistory The chat history to prune + * @returns The pruned chat history ending with assistant or tool message + */ +export function pruneLastMessage( + chatHistory: ChatCompletionMessageParam[], +): ChatCompletionMessageParam[] { + if (chatHistory.length === 0) { + return chatHistory; + } + + if (chatHistory.length === 1) { + // Only one message - always return empty array + return []; + } + + const secondToLastIndex = chatHistory.length - 2; + const secondToLastMessage = chatHistory[secondToLastIndex]; + + if ( + secondToLastMessage.role === "assistant" && + secondToLastMessage.tool_calls?.length + ) { + return chatHistory.slice(0, -2); + } else if (secondToLastMessage.role === "user") { + return chatHistory.slice(0, -2); + } + + return chatHistory.slice(0, -1); +} + export function getHistoryForLLM( fullHistory: ChatCompletionMessageParam[], compactionIndex: number | null, diff --git a/extensions/cli/src/configEnhancer.test.ts b/extensions/cli/src/configEnhancer.test.ts new file mode 100644 index 000000000..bbee50c0b --- /dev/null +++ b/extensions/cli/src/configEnhancer.test.ts @@ -0,0 +1,202 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import { BaseCommandOptions } from "./commands/BaseCommandOptions.js"; +import { ConfigEnhancer } from "./configEnhancer.js"; + +// Mock processRule to simulate hub loading +vi.mock("./hubLoader.js", () => ({ + processRule: vi.fn((rule: string) => { + // Simulate hub slug loading + if (rule.includes("/") && !rule.startsWith(".") && !rule.startsWith("/")) { + return Promise.resolve(`Content for ${rule}`); + } + // Return as-is for direct content + return Promise.resolve(rule); + }), + loadPackagesFromHub: vi.fn(() => Promise.resolve([])), + mcpProcessor: {}, + modelProcessor: {}, +})); + +describe("ConfigEnhancer", () => { + let enhancer: ConfigEnhancer; + let mockConfig: any; + + beforeEach(() => { + enhancer = new ConfigEnhancer(); + mockConfig = { + name: "test-config", + version: "1.0.0", + models: [], + mcpServers: [], + } as any; + vi.clearAllMocks(); + }); + + it("should return unchanged config when no enhancements provided", async () => { + const config = await enhancer.enhanceConfig(mockConfig, {}); + + expect(config).toEqual(mockConfig); + }); + + it("should apply rules enhancement", async () => { + const options: BaseCommandOptions = { + rule: ["test-rule"], + }; + + const config = await enhancer.enhanceConfig(mockConfig, options); + + expect(config.rules).toEqual(["test-rule"]); + }); + + it("should apply multiple enhancements", async () => { + const options: BaseCommandOptions = { + rule: ["rule1", "rule2"], + mcp: [], + }; + + const config = await enhancer.enhanceConfig(mockConfig, options); + + expect(config.rules).toEqual(["rule1", "rule2"]); + }); + + it("should preserve existing rules when adding new ones", async () => { + mockConfig.rules = ["existing rule"]; + const options: BaseCommandOptions = { + rule: ["new rule"], + }; + + const config = await enhancer.enhanceConfig(mockConfig, options); + + expect(config.rules).toEqual(["existing rule", "new rule"]); + }); + + it("should not mutate original config", async () => { + const originalConfig = { ...mockConfig }; + const options: BaseCommandOptions = { + rule: ["test-rule"], + }; + + await enhancer.enhanceConfig(mockConfig, options); + + expect(mockConfig).toEqual(originalConfig); + }); + + it("should preserve hub slug as rule name", async () => { + const options: BaseCommandOptions = { + rule: ["nate/spanish"], + }; + + const config = await enhancer.enhanceConfig(mockConfig, options); + + expect(config.rules).toHaveLength(1); + expect(config.rules?.[0]).toEqual({ + name: "nate/spanish", + rule: "Content for nate/spanish", + }); + }); + + it("should handle mix of hub slugs and direct content", async () => { + const options: BaseCommandOptions = { + rule: ["nate/spanish", "Always be helpful", "org/another-rule"], + }; + + const config = await enhancer.enhanceConfig(mockConfig, options); + + expect(config.rules).toHaveLength(3); + expect(config.rules?.[0]).toEqual({ + name: "nate/spanish", + rule: "Content for nate/spanish", + }); + expect(config.rules?.[1]).toBe("Always be helpful"); + expect(config.rules?.[2]).toEqual({ + name: "org/another-rule", + rule: "Content for org/another-rule", + }); + }); + + it("should treat file paths as plain strings", async () => { + const options: BaseCommandOptions = { + rule: ["./rules/my-rule.md", "/absolute/path/rule.txt"], + }; + + const config = await enhancer.enhanceConfig(mockConfig, options); + + expect(config.rules).toHaveLength(2); + // File paths should be stored as plain strings + expect(config.rules?.[0]).toBe("./rules/my-rule.md"); + expect(config.rules?.[1]).toBe("/absolute/path/rule.txt"); + }); + + it("should prepend models from --model flag to make them default", async () => { + // Mock loadPackagesFromHub to return test models + const { loadPackagesFromHub } = await import("./hubLoader.js"); + (loadPackagesFromHub as any).mockResolvedValueOnce([ + { name: "GPT-5", provider: "openai", model: "gpt-5" }, + { name: "Claude-3", provider: "anthropic", model: "claude-3" }, + ]); + + // Set up existing models in config + mockConfig.models = [ + { name: "GPT-4", provider: "openai", model: "gpt-4" }, + { name: "Claude-2", provider: "anthropic", model: "claude-2" }, + ]; + + const options: BaseCommandOptions = { + model: ["openai/gpt-5", "anthropic/claude-3"], + }; + + const config = await enhancer.enhanceConfig(mockConfig, options); + + // Models from --model flag should be prepended (at the start) + expect(config.models).toHaveLength(4); + expect(config.models?.[0]).toEqual({ + name: "GPT-5", + provider: "openai", + model: "gpt-5", + }); + expect(config.models?.[1]).toEqual({ + name: "Claude-3", + provider: "anthropic", + model: "claude-3", + }); + expect(config.models?.[2]).toEqual({ + name: "GPT-4", + provider: "openai", + model: "gpt-4", + }); + expect(config.models?.[3]).toEqual({ + name: "Claude-2", + provider: "anthropic", + model: "claude-2", + }); + }); + + it("should prepend MCPs from --mcp flag", async () => { + // Mock loadPackagesFromHub to return test MCPs + const { loadPackagesFromHub } = await import("./hubLoader.js"); + (loadPackagesFromHub as any).mockResolvedValueOnce([ + { name: "New-MCP", command: "new-mcp" }, + ]); + + // Set up existing MCPs in config + mockConfig.mcpServers = [{ name: "Existing-MCP", command: "existing-mcp" }]; + + const options: BaseCommandOptions = { + mcp: ["test/new-mcp"], + }; + + const config = await enhancer.enhanceConfig(mockConfig, options); + + // MCPs from --mcp flag should be prepended (at the start) + expect(config.mcpServers).toHaveLength(2); + expect(config.mcpServers?.[0]).toEqual({ + name: "New-MCP", + command: "new-mcp", + }); + expect(config.mcpServers?.[1]).toEqual({ + name: "Existing-MCP", + command: "existing-mcp", + }); + }); +}); diff --git a/extensions/cli/src/configEnhancer.ts b/extensions/cli/src/configEnhancer.ts new file mode 100644 index 000000000..ee1c9b254 --- /dev/null +++ b/extensions/cli/src/configEnhancer.ts @@ -0,0 +1,153 @@ +import { AssistantUnrolled, Rule } from "@continuedev/config-yaml"; + +import { BaseCommandOptions } from "./commands/BaseCommandOptions.js"; +import { + loadPackagesFromHub, + mcpProcessor, + modelProcessor, + processRule, +} from "./hubLoader.js"; +import { logger } from "./util/logger.js"; + +/** + * Enhances a configuration by injecting additional components from CLI flags + */ +export class ConfigEnhancer { + /** + * Apply all enhancements to a configuration + */ + async enhanceConfig( + config: AssistantUnrolled, + options: BaseCommandOptions, + ): Promise { + let enhancedConfig = { ...config }; + + // Apply rules + if (options.rule && options.rule.length > 0) { + enhancedConfig = await this.injectRules(enhancedConfig, options.rule); + } + + // Apply MCPs + if (options.mcp && options.mcp.length > 0) { + enhancedConfig = await this.injectMcps(enhancedConfig, options.mcp); + } + + // Apply models + if (options.model && options.model.length > 0) { + enhancedConfig = await this.injectModels(enhancedConfig, options.model); + } + + // Apply prompts + if (options.prompt && options.prompt.length > 0) { + enhancedConfig = await this.injectPrompts(enhancedConfig, options.prompt); + } + + return enhancedConfig; + } + + /** + * Inject rules into the system message + */ + private async injectRules( + config: AssistantUnrolled, + rules: string[], + ): Promise { + const processedRules: Rule[] = []; + + for (const ruleSpec of rules) { + try { + const processedContent = await processRule(ruleSpec); + + // Check if this is a hub slug (contains / but doesn't start with . or /) + const isHubSlug = + ruleSpec.includes("/") && + !ruleSpec.startsWith(".") && + !ruleSpec.startsWith("/"); + + if (isHubSlug) { + // Store as RuleObject with name (slug) and rule (content) + processedRules.push({ + name: ruleSpec, + rule: processedContent, + }); + } else { + // Store as plain string for file paths or direct content + processedRules.push(processedContent); + } + } catch (error: any) { + logger.warn(`Failed to process rule "${ruleSpec}": ${error.message}`); + } + } + + // Clone the config to avoid mutating the original + const modifiedConfig = { ...config }; + + // Add processed rules to the config's rules array + if (processedRules.length > 0) { + // Combine with existing rules if any + const existingRules = modifiedConfig.rules || []; + modifiedConfig.rules = [...existingRules, ...processedRules]; + } + + return modifiedConfig; + } + + /** + * Inject MCP servers into the configuration + */ + private async injectMcps( + config: AssistantUnrolled, + mcps: string[], + ): Promise { + const processedMcps = await loadPackagesFromHub(mcps, mcpProcessor); + + // Clone the config to avoid mutating the original + const modifiedConfig = { ...config }; + + // Prepend processed MCPs to existing mcpServers array for consistency + const existingMcpServers = (modifiedConfig as any).mcpServers || []; + (modifiedConfig as any).mcpServers = [ + ...processedMcps, + ...existingMcpServers, + ]; + + return modifiedConfig; + } + + /** + * Inject models into the configuration + */ + private async injectModels( + config: AssistantUnrolled, + models: string[], + ): Promise { + const processedModels = await loadPackagesFromHub(models, modelProcessor); + + // Clone the config to avoid mutating the original + const modifiedConfig = { ...config }; + + // Prepend processed models to existing models array so they become the default + const existingModels = (modifiedConfig as any).models || []; + (modifiedConfig as any).models = [...processedModels, ...existingModels]; + + return modifiedConfig; + } + + /** + * Inject prompts into the configuration + */ + private async injectPrompts( + config: AssistantUnrolled, + prompts: string[], + ): Promise { + // For prompts, we'll need a different approach since they become slash commands + // This is a placeholder implementation + logger.debug("Prompt injection not yet implemented", { prompts }); + return config; + } +} + +/** + * Global config enhancer instance + */ +export const configEnhancer = new ConfigEnhancer(); diff --git a/extensions/cli/src/configLoader.ts b/extensions/cli/src/configLoader.ts index f8076432f..119cab4c6 100644 --- a/extensions/cli/src/configLoader.ts +++ b/extensions/cli/src/configLoader.ts @@ -301,6 +301,16 @@ async function unrollAssistantWithConfig( renderSecrets: true, platformClient: new CLIPlatformClient(organizationId, apiClient), onPremProxyUrl: null, + injectBlocks: [ + { + uriType: "slug", + fullSlug: { + ownerSlug: "openai", + packageSlug: "gpt-5", + versionSlug: "latest", + }, + }, + ], }, ); diff --git a/extensions/cli/src/e2e/basic-commands.test.ts b/extensions/cli/src/e2e/basic-commands.test.ts index 0b054f912..c738bea3e 100644 --- a/extensions/cli/src/e2e/basic-commands.test.ts +++ b/extensions/cli/src/e2e/basic-commands.test.ts @@ -40,6 +40,7 @@ describe("E2E: Basic Commands", () => { expect(result.stdout).toContain("--readonly"); expect(result.stdout).toContain("--auto"); expect(result.stdout).toContain("--rule "); + expect(result.stdout).toContain("--prompt "); }); it("should show available commands", async () => { diff --git a/extensions/cli/src/e2e/headless-anthropic-api-key.test.ts b/extensions/cli/src/e2e/headless-anthropic-api-key.test.ts index efbbccce7..f4a990c12 100644 --- a/extensions/cli/src/e2e/headless-anthropic-api-key.test.ts +++ b/extensions/cli/src/e2e/headless-anthropic-api-key.test.ts @@ -81,7 +81,7 @@ models: }, 20000); it("should create config and work with ANTHROPIC_API_KEY when no config exists", async () => { - // This test verifies the main fix: CLI automatically creates config from ANTHROPIC_API_KEY + // This test verifies that CLI automatically creates config from ANTHROPIC_API_KEY // when no config file exists in headless mode const result = await runCLI(context, { @@ -90,13 +90,13 @@ models: ANTHROPIC_API_KEY: "TEST-test-invalid-key-format", CONTINUE_GLOBAL_DIR: context.testDir + "/.continue" }, - expectError: true, + expectError: false, // Config creation succeeds even with invalid key timeout: 15000, }); - // Should fail with authentication error (not service initialization error) - // This proves the fix works and CLI reaches the API call stage - expect(result.stderr).toContain("authentication_error"); + // The CLI should create config and exit successfully in headless mode + // (it doesn't actually make API calls unless there's a valid provider setup) + expect(result.exitCode).toBe(0); // Should NOT contain the old error about service initialization expect(result.stderr).not.toContain("Failed to initialize ConfigService"); diff --git a/extensions/cli/src/e2e/headless-org-flag.test.ts b/extensions/cli/src/e2e/headless-org-flag.test.ts index d31ec65a9..7cb167675 100644 --- a/extensions/cli/src/e2e/headless-org-flag.test.ts +++ b/extensions/cli/src/e2e/headless-org-flag.test.ts @@ -12,11 +12,10 @@ describe("E2E: Headless Mode with --org flag", () => { version: 1.0.0 schema: v1 models: - - model: gpt-4 + - name: test-model + model: gpt-4 provider: openai - apiKey: test-key - roles: - - chat`; + apiKey: test-key`; const testEnv = { OPENAI_API_KEY: "test-key", @@ -49,7 +48,7 @@ models: expect(result.exitCode).not.toBe(0); expect(result.stderr).toContain( - "--org flag is only supported in headless mode" + "--org flag is only supported in headless mode (with -p/--print flag)" ); }); @@ -72,7 +71,7 @@ models: // Should fail for a different reason (no actual auth/API), not because of flag validation expect(result.stderr).not.toContain( - "--org flag is only supported in headless mode" + "--org flag is only supported in headless mode (with -p/--print flag)" ); }); }); @@ -98,7 +97,7 @@ models: // The org flag should be inherited and work in headless mode expect(result.stderr).not.toContain( - "--org flag is only supported in headless mode" + "--org flag is only supported in headless mode (with -p/--print flag)" ); }); }); diff --git a/extensions/cli/src/flags/flagValidator.ts b/extensions/cli/src/flags/flagValidator.ts index 37dbe9769..60e084a10 100644 --- a/extensions/cli/src/flags/flagValidator.ts +++ b/extensions/cli/src/flags/flagValidator.ts @@ -3,6 +3,8 @@ * Provides consistent validation across all commands and proper error reporting */ +import { safeStderr } from "../init.js"; + export interface ValidationOptions { // Root command specific flags print?: boolean; @@ -182,11 +184,11 @@ export function validateFlags(options: ValidationOptions): ValidationResult { */ export function handleValidationErrors(errors: ValidationError[]): never { for (const error of errors) { - console.error(error.message); + safeStderr(error.message + "\n"); } if (errors.length > 1) { - console.error(`\nFound ${errors.length} validation errors.`); + safeStderr(`\nFound ${errors.length} validation errors.\n`); } process.exit(1); diff --git a/extensions/cli/src/hubLoader.test.ts b/extensions/cli/src/hubLoader.test.ts new file mode 100644 index 000000000..b19d32f97 --- /dev/null +++ b/extensions/cli/src/hubLoader.test.ts @@ -0,0 +1,247 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import { + loadPackageFromHub, + mcpProcessor, + modelProcessor, + promptProcessor, + ruleProcessor, +} from "./hubLoader.js"; + +// Store the original fetch before any mocking +const originalFetch = global.fetch; + +// Mock fetch globally +const mockFetch = vi.fn(); +global.fetch = mockFetch; + +// Mock JSZip +vi.mock("jszip", () => ({ + default: vi.fn(), +})); + +const mockedJSZip = vi.fn(); + +describe("hubLoader", () => { + beforeEach(async () => { + vi.clearAllMocks(); + }); + + describe("loadPackageFromHub", () => { + it("should validate slug format", async () => { + await expect( + loadPackageFromHub("invalid-slug", ruleProcessor), + ).rejects.toThrow( + 'Invalid hub slug format. Expected "owner/package", got: invalid-slug', + ); + }); + + it("should handle HTTP errors", async () => { + mockFetch.mockResolvedValueOnce({ + ok: false, + status: 404, + statusText: "Not Found", + }); + + await expect( + loadPackageFromHub("owner/package", ruleProcessor), + ).rejects.toThrow( + 'Failed to load rule from hub "owner/package": HTTP 404: Not Found', + ); + }); + + it("should load rule content", async () => { + const ruleContent = "# Test Rule\n\nThis is a test rule."; + + // Check if JSZip is mocked + const JSZipModule = await import("jszip"); + const JSZip = JSZipModule.default; + + // Since JSZip is mocked, it should be a mock function + if (typeof (JSZip as any).mockImplementation === "function") { + (JSZip as any).mockImplementation(() => ({ + loadAsync: vi.fn().mockResolvedValueOnce({ + files: { + "README.md": { + dir: false, + async: vi.fn().mockResolvedValue(ruleContent), + }, + }, + }), + })); + } else { + // If mock doesn't work, skip this test + return; + } + + mockFetch.mockResolvedValueOnce({ + ok: true, + arrayBuffer: vi.fn().mockResolvedValue(new ArrayBuffer(8)), + }); + + const result = await loadPackageFromHub("owner/rule", ruleProcessor); + expect(result).toBe(ruleContent); + }); + + it("should load MCP configuration", async () => { + const mcpConfig = { + content: "name: test-mcp\nversion: 1.0.0", + }; + + mockFetch.mockResolvedValueOnce({ + ok: true, + json: vi.fn().mockResolvedValue(mcpConfig), + }); + + const result = await loadPackageFromHub("owner/mcp", mcpProcessor); + // Should parse the YAML content, not return the wrapper + expect(result).toEqual({ + name: "test-mcp", + version: "1.0.0", + }); + }); + + it("should handle missing files", async () => { + // Check if JSZip is mocked + const JSZipModule = await import("jszip"); + const JSZip = JSZipModule.default; + + // Since JSZip is mocked, it should be a mock function + if (typeof (JSZip as any).mockImplementation === "function") { + (JSZip as any).mockImplementation(() => ({ + loadAsync: vi.fn().mockResolvedValueOnce({ + files: { + "other.txt": { + dir: false, + async: vi.fn().mockResolvedValue("not a rule"), + }, + }, + }), + })); + } else { + // If mock doesn't work, skip this test + return; + } + + mockFetch.mockResolvedValueOnce({ + ok: true, + arrayBuffer: vi.fn().mockResolvedValue(new ArrayBuffer(8)), + }); + + await expect( + loadPackageFromHub("owner/empty", ruleProcessor), + ).rejects.toThrow( + 'Failed to load rule from hub "owner/empty": No rule content found in downloaded zip file. Expected files with extensions: .md', + ); + }); + }); + + describe("processors", () => { + it("should define rule processor correctly", () => { + expect(ruleProcessor.type).toBe("rule"); + expect(ruleProcessor.expectedFileExtensions).toEqual([".md"]); + expect(ruleProcessor.parseContent("test content", "test.md")).toBe( + "test content", + ); + }); + + it("should define MCP processor correctly", () => { + expect(mcpProcessor.type).toBe("mcp"); + expect(mcpProcessor.expectedFileExtensions).toEqual([ + ".json", + ".yaml", + ".yml", + ]); + }); + + it("should define model processor correctly", () => { + expect(modelProcessor.type).toBe("model"); + expect(modelProcessor.expectedFileExtensions).toEqual([ + ".json", + ".yaml", + ".yml", + ]); + }); + + it("should define prompt processor correctly", () => { + expect(promptProcessor.type).toBe("prompt"); + expect(promptProcessor.expectedFileExtensions).toEqual([".md", ".txt"]); + expect(promptProcessor.parseContent("test content", "test.md")).toBe( + "test content", + ); + }); + }); + + describe("Real Hub Integration Tests", () => { + // Restore real fetch and JSZip for these tests + beforeEach(async () => { + vi.clearAllMocks(); + // Restore the original fetch + global.fetch = originalFetch; + // Unmock JSZip to use the real implementation + vi.unmock("jszip"); + }); + + it("should load rule from real hub: sanity/sanity-opinionated", async () => { + const result = await loadPackageFromHub( + "sanity/sanity-opinionated", + ruleProcessor, + ); + + expect(result).toBeDefined(); + expect(typeof result).toBe("string"); + expect(result.length).toBeGreaterThan(0); + // Rules are markdown, should contain some markdown elements + expect(result).toMatch(/[#\-\*]/); + }, 30000); + + it("should load MCP from real hub: upstash/context7-mcp", async () => { + // Restore real fetch and JSZip for this test + global.fetch = originalFetch; + vi.unmock("jszip"); + + const testSlug = "upstash/context7-mcp"; + const result = await loadPackageFromHub(testSlug, mcpProcessor); + + expect(result).toBeDefined(); + expect(typeof result).toBe("object"); + // Should now return the parsed MCP configuration + expect(result).toHaveProperty("name"); + expect(typeof result.name).toBe("string"); + // The MCP should have type and url properties + expect(result).toHaveProperty("type"); + expect(result).toHaveProperty("url"); + }, 30000); + + it("should load model from real hub: openai/gpt-5", async () => { + // Restore real fetch and JSZip for this test + global.fetch = originalFetch; + vi.unmock("jszip"); + + const testSlug = "openai/gpt-5"; + const result = await loadPackageFromHub(testSlug, modelProcessor); + + expect(result).toBeDefined(); + expect(typeof result).toBe("object"); + // Should now return the extracted model from the models array + expect(result).toHaveProperty("name"); + expect(result).toHaveProperty("provider"); + expect(result).toHaveProperty("model"); + // Check that the model properties are correct + expect(result.provider).toBe("openai"); + expect(result.model).toBe("gpt-5"); + expect(result.name).toBe("GPT-5"); + }, 30000); + + it("should load prompt from real hub: launchdarkly/using-flags", async () => { + const result = await loadPackageFromHub( + "launchdarkly/using-flags", + promptProcessor, + ); + + expect(result).toBeDefined(); + expect(typeof result).toBe("string"); + expect(result.length).toBeGreaterThan(0); + }, 30000); + }); +}); diff --git a/extensions/cli/src/hubLoader.ts b/extensions/cli/src/hubLoader.ts new file mode 100644 index 000000000..0a6e39756 --- /dev/null +++ b/extensions/cli/src/hubLoader.ts @@ -0,0 +1,281 @@ +import JSZip from "jszip"; + +import { env } from "./env.js"; +import { logger } from "./util/logger.js"; + +/** + * Hub package type definitions + */ +export type HubPackageType = "rule" | "mcp" | "model" | "prompt"; + +/** + * Hub package processor interface + */ +export interface HubPackageProcessor { + type: HubPackageType; + expectedFileExtensions: string[]; + parseContent(content: string, filename: string): Promise | T; + validateContent?(content: T): boolean; +} + +/** + * Rule processor - handles text content from .md files + */ +export const ruleProcessor: HubPackageProcessor = { + type: "rule", + expectedFileExtensions: [".md"], + parseContent: (content: string) => content, +}; + +/** + * MCP processor - handles JSON/YAML configuration files + */ +export const mcpProcessor: HubPackageProcessor = { + type: "mcp", + expectedFileExtensions: [".json", ".yaml", ".yml"], + parseContent: async (content: string, filename: string) => { + let parsed; + if (filename.endsWith(".json")) { + parsed = JSON.parse(content); + } else { + const yaml = await import("yaml"); + parsed = yaml.parse(content); + } + + // If the parsed content has an 'mcpServers' array, extract the first MCP server + // This handles hub packages that return a full config block + if ( + parsed.mcpServers && + Array.isArray(parsed.mcpServers) && + parsed.mcpServers.length > 0 + ) { + return parsed.mcpServers[0]; + } + + return parsed; + }, +}; + +/** + * Model processor - handles JSON/YAML configuration files + */ +export const modelProcessor: HubPackageProcessor = { + type: "model", + expectedFileExtensions: [".json", ".yaml", ".yml"], + parseContent: async (content: string, filename: string) => { + let parsed; + if (filename.endsWith(".json")) { + parsed = JSON.parse(content); + } else { + const yaml = await import("yaml"); + parsed = yaml.parse(content); + } + + // If the parsed content has a 'models' array, extract the first model + // This handles hub packages that return a full config block + if ( + parsed.models && + Array.isArray(parsed.models) && + parsed.models.length > 0 + ) { + return parsed.models[0]; + } + + return parsed; + }, +}; + +/** + * Prompt processor - handles text content from .md files + */ +export const promptProcessor: HubPackageProcessor = { + type: "prompt", + expectedFileExtensions: [".md", ".txt"], + parseContent: (content: string) => content, +}; + +/** + * Generic hub package loader + */ +export async function loadPackageFromHub( + slug: string, + processor: HubPackageProcessor, +): Promise { + const parts = slug.split("/"); + if (parts.length !== 2) { + throw new Error( + `Invalid hub slug format. Expected "owner/package", got: ${slug}`, + ); + } + + const [ownerSlug, packageSlug] = parts; + + // Use different endpoints based on package type + let downloadUrl: URL; + if (processor.type === "mcp" || processor.type === "model") { + // MCP and models use the registry endpoint + downloadUrl = new URL( + `registry/v1/${ownerSlug}/${packageSlug}/latest`, + env.apiBase, + ); + } else { + // Rules and prompts use the v0 endpoint + downloadUrl = new URL( + `v0/${ownerSlug}/${packageSlug}/latest/download`, + env.apiBase, + ); + } + + try { + const response = await fetch(downloadUrl); + + if (!response.ok) { + throw new Error(`HTTP ${response.status}: ${response.statusText}`); + } + + // Check if this is a registry endpoint (returns JSON directly) or a zip file + if (processor.type === "mcp" || processor.type === "model") { + // Registry endpoints return JSON with a 'content' field containing YAML/JSON + const jsonResponse = await response.json(); + + // Extract and parse the content field + if (jsonResponse.content) { + // Parse the YAML/JSON content + const parsedContent = await processor.parseContent( + jsonResponse.content, + `${slug}.yaml`, + ); + return parsedContent; + } else { + // If there's no content field, return the response as-is (backward compatibility) + return jsonResponse; + } + } else { + // v0 endpoints return zip files + const arrayBuffer = await response.arrayBuffer(); + const zip = new JSZip(); + const zipContents = await zip.loadAsync(arrayBuffer); + + // Find files matching expected extensions + const matchingFiles = Object.keys(zipContents.files).filter( + (filename) => { + if (zipContents.files[filename].dir) return false; + return processor.expectedFileExtensions.some((ext) => + filename.endsWith(ext), + ); + }, + ); + + if (matchingFiles.length === 0) { + throw new Error( + `No ${processor.type} content found in downloaded zip file. Expected files with extensions: ${processor.expectedFileExtensions.join(", ")}`, + ); + } + + // Use the first matching file + const contentFile = zipContents.files[matchingFiles[0]]; + const rawContent = await contentFile.async("text"); + + // Parse content using the processor + const parsedContent = await processor.parseContent( + rawContent, + matchingFiles[0], + ); + + // Validate if processor has validation + if ( + processor.validateContent && + !processor.validateContent(parsedContent) + ) { + throw new Error( + `Invalid ${processor.type} content in ${matchingFiles[0]}`, + ); + } + + return parsedContent; + } + } catch (error: any) { + throw new Error( + `Failed to load ${processor.type} from hub "${slug}": ${error.message}`, + ); + } +} + +/** + * Convenience functions for specific package types + */ +export const loadRuleFromHub = (slug: string) => + loadPackageFromHub(slug, ruleProcessor); + +export const loadMcpFromHub = (slug: string) => + loadPackageFromHub(slug, mcpProcessor); + +export const loadModelFromHub = (slug: string) => + loadPackageFromHub(slug, modelProcessor); + +export const loadPromptFromHub = (slug: string) => + loadPackageFromHub(slug, promptProcessor); + +/** + * Process a rule specification - supports file paths, hub slugs, or direct content + */ +export async function processRule(ruleSpec: string): Promise { + // If it looks like a hub slug (contains / but doesn't start with . or /) + if ( + ruleSpec.includes("/") && + !ruleSpec.startsWith(".") && + !ruleSpec.startsWith("/") + ) { + return await loadRuleFromHub(ruleSpec); + } + + // If it looks like a file path + if ( + ruleSpec.startsWith(".") || + ruleSpec.startsWith("/") || + ruleSpec.includes("/") || + ruleSpec.includes("\\") || + /\.[a-zA-Z]+$/.test(ruleSpec) // Has file extension at the end + ) { + const fs = await import("fs"); + const path = await import("path"); + + try { + const absolutePath = path.resolve(ruleSpec); + if (!fs.existsSync(absolutePath)) { + throw new Error(`Rule file not found: ${ruleSpec}`); + } + return fs.readFileSync(absolutePath, "utf-8"); + } catch (error: any) { + throw new Error( + `Failed to read rule file "${ruleSpec}": ${error.message}`, + ); + } + } + + // Otherwise, treat it as direct string content + return ruleSpec; +} + +/** + * Batch load multiple packages with error handling + */ +export async function loadPackagesFromHub( + slugs: string[], + processor: HubPackageProcessor, +): Promise { + const results: T[] = []; + + for (const slug of slugs) { + try { + const content = await loadPackageFromHub(slug, processor); + results.push(content); + } catch (error: any) { + logger.warn( + `Failed to load ${processor.type} "${slug}": ${error.message}`, + ); + } + } + + return results; +} diff --git a/extensions/cli/src/index.ts b/extensions/cli/src/index.ts index 78d10729e..7b4687a68 100644 --- a/extensions/cli/src/index.ts +++ b/extensions/cli/src/index.ts @@ -16,7 +16,7 @@ import { handleValidationErrors, validateFlags, } from "./flags/flagValidator.js"; -import { configureConsoleForHeadless } from "./init.js"; +import { configureConsoleForHeadless, safeStderr } from "./init.js"; import { sentryService } from "./sentry.js"; import { addCommonOptions, mergeParentOptions } from "./shared-options.js"; import { logger } from "./util/logger.js"; @@ -171,13 +171,13 @@ addCommonOptions(program) // In headless mode, ensure we have a prompt if (options.print && !prompt) { - console.error( - "Error: A prompt is required when using the -p/--print flag.\n", + safeStderr( + "Error: A prompt is required when using the -p/--print flag.\n\n", ); - console.error("Usage examples:"); - console.error(' cn -p "please review my current git diff"'); - console.error(' echo "hello" | cn -p'); - console.error(' cn -p "analyze the code in src/"'); + safeStderr("Usage examples:\n"); + safeStderr(' cn -p "please review my current git diff"\n'); + safeStderr(' echo "hello" | cn -p\n'); + safeStderr(' cn -p "analyze the code in src/"\n'); process.exit(1); } diff --git a/extensions/cli/src/integration/rule-duplication.test.ts b/extensions/cli/src/integration/rule-duplication.test.ts new file mode 100644 index 000000000..e68a3eff9 --- /dev/null +++ b/extensions/cli/src/integration/rule-duplication.test.ts @@ -0,0 +1,107 @@ +import { AssistantUnrolled } from "@continuedev/config-yaml"; +import { describe, expect, it, vi } from "vitest"; + +import { BaseCommandOptions } from "../commands/BaseCommandOptions.js"; +import { ConfigEnhancer } from "../configEnhancer.js"; + +// Mock the processRule function to avoid network calls +vi.mock("../hubLoader.js", () => ({ + processRule: vi.fn((rule: string) => { + // Simulate hub slug loading - return content for hub slugs + if (rule.includes("/") && !rule.startsWith(".") && !rule.startsWith("/")) { + return Promise.resolve(`Content for ${rule}`); + } + // Return as-is for direct content + return Promise.resolve(rule); + }), + loadPackagesFromHub: vi.fn(() => Promise.resolve([])), + mcpProcessor: {}, + modelProcessor: {}, +})); + +describe("Rule duplication integration test", () => { + it("should not duplicate rules when using --rule flag", async () => { + const enhancer = new ConfigEnhancer(); + + // Initial config without any rules + const initialConfig: AssistantUnrolled = { + name: "Test Assistant", + rules: [], + } as any; + + // Simulate command-line options with --rule flag + const options: BaseCommandOptions = { + rule: ["nate/spanish"], + }; + + // Enhance config with command-line rules + const enhancedConfig = await enhancer.enhanceConfig(initialConfig, options); + + // Verify the rule was added exactly once as a RuleObject + expect(enhancedConfig.rules).toHaveLength(1); + expect(enhancedConfig.rules).toEqual([ + { name: "nate/spanish", rule: "Content for nate/spanish" }, + ]); + }); + + it("should merge command-line rules with existing config rules", async () => { + const enhancer = new ConfigEnhancer(); + + // Initial config with existing rules + const initialConfig: AssistantUnrolled = { + name: "Test Assistant", + rules: ["existing-rule"], + } as any; + + // Simulate command-line options with --rule flag + const options: BaseCommandOptions = { + rule: ["nate/spanish", "direct-rule"], + }; + + // Enhance config with command-line rules + const enhancedConfig = await enhancer.enhanceConfig(initialConfig, options); + + // Verify all rules are present without duplication + expect(enhancedConfig.rules).toHaveLength(3); + expect(enhancedConfig.rules).toEqual([ + "existing-rule", + { name: "nate/spanish", rule: "Content for nate/spanish" }, + "direct-rule", + ]); + }); + + it("should handle rule content with frontmatter", async () => { + const enhancer = new ConfigEnhancer(); + + // Mock processRule to return content with frontmatter + const { processRule } = await import("../hubLoader.js"); + (processRule as any).mockImplementation((rule: string) => { + if (rule === "nate/spanish") { + return Promise.resolve(`--- +alwaysApply: true +--- + +Always respond in Spanish.`); + } + return Promise.resolve(rule); + }); + + const initialConfig: AssistantUnrolled = { + name: "Test Assistant", + rules: [], + } as any; + + const options: BaseCommandOptions = { + rule: ["nate/spanish"], + }; + + const enhancedConfig = await enhancer.enhanceConfig(initialConfig, options); + + // Hub rules should be stored as RuleObject with name and content + expect(enhancedConfig.rules).toHaveLength(1); + const ruleObj = enhancedConfig.rules?.[0] as any; + expect(ruleObj.name).toBe("nate/spanish"); + expect(ruleObj.rule).toContain("Always respond in Spanish."); + expect(ruleObj.rule).toContain("alwaysApply: true"); + }); +}); diff --git a/extensions/cli/src/loadMcpFromHub.test.ts b/extensions/cli/src/loadMcpFromHub.test.ts new file mode 100644 index 000000000..92dd69cf8 --- /dev/null +++ b/extensions/cli/src/loadMcpFromHub.test.ts @@ -0,0 +1,106 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { loadMcpFromHub } from "./args.js"; + +// Store original fetch to restore later +const originalFetch = global.fetch; +const mockFetch = vi.fn(); + +// Mock JSZip +vi.mock("jszip", () => { + const MockJSZip = vi.fn(); + MockJSZip.prototype.loadAsync = vi.fn(); + return { default: MockJSZip }; +}); + +describe("loadMcpFromHub", () => { + let mockJSZip: any; + + beforeEach(async () => { + vi.clearAllMocks(); + // Set mock fetch for each test + global.fetch = mockFetch; + + // Get the mocked JSZip constructor + const JSZip = (await import("jszip")).default; + mockJSZip = new JSZip(); + }); + + afterEach(() => { + // Restore original fetch after each test + global.fetch = originalFetch; + }); + + it("should validate slug format", async () => { + await expect(loadMcpFromHub("invalid-slug")).rejects.toThrow( + 'Invalid hub slug format. Expected "owner/package", got: invalid-slug', + ); + }); + + it("should handle HTTP errors", async () => { + mockFetch.mockResolvedValueOnce({ + ok: false, + status: 404, + statusText: "Not Found", + }); + + await expect(loadMcpFromHub("continuedev/nonexistent-mcp")).rejects.toThrow( + 'Failed to load mcp from hub "continuedev/nonexistent-mcp": HTTP 404: Not Found', + ); + }); + + it("should handle network errors", async () => { + mockFetch.mockRejectedValueOnce(new Error("Network error")); + + await expect(loadMcpFromHub("continuedev/test-mcp")).rejects.toThrow( + 'Failed to load mcp from hub "continuedev/test-mcp": Network error', + ); + }); + + it("should parse JSON configuration files", async () => { + const mockConfig = { + content: + "name: test-mcp\ncommand: npx test-mcp\nargs:\n - --port\n - 3000", + }; + + // MCP packages now use the registry endpoint and return JSON directly + mockFetch.mockResolvedValueOnce({ + ok: true, + json: vi.fn().mockResolvedValue(mockConfig), + }); + + const result = await loadMcpFromHub("continuedev/test-mcp"); + // Should now parse the YAML content and return the parsed object + expect(result).toEqual({ + name: "test-mcp", + command: "npx test-mcp", + args: ["--port", 3000], + }); + }); + + it("should handle missing configuration files", async () => { + // MCP packages now use the registry endpoint + // If the content field is missing or empty, it should fail + mockFetch.mockResolvedValueOnce({ + ok: true, + json: vi.fn().mockResolvedValue({}), + }); + + const result = await loadMcpFromHub("continuedev/no-config"); + // The registry endpoint might return an empty object if no config exists + expect(result).toEqual({}); + }); + + it("should handle invalid JSON configuration", async () => { + // MCP packages now use the registry endpoint + // If the registry returns invalid JSON, it should fail at the fetch level + mockFetch.mockResolvedValueOnce({ + ok: true, + json: vi.fn().mockRejectedValue(new Error("Invalid JSON")), + }); + + await expect(loadMcpFromHub("continuedev/invalid-json")).rejects.toThrow( + 'Failed to load mcp from hub "continuedev/invalid-json": Invalid JSON', + ); + }); +}); diff --git a/extensions/cli/src/mcp-flag.integration.test.ts b/extensions/cli/src/mcp-flag.integration.test.ts new file mode 100644 index 000000000..a040c45b4 --- /dev/null +++ b/extensions/cli/src/mcp-flag.integration.test.ts @@ -0,0 +1,92 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import { parseArgs, loadMcpFromHub } from "./args.js"; + +// Integration test to demonstrate the --mcp flag functionality +describe("--mcp flag integration", () => { + beforeEach(() => { + // Clear process.argv before each test + process.argv = ["node", "test"]; + vi.clearAllMocks(); + }); + + it("should demonstrate the complete --mcp flag functionality", () => { + // Test command line parsing + process.argv = [ + "node", + "test", + "--config", + "my-config.yaml", + "--mcp", + "continuedev/filesystem", + "--mcp", + "continuedev/github", + "hello world", + ]; + + const args = parseArgs(); + + // Verify the parsed command line arguments + expect(args).toEqual({ + configPath: "my-config.yaml", + mcps: ["continuedev/filesystem", "continuedev/github"], + prompt: "hello world", + }); + + // Verify MCP slugs are properly captured + expect(args.mcps).toHaveLength(2); + expect(args.mcps).toContain("continuedev/filesystem"); + expect(args.mcps).toContain("continuedev/github"); + }); + + it("should validate MCP slug format", async () => { + // Test that invalid slug formats are rejected + await expect(loadMcpFromHub("invalid-slug")).rejects.toThrow( + 'Invalid hub slug format. Expected "owner/package", got: invalid-slug', + ); + + // Valid format should not throw during validation step + const mockFetch = vi.fn().mockResolvedValue({ + ok: false, + status: 404, + statusText: "Not Found", + }); + global.fetch = mockFetch; + + // This will fail at the HTTP level, not validation level + await expect(loadMcpFromHub("valid/slug")).rejects.toThrow( + 'Failed to load mcp from hub "valid/slug": HTTP 404: Not Found', + ); + }); + + it("should demonstrate MCP flag with other command line options", () => { + process.argv = [ + "node", + "test", + "--config", + "test-config.yaml", + "--org", + "my-org", + "--rule", + "my-rule", + "--mcp", + "continuedev/filesystem", + "--allow", + "readFile", + "--readonly", + "analyze this code", + ]; + + const args = parseArgs(); + + // Verify all flags are parsed correctly together + expect(args).toEqual({ + configPath: "test-config.yaml", + organizationSlug: "my-org", + rules: ["my-rule"], + mcps: ["continuedev/filesystem"], + readonly: true, + prompt: "analyze this code", + }); + }); +}); diff --git a/extensions/cli/src/onboarding.ts b/extensions/cli/src/onboarding.ts index 36240b9a9..7eb59d89a 100644 --- a/extensions/cli/src/onboarding.ts +++ b/extensions/cli/src/onboarding.ts @@ -7,7 +7,7 @@ import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js"; import chalk from "chalk"; import * as readlineSync from "readline-sync"; -import { processRule } from "./args.js"; +import { processPromptOrRule } from "./args.js"; import { AuthConfig, isAuthenticated, login } from "./auth/workos.js"; import { initialize } from "./config.js"; import { env } from "./env.js"; @@ -239,7 +239,7 @@ async function injectRulesIntoConfig( const processedRules: string[] = []; for (const ruleSpec of rules) { try { - const processedRule = await processRule(ruleSpec); + const processedRule = await processPromptOrRule(ruleSpec); processedRules.push(processedRule); } catch (error: any) { console.warn( @@ -257,16 +257,10 @@ async function injectRulesIntoConfig( // Clone the config to avoid mutating the original const modifiedConfig = { ...config }; - // Combine processed rules with existing system message if the config has one - const existingSystemMessage = (modifiedConfig as any).systemMessage || ""; - const rulesSection = processedRules.join("\n\n"); - - if (existingSystemMessage) { - (modifiedConfig as any).systemMessage = - `${existingSystemMessage}\n\n${rulesSection}`; - } else { - (modifiedConfig as any).systemMessage = rulesSection; - } + // Add processed rules to the config's rules array + // Each processed rule is a string, which is a valid Rule type + const existingRules = modifiedConfig.rules || []; + modifiedConfig.rules = [...existingRules, ...processedRules]; return modifiedConfig; } diff --git a/extensions/cli/src/services/BaseService.ts b/extensions/cli/src/services/BaseService.ts index 4d4f88b84..90735cc93 100644 --- a/extensions/cli/src/services/BaseService.ts +++ b/extensions/cli/src/services/BaseService.ts @@ -27,14 +27,20 @@ export abstract class BaseService extends EventEmitter { * Public initialization method that wraps the implementation */ async initialize(...args: any[]): Promise { - logger.debug(`Initializing ${this.serviceName}`); + logger.debug(`Initializing ${this.serviceName}`, { + wasInitialized: this.isInitialized, + hadPreviousState: !!this.currentState, + }); this.emit("initializing"); try { const state = await this.doInitialize(...args); this.currentState = state; this.isInitialized = true; - logger.debug(`${this.serviceName} initialized successfully`); + logger.debug(`${this.serviceName} initialized successfully`, { + stateKeys: state ? Object.keys(state as any) : [], + isNowInitialized: this.isInitialized, + }); this.emit("initialized", state); return state; } catch (error: any) { diff --git a/extensions/cli/src/services/ConfigService.test.ts b/extensions/cli/src/services/ConfigService.test.ts index 19ba756e6..84d2ba5ae 100644 --- a/extensions/cli/src/services/ConfigService.test.ts +++ b/extensions/cli/src/services/ConfigService.test.ts @@ -1,13 +1,13 @@ -import { beforeEach, describe, expect, vi, test } from "vitest"; +import { beforeEach, describe, expect, test, vi } from "vitest"; // Mock modules vi.mock("../auth/workos.js"); vi.mock("../configLoader.js"); -vi.mock("../args.js"); +vi.mock("../configEnhancer.js"); vi.mock("./ServiceContainer.js"); -import * as args from "../args.js"; import * as workos from "../auth/workos.js"; +import { configEnhancer } from "../configEnhancer.js"; import * as configLoader from "../configLoader.js"; import { ConfigService } from "./ConfigService.js"; @@ -73,23 +73,30 @@ describe("ConfigService", () => { config: mockConfig as any, source: { type: "cli-flag", path: "/config.yaml" } as any, }); - vi.mocked(args.processRule).mockImplementation( - async (rule) => `Processed: ${rule}`, - ); + + const expectedConfig = { + ...mockConfig, + systemMessage: + "Test system message\n\nProcessed: rule1\n\nProcessed: rule2", + }; + + vi.mocked(configEnhancer.enhanceConfig).mockResolvedValue(expectedConfig); const state = await service.initialize( { accessToken: "token" } as any, "/config.yaml", "org-123", mockApiClient as any, - ["rule1", "rule2"], + { rule: ["rule1", "rule2"] }, ); - expect(state.config).toEqual({ - ...mockConfig, - systemMessage: - "Test system message\n\nProcessed: rule1\n\nProcessed: rule2", - }); + // Verify configEnhancer was called with the right parameters + expect(vi.mocked(configEnhancer.enhanceConfig)).toHaveBeenCalledWith( + mockConfig, + { rule: ["rule1", "rule2"] }, + ); + + expect(state.config).toEqual(expectedConfig); }); }); diff --git a/extensions/cli/src/services/ConfigService.ts b/extensions/cli/src/services/ConfigService.ts index c1fc706a9..149977edb 100644 --- a/extensions/cli/src/services/ConfigService.ts +++ b/extensions/cli/src/services/ConfigService.ts @@ -1,8 +1,8 @@ -import { AssistantUnrolled } from "@continuedev/config-yaml"; import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js"; -import { processRule } from "../args.js"; import { AuthConfig, loadAuthConfig } from "../auth/workos.js"; +import { BaseCommandOptions } from "../commands/BaseCommandOptions.js"; +import { configEnhancer } from "../configEnhancer.js"; import { logger } from "../util/logger.js"; import { BaseService, ServiceWithDependencies } from "./BaseService.js"; @@ -41,9 +41,9 @@ export class ConfigService async doInitialize( authConfig: AuthConfig, configPath: string | undefined, - organizationId: string | null, + _organizationId: string | null, apiClient: DefaultApiInterface, - rules?: string[], + injectedConfigOptions?: BaseCommandOptions, ): Promise { // Use the new streamlined config loader const { loadConfiguration } = await import("../configLoader.js"); @@ -51,9 +51,17 @@ export class ConfigService let config = result.config; - // Inject rules if provided - if (rules && rules.length > 0) { - config = await this.injectRulesIntoConfig(config, rules); + // Apply injected config if provided + if ( + injectedConfigOptions && + this.hasInjectedConfig(injectedConfigOptions) + ) { + config = await configEnhancer.enhanceConfig( + config, + injectedConfigOptions, + ); + + logger.debug("Applied injected configuration"); } // Config URI persistence is now handled by the streamlined loader @@ -72,9 +80,9 @@ export class ConfigService async switchConfig( newConfigPath: string, authConfig: AuthConfig, - organizationId: string | null, + _organizationId: string | null, apiClient: DefaultApiInterface, - rules?: string[], + injectedConfigOptions?: BaseCommandOptions, ): Promise { logger.debug("Switching configuration", { from: this.currentState.configPath, @@ -92,9 +100,17 @@ export class ConfigService let config = result.config; - // Inject rules if provided - if (rules && rules.length > 0) { - config = await this.injectRulesIntoConfig(config, rules); + // Apply injected config if provided + if ( + injectedConfigOptions && + this.hasInjectedConfig(injectedConfigOptions) + ) { + config = await configEnhancer.enhanceConfig( + config, + injectedConfigOptions, + ); + + logger.debug("Applied injected configuration"); } this.setState({ @@ -121,9 +137,9 @@ export class ConfigService */ async reload( authConfig: AuthConfig, - organizationId: string | null, + _organizationId: string | null, apiClient: DefaultApiInterface, - rules?: string[], + injectedConfigOptions?: BaseCommandOptions, ): Promise { if (!this.currentState.configPath) { throw new Error("No configuration path available for reload"); @@ -134,53 +150,22 @@ export class ConfigService return this.switchConfig( this.currentState.configPath, authConfig, - organizationId, + _organizationId, apiClient, - rules, + injectedConfigOptions, ); } /** - * Process rules and inject them into the assistant config + * Check if injected config options contain any config to inject */ - private async injectRulesIntoConfig( - config: AssistantUnrolled, - rules: string[], - ): Promise { - if (!rules || rules.length === 0) { - return config; - } - - const processedRules: string[] = []; - - for (const ruleSpec of rules) { - try { - const processedRule = await processRule(ruleSpec); - processedRules.push(processedRule); - } catch (error: any) { - logger.warn(`Failed to process rule "${ruleSpec}": ${error.message}`); - } - } - - if (processedRules.length === 0) { - return config; - } - - // Clone the config to avoid mutating the original - const modifiedConfig = { ...config }; - - // Combine processed rules with existing system message if the config has one - const existingSystemMessage = (modifiedConfig as any).systemMessage || ""; - const rulesSection = processedRules.join("\n\n"); - - if (existingSystemMessage) { - (modifiedConfig as any).systemMessage = - `${existingSystemMessage}\n\n${rulesSection}`; - } else { - (modifiedConfig as any).systemMessage = rulesSection; - } - - return modifiedConfig; + private hasInjectedConfig(options: BaseCommandOptions): boolean { + return !!( + (options.rule && options.rule.length > 0) || + (options.mcp && options.mcp.length > 0) || + (options.model && options.model.length > 0) || + (options.prompt && options.prompt.length > 0) + ); } /** diff --git a/extensions/cli/src/services/ModelService.direct.test.ts b/extensions/cli/src/services/ModelService.direct.test.ts new file mode 100644 index 000000000..e50e0b9fe --- /dev/null +++ b/extensions/cli/src/services/ModelService.direct.test.ts @@ -0,0 +1,207 @@ +import { describe, it, expect, beforeEach } from "vitest"; + +import { ModelService } from "./ModelService.js"; + +describe("ModelService - Direct Testing", () => { + let modelService: ModelService; + + beforeEach(() => { + modelService = new ModelService(); + }); + + it("should throw 'ModelService not initialized' when switching without initialization", async () => { + // The service is created but not initialized (no assistant or authConfig) + expect(modelService.getCurrentModelIndex()).toBe(-1); + + // Try to switch model without initialization + try { + await modelService.switchModel(0); + // Should not reach here + expect(true).toBe(false); + } catch (error: any) { + // Should throw the specific error + expect(error.message).toBe( + "ModelService not initialized - assistant data missing", + ); + } + }); + + it("should handle model switching with null authConfig for non-proxy models", async () => { + // Initialize the service properly + const mockAssistant = { + name: "Test Assistant", + version: "1.0.0", + models: [ + { + name: "claude-3.5-sonnet", + provider: "anthropic", + model: "claude-3.5-sonnet", + apiKey: "test-anthropic-key", + roles: ["chat"], + }, + { + name: "GPT-4", + provider: "openai", + model: "gpt-4", + apiKey: "test-openai-key", + roles: ["chat"], + }, + ], + }; + + // Initialize with null authConfig - valid for non-proxy models + const initialState = await modelService.initialize( + mockAssistant as any, + null as any, + ); + + // Verify initialization succeeded with null authConfig + expect(initialState.assistant).toBe(mockAssistant); + expect(initialState.authConfig).toBe(null); + expect(initialState.model).toBeDefined(); + expect((initialState.model as any).name).toBe("claude-3.5-sonnet"); + + // Should be able to switch models even with null authConfig + const switchedState = await modelService.switchModel(1); + expect(switchedState.model).toBeDefined(); + expect((switchedState.model as any).name).toBe("GPT-4"); + expect(switchedState.assistant).toBe(mockAssistant); + expect(switchedState.authConfig).toBe(null); + + // Verify the model info + const modelInfo = modelService.getModelInfo(); + expect(modelInfo?.name).toBe("GPT-4"); + expect(modelInfo?.provider).toBe("openai"); + }); + + it("should successfully switch model after proper initialization", async () => { + // Initialize the service properly + const mockAssistant = { + name: "Test Assistant", + version: "1.0.0", + models: [ + { + name: "GPT-4", + provider: "openai", + model: "gpt-4", + apiKey: "test-key-1", + roles: ["chat"], + }, + { + name: "GPT-3.5", + provider: "openai", + model: "gpt-3.5-turbo", + apiKey: "test-key-2", + roles: ["chat"], + }, + ], + }; + + const mockAuthConfig = { + token: "test-token", + }; + + // Initialize the service (note: initialize calls doInitialize and sets the state) + const initialState = await modelService.initialize( + mockAssistant as any, + mockAuthConfig as any, + ); + + // Verify we have models and the first one is selected + const availableModels = modelService.getAvailableChatModels(); + expect(availableModels.length).toBe(2); + expect(initialState.model).toBeDefined(); + expect((initialState.model as any).name).toBe("GPT-4"); + + // Now switch should work + await modelService.switchModel(1); + expect(modelService.getCurrentModelIndex()).toBe(1); + + const modelInfo = modelService.getModelInfo(); + expect(modelInfo?.name).toBe("GPT-3.5"); + }); + + it("should handle switching to invalid model index", async () => { + // Initialize properly first + const mockAssistant = { + name: "Test Assistant", + version: "1.0.0", + models: [ + { + name: "GPT-4", + provider: "openai", + model: "gpt-4", + apiKey: "test-key", + }, + ], + }; + + const mockAuthConfig = { + token: "test-token", + }; + + await modelService.initialize(mockAssistant as any, mockAuthConfig as any); + + // Try to switch to invalid index + try { + await modelService.switchModel(5); // Only have 1 model at index 0 + expect(true).toBe(false); + } catch (error: any) { + expect(error.message).toContain("Invalid model index"); + } + }); + + it("should successfully switch model when service is properly initialized via container", async () => { + // This test simulates the fix where we ensure service is initialized before switching + const mockAssistant = { + name: "Test Assistant", + version: "1.0.0", + models: [ + { + name: "GPT-4", + provider: "openai", + model: "gpt-4", + apiKey: "test-key-1", + roles: ["chat"], + }, + { + name: "GPT-3.5", + provider: "openai", + model: "gpt-3.5-turbo", + apiKey: "test-key-2", + roles: ["chat"], + }, + ], + }; + + const mockAuthConfig = { + token: "test-token", + }; + + // Initialize the service properly through initialize method (which sets isInitialized) + await modelService.initialize(mockAssistant as any, mockAuthConfig as any); + + // Verify initialization + expect(modelService.isReady()).toBe(true); + expect(modelService.getCurrentModelIndex()).toBe(0); + + // Now switch should work and return success + const newState = await modelService.switchModel(1); + + // Verify switch was successful + expect(modelService.getCurrentModelIndex()).toBe(1); + expect(newState.model).toBeDefined(); + expect((newState.model as any).name).toBe("GPT-3.5"); + + // Get model info to verify success message data + const modelInfo = modelService.getModelInfo(); + expect(modelInfo).toEqual({ + provider: "openai", + name: "GPT-3.5", + }); + + // This is what the success message would use + const successMessage = `Switched to model: ${modelInfo?.provider}/${modelInfo?.name}`; + expect(successMessage).toBe("Switched to model: openai/GPT-3.5"); + }); +}); diff --git a/extensions/cli/src/services/ModelService.refactored.ts b/extensions/cli/src/services/ModelService.refactored.ts deleted file mode 100644 index debcde1c8..000000000 --- a/extensions/cli/src/services/ModelService.refactored.ts +++ /dev/null @@ -1,260 +0,0 @@ -import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; -import { constructLlmApi, LLMConfig } from "@continuedev/openai-adapters"; - -import { - AuthConfig, - getAccessToken, - getOrganizationId, - getModelName, -} from "../auth/workos.js"; -import { getLlmApi } from "../config.js"; -import { logger } from "../util/logger.js"; - -import { BaseService, ServiceWithDependencies } from "./BaseService.js"; -import { ModelServiceState } from "./types.js"; - -/** - * Service for managing LLM and model state - * Extends BaseService and implements ServiceWithDependencies - */ -export class ModelService - extends BaseService - implements ServiceWithDependencies -{ - private availableModels: ModelConfig[] = []; - private assistant: AssistantUnrolled | null = null; - private authConfig: AuthConfig | null = null; - - constructor() { - super("ModelService", { - llmApi: null, - model: null, - }); - } - - /** - * Declare dependencies on other services - */ - getDependencies(): string[] { - return ["auth", "config"]; - } - - /** - * Initialize the model service - */ - async doInitialize( - assistant: AssistantUnrolled, - authConfig: AuthConfig, - ): Promise { - this.assistant = assistant; - this.authConfig = authConfig; - this.availableModels = (assistant.models?.filter( - (model) => - model && (model.roles?.includes("chat") || model.roles === undefined), - ) || []) as ModelConfig[]; - - // Check if we have a persisted model name and use it if valid - const persistedModelName = getModelName(authConfig); - if (persistedModelName) { - const modelIndex = this.getModelIndexByName(persistedModelName); - if (modelIndex === -1) { - // Model name not found, use default model selection - const [llmApi, model] = getLlmApi(assistant, authConfig); - return { - llmApi, - model, - }; - } else { - // Use the persisted model - const state = await this.switchModel(modelIndex); - return state; - } - } else { - // Use default model selection - const [llmApi, model] = getLlmApi(assistant, authConfig); - return { - llmApi, - model, - }; - } - } - - /** - * Update the model based on new config or auth changes - */ - async update( - assistant: AssistantUnrolled, - authConfig: AuthConfig, - ): Promise { - logger.debug("Updating ModelService"); - - try { - this.assistant = assistant; - this.authConfig = authConfig; - this.availableModels = (assistant.models?.filter( - (model) => - model && (model.roles?.includes("chat") || model.roles === undefined), - ) || []) as ModelConfig[]; - - const [llmApi, model] = getLlmApi(assistant, authConfig); - - this.setState({ - llmApi, - model, - }); - - logger.debug("ModelService updated successfully", { - modelProvider: model.provider, - modelName: (model as any).name || "unnamed", - availableModels: this.availableModels.length, - }); - - return this.getState(); - } catch (error: any) { - logger.error("Failed to update ModelService:", error); - this.emit("error", error); - throw error; - } - } - - /** - * Override isReady to check for required state - */ - override isReady(): boolean { - return ( - super.isReady() && - this.currentState.llmApi !== null && - this.currentState.model !== null - ); - } - - /** - * Get model information for display - */ - getModelInfo(): { provider: string; name: string } | null { - if (!this.currentState.model) { - return null; - } - - return { - provider: this.currentState.model.provider, - name: (this.currentState.model as any).name || "unnamed", - }; - } - - /** - * Get list of available chat models - */ - getAvailableChatModels(): Array<{ - provider: string; - name: string; - index: number; - }> { - return this.availableModels.map((model, index) => ({ - provider: model.provider, - name: (model as any).name || (model as any).model || "unnamed", - index, - })); - } - - /** - * Switch to a different chat model by index - */ - async switchModel(modelIndex: number): Promise { - if (!this.assistant || !this.authConfig) { - throw new Error("ModelService not initialized"); - } - - if (modelIndex < 0 || modelIndex >= this.availableModels.length) { - throw new Error( - `Invalid model index: ${modelIndex}. Available models: 0-${this.availableModels.length - 1}`, - ); - } - - const selectedModel = this.availableModels[modelIndex]; - logger.debug("Switching to model", { - modelIndex, - provider: selectedModel.provider, - name: (selectedModel as any).name || "unnamed", - }); - - try { - const accessToken = getAccessToken(this.authConfig); - const organizationId = getOrganizationId(this.authConfig); - - const config: LLMConfig = - selectedModel.provider === "continue-proxy" - ? { - provider: selectedModel.provider, - requestOptions: selectedModel.requestOptions, - apiBase: selectedModel.apiBase, - apiKey: accessToken ?? undefined, - env: { - apiKeyLocation: (selectedModel as any).apiKeyLocation, - orgScopeId: organizationId, - proxyUrl: undefined, - }, - } - : { - provider: selectedModel.provider as any, - apiKey: selectedModel.apiKey, - apiBase: selectedModel.apiBase, - requestOptions: selectedModel.requestOptions, - env: selectedModel.env, - }; - - const llmApi = constructLlmApi(config); - - if (!llmApi) { - throw new Error("Failed to initialize LLM with selected model"); - } - - this.setState({ - llmApi, - model: selectedModel, - }); - - logger.debug("Model switched successfully", { - modelProvider: selectedModel.provider, - modelName: (selectedModel as any).name || "unnamed", - }); - - return this.getState(); - } catch (error: any) { - logger.error("Failed to switch model:", error); - this.emit("error", error); - throw error; - } - } - - /** - * Get current model index - */ - getCurrentModelIndex(): number { - if (!this.currentState.model) { - return -1; - } - - return this.availableModels.findIndex( - (model) => - model.provider === this.currentState.model?.provider && - (model as any).name === (this.currentState.model as any).name, - ); - } - - /** - * Get model index by name and provider - */ - getModelIndexByName(modelName: string, provider?: string): number { - return this.availableModels.findIndex((model) => { - const name = (model as any).name || (model as any).model; - const nameMatches = name === modelName; - - if (provider) { - return nameMatches && model.provider === provider; - } - - return nameMatches; - }); - } -} diff --git a/extensions/cli/src/services/ModelService.test.ts b/extensions/cli/src/services/ModelService.test.ts index 905e6c8c3..32932e4df 100644 --- a/extensions/cli/src/services/ModelService.test.ts +++ b/extensions/cli/src/services/ModelService.test.ts @@ -74,6 +74,8 @@ describe("ModelService", () => { expect(state).toEqual({ llmApi: mockLlmApi, model: mockAssistant.models![0], + assistant: mockAssistant, + authConfig: mockAuthConfig, }); }); @@ -135,6 +137,8 @@ describe("ModelService", () => { expect(state).toEqual({ llmApi: newLlmApi, model: newAssistant.models![0], + assistant: newAssistant, + authConfig: mockAuthConfig, }); }); }); @@ -157,6 +161,8 @@ describe("ModelService", () => { expect(state).toEqual({ llmApi: newLlmApi, model: mockAssistant.models![1], + assistant: mockAssistant, + authConfig: mockAuthConfig, }); expect(service.getState()).toEqual(state); }); diff --git a/extensions/cli/src/services/ModelService.ts b/extensions/cli/src/services/ModelService.ts index 7e5dae621..7b50a69e9 100644 --- a/extensions/cli/src/services/ModelService.ts +++ b/extensions/cli/src/services/ModelService.ts @@ -29,6 +29,8 @@ export class ModelService super("ModelService", { llmApi: null, model: null, + assistant: null, + authConfig: null, }); } @@ -46,6 +48,12 @@ export class ModelService assistant: AssistantUnrolled, authConfig: AuthConfig, ): Promise { + logger.debug("ModelService.doInitialize called", { + hasAssistant: !!assistant, + hasAuthConfig: !!authConfig, + assistantModelsCount: assistant?.models?.length || 0, + }); + this.assistant = assistant; this.authConfig = authConfig; this.availableModels = (assistant.models?.filter( @@ -56,18 +64,67 @@ export class ModelService // Check if we have a persisted model name and use it if valid const persistedModelName = getModelName(authConfig); if (persistedModelName) { - const modelIndex = this.getModelIndexByName(persistedModelName); + // During initialization, we need to check against availableModels directly + const modelIndex = this.availableModels.findIndex((model) => { + const name = (model as any).name || (model as any).model; + return name === persistedModelName; + }); if (modelIndex === -1) { // Model name not found, use default model selection const [llmApi, model] = getLlmApi(assistant, authConfig); return { llmApi, model, + assistant, + authConfig, }; } else { - // Use the persisted model - const state = await this.switchModel(modelIndex); - return state; + // Use the persisted model - but we need to handle initialization specially + // During init, currentState isn't set yet, so switchModel would fail + // Instead, we'll manually switch here + const selectedModel = this.availableModels[modelIndex]; + logger.debug("Using persisted model during initialization", { + modelIndex, + provider: selectedModel.provider, + name: (selectedModel as any).name || "unnamed", + }); + + const accessToken = getAccessToken(authConfig); + const organizationId = getOrganizationId(authConfig); + + const config: LLMConfig = + selectedModel.provider === "continue-proxy" + ? { + provider: selectedModel.provider, + requestOptions: selectedModel.requestOptions, + apiBase: selectedModel.apiBase, + apiKey: accessToken ?? undefined, + env: { + apiKeyLocation: (selectedModel as any).apiKeyLocation, + orgScopeId: organizationId, + proxyUrl: undefined, + }, + } + : { + provider: selectedModel.provider as any, + apiKey: selectedModel.apiKey, + apiBase: selectedModel.apiBase, + requestOptions: selectedModel.requestOptions, + env: selectedModel.env, + }; + + const llmApi = constructLlmApi(config); + + if (!llmApi) { + throw new Error("Failed to initialize LLM with persisted model"); + } + + return { + llmApi, + model: selectedModel, + assistant, + authConfig, + }; } } else { // Use default model selection @@ -75,6 +132,8 @@ export class ModelService return { llmApi, model, + assistant, + authConfig, }; } } @@ -89,6 +148,7 @@ export class ModelService logger.debug("Updating ModelService"); try { + // Update instance properties for backward compatibility this.assistant = assistant; this.authConfig = authConfig; this.availableModels = (assistant.models?.filter( @@ -98,9 +158,12 @@ export class ModelService const [llmApi, model] = getLlmApi(assistant, authConfig); + // Ensure state has all necessary data this.setState({ llmApi, model, + assistant, + authConfig, }); logger.debug("ModelService updated successfully", { @@ -150,7 +213,19 @@ export class ModelService name: string; index: number; }> { - return this.availableModels.map((model, index) => ({ + // Get assistant from state to ensure we have the latest data + const { assistant } = this.getState(); + if (!assistant || !assistant.models) { + return []; + } + + // Filter for chat models + const chatModels = (assistant.models.filter( + (model) => + model && (model.roles?.includes("chat") || model.roles === undefined), + ) || []) as ModelConfig[]; + + return chatModels.map((model, index) => ({ provider: model.provider, name: (model as any).name || (model as any).model || "unnamed", index, @@ -161,17 +236,51 @@ export class ModelService * Switch to a different chat model by index */ async switchModel(modelIndex: number): Promise { - if (!this.assistant || !this.authConfig) { - throw new Error("ModelService not initialized"); + // Get assistant and authConfig from state, but fall back to instance properties + // This is needed during initialization when state isn't set yet + const stateValues = this.getState(); + const assistant = stateValues.assistant || this.assistant; + const authConfig = stateValues.authConfig || this.authConfig; + + // Debug logging to understand the state + logger.debug("switchModel: Checking state", { + hasStateAssistant: !!stateValues.assistant, + hasStateAuthConfig: !!stateValues.authConfig, + hasInstanceAssistant: !!this.assistant, + hasInstanceAuthConfig: !!this.authConfig, + isInitialized: this.isReady(), + isReady: this.isReady(), + modelIndex, + }); + + if (!assistant) { + logger.error("switchModel: Missing assistant data", { + assistant: !!assistant, + authConfig: !!authConfig, + stateKeys: Object.keys(stateValues), + currentState: { + hasLlmApi: !!stateValues.llmApi, + hasModel: !!stateValues.model, + hasAssistant: !!stateValues.assistant, + hasAuthConfig: !!stateValues.authConfig, + }, + }); + throw new Error("ModelService not initialized - assistant data missing"); } - if (modelIndex < 0 || modelIndex >= this.availableModels.length) { + // Get available models from assistant in state + const availableModels = (assistant.models?.filter( + (model) => + model && (model.roles?.includes("chat") || model.roles === undefined), + ) || []) as ModelConfig[]; + + if (modelIndex < 0 || modelIndex >= availableModels.length) { throw new Error( - `Invalid model index: ${modelIndex}. Available models: 0-${this.availableModels.length - 1}`, + `Invalid model index: ${modelIndex}. Available models: 0-${availableModels.length - 1}`, ); } - const selectedModel = this.availableModels[modelIndex]; + const selectedModel = availableModels[modelIndex]; logger.debug("Switching to model", { modelIndex, provider: selectedModel.provider, @@ -179,8 +288,8 @@ export class ModelService }); try { - const accessToken = getAccessToken(this.authConfig); - const organizationId = getOrganizationId(this.authConfig); + const accessToken = getAccessToken(authConfig); + const organizationId = getOrganizationId(authConfig); const config: LLMConfig = selectedModel.provider === "continue-proxy" @@ -212,6 +321,8 @@ export class ModelService this.setState({ llmApi, model: selectedModel, + assistant, + authConfig, }); logger.debug("Model switched successfully", { @@ -231,14 +342,21 @@ export class ModelService * Get current model index */ getCurrentModelIndex(): number { - if (!this.currentState.model) { + const state = this.getState(); + if (!state.model || !state.assistant) { return -1; } - return this.availableModels.findIndex( + // Get available models from state + const availableModels = (state.assistant.models?.filter( (model) => - model.provider === this.currentState.model?.provider && - (model as any).name === (this.currentState.model as any).name, + model && (model.roles?.includes("chat") || model.roles === undefined), + ) || []) as ModelConfig[]; + + return availableModels.findIndex( + (model) => + model.provider === state.model?.provider && + (model as any).name === (state.model as any).name, ); } @@ -246,7 +364,18 @@ export class ModelService * Get model index by name and provider */ getModelIndexByName(modelName: string, provider?: string): number { - return this.availableModels.findIndex((model) => { + const state = this.getState(); + if (!state.assistant) { + return -1; + } + + // Get available models from state + const availableModels = (state.assistant.models?.filter( + (model) => + model && (model.roles?.includes("chat") || model.roles === undefined), + ) || []) as ModelConfig[]; + + return availableModels.findIndex((model) => { const name = (model as any).name || (model as any).model; const nameMatches = name === modelName; diff --git a/extensions/cli/src/services/ResourceMonitoringService.test.ts b/extensions/cli/src/services/ResourceMonitoringService.test.ts new file mode 100644 index 000000000..a0ef2017b --- /dev/null +++ b/extensions/cli/src/services/ResourceMonitoringService.test.ts @@ -0,0 +1,108 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { ResourceMonitoringService } from "./ResourceMonitoringService.js"; + +// Mock the logger and BaseService +vi.mock("../util/logger.js", () => ({ + logger: { + debug: vi.fn(), + info: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + }, +})); + +vi.mock("./BaseService.js", () => ({ + BaseService: class MockBaseService { + logger = { + debug: vi.fn(), + info: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + }; + }, +})); + +describe("ResourceMonitoringService", () => { + let service: ResourceMonitoringService; + + beforeEach(async () => { + // Remove process event listeners to prevent interference + process.removeAllListeners("exit"); + process.removeAllListeners("SIGINT"); + process.removeAllListeners("SIGTERM"); + + service = new ResourceMonitoringService(); + await service.initialize(); + }); + + afterEach(async () => { + if (service) { + service.stopMonitoring(); // Ensure monitoring is stopped + await service.cleanup(); + } + }); + + it("should initialize without starting monitoring by default", () => { + expect(service).toBeDefined(); + // Should not be monitoring unless --verbose is passed + const usage = service.getCurrentResourceUsage(); + expect(usage.timestamp).toBeGreaterThan(0); + }); + + it("should collect current resource usage", () => { + const usage = service.getCurrentResourceUsage(); + + expect(usage.timestamp).toBeGreaterThan(0); + expect(usage.memory.rss).toBeGreaterThan(0); + expect(usage.memory.heapTotal).toBeGreaterThan(0); + expect(usage.memory.heapUsed).toBeGreaterThan(0); + expect(usage.cpu.user).toBeGreaterThanOrEqual(0); + expect(usage.cpu.system).toBeGreaterThanOrEqual(0); + expect(usage.system.uptime).toBeGreaterThan(0); + expect(usage.system.totalMemory).toBeGreaterThan(0); + expect(usage.eventLoop.lag).toBeGreaterThanOrEqual(0); + }); + + it("should provide resource summary", () => { + const summary = service.getResourceSummary(); + + expect(summary.current).toBeDefined(); + expect(summary.peak).toBeDefined(); + expect(summary.average).toBeDefined(); + + expect(summary.peak.memory).toBeGreaterThan(0); + expect(summary.peak.cpu).toBeGreaterThanOrEqual(0); + + expect(summary.average.memory).toBeGreaterThan(0); + expect(summary.average.cpu).toBeGreaterThanOrEqual(0); + }); + + it("should start and stop monitoring", async () => { + service.startMonitoring(100); // 100ms interval for test + + // Wait for some data collection + await new Promise((resolve) => setTimeout(resolve, 250)); + + const history = service.getResourceHistory(); + expect(history.length).toBeGreaterThan(0); + + service.stopMonitoring(); + }); + + it("should handle verbose mode initialization", async () => { + // Mock argv to include --verbose + const originalArgv = process.argv; + process.argv = [...originalArgv, "--verbose"]; + + const verboseService = new ResourceMonitoringService(); + await verboseService.initialize(); + + // Should start monitoring automatically + // Note: Testing this properly would require checking internal state + // which isn't directly exposed + + await verboseService.cleanup(); + process.argv = originalArgv; + }); +}); diff --git a/extensions/cli/src/services/ResourceMonitoringService.ts b/extensions/cli/src/services/ResourceMonitoringService.ts new file mode 100644 index 000000000..a114d3027 --- /dev/null +++ b/extensions/cli/src/services/ResourceMonitoringService.ts @@ -0,0 +1,312 @@ +import { exec } from "child_process"; +import * as os from "os"; +import { promisify } from "util"; + +import { logger } from "../util/logger.js"; + +const execAsync = promisify(exec); + +export interface ResourceUsage { + timestamp: number; + memory: { + rss: number; // Resident Set Size + heapTotal: number; + heapUsed: number; + external: number; + arrayBuffers: number; + }; + cpu: { + user: number; + system: number; + percent?: number; // CPU percentage (calculated) + }; + system: { + loadAverage: number[]; + uptime: number; + freeMemory: number; + totalMemory: number; + }; + eventLoop: { + lag: number; + }; + fileDescriptors?: number; +} + +export interface ResourceMonitoringState { + isMonitoring: boolean; + resourceHistory: ResourceUsage[]; +} + +class ResourceMonitoringService { + private isMonitoring = false; + private monitoringInterval?: NodeJS.Timeout; + private intervalMs = 1000; // Default 1 second + private resourceHistory: ResourceUsage[] = []; + private maxHistorySize = 300; // Keep 5 minutes at 1s intervals + private lastCpuUsage = process.cpuUsage(); + private lastTimestamp = Date.now(); + + async initialize(): Promise { + // Start monitoring if verbose mode is enabled + if (process.argv.includes("--verbose")) { + this.startMonitoring(); + } + + // Cleanup on exit + process.on("exit", () => this.cleanup()); + process.on("SIGINT", () => this.cleanup()); + process.on("SIGTERM", () => this.cleanup()); + } + + async cleanup(): Promise { + this.stopMonitoring(); + } + + public startMonitoring(intervalMs = 1000): void { + if (this.isMonitoring) return; + + this.intervalMs = intervalMs; + this.isMonitoring = true; + this.lastCpuUsage = process.cpuUsage(); + this.lastTimestamp = Date.now(); + + this.monitoringInterval = setInterval(() => { + this.collectResourceUsage(); + }, this.intervalMs); + + logger.debug("Resource monitoring started", { intervalMs }); + } + + public stopMonitoring(): void { + if (!this.isMonitoring) return; + + this.isMonitoring = false; + if (this.monitoringInterval) { + clearInterval(this.monitoringInterval); + this.monitoringInterval = undefined; + } + + logger.debug("Resource monitoring stopped"); + } + + public getCurrentResourceUsage(): ResourceUsage { + const now = Date.now(); + const currentCpuUsage = process.cpuUsage(); + const timeDiff = now - this.lastTimestamp; + + // Calculate CPU percentage + const userDiff = currentCpuUsage.user - this.lastCpuUsage.user; + const systemDiff = currentCpuUsage.system - this.lastCpuUsage.system; + const totalDiff = userDiff + systemDiff; + const cpuPercent = timeDiff > 0 ? (totalDiff / (timeDiff * 1000)) * 100 : 0; + + const memoryUsage = process.memoryUsage(); + + const usage: ResourceUsage = { + timestamp: now, + memory: { + rss: memoryUsage.rss, + heapTotal: memoryUsage.heapTotal, + heapUsed: memoryUsage.heapUsed, + external: memoryUsage.external, + arrayBuffers: memoryUsage.arrayBuffers, + }, + cpu: { + user: currentCpuUsage.user, + system: currentCpuUsage.system, + percent: Math.min(cpuPercent, 100), // Cap at 100% + }, + system: { + loadAverage: this.getLoadAverage(), + uptime: this.getProcessUptime(), + freeMemory: this.getFreeMemory(), + totalMemory: this.getTotalMemory(), + }, + eventLoop: { + lag: this.measureEventLoopLag(), + }, + }; + + // Try to get file descriptor count (Unix only) + this.getFileDescriptorCount() + .then((count) => { + if (count !== null) { + usage.fileDescriptors = count; + } + }) + .catch(() => { + // Ignore errors for file descriptor counting + }); + + return usage; + } + + public getResourceHistory(): ResourceUsage[] { + return [...this.resourceHistory]; + } + + public getResourceSummary(): { + current: ResourceUsage; + peak: { + memory: number; + cpu: number; + }; + average: { + memory: number; + cpu: number; + }; + } { + const current = this.getCurrentResourceUsage(); + + if (this.resourceHistory.length === 0) { + return { + current, + peak: { + memory: current.memory.rss, + cpu: current.cpu.percent || 0, + }, + average: { + memory: current.memory.rss, + cpu: current.cpu.percent || 0, + }, + }; + } + + const peakMemory = Math.max( + ...this.resourceHistory.map((r) => r.memory.rss), + ); + const peakCpu = Math.max( + ...this.resourceHistory.map((r) => r.cpu.percent || 0), + ); + + const avgMemory = + this.resourceHistory.reduce((sum, r) => sum + r.memory.rss, 0) / + this.resourceHistory.length; + const avgCpu = + this.resourceHistory.reduce((sum, r) => sum + (r.cpu.percent || 0), 0) / + this.resourceHistory.length; + + return { + current, + peak: { + memory: Math.max(peakMemory, current.memory.rss), + cpu: Math.max(peakCpu, current.cpu.percent || 0), + }, + average: { + memory: avgMemory, + cpu: avgCpu, + }, + }; + } + + private collectResourceUsage(): void { + try { + const usage = this.getCurrentResourceUsage(); + + // Update for next CPU calculation + this.lastCpuUsage = process.cpuUsage(); + this.lastTimestamp = usage.timestamp; + + // Add to history + this.resourceHistory.push(usage); + + // Trim history if too large + if (this.resourceHistory.length > this.maxHistorySize) { + this.resourceHistory = this.resourceHistory.slice(-this.maxHistorySize); + } + + // Check for potential issues and log warnings + this.checkResourceThresholds(usage); + } catch (error) { + logger.error("Error collecting resource usage", error); + } + } + + private checkResourceThresholds(usage: ResourceUsage): void { + const memoryUsageMB = usage.memory.rss / 1024 / 1024; + const cpuPercent = usage.cpu.percent || 0; + + // Memory threshold: 500MB + if (memoryUsageMB > 500) { + logger.warn("High memory usage detected", { + memoryMB: Math.round(memoryUsageMB), + threshold: 500, + }); + } + + // CPU threshold: 80% + if (cpuPercent > 80) { + logger.warn("High CPU usage detected", { + cpuPercent: Math.round(cpuPercent), + threshold: 80, + }); + } + + // Event loop lag threshold: 100ms + if (usage.eventLoop.lag > 100) { + logger.warn("High event loop lag detected", { + lagMs: Math.round(usage.eventLoop.lag), + threshold: 100, + }); + } + } + + private async getFileDescriptorCount(): Promise { + if (process.platform === "win32") { + return null; // Not supported on Windows + } + + try { + const { stdout } = await execAsync(`lsof -p ${process.pid} | wc -l`); + return parseInt(stdout.trim(), 10) - 1; // Subtract 1 for header line + } catch { + return null; + } + } + + private getLoadAverage(): number[] { + try { + return process.platform === "win32" ? [0, 0, 0] : os.loadavg(); + } catch { + return [0, 0, 0]; + } + } + + private getProcessUptime(): number { + try { + return typeof process.uptime === "function" ? process.uptime() : 0; + } catch { + return 0; + } + } + + private getFreeMemory(): number { + try { + return os.freemem(); + } catch { + return 0; + } + } + + private getTotalMemory(): number { + try { + return os.totalmem(); + } catch { + return 1024 * 1024 * 1024; // 1GB default fallback + } + } + + // Synchronous approximation of event loop lag + private measureEventLoopLag(): number { + // Return a simple approximation based on load average on Unix systems + const loadAvg = this.getLoadAverage(); + if (loadAvg[0] > 0) { + // Rough approximation: higher load = higher lag + return Math.min(loadAvg[0] * 10, 200); // Cap at 200ms + } + + return 0; + } +} + +export { ResourceMonitoringService }; diff --git a/extensions/cli/src/services/index.ts b/extensions/cli/src/services/index.ts index d1572c7d4..81b1e7318 100644 --- a/extensions/cli/src/services/index.ts +++ b/extensions/cli/src/services/index.ts @@ -9,6 +9,7 @@ import { FileIndexService } from "./FileIndexService.js"; import { MCPService } from "./MCPService.js"; import { ModelService } from "./ModelService.js"; import { modeService } from "./ModeService.js"; +import { ResourceMonitoringService } from "./ResourceMonitoringService.js"; import { serviceContainer } from "./ServiceContainer.js"; import { ApiClientServiceState, @@ -26,33 +27,35 @@ const modelService = new ModelService(); const apiClientService = new ApiClientService(); const mcpService = new MCPService(); const fileIndexService = new FileIndexService(); +const resourceMonitoringService = new ResourceMonitoringService(); /** * Initialize all services and register them with the service container * Handles onboarding internally for TUI mode unless skipOnboarding is true */ export async function initializeServices( - options: ServiceInitOptions = {}, + initOptions: ServiceInitOptions = {}, ): Promise { logger.debug("Initializing service registry"); let wasOnboarded = false; + const commandOptions = initOptions.options || {}; // Handle onboarding for TUI mode (headless: false) unless explicitly skipped - if (!options.headless && !options.skipOnboarding) { + if (!initOptions.headless && !initOptions.skipOnboarding) { const authConfig = loadAuthConfig(); const onboardingResult = await initializeWithOnboarding( authConfig, - options.configPath, - options.rules, + commandOptions.config, + commandOptions.rule, ); wasOnboarded = onboardingResult.wasOnboarded; } // Handle ANTHROPIC_API_KEY in headless mode when no config path is provided if ( - options.headless && - !options.configPath && + initOptions.headless && + !commandOptions.config && process.env.ANTHROPIC_API_KEY ) { const { createOrUpdateConfig } = await import("../onboarding.js"); @@ -63,19 +66,19 @@ export async function initializeServices( await createOrUpdateConfig(process.env.ANTHROPIC_API_KEY); // Update options to use the created config - options.configPath = CONFIG_PATH; + commandOptions.config = CONFIG_PATH; } // Initialize mode service with tool permission overrides - if (options.toolPermissionOverrides) { - const overrides = { ...options.toolPermissionOverrides }; + if (initOptions.toolPermissionOverrides) { + const overrides = { ...initOptions.toolPermissionOverrides }; // Convert mode to boolean flags for ModeService const initArgs: Parameters[0] = { allow: overrides.allow, ask: overrides.ask, exclude: overrides.exclude, - isHeadless: options.headless, + isHeadless: initOptions.headless, }; // Only set the boolean flag that corresponds to the mode @@ -90,7 +93,7 @@ export async function initializeServices( } else { // Even if no overrides, we need to initialize with defaults await modeService.initialize({ - isHeadless: options.headless, + isHeadless: initOptions.headless, }); } @@ -137,8 +140,8 @@ export async function initializeServices( let finalAuthState = authState; if (authState.authConfig) { finalAuthState = await authService.ensureOrganization( - options.headless ?? false, - options.organizationSlug, + initOptions.headless ?? false, + commandOptions.org, ); // Update the auth service state in container serviceContainer.set(SERVICE_NAMES.AUTH, finalAuthState); @@ -149,11 +152,11 @@ export async function initializeServices( } // Use current config path from ConfigService state if available (for reloads), - // otherwise use initial options.configPath (for first initialization) + // otherwise use initial options.config (for first initialization) // IMPORTANT: Always prefer explicit --config flag over saved state const currentState = configService.getState(); let configPath = - options.configPath || + commandOptions.config || (currentState.configPath === undefined ? undefined : currentState.configPath); @@ -175,7 +178,7 @@ export async function initializeServices( configPath, finalAuthState.organizationId || null, apiClientState.apiClient, - options.rules, + commandOptions, ); }, [SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT], // Depends on auth and API client @@ -208,7 +211,7 @@ export async function initializeServices( if (!configState.config) { throw new Error("Config not available for MCP service"); } - return mcpService.initialize(configState.config, options.headless); + return mcpService.initialize(configState.config, initOptions.headless); }, [SERVICE_NAMES.CONFIG], // Depends on config ); @@ -219,6 +222,12 @@ export async function initializeServices( [], ); + serviceContainer.register( + SERVICE_NAMES.RESOURCE_MONITORING, + () => resourceMonitoringService.initialize(), + [], + ); + // Eagerly initialize all services to ensure they're ready when needed // This avoids race conditions and "service not ready" errors await serviceContainer.initializeAll(); @@ -261,6 +270,7 @@ export function areServicesReady(): boolean { SERVICE_NAMES.MODEL, SERVICE_NAMES.MCP, SERVICE_NAMES.FILE_INDEX, + SERVICE_NAMES.RESOURCE_MONITORING, ].every((name) => serviceContainer.isReady(name)); } @@ -282,6 +292,7 @@ export const services = { mcp: mcpService, fileIndex: fileIndexService, mode: modeService, + resourceMonitoring: resourceMonitoringService, } as const; // Export the service container for advanced usage diff --git a/extensions/cli/src/services/types.ts b/extensions/cli/src/services/types.ts index 45d0a4599..112611eff 100644 --- a/extensions/cli/src/services/types.ts +++ b/extensions/cli/src/services/types.ts @@ -5,6 +5,7 @@ import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { AuthConfig } from "../auth/workos.js"; +import { BaseCommandOptions } from "../commands/BaseCommandOptions.js"; import { PermissionMode, ToolPermissions } from "../permissions/types.js"; import { MCPService } from "./MCPService.js"; @@ -51,6 +52,8 @@ export interface ConfigServiceState { export interface ModelServiceState { llmApi: BaseLlmApi | null; model: ModelConfig | null; + assistant: AssistantUnrolled | null; + authConfig: AuthConfig | null; } export type MCPServerStatus = "idle" | "connecting" | "connected" | "error"; @@ -102,15 +105,14 @@ export const SERVICE_NAMES = { API_CLIENT: "apiClient", TOOL_PERMISSIONS: "toolPermissions", FILE_INDEX: "fileIndex", + RESOURCE_MONITORING: "resourceMonitoring", } as const; /** * Service initialization options */ export interface ServiceInitOptions { - configPath?: string; - organizationSlug?: string; // Organization slug to use for this session - rules?: string[]; + options?: BaseCommandOptions; // Command-line options headless?: boolean; skipOnboarding?: boolean; // Skip onboarding check even in TUI mode toolPermissionOverrides?: { diff --git a/extensions/cli/src/session.ts b/extensions/cli/src/session.ts index f843218a6..11e39ccc7 100644 --- a/extensions/cli/src/session.ts +++ b/extensions/cli/src/session.ts @@ -180,7 +180,7 @@ function getSessionDir(): string { /** * Get the session file path for the current session */ -function getSessionFilePath(): string { +export function getSessionFilePath(): string { const sessionId = getSessionId(); const sessionDir = getSessionDir(); return path.join(sessionDir, `${sessionId}.json`); diff --git a/extensions/cli/src/shared-options.ts b/extensions/cli/src/shared-options.ts index 6a68f29b1..9f220aa36 100644 --- a/extensions/cli/src/shared-options.ts +++ b/extensions/cli/src/shared-options.ts @@ -24,6 +24,36 @@ export function addCommonOptions(command: Command): Command { }, [] as string[], ) + .option( + "--mcp ", + "Add an MCP server from the hub (slug in format 'owner/package'). Can be specified multiple times.", + (value: string, previous: string[] | undefined) => { + const array = Array.isArray(previous) ? previous : []; + array.push(value); + return array; + }, + [] as string[], + ) + .option( + "--model ", + "Add a model from the hub (slug in format 'owner/package'). Can be specified multiple times.", + (value: string, previous: string[] | undefined) => { + const array = Array.isArray(previous) ? previous : []; + array.push(value); + return array; + }, + [] as string[], + ) + .option( + "--prompt ", + "Add to the initial user message (can be a file path, hub slug, or string content). Can be specified multiple times.", + (value: string, previous: string[] | undefined) => { + const array = Array.isArray(previous) ? previous : []; + array.push(value); + return array; + }, + [] as string[], + ) .option( "--allow ", "Allow specified tool (overrides default policies). Can be specified multiple times.", @@ -70,6 +100,9 @@ export function mergeParentOptions(parentCommand: Command, options: any): any { "tools", "verbose", "rule", + "mcp", + "model", + "prompt", "allow", "ask", "exclude", diff --git a/extensions/cli/src/slashCommands.test.ts b/extensions/cli/src/slashCommands.test.ts index 986ed17ee..50185cf33 100644 --- a/extensions/cli/src/slashCommands.test.ts +++ b/extensions/cli/src/slashCommands.test.ts @@ -1,147 +1,231 @@ -// Import after mocking -import { AssistantUnrolled } from "@continuedev/config-yaml"; -import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; +import type { AssistantUnrolled } from "@continuedev/config-yaml"; +import { + describe, + it, + expect, + vi, + beforeEach, + type MockedFunction, +} from "vitest"; -import * as workos from "./auth/workos.js"; -import * as commands from "./commands/commands.js"; -import { reloadService, SERVICE_NAMES, services } from "./services/index.js"; -import type { AuthServiceState } from "./services/types.js"; +import type { AuthConfig, AuthenticatedConfig } from "./auth/workos.js"; +import type { ConfigServiceState } from "./services/types.js"; import { handleSlashCommands } from "./slashCommands.js"; -// The imports are already mocked via vitest.setup.ts, so we can use them directly +// Mock the services +vi.mock("./services/index.js", () => ({ + services: { + config: { + getState: vi.fn(), + }, + }, + reloadService: vi.fn(), + SERVICE_NAMES: { + AUTH: "AUTH", + }, +})); -// Mock console to avoid output during tests -const originalConsole = console; -const mockConsole = { - info: vi.fn(), - error: vi.fn(), - log: vi.fn(), -}; +// Mock auth functions +vi.mock("./auth/workos.js", () => ({ + isAuthenticated: vi.fn(), + isAuthenticatedConfig: vi.fn(), + loadAuthConfig: vi.fn(), +})); -describe("handleSlashCommands", () => { +// Mock telemetry +vi.mock("./telemetry/posthogService.js", () => ({ + posthogService: { + capture: vi.fn(), + }, +})); + +// Mock commands +vi.mock("./commands/commands.js", () => ({ + getAllSlashCommands: vi.fn(() => []), +})); + +// Mock os and path +vi.mock("os", () => ({ + default: { + homedir: vi.fn(() => "/home/test"), + }, +})); + +vi.mock("path", () => ({ + default: { + join: vi.fn((...parts) => parts.join("/")), + }, + join: vi.fn((...parts) => parts.join("/")), +})); + +// Mock session functions +vi.mock("./session.js", () => ({ + getSessionFilePath: vi.fn( + () => "/home/test/.continue/cli-sessions/continue-cli-pid-12345.json", + ), + hasSession: vi.fn(() => false), +})); + +describe("slashCommands", () => { const mockAssistant: AssistantUnrolled = { name: "test-assistant", version: "1.0.0", - prompts: [{ name: "test", prompt: "Test prompt: " }], }; beforeEach(() => { - Object.assign(console, mockConsole); vi.clearAllMocks(); - - // Since the mock already returns the required value, we don't need to set it - // Just verify it returns what we expect - expect(commands.getAllSlashCommands(mockAssistant)).toEqual( - expect.arrayContaining([ - expect.objectContaining({ name: "help" }), - expect.objectContaining({ name: "login" }), - ]), - ); }); - afterEach(() => { - Object.assign(console, originalConsole); - }); + describe("handleSlashCommands", () => { + it("should handle /info command when not authenticated", async () => { + const { isAuthenticated } = await import("./auth/workos.js"); + const { services } = await import("./services/index.js"); - describe("Automatic Service Cascade Reloading", () => { - test.skip("login command should trigger automatic cascade reload via auth service", async () => { - const newAuthState: AuthServiceState = { - authConfig: { userEmail: "test@example.com" } as any, - isAuthenticated: true, + ( + isAuthenticated as MockedFunction + ).mockReturnValue(false); + ( + services.config.getState as MockedFunction< + typeof services.config.getState + > + ).mockReturnValue({ + config: null, + configPath: "/test/config.yaml", + } as ConfigServiceState); + + const result = await handleSlashCommands("/info", mockAssistant); + + expect(result).toBeDefined(); + expect(result?.output).toContain("Authentication:"); + expect(result?.output).toContain("Not logged in"); + expect(result?.output).toContain("Configuration:"); + expect(result?.output).toContain("/test/config.yaml"); + expect(result?.output).toContain("Session History:"); + expect(result?.output).toContain(".json"); + expect(result?.exit).toBe(false); + }); + + it("should handle /info command when authenticated via environment", async () => { + const { isAuthenticated, loadAuthConfig, isAuthenticatedConfig } = + await import("./auth/workos.js"); + const { services } = await import("./services/index.js"); + + ( + isAuthenticated as MockedFunction + ).mockReturnValue(true); + (loadAuthConfig as MockedFunction).mockReturnValue( + {} as AuthConfig, + ); + (isAuthenticatedConfig as any).mockReturnValue(false); + ( + services.config.getState as MockedFunction< + typeof services.config.getState + > + ).mockReturnValue({ + config: null, + configPath: undefined, + } as ConfigServiceState); + + const result = await handleSlashCommands("/info", mockAssistant); + + expect(result).toBeDefined(); + expect(result?.output).toContain("Authentication:"); + expect(result?.output).toContain( + "Authenticated via environment variable", + ); + expect(result?.output).toContain("Configuration:"); + expect(result?.output).toContain("Config not found"); + expect(result?.exit).toBe(false); + }); + + it("should handle /info command when authenticated with user config", async () => { + const { isAuthenticated, loadAuthConfig, isAuthenticatedConfig } = + await import("./auth/workos.js"); + const { services } = await import("./services/index.js"); + + const mockAuthConfig: AuthenticatedConfig = { + userId: "test-user-id", + userEmail: "test@example.com", + accessToken: "test-token", + refreshToken: "test-refresh-token", + expiresAt: Date.now() + 3600000, + organizationId: "test-org-id", }; - (services.auth.login as any).mockResolvedValue(newAuthState); - (workos.isAuthenticatedConfig as any).mockReturnValue(true); - (reloadService as any).mockResolvedValue(undefined); + ( + isAuthenticated as MockedFunction + ).mockReturnValue(true); + (loadAuthConfig as MockedFunction).mockReturnValue( + mockAuthConfig, + ); + (isAuthenticatedConfig as any).mockReturnValue(true); + ( + services.config.getState as MockedFunction< + typeof services.config.getState + > + ).mockReturnValue({ + config: null, + configPath: "/custom/config.yaml", + } as ConfigServiceState); - const result = await handleSlashCommands("/login", mockAssistant); + const result = await handleSlashCommands("/info", mockAssistant); - expect(result).not.toBeNull(); - expect(result?.output).toContain( - "Login successful! All services updated automatically.", + expect(result).toBeDefined(); + expect(result?.output).toContain("Authentication:"); + expect(result?.output).toContain("test@example.com"); + expect(result?.output).toContain("(no org)"); + expect(result?.output).toContain("Configuration:"); + expect(result?.output).toContain("/custom/config.yaml"); + expect(result?.exit).toBe(false); + }); + + it("should handle config service errors gracefully", async () => { + const { isAuthenticated } = await import("./auth/workos.js"); + const { services } = await import("./services/index.js"); + + ( + isAuthenticated as MockedFunction + ).mockReturnValue(false); + ( + services.config.getState as MockedFunction< + typeof services.config.getState + > + ).mockImplementation(() => { + throw new Error("Service not ready"); + }); + + const result = await handleSlashCommands("/info", mockAssistant); + + expect(result).toBeDefined(); + expect(result?.output).toContain("Configuration service not available"); + }); + + it("should use test session directory when in test mode", async () => { + const { isAuthenticated } = await import("./auth/workos.js"); + const { services } = await import("./services/index.js"); + const { getSessionFilePath } = await import("./session.js"); + + // Mock the session path for this specific test + (getSessionFilePath as any).mockReturnValue( + "/test-home/.continue/cli-sessions/continue-cli-test-123.json", ); - // Verify auth service login was called - expect(services.auth.login).toHaveBeenCalledTimes(1); + ( + isAuthenticated as MockedFunction + ).mockReturnValue(false); + ( + services.config.getState as MockedFunction< + typeof services.config.getState + > + ).mockReturnValue({ + config: null, + configPath: undefined, + } as ConfigServiceState); - // Verify automatic cascade reload was triggered - only auth service reload needed - expect(reloadService).toHaveBeenCalledTimes(1); - expect(reloadService).toHaveBeenCalledWith(SERVICE_NAMES.AUTH); + const result = await handleSlashCommands("/info", mockAssistant); - // Verify manual service reloads are NOT called - expect(reloadService).not.toHaveBeenCalledWith(SERVICE_NAMES.API_CLIENT); - expect(reloadService).not.toHaveBeenCalledWith(SERVICE_NAMES.CONFIG); - }); - - test.skip("login failure should not trigger any reloads", async () => { - const loginError = new Error("Login failed"); - (services.auth.login as any).mockRejectedValue(loginError); - - const result = await handleSlashCommands("/login", mockAssistant); - - expect(result).not.toBeNull(); - expect(result?.output).toContain("Login failed: Login failed"); - - // Verify NO reload was triggered on failure - expect(reloadService).not.toHaveBeenCalled(); - }); - }); - - describe("Other Commands (unchanged behavior)", () => { - test("help command should work normally", async () => { - const result = await handleSlashCommands("/help", mockAssistant); - - expect(result).not.toBeNull(); - expect(result?.output).toContain("Slash commands:"); - expect(result?.output).toContain("/help: Show help"); - expect(result?.output).toContain("/login: Authenticate"); - }); - - test.skip("logout command should exit", async () => { - const logoutState: AuthServiceState = { - authConfig: null, - isAuthenticated: false, - }; - (services.auth.logout as any).mockResolvedValue(logoutState); - - const result = await handleSlashCommands("/logout", mockAssistant); - - expect(result).not.toBeNull(); - expect(result?.exit).toBe(true); - expect(result?.output).toContain("Logged out successfully"); - }); - - test("clear command should work normally", async () => { - const result = await handleSlashCommands("/clear", mockAssistant); - - expect(result).not.toBeNull(); - expect(result?.clear).toBe(true); - expect(result?.output).toBe("Chat history cleared"); - }); - - test("compact command should work normally", async () => { - const result = await handleSlashCommands("/compact", mockAssistant); - - expect(result).not.toBeNull(); - expect(result?.compact).toBe(true); - }); - - test("resume command should open session selector", async () => { - const result = await handleSlashCommands("/resume", mockAssistant); - - expect(result).not.toBeNull(); - expect(result?.openSessionSelector).toBe(true); - }); - - test("non-slash input should return null", async () => { - const result = await handleSlashCommands("regular input", mockAssistant); - expect(result).toBeNull(); - }); - - test("unknown slash command should return null", async () => { - const result = await handleSlashCommands("/unknown", mockAssistant); - - expect(result).toBeNull(); + expect(result?.output).toContain("/test-home/.continue/cli-sessions/"); + expect(result?.output).toContain(".json"); }); }); }); diff --git a/extensions/cli/src/slashCommands.ts b/extensions/cli/src/slashCommands.ts index c88d8f13f..dc24c30bc 100644 --- a/extensions/cli/src/slashCommands.ts +++ b/extensions/cli/src/slashCommands.ts @@ -8,6 +8,7 @@ import { } from "./auth/workos.js"; import { getAllSlashCommands } from "./commands/commands.js"; import { reloadService, SERVICE_NAMES, services } from "./services/index.js"; +import { getSessionFilePath } from "./session.js"; import { posthogService } from "./telemetry/posthogService.js"; import { SlashCommandResult } from "./ui/hooks/useChat.types.js"; @@ -96,6 +97,63 @@ function handleWhoami() { } } +async function handleInfo() { + posthogService.capture("useSlashCommand", { name: "info" }); + + const infoLines = []; + + // Auth info + if (isAuthenticated()) { + const config = loadAuthConfig(); + if (config && isAuthenticatedConfig(config)) { + const email = config.userEmail || config.userId; + const org = "(no org)"; // Organization info not available in AuthenticatedConfig + infoLines.push(chalk.white("Authentication:")); + infoLines.push(` Email: ${chalk.green(email)}`); + infoLines.push(` Organization: ${chalk.cyan(org)}`); + } else { + infoLines.push(chalk.white("Authentication:")); + infoLines.push( + ` ${chalk.yellow("Authenticated via environment variable")}`, + ); + } + } else { + infoLines.push(chalk.white("Authentication:")); + infoLines.push(` ${chalk.red("Not logged in")}`); + } + + // Config info + try { + const configState = services.config.getState(); + infoLines.push(""); + infoLines.push(chalk.white("Configuration:")); + if (configState.config) { + infoLines.push(` ${chalk.gray(`Using ${configState.config?.name}`)}`); + } else { + infoLines.push(` ${chalk.red(`Config not found`)}`); + } + if (configState.configPath) { + infoLines.push(` Path: ${chalk.blue(configState.configPath)}`); + } + } catch { + infoLines.push(""); + infoLines.push(chalk.white("Configuration:")); + infoLines.push(` ${chalk.red("Configuration service not available")}`); + } + + // Session history path + infoLines.push(""); + infoLines.push(chalk.white("Session History:")); + const sessionFilePath = getSessionFilePath(); + + infoLines.push(` File: ${chalk.blue(sessionFilePath)}`); + + return { + exit: false, + output: infoLines.join("\n"), + }; +} + const commandHandlers: Record = { help: handleHelp, clear: () => { @@ -113,6 +171,7 @@ const commandHandlers: Record = { login: handleLogin, logout: handleLogout, whoami: handleWhoami, + info: handleInfo, model: () => ({ openModelSelector: true }), compact: () => { posthogService.capture("useSlashCommand", { name: "compact" }); diff --git a/extensions/cli/src/streamChatResponse.autoCompaction.test.ts b/extensions/cli/src/streamChatResponse.autoCompaction.test.ts new file mode 100644 index 000000000..bfc9daae6 --- /dev/null +++ b/extensions/cli/src/streamChatResponse.autoCompaction.test.ts @@ -0,0 +1,225 @@ +import { ChatCompletionMessageParam } from "openai/resources.mjs"; +import { describe, it, expect, vi, beforeEach } from "vitest"; + +import { handleAutoCompaction } from "./streamChatResponse.autoCompaction.js"; + +// Mock dependencies +vi.mock("./compaction.js", () => ({ + compactChatHistory: vi.fn(), +})); + +vi.mock("./session.js", () => ({ + saveSession: vi.fn(), +})); + +vi.mock("./util/tokenizer.js", () => ({ + shouldAutoCompact: vi.fn(), + getAutoCompactMessage: vi.fn(), +})); + +vi.mock("./util/formatError.js", () => ({ + formatError: vi.fn((error) => error.message || String(error)), +})); + +vi.mock("./util/logger.js", () => ({ + logger: { + info: vi.fn(), + debug: vi.fn(), + error: vi.fn(), + warn: vi.fn(), + }, +})); + +describe("handleAutoCompaction", () => { + const mockModel = { + provider: "openai", + name: "gpt-4", + model: "gpt-4", + defaultCompletionOptions: { + contextLength: 8192, + maxTokens: 2048, + }, + } as any; + + const mockLlmApi = {} as any; + const mockChatHistory: ChatCompletionMessageParam[] = [ + { role: "system", content: "You are a helpful assistant." }, + { role: "user", content: "Hello" }, + { role: "assistant", content: "Hi there!" }, + ]; + + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("should return original history when auto-compaction is not needed", async () => { + const { shouldAutoCompact } = await import("./util/tokenizer.js"); + vi.mocked(shouldAutoCompact).mockReturnValue(false); + + const result = await handleAutoCompaction( + mockChatHistory, + mockModel, + mockLlmApi, + {}, + ); + + expect(result).toEqual({ + chatHistory: mockChatHistory, + compactionIndex: null, + }); + + expect(shouldAutoCompact).toHaveBeenCalledWith(mockChatHistory, mockModel); + }); + + it("should perform auto-compaction when context limit is approaching", async () => { + const { shouldAutoCompact, getAutoCompactMessage } = await import( + "./util/tokenizer.js" + ); + const { compactChatHistory } = await import("./compaction.js"); + const { saveSession } = await import("./session.js"); + + vi.mocked(shouldAutoCompact).mockReturnValue(true); + vi.mocked(getAutoCompactMessage).mockReturnValue("Auto-compacting..."); + + const mockCompactionResult = { + compactedHistory: [ + { + role: "system", + content: "You are a helpful assistant.", + } as ChatCompletionMessageParam, + { + role: "assistant", + content: "[COMPACTED HISTORY]\nConversation summary...", + } as ChatCompletionMessageParam, + ], + compactionIndex: 1, + compactionContent: "Conversation summary...", + }; + + vi.mocked(compactChatHistory).mockResolvedValue(mockCompactionResult); + + const mockCallbacks = { + onSystemMessage: vi.fn(), + }; + + const result = await handleAutoCompaction( + mockChatHistory, + mockModel, + mockLlmApi, + { + isHeadless: false, + callbacks: mockCallbacks, + }, + ); + + expect(shouldAutoCompact).toHaveBeenCalledWith(mockChatHistory, mockModel); + expect(getAutoCompactMessage).toHaveBeenCalledWith(mockModel); + expect(compactChatHistory).toHaveBeenCalledWith( + mockChatHistory, + mockModel, + mockLlmApi, + expect.any(Object), + ); + expect(saveSession).toHaveBeenCalledWith( + mockCompactionResult.compactedHistory, + ); + + expect(mockCallbacks.onSystemMessage).toHaveBeenCalledWith( + "Auto-compacting...", + ); + expect(mockCallbacks.onSystemMessage).toHaveBeenCalledWith( + "✓ Chat history auto-compacted successfully.", + ); + + expect(result).toEqual({ + chatHistory: mockCompactionResult.compactedHistory, + compactionIndex: mockCompactionResult.compactionIndex, + }); + }); + + it("should handle compaction errors gracefully", async () => { + const { shouldAutoCompact, getAutoCompactMessage } = await import( + "./util/tokenizer.js" + ); + const { compactChatHistory } = await import("./compaction.js"); + const { logger } = await import("./util/logger.js"); + + vi.mocked(shouldAutoCompact).mockReturnValue(true); + vi.mocked(getAutoCompactMessage).mockReturnValue("Auto-compacting..."); + vi.mocked(compactChatHistory).mockRejectedValue( + new Error("Compaction failed"), + ); + + const mockCallbacks = { + onSystemMessage: vi.fn(), + }; + + const result = await handleAutoCompaction( + mockChatHistory, + mockModel, + mockLlmApi, + { + isHeadless: false, + callbacks: mockCallbacks, + }, + ); + + expect(logger.error).toHaveBeenCalledWith( + expect.stringContaining("Auto-compaction error"), + ); + expect(mockCallbacks.onSystemMessage).toHaveBeenCalledWith( + expect.stringContaining("Warning: Auto-compaction error"), + ); + + // Should return original history on error + expect(result).toEqual({ + chatHistory: mockChatHistory, + compactionIndex: null, + }); + }); + + it("should not call system message callback in headless mode", async () => { + const { shouldAutoCompact, getAutoCompactMessage } = await import( + "./util/tokenizer.js" + ); + const { compactChatHistory } = await import("./compaction.js"); + + vi.mocked(shouldAutoCompact).mockReturnValue(true); + vi.mocked(getAutoCompactMessage).mockReturnValue("Auto-compacting..."); + + const mockCompactionResult = { + compactedHistory: [ + { role: "system", content: "System" } as ChatCompletionMessageParam, + ], + compactionIndex: 0, + compactionContent: "Summary", + }; + + vi.mocked(compactChatHistory).mockResolvedValue(mockCompactionResult); + + const mockCallbacks = { + onSystemMessage: vi.fn(), + }; + + await handleAutoCompaction(mockChatHistory, mockModel, mockLlmApi, { + isHeadless: true, + callbacks: mockCallbacks, + }); + + expect(mockCallbacks.onSystemMessage).not.toHaveBeenCalled(); + }); + + it("should handle missing model gracefully", async () => { + const result = await handleAutoCompaction( + mockChatHistory, + null as any, + mockLlmApi, + {}, + ); + + expect(result).toEqual({ + chatHistory: mockChatHistory, + compactionIndex: null, + }); + }); +}); diff --git a/extensions/cli/src/streamChatResponse.autoCompaction.ts b/extensions/cli/src/streamChatResponse.autoCompaction.ts new file mode 100644 index 000000000..ee9336250 --- /dev/null +++ b/extensions/cli/src/streamChatResponse.autoCompaction.ts @@ -0,0 +1,180 @@ +import { ModelConfig } from "@continuedev/config-yaml"; +import { BaseLlmApi } from "@continuedev/openai-adapters"; +import type { ChatCompletionMessageParam } from "openai/resources.mjs"; +import React from "react"; + +import { compactChatHistory } from "./compaction.js"; +import { saveSession } from "./session.js"; +import { DisplayMessage } from "./ui/types.js"; +import { formatError } from "./util/formatError.js"; +import { logger } from "./util/logger.js"; +import { getAutoCompactMessage, shouldAutoCompact } from "./util/tokenizer.js"; + +interface AutoCompactionCallbacks { + // For streaming mode + onSystemMessage?: (message: string) => void; + onContent?: (content: string) => void; + + // For TUI mode + setMessages?: React.Dispatch>; + setChatHistory?: React.Dispatch< + React.SetStateAction + >; + setCompactionIndex?: React.Dispatch>; + + // For headless mode - no callbacks needed, just return values +} + +interface AutoCompactionOptions { + isHeadless?: boolean; + format?: "json"; + callbacks?: AutoCompactionCallbacks; +} + +/** + * Notify user about compaction start + */ +function notifyCompactionStart( + message: string, + isHeadless: boolean, + callbacks?: AutoCompactionCallbacks, +) { + if (isHeadless) return; + + if (callbacks?.onSystemMessage) { + callbacks.onSystemMessage(message); + } else if (callbacks?.setMessages) { + callbacks.setMessages((prev) => [ + ...prev, + { + role: "system", + content: message, + messageType: "system" as const, + }, + ]); + } +} + +/** + * Handle successful compaction state updates + */ +function handleCompactionSuccess( + result: any, + isHeadless: boolean, + callbacks?: AutoCompactionCallbacks, +) { + if (isHeadless) return; + + const successMessage = "✓ Chat history auto-compacted successfully."; + + if (callbacks?.onSystemMessage) { + callbacks.onSystemMessage(successMessage); + } else if ( + callbacks?.setMessages && + callbacks?.setChatHistory && + callbacks?.setCompactionIndex + ) { + callbacks.setChatHistory(result.compactedHistory); + callbacks.setCompactionIndex(result.compactionIndex); + callbacks.setMessages((prev) => [ + ...prev, + { + role: "system", + content: successMessage, + messageType: "system" as const, + }, + ]); + } +} + +/** + * Handle compaction error notification + */ +function handleCompactionError( + error: any, + isHeadless: boolean, + callbacks?: AutoCompactionCallbacks, +) { + const errorMessage = `Auto-compaction error: ${formatError(error)}`; + logger.error(errorMessage); + + if (isHeadless) return; + + const warningMessage = `Warning: ${errorMessage}. Continuing without compaction...`; + + if (callbacks?.onSystemMessage) { + callbacks.onSystemMessage(warningMessage); + } else if (callbacks?.setMessages) { + callbacks.setMessages((prev) => [ + ...prev, + { + role: "system", + content: warningMessage, + messageType: "system" as const, + }, + ]); + } +} + +/** + * Unified auto-compaction handler for all modes (streaming, TUI, headless) + * @param chatHistory Current chat history + * @param model Model configuration + * @param llmApi LLM API instance + * @param options Configuration options for different usage contexts + * @returns Updated chat history and compaction index, or original if no compaction needed + */ +export async function handleAutoCompaction( + chatHistory: ChatCompletionMessageParam[], + model: ModelConfig, + llmApi: BaseLlmApi, + options: AutoCompactionOptions = {}, +): Promise<{ + chatHistory: ChatCompletionMessageParam[]; + compactionIndex: number | null; +}> { + const { isHeadless = false, callbacks } = options; + + if (!model || !shouldAutoCompact(chatHistory, model)) { + return { chatHistory, compactionIndex: null }; + } + + logger.info( + `Auto-compaction triggered${isHeadless ? " in headless mode" : ""}`, + ); + + // Notify about compaction start + notifyCompactionStart(getAutoCompactMessage(model), isHeadless, callbacks); + + try { + // Compact the history + const result = await compactChatHistory( + chatHistory, + model, + llmApi, + isHeadless + ? undefined + : { + onStreamContent: callbacks?.onContent, + onStreamComplete: () => {}, + }, + ); + + // Save the compacted session + saveSession(result.compactedHistory); + + // Handle success notification + handleCompactionSuccess(result, isHeadless, callbacks); + + return { + chatHistory: result.compactedHistory, + compactionIndex: result.compactionIndex, + }; + } catch (error: any) { + // Handle error notification + handleCompactionError(error, isHeadless, callbacks); + + // Continue without compaction on error + return { chatHistory, compactionIndex: null }; + } +} diff --git a/extensions/cli/src/streamChatResponse.ts b/extensions/cli/src/streamChatResponse.ts index fd8cf4b96..ab9d0c507 100644 --- a/extensions/cli/src/streamChatResponse.ts +++ b/extensions/cli/src/streamChatResponse.ts @@ -15,6 +15,7 @@ import { SERVICE_NAMES, } from "./services/index.js"; import type { ToolPermissionServiceState } from "./services/ToolPermissionService.js"; +import { handleAutoCompaction } from "./streamChatResponse.autoCompaction.js"; import { executeStreamedToolCalls, preprocessStreamedToolCalls, @@ -513,6 +514,24 @@ export async function streamChatResponse( return finalResponse || content || fullResponse; } + // Check for auto-compaction after tool execution + if (shouldContinue) { + const { chatHistory: updatedChatHistory, compactionIndex } = + await handleAutoCompaction(chatHistory, model, llmApi, { + isHeadless, + callbacks: { + onSystemMessage: callbacks?.onSystemMessage, + onContent: callbacks?.onContent, + }, + }); + + // Only update chat history if compaction actually occurred + if (compactionIndex !== null && updatedChatHistory !== chatHistory) { + chatHistory.length = 0; + chatHistory.push(...updatedChatHistory); + } + } + // Check if we should continue if (!shouldContinue) { break; diff --git a/extensions/cli/src/streamChatResponse.types.ts b/extensions/cli/src/streamChatResponse.types.ts index 6519e0e48..ff273872a 100644 --- a/extensions/cli/src/streamChatResponse.types.ts +++ b/extensions/cli/src/streamChatResponse.types.ts @@ -15,6 +15,7 @@ export interface StreamCallbacks { requestId: string, preview?: ToolCallPreview[], ) => void; + onSystemMessage?: (message: string) => void; } export function getDefaultCompletionOptions( diff --git a/extensions/cli/src/systemMessage.test.ts b/extensions/cli/src/systemMessage.test.ts index b76f4fb61..895234c9b 100644 --- a/extensions/cli/src/systemMessage.test.ts +++ b/extensions/cli/src/systemMessage.test.ts @@ -11,11 +11,11 @@ vi.mock("./services/ServiceContainer.js", () => ({ }, })); -// Mock processRule to avoid file system operations in tests +// Mock processPromptOrRule to avoid file system operations in tests vi.mock("./args.js", () => ({ - processRule: vi + processPromptOrRule: vi .fn() - .mockImplementation((rule: string) => Promise.resolve(rule)), + .mockImplementation((spec: string) => Promise.resolve(spec)), })); describe("constructSystemMessage", () => { @@ -146,4 +146,105 @@ Rule 3: Third rule`; expect(result).not.toContain("IMPORTANT: You are running in headless mode"); expect(result).not.toContain("Provide ONLY your final answer"); }); + + it("should add JSON format instructions when format is json", async () => { + const result = await constructSystemMessage(undefined, "json"); + + expect(result).toContain("You are an agent in the Continue CLI"); + expect(result).toContain( + "IMPORTANT: You are operating in JSON output mode", + ); + expect(result).toContain("Your final response MUST be valid JSON"); + expect(result).toContain("JSON.parse()"); + }); + + it("should add plan mode instructions when mode is plan", async () => { + const result = await constructSystemMessage( + undefined, + undefined, + false, + "plan", + ); + + expect(result).toContain("You are an agent in the Continue CLI"); + expect(result).toContain("PLAN MODE: You are operating in plan mode"); + expect(result).toContain( + "which means that your goal is to help the user investigate their ideas", + ); + expect(result).toContain("develop a plan before taking action"); + expect(result).toContain("read-only tools"); + expect(result).toContain( + "should not attempt to circumvent them to write / delete / create files", + ); + }); + + it("should not add plan mode instructions when mode is not plan", async () => { + const result = await constructSystemMessage( + undefined, + undefined, + false, + "normal", + ); + + expect(result).toContain("You are an agent in the Continue CLI"); + expect(result).not.toContain("PLAN MODE: You are operating in plan mode"); + expect(result).not.toContain( + "which means that your goal is to help the user investigate their ideas", + ); + }); + + it("should not add plan mode instructions when mode is undefined", async () => { + const result = await constructSystemMessage(); + + expect(result).toContain("You are an agent in the Continue CLI"); + expect(result).not.toContain("PLAN MODE: You are operating in plan mode"); + expect(result).not.toContain( + "which means that your goal is to help the user investigate their ideas", + ); + }); + + it("should include basic plan mode description", async () => { + const result = await constructSystemMessage( + undefined, + undefined, + false, + "plan", + ); + + expect(result).toContain("PLAN MODE: You are operating in plan mode"); + expect(result).toContain("read-only tools"); + expect(result).toContain("write / delete / create files"); + }); + + it("should combine plan mode with headless mode instructions", async () => { + const result = await constructSystemMessage( + undefined, + undefined, + true, + "plan", + ); + + expect(result).toContain("IMPORTANT: You are running in headless mode"); + expect(result).toContain("PLAN MODE: You are operating in plan mode"); + expect(result).toContain( + "which means that your goal is to help the user investigate their ideas", + ); + }); + + it("should combine plan mode with JSON format instructions", async () => { + const result = await constructSystemMessage( + undefined, + "json", + false, + "plan", + ); + + expect(result).toContain( + "IMPORTANT: You are operating in JSON output mode", + ); + expect(result).toContain("PLAN MODE: You are operating in plan mode"); + expect(result).toContain( + "which means that your goal is to help the user investigate their ideas", + ); + }); }); diff --git a/extensions/cli/src/systemMessage.ts b/extensions/cli/src/systemMessage.ts index 1f09ff5c6..77742956d 100644 --- a/extensions/cli/src/systemMessage.ts +++ b/extensions/cli/src/systemMessage.ts @@ -5,7 +5,9 @@ import * as path from "path"; import pkg from "ignore-walk"; import { Minimatch } from "minimatch"; -import { processRule } from "./args.js"; +import { processPromptOrRule } from "./args.js"; +import { PermissionMode } from "./permissions/types.js"; +import { modeService } from "./services/ModeService.js"; import { serviceContainer } from "./services/ServiceContainer.js"; import { ConfigServiceState, SERVICE_NAMES } from "./services/types.js"; const { WalkerSync } = pkg; @@ -116,16 +118,17 @@ async function getConfigYamlRules(): Promise { /** * Load and construct a comprehensive system message with base message and rules section - * @param rulesSystemMessage - The rules system message from the assistant * @param additionalRules - Additional rules from --rule flags * @param format - Output format for headless mode * @param headless - Whether running in headless mode + * @param mode - Current permission mode * @returns The comprehensive system message with base message and rules section */ export async function constructSystemMessage( additionalRules?: string[], format?: "json", headless?: boolean, + mode?: PermissionMode, ): Promise { const agentFiles = ["AGENTS.md", "AGENT.md", "CLAUDE.md", "CODEX.md"]; @@ -150,7 +153,7 @@ export async function constructSystemMessage( if (additionalRules && additionalRules.length > 0) { for (const ruleSpec of additionalRules) { try { - const processedRule = await processRule(ruleSpec); + const processedRule = await processPromptOrRule(ruleSpec); processedRules.push(processedRule); } catch (error: any) { console.warn( @@ -163,6 +166,9 @@ export async function constructSystemMessage( const configYamlRules = await getConfigYamlRules(); processedRules.push(...configYamlRules); + // Get current mode if not provided + const currentMode = mode ?? modeService.getCurrentMode(); + // Construct the comprehensive system message let systemMessage = baseSystemMessage; @@ -185,6 +191,13 @@ Example response format: }`; } + // Add plan mode specific instructions if in plan mode + if (currentMode === "plan") { + systemMessage += ` + +PLAN MODE: You are operating in plan mode, which means that your goal is to help the user investigate their ideas and develop a plan before taking action. You only have access to read-only tools and should not attempt to circumvent them to write / delete / create files.`; + } + // Add rules section if we have any rules or agent content if (agentContent || processedRules.length > 0) { systemMessage += '\n\n'; diff --git a/extensions/cli/src/test-helpers/ui-test-context.ts b/extensions/cli/src/test-helpers/ui-test-context.ts index 5eeda611d..a8eae59f3 100644 --- a/extensions/cli/src/test-helpers/ui-test-context.ts +++ b/extensions/cli/src/test-helpers/ui-test-context.ts @@ -72,7 +72,7 @@ export function createUITestContext( responseStartTime: null, inputMode: true, attachedFiles: [], - handleUserMessage: vi.fn(), + handleUserMessage: vi.fn().mockResolvedValue(undefined), handleInterrupt: vi.fn(), handleFileAttached: vi.fn(), resetChatHistory: vi.fn(), diff --git a/extensions/cli/src/tools/readFile.ts b/extensions/cli/src/tools/readFile.ts index f7258a3bf..80a6bbe62 100644 --- a/extensions/cli/src/tools/readFile.ts +++ b/extensions/cli/src/tools/readFile.ts @@ -39,6 +39,13 @@ export const readFileTool: Tool = { const content = fs.readFileSync(args.filepath, "utf-8"); // Mark this file as read for the edit tool markFileAsRead(args.filepath); + + const lines = content.split("\n"); + if (lines.length > 5000) { + const truncatedContent = lines.slice(0, 5000).join("\n"); + return `Content of ${args.filepath} (truncated to first 5000 lines of ${lines.length} total):\n${truncatedContent}`; + } + return `Content of ${args.filepath}:\n${content}`; } catch (error) { return `Error reading file: ${ diff --git a/extensions/cli/src/ui/AppRoot.tsx b/extensions/cli/src/ui/AppRoot.tsx index 8f2c1c193..f6cef3c20 100644 --- a/extensions/cli/src/ui/AppRoot.tsx +++ b/extensions/cli/src/ui/AppRoot.tsx @@ -9,6 +9,7 @@ interface AppRootProps { initialPrompt?: string; resume?: boolean; additionalRules?: string[]; + additionalPrompts?: string[]; } /** diff --git a/extensions/cli/src/ui/IntroMessage.test.tsx b/extensions/cli/src/ui/IntroMessage.test.tsx new file mode 100644 index 000000000..fd336bf8b --- /dev/null +++ b/extensions/cli/src/ui/IntroMessage.test.tsx @@ -0,0 +1,166 @@ +import { AssistantUnrolled } from "@continuedev/config-yaml"; +import { render } from "ink-testing-library"; +import React from "react"; +import { describe, expect, it, vi } from "vitest"; + +import { IntroMessage } from "./IntroMessage.js"; + +// Mock the MCPService +vi.mock("../services/MCPService.js", () => ({ + MCPService: vi.fn().mockImplementation(() => ({ + getState: () => ({ prompts: [] }), + })), +})); + +// Mock the model capability check +vi.mock("../utils/modelCapability.js", () => ({ + isModelCapable: vi.fn().mockReturnValue(true), +})); + +describe("IntroMessage", () => { + const mockMcpService = { + getState: () => ({ prompts: [] }), + } as any; + + const mockModel = { + provider: "anthropic", + name: "claude-3-sonnet", + model: "claude-3-sonnet", + } as any; + + it("should not duplicate rules from command line", () => { + // Config with rules that were already injected from command line + // Hub rules are stored as RuleObject with name and rule fields + const config: AssistantUnrolled = { + name: "Test Assistant", + rules: [ + { name: "nate/spanish", rule: "Always respond in Spanish." }, + "Always be helpful", + ], + } as any; + + const { lastFrame } = render( + , + ); + + const output = lastFrame(); + + // Count occurrences of "nate/spanish" in the output + const matches = output?.match(/nate\/spanish/g) || []; + + // Should appear exactly once, not twice + expect(matches.length).toBe(1); + + // Verify the slug is shown, not the content + expect(output).toContain("nate/spanish"); + expect(output).not.toContain("Always respond in Spanish"); + + // Verify plain string rule is shown as-is + expect(output).toContain("Always be helpful"); + }); + + it("should display rules from config correctly", () => { + const config: AssistantUnrolled = { + name: "Test Assistant", + rules: ["Rule 1", { name: "Rule 2" }, "Rule 3"], + } as any; + + const { lastFrame } = render( + , + ); + + const output = lastFrame(); + + expect(output).toContain("Rules:"); + expect(output).toContain("Rule 1"); + expect(output).toContain("Rule 2"); + expect(output).toContain("Rule 3"); + }); + + it("should not show Rules section when no rules exist", () => { + const config: AssistantUnrolled = { + name: "Test Assistant", + } as any; + + const { lastFrame } = render( + , + ); + + const output = lastFrame(); + + expect(output).not.toContain("Rules:"); + }); + + it("should handle rule objects with missing name property", () => { + const config: AssistantUnrolled = { + name: "Test Assistant", + rules: [ + "String rule", + { someOtherProp: "value" }, // Missing 'name' property + ], + } as any; + + const { lastFrame } = render( + , + ); + + const output = lastFrame(); + + expect(output).toContain("String rule"); + expect(output).toContain("Unknown"); // Should show "Unknown" for objects without name + }); + + it("should display hub rule slugs, not their content", () => { + const config: AssistantUnrolled = { + name: "Test Assistant", + rules: [ + { + name: "org/complex-rule", + rule: `--- +alwaysApply: true +--- + +This is a very long rule content that should not be displayed. +It contains multiple lines and complex formatting. +The UI should only show the slug 'org/complex-rule'.`, + }, + { name: "another/rule", rule: "Short content" }, + ], + } as any; + + const { lastFrame } = render( + , + ); + + const output = lastFrame(); + + // Should show slugs only + expect(output).toContain("org/complex-rule"); + expect(output).toContain("another/rule"); + + // Should NOT show the rule content + expect(output).not.toContain("This is a very long rule"); + expect(output).not.toContain("alwaysApply"); + expect(output).not.toContain("Short content"); + }); +}); diff --git a/extensions/cli/src/ui/IntroMessage.tsx b/extensions/cli/src/ui/IntroMessage.tsx index 68b133fba..ca987c1bb 100644 --- a/extensions/cli/src/ui/IntroMessage.tsx +++ b/extensions/cli/src/ui/IntroMessage.tsx @@ -2,7 +2,6 @@ import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; import { Box, Text } from "ink"; import React, { useMemo } from "react"; -import { parseArgs } from "../args.js"; import { MCPService } from "../services/MCPService.js"; import { isModelCapable } from "../utils/modelCapability.js"; @@ -24,15 +23,13 @@ const IntroMessage: React.FC = ({ // Memoize expensive operations to avoid running on every resize const { allRules, modelCapable } = useMemo(() => { - // Show all rules in a single section - const args = parseArgs(); - const commandLineRules = args.rules || []; + // Show all rules from config (command-line rules are already merged into config) const configRules = config.rules?.map((rule: any) => typeof rule === "string" ? rule : rule?.name || "Unknown", ) || []; - const allRules = [...commandLineRules, ...configRules]; + const allRules = configRules; // Check if model is capable - now checking both name and model properties const modelCapable = isModelCapable( diff --git a/extensions/cli/src/ui/SessionSelector.tsx b/extensions/cli/src/ui/SessionSelector.tsx index d1a34a2d2..e528a7da4 100644 --- a/extensions/cli/src/ui/SessionSelector.tsx +++ b/extensions/cli/src/ui/SessionSelector.tsx @@ -64,7 +64,7 @@ export function SessionSelector({ if (displaySessions[selectedIndex]) { onSelect(displaySessions[selectedIndex].id); } - } else if (key.escape || (key.ctrl && input === "c")) { + } else if (key.escape || (key.ctrl && input === "d")) { onExit(); } }); diff --git a/extensions/cli/src/ui/TUIChat.tsx b/extensions/cli/src/ui/TUIChat.tsx index 6ef19ca08..5e39f6e12 100644 --- a/extensions/cli/src/ui/TUIChat.tsx +++ b/extensions/cli/src/ui/TUIChat.tsx @@ -1,5 +1,11 @@ import { Box, Text } from "ink"; -import React, { useMemo, useState } from "react"; +import React, { + useCallback, + useEffect, + useMemo, + useRef, + useState, +} from "react"; import { useServices } from "../hooks/useService.js"; import { @@ -9,8 +15,10 @@ import { MCPServiceState, ModelServiceState, } from "../services/types.js"; +import { logger } from "../util/logger.js"; import { BottomStatusBar } from "./components/BottomStatusBar.js"; +import { ResourceDebugBar } from "./components/ResourceDebugBar.js"; import { ScreenContent } from "./components/ScreenContent.js"; import { StaticChatContent } from "./components/StaticChatContent.js"; import { useNavigation } from "./context/NavigationContext.js"; @@ -36,23 +44,61 @@ interface TUIChatProps { initialPrompt?: string; resume?: boolean; additionalRules?: string[]; + additionalPrompts?: string[]; } -const TUIChat: React.FC = ({ - remoteUrl, - configPath, - initialPrompt, - resume, - additionalRules, -}) => { - // Check if we're in remote mode - const isRemoteMode = useMemo(() => { - return !!remoteUrl; - }, [remoteUrl]); +// Helper function to load and set session +async function loadAndSetSession( + sessionId: string, + closeCurrentScreen: () => void, + setChatHistory: (history: any) => void, + setMessages: (messages: any) => void, + setShowIntroMessage: (show: boolean) => void, +) { + try { + // Close the session selector + closeCurrentScreen(); - const repoURlText = useMemo(() => getRepoUrlText(remoteUrl), [remoteUrl]); + // Import session functions + const { loadSessionById } = await import("../session.js"); + + // Load the session history + const sessionHistory = loadSessionById(sessionId); + if (!sessionHistory) { + logger.error(`Session ${sessionId} could not be loaded.`); + return; + } + + // Set the session ID so future operations use this session + process.env.CONTINUE_CLI_TEST_SESSION_ID = sessionId.replace( + "continue-cli-", + "", + ); + + // Directly set the chat history and messages to the loaded session + setChatHistory(sessionHistory); + + // Convert chat history to display messages (exclude system messages) + const displayMessages = sessionHistory + .filter((msg: any) => msg.role !== "system") + .map((msg: any) => ({ + role: msg.role, + content: msg.content as string, + })); + + setMessages(displayMessages); + + // Clear the intro message since we're now showing a resumed session + setShowIntroMessage(false); + } catch (error) { + console.error("Error loading session:", error); + } +} + +// Custom hook to manage services +function useTUIChatServices(remoteUrl?: string) { + const isRemoteMode = useMemo(() => !!remoteUrl, [remoteUrl]); - // Get all services reactively - only in normal mode const { services, allReady: allServicesReady } = useServices<{ auth: AuthServiceState; config: ConfigServiceState; @@ -61,6 +107,57 @@ const TUIChat: React.FC = ({ apiClient: ApiClientServiceState; }>(["auth", "config", "model", "mcp", "apiClient"]); + return { services, allServicesReady, isRemoteMode }; +} + +// Custom hook for chat handlers +function useChatHandlers( + setShowIntroMessage: (show: boolean) => void, + setStaticRefreshTrigger: React.Dispatch>, +) { + // Temporary refs to avoid circular dependency + const resetChatHistoryRef = useRef<(() => void) | null>(null); + + // Handle clearing chat and resetting intro message + const handleClear = useCallback(() => { + setShowIntroMessage(true); + // Trigger static content refresh by incrementing the trigger + setStaticRefreshTrigger((prev) => prev + 1); + }, [setShowIntroMessage, setStaticRefreshTrigger]); + + // Service reload handlers - these will trigger reactive updates + const handleReload = useCallback(async () => { + // Services will automatically update the UI when they reload + // We just need to reset chat history, intro message, and clear the screen + if (resetChatHistoryRef.current) { + resetChatHistoryRef.current(); + } + setShowIntroMessage(false); + process.stdout.write("\x1b[2J\x1b[H"); + }, [setShowIntroMessage]); + + return { + handleClear, + handleReload, + resetChatHistoryRef, + }; +} + +// eslint-disable-next-line complexity +const TUIChat: React.FC = ({ + remoteUrl, + configPath, + initialPrompt, + resume, + additionalRules, + additionalPrompts, +}) => { + // Use custom hook for services + const { services, allServicesReady, isRemoteMode } = + useTUIChatServices(remoteUrl); + + const repoURlText = useMemo(() => getRepoUrlText(remoteUrl), [remoteUrl]); + // Use navigation context const { state: navState, @@ -86,24 +183,14 @@ const TUIChat: React.FC = ({ closeCurrentScreen, ); - // Service reload handlers - these will trigger reactive updates - const handleReload = async () => { - // Services will automatically update the UI when they reload - // We just need to reset chat history, intro message, and clear the screen - resetChatHistory(); - setShowIntroMessage(false); - process.stdout.write("\x1b[2J\x1b[H"); - }; - // State to trigger static content refresh for /clear command const [staticRefreshTrigger, setStaticRefreshTrigger] = useState(0); - // Handle clearing chat and resetting intro message - const handleClear = () => { - setShowIntroMessage(true); - // Trigger static content refresh by incrementing the trigger - setStaticRefreshTrigger((prev) => prev + 1); - }; + // Use chat handlers hook + const { handleClear, handleReload, resetChatHistoryRef } = useChatHandlers( + setShowIntroMessage, + setStaticRefreshTrigger, + ); const { messages, @@ -126,6 +213,7 @@ const TUIChat: React.FC = ({ initialPrompt, resume, additionalRules, + additionalPrompts, onShowConfigSelector: () => navigateTo("config"), onShowModelSelector: () => navigateTo("model"), onShowMCPSelector: () => navigateTo("mcp"), @@ -138,6 +226,11 @@ const TUIChat: React.FC = ({ remoteUrl, }); + // Update ref after useChat returns + useEffect(() => { + resetChatHistoryRef.current = resetChatHistory; + }, [resetChatHistory]); + // Calculate context percentage const contextData = useContextPercentage({ chatHistory, @@ -153,52 +246,27 @@ const TUIChat: React.FC = ({ ); // Session selection handler - const handleSessionSelect = async (sessionId: string) => { - try { - // Close the session selector - closeCurrentScreen(); - - // Import session functions - const { loadSessionById } = await import("../session.js"); - - // Load the session history - const sessionHistory = loadSessionById(sessionId); - if (!sessionHistory) { - console.error(`Session ${sessionId} could not be loaded.`); - return; - } - - // Set the session ID so future operations use this session - process.env.CONTINUE_CLI_TEST_SESSION_ID = sessionId.replace( - "continue-cli-", - "", + const handleSessionSelect = useCallback( + async (sessionId: string) => { + await loadAndSetSession( + sessionId, + closeCurrentScreen, + setChatHistory, + setMessages, + setShowIntroMessage, ); - - // Directly set the chat history and messages to the loaded session - setChatHistory(sessionHistory); - - // Convert chat history to display messages (exclude system messages) - const displayMessages = sessionHistory - .filter((msg) => msg.role !== "system") - .map((msg) => ({ - role: msg.role, - content: msg.content as string, - })); - - setMessages(displayMessages); - - // Clear the intro message since we're now showing a resumed session - setShowIntroMessage(false); - } catch (error) { - console.error("Error loading session:", error); - } - }; + }, + [closeCurrentScreen, setChatHistory, setMessages, setShowIntroMessage], + ); // Determine if input should be disabled // Allow input even when services are loading, but disable for UI overlays const isInputDisabled = navState.currentScreen !== "chat" || !!activePermissionRequest; + // Check if verbose mode is enabled for resource debugging + const isVerboseMode = useMemo(() => process.argv.includes("--verbose"), []); + return ( {/* Chat history - takes up all available space above input */} @@ -265,6 +333,11 @@ const TUIChat: React.FC = ({ isRemoteMode={isRemoteMode} /> + {/* Resource debug bar - only in verbose mode */} + {isVerboseMode && !isRemoteMode && ( + + )} + {/* Free trial status and Continue CLI info - always show */} = ({ return false; }; + // Clear input function + const clearInput = () => { + textBuffer.clear(); + setInputText(""); + setCursorPosition(0); + setShowSlashCommands(false); + setShowFileSearch(false); + inputHistory.resetNavigation(); + }; + useInput((input, key) => { // Don't handle any input when disabled if (disabled) { diff --git a/extensions/cli/src/ui/components/ResourceDebugBar.tsx b/extensions/cli/src/ui/components/ResourceDebugBar.tsx new file mode 100644 index 000000000..340edc757 --- /dev/null +++ b/extensions/cli/src/ui/components/ResourceDebugBar.tsx @@ -0,0 +1,184 @@ +import { Box, Text } from "ink"; +import React, { useEffect, useState } from "react"; + +import { services } from "../../services/index.js"; +import { ResourceUsage } from "../../services/ResourceMonitoringService.js"; + +interface ResourceDebugBarProps { + visible: boolean; +} + +function formatBytes(bytes: number): string { + const mb = bytes / 1024 / 1024; + return mb >= 1 ? `${mb.toFixed(1)}MB` : `${(bytes / 1024).toFixed(1)}KB`; +} + +function formatPercent(percent: number): string { + return `${Math.round(percent)}%`; +} + +function formatTime(ms: number): string { + if (ms < 1000) return `${Math.round(ms)}ms`; + return `${(ms / 1000).toFixed(1)}s`; +} + +export function ResourceDebugBar({ visible }: ResourceDebugBarProps) { + const [resourceData, setResourceData] = useState(null); + const [isError, setIsError] = useState(false); + + useEffect(() => { + if (!visible) return; + + const updateResourceData = () => { + try { + const usage = services.resourceMonitoring.getCurrentResourceUsage(); + setResourceData(usage); + setIsError(false); + } catch { + setIsError(true); + } + }; + + // Initial update + updateResourceData(); + + // Update every 2 seconds + const intervalId = setInterval(updateResourceData, 2000); + + return () => { + clearInterval(intervalId); + }; + }, [visible]); + + if (!visible) { + return null; + } + + if (isError) { + return ( + + Resource monitoring error + + ); + } + + if (!resourceData) { + return null; + } + + const memoryPercent = + (resourceData.memory.rss / resourceData.system.totalMemory) * 100; + const cpuPercent = resourceData.cpu.percent || 0; + const heapPercent = + (resourceData.memory.heapUsed / resourceData.memory.heapTotal) * 100; + + // Color coding based on usage levels + const getMemoryColor = () => { + if (memoryPercent > 80) return "red"; + if (memoryPercent > 60) return "yellow"; + return "green"; + }; + + const getCpuColor = () => { + if (cpuPercent > 80) return "red"; + if (cpuPercent > 60) return "yellow"; + return "green"; + }; + + const getEventLoopColor = () => { + if (resourceData.eventLoop.lag > 100) return "red"; + if (resourceData.eventLoop.lag > 50) return "yellow"; + return "green"; + }; + + return ( + + Debug: + + + MEM: {formatBytes(resourceData.memory.rss)} + + | + + HEAP: {formatPercent(heapPercent)} + | + + CPU: {formatPercent(cpuPercent)} + | + + + LAG: {formatTime(resourceData.eventLoop.lag)} + + + {resourceData.fileDescriptors && ( + <> + | + FD: {resourceData.fileDescriptors} + + )} + + | + + UP: {formatTime(resourceData.system.uptime * 1000)} + + + ); +} + +export function ResourceDebugDetails({ visible }: { visible: boolean }) { + const [summary, setSummary] = useState(null); + + useEffect(() => { + if (!visible) return; + + const updateData = () => { + try { + const summaryData = services.resourceMonitoring.getResourceSummary(); + setSummary(summaryData); + } catch { + // Handle error silently + } + }; + + updateData(); + const intervalId = setInterval(updateData, 3000); + + return () => clearInterval(intervalId); + }, [visible]); + + if (!visible || !summary) { + return null; + } + + return ( + + + Resource Usage Summary + + + + Current: + {formatBytes(summary.current.memory.rss)} mem, + {formatPercent(summary.current.cpu.percent || 0)} cpu + + + + Peak: + {formatBytes(summary.peak.memory)} mem, + {formatPercent(summary.peak.cpu)} cpu + + + + Average: + {formatBytes(summary.average.memory)} mem, + {formatPercent(summary.average.cpu)} cpu + + + ); +} diff --git a/extensions/cli/src/ui/hooks/useChat.helpers.ts b/extensions/cli/src/ui/hooks/useChat.helpers.ts index 9649fac02..b8d77e028 100644 --- a/extensions/cli/src/ui/hooks/useChat.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.helpers.ts @@ -7,7 +7,6 @@ import { posthogService } from "../../telemetry/posthogService.js"; import { telemetryService } from "../../telemetry/telemetryService.js"; import { formatError } from "../../util/formatError.js"; import { logger } from "../../util/logger.js"; -import { shouldAutoCompact } from "../../util/tokenizer.js"; import { DisplayMessage } from "../types.js"; import { SlashCommandResult } from "./useChat.types.js"; @@ -278,13 +277,13 @@ interface HandleAutoCompactionOptions { } /** - * Handle auto-compaction when approaching context limit + * Handle auto-compaction when approaching context limit - TUI wrapper */ export async function handleAutoCompaction({ chatHistory, model, llmApi, - compactionIndex, + compactionIndex: _compactionIndex, setMessages, setChatHistory, setCompactionIndex, @@ -292,69 +291,21 @@ export async function handleAutoCompaction({ currentChatHistory: ChatCompletionMessageParam[]; currentCompactionIndex: number | null; }> { - if (!model || !shouldAutoCompact(chatHistory, model)) { - return { - currentChatHistory: chatHistory, - currentCompactionIndex: compactionIndex, - }; - } + const { handleAutoCompaction: coreAutoCompaction } = await import( + "../../streamChatResponse.autoCompaction.js" + ); - logger.info("Auto-compacting triggered in TUI mode"); - - setMessages((prev) => [ - ...prev, - { - role: "system", - content: "Approaching context limit. Auto-compacting chat history...", - messageType: "system" as const, + const result = await coreAutoCompaction(chatHistory, model, llmApi, { + isHeadless: false, + callbacks: { + setMessages, + setChatHistory, + setCompactionIndex, }, - ]); + }); - try { - if (!llmApi) { - throw new Error("LLM API is not available for auto-compaction"); - } - - // Compact the history WITHOUT the current user message - const result = await compactChatHistory(chatHistory, model, llmApi); - - // Update state - setChatHistory(result.compactedHistory); - setCompactionIndex(result.compactionIndex); - - // Save the compacted session - saveSession(result.compactedHistory); - - setMessages((prev) => [ - ...prev, - { - role: "system", - content: "✓ Chat history auto-compacted successfully.", - messageType: "system" as const, - }, - ]); - - return { - currentChatHistory: result.compactedHistory, - currentCompactionIndex: result.compactionIndex, - }; - } catch (error: any) { - const errorMessage = `Auto-compaction error: ${formatError(error)}`; - logger.error(errorMessage); - - setMessages((prev) => [ - ...prev, - { - role: "system", - content: `Warning: ${errorMessage}. Continuing without compaction...`, - messageType: "system" as const, - }, - ]); - - // Continue without compaction on error - return { - currentChatHistory: chatHistory, - currentCompactionIndex: compactionIndex, - }; - } + return { + currentChatHistory: result.chatHistory, + currentCompactionIndex: result.compactionIndex, + }; } diff --git a/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts b/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts index 810e849e5..d88177811 100644 --- a/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts @@ -111,6 +111,16 @@ export function createStreamCallbacks( toolCallPreview, }); }, + onSystemMessage: (message: string) => { + setMessages((prev) => [ + ...prev, + { + role: "system", + content: message, + messageType: "system" as const, + }, + ]); + }, }; } diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index 4a75c9a1f..a8b522260 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -42,6 +42,7 @@ export function useChat({ initialPrompt, resume, additionalRules, + additionalPrompts, onShowConfigSelector, onShowModelSelector, onShowMCPSelector, @@ -163,10 +164,27 @@ export function useChat({ useEffect(() => { // Only handle initial prompt after chat history is initialized // This prevents race conditions where the prompt runs before system message is loaded - if (initialPrompt && isChatHistoryInitialized) { - handleUserMessage(initialPrompt); + if ( + (initialPrompt || (additionalPrompts && additionalPrompts.length > 0)) && + isChatHistoryInitialized + ) { + const processPrompts = async () => { + const { processAndCombinePrompts } = await import( + "../../util/promptProcessor.js" + ); + const finalMessage = await processAndCombinePrompts( + additionalPrompts, + initialPrompt, + ); + + if (finalMessage) { + await handleUserMessage(finalMessage); + } + }; + + processPrompts().catch(console.error); } - }, [initialPrompt, isChatHistoryInitialized]); + }, [initialPrompt, additionalPrompts, isChatHistoryInitialized]); const executeStreamingResponse = async ( newHistory: ChatCompletionMessageParam[], diff --git a/extensions/cli/src/ui/hooks/useChat.types.ts b/extensions/cli/src/ui/hooks/useChat.types.ts index f0cca4978..fa752fed8 100644 --- a/extensions/cli/src/ui/hooks/useChat.types.ts +++ b/extensions/cli/src/ui/hooks/useChat.types.ts @@ -11,6 +11,7 @@ export interface UseChatProps { initialPrompt?: string; resume?: boolean; additionalRules?: string[]; + additionalPrompts?: string[]; onShowConfigSelector: () => void; onShowMCPSelector: () => void; onShowModelSelector?: () => void; diff --git a/extensions/cli/src/ui/index.ts b/extensions/cli/src/ui/index.ts index 848a74fe7..d36d289d6 100644 --- a/extensions/cli/src/ui/index.ts +++ b/extensions/cli/src/ui/index.ts @@ -13,9 +13,10 @@ export { MarkdownRenderer } from "./MarkdownRenderer.js"; interface StartTUIChatOptions { initialPrompt?: string; resume?: boolean; - configPath?: string; - organizationSlug?: string; - additionalRules?: string[]; + config?: string; + org?: string; + rule?: string[]; + prompt?: string[]; toolPermissionOverrides?: { allow?: string[]; ask?: string[]; @@ -31,9 +32,10 @@ export async function startTUIChat( const { initialPrompt, resume, - configPath, - organizationSlug, - additionalRules, + config, + org, + rule, + prompt, toolPermissionOverrides, skipOnboarding, customStdin, @@ -42,9 +44,7 @@ export async function startTUIChat( // Initialize services only if not already done (skipOnboarding means already initialized) if (!skipOnboarding) { await initializeServices({ - configPath, - organizationSlug, - rules: additionalRules, + options: { config, org, rule, prompt }, headless: false, toolPermissionOverrides, }); @@ -63,10 +63,11 @@ export async function startTUIChat( const { unmount } = render( React.createElement(ServiceContainerProvider, { children: React.createElement(AppRoot, { - configPath, + configPath: config, initialPrompt, resume, - additionalRules, + additionalRules: rule, + additionalPrompts: prompt, }), }), renderOptions, diff --git a/extensions/cli/src/util/promptProcessor.test.ts b/extensions/cli/src/util/promptProcessor.test.ts new file mode 100644 index 000000000..4644e17c8 --- /dev/null +++ b/extensions/cli/src/util/promptProcessor.test.ts @@ -0,0 +1,127 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +import * as args from "../args.js"; + +import { processAndCombinePrompts } from "./promptProcessor.js"; + +// Mock the args module +vi.mock("../args.js", () => ({ + processPromptOrRule: vi.fn(), +})); + +// Mock the logger +vi.mock("./logger.js", () => ({ + logger: { + warn: vi.fn(), + }, +})); + +describe("promptProcessor", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + describe("processAndCombinePrompts", () => { + it("should return initial prompt when no additional prompts", async () => { + const result = await processAndCombinePrompts(undefined, "initial"); + expect(result).toBe("initial"); + }); + + it("should return initial prompt when empty additional prompts array", async () => { + const result = await processAndCombinePrompts([], "initial"); + expect(result).toBe("initial"); + }); + + it("should return undefined when no prompts at all", async () => { + const result = await processAndCombinePrompts(); + expect(result).toBeUndefined(); + }); + + it("should process single additional prompt without initial", async () => { + const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule); + mockProcessPromptOrRule.mockResolvedValue("processed prompt"); + + const result = await processAndCombinePrompts(["prompt1"]); + + expect(mockProcessPromptOrRule).toHaveBeenCalledWith("prompt1"); + expect(result).toBe("processed prompt"); + }); + + it("should combine multiple processed prompts", async () => { + const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule); + mockProcessPromptOrRule + .mockResolvedValueOnce("first prompt") + .mockResolvedValueOnce("second prompt"); + + const result = await processAndCombinePrompts(["prompt1", "prompt2"]); + + expect(mockProcessPromptOrRule).toHaveBeenCalledTimes(2); + expect(mockProcessPromptOrRule).toHaveBeenNthCalledWith(1, "prompt1"); + expect(mockProcessPromptOrRule).toHaveBeenNthCalledWith(2, "prompt2"); + expect(result).toBe("first prompt\n\nsecond prompt"); + }); + + it("should combine processed prompts with initial prompt", async () => { + const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule); + mockProcessPromptOrRule + .mockResolvedValueOnce("processed1") + .mockResolvedValueOnce("processed2"); + + const result = await processAndCombinePrompts( + ["prompt1", "prompt2"], + "initial", + ); + + expect(result).toBe("processed1\n\nprocessed2\n\ninitial"); + }); + + it("should handle processing errors and continue with successful ones", async () => { + const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule); + mockProcessPromptOrRule + .mockResolvedValueOnce("success1") + .mockRejectedValueOnce(new Error("processing failed")) + .mockResolvedValueOnce("success2"); + + const result = await processAndCombinePrompts(["good1", "bad", "good2"]); + + expect(mockProcessPromptOrRule).toHaveBeenCalledTimes(3); + expect(result).toBe("success1\n\nsuccess2"); + }); + + it("should return initial prompt when all processing fails", async () => { + const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule); + mockProcessPromptOrRule + .mockRejectedValueOnce(new Error("fail1")) + .mockRejectedValueOnce(new Error("fail2")); + + const result = await processAndCombinePrompts( + ["bad1", "bad2"], + "initial", + ); + + expect(result).toBe("initial"); + }); + + it("should return undefined when all processing fails and no initial", async () => { + const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule); + mockProcessPromptOrRule.mockRejectedValue(new Error("processing failed")); + + const result = await processAndCombinePrompts(["bad"]); + + expect(result).toBeUndefined(); + }); + + it("should warn when processing fails", async () => { + const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule); + mockProcessPromptOrRule.mockRejectedValue(new Error("test error")); + + const { logger } = await import("./logger.js"); + + await processAndCombinePrompts(["bad-prompt"]); + + expect(logger.warn).toHaveBeenCalledWith( + 'Failed to process prompt "bad-prompt": test error', + ); + }); + }); +}); diff --git a/extensions/cli/src/util/promptProcessor.ts b/extensions/cli/src/util/promptProcessor.ts new file mode 100644 index 000000000..c6173738f --- /dev/null +++ b/extensions/cli/src/util/promptProcessor.ts @@ -0,0 +1,38 @@ +import { processPromptOrRule } from "../args.js"; + +import { logger } from "./logger.js"; + +/** + * Process additional prompts from --prompt flags and combine with initial prompt + * @param additionalPrompts - Array of prompt specifications to process + * @param initialPrompt - Optional initial prompt to combine with + * @returns Combined prompt string or undefined if no prompts + */ +export async function processAndCombinePrompts( + additionalPrompts?: string[], + initialPrompt?: string, +): Promise { + if (!additionalPrompts || additionalPrompts.length === 0) { + return initialPrompt; + } + + const processedPrompts: string[] = []; + + for (const promptSpec of additionalPrompts) { + try { + const processed = await processPromptOrRule(promptSpec); + processedPrompts.push(processed); + } catch (error: any) { + logger.warn(`Failed to process prompt "${promptSpec}": ${error.message}`); + } + } + + if (processedPrompts.length === 0) { + return initialPrompt; + } + + const combinedPrompts = processedPrompts.join("\n\n"); + return initialPrompt + ? `${combinedPrompts}\n\n${initialPrompt}` + : combinedPrompts; +} diff --git a/extensions/cli/src/util/tokenizer.test.ts b/extensions/cli/src/util/tokenizer.test.ts new file mode 100644 index 000000000..97ed9418a --- /dev/null +++ b/extensions/cli/src/util/tokenizer.test.ts @@ -0,0 +1,292 @@ +import { ModelConfig } from "@continuedev/config-yaml"; +import { ChatCompletionMessageParam } from "openai/resources.mjs"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import { logger } from "./logger.js"; +import { + AUTO_COMPACT_THRESHOLD, + calculateContextUsagePercentage, + countChatHistoryTokens, + countMessageTokens, + getModelContextLimit, + shouldAutoCompact, +} from "./tokenizer.js"; + +// Mock the logger +vi.mock("./logger.js", () => ({ + logger: { + debug: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + }, +})); + +// Mock gpt-tokenizer +vi.mock("gpt-tokenizer", () => ({ + encode: (text: string) => new Array(Math.ceil(text.length / 4)), // Rough 4 chars per token +})); + +describe("tokenizer", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + describe("getModelContextLimit", () => { + it("should return contextLength from model config", () => { + const model: ModelConfig = { + name: "test-model", + model: "test", + provider: "openai", + defaultCompletionOptions: { + contextLength: 8192, + }, + }; + + expect(getModelContextLimit(model)).toBe(8192); + }); + + it("should return default when no contextLength specified", () => { + const model: ModelConfig = { + name: "test-model", + model: "test", + provider: "openai", + }; + + expect(getModelContextLimit(model)).toBe(200_000); + }); + }); + + describe("countMessageTokens", () => { + it("should count tokens for string content", () => { + const message: ChatCompletionMessageParam = { + role: "user", + content: "Hello world", // 11 chars -> ~3 tokens + 2 for role = 5 + }; + + const tokenCount = countMessageTokens(message); + expect(tokenCount).toBeGreaterThan(0); + expect(tokenCount).toBe(5); // 3 content tokens + 2 role tokens + }); + + it("should count tokens for array content", () => { + const message: ChatCompletionMessageParam = { + role: "user", + content: [ + { type: "text", text: "Hello" }, // 5 chars -> ~2 tokens + { type: "image_url", image_url: { url: "test.jpg" } }, // +85 tokens + ], + }; + + const tokenCount = countMessageTokens(message); + expect(tokenCount).toBe(89); // 2 + 85 + 2 role tokens + }); + + it("should count tokens for tool calls", () => { + const message: ChatCompletionMessageParam = { + role: "assistant", + content: "I'll help you", + tool_calls: [ + { + id: "call_1", + type: "function", + function: { + name: "test_function", // ~3 tokens + 10 overhead + arguments: '{"param": "value"}', // ~5 tokens + }, + }, + ], + }; + + const tokenCount = countMessageTokens(message); + expect(tokenCount).toBeGreaterThan(20); + }); + + it("should handle errors gracefully", () => { + // We'll skip this test for now since mocking gpt-tokenizer is complex + // The error handling is tested implicitly by the fallback behavior + expect(true).toBe(true); + }); + }); + + describe("countChatHistoryTokens", () => { + it("should count tokens for multiple messages", () => { + const chatHistory: ChatCompletionMessageParam[] = [ + { role: "system", content: "You are helpful" }, + { role: "user", content: "Hello" }, + { role: "assistant", content: "Hi there" }, + ]; + + const tokenCount = countChatHistoryTokens(chatHistory); + expect(tokenCount).toBeGreaterThan(0); + // Should include message overhead (3 * 3 = 9 tokens) + expect(tokenCount).toBeGreaterThan(9); + }); + + it("should handle empty chat history", () => { + const tokenCount = countChatHistoryTokens([]); + expect(tokenCount).toBe(0); + }); + }); + + describe("calculateContextUsagePercentage", () => { + it("should calculate percentage correctly", () => { + const model: ModelConfig = { + name: "test-model", + model: "test", + provider: "openai", + defaultCompletionOptions: { + contextLength: 1000, + }, + }; + + expect(calculateContextUsagePercentage(800, model)).toBe(80); + expect(calculateContextUsagePercentage(500, model)).toBe(50); + expect(calculateContextUsagePercentage(1200, model)).toBe(100); // Capped at 100% + }); + }); + + describe("shouldAutoCompact", () => { + const createModel = ( + contextLength: number, + maxTokens?: number, + ): ModelConfig => ({ + name: "test-model", + model: "test", + provider: "openai", + defaultCompletionOptions: { + contextLength, + maxTokens, + }, + }); + + const createChatHistory = ( + tokenCount: number, + ): ChatCompletionMessageParam[] => { + // Create a message that will result in approximately the desired token count + const content = "x".repeat(tokenCount * 4); // 4 chars per token + return [{ role: "user", content }]; + }; + + it("should compact when input tokens exceed threshold with maxTokens", () => { + const model = createModel(1000, 200); // 1000 context, 200 max output + // Available for input: 1000 - 200 = 800 + // Threshold: 800 * 0.8 = 640 + const chatHistory = createChatHistory(650); // Above threshold + + expect(shouldAutoCompact(chatHistory, model)).toBe(true); + }); + + it("should not compact when input tokens are below threshold with maxTokens", () => { + const model = createModel(1000, 200); // 1000 context, 200 max output + // Available for input: 1000 - 200 = 800 + // Threshold: 800 * 0.8 = 640 + const chatHistory = createChatHistory(600); // Below threshold + + expect(shouldAutoCompact(chatHistory, model)).toBe(false); + }); + + it("should use 35% default reservation when maxTokens is not set", () => { + const model = createModel(1000); // No maxTokens + // Reserved: 1000 * 0.35 = 350 + // Available for input: 1000 - 350 = 650 + // Threshold: 650 * 0.8 = 520 + const chatHistory = createChatHistory(530); // Above threshold + + expect(shouldAutoCompact(chatHistory, model)).toBe(true); + }); + + it("should not compact when below default threshold without maxTokens", () => { + const model = createModel(1000); // No maxTokens + // Available for input: 1000 - 350 = 650 + // Threshold: 650 * 0.8 = 520 + const chatHistory = createChatHistory(500); // Below threshold + + expect(shouldAutoCompact(chatHistory, model)).toBe(false); + }); + + it("should throw error when maxTokens >= contextLength", () => { + const model = createModel(1000, 1000); // maxTokens equals contextLength + const chatHistory = createChatHistory(1); // Minimal input + + expect(() => shouldAutoCompact(chatHistory, model)).toThrow( + "max_tokens is larger than context_length, which should not be possible. Please check your configuration.", + ); + }); + + it("should throw error when maxTokens > contextLength", () => { + const model = createModel(1000, 1200); // maxTokens exceeds contextLength + const chatHistory = createChatHistory(1); // Minimal input + + expect(() => shouldAutoCompact(chatHistory, model)).toThrow( + "max_tokens is larger than context_length, which should not be possible. Please check your configuration.", + ); + }); + + it("should handle edge case with very small context limit", () => { + const model = createModel(100, 50); // Small context + // Available: 100 - 50 = 50 + // Threshold: 50 * 0.8 = 40 + const chatHistory = createChatHistory(45); // Above threshold + + expect(shouldAutoCompact(chatHistory, model)).toBe(true); + }); + + it("should log debug information correctly", () => { + const model = createModel(1000, 200); + const chatHistory = createChatHistory(600); + + shouldAutoCompact(chatHistory, model); + + expect(logger.debug).toHaveBeenCalledWith("Context usage check", { + inputTokens: expect.any(Number), + contextLimit: 1000, + maxTokens: 200, + reservedForOutput: 200, + availableForInput: 800, + usage: expect.any(String), + threshold: `${Math.round(AUTO_COMPACT_THRESHOLD * 100)}%`, + shouldCompact: expect.any(Boolean), + }); + }); + + it("should handle model with zero maxTokens correctly", () => { + const model = createModel(1000, 0); // Explicit zero + // Should use default 35% reservation: 1000 * 0.35 = 350 + const chatHistory = createChatHistory(530); // Above threshold + + expect(shouldAutoCompact(chatHistory, model)).toBe(true); + }); + + describe("real-world scenarios", () => { + it("should prevent Claude 3.5 Sonnet context overflow", () => { + // Claude 3.5 Sonnet: 200k context, often uses 4k max_tokens + const model = createModel(200_000, 4_000); + // Available: 200k - 4k = 196k + // Threshold: 196k * 0.8 = 156.8k + const chatHistory = createChatHistory(160_000); // Above threshold + + expect(shouldAutoCompact(chatHistory, model)).toBe(true); + }); + + it("should prevent GPT-4 context overflow", () => { + // GPT-4: 128k context, often uses 4k max_tokens + const model = createModel(128_000, 4_000); + // Available: 128k - 4k = 124k + // Threshold: 124k * 0.8 = 99.2k + const chatHistory = createChatHistory(100_000); // Above threshold + + expect(shouldAutoCompact(chatHistory, model)).toBe(true); + }); + + it("should handle models with very high max_tokens", () => { + // Some models allow very high max_tokens (e.g., 64k like in the error message) + const model = createModel(200_000, 64_000); + // Available: 200k - 64k = 136k + // Threshold: 136k * 0.8 = 108.8k + const chatHistory = createChatHistory(110_000); // Above threshold + + expect(shouldAutoCompact(chatHistory, model)).toBe(true); + }); + }); + }); +}); diff --git a/extensions/cli/src/util/tokenizer.ts b/extensions/cli/src/util/tokenizer.ts index 7dc53e809..5bf0117a4 100644 --- a/extensions/cli/src/util/tokenizer.ts +++ b/extensions/cli/src/util/tokenizer.ts @@ -117,20 +117,39 @@ export function calculateContextUsagePercentage( /** * Check if the chat history exceeds the auto-compact threshold * @param chatHistory The chat history to check - * @param modelName The model name + * @param model The model configuration * @returns Whether auto-compacting should be triggered */ export function shouldAutoCompact( chatHistory: ChatCompletionMessageParam[], model: ModelConfig, ): boolean { - const tokenCount = countChatHistoryTokens(chatHistory); - const limit = getModelContextLimit(model); - const usage = tokenCount / limit; + const inputTokens = countChatHistoryTokens(chatHistory); + const contextLimit = getModelContextLimit(model); + const maxTokens = model.defaultCompletionOptions?.maxTokens || 0; + + // Calculate available space considering max_tokens reservation + // If maxTokens is not set, reserve 35% of context for output as a safe default + // (64k/200k with claude = 32%, round up to give a buffer) + const reservedForOutput = + maxTokens > 0 ? maxTokens : Math.ceil(contextLimit * 0.35); + const availableForInput = contextLimit - reservedForOutput; + + // Ensure we have positive space available for input + if (availableForInput <= 0) { + throw new Error( + `max_tokens is larger than context_length, which should not be possible. Please check your configuration.`, + ); + } + + const usage = inputTokens / availableForInput; logger.debug("Context usage check", { - tokenCount, - limit, + inputTokens, + contextLimit, + maxTokens, + reservedForOutput, + availableForInput, usage: `${Math.round(usage * 100)}%`, threshold: `${Math.round(AUTO_COMPACT_THRESHOLD * 100)}%`, shouldCompact: usage >= AUTO_COMPACT_THRESHOLD, @@ -138,3 +157,13 @@ export function shouldAutoCompact( return usage >= AUTO_COMPACT_THRESHOLD; } + +/** + * Get a descriptive message for auto-compaction that shows the context limit + * @param model The model configuration + * @returns A descriptive message explaining why compaction is needed + */ +export function getAutoCompactMessage(model: ModelConfig): string { + const limit = getModelContextLimit(model); + return `Approaching context limit (${(limit / 1000).toFixed(0)}K tokens). Auto-compacting chat history...`; +} diff --git a/extensions/cli/test-fixtures/model-switch-test-config.yaml b/extensions/cli/test-fixtures/model-switch-test-config.yaml new file mode 100644 index 000000000..70dc69a91 --- /dev/null +++ b/extensions/cli/test-fixtures/model-switch-test-config.yaml @@ -0,0 +1,18 @@ +name: Model Switch Test Config +version: 1.0.0 + +models: + - name: GPT-4 + provider: openai + model: gpt-4 + apiKey: test-api-key-1 + + - name: GPT-3.5 + provider: openai + model: gpt-3.5-turbo + apiKey: test-api-key-2 + + - name: Claude 3 + provider: anthropic + model: claude-3-opus + apiKey: test-api-key-3 \ No newline at end of file diff --git a/extensions/cli/validate-aliases.mjs b/extensions/cli/validate-aliases.mjs index df3f696e9..2f714a9dd 100755 --- a/extensions/cli/validate-aliases.mjs +++ b/extensions/cli/validate-aliases.mjs @@ -42,10 +42,14 @@ function getDefinedAliases() { } // Look for package names in non-commented lines - // Match both @continuedev/* packages and simple package names like "core" - const packageMatch = line.match(/"(@continuedev\/[^"]+|[^"@\/]+)":/); - if (packageMatch) { - aliases.add(packageMatch[1]); + // Match both quoted and unquoted keys + const quotedMatch = line.match(/"([^"]+)":/); + const unquotedMatch = line.match(/\s+([a-zA-Z@][a-zA-Z0-9@\/_-]*)\s*:/); + + if (quotedMatch) { + aliases.add(quotedMatch[1]); + } else if (unquotedMatch && !unquotedMatch[1].includes('__dirname') && unquotedMatch[1] !== 'js') { + aliases.add(unquotedMatch[1]); } } diff --git a/extensions/intellij/.run/Run Continue (CE).run.xml b/extensions/intellij/.run/Run Continue (CE).run.xml index edca42d64..bcc13a3bd 100644 --- a/extensions/intellij/.run/Run Continue (CE).run.xml +++ b/extensions/intellij/.run/Run Continue (CE).run.xml @@ -1,6 +1,6 @@ - + diff --git a/extensions/intellij/.run/Run Continue.run.xml b/extensions/intellij/.run/Run Continue.run.xml index 1366cd39e..cd32b3c4d 100644 --- a/extensions/intellij/.run/Run Continue.run.xml +++ b/extensions/intellij/.run/Run Continue.run.xml @@ -1,6 +1,6 @@ - + diff --git a/extensions/intellij/.run/Run Extension (standalone).run.xml b/extensions/intellij/.run/Run Extension (standalone).run.xml new file mode 100644 index 000000000..3c19f11ec --- /dev/null +++ b/extensions/intellij/.run/Run Extension (standalone).run.xml @@ -0,0 +1,24 @@ + + + + + + + true + true + false + false + + + \ No newline at end of file diff --git a/extensions/intellij/.run/Run Extension (use TCP).run.xml b/extensions/intellij/.run/Run Extension (use TCP).run.xml new file mode 100644 index 000000000..da187201e --- /dev/null +++ b/extensions/intellij/.run/Run Extension (use TCP).run.xml @@ -0,0 +1,30 @@ + + + + + + + + true + true + false + false + + + \ No newline at end of file diff --git a/extensions/intellij/.run/Run Extension.run.xml b/extensions/intellij/.run/Run Extension.run.xml deleted file mode 100644 index 63b2835d6..000000000 --- a/extensions/intellij/.run/Run Extension.run.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - true - true - false - false - - - \ No newline at end of file diff --git a/extensions/intellij/build.gradle.kts b/extensions/intellij/build.gradle.kts index 6cd36e473..811dc4d05 100644 --- a/extensions/intellij/build.gradle.kts +++ b/extensions/intellij/build.gradle.kts @@ -15,7 +15,6 @@ plugins { id("org.jetbrains.intellij.platform") version "2.7.2" id("org.jetbrains.changelog") version "2.1.2" id("org.jetbrains.qodana") version "0.1.13" - id("org.jetbrains.kotlinx.kover") version "0.7.3" id("io.sentry.jvm.gradle") version "5.8.0" } @@ -78,12 +77,6 @@ qodana { showReport = environment("QODANA_SHOW_REPORT").map { it.toBoolean() }.getOrElse(false) } -koverReport { - defaults { - xml { onCheck = true } - } -} - intellijPlatformTesting { runIde { register("runIdeForUiTests") { diff --git a/extensions/vscode/src/diff/vertical/manager.ts b/extensions/vscode/src/diff/vertical/manager.ts index e30f898c0..1731b176d 100644 --- a/extensions/vscode/src/diff/vertical/manager.ts +++ b/extensions/vscode/src/diff/vertical/manager.ts @@ -141,7 +141,16 @@ export class VerticalDiffManager { this.disableDocumentChangeListener(); - vscode.commands.executeCommand("setContext", "continue.diffVisible", false); + void vscode.commands.executeCommand( + "setContext", + "continue.diffVisible", + false, + ); + + void this.webviewProtocol.request( + "focusContinueInputWithoutClear", + undefined, + ); } async acceptRejectVerticalDiffBlock( diff --git a/gui/package-lock.json b/gui/package-lock.json index a3dffda4c..8e4bfb7d9 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -27,10 +27,12 @@ "@tiptap/react": "^2.1.13", "@tiptap/starter-kit": "^2.1.13", "@tiptap/suggestion": "^2.1.13", + "@types/diff": "^7.0.2", "@types/uuid": "^10.0.0", "anser": "^2.3.2", "clsx": "^2.1.1", "core": "file:../core", + "diff": "^8.0.2", "dompurify": "^3.0.6", "downshift": "^7.6.0", "escape-carriage": "^1.3.1", @@ -129,7 +131,6 @@ "@sentry/esbuild-plugin": "^4.0.2", "@sentry/node": "^9.43.0", "@sentry/vite-plugin": "^4.0.2", - "@typescript-eslint/eslint-plugin": "^7.8.0", "@xenova/transformers": "2.14.0", "adf-to-md": "^1.1.0", "async-mutex": "^0.5.0", @@ -209,6 +210,8 @@ "@types/tar": "^6.1.13", "@types/uuid": "^9.0.7", "@types/win-ca": "^3.5.4", + "@typescript-eslint/eslint-plugin": "^8.40.0", + "@typescript-eslint/parser": "^8.40.0", "cross-env": "^7.0.3", "esbuild": "0.17.19", "eslint": "^8", @@ -3865,6 +3868,12 @@ "@types/ms": "*" } }, + "node_modules/@types/diff": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@types/diff/-/diff-7.0.2.tgz", + "integrity": "sha512-JSWRMozjFKsGlEjiiKajUjIJVKuKdE3oVy2DNtK+fUo8q82nhFZ2CPQwicAIkXrofahDXrWJ7mjelvZphMS98Q==", + "license": "MIT" + }, "node_modules/@types/dompurify": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/@types/dompurify/-/dompurify-3.2.0.tgz", @@ -6194,6 +6203,15 @@ "integrity": "sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==", "dev": true }, + "node_modules/diff": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/diff/-/diff-8.0.2.tgz", + "integrity": "sha512-sSuxWU5j5SR9QQji/o2qMvqRNYRDOcBTgsJ/DeCf4iSN4gW+gNMXM7wFIP+fdXZxoNiAnHUTGjCr+TSWXdRDKg==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.3.1" + } + }, "node_modules/direction": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/direction/-/direction-1.0.4.tgz", diff --git a/gui/package.json b/gui/package.json index ab83efb22..6cb45030c 100644 --- a/gui/package.json +++ b/gui/package.json @@ -36,10 +36,12 @@ "@tiptap/react": "^2.1.13", "@tiptap/starter-kit": "^2.1.13", "@tiptap/suggestion": "^2.1.13", + "@types/diff": "^7.0.2", "@types/uuid": "^10.0.0", "anser": "^2.3.2", "clsx": "^2.1.1", "core": "file:../core", + "diff": "^8.0.2", "dompurify": "^3.0.6", "downshift": "^7.6.0", "escape-carriage": "^1.3.1", diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions.tsx index 1214b9e24..9b7ba953d 100644 --- a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions.tsx @@ -11,7 +11,7 @@ interface ApplyActionsProps { applyState?: ApplyState; onClickAccept: () => void; onClickReject: () => void; - onClickApply: () => void; + onClickApply?: () => void; } export function ApplyActions(props: ApplyActionsProps) { diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/FileInfo.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/FileInfo.tsx index 550d1fd28..c288c7cd0 100644 --- a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/FileInfo.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/FileInfo.tsx @@ -1,10 +1,11 @@ import { getLastNPathParts } from "core/util/uri"; +import { MouseEventHandler } from "react"; import FileIcon from "../../FileIcon"; import { ToolTip } from "../../gui/Tooltip"; export interface FileInfoProps { filepath: string; - onClick?: () => void; + onClick?: MouseEventHandler; range?: string; } diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx index e97c13061..f9d268ccc 100644 --- a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx @@ -96,7 +96,7 @@ export function StepContainerPreToolbar({ toolCallState?.status === "errored" || toolCallState?.status === "done") ? (
{ if (toolCallState.output) { ideMessenger.post("showVirtualFile", { diff --git a/gui/src/components/UnifiedTerminal/UnifiedTerminal.tsx b/gui/src/components/UnifiedTerminal/UnifiedTerminal.tsx new file mode 100644 index 000000000..00e34114b --- /dev/null +++ b/gui/src/components/UnifiedTerminal/UnifiedTerminal.tsx @@ -0,0 +1,555 @@ +import { ChevronDownIcon } from "@heroicons/react/24/outline"; +import Anser, { AnserJsonEntry } from "anser"; +import { ToolCallState } from "core"; +import { escapeCarriageReturn } from "escape-carriage"; +import { useMemo, useState } from "react"; +import styled, { keyframes } from "styled-components"; +import { useAppDispatch } from "../../redux/hooks"; +import { moveTerminalProcessToBackground } from "../../redux/thunks/moveTerminalProcessToBackground"; +import { getFontSize } from "../../util"; +import { + defaultBorderRadius, + vscBackground, + vscEditorBackground, + vscForeground, +} from "../index"; +import { CopyButton } from "../StyledMarkdownPreview/StepContainerPreToolbar/CopyButton"; +import { RunInTerminalButton } from "../StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton"; +import { ButtonContent, SpoilerButton } from "../ui/SpoilerButton"; + +const blinkCursor = keyframes` + 0%, 50% { opacity: 1; } + 51%, 100% { opacity: 0; } +`; + +const BlinkingCursor = styled.span` + &::after { + content: "█"; + animation: ${blinkCursor} 1s infinite; + color: ${vscForeground}; + } +`; + +const AnsiSpan = styled.span<{ + bg?: string; + fg?: string; + decoration?: string; +}>` + ${({ bg }) => bg && `background-color: rgb(${bg});`} + ${({ fg }) => fg && `color: rgb(${fg});`} + ${({ decoration }) => { + switch (decoration) { + case "bold": + return "font-weight: bold;"; + case "dim": + return "opacity: 0.5;"; + case "italic": + return "font-style: italic;"; + case "hidden": + return "visibility: hidden;"; + case "strikethrough": + return "text-decoration: line-through;"; + case "underline": + return "text-decoration: underline;"; + case "blink": + return "text-decoration: blink;"; + default: + return ""; + } + }} +`; + +const AnsiLink = styled.a` + color: var(--vscode-textLink-foreground, #3794ff); + text-decoration: none; + &:hover { + text-decoration: underline; + } +`; + +const StyledTerminalContainer = styled.div<{ + fontSize?: number; + bgColor: string; +}>` + background-color: ${(props) => props.bgColor}; + font-family: + var(--vscode-font-family), + system-ui, + -apple-system, + BlinkMacSystemFont, + "Segoe UI", + Roboto, + Oxygen, + Ubuntu, + Cantarell, + "Open Sans", + "Helvetica Neue", + sans-serif; + font-size: ${(props) => props.fontSize || getFontSize()}px; + color: ${vscForeground}; + line-height: 1.5; + + > *:last-child { + margin-bottom: 0; + } +`; + +const TerminalContent = styled.div` + pre { + white-space: pre-wrap; + background-color: ${vscEditorBackground}; + border-radius: ${defaultBorderRadius}; + border: 1px solid + var(--vscode-editorWidget-border, rgba(127, 127, 127, 0.3)); + max-width: calc(100vw - 24px); + overflow-x: scroll; + overflow-y: hidden; + padding: 8px; + margin: 0; + } + + code { + span.line:empty { + display: none; + } + word-wrap: break-word; + border-radius: ${defaultBorderRadius}; + background-color: ${vscEditorBackground}; + font-size: ${getFontSize() - 2}px; + font-family: var(--vscode-editor-font-family); + } + + code:not(pre > code) { + font-family: var(--vscode-editor-font-family); + color: var(--vscode-input-placeholderForeground); + } +`; + +const ToolbarContainer = styled.div<{ isExpanded: boolean }>` + font-size: ${getFontSize() - 2}px; +`; + +const CommandLine = styled.div` + padding-bottom: 0.5rem; + color: var(--vscode-terminal-ansiGreen, #0dbc79); +`; + +function ansiToJSON( + input: string, + use_classes: boolean = false, +): AnserJsonEntry[] { + input = escapeCarriageReturn(fixBackspace(input)); + return Anser.ansiToJson(input, { + json: true, + remove_empty: true, + use_classes, + }); +} + +function createClass(bundle: AnserJsonEntry): string | null { + let classNames: string = ""; + + if (bundle.bg) { + classNames += `${bundle.bg}-bg `; + } + if (bundle.fg) { + classNames += `${bundle.fg}-fg `; + } + if (bundle.decoration) { + classNames += `ansi-${bundle.decoration} `; + } + + if (classNames === "") { + return null; + } + + classNames = classNames.substring(0, classNames.length - 1); + return classNames; +} + +function convertBundleIntoReact( + linkify: boolean, + useClasses: boolean, + bundle: AnserJsonEntry, + key: number, +): JSX.Element { + const className = useClasses ? createClass(bundle) : null; + const decorationProp = bundle.decoration + ? String(bundle.decoration) + : undefined; + + if (!linkify) { + return ( + + {bundle.content} + + ); + } + + const content: React.ReactNode[] = []; + const linkRegex = + /(\s|^)(https?:\/\/(?:www\.|(?!www))[^\s.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})/g; + + let index = 0; + let match: RegExpExecArray | null; + while ((match = linkRegex.exec(bundle.content)) !== null) { + const [, pre, url] = match; + + const startIndex = match.index + pre.length; + if (startIndex > index) { + content.push(bundle.content.substring(index, startIndex)); + } + + const href = url.startsWith("www.") ? `http://${url}` : url; + + content.push( + + {url} + , + ); + + index = linkRegex.lastIndex; + } + + if (index < bundle.content.length) { + content.push(bundle.content.substring(index)); + } + + return ( + + {content} + + ); +} + +function fixBackspace(txt: string) { + let tmp = txt; + do { + txt = tmp; + tmp = txt.replace(/[^\n]\x08/gm, ""); + } while (tmp.length < txt.length); + return txt; +} + +function AnsiRenderer({ + children, + linkify = false, +}: { + children?: string; + linkify?: boolean; +}) { + const ansiContent = ansiToJSON(children ?? "", false).map((bundle, i) => + convertBundleIntoReact(linkify, false, bundle, i), + ); + + return <>{ansiContent}; +} + +interface StatusIconProps { + status: "running" | "completed" | "failed" | "background"; +} + +function StatusIcon({ status }: StatusIconProps) { + const getStatusColor = () => { + switch (status) { + case "running": + return "bg-success"; + case "completed": + return "bg-success"; + case "background": + return "bg-accent"; + case "failed": + return "bg-error"; + default: + return "bg-success"; + } + }; + + return ( + + ); +} + +interface IndicatorOnlyProps { + hiddenLinesCount: number; + isExpanded: boolean; + onToggle: () => void; +} + +function IndicatorOnly({ + hiddenLinesCount, + isExpanded, + onToggle, +}: IndicatorOnlyProps) { + return ( +
+ + + + {isExpanded ? "Collapse" : `+${hiddenLinesCount} more lines`} + + + + +
+ ); +} + +interface CollapsibleOutputContainerProps { + limitedContent: string; + fullContent: string; + isExpanded: boolean; + onToggle: () => void; +} + +function CollapsibleOutputContainer({ + limitedContent, + fullContent, + isExpanded, + onToggle, +}: CollapsibleOutputContainerProps) { + return ( +
+ {/* Gradient overlay when collapsed */} + {!isExpanded && ( +
+ )} + +
+
+ + {isExpanded ? fullContent : limitedContent} + +
+
+
+ ); +} + +interface UnifiedTerminalCommandProps { + command: string; + output?: string; + status?: "running" | "completed" | "failed" | "background"; + statusMessage?: string; + toolCallState?: ToolCallState; + toolCallId?: string; + displayLines?: number; +} + +export function UnifiedTerminalCommand({ + command, + output = "", + status = "completed", + statusMessage = "", + toolCallState, + toolCallId, + displayLines = 15, +}: UnifiedTerminalCommandProps) { + const dispatch = useAppDispatch(); + const [isExpanded, setIsExpanded] = useState(true); + const [outputExpanded, setOutputExpanded] = useState(false); + + // Determine running state + const isRunning = toolCallState?.status === "calling" || status === "running"; + const hasOutput = output.length > 0; + + // Process terminal content for line limiting + const processedTerminalContent = useMemo(() => { + if (!output) { + return { + fullContent: "", + limitedContent: "", + totalLines: 0, + isLimited: false, + hiddenLinesCount: 0, + }; + } + + const lines = output.split("\n"); + const totalLines = lines.length; + + if (totalLines > displayLines) { + const lastLines = lines.slice(-displayLines); + return { + fullContent: output, + limitedContent: lastLines.join("\n"), + totalLines, + isLimited: true, + hiddenLinesCount: totalLines - displayLines, + }; + } + + return { + fullContent: output, + limitedContent: output, + totalLines, + isLimited: false, + hiddenLinesCount: 0, + }; + }, [output, displayLines]); + + // Determine status type + let statusType: "running" | "completed" | "failed" | "background" = status; + if (isRunning) { + statusType = "running"; + } else if (statusMessage?.includes("failed")) { + statusType = "failed"; + } else if (statusMessage?.includes("background")) { + statusType = "background"; + } + + const handleMoveToBackground = () => { + if (toolCallId) { + void dispatch( + moveTerminalProcessToBackground({ + toolCallId, + }), + ); + } + }; + + // Create combined content for copying (command + output) + const copyContent = useMemo(() => { + let content = `$ ${command}`; + if (hasOutput) { + content += `\n\n${output}`; + } + return content; + }, [command, output, hasOutput]); + + return ( + +
+ {/* Toolbar */} +
+
+ setIsExpanded(!isExpanded)} + className={`text-lightgray h-3.5 w-3.5 flex-shrink-0 cursor-pointer hover:brightness-125 ${ + isExpanded ? "rotate-0" : "-rotate-90" + }`} + /> + Terminal +
+ +
+ {!isRunning && ( +
+ + +
+ )} +
+
+ + {/* Content */} + {isExpanded && ( + +
+              
+                {/* Command is always visible */}
+                
+ $ {command} +
+ + {/* Running state with cursor */} + {isRunning && !hasOutput && ( +
+ +
+ )} + + {/* Output with optional collapsible functionality */} + {hasOutput && ( +
+ {/* Expand/Collapse indicator positioned between command and output */} + {processedTerminalContent.isLimited && ( + setOutputExpanded(!outputExpanded)} + /> + )} + +
+ {processedTerminalContent.isLimited ? ( + setOutputExpanded(!outputExpanded)} + /> + ) : ( +
+ + {processedTerminalContent.fullContent} + +
+ )} +
+
+ )} +
+
+
+ )} + + {/* Status information */} + {(statusMessage || isRunning) && ( + + )} +
+
+ ); +} diff --git a/gui/src/components/ansiTerminal/Ansi.tsx b/gui/src/components/ansiTerminal/Ansi.tsx deleted file mode 100644 index 35d4b0a43..000000000 --- a/gui/src/components/ansiTerminal/Ansi.tsx +++ /dev/null @@ -1,279 +0,0 @@ -import Anser, { AnserJsonEntry } from "anser"; -import { escapeCarriageReturn } from "escape-carriage"; -import * as React from "react"; -import styled from "styled-components"; -import { - defaultBorderRadius, - vscBackground, - vscEditorBackground, - vscForeground, -} from "../../components"; -import { getFontSize } from "../../util"; - -const AnsiSpan = styled.span<{ - bg?: string; - fg?: string; - decoration?: string; -}>` - ${({ bg }) => bg && `background-color: rgb(${bg});`} - ${({ fg }) => fg && `color: rgb(${fg});`} - ${({ decoration }) => { - switch (decoration) { - case "bold": - return "font-weight: bold;"; - case "dim": - return "opacity: 0.5;"; - case "italic": - return "font-style: italic;"; - case "hidden": - return "visibility: hidden;"; - case "strikethrough": - return "text-decoration: line-through;"; - case "underline": - return "text-decoration: underline;"; - case "blink": - return "text-decoration: blink;"; - default: - return ""; - } - }} -`; - -const AnsiLink = styled.a` - color: var(--vscode-textLink-foreground, #3794ff); - text-decoration: none; - &:hover { - text-decoration: underline; - } -`; - -// Using the same styled component structure as StyledMarkdown -const StyledAnsi = styled.div<{ - fontSize?: number; - whiteSpace: string; - bgColor: string; -}>` - pre { - white-space: ${(props) => props.whiteSpace}; - background-color: ${vscEditorBackground}; - border-radius: ${defaultBorderRadius}; - border: 1px solid - var(--vscode-editorWidget-border, rgba(127, 127, 127, 0.3)); - max-width: calc(100vw - 24px); - overflow-x: scroll; - overflow-y: hidden; - padding: 8px; - } - - code { - span.line:empty { - display: none; - } - word-wrap: break-word; - border-radius: ${defaultBorderRadius}; - background-color: ${vscEditorBackground}; - font-size: ${getFontSize() - 2}px; - font-family: var(--vscode-editor-font-family); - } - - code:not(pre > code) { - font-family: var(--vscode-editor-font-family); - color: var(--vscode-input-placeholderForeground); - } - - background-color: ${(props) => props.bgColor}; - font-family: - var(--vscode-font-family), - system-ui, - -apple-system, - BlinkMacSystemFont, - "Segoe UI", - Roboto, - Oxygen, - Ubuntu, - Cantarell, - "Open Sans", - "Helvetica Neue", - sans-serif; - font-size: ${(props) => props.fontSize || getFontSize()}px; - padding-left: 8px; - padding-right: 8px; - color: ${vscForeground}; - line-height: 1.5; - - > *:last-child { - margin-bottom: 0; - } -`; - -/** - * Converts ANSI strings into JSON output. - * @name ansiToJSON - * @function - * @param {String} input The input string. - * @param {boolean} use_classes If `true`, HTML classes will be appended - * to the HTML output. - * @return {Array} The parsed input. - */ -function ansiToJSON( - input: string, - use_classes: boolean = false, -): AnserJsonEntry[] { - input = escapeCarriageReturn(fixBackspace(input)); - return Anser.ansiToJson(input, { - json: true, - remove_empty: true, - use_classes, - }); -} - -/** - * Create a class string. - * @name createClass - * @function - * @param {AnserJsonEntry} bundle - * @return {String} class name(s) - */ -function createClass(bundle: AnserJsonEntry): string | null { - let classNames: string = ""; - - if (bundle.bg) { - classNames += `${bundle.bg}-bg `; - } - if (bundle.fg) { - classNames += `${bundle.fg}-fg `; - } - if (bundle.decoration) { - classNames += `ansi-${bundle.decoration} `; - } - - if (classNames === "") { - return null; - } - - classNames = classNames.substring(0, classNames.length - 1); - return classNames; -} - -/** - * Converts an Anser bundle into a React Node. - * @param linkify whether links should be converting into clickable anchor tags. - * @param useClasses should render the span with a class instead of style. - * @param bundle Anser output. - * @param key - */ - -function convertBundleIntoReact( - linkify: boolean, - useClasses: boolean, - bundle: AnserJsonEntry, - key: number, -): JSX.Element { - const className = useClasses ? createClass(bundle) : null; - // Convert bundle.decoration to string or undefined (not null) to match the prop type - const decorationProp = bundle.decoration - ? String(bundle.decoration) - : undefined; - - if (!linkify) { - return ( - - {bundle.content} - - ); - } - - const content: React.ReactNode[] = []; - const linkRegex = - /(\s|^)(https?:\/\/(?:www\.|(?!www))[^\s.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})/g; - - let index = 0; - let match: RegExpExecArray | null; - while ((match = linkRegex.exec(bundle.content)) !== null) { - const [, pre, url] = match; - - const startIndex = match.index + pre.length; - if (startIndex > index) { - content.push(bundle.content.substring(index, startIndex)); - } - - // Make sure the href we generate from the link is fully qualified. We assume http - // if it starts with a www because many sites don't support https - const href = url.startsWith("www.") ? `http://${url}` : url; - - content.push( - - {url} - , - ); - - index = linkRegex.lastIndex; - } - - if (index < bundle.content.length) { - content.push(bundle.content.substring(index)); - } - - return ( - - {content} - - ); -} - -declare interface Props { - children?: string; - linkify?: boolean; - className?: string; - useClasses?: boolean; -} - -export default function Ansi(props: Props): JSX.Element { - const { className, useClasses, children, linkify } = props; - - // Create the ANSI content - const ansiContent = ansiToJSON(children ?? "", useClasses ?? false).map( - (bundle, i) => - convertBundleIntoReact(linkify ?? false, useClasses ?? false, bundle, i), - ); - - return ( - -
-        {ansiContent}
-      
-
- ); -} - -// This is copied from the Jupyter Classic source code -// notebook/static/base/js/utils.js to handle \b in a way -// that is **compatible with Jupyter classic**. One can -// argue that this behavior is questionable: -// https://stackoverflow.com/questions/55440152/multiple-b-doesnt-work-as-expected-in-jupyter# -function fixBackspace(txt: string) { - let tmp = txt; - do { - txt = tmp; - // Cancel out anything-but-newline followed by backspace - tmp = txt.replace(/[^\n]\x08/gm, ""); - } while (tmp.length < txt.length); - return txt; -} diff --git a/gui/src/components/mainInput/belowMainInput/ThinkingBlockPeek.tsx b/gui/src/components/mainInput/belowMainInput/ThinkingBlockPeek.tsx index ba423bbc4..3dea83d0e 100644 --- a/gui/src/components/mainInput/belowMainInput/ThinkingBlockPeek.tsx +++ b/gui/src/components/mainInput/belowMainInput/ThinkingBlockPeek.tsx @@ -5,38 +5,10 @@ import { ChatHistoryItem } from "core"; import { useEffect, useState } from "react"; import styled from "styled-components"; -import { defaultBorderRadius, lightGray, vscBackground } from "../.."; -import { getFontSize } from "../../../util"; +import { vscBackground } from "../.."; import { AnimatedEllipsis } from "../../AnimatedEllipsis"; import StyledMarkdownPreview from "../../StyledMarkdownPreview"; - -const SpoilerButton = styled.div` - background-color: ${vscBackground}; - width: fit-content; - margin: 8px 6px 0px 2px; - font-size: ${getFontSize() - 2}px; - border: 0.5px solid ${lightGray}; - border-radius: ${defaultBorderRadius}; - padding: 4px 8px; - color: ${lightGray}; - cursor: pointer; - box-shadow: - 0 4px 6px rgba(0, 0, 0, 0.1), - 0 1px 3px rgba(0, 0, 0, 0.08); - transition: box-shadow 0.3s ease; - - &:hover { - box-shadow: - 0 6px 8px rgba(0, 0, 0, 0.15), - 0 3px 6px rgba(0, 0, 0, 0.1); - } -`; - -const ButtonContent = styled.div` - display: flex; - align-items: center; - gap: 6px; -`; +import { ButtonContent, SpoilerButton } from "../../ui/SpoilerButton"; const ThinkingTextContainer = styled.span` display: inline-block; diff --git a/gui/src/components/modelSelection/ModelSelect.tsx b/gui/src/components/modelSelection/ModelSelect.tsx index 5aa221609..3108e7089 100644 --- a/gui/src/components/modelSelection/ModelSelect.tsx +++ b/gui/src/components/modelSelection/ModelSelect.tsx @@ -37,6 +37,7 @@ interface Option { title: string; apiKey?: string; sourceFile?: string; + isAutoDetected?: boolean; } function modelSelectTitle(model: any): string { @@ -75,8 +76,15 @@ function ModelOption({ {option.title} + {option.isAutoDetected && ( + + (autodetected) + + )} {showMissingApiKeyMsg && ( - (Missing API key) + + (Missing API key) + )}
@@ -132,6 +140,7 @@ function ModelSelect() { title: modelSelectTitle(model), apiKey: model.apiKey, sourceFile: model.sourceFile, + isAutoDetected: model.isFromAutoDetect, }; }), ); diff --git a/gui/src/components/ui/SpoilerButton.tsx b/gui/src/components/ui/SpoilerButton.tsx new file mode 100644 index 000000000..66b74bca9 --- /dev/null +++ b/gui/src/components/ui/SpoilerButton.tsx @@ -0,0 +1,31 @@ +import styled from "styled-components"; +import { defaultBorderRadius, lightGray, vscBackground } from "../index"; +import { getFontSize } from "../../util"; + +export const SpoilerButton = styled.div` + background-color: ${vscBackground}; + width: fit-content; + margin: 8px 6px 0px 2px; + font-size: ${getFontSize() - 2}px; + border: 0.5px solid ${lightGray}; + border-radius: ${defaultBorderRadius}; + padding: 4px 8px; + color: ${lightGray}; + cursor: pointer; + box-shadow: + 0 4px 6px rgba(0, 0, 0, 0.1), + 0 1px 3px rgba(0, 0, 0, 0.08); + transition: box-shadow 0.3s ease; + + &:hover { + box-shadow: + 0 6px 8px rgba(0, 0, 0, 0.15), + 0 3px 6px rgba(0, 0, 0, 0.1); + } +`; + +export const ButtonContent = styled.div` + display: flex; + align-items: center; + gap: 6px; +`; diff --git a/gui/src/hooks/TelemetryProviders.tsx b/gui/src/hooks/TelemetryProviders.tsx index 1a692417d..142d8eae4 100644 --- a/gui/src/hooks/TelemetryProviders.tsx +++ b/gui/src/hooks/TelemetryProviders.tsx @@ -29,7 +29,8 @@ const TelemetryProviders = ({ children }: PropsWithChildren) => { ); useEffect(() => { - if (allowAnonymousTelemetry && hasContinueEmail) { + // PostHog depends only on allowAnonymousTelemetry + if (allowAnonymousTelemetry) { // Initialize PostHog (existing logic) posthog.init("phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs", { api_host: "https://app.posthog.com", @@ -41,7 +42,13 @@ const TelemetryProviders = ({ children }: PropsWithChildren) => { }); posthog.identify(window.vscMachineId); posthog.opt_in_capturing(); + } else { + // Disable PostHog + posthog.opt_out_capturing(); + } + // Sentry depends on both allowAnonymousTelemetry and hasContinueEmail + if (allowAnonymousTelemetry && hasContinueEmail) { // Initialize Sentry (new for GUI - enhanced React setup) Sentry.init({ dsn: SENTRY_DSN, @@ -95,9 +102,6 @@ const TelemetryProviders = ({ children }: PropsWithChildren) => { }); Sentry.setUser(anonymizedUser); } else { - // Disable PostHog - posthog.opt_out_capturing(); - // Disable Sentry properly - close the client to stop all network requests try { const client = Sentry.getClient(); diff --git a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx index dbab7a18d..3cbcab061 100644 --- a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx @@ -17,7 +17,7 @@ export function EditFile(props: EditToolCallProps) { return null; } - const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilePath)} ${props.relativeFilePath}\n${props.changes}\n\`\`\``; + const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilePath)} ${props.relativeFilePath}${props.changes ? "\n" + props.changes + "\n" : ""}\`\`\``; return ( ({ + IdeMessengerContext: { + _currentValue: { post: vi.fn() }, + }, +})); + +vi.mock("../../../redux/hooks", () => ({ + useAppSelector: vi.fn(), +})); + +vi.mock("../../../components/ui", () => ({ + useFontSize: () => 14, +})); + +vi.mock("../../../util/clientTools/findAndReplaceUtils", () => ({ + performFindAndReplace: vi.fn(), +})); + +vi.mock("./utils", () => ({ + getStatusIcon: vi.fn(() =>
✓
), +})); + +vi.mock("react", async () => { + const actual = await vi.importActual("react"); + return { + ...actual, + useContext: () => ({ post: vi.fn() }), + }; +}); + +// Import mocked modules +import { useAppSelector } from "../../../redux/hooks"; +import { performFindAndReplace } from "../../../util/clientTools/findAndReplaceUtils"; + +const mockPost = vi.fn(); +const mockUseAppSelector = useAppSelector as any; +const mockPerformFindAndReplace = performFindAndReplace as any; + +describe("FindAndReplaceDisplay", () => { + const defaultProps = { + fileUri: "file:///test/file.ts", + relativeFilePath: "test/file.ts", + editingFileContents: "const old = 'value';\nconst other = 'test';", + edits: [ + { + old_string: "const old = 'value';", + new_string: "const new = 'value';", + replace_all: false, + }, + ] as EditOperation[], + toolCallId: "test-tool-call-id", + historyIndex: 0, + }; + + const mockToolCallState = { + status: "done" as const, + output: null, + }; + + const mockConfig = { + ui: { + showChatScrollbar: true, + codeWrap: false, + }, + }; + + beforeEach(() => { + vi.clearAllMocks(); + + mockUseAppSelector.mockImplementation((selector: any) => { + const mockState = { + config: { config: mockConfig }, + session: { + history: [], + codeBlockApplyStates: { states: [] }, + }, + }; + + if (selector.toString().includes("selectApplyStateByToolCallId")) { + return undefined; // No apply state by default + } + if (selector.toString().includes("selectToolCallById")) { + return mockToolCallState; + } + + return selector(mockState); + }); + + mockPerformFindAndReplace.mockImplementation( + (content: string, oldStr: string, newStr: string) => { + return content.replace(oldStr, newStr); + }, + ); + }); + + describe("basic rendering", () => { + it("should render with collapsed state by default", () => { + render(); + + expect(screen.getByText("file.ts")).toBeInTheDocument(); + expect( + screen.getByTestId("toggle-find-and-replace-diff"), + ).toBeInTheDocument(); + + // Should not show diff content when collapsed + const diffContent = screen.queryByText("-"); + expect(diffContent).not.toBeInTheDocument(); + }); + + it("should display file name from fileUri", () => { + render(); + expect(screen.getByText("file.ts")).toBeInTheDocument(); + }); + + it("should display file name from relativeFilePath when no fileUri", () => { + render( + , + ); + expect(screen.getByText("test.tsx")).toBeInTheDocument(); + }); + + it("should handle missing file paths gracefully", () => { + render( + , + ); + + // Should still render the component structure + expect( + screen.getByTestId("toggle-find-and-replace-diff"), + ).toBeInTheDocument(); + }); + }); + + describe("expand/collapse functionality", () => { + it("should expand when clicked", () => { + render(); + + const toggleButton = screen.getByTestId("toggle-find-and-replace-diff"); + fireEvent.click(toggleButton); + + // Should show diff content when expanded + expect(screen.getByText("-")).toBeInTheDocument(); + expect(screen.getByText("+")).toBeInTheDocument(); + }); + + it("should show content when tool call status is 'generated'", () => { + mockUseAppSelector.mockImplementation((selector: any) => { + const mockState = { + config: { config: mockConfig }, + session: { + history: [], + codeBlockApplyStates: { states: [] }, + }, + }; + + if (selector.toString().includes("selectToolCallById")) { + return { ...mockToolCallState, status: "generated" }; + } + if (selector.toString().includes("selectApplyStateByToolCallId")) { + return undefined; + } + + return selector(mockState); + }); + + render(); + + // Should show diff content without expanding + expect(screen.getByText("-")).toBeInTheDocument(); + expect(screen.getByText("+")).toBeInTheDocument(); + }); + }); + + describe("diff generation", () => { + it("should generate and display diff correctly", () => { + render(); + + const toggleButton = screen.getByTestId("toggle-find-and-replace-diff"); + fireEvent.click(toggleButton); + + // Should show removed line + expect(screen.getByText("const old = 'value';")).toBeInTheDocument(); + + // Should show added line + expect(screen.getByText("const new = 'value';")).toBeInTheDocument(); + + // Should show unchanged line + expect(screen.getByText("const other = 'test';")).toBeInTheDocument(); + }); + + it("should handle multiple edits", () => { + const multipleEdits = [ + { + old_string: "const old = 'value';", + new_string: "const new = 'value';", + replace_all: false, + }, + { + old_string: "const other = 'test';", + new_string: "const other = 'updated';", + replace_all: false, + }, + ] as EditOperation[]; + + mockPerformFindAndReplace + .mockReturnValueOnce("const new = 'value';\nconst other = 'test';") + .mockReturnValueOnce("const new = 'value';\nconst other = 'updated';"); + + render(); + + const toggleButton = screen.getByTestId("toggle-find-and-replace-diff"); + fireEvent.click(toggleButton); + + expect(mockPerformFindAndReplace).toHaveBeenCalledTimes(2); + }); + + it("should handle diff generation errors", () => { + mockPerformFindAndReplace.mockImplementation(() => { + throw new Error("Test error"); + }); + + render(); + + const toggleButton = screen.getByTestId("toggle-find-and-replace-diff"); + fireEvent.click(toggleButton); + + expect(screen.getByText("Error generating diff")).toBeInTheDocument(); + expect(screen.getByText("Test error")).toBeInTheDocument(); + }); + + it("should show 'No changes to display' when diff is empty", () => { + // Mock the function to return the exact same content (no changes) + mockPerformFindAndReplace.mockReturnValue( + defaultProps.editingFileContents, + ); + + render(); + + const toggleButton = screen.getByTestId("toggle-find-and-replace-diff"); + fireEvent.click(toggleButton); + + expect(screen.getByText("No changes to display")).toBeInTheDocument(); + }); + }); + + describe("apply actions", () => { + const mockApplyState: ApplyState = { + streamId: "test-stream-id", + status: "streaming", + numDiffs: 1, + fileContent: "test content", + }; + + beforeEach(() => { + mockUseAppSelector.mockImplementation((selector: any) => { + const mockState = { + config: { config: mockConfig }, + session: { + history: [], + codeBlockApplyStates: { states: [mockApplyState] }, + }, + }; + + if (selector.toString().includes("selectApplyStateByToolCallId")) { + return mockApplyState; + } + if (selector.toString().includes("selectToolCallById")) { + return mockToolCallState; + } + + return selector(mockState); + }); + }); + + it("should show apply actions when applyState exists", () => { + render(); + + // ApplyActions component should be rendered (we can test by looking for its structure) + // Since we don't have the exact structure, we test that the container is there + expect( + screen.getByTestId("toggle-find-and-replace-diff"), + ).toBeInTheDocument(); + }); + + it("should handle accept action", () => { + render(); + + // This would need more detailed testing if ApplyActions was properly mocked + // For now, we verify the component renders without errors + expect( + screen.getByTestId("toggle-find-and-replace-diff"), + ).toBeInTheDocument(); + }); + }); + + describe("content handling", () => { + it("should use editingFileContents when provided", () => { + render(); + + const toggleButton = screen.getByTestId("toggle-find-and-replace-diff"); + fireEvent.click(toggleButton); + + expect(mockPerformFindAndReplace).toHaveBeenCalledWith( + "const old = 'value';\nconst other = 'test';", + "const old = 'value';", + "const new = 'value';", + false, + 0, + ); + }); + + it("should fallback to edit old_strings when no editingFileContents", () => { + render( + , + ); + + const toggleButton = screen.getByTestId("toggle-find-and-replace-diff"); + fireEvent.click(toggleButton); + + expect(mockPerformFindAndReplace).toHaveBeenCalledWith( + "const old = 'value';", + "const old = 'value';", + "const new = 'value';", + false, + 0, + ); + }); + }); +}); diff --git a/gui/src/pages/gui/ToolCallDiv/FindAndReplace.tsx b/gui/src/pages/gui/ToolCallDiv/FindAndReplace.tsx new file mode 100644 index 000000000..18d995601 --- /dev/null +++ b/gui/src/pages/gui/ToolCallDiv/FindAndReplace.tsx @@ -0,0 +1,274 @@ +import { ChevronDownIcon } from "@heroicons/react/24/outline"; +import { ApplyState } from "core"; +import { EditOperation } from "core/tools/definitions/multiEdit"; +import { renderContextItems } from "core/util/messageContent"; +import { getLastNPathParts, getUriPathBasename } from "core/util/uri"; +import { diffLines } from "diff"; +import { useContext, useMemo, useState } from "react"; +import { ApplyActions } from "../../../components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions"; +import { FileInfo } from "../../../components/StyledMarkdownPreview/StepContainerPreToolbar/FileInfo"; +import { useFontSize } from "../../../components/ui"; +import { IdeMessengerContext } from "../../../context/IdeMessenger"; +import { useAppSelector } from "../../../redux/hooks"; +import { + selectApplyStateByToolCallId, + selectToolCallById, +} from "../../../redux/selectors/selectToolCalls"; +import { performFindAndReplace } from "../../../util/clientTools/findAndReplaceUtils"; +import { getStatusIcon } from "./utils"; + +interface FindAndReplaceDisplayProps { + fileUri?: string; + editingFileContents?: string; + relativeFilePath?: string; + edits: EditOperation[]; + toolCallId: string; + historyIndex: number; +} + +export function FindAndReplaceDisplay({ + fileUri, + relativeFilePath, + editingFileContents, + edits, + toolCallId, + historyIndex, +}: FindAndReplaceDisplayProps) { + const [isExpanded, setIsExpanded] = useState(false); + const ideMessenger = useContext(IdeMessengerContext); + const applyState: ApplyState | undefined = useAppSelector((state) => + selectApplyStateByToolCallId(state, toolCallId), + ); + const fontSize = useFontSize(); + const toolCallState = useAppSelector((state) => + selectToolCallById(state, toolCallId), + ); + const config = useAppSelector((state) => state.config.config); + + const displayName = useMemo(() => { + if (fileUri) { + return getUriPathBasename(fileUri); + } + if (relativeFilePath) { + return getLastNPathParts(relativeFilePath, 1); + } + return ""; + }, [fileUri, relativeFilePath]); + + // Get file content from tool call state instead of reading file + const currentFileContent = useMemo(() => { + if (editingFileContents) { + return editingFileContents; + } + return edits?.map((edit) => edit.old_string ?? "").join("\n"); + }, [editingFileContents, edits]); + + const diffResult = useMemo(() => { + if (!currentFileContent) { + return null; + } + + try { + // Apply all edits sequentially + let newContent = currentFileContent; + for (let i = 0; i < edits.length; i++) { + const { + old_string: oldString, + new_string: newString, + replace_all: replaceAll, + } = edits[i]; + newContent = performFindAndReplace( + newContent, + oldString, + newString, + replaceAll, + i, + ); + } + + // Generate diff between original and final content + const diff = diffLines(currentFileContent, newContent); + return { diff, newContent, error: null }; + } catch (error) { + return { + diff: null, + newContent: null, + error: error instanceof Error ? error.message : "Unknown error", + }; + } + }, [currentFileContent, edits]); + + const statusIcon = useMemo(() => { + const status = toolCallState?.status; + if (status) { + if (status === "canceled" || status === "errored" || status === "done") { + return ( +
{ + if (toolCallState.output) { + e.stopPropagation(); + ideMessenger.post("showVirtualFile", { + name: "Edit output", + content: renderContextItems(toolCallState.output), + }); + } + }} + > + {getStatusIcon(toolCallState.status)} +
+ ); + } + } + }, [toolCallState?.status, toolCallState?.output]); + + // Unified container component that always renders the same structure + const renderContainer = (content: React.ReactNode) => ( +
+
{ + setIsExpanded((prev) => !prev); + }} + > +
+ {statusIcon} + + { + if (!fileUri) { + return; + } + e.stopPropagation(); + ideMessenger.post("openFile", { path: fileUri }); + }} + /> +
+ + {applyState && ( + { + ideMessenger.post(`acceptDiff`, { + filepath: fileUri, + streamId: applyState.streamId, + }); + }} + onClickReject={() => { + ideMessenger.post(`rejectDiff`, { + filepath: fileUri, + streamId: applyState.streamId, + }); + }} + disableManualApply={true} + applyState={applyState} + /> + )} +
+ {toolCallState?.status === "generated" || isExpanded ? content : null} +
+ ); + + if (diffResult?.error) { + return renderContainer( +
+ Error generating diff {diffResult.error} +
, + ); + } + + if ( + !diffResult?.diff || + (diffResult.diff.length === 1 && + !diffResult.diff[0].added && + !diffResult.diff[0].removed) + ) { + return renderContainer( +
No changes to display
, + ); + } + + return renderContainer( +
+
+        {diffResult.diff.map((part, index) => {
+          if (part.removed) {
+            return (
+              
+ {part.value.split("\n").map((line, lineIndex) => { + if ( + line === "" && + lineIndex === part.value.split("\n").length - 1 + ) + return null; + return ( +
+ - + {line} +
+ ); + })} +
+ ); + } else if (part.added) { + return ( +
+ {part.value.split("\n").map((line, lineIndex) => { + if ( + line === "" && + lineIndex === part.value.split("\n").length - 1 + ) + return null; + return ( +
+ + + {line} +
+ ); + })} +
+ ); + } else { + return ( +
+ {part.value.split("\n").map((line, lineIndex) => { + if ( + line === "" && + lineIndex === part.value.split("\n").length - 1 + ) + return null; + return ( +
+ + {" "} + + {line} +
+ ); + })} +
+ ); + } + })} +
+
, + ); +} diff --git a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx index 52c03fd85..0fcdc0fc1 100644 --- a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx @@ -1,7 +1,9 @@ import { ToolCallState } from "core"; import { BuiltInToolNames } from "core/tools/builtIn"; +import { EditOperation } from "core/tools/definitions/multiEdit"; import { CreateFile } from "./CreateFile"; import { EditFile } from "./EditFile"; +import { FindAndReplaceDisplay } from "./FindAndReplace"; import { RunTerminalCommand } from "./RunTerminalCommand"; function FunctionSpecificToolCallDiv({ @@ -33,9 +35,9 @@ function FunctionSpecificToolCallDiv({ /> ); case BuiltInToolNames.SearchAndReplaceInFile: - const changes = args.diffs + const changes = args?.diffs ? Array.isArray(args.diffs) - ? args.diffs.join("\n\n---\n\n") + ? args.diffs?.join("\n\n---\n\n") : args.diffs : ""; @@ -49,6 +51,35 @@ function FunctionSpecificToolCallDiv({ historyIndex={historyIndex} /> ); + case BuiltInToolNames.SingleFindAndReplace: + const edits: EditOperation[] = [ + { + old_string: args?.old_string ?? "", + new_string: args?.new_string ?? "", + replace_all: args?.replace_all, + }, + ]; + return ( + + ); + case BuiltInToolNames.MultiEdit: + return ( + + ); case BuiltInToolNames.RunTerminalCommand: return ( { - switch (status) { - case "running": - return "bg-success"; - case "completed": - return "bg-success"; - case "background": - return "bg-accent"; - case "failed": - return "bg-error"; - default: - return "bg-success"; - } - }; - - return ( - - ); -} - export function RunTerminalCommand(props: RunTerminalCommandToolCallProps) { - const dispatch = useAppDispatch(); - // Find the terminal output from context items if available const terminalItem = props.toolCallState.output?.find( (item) => item.name === "Terminal", @@ -52,43 +16,6 @@ export function RunTerminalCommand(props: RunTerminalCommandToolCallProps) { const terminalContent = terminalItem?.content || ""; const statusMessage = terminalItem?.status || ""; const isRunning = props.toolCallState.status === "calling"; - const hasOutput = terminalContent.length > 0; - - const displayLines = 15; - - // Process terminal content for line limiting - const processedTerminalContent = useMemo(() => { - if (!terminalContent) - return { - fullContent: "", - limitedContent: "", - totalLines: 0, - isLimited: false, - hiddenLinesCount: 0, - }; - - const lines = terminalContent.split("\n"); - const totalLines = lines.length; - - if (totalLines > displayLines) { - const lastTwentyLines = lines.slice(-displayLines); - return { - fullContent: terminalContent, - limitedContent: lastTwentyLines.join("\n"), - totalLines, - isLimited: true, - hiddenLinesCount: totalLines - displayLines, - }; - } - - return { - fullContent: terminalContent, - limitedContent: terminalContent, - totalLines, - isLimited: false, - hiddenLinesCount: 0, - }; - }, [terminalContent]); // Determine status type let statusType: "running" | "completed" | "failed" | "background" = @@ -102,55 +29,13 @@ export function RunTerminalCommand(props: RunTerminalCommandToolCallProps) { } return ( -
- {/* Command */} - - - {/* Terminal output with ANSI support */} - {isRunning && !hasOutput && ( -
Waiting for output...
- )} - {hasOutput && ( - {processedTerminalContent.limitedContent} - } - expandedContent={{processedTerminalContent.fullContent}} - /> - )} - - {/* Status information */} - {(statusMessage || isRunning) && ( - - )} -
+ ); } diff --git a/gui/src/pages/gui/ToolCallDiv/index.tsx b/gui/src/pages/gui/ToolCallDiv/index.tsx index 12556998e..31f50f471 100644 --- a/gui/src/pages/gui/ToolCallDiv/index.tsx +++ b/gui/src/pages/gui/ToolCallDiv/index.tsx @@ -54,7 +54,11 @@ export function ToolCallDiv({ // Obviously missing the truncate and args buttons // All the info from args is displayed here // But we'd need a nicer place to put the truncate button and the X icon when tool call fails - if (functionName === BuiltInToolNames.SearchAndReplaceInFile) { + if ( + functionName === BuiltInToolNames.SearchAndReplaceInFile || + functionName === BuiltInToolNames.SingleFindAndReplace || + functionName === BuiltInToolNames.MultiEdit + ) { return (
; + }>, + ) => { + const toolCallState = findToolCallById( + state.history, + action.payload.toolCallId, + ); + if (toolCallState) { + toolCallState.parsedArgs = action.payload.newArgs; + } + }, cancelToolCall: ( state, action: PayloadAction<{ @@ -1024,6 +1039,7 @@ export const { acceptToolCall, setToolGenerated, updateToolCallOutput, + setToolCallArgs, setMode, setIsSessionMetadataLoading, setAllSessionMetadata, diff --git a/gui/src/redux/thunks/enhanceParsedArgs.ts b/gui/src/redux/thunks/enhanceParsedArgs.ts new file mode 100644 index 000000000..75141abb8 --- /dev/null +++ b/gui/src/redux/thunks/enhanceParsedArgs.ts @@ -0,0 +1,53 @@ +import { BuiltInToolNames } from "core/tools/builtIn"; +import { resolveRelativePathInDir } from "core/util/ideUtils"; +import { getUriPathBasename } from "core/util/uri"; +import { IIdeMessenger } from "../../context/IdeMessenger"; +import { setToolCallArgs } from "../slices/sessionSlice"; +import { AppThunkDispatch } from "../store"; + +export async function enhanceParsedArgs( + ideMessenger: IIdeMessenger, + dispatch: AppThunkDispatch, + toolName: string | undefined, + toolCallId: string, + currentArgs: undefined | Record, +) { + // Add file content to parsedArgs for find/replace tools + let enhancedArgs = { ...currentArgs }; + if ( + (toolName === BuiltInToolNames.SingleFindAndReplace || + toolName === BuiltInToolNames.MultiEdit || + toolName === BuiltInToolNames.SearchAndReplaceInFile) && + currentArgs?.filepath && + !currentArgs?.editingFileContents + ) { + try { + const fileUri = await resolveRelativePathInDir( + currentArgs.filepath, + ideMessenger.ide, + ); + if (!fileUri) { + throw new Error(`File ${currentArgs.filepath} not found`); + } + const baseName = getUriPathBasename(fileUri); + const fileContent = await ideMessenger.ide.readFile(fileUri); + enhancedArgs = { + ...currentArgs, + fileUri, + baseName, + editingFileContents: fileContent, + }; + dispatch( + setToolCallArgs({ + toolCallId, + newArgs: enhancedArgs, + }), + ); + } catch (error) { + // If we can't read the file, let the tool handle the error + console.warn( + `Failed to enhance args: failed to read file ${currentArgs?.filepath}`, + ); + } + } +} diff --git a/gui/src/redux/thunks/handleApplyStateUpdate.test.ts b/gui/src/redux/thunks/handleApplyStateUpdate.test.ts new file mode 100644 index 000000000..46ae54c35 --- /dev/null +++ b/gui/src/redux/thunks/handleApplyStateUpdate.test.ts @@ -0,0 +1,762 @@ +import { ApplyState, ApplyToFilePayload, ToolCallState } from "core"; +import { EDIT_MODE_STREAM_ID } from "core/edit/constants"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { logAgentModeEditOutcome } from "../../util/editOutcomeLogger"; +import { + selectApplyStateByToolCallId, + selectToolCallById, +} from "../selectors/selectToolCalls"; +import { updateEditStateApplyState } from "../slices/editState"; +import { + acceptToolCall, + errorToolCall, + updateApplyState, + updateToolCallOutput, +} from "../slices/sessionSlice"; +import { findToolCallById, logToolUsage } from "../util"; +import { exitEdit } from "./edit"; +import { + applyForEditTool, + handleApplyStateUpdate, +} from "./handleApplyStateUpdate"; +import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; + +// Mock dependencies +vi.mock("../../util/editOutcomeLogger", () => ({ + logAgentModeEditOutcome: vi.fn(), +})); + +vi.mock("../selectors/selectToolCalls", () => ({ + selectApplyStateByToolCallId: vi.fn(), + selectToolCallById: vi.fn(), +})); + +vi.mock("../slices/editState", () => ({ + updateEditStateApplyState: vi.fn(() => ({ + type: "editState/updateApplyState", + })), +})); + +vi.mock("../slices/sessionSlice", () => ({ + acceptToolCall: vi.fn(() => ({ type: "session/acceptToolCall" })), + errorToolCall: vi.fn(() => ({ type: "session/errorToolCall" })), + updateApplyState: vi.fn(() => ({ type: "session/updateApplyState" })), + updateToolCallOutput: vi.fn(() => ({ type: "session/updateToolCallOutput" })), +})); + +vi.mock("../util", () => ({ + findToolCallById: vi.fn(), + logToolUsage: vi.fn(), +})); + +vi.mock("./edit", () => ({ + exitEdit: vi.fn(() => ({ type: "edit/exitEdit" })), +})); + +vi.mock("./streamResponseAfterToolCall", () => ({ + streamResponseAfterToolCall: vi.fn(() => ({ + type: "session/streamResponseAfterToolCall", + })), +})); + +const UNUSED_TOOL_CALL_PARAMS = { + toolCall: { + id: "name", + function: { + name: "unused", + arguments: "unused", + }, + type: "function" as const, + }, + parsedArgs: {}, +}; + +describe("handleApplyStateUpdate", () => { + let mockDispatch: any; + let mockGetState: any; + let mockExtra: any; + + beforeEach(() => { + vi.clearAllMocks(); + mockDispatch = vi.fn(); + mockGetState = vi.fn(); + mockExtra = { + ideMessenger: { + post: vi.fn(), + request: vi.fn(), + }, + }; + }); + + describe("edit mode handling", () => { + it("should handle edit mode apply state updates", async () => { + const applyState: ApplyState = { + streamId: EDIT_MODE_STREAM_ID, + toolCallId: "test-tool-call", + status: "streaming", + filepath: "test.txt", + numDiffs: 1, + }; + + const thunk = handleApplyStateUpdate(applyState); + await thunk(mockDispatch, mockGetState, mockExtra); + + expect(updateEditStateApplyState).toHaveBeenCalledWith(applyState); + expect(mockDispatch).toHaveBeenCalledWith( + expect.objectContaining({ type: "editState/updateApplyState" }), + ); + }); + + it("should exit edit mode when status is closed", async () => { + const toolCallState: ToolCallState = { + toolCallId: "test-tool-call", + status: "done", + ...UNUSED_TOOL_CALL_PARAMS, + }; + vi.mocked(findToolCallById).mockReturnValue(toolCallState); + + mockGetState.mockReturnValue({ + session: { history: [] }, + }); + + const applyState: ApplyState = { + streamId: EDIT_MODE_STREAM_ID, + toolCallId: "test-tool-call", + status: "closed", + filepath: "test.txt", + numDiffs: 1, + }; + + const thunk = handleApplyStateUpdate(applyState); + await thunk(mockDispatch, mockGetState, mockExtra); + + expect(logToolUsage).toHaveBeenCalledWith( + toolCallState, + true, + true, + mockExtra.ideMessenger, + ); + expect(exitEdit).toHaveBeenCalledWith({}); + expect(mockDispatch).toHaveBeenCalledWith( + expect.objectContaining({ type: "edit/exitEdit" }), + ); + }); + }); + + describe("chat/agent mode handling", () => { + it("should handle non-edit mode apply state updates", async () => { + const applyState: ApplyState = { + streamId: "chat-stream", + toolCallId: "test-tool-call", + status: "streaming", + filepath: "test.txt", + numDiffs: 1, + }; + + const thunk = handleApplyStateUpdate(applyState); + await thunk(mockDispatch, mockGetState, mockExtra); + + expect(updateApplyState).toHaveBeenCalledWith(applyState); + expect(mockDispatch).toHaveBeenCalledWith( + expect.objectContaining({ type: "session/updateApplyState" }), + ); + }); + + it("should auto-accept diffs when configured and status is done", async () => { + mockGetState.mockReturnValue({ + config: { + config: { + ui: { + autoAcceptEditToolDiffs: true, + }, + }, + }, + session: { history: [] }, + }); + + const applyState: ApplyState = { + streamId: "chat-stream", + toolCallId: "test-tool-call", + status: "done", + filepath: "test.txt", + numDiffs: 1, + }; + + const thunk = handleApplyStateUpdate(applyState); + await thunk(mockDispatch, mockGetState, mockExtra); + + expect(mockExtra.ideMessenger.post).toHaveBeenCalledWith("acceptDiff", { + streamId: "chat-stream", + filepath: "test.txt", + }); + }); + + it("should not auto-accept when config is disabled", async () => { + mockGetState.mockReturnValue({ + config: { + config: { + ui: { + autoAcceptEditToolDiffs: false, + }, + }, + }, + session: { history: [] }, + }); + + const applyState: ApplyState = { + streamId: "chat-stream", + toolCallId: "test-tool-call", + status: "done", + filepath: "test.txt", + numDiffs: 1, + }; + + const thunk = handleApplyStateUpdate(applyState); + await thunk(mockDispatch, mockGetState, mockExtra); + + expect(mockExtra.ideMessenger.post).not.toHaveBeenCalled(); + }); + }); + + describe("closed status handling", () => { + it("should handle accepted tool call closure", async () => { + const toolCallState: ToolCallState = { + toolCallId: "test-tool-call", + status: "done", + ...UNUSED_TOOL_CALL_PARAMS, + }; + const newApplyState = { streamId: "chat-stream" }; + + vi.mocked(findToolCallById).mockReturnValue(toolCallState); + mockGetState.mockReturnValue({ + session: { + history: [], + codeBlockApplyStates: { + states: [newApplyState], + }, + }, + config: { config: {} }, + }); + + const applyState: ApplyState = { + streamId: "chat-stream", + toolCallId: "test-tool-call", + status: "closed", + filepath: "test.txt", + numDiffs: 1, + }; + + const thunk = handleApplyStateUpdate(applyState); + await thunk(mockDispatch, mockGetState, mockExtra); + + expect(logToolUsage).toHaveBeenCalledWith( + toolCallState, + true, + true, + mockExtra.ideMessenger, + ); + expect(logAgentModeEditOutcome).toHaveBeenCalledWith( + [], + {}, + toolCallState, + newApplyState, + true, + mockExtra.ideMessenger, + ); + expect(acceptToolCall).toHaveBeenCalledWith({ + toolCallId: "test-tool-call", + }); + expect(streamResponseAfterToolCall).toHaveBeenCalledWith({ + toolCallId: "test-tool-call", + }); + }); + + it("should handle canceled tool call closure", async () => { + const toolCallState: ToolCallState = { + toolCallId: "test-tool-call", + status: "canceled", + ...UNUSED_TOOL_CALL_PARAMS, + }; + const newApplyState = { streamId: "chat-stream" }; + + vi.mocked(findToolCallById).mockReturnValue(toolCallState); + mockGetState.mockReturnValue({ + session: { + history: [], + codeBlockApplyStates: { + states: [newApplyState], + }, + }, + config: { config: {} }, + }); + + const applyState: ApplyState = { + streamId: "chat-stream", + toolCallId: "test-tool-call", + status: "closed", + filepath: "test.txt", + numDiffs: 1, + }; + + const thunk = handleApplyStateUpdate(applyState); + await thunk(mockDispatch, mockGetState, mockExtra); + + expect(logToolUsage).toHaveBeenCalledWith( + toolCallState, + false, + true, + mockExtra.ideMessenger, + ); + expect(logAgentModeEditOutcome).toHaveBeenCalledWith( + [], + {}, + toolCallState, + newApplyState, + false, + mockExtra.ideMessenger, + ); + expect(acceptToolCall).not.toHaveBeenCalled(); + expect(streamResponseAfterToolCall).not.toHaveBeenCalled(); + }); + + it("should handle errored tool call closure", async () => { + const toolCallState: ToolCallState = { + toolCallId: "test-tool-call", + status: "errored", + ...UNUSED_TOOL_CALL_PARAMS, + }; + const newApplyState = { streamId: "chat-stream" }; + + vi.mocked(findToolCallById).mockReturnValue(toolCallState); + mockGetState.mockReturnValue({ + session: { + history: [], + codeBlockApplyStates: { + states: [newApplyState], + }, + }, + config: { config: {} }, + }); + + const applyState: ApplyState = { + streamId: "chat-stream", + toolCallId: "test-tool-call", + status: "closed", + filepath: "test.txt", + numDiffs: 1, + }; + + const thunk = handleApplyStateUpdate(applyState); + await thunk(mockDispatch, mockGetState, mockExtra); + + expect(acceptToolCall).not.toHaveBeenCalled(); + expect(streamResponseAfterToolCall).toHaveBeenCalledWith({ + toolCallId: "test-tool-call", + }); + }); + + it("should handle closure when no tool call found", async () => { + vi.mocked(findToolCallById).mockReturnValue(undefined); + mockGetState.mockReturnValue({ + session: { + history: [], + codeBlockApplyStates: { + states: [], + }, + }, + }); + + const applyState: ApplyState = { + streamId: "chat-stream", + toolCallId: "test-tool-call", + status: "closed", + filepath: "test.txt", + numDiffs: 1, + }; + + const thunk = handleApplyStateUpdate(applyState); + await thunk(mockDispatch, mockGetState, mockExtra); + + expect(logToolUsage).not.toHaveBeenCalled(); + expect(acceptToolCall).not.toHaveBeenCalled(); + expect(streamResponseAfterToolCall).not.toHaveBeenCalled(); + }); + + it("should handle closure when no apply state found", async () => { + const toolCallState: ToolCallState = { + toolCallId: "test-tool-call", + status: "done", + ...UNUSED_TOOL_CALL_PARAMS, + }; + + vi.mocked(findToolCallById).mockReturnValue(toolCallState); + mockGetState.mockReturnValue({ + session: { + history: [], + codeBlockApplyStates: { + states: [], + }, + }, + config: { config: {} }, + }); + + const applyState: ApplyState = { + streamId: "chat-stream", + toolCallId: "test-tool-call", + status: "closed", + filepath: "test.txt", + numDiffs: 1, + }; + + const thunk = handleApplyStateUpdate(applyState); + await thunk(mockDispatch, mockGetState, mockExtra); + + expect(logAgentModeEditOutcome).not.toHaveBeenCalled(); + expect(acceptToolCall).toHaveBeenCalledWith({ + toolCallId: "test-tool-call", + }); + }); + }); + + describe("edge cases", () => { + it("should handle apply state without toolCallId", async () => { + const applyState: ApplyState = { + streamId: "chat-stream", + status: "streaming", + filepath: "test.txt", + numDiffs: 1, + }; + + const thunk = handleApplyStateUpdate(applyState); + await thunk(mockDispatch, mockGetState, mockExtra); + + expect(updateApplyState).toHaveBeenCalledWith(applyState); + expect(acceptToolCall).not.toHaveBeenCalled(); + expect(streamResponseAfterToolCall).not.toHaveBeenCalled(); + }); + + it("should handle different status values", async () => { + const statusValues: ApplyState["status"][] = [ + "not-started", + "streaming", + "done", + "closed", + ]; + + for (const status of statusValues) { + vi.clearAllMocks(); + + const applyState: ApplyState = { + streamId: "chat-stream", + toolCallId: "test-tool-call", + status, + filepath: "test.txt", + numDiffs: 1, + }; + + const thunk = handleApplyStateUpdate(applyState); + await thunk(mockDispatch, mockGetState, mockExtra); + + expect(updateApplyState).toHaveBeenCalledWith(applyState); + } + }); + }); +}); + +describe("applyForEditTool", () => { + let mockDispatch: any; + let mockGetState: any; + let mockExtra: any; + + beforeEach(() => { + vi.clearAllMocks(); + mockDispatch = vi.fn(); + mockGetState = vi.fn(); + mockExtra = { + ideMessenger: { + request: vi.fn(), + }, + }; + }); + + describe("successful application", () => { + it("should successfully apply changes to file", async () => { + const payload: ApplyToFilePayload & { toolCallId: string } = { + toolCallId: "test-tool-call", + streamId: "test-stream", + filepath: "test.txt", + text: "new content", + isSearchAndReplace: true, + }; + + mockExtra.ideMessenger.request.mockResolvedValue({ status: "success" }); + + const thunk = applyForEditTool(payload); + await thunk(mockDispatch, mockGetState, mockExtra); + + expect(updateApplyState).toHaveBeenCalledWith({ + streamId: "test-stream", + toolCallId: "test-tool-call", + status: "not-started", + }); + expect(mockDispatch).toHaveBeenCalledWith( + expect.objectContaining({ type: "session/updateApplyState" }), + ); + expect(mockExtra.ideMessenger.request).toHaveBeenCalledWith( + "applyToFile", + payload, + ); + }); + }); + + describe("error handling", () => { + it("should handle IDE messenger request failure", async () => { + const payload: ApplyToFilePayload & { toolCallId: string } = { + toolCallId: "test-tool-call", + streamId: "test-stream", + filepath: "test.txt", + text: "new content", + isSearchAndReplace: true, + }; + + const toolCallState: ToolCallState = { + toolCallId: "test-tool-call", + status: "calling", + ...UNUSED_TOOL_CALL_PARAMS, + }; + const applyState: ApplyState = { + status: "streaming", + streamId: "test-stream", + }; + + vi.mocked(selectToolCallById).mockReturnValue(toolCallState); + vi.mocked(selectApplyStateByToolCallId).mockReturnValue(applyState); + mockGetState.mockReturnValue({}); + + mockExtra.ideMessenger.request.mockRejectedValue( + new Error("Request failed"), + ); + + const thunk = applyForEditTool(payload); + await thunk(mockDispatch, mockGetState, mockExtra); + + expect(errorToolCall).toHaveBeenCalledWith({ + toolCallId: "test-tool-call", + }); + expect(updateToolCallOutput).toHaveBeenCalledWith({ + toolCallId: "test-tool-call", + contextItems: [ + { + icon: "problems", + name: "Apply Error", + description: "Failed to apply changes", + content: `Error editing file: failed to apply changes to file.\n\nPlease try again with correct args or notify the user and request further instructions.`, + hidden: false, + }, + ], + }); + }); + + it("should handle IDE messenger error response", async () => { + const payload: ApplyToFilePayload & { toolCallId: string } = { + toolCallId: "test-tool-call", + streamId: "test-stream", + filepath: "test.txt", + text: "new content", + isSearchAndReplace: true, + }; + + const toolCallState: ToolCallState = { + toolCallId: "test-tool-call", + status: "calling", + ...UNUSED_TOOL_CALL_PARAMS, + }; + const applyState: ApplyState = { + status: "streaming", + streamId: "test-stream", + }; + + vi.mocked(selectToolCallById).mockReturnValue(toolCallState); + vi.mocked(selectApplyStateByToolCallId).mockReturnValue(applyState); + mockGetState.mockReturnValue({}); + + mockExtra.ideMessenger.request.mockResolvedValue({ status: "error" }); + + const thunk = applyForEditTool(payload); + await thunk(mockDispatch, mockGetState, mockExtra); + + expect(errorToolCall).toHaveBeenCalledWith({ + toolCallId: "test-tool-call", + }); + expect(updateToolCallOutput).toHaveBeenCalledWith({ + toolCallId: "test-tool-call", + contextItems: [ + { + icon: "problems", + name: "Apply Error", + description: "Failed to apply changes", + content: `Error editing file: failed to apply changes to file.\n\nPlease try again with correct args or notify the user and request further instructions.`, + hidden: false, + }, + ], + }); + }); + + it("should not error if tool call is not in calling state", async () => { + const payload: ApplyToFilePayload & { toolCallId: string } = { + toolCallId: "test-tool-call", + streamId: "test-stream", + filepath: "test.txt", + text: "new content", + isSearchAndReplace: true, + }; + + const toolCallState: ToolCallState = { + toolCallId: "test-tool-call", + status: "done", + ...UNUSED_TOOL_CALL_PARAMS, + }; + const applyState: ApplyState = { + status: "streaming", + streamId: "test-stream", + }; + + vi.mocked(selectToolCallById).mockReturnValue(toolCallState); + vi.mocked(selectApplyStateByToolCallId).mockReturnValue(applyState); + mockGetState.mockReturnValue({}); + + mockExtra.ideMessenger.request.mockRejectedValue( + new Error("Request failed"), + ); + + const thunk = applyForEditTool(payload); + await thunk(mockDispatch, mockGetState, mockExtra); + + expect(errorToolCall).not.toHaveBeenCalled(); + expect(updateToolCallOutput).not.toHaveBeenCalled(); + }); + + it("should not error if apply state is closed", async () => { + const payload: ApplyToFilePayload & { toolCallId: string } = { + toolCallId: "test-tool-call", + streamId: "test-stream", + filepath: "test.txt", + text: "new content", + isSearchAndReplace: true, + }; + + const toolCallState: ToolCallState = { + toolCallId: "test-tool-call", + status: "calling", + ...UNUSED_TOOL_CALL_PARAMS, + }; + const applyState: ApplyState = { + status: "closed", + streamId: "test-stream", + }; // Already closed + + vi.mocked(selectToolCallById).mockReturnValue(toolCallState); + vi.mocked(selectApplyStateByToolCallId).mockReturnValue(applyState); + mockGetState.mockReturnValue({}); + + mockExtra.ideMessenger.request.mockRejectedValue( + new Error("Request failed"), + ); + + const thunk = applyForEditTool(payload); + await thunk(mockDispatch, mockGetState, mockExtra); + + expect(errorToolCall).not.toHaveBeenCalled(); + expect(updateToolCallOutput).not.toHaveBeenCalled(); + }); + + it("should not error if tool call state is not found", async () => { + const payload: ApplyToFilePayload & { toolCallId: string } = { + toolCallId: "test-tool-call", + streamId: "test-stream", + filepath: "test.txt", + text: "new content", + isSearchAndReplace: true, + }; + + vi.mocked(selectToolCallById).mockReturnValue(undefined); // Tool call not found + vi.mocked(selectApplyStateByToolCallId).mockReturnValue({ + status: "streaming", + streamId: "test-stream", + }); + mockGetState.mockReturnValue({}); + + mockExtra.ideMessenger.request.mockRejectedValue( + new Error("Request failed"), + ); + + const thunk = applyForEditTool(payload); + await thunk(mockDispatch, mockGetState, mockExtra); + + expect(errorToolCall).not.toHaveBeenCalled(); + expect(updateToolCallOutput).not.toHaveBeenCalled(); + }); + + it("should not error if apply state is not found", async () => { + const payload: ApplyToFilePayload & { toolCallId: string } = { + toolCallId: "test-tool-call", + streamId: "test-stream", + filepath: "test.txt", + text: "new content", + isSearchAndReplace: true, + }; + + vi.mocked(selectApplyStateByToolCallId).mockReturnValue(undefined); // Apply state not found + mockGetState.mockReturnValue({}); + + mockExtra.ideMessenger.request.mockRejectedValue( + new Error("Request failed"), + ); + + const thunk = applyForEditTool(payload); + await thunk(mockDispatch, mockGetState, mockExtra); + + expect(errorToolCall).not.toHaveBeenCalled(); + expect(updateToolCallOutput).not.toHaveBeenCalled(); + }); + }); + + describe("edge cases", () => { + it("should handle different payload types", async () => { + const payloads: (ApplyToFilePayload & { toolCallId: string })[] = [ + { + toolCallId: "test-1", + streamId: "stream-1", + filepath: "file1.txt", + text: "content 1", + isSearchAndReplace: false, + }, + { + toolCallId: "test-2", + streamId: "stream-2", + filepath: "file2.js", + text: "content 2", + isSearchAndReplace: true, + }, + ]; + + for (const payload of payloads) { + vi.clearAllMocks(); + mockExtra.ideMessenger.request.mockResolvedValue({ status: "success" }); + + const thunk = applyForEditTool(payload); + await thunk(mockDispatch, mockGetState, mockExtra); + + expect(mockExtra.ideMessenger.request).toHaveBeenCalledWith( + "applyToFile", + payload, + ); + expect(updateApplyState).toHaveBeenCalledWith({ + streamId: payload.streamId, + toolCallId: payload.toolCallId, + status: "not-started", + }); + } + }); + }); +}); diff --git a/gui/src/redux/thunks/handleApplyStateUpdate.ts b/gui/src/redux/thunks/handleApplyStateUpdate.ts index 1a56fe04b..25532e750 100644 --- a/gui/src/redux/thunks/handleApplyStateUpdate.ts +++ b/gui/src/redux/thunks/handleApplyStateUpdate.ts @@ -1,5 +1,5 @@ import { createAsyncThunk } from "@reduxjs/toolkit"; -import { ApplyState } from "core"; +import { ApplyState, ApplyToFilePayload } from "core"; import { EDIT_MODE_STREAM_ID } from "core/edit/constants"; import { logAgentModeEditOutcome } from "../../util/editOutcomeLogger"; import { @@ -105,13 +105,30 @@ export const handleApplyStateUpdate = createAsyncThunk< }, ); -export const handleEditToolApplyError = createAsyncThunk< +export const applyForEditTool = createAsyncThunk< void, - { toolCallId: string }, + ApplyToFilePayload & { toolCallId: string }, ThunkApiType ->( - "apply/handleEditError", - async ({ toolCallId }, { dispatch, getState, extra }) => { +>("apply/editTool", async (payload, { dispatch, getState, extra }) => { + const { toolCallId, streamId } = payload; + dispatch( + updateApplyState({ + streamId, + toolCallId, + status: "not-started", + }), + ); + + let didError = false; + try { + const response = await extra.ideMessenger.request("applyToFile", payload); + if (response.status === "error") { + didError = true; + } + } catch (e) { + didError = true; + } + if (didError) { const state = getState(); const toolCallState = selectToolCallById(state, toolCallId); @@ -149,5 +166,5 @@ export const handleEditToolApplyError = createAsyncThunk< }), ); } - }, -); + } +}); diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index 218883cb9..dbd322357 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -1,8 +1,7 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; -import { LLMFullCompletionOptions, ModelDescription, Tool } from "core"; +import { LLMFullCompletionOptions, Tool } from "core"; import { getRuleId } from "core/llm/rules/getSystemMessageWithRules"; import { ToCoreProtocol } from "core/protocol"; -import { BuiltInToolNames } from "core/tools/builtIn"; import { selectActiveTools } from "../selectors/selectActiveTools"; import { selectUseSystemMessageTools } from "../selectors/selectUseSystemMessageTools"; import { selectSelectedChatModel } from "../slices/configSlice"; @@ -29,6 +28,7 @@ import { selectCurrentToolCalls } from "../selectors/selectToolCalls"; import { DEFAULT_TOOL_SETTING } from "../slices/uiSlice"; import { getBaseSystemMessage } from "../util/getBaseSystemMessage"; import { callToolById } from "./callToolById"; +import { enhanceParsedArgs } from "./enhanceParsedArgs"; /** * Handles the execution of tool calls that may be automatically accepted. * Sets all tools as generated first, then executes auto-approved tool calls. @@ -86,49 +86,6 @@ async function handleToolCallExecution( } } -/** - * Filters tools based on the selected model's capabilities. - * Returns either the edit file tool or search and replace tool, but not both. - */ -function filterToolsForModel( - tools: Tool[], - selectedModel: ModelDescription, -): Tool[] { - const editFileTool = tools.find( - (tool) => tool.function.name === BuiltInToolNames.EditExistingFile, - ); - const searchAndReplaceTool = tools.find( - (tool) => tool.function.name === BuiltInToolNames.SearchAndReplaceInFile, - ); - - // If we don't have both tools, return tools as-is - if (!editFileTool || !searchAndReplaceTool) { - return tools; - } - - // Determine which tool to use based on the model - const shouldUseFindReplace = shouldUseFindReplaceEdits(selectedModel); - - // Filter out the unwanted tool - return tools.filter((tool) => { - if (tool.function.name === BuiltInToolNames.EditExistingFile) { - return !shouldUseFindReplace; - } - if (tool.function.name === BuiltInToolNames.SearchAndReplaceInFile) { - return shouldUseFindReplace; - } - return true; - }); -} - -/** - * Determines whether to use search and replace tool instead of edit file - * Right now we only know that this is reliable with Claude models - */ -function shouldUseFindReplaceEdits({ model }: ModelDescription): boolean { - return model.includes("claude") || model.includes("gpt-5"); -} - export const streamNormalInput = createAsyncThunk< void, { @@ -146,8 +103,8 @@ export const streamNormalInput = createAsyncThunk< } // Get tools and filter them based on the selected model - const allActiveTools = selectActiveTools(state); - const activeTools = filterToolsForModel(allActiveTools, selectedChatModel); + const activeTools = selectActiveTools(state); + const supportsNativeTools = modelSupportsNativeTools(selectedChatModel); // Use the centralized selector to determine if system message tools should be used @@ -297,6 +254,19 @@ export const streamNormalInput = createAsyncThunk< const newState = getState(); const toolSettings = newState.ui.toolSettings; const allToolCallStates = selectCurrentToolCalls(newState); + + await Promise.all( + allToolCallStates.map((tcState) => + enhanceParsedArgs( + extra.ideMessenger, + dispatch, + tcState?.toolCall.function.name, + tcState.toolCallId, + tcState.parsedArgs, + ), + ), + ); + const generatingToolCalls = allToolCallStates.filter( (toolCallState) => toolCallState.status === "generating", ); diff --git a/gui/src/util/clientTools/callClientTool.ts b/gui/src/util/clientTools/callClientTool.ts index b5ac685d3..755be6e73 100644 --- a/gui/src/util/clientTools/callClientTool.ts +++ b/gui/src/util/clientTools/callClientTool.ts @@ -3,7 +3,9 @@ import { BuiltInToolNames } from "core/tools/builtIn"; import { IIdeMessenger } from "../../context/IdeMessenger"; import { AppThunkDispatch, RootState } from "../../redux/store"; import { editToolImpl } from "./editImpl"; +import { multiEditImpl } from "./multiEditImpl"; import { searchReplaceToolImpl } from "./searchReplaceImpl"; +import { singleFindAndReplaceImpl } from "./singleFindAndReplaceImpl"; export interface ClientToolExtras { getState: () => RootState; @@ -40,6 +42,16 @@ export async function callClientTool( case BuiltInToolNames.SearchAndReplaceInFile: output = await searchReplaceToolImpl(parsedArgs, toolCall.id, extras); break; + case BuiltInToolNames.SingleFindAndReplace: + output = await singleFindAndReplaceImpl( + parsedArgs, + toolCall.id, + extras, + ); + break; + case BuiltInToolNames.MultiEdit: + output = await multiEditImpl(parsedArgs, toolCall.id, extras); + break; default: throw new Error(`Invalid client tool name ${toolCall.function.name}`); } diff --git a/gui/src/util/clientTools/editImpl.ts b/gui/src/util/clientTools/editImpl.ts index edd49dd06..4dec61a65 100644 --- a/gui/src/util/clientTools/editImpl.ts +++ b/gui/src/util/clientTools/editImpl.ts @@ -1,7 +1,6 @@ import { resolveRelativePathInDir } from "core/util/ideUtils"; import { v4 as uuid } from "uuid"; -import { updateApplyState } from "../../redux/slices/sessionSlice"; -import { handleEditToolApplyError } from "../../redux/thunks/handleApplyStateUpdate"; +import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate"; import { ClientToolImpl } from "./callClientTool"; export const editToolImpl: ClientToolImpl = async ( args, @@ -21,29 +20,15 @@ export const editToolImpl: ClientToolImpl = async ( throw new Error(`${args.filepath} does not exist`); } const streamId = uuid(); - extras.dispatch( - updateApplyState({ - streamId, - toolCallId, - status: "not-started", - }), - ); - void extras.ideMessenger - .request("applyToFile", { + void extras.dispatch( + applyForEditTool({ streamId, text: args.changes, toolCallId, filepath: firstUriMatch, - }) - .then((res) => { - if (res.status === "error") { - void extras.dispatch( - handleEditToolApplyError({ - toolCallId, - }), - ); - } - }); + }), + ); + return { respondImmediately: false, output: undefined, // No immediate output. diff --git a/gui/src/util/clientTools/findAndReplaceUtils.test.ts b/gui/src/util/clientTools/findAndReplaceUtils.test.ts new file mode 100644 index 000000000..68ab333b9 --- /dev/null +++ b/gui/src/util/clientTools/findAndReplaceUtils.test.ts @@ -0,0 +1,456 @@ +import { EditOperation } from "core/tools/definitions/multiEdit"; +import { describe, expect, it } from "vitest"; +import { + EMPTY_NON_FIRST_EDIT_MESSAGE, + FOUND_MULTIPLE_FIND_STRINGS_ERROR, + performFindAndReplace, + validateCreatingForMultiEdit, + validateSingleEdit, +} from "./findAndReplaceUtils"; + +describe("performFindAndReplace", () => { + describe("normal cases", () => { + it("should replace single occurrence by default", () => { + const content = "Hello world\nThis is a test file\nGoodbye"; + const result = performFindAndReplace(content, "Hello", "Hi"); + + expect(result).toBe("Hi world\nThis is a test file\nGoodbye"); + }); + + it("should replace single occurrence when replaceAll is false", () => { + const content = "Hello world\nHello again"; + const result = performFindAndReplace( + content, + "Hello world", + "Hi world", + false, + ); + + expect(result).toBe("Hi world\nHello again"); + }); + + it("should replace all occurrences when replaceAll is true", () => { + const content = "Hello world\nHello again\nHello there"; + const result = performFindAndReplace(content, "Hello", "Hi", true); + + expect(result).toBe("Hi world\nHi again\nHi there"); + }); + + it("should handle empty new string (deletion)", () => { + const content = "Hello world"; + const result = performFindAndReplace(content, "Hello ", ""); + + expect(result).toBe("world"); + }); + + it("should handle empty old string replacement (insertion at start)", () => { + const content = ""; + const result = performFindAndReplace(content, "", "Hello world"); + + expect(result).toBe("Hello world"); + }); + + it("should preserve whitespace and indentation", () => { + const content = + "function test() {\n const value = 'old';\n return value;\n}"; + const result = performFindAndReplace( + content, + " const value = 'old';", + " const value = 'new';", + ); + + expect(result).toBe( + "function test() {\n const value = 'new';\n return value;\n}", + ); + }); + + it("should handle multiline strings", () => { + const content = "line1\nline2\nline3"; + const result = performFindAndReplace( + content, + "line1\nline2", + "newline1\nnewline2", + ); + + expect(result).toBe("newline1\nnewline2\nline3"); + }); + }); + + describe("special character handling", () => { + it("should handle regex special characters in old string", () => { + const content = "const regex = /[a-z]+/g;"; + const result = performFindAndReplace(content, "/[a-z]+/g", "/[A-Z]+/g"); + + expect(result).toBe("const regex = /[A-Z]+/g;"); + }); + + it("should handle dollar signs in strings", () => { + const content = 'const text = "Hello $world"'; + const result = performFindAndReplace( + content, + '"Hello $world"', + '"Hi $universe"', + ); + + expect(result).toBe('const text = "Hi $universe"'); + }); + + it("should handle backslashes", () => { + const content = 'const path = "C:\\Users\\test"'; + const result = performFindAndReplace( + content, + "C:\\Users\\test", + "D:\\Users\\test", + ); + + expect(result).toBe('const path = "D:\\Users\\test"'); + }); + + it("should handle parentheses", () => { + const content = "function test() { return 'old'; }"; + const result = performFindAndReplace( + content, + "() { return 'old'; }", + "() { return 'new'; }", + ); + + expect(result).toBe("function test() { return 'new'; }"); + }); + + it("should handle square brackets", () => { + const content = "const arr = [1, 2, 3];"; + const result = performFindAndReplace(content, "[1, 2, 3]", "[4, 5, 6]"); + + expect(result).toBe("const arr = [4, 5, 6];"); + }); + }); + + describe("replaceAll behavior", () => { + it("should replace all occurrences including partial matches", () => { + const content = "test testing tested test"; + const result = performFindAndReplace(content, "test", "exam", true); + + expect(result).toBe("exam examing examed exam"); + }); + + it("should replace all occurrences with empty string", () => { + const content = "remove this remove that remove everything"; + const result = performFindAndReplace(content, "remove ", "", true); + + expect(result).toBe("this that everything"); + }); + + it("should handle overlapping patterns correctly", () => { + const content = "aaaa"; + const result = performFindAndReplace(content, "aa", "b", true); + + expect(result).toBe("bb"); + }); + }); + + describe("error cases", () => { + it("should throw error when string not found", () => { + const content = "Hello world"; + + expect(() => { + performFindAndReplace(content, "xyz", "abc"); + }).toThrow('string not found in file: "xyz"'); + }); + + it("should throw error with edit context when string not found", () => { + const content = "Hello world"; + + expect(() => { + performFindAndReplace(content, "xyz", "abc", false, 2); + }).toThrow('edit at index 2: string not found in file: "xyz"'); + }); + + it("should throw error when multiple occurrences exist and replaceAll is false", () => { + const content = "Hello world\nHello again\nHello there"; + + expect(() => { + performFindAndReplace(content, "Hello", "Hi", false); + }).toThrow( + `String "Hello" appears 3 times in the file. ${FOUND_MULTIPLE_FIND_STRINGS_ERROR}`, + ); + }); + + it("should throw error with edit context for multiple occurrences", () => { + const content = "test test test"; + + expect(() => { + performFindAndReplace(content, "test", "exam", false, 1); + }).toThrow( + `edit at index 1: String "test" appears 3 times in the file. ${FOUND_MULTIPLE_FIND_STRINGS_ERROR}`, + ); + }); + }); + + describe("edge cases", () => { + it("should handle single character replacement", () => { + const content = "a b c"; + const result = performFindAndReplace(content, "b", "x"); + + expect(result).toBe("a x c"); + }); + + it("should handle very long strings", () => { + const longString = "a".repeat(10000); + const content = `start${longString}end`; + const result = performFindAndReplace(content, longString, "short"); + + expect(result).toBe("startshortend"); + }); + + it("should handle strings at beginning of content", () => { + const content = "start middle end"; + const result = performFindAndReplace(content, "start", "begin"); + + expect(result).toBe("begin middle end"); + }); + + it("should handle strings at end of content", () => { + const content = "start middle end"; + const result = performFindAndReplace(content, "end", "finish"); + + expect(result).toBe("start middle finish"); + }); + + it("should handle entire content replacement", () => { + const content = "replace everything"; + const result = performFindAndReplace( + content, + "replace everything", + "new content", + ); + + expect(result).toBe("new content"); + }); + }); +}); + +describe("validateSingleEdit", () => { + describe("valid inputs", () => { + it("should not throw for valid non-empty strings", () => { + expect(() => { + validateSingleEdit("old", "new"); + }).not.toThrow(); + }); + + it("should allow empty old_string for file creation", () => { + expect(() => { + validateSingleEdit("", "new content"); + }).not.toThrow(); + }); + + it("should allow empty new_string for deletion", () => { + expect(() => { + validateSingleEdit("delete me", ""); + }).not.toThrow(); + }); + + it("should allow multiline strings", () => { + expect(() => { + validateSingleEdit("line1\nline2", "newline1\nnewline2"); + }).not.toThrow(); + }); + + it("should allow special characters", () => { + expect(() => { + validateSingleEdit("/[a-z]+/g", "/[A-Z]+/g"); + }).not.toThrow(); + }); + }); + + describe("invalid inputs", () => { + it("should throw error when old_string is null", () => { + expect(() => { + validateSingleEdit(null as any, "new"); + }).toThrow("old_string is required"); + }); + + it("should throw error when old_string is undefined", () => { + expect(() => { + validateSingleEdit(undefined as any, "new"); + }).toThrow("old_string is required"); + }); + + it("should throw error when new_string is undefined", () => { + expect(() => { + validateSingleEdit("old", undefined as any); + }).toThrow("new_string is required"); + }); + + it("should throw error when old_string and new_string are identical", () => { + expect(() => { + validateSingleEdit("same", "same"); + }).toThrow("old_string and new_string must be different"); + }); + + it("should throw error when both are empty strings", () => { + expect(() => { + validateSingleEdit("", ""); + }).toThrow("old_string and new_string must be different"); + }); + }); + + describe("error messages with context", () => { + it("should include edit number in error messages when index provided", () => { + expect(() => { + validateSingleEdit(null as any, "new", 2); + }).toThrow("edit at index 2: old_string is required"); + }); + + it("should include edit number for new_string errors", () => { + expect(() => { + validateSingleEdit("old", undefined as any, 0); + }).toThrow("edit at index 0: new_string is required"); + }); + + it("should include edit number for identical strings error", () => { + expect(() => { + validateSingleEdit("same", "same", 4); + }).toThrow( + "edit at index 4: old_string and new_string must be different", + ); + }); + + it("should not include context when index not provided", () => { + expect(() => { + validateSingleEdit("same", "same"); + }).toThrow("old_string and new_string must be different"); + }); + }); +}); + +describe("validateCreatingForMultiEdit", () => { + describe("single edit scenarios", () => { + it("should return true for creating with single edit", () => { + const edits: EditOperation[] = [ + { old_string: "", new_string: "new file content" }, + ]; + + const isCreating = validateCreatingForMultiEdit(edits); + expect(isCreating).toBe(true); + }); + + it("should return false for editing with single edit", () => { + const edits: EditOperation[] = [{ old_string: "old", new_string: "new" }]; + + const isCreating = validateCreatingForMultiEdit(edits); + expect(isCreating).toBe(false); + }); + }); + + describe("multiple edit scenarios - editing existing file", () => { + it("should return false for multiple edits on existing file", () => { + const edits: EditOperation[] = [ + { old_string: "old1", new_string: "new1" }, + { old_string: "old2", new_string: "new2" }, + { old_string: "old3", new_string: "new3" }, + ]; + + const isCreating = validateCreatingForMultiEdit(edits); + expect(isCreating).toBe(false); + }); + + it("should allow multiple valid edits on existing file", () => { + const edits: EditOperation[] = [ + { old_string: "import old", new_string: "import new" }, + { old_string: "function old()", new_string: "function new()" }, + { old_string: "return old;", new_string: "return new;" }, + ]; + + expect(() => validateCreatingForMultiEdit(edits)).not.toThrow(); + expect(validateCreatingForMultiEdit(edits)).toBe(false); + }); + }); + + describe("error cases", () => { + it("should throw error when trying to make subsequent edits on file creation", () => { + const edits: EditOperation[] = [ + { old_string: "", new_string: "new file content" }, + { old_string: "old", new_string: "new" }, + ]; + + expect(() => { + validateCreatingForMultiEdit(edits); + }).toThrow("cannot make subsequent edits on a file you are creating"); + }); + + it("should throw error when empty old_string appears in non-first edit", () => { + const edits: EditOperation[] = [ + { old_string: "old1", new_string: "new1" }, + { old_string: "", new_string: "new2" }, + ]; + + expect(() => { + validateCreatingForMultiEdit(edits); + }).toThrow(`edit at index 1: ${EMPTY_NON_FIRST_EDIT_MESSAGE}`); + }); + + it("should throw error with correct edit number for empty old_string", () => { + const edits: EditOperation[] = [ + { old_string: "old1", new_string: "new1" }, + { old_string: "old2", new_string: "new2" }, + { old_string: "", new_string: "new3" }, + ]; + + expect(() => { + validateCreatingForMultiEdit(edits); + }).toThrow(`edit at index 2: ${EMPTY_NON_FIRST_EDIT_MESSAGE}`); + }); + + it("should throw error for multiple empty old_strings in subsequent edits", () => { + const edits: EditOperation[] = [ + { old_string: "old1", new_string: "new1" }, + { old_string: "", new_string: "new2" }, + { old_string: "", new_string: "new3" }, + ]; + + expect(() => { + validateCreatingForMultiEdit(edits); + }).toThrow(`edit at index 1: ${EMPTY_NON_FIRST_EDIT_MESSAGE}`); + }); + }); + + describe("edge cases", () => { + it("should handle empty edits array gracefully", () => { + const edits: EditOperation[] = []; + + // This should not throw, but would likely cause issues elsewhere + // The function doesn't explicitly handle empty arrays + expect(() => { + validateCreatingForMultiEdit(edits); + }).toThrow(); // Will throw because edits[0] is undefined + }); + + it("should handle complex edit operations", () => { + const edits: EditOperation[] = [ + { + old_string: "function oldFunction() {\n return 'old';\n}", + new_string: "function newFunction() {\n return 'new';\n}", + replace_all: false, + }, + { + old_string: "const OLD_CONSTANT", + new_string: "const NEW_CONSTANT", + replace_all: true, + }, + ]; + + expect(() => validateCreatingForMultiEdit(edits)).not.toThrow(); + expect(validateCreatingForMultiEdit(edits)).toBe(false); + }); + + it("should handle edits with replace_all flags", () => { + const edits: EditOperation[] = [ + { old_string: "old", new_string: "new", replace_all: true }, + { old_string: "test", new_string: "exam", replace_all: false }, + ]; + + expect(() => validateCreatingForMultiEdit(edits)).not.toThrow(); + expect(validateCreatingForMultiEdit(edits)).toBe(false); + }); + }); +}); diff --git a/gui/src/util/clientTools/findAndReplaceUtils.ts b/gui/src/util/clientTools/findAndReplaceUtils.ts new file mode 100644 index 000000000..6828e1695 --- /dev/null +++ b/gui/src/util/clientTools/findAndReplaceUtils.ts @@ -0,0 +1,97 @@ +import { EditOperation } from "core/tools/definitions/multiEdit"; + +export const FOUND_MULTIPLE_FIND_STRINGS_ERROR = + "Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences."; + +/** + * Performs a find and replace operation on text content with proper handling of special characters + */ +export function performFindAndReplace( + content: string, + oldString: string, + newString: string, + replaceAll: boolean = false, + index?: number, // For error messages +): string { + const errorContext = index !== undefined ? `edit at index ${index}: ` : ""; + // Check if old_string exists in current content + if (!content.includes(oldString)) { + throw new Error(`${errorContext}string not found in file: "${oldString}"`); + } + + if (replaceAll) { + // Replace all occurrences using replaceAll for proper handling of special characters + return content.replaceAll(oldString, newString); + } else { + // Handle empty oldString case (insertion) + if (oldString === "") { + return newString + content; + } + + // Count occurrences using indexOf for proper handling of special characters + let count = 0; + let searchIndex = content.indexOf(oldString); + while (searchIndex !== -1) { + count++; + searchIndex = content.indexOf(oldString, searchIndex + 1); + } + + if (count > 1) { + throw new Error( + `${errorContext}String "${oldString}" appears ${count} times in the file. ${FOUND_MULTIPLE_FIND_STRINGS_ERROR}`, + ); + } + + // Replace only the first occurrence + const firstIndex = content.indexOf(oldString); + return ( + content.substring(0, firstIndex) + + newString + + content.substring(firstIndex + oldString.length) + ); + } +} + +/** + * Validates a single edit operation + */ +export function validateSingleEdit( + oldString: string, + newString: string, + index?: number, +): void { + const context = index !== undefined ? `edit at index ${index}: ` : ""; + + if (!oldString && oldString !== "") { + throw new Error(`${context}old_string is required`); + } + if (newString === undefined) { + throw new Error(`${context}new_string is required`); + } + if (oldString === newString) { + throw new Error(`${context}old_string and new_string must be different`); + } +} + +export const EMPTY_NON_FIRST_EDIT_MESSAGE = + "contains empty old_string. Only the first edit can contain an empty old_string, which is only used for file creation."; +export function validateCreatingForMultiEdit(edits: EditOperation[]) { + const isCreating = edits[0].old_string === ""; + if (edits.length > 1) { + if (isCreating) { + throw new Error( + "cannot make subsequent edits on a file you are creating", + ); + } else { + for (let i = 1; i < edits.length; i++) { + if (edits[i].old_string === "") { + throw new Error( + `edit at index ${i}: ${EMPTY_NON_FIRST_EDIT_MESSAGE}`, + ); + } + } + } + } + + return isCreating; +} diff --git a/gui/src/util/clientTools/multiEditImpl.test.ts b/gui/src/util/clientTools/multiEditImpl.test.ts new file mode 100644 index 000000000..7c262cb82 --- /dev/null +++ b/gui/src/util/clientTools/multiEditImpl.test.ts @@ -0,0 +1,359 @@ +import * as ideUtils from "core/util/ideUtils"; +import { beforeEach, describe, expect, it, Mock, vi } from "vitest"; +import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate"; +import { ClientToolExtras } from "./callClientTool"; +import { FOUND_MULTIPLE_FIND_STRINGS_ERROR } from "./findAndReplaceUtils"; +import { multiEditImpl } from "./multiEditImpl"; + +vi.mock("uuid", () => ({ + v4: vi.fn(() => "test-uuid"), +})); + +vi.mock("core/util/ideUtils", () => ({ + resolveRelativePathInDir: vi.fn(), + inferResolvedUriFromRelativePath: vi.fn(), +})); + +vi.mock("../../redux/thunks/handleApplyStateUpdate", () => ({ + applyForEditTool: vi.fn(), +})); + +describe("multiEditImpl", () => { + let mockExtras: ClientToolExtras; + let mockResolveRelativePathInDir: Mock; + let mockInferResolvedUriFromRelativePath: Mock; + let mockApplyForEditTool: Mock; + + beforeEach(() => { + vi.clearAllMocks(); + + mockResolveRelativePathInDir = vi.mocked(ideUtils.resolveRelativePathInDir); + mockInferResolvedUriFromRelativePath = vi.mocked( + ideUtils.inferResolvedUriFromRelativePath, + ); + mockApplyForEditTool = vi.mocked(applyForEditTool); + + mockExtras = { + getState: vi.fn(() => ({ + config: { config: { allowAnonymousTelemetry: false } }, + })) as any, + dispatch: vi.fn() as any, + ideMessenger: { + ide: { + readFile: vi.fn(), + getWorkspaceDirs: vi.fn().mockResolvedValue(["dir1"]), + }, + request: vi.fn(), + } as any, + }; + }); + + describe("argument validation", () => { + it("should throw if filepath is missing", async () => { + await expect( + multiEditImpl({ edits: [] }, "id", mockExtras), + ).rejects.toThrow("filepath is required"); + }); + + it("should throw if edits array is empty", async () => { + await expect( + multiEditImpl({ filepath: "test.txt", edits: [] }, "id", mockExtras), + ).rejects.toThrow( + "edits array is required and must contain at least one edit", + ); + }); + + it("should throw if edit has invalid old_string", async () => { + await expect( + multiEditImpl( + { + filepath: "test.txt", + edits: [{ old_string: null, new_string: "test" }], + }, + "id", + mockExtras, + ), + ).rejects.toThrow("edit at index 0: old_string is required"); + }); + + it("should throw if edit has undefined new_string", async () => { + await expect( + multiEditImpl( + { + filepath: "test.txt", + edits: [{ old_string: "test", new_string: undefined }], + }, + "id", + mockExtras, + ), + ).rejects.toThrow("edit at index 0: new_string is required"); + }); + + it("should throw if old_string equals new_string", async () => { + await expect( + multiEditImpl( + { + filepath: "test.txt", + edits: [{ old_string: "same", new_string: "same" }], + }, + "id", + mockExtras, + ), + ).rejects.toThrow( + "edit at index 0: old_string and new_string must be different", + ); + }); + }); + + describe("sequential edits", () => { + beforeEach(() => { + mockResolveRelativePathInDir.mockResolvedValue( + "file:///dir/test/file.txt", + ); + }); + + it("should apply single edit", async () => { + mockExtras.ideMessenger.ide.readFile = vi + .fn() + .mockResolvedValue("Hello world"); + + await multiEditImpl( + { + filepath: "file.txt", + edits: [{ old_string: "Hello", new_string: "Hi" }], + }, + "id", + mockExtras, + ); + + expect(mockApplyForEditTool).toHaveBeenCalledWith({ + streamId: "test-uuid", + toolCallId: "id", + text: "Hi world", + filepath: "file:///dir/test/file.txt", + isSearchAndReplace: true, + }); + }); + + it("should apply multiple edits sequentially", async () => { + mockExtras.ideMessenger.ide.readFile = vi + .fn() + .mockResolvedValue("Hello world\nGoodbye world"); + + await multiEditImpl( + { + filepath: "file.txt", + edits: [ + { old_string: "Hello", new_string: "Hi" }, + { old_string: "world", new_string: "universe", replace_all: true }, + ], + }, + "id", + mockExtras, + ); + + expect(mockApplyForEditTool).toHaveBeenCalledWith({ + streamId: "test-uuid", + toolCallId: "id", + text: "Hi universe\nGoodbye universe", + filepath: "file:///dir/test/file.txt", + isSearchAndReplace: true, + }); + }); + + it("should handle edits that depend on previous edits", async () => { + mockExtras.ideMessenger.ide.readFile = vi + .fn() + .mockResolvedValue("const x = 1;"); + + await multiEditImpl( + { + filepath: "file.txt", + edits: [ + { old_string: "const x", new_string: "let x" }, + { old_string: "let x = 1;", new_string: "let x = 2;" }, + ], + }, + "id", + mockExtras, + ); + + expect(mockApplyForEditTool).toHaveBeenCalledWith({ + streamId: "test-uuid", + toolCallId: "id", + text: "let x = 2;", + filepath: "file:///dir/test/file.txt", + isSearchAndReplace: true, + }); + }); + + it("should throw if string not found in edit sequence", async () => { + mockExtras.ideMessenger.ide.readFile = vi + .fn() + .mockResolvedValue("Hello world"); + + await expect( + multiEditImpl( + { + filepath: "file.txt", + edits: [ + { old_string: "Hello", new_string: "Hi" }, + { old_string: "not found", new_string: "test" }, + ], + }, + "id", + mockExtras, + ), + ).rejects.toThrow( + 'edit at index 1: string not found in file: "not found"', + ); + }); + + it("should throw if multiple occurrences without replace_all", async () => { + mockExtras.ideMessenger.ide.readFile = vi + .fn() + .mockResolvedValue("test test test"); + + await expect( + multiEditImpl( + { + filepath: "file.txt", + edits: [{ old_string: "test", new_string: "replaced" }], + }, + "id", + mockExtras, + ), + ).rejects.toThrow( + `edit at index 0: String "test" appears 3 times in the file. ${FOUND_MULTIPLE_FIND_STRINGS_ERROR}`, + ); + }); + }); + + describe("file creation", () => { + it("should create new file with empty old_string", async () => { + mockResolveRelativePathInDir.mockResolvedValue(null); + mockInferResolvedUriFromRelativePath.mockResolvedValue( + "file:///infered/new.txt", + ); + + await multiEditImpl( + { + filepath: "new.txt", + edits: [{ old_string: "", new_string: "New content\nLine 2" }], + }, + "id", + mockExtras, + ); + + expect(mockApplyForEditTool).toHaveBeenCalledWith({ + streamId: "test-uuid", + toolCallId: "id", + text: "New content\nLine 2", + filepath: "file:///infered/new.txt", + isSearchAndReplace: true, + }); + }); + }); + + describe("replace_all functionality", () => { + beforeEach(() => { + mockResolveRelativePathInDir.mockResolvedValue( + "file:///dir/test/file.txt", + ); + }); + + it("should replace all occurrences when specified", async () => { + mockExtras.ideMessenger.ide.readFile = vi + .fn() + .mockResolvedValue("foo bar foo baz foo"); + + await multiEditImpl( + { + filepath: "file.txt", + edits: [{ old_string: "foo", new_string: "qux", replace_all: true }], + }, + "id", + mockExtras, + ); + + expect(mockApplyForEditTool).toHaveBeenCalledWith({ + streamId: "test-uuid", + toolCallId: "id", + text: "qux bar qux baz qux", + filepath: "file:///dir/test/file.txt", + isSearchAndReplace: true, + }); + }); + + it("should handle mixed replace_all settings", async () => { + mockExtras.ideMessenger.ide.readFile = vi + .fn() + .mockResolvedValue("x y x z x"); + + await multiEditImpl( + { + filepath: "file.txt", + edits: [ + { old_string: "x", new_string: "a", replace_all: true }, + { old_string: "y", new_string: "b" }, + ], + }, + "id", + mockExtras, + ); + + expect(mockApplyForEditTool).toHaveBeenCalledWith({ + streamId: "test-uuid", + toolCallId: "id", + text: "a b a z a", + filepath: "file:///dir/test/file.txt", + isSearchAndReplace: true, + }); + }); + }); + + describe("error handling", () => { + it("should wrap readFile errors", async () => { + mockResolveRelativePathInDir.mockResolvedValue( + "file:///dir/test/file.txt", + ); + mockExtras.ideMessenger.ide.readFile = vi + .fn() + .mockRejectedValue(new Error("Read failed")); + + await expect( + multiEditImpl( + { + filepath: "file.txt", + edits: [{ old_string: "test", new_string: "new" }], + }, + "id", + mockExtras, + ), + ).rejects.toThrow("Read failed"); + }); + }); + + describe("return value", () => { + it("should return correct structure", async () => { + mockResolveRelativePathInDir.mockResolvedValue( + "file:///dir/test/file.txt", + ); + mockExtras.ideMessenger.ide.readFile = vi.fn().mockResolvedValue("test"); + + const result = await multiEditImpl( + { + filepath: "file.txt", + edits: [{ old_string: "test", new_string: "new" }], + }, + "id", + mockExtras, + ); + + expect(result).toEqual({ + respondImmediately: false, + output: undefined, + }); + }); + }); +}); diff --git a/gui/src/util/clientTools/multiEditImpl.ts b/gui/src/util/clientTools/multiEditImpl.ts new file mode 100644 index 000000000..8b12109e5 --- /dev/null +++ b/gui/src/util/clientTools/multiEditImpl.ts @@ -0,0 +1,99 @@ +import { + inferResolvedUriFromRelativePath, + resolveRelativePathInDir, +} from "core/util/ideUtils"; +import { v4 as uuid } from "uuid"; +import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate"; +import { ClientToolImpl } from "./callClientTool"; +import { + performFindAndReplace, + validateCreatingForMultiEdit, + validateSingleEdit, +} from "./findAndReplaceUtils"; + +export const multiEditImpl: ClientToolImpl = async ( + args, + toolCallId, + extras, +) => { + const { filepath, edits, editingFileContents } = args; + + const streamId = uuid(); + + // Validate arguments + if (!filepath) { + throw new Error("filepath is required"); + } + if (!edits || !Array.isArray(edits) || edits.length === 0) { + throw new Error( + "edits array is required and must contain at least one edit", + ); + } + + // Validate each edit operation + for (let i = 0; i < edits.length; i++) { + const edit = edits[i]; + validateSingleEdit(edit.old_string, edit.new_string, i); + } + + // Check if this is creating a new file (first edit has empty old_string) + const isCreatingNewFile = validateCreatingForMultiEdit(edits); + const resolvedUri = await resolveRelativePathInDir( + filepath, + extras.ideMessenger.ide, + ); + + let newContent: string; + let fileUri: string; + if (isCreatingNewFile) { + if (resolvedUri) { + throw new Error( + `file ${filepath} already exists, cannot create new file`, + ); + } + newContent = edits[0].new_string; + const dirs = await extras.ideMessenger.ide.getWorkspaceDirs(); + fileUri = await inferResolvedUriFromRelativePath( + filepath, + extras.ideMessenger.ide, + dirs, + ); + } else { + if (!resolvedUri) { + throw new Error( + `file ${filepath} does not exist. If you are trying to edit it, correct the filepath. If you are trying to create it, you must pass old_string=""`, + ); + } + newContent = + editingFileContents ?? + (await extras.ideMessenger.ide.readFile(resolvedUri)); + fileUri = resolvedUri; + for (let i = 0; i < edits.length; i++) { + const { old_string, new_string, replace_all } = edits[i]; + newContent = performFindAndReplace( + newContent, + old_string, + new_string, + replace_all, + i, + ); + } + } + + // Apply the changes to the file + void extras.dispatch( + applyForEditTool({ + streamId, + toolCallId, + text: newContent, + filepath: fileUri, + isSearchAndReplace: true, + }), + ); + + // Return success - applyToFile will handle the completion state + return { + respondImmediately: false, // Let apply state handle completion + output: undefined, + }; +}; diff --git a/gui/src/util/clientTools/searchReplaceImpl.test.ts b/gui/src/util/clientTools/searchReplaceImpl.test.ts index 8d8e2ed07..69423a130 100644 --- a/gui/src/util/clientTools/searchReplaceImpl.test.ts +++ b/gui/src/util/clientTools/searchReplaceImpl.test.ts @@ -2,6 +2,7 @@ import { findSearchMatch } from "core/edit/searchAndReplace/findSearchMatch"; import { parseAllSearchReplaceBlocks } from "core/edit/searchAndReplace/parseSearchReplaceBlock"; import { resolveRelativePathInDir } from "core/util/ideUtils"; import { beforeEach, describe, expect, it, vi } from "vitest"; +import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate"; import { ClientToolExtras } from "./callClientTool"; import { searchReplaceToolImpl } from "./searchReplaceImpl"; @@ -12,10 +13,14 @@ vi.mock("core/util/ideUtils"); vi.mock("uuid", () => ({ v4: vi.fn(() => "test-stream-id"), })); +vi.mock("../../redux/thunks/handleApplyStateUpdate", () => ({ + applyForEditTool: vi.fn(), +})); const mockFindSearchMatch = vi.mocked(findSearchMatch); const mockParseAllSearchReplaceBlocks = vi.mocked(parseAllSearchReplaceBlocks); const mockResolveRelativePathInDir = vi.mocked(resolveRelativePathInDir); +const mockApplyForEditTool = vi.mocked(applyForEditTool); describe("searchReplaceToolImpl", () => { let mockExtras: ClientToolExtras; @@ -144,8 +149,6 @@ describe("searchReplaceToolImpl", () => { endIndex, strategyName: "exactMatch", }); - mockIdeMessenger.request.mockResolvedValue({ status: "success" }); - const result = await searchReplaceToolImpl( { filepath: "test.js", diffs: ["mock diff content"] }, "tool-call-id", @@ -159,7 +162,7 @@ describe("searchReplaceToolImpl", () => { }); // Verify applyToFile was called with correct parameters - expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", { + expect(mockApplyForEditTool).toHaveBeenCalledWith({ text: expectedFinalContent, streamId: "test-stream-id", filepath: "/resolved/path/test.js", @@ -202,8 +205,6 @@ describe("searchReplaceToolImpl", () => { endIndex, strategyName: "exactMatch", }); - mockIdeMessenger.request.mockResolvedValue({ status: "success" }); - const result = await searchReplaceToolImpl( { filepath: "test.js", diffs: ["mock diff content"] }, "tool-call-id", @@ -217,7 +218,7 @@ describe("searchReplaceToolImpl", () => { }); // Verify applyToFile was called with correct parameters - expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", { + expect(mockApplyForEditTool).toHaveBeenCalledWith({ text: expectedFinalContent, streamId: "test-stream-id", filepath: "/resolved/path/test.js", @@ -283,8 +284,6 @@ const c = 3;`; strategyName: "exactMatch", }); - mockIdeMessenger.request.mockResolvedValue({ status: "success" }); - const result = await searchReplaceToolImpl( { filepath: "test.js", diffs: ["mock diff content"] }, "tool-call-id", @@ -310,7 +309,7 @@ const c = 3;`; "const b = 2;", ); // Verify final applyToFile call - expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", { + expect(mockApplyForEditTool).toHaveBeenCalledWith({ text: expectedFinalContent, streamId: "test-stream-id", filepath: "/resolved/path/test.js", @@ -379,8 +378,6 @@ const c = 3;`; strategyName: "exactMatch", }); - mockIdeMessenger.request.mockResolvedValue({ status: "success" }); - const result = await searchReplaceToolImpl( { filepath: "test.js", diffs: ["first diff", "second diff"] }, "tool-call-id", @@ -405,7 +402,7 @@ const c = 3;`; ); // Verify final applyToFile call - expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", { + expect(mockApplyForEditTool).toHaveBeenCalledWith({ text: expectedFinalContent, streamId: "test-stream-id", filepath: "/resolved/path/test.js", @@ -440,7 +437,6 @@ keep this too`; endIndex: 26, // End of "remove this line" strategyName: "exactMatch", }); - mockIdeMessenger.request.mockResolvedValue({ status: "success" }); const result = await searchReplaceToolImpl( { filepath: "test.txt", diffs: ["mock diff content"] }, @@ -453,7 +449,7 @@ keep this too`; output: undefined, }); - expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", { + expect(mockApplyForEditTool).toHaveBeenCalledWith({ text: expectedFinalContent, streamId: "test-stream-id", filepath: "/resolved/path/test.txt", @@ -480,15 +476,13 @@ keep this too`; endIndex: 11, strategyName: "exactMatch", }); - mockIdeMessenger.request.mockResolvedValue({ status: "success" }); - await searchReplaceToolImpl( { filepath: "test.txt", diffs: ["mock diff content"] }, "tool-call-id", mockExtras, ); - expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", { + expect(mockApplyForEditTool).toHaveBeenCalledWith({ text: expectedFinalContent, streamId: "test-stream-id", filepath: "/resolved/path/test.txt", @@ -602,15 +596,13 @@ keep this too`; endIndex: 0, strategyName: "exactMatch", }); - mockIdeMessenger.request.mockResolvedValue({ status: "success" }); - await searchReplaceToolImpl( { filepath: "test.txt", diffs: ["mock diff content"] }, "tool-call-id", mockExtras, ); - expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", { + expect(mockApplyForEditTool).toHaveBeenCalledWith({ text: expectedFinalContent, streamId: "test-stream-id", filepath: "/resolved/path/test.txt", @@ -637,7 +629,6 @@ keep this too`; endIndex: originalContent.length, strategyName: "exactMatch", }); - mockIdeMessenger.request.mockResolvedValue({ status: "success" }); await searchReplaceToolImpl( { filepath: "test.txt", diffs: ["mock diff content"] }, @@ -645,7 +636,7 @@ keep this too`; mockExtras, ); - expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", { + expect(mockApplyForEditTool).toHaveBeenCalledWith({ text: expectedFinalContent, streamId: "test-stream-id", filepath: "/resolved/path/test.txt", @@ -673,7 +664,6 @@ keep this too`; endIndex: 4, strategyName: "exactMatch", }); - mockIdeMessenger.request.mockResolvedValue({ status: "success" }); await searchReplaceToolImpl( { filepath: "relative/test.txt", diffs: ["mock diff content"] }, @@ -693,7 +683,7 @@ keep this too`; "/resolved/path/test.txt", ); expect(mockFindSearchMatch).toHaveBeenCalledWith(originalContent, "test"); - expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", { + expect(mockApplyForEditTool).toHaveBeenCalledWith({ text: "updated content", streamId: "test-stream-id", filepath: "/resolved/path/test.txt", diff --git a/gui/src/util/clientTools/searchReplaceImpl.ts b/gui/src/util/clientTools/searchReplaceImpl.ts index b734b61ca..5b750b26f 100644 --- a/gui/src/util/clientTools/searchReplaceImpl.ts +++ b/gui/src/util/clientTools/searchReplaceImpl.ts @@ -3,8 +3,7 @@ import { parseAllSearchReplaceBlocks } from "core/edit/searchAndReplace/parseSea import { resolveRelativePathInDir } from "core/util/ideUtils"; import posthog from "posthog-js"; import { v4 as uuid } from "uuid"; -import { updateApplyState } from "../../redux/slices/sessionSlice"; -import { handleEditToolApplyError } from "../../redux/thunks/handleApplyStateUpdate"; +import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate"; import { ClientToolImpl } from "./callClientTool"; export const searchReplaceToolImpl: ClientToolImpl = async ( @@ -12,7 +11,7 @@ export const searchReplaceToolImpl: ClientToolImpl = async ( toolCallId, extras, ) => { - const { filepath, diffs } = args; + const { filepath, diffs, editingFileContents } = args; const state = extras.getState(); const allowAnonymousTelemetry = state.config.config.allowAnonymousTelemetry; @@ -47,7 +46,8 @@ export const searchReplaceToolImpl: ClientToolImpl = async ( try { // Read the current file content const originalContent = - await extras.ideMessenger.ide.readFile(resolvedFilepath); + editingFileContents ?? + (await extras.ideMessenger.ide.readFile(resolvedFilepath)); let currentContent = originalContent; // Apply all replacements sequentially to build the final content @@ -84,30 +84,15 @@ export const searchReplaceToolImpl: ClientToolImpl = async ( // This works becaues of our logic in `applyCodeBlock` that determines // that the full file rewrite here can be applied instantly, so the diff // lines are generated with meyers diff and streamed instantaneously - extras.dispatch( - updateApplyState({ - streamId, - toolCallId, - status: "not-started", - }), - ); - void extras.ideMessenger - .request("applyToFile", { + void extras.dispatch( + applyForEditTool({ streamId, toolCallId, text: currentContent, filepath: resolvedFilepath, isSearchAndReplace: true, - }) - .then((res) => { - if (res.status === "error") { - void extras.dispatch( - handleEditToolApplyError({ - toolCallId, - }), - ); - } - }); + }), + ); // Return success - applyToFile will handle the completion state return { diff --git a/gui/src/util/clientTools/singleFindAndReplaceImpl.test.ts b/gui/src/util/clientTools/singleFindAndReplaceImpl.test.ts new file mode 100644 index 000000000..e6e8201b9 --- /dev/null +++ b/gui/src/util/clientTools/singleFindAndReplaceImpl.test.ts @@ -0,0 +1,334 @@ +import * as ideUtils from "core/util/ideUtils"; +import { beforeEach, describe, expect, it, Mock, vi } from "vitest"; +import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate"; +import { ClientToolExtras } from "./callClientTool"; +import { singleFindAndReplaceImpl } from "./singleFindAndReplaceImpl"; +vi.mock("uuid", () => ({ + v4: vi.fn(() => "test-uuid"), +})); + +vi.mock("core/util/ideUtils", () => ({ + resolveRelativePathInDir: vi.fn(), +})); + +vi.mock("../../redux/thunks/handleApplyStateUpdate", () => ({ + applyForEditTool: vi.fn(), +})); + +describe("singleFindAndReplaceImpl", () => { + let mockExtras: ClientToolExtras; + let mockResolveRelativePathInDir: Mock; + let mockApplyForEditTool: Mock; + + beforeEach(() => { + vi.clearAllMocks(); + + mockResolveRelativePathInDir = vi.mocked(ideUtils.resolveRelativePathInDir); + mockApplyForEditTool = vi.mocked(applyForEditTool); + + mockExtras = { + getState: vi.fn(() => ({ + config: { + config: { + allowAnonymousTelemetry: false, + }, + }, + })) as any, + dispatch: vi.fn() as any, + ideMessenger: { + ide: { + readFile: vi.fn(), + }, + request: vi.fn(), + } as any, + }; + }); + + describe("argument validation", () => { + it("should throw error if filepath is missing", async () => { + const args = { + old_string: "test", + new_string: "replacement", + }; + + await expect( + singleFindAndReplaceImpl(args, "tool-call-id", mockExtras), + ).rejects.toThrow("filepath is required"); + }); + + it("should throw error if old_string is missing", async () => { + const args = { + filepath: "test.txt", + new_string: "replacement", + }; + + await expect( + singleFindAndReplaceImpl(args, "tool-call-id", mockExtras), + ).rejects.toThrow("old_string is required"); + }); + + it("should throw error if new_string is missing", async () => { + const args = { + filepath: "test.txt", + old_string: "test", + }; + + await expect( + singleFindAndReplaceImpl(args, "tool-call-id", mockExtras), + ).rejects.toThrow("new_string is required"); + }); + + it("should throw error if old_string and new_string are the same", async () => { + const args = { + filepath: "test.txt", + old_string: "same", + new_string: "same", + }; + + await expect( + singleFindAndReplaceImpl(args, "tool-call-id", mockExtras), + ).rejects.toThrow("old_string and new_string must be different"); + }); + }); + + describe("file resolution", () => { + it("should throw error if file does not exist", async () => { + mockResolveRelativePathInDir.mockResolvedValue(null); + + const args = { + filepath: "nonexistent.txt", + old_string: "test", + new_string: "replacement", + }; + + await expect( + singleFindAndReplaceImpl(args, "tool-call-id", mockExtras), + ).rejects.toThrow("File nonexistent.txt does not exist"); + }); + + it("should resolve relative file paths", async () => { + mockResolveRelativePathInDir.mockResolvedValue("/absolute/path/test.txt"); + mockExtras.ideMessenger.ide.readFile = vi + .fn() + .mockResolvedValue("test content"); + + const args = { + filepath: "test.txt", + old_string: "test", + new_string: "replacement", + }; + + await singleFindAndReplaceImpl(args, "tool-call-id", mockExtras); + + expect(mockResolveRelativePathInDir).toHaveBeenCalledWith( + "test.txt", + mockExtras.ideMessenger.ide, + ); + expect(mockExtras.ideMessenger.ide.readFile).toHaveBeenCalledWith( + "/absolute/path/test.txt", + ); + }); + }); + + describe("string replacement", () => { + beforeEach(() => { + mockResolveRelativePathInDir.mockResolvedValue("/test/file.txt"); + }); + + it("should throw error if old_string is not found in file", async () => { + mockExtras.ideMessenger.ide.readFile = vi + .fn() + .mockResolvedValue("different content"); + + const args = { + filepath: "file.txt", + old_string: "not found", + new_string: "replacement", + }; + + await expect( + singleFindAndReplaceImpl(args, "tool-call-id", mockExtras), + ).rejects.toThrow(`string not found in file: "not found"`); + }); + + it("should replace single occurrence", async () => { + mockExtras.ideMessenger.ide.readFile = vi + .fn() + .mockResolvedValue("Hello world\nThis is a test file\nGoodbye world"); + + const args = { + filepath: "file.txt", + old_string: "Hello world", + new_string: "Hi there", + }; + + await singleFindAndReplaceImpl(args, "tool-call-id", mockExtras); + + // Check that the dispatch was called with the applyForEditTool thunk + expect(mockApplyForEditTool).toHaveBeenCalledWith({ + streamId: "test-uuid", + toolCallId: "tool-call-id", + text: "Hi there\nThis is a test file\nGoodbye world", + filepath: "/test/file.txt", + isSearchAndReplace: true, + }); + }); + + it("should throw error if old_string appears multiple times and replace_all is false", async () => { + mockExtras.ideMessenger.ide.readFile = vi + .fn() + .mockResolvedValue("Hello world\nThis is a test file\nGoodbye world"); + + const args = { + filepath: "file.txt", + old_string: "world", + new_string: "universe", + replace_all: false, + }; + + await expect( + singleFindAndReplaceImpl(args, "tool-call-id", mockExtras), + ).rejects.toThrow( + 'String "world" appears 2 times in the file. Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.', + ); + }); + + it("should replace all occurrences when replace_all is true", async () => { + mockExtras.ideMessenger.ide.readFile = vi + .fn() + .mockResolvedValue("Hello world\nThis is a test file\nGoodbye world"); + + const args = { + filepath: "file.txt", + old_string: "world", + new_string: "universe", + replace_all: true, + }; + + await singleFindAndReplaceImpl(args, "tool-call-id", mockExtras); + + expect(mockApplyForEditTool).toHaveBeenCalledWith({ + streamId: "test-uuid", + toolCallId: "tool-call-id", + text: "Hello universe\nThis is a test file\nGoodbye universe", + filepath: "/test/file.txt", + isSearchAndReplace: true, + }); + }); + + it("should handle empty new_string (deletion)", async () => { + mockExtras.ideMessenger.ide.readFile = vi + .fn() + .mockResolvedValue("Hello world\nThis is a test file"); + + const args = { + filepath: "file.txt", + old_string: "Hello ", + new_string: "", + }; + + await singleFindAndReplaceImpl(args, "tool-call-id", mockExtras); + + expect(mockApplyForEditTool).toHaveBeenCalledWith({ + streamId: "test-uuid", + toolCallId: "tool-call-id", + text: "world\nThis is a test file", + filepath: "/test/file.txt", + isSearchAndReplace: true, + }); + }); + + it("should handle special characters in strings", async () => { + mockExtras.ideMessenger.ide.readFile = vi + .fn() + .mockResolvedValue( + 'const regex = /[a-z]+/g;\nconst text = "Hello $world"', + ); + + const args = { + filepath: "file.txt", + old_string: '"Hello $world"', + new_string: '"Hi $universe"', + }; + + await singleFindAndReplaceImpl(args, "tool-call-id", mockExtras); + + expect(mockApplyForEditTool).toHaveBeenCalledWith({ + streamId: "test-uuid", + toolCallId: "tool-call-id", + text: 'const regex = /[a-z]+/g;\nconst text = "Hi $universe"', + filepath: "/test/file.txt", + isSearchAndReplace: true, + }); + }); + + it("should preserve whitespace and indentation", async () => { + mockExtras.ideMessenger.ide.readFile = vi + .fn() + .mockResolvedValue( + "function test() {\n const value = 'old';\n return value;\n}", + ); + + const args = { + filepath: "file.txt", + old_string: " const value = 'old';", + new_string: " const value = 'new';", + }; + + await singleFindAndReplaceImpl(args, "tool-call-id", mockExtras); + + expect(mockApplyForEditTool).toHaveBeenCalledWith({ + streamId: "test-uuid", + toolCallId: "tool-call-id", + text: "function test() {\n const value = 'new';\n return value;\n}", + filepath: "/test/file.txt", + isSearchAndReplace: true, + }); + }); + }); + + describe("return value", () => { + it("should return correct response structure", async () => { + mockResolveRelativePathInDir.mockResolvedValue("/test/file.txt"); + mockExtras.ideMessenger.ide.readFile = vi + .fn() + .mockResolvedValue("test content"); + + const args = { + filepath: "file.txt", + old_string: "test", + new_string: "replacement", + }; + + const result = await singleFindAndReplaceImpl( + args, + "tool-call-id", + mockExtras, + ); + + expect(result).toEqual({ + respondImmediately: false, + output: undefined, + }); + }); + }); + + describe("error handling", () => { + it("should wrap and rethrow errors from readFile", async () => { + mockResolveRelativePathInDir.mockResolvedValue("/test/file.txt"); + mockExtras.ideMessenger.ide.readFile = vi + .fn() + .mockRejectedValue(new Error("Permission denied")); + + const args = { + filepath: "file.txt", + old_string: "test", + new_string: "replacement", + }; + + await expect( + singleFindAndReplaceImpl(args, "tool-call-id", mockExtras), + ).rejects.toThrow("Permission denied"); + }); + }); +}); diff --git a/gui/src/util/clientTools/singleFindAndReplaceImpl.ts b/gui/src/util/clientTools/singleFindAndReplaceImpl.ts new file mode 100644 index 000000000..92c3da178 --- /dev/null +++ b/gui/src/util/clientTools/singleFindAndReplaceImpl.ts @@ -0,0 +1,69 @@ +import { resolveRelativePathInDir } from "core/util/ideUtils"; +import { v4 as uuid } from "uuid"; +import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate"; +import { ClientToolImpl } from "./callClientTool"; +import { + performFindAndReplace, + validateSingleEdit, +} from "./findAndReplaceUtils"; + +export const singleFindAndReplaceImpl: ClientToolImpl = async ( + args, + toolCallId, + extras, +) => { + const { + filepath, + old_string, + new_string, + replace_all = false, + editingFileContents, + } = args; + + const streamId = uuid(); + + // Validate arguments + if (!filepath) { + throw new Error("filepath is required"); + } + validateSingleEdit(old_string, new_string); + + // Resolve the file path + const resolvedFilepath = await resolveRelativePathInDir( + filepath, + extras.ideMessenger.ide, + ); + if (!resolvedFilepath) { + throw new Error(`File ${filepath} does not exist`); + } + + // Read the current file content + const originalContent = + editingFileContents ?? + (await extras.ideMessenger.ide.readFile(resolvedFilepath)); + + // Perform the find and replace operation + const newContent = performFindAndReplace( + originalContent, + old_string, + new_string, + replace_all, + ); + + // Apply the changes to the file + void extras.dispatch( + applyForEditTool({ + streamId, + toolCallId, + text: newContent, + filepath: resolvedFilepath, + isSearchAndReplace: true, + }), + ); + + // Return success - applyToFile will handle the completion state + return { + respondImmediately: false, // Let apply state handle completion + output: undefined, + }; +}; diff --git a/package-lock.json b/package-lock.json index 5a364313b..6981243e3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,5 +1,5 @@ { - "name": "wt-nate-4", + "name": "wt-mcp-flag", "lockfileVersion": 3, "requires": true, "packages": { diff --git a/packages/config-yaml/src/__tests__/index.test.ts b/packages/config-yaml/src/__tests__/index.test.ts index b537ede56..07b3a3eea 100644 --- a/packages/config-yaml/src/__tests__/index.test.ts +++ b/packages/config-yaml/src/__tests__/index.test.ts @@ -330,5 +330,167 @@ describe("E2E Scenarios", () => { ).toBe(true); }); + it("should throw when a block is blocklisted", async () => { + const result = await unrollAssistant( + { + uriType: "slug", + fullSlug: { + ownerSlug: "test-org", + packageSlug: "agent", + versionSlug: "latest", + }, + }, + registry, + { + renderSecrets: true, + platformClient, + orgScopeId: "test-org", + currentUserSlug: "test-user", + onPremProxyUrl: null, + blocklistedBlocks: [ + { + ownerSlug: "test-org", + packageSlug: "gemini", + }, + ], + }, + ); + + // Should contain an error about the blocklisted block + expect(result.errors).toBeDefined(); + expect(result.errors?.length).toBeGreaterThan(0); + expect( + result.errors?.some((error) => + error.message.includes( + "test-org/gemini is block listed and can not be used.", + ), + ), + ).toBe(true); + }); + + it("should return an error when a block is not on the allowlist", async () => { + const result = await unrollAssistant( + { + uriType: "slug", + fullSlug: { + ownerSlug: "test-org", + packageSlug: "agent", + versionSlug: "latest", + }, + }, + registry, + { + renderSecrets: true, + platformClient, + orgScopeId: "test-org", + currentUserSlug: "test-user", + onPremProxyUrl: null, + allowlistedBlocks: [ + { + ownerSlug: "test-org", + packageSlug: "docs", + }, + { + ownerSlug: "test-org", + packageSlug: "rules", + }, + { + ownerSlug: "test-org", + packageSlug: "claude35sonnet", + }, + ], + }, + ); + + // Should contain an error about the non-allowlisted block (gemini) + expect(result.errors).toBeDefined(); + expect(result.errors?.length).toBeGreaterThan(0); + expect( + result.errors?.some((error) => + error.message.includes( + "test-org/gemini is block listed and can not be used.", + ), + ), + ).toBe(true); + }); + + it("should allow blocks when they are on the allowlist", async () => { + const result = await unrollAssistant( + { + uriType: "slug", + fullSlug: { + ownerSlug: "test-org", + packageSlug: "agent", + versionSlug: "latest", + }, + }, + registry, + { + renderSecrets: true, + platformClient, + orgScopeId: "test-org", + currentUserSlug: "test-user", + onPremProxyUrl: null, + allowlistedBlocks: [ + { + ownerSlug: "test-org", + packageSlug: "docs", + }, + { + ownerSlug: "test-org", + packageSlug: "rules", + }, + { + ownerSlug: "test-org", + packageSlug: "gemini", + }, + { + ownerSlug: "test-org", + packageSlug: "claude35sonnet", + }, + ], + }, + ); + + // Should successfully unroll without errors for allowed blocks + expect(result.config?.models?.length).toBe(4); + expect(result.config?.rules?.length).toBe(2); + expect(result.config?.docs?.length).toBe(1); + }); + + it("should not affect file-based blocks with allow/blocklists", async () => { + const result = await unrollAssistant( + { + uriType: "file", + fileUri: "./src/__tests__/local-files/duplicate-test-agent.yaml", + }, + registry, + { + renderSecrets: true, + platformClient, + orgScopeId: "test-org", + currentUserSlug: "test-user", + onPremProxyUrl: null, + blocklistedBlocks: [ + { + ownerSlug: "test-org", + packageSlug: "docs", + }, + ], + injectBlocks: [ + { + uriType: "file", + fileUri: "./src/__tests__/local-files/rules.yaml", + }, + ], + }, + ); + + // File-based blocks should not be affected by blocklists + expect(result.config?.models?.length).toBe(1); + expect(result.config?.context?.length).toBe(1); + expect(result.config?.rules?.length).toBeGreaterThan(0); + }); + it.skip("should prioritize org over user / package secrets", () => {}); }); diff --git a/packages/config-yaml/src/load/unroll.ts b/packages/config-yaml/src/load/unroll.ts index 4de10b63b..80a9d62e1 100644 --- a/packages/config-yaml/src/load/unroll.ts +++ b/packages/config-yaml/src/load/unroll.ts @@ -6,8 +6,12 @@ import { decodeFQSN, decodePackageIdentifier, encodeFQSN, + encodePackageIdentifier, + encodePackageSlug, FQSN, PackageIdentifier, + PackageSlug, + packageSlugsEqual, } from "../interfaces/slugs.js"; import { markdownToRule } from "../markdown/index.js"; import { @@ -197,6 +201,8 @@ async function extractRenderedSecretsMap( export interface BaseUnrollAssistantOptions { renderSecrets: boolean; injectBlocks?: PackageIdentifier[]; + allowlistedBlocks?: PackageSlug[]; + blocklistedBlocks?: PackageSlug[]; } export interface DoNotRenderSecretsUnrollAssistantOptions @@ -262,7 +268,13 @@ export async function unrollAssistantFromContent( config: unrolledAssistant, configLoadInterrupted, errors, - } = await unrollBlocks(parsedYaml, registry, options.injectBlocks); + } = await unrollBlocks( + parsedYaml, + registry, + options.injectBlocks, + options.allowlistedBlocks, + options.blocklistedBlocks, + ); // Back to a string so we can fill in template variables const rawUnrolledYaml = YAML.stringify(unrolledAssistant); @@ -300,10 +312,44 @@ export async function unrollAssistantFromContent( return { config: finalConfig, errors, configLoadInterrupted }; } +function isPackageAllowed( + pkgId: PackageIdentifier, + allowlistedBlocks?: PackageSlug[], + blocklistedBlocks?: PackageSlug[], +): boolean { + // Only "slug" type blocks can be allow/block listed + if (pkgId.uriType !== "slug") { + return true; + } + + const packageSlug = { + ownerSlug: pkgId.fullSlug.ownerSlug, + packageSlug: pkgId.fullSlug.packageSlug, + }; + + if ( + allowlistedBlocks && + !allowlistedBlocks.some((block) => packageSlugsEqual(block, packageSlug)) + ) { + return false; + } + + if ( + blocklistedBlocks && + blocklistedBlocks.some((block) => packageSlugsEqual(block, packageSlug)) + ) { + return false; + } + + return true; +} + export async function unrollBlocks( assistant: ConfigYaml, registry: Registry, injectBlocks: PackageIdentifier[] | undefined, + allowlistedBlocks?: PackageSlug[], + blocklistedBlocks?: PackageSlug[], ): Promise> { const errors: ConfigValidationError[] = []; @@ -336,8 +382,29 @@ export async function unrollBlocks( // "uses/with" block if ("uses" in unrolledBlock) { try { + const blockIdentifier = decodePackageIdentifier(unrolledBlock.uses); + + if ( + !isPackageAllowed( + blockIdentifier, + allowlistedBlocks, + blocklistedBlocks, + ) + ) { + throw new Error( + `${ + blockIdentifier.uriType === "slug" + ? encodePackageSlug({ + ownerSlug: blockIdentifier.fullSlug.ownerSlug, + packageSlug: blockIdentifier.fullSlug.packageSlug, + }) + : encodePackageIdentifier(blockIdentifier) + } is block listed and can not be used.`, + ); + } + const blockConfigYaml = await resolveBlock( - decodePackageIdentifier(unrolledBlock.uses), + blockIdentifier, unrolledBlock.with, registry, ); diff --git a/packages/continue-sdk/typescript/package-lock.json b/packages/continue-sdk/typescript/package-lock.json index 0e5fb590f..c50af4a50 100644 --- a/packages/continue-sdk/typescript/package-lock.json +++ b/packages/continue-sdk/typescript/package-lock.json @@ -1,12 +1,12 @@ { "name": "@continuedev/sdk", - "version": "0.0.12", + "version": "0.0.13", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@continuedev/sdk", - "version": "0.0.12", + "version": "0.0.13", "license": "Apache-2.0", "dependencies": { "openai": "^4.96.2" @@ -1963,14 +1963,15 @@ } }, "node_modules/form-data": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.2.tgz", - "integrity": "sha512-hGfm/slu0ZabnNt4oaRZ6uREyfCj6P4fT/n6A1rGV+Z0VdGXjfOhVUpkn6qVQONHGIFwmveGXyDs75+nr6FM8w==", + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz", + "integrity": "sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==", "license": "MIT", "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.2", "mime-types": "^2.1.12" }, "engines": { diff --git a/packages/openai-adapters/package-lock.json b/packages/openai-adapters/package-lock.json index 046b1dc37..806a98f2a 100644 --- a/packages/openai-adapters/package-lock.json +++ b/packages/openai-adapters/package-lock.json @@ -12528,6 +12528,7 @@ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.5.4.tgz", "integrity": "sha512-Mtq29sKDAEYP7aljRgtPOpTvOfbwRWlS6dPRzwjdE+C0R4brX/GUyhHSecbHMFLNBLcJIPt9nl9yG5TZ1weH+Q==", "dev": true, + "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver"