diff --git a/eslint.config.js b/eslint.config.js index 6ff18d389..da7a3556d 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -1,102 +1,112 @@ -import js from '@eslint/js'; -import tseslint from 'typescript-eslint'; -import importPlugin from 'eslint-plugin-import'; -import unusedImports from 'eslint-plugin-unused-imports'; +import tsParser from "@typescript-eslint/parser"; +import tsPlugin from "@typescript-eslint/eslint-plugin"; +import importPlugin from "eslint-plugin-import"; +import unusedImports from "eslint-plugin-unused-imports"; -export default tseslint.config( - js.configs.recommended, - ...tseslint.configs.recommended, +export default [ { + files: ["**/*.ts", "**/*.tsx"], plugins: { - '@typescript-eslint': tseslint.plugin, - 'import': importPlugin, - 'unused-imports': unusedImports, + "@typescript-eslint": tsPlugin, + import: importPlugin, + "unused-imports": unusedImports, }, languageOptions: { - parser: tseslint.parser, + parser: tsParser, parserOptions: { - project: './tsconfig.json', - ecmaVersion: 'latest', - sourceType: 'module', + project: "./tsconfig.json", + ecmaVersion: "latest", + sourceType: "module", }, }, rules: { // Core rules - all as errors - 'max-classes-per-file': ['error', 1], - 'prefer-const': 'error', - + "max-classes-per-file": ["error", 1], + "prefer-const": "error", + // TypeScript specific rules - '@typescript-eslint/no-floating-promises': 'error', - + "@typescript-eslint/no-floating-promises": "off", + // Import rules - 'import/order': ['error', { - 'groups': [ - 'builtin', - 'external', - 'internal', - 'parent', - 'sibling', - 'index', - ], - 'newlines-between': 'always', - 'alphabetize': { - 'order': 'asc', - 'caseInsensitive': true, - }, - }], - 'import/no-default-export': 'error', - - // Unused code detection - 'no-unused-vars': 'off', - '@typescript-eslint/no-unused-vars': 'off', - 'unused-imports/no-unused-imports': 'error', - 'unused-imports/no-unused-vars': [ - 'error', + "import/order": [ + "error", { - 'vars': 'all', - 'varsIgnorePattern': '^_', - 'args': 'after-used', - 'argsIgnorePattern': '^_', + groups: [ + "builtin", + "external", + "internal", + "parent", + "sibling", + "index", + ], + "newlines-between": "always", + alphabetize: { + order: "asc", + caseInsensitive: true, + }, }, ], - + "import/no-default-export": "error", + + // Unused code detection + "no-unused-vars": "off", + "@typescript-eslint/no-unused-vars": "off", + "unused-imports/no-unused-imports": "error", + "unused-imports/no-unused-vars": [ + "error", + { + vars: "all", + varsIgnorePattern: "^_", + args: "after-used", + argsIgnorePattern: "^_", + }, + ], + // Turn off rules that might be too strict - '@typescript-eslint/no-explicit-any': 'off', - '@typescript-eslint/explicit-function-return-type': 'off', - '@typescript-eslint/explicit-module-boundary-types': 'off', - '@typescript-eslint/no-non-null-assertion': 'off', - + "@typescript-eslint/no-explicit-any": "off", + "@typescript-eslint/explicit-function-return-type": "off", + "@typescript-eslint/explicit-module-boundary-types": "off", + "@typescript-eslint/no-non-null-assertion": "off", + // Allow console for CLI tool - 'no-console': 'off', + "no-console": "off", }, settings: { - 'import/resolver': { - typescript: true, + "import/resolver": { + typescript: { + project: "./tsconfig.json", + }, node: true, }, }, }, { // Allow default exports in specific files - files: ['src/index.ts', '*.config.js', '*.config.ts'], + files: ["src/index.ts", "*.config.js", "*.config.ts"], rules: { - 'import/no-default-export': 'off', + "import/no-default-export": "off", }, }, { // Test files can have different rules - files: ['**/*.test.ts', '**/*.test.tsx', '**/*.spec.ts', '**/*.spec.tsx'], + files: ["**/*.test.ts", "**/*.test.tsx", "**/*.spec.ts", "**/*.spec.tsx"], rules: { - '@typescript-eslint/no-explicit-any': 'off', + "@typescript-eslint/no-explicit-any": "off", + "unused-imports/no-unused-vars": "off", + "max-classes-per-file": "off", }, }, { ignores: [ - 'dist/**', - 'node_modules/**', - 'coverage/**', - '*.d.ts', - 'src/__mocks__/**', + "dist/**", + "node_modules/**", + "coverage/**", + "*.d.ts", + "src/__mocks__/**", + "jest.setup.ts", + "vitest.config.ts", + "*.config.js", + "*.config.ts", ], }, -); \ No newline at end of file +]; diff --git a/package-lock.json b/package-lock.json index 528ba6f0e..64cdfb0ce 100644 --- a/package-lock.json +++ b/package-lock.json @@ -71,6 +71,7 @@ "conventional-changelog-conventionalcommits": "^9.1.0", "cross-env": "^7.0.3", "eslint": "^9.32.0", + "eslint-import-resolver-typescript": "^4.4.4", "eslint-plugin-import": "^2.32.0", "eslint-plugin-unused-imports": "^4.1.4", "execa": "^9.6.0", @@ -1180,6 +1181,40 @@ "kuler": "^2.0.0" } }, + "node_modules/@emnapi/core": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.4.5.tgz", + "integrity": "sha512-XsLw1dEOpkSX/WucdqUhPWP7hDxSvZiY+fsUC14h+FtQ2Ifni4znbBt8punRX+Uj2JG/uDb8nEHVKvrVlvdZ5Q==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "1.0.4", + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/runtime": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.4.5.tgz", + "integrity": "sha512-++LApOtY0pEEz1zrd9vy1/zXVaVJJ/EbAF3u0fXIzPJEDtnITsBGbbK0EkM72amhl/R5b+5xx0Y/QhcVOpuulg==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/wasi-threads": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.0.4.tgz", + "integrity": "sha512-PJR+bOmMOPH8AtcTGAyYNiuJ3/Fcoj2XN/gBEWzDIKh254XO+mM9XoXHk5GNEhodxeMznbg7BlRojVbKN+gC6g==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, "node_modules/@esbuild/darwin-arm64": { "version": "0.25.6", "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.6.tgz", @@ -1644,6 +1679,19 @@ "node": ">=18" } }, + "node_modules/@napi-rs/wasm-runtime": { + "version": "0.2.12", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-0.2.12.tgz", + "integrity": "sha512-ZVWUcfwY4E/yPitQJl481FjFo3K22D6qF0DuFH6Y/nbnE11GY5uguDxZMGXPQ8WQ0128MXQD7TnfHyK4oWoIJQ==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "^1.4.3", + "@emnapi/runtime": "^1.4.3", + "@tybys/wasm-util": "^0.10.0" + } + }, "node_modules/@noble/hashes": { "version": "1.8.0", "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", @@ -3863,6 +3911,17 @@ "dev": true, "license": "MIT" }, + "node_modules/@tybys/wasm-util": { + "version": "0.10.0", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.0.tgz", + "integrity": "sha512-VyyPYFlOMNylG45GoAe0xDoLwWuowvf92F9kySqzYh8vmYm7D2u4iUJKa1tOUpS70Ku13ASrOkS4ScXFsTaCNQ==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, "node_modules/@types/accepts": { "version": "1.3.7", "resolved": "https://registry.npmjs.org/@types/accepts/-/accepts-1.3.7.tgz", @@ -4514,6 +4573,275 @@ "url": "https://opencollective.com/eslint" } }, + "node_modules/@unrs/resolver-binding-android-arm-eabi": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-android-arm-eabi/-/resolver-binding-android-arm-eabi-1.11.1.tgz", + "integrity": "sha512-ppLRUgHVaGRWUx0R0Ut06Mjo9gBaBkg3v/8AxusGLhsIotbBLuRk51rAzqLC8gq6NyyAojEXglNjzf6R948DNw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@unrs/resolver-binding-android-arm64": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-android-arm64/-/resolver-binding-android-arm64-1.11.1.tgz", + "integrity": "sha512-lCxkVtb4wp1v+EoN+HjIG9cIIzPkX5OtM03pQYkG+U5O/wL53LC4QbIeazgiKqluGeVEeBlZahHalCaBvU1a2g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@unrs/resolver-binding-darwin-arm64": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-darwin-arm64/-/resolver-binding-darwin-arm64-1.11.1.tgz", + "integrity": "sha512-gPVA1UjRu1Y/IsB/dQEsp2V1pm44Of6+LWvbLc9SDk1c2KhhDRDBUkQCYVWe6f26uJb3fOK8saWMgtX8IrMk3g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@unrs/resolver-binding-darwin-x64": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-darwin-x64/-/resolver-binding-darwin-x64-1.11.1.tgz", + "integrity": "sha512-cFzP7rWKd3lZaCsDze07QX1SC24lO8mPty9vdP+YVa3MGdVgPmFc59317b2ioXtgCMKGiCLxJ4HQs62oz6GfRQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@unrs/resolver-binding-freebsd-x64": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-freebsd-x64/-/resolver-binding-freebsd-x64-1.11.1.tgz", + "integrity": "sha512-fqtGgak3zX4DCB6PFpsH5+Kmt/8CIi4Bry4rb1ho6Av2QHTREM+47y282Uqiu3ZRF5IQioJQ5qWRV6jduA+iGw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@unrs/resolver-binding-linux-arm-gnueabihf": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm-gnueabihf/-/resolver-binding-linux-arm-gnueabihf-1.11.1.tgz", + "integrity": "sha512-u92mvlcYtp9MRKmP+ZvMmtPN34+/3lMHlyMj7wXJDeXxuM0Vgzz0+PPJNsro1m3IZPYChIkn944wW8TYgGKFHw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-arm-musleabihf": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm-musleabihf/-/resolver-binding-linux-arm-musleabihf-1.11.1.tgz", + "integrity": "sha512-cINaoY2z7LVCrfHkIcmvj7osTOtm6VVT16b5oQdS4beibX2SYBwgYLmqhBjA1t51CarSaBuX5YNsWLjsqfW5Cw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-arm64-gnu": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm64-gnu/-/resolver-binding-linux-arm64-gnu-1.11.1.tgz", + "integrity": "sha512-34gw7PjDGB9JgePJEmhEqBhWvCiiWCuXsL9hYphDF7crW7UgI05gyBAi6MF58uGcMOiOqSJ2ybEeCvHcq0BCmQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-arm64-musl": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm64-musl/-/resolver-binding-linux-arm64-musl-1.11.1.tgz", + "integrity": "sha512-RyMIx6Uf53hhOtJDIamSbTskA99sPHS96wxVE/bJtePJJtpdKGXO1wY90oRdXuYOGOTuqjT8ACccMc4K6QmT3w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-ppc64-gnu": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-ppc64-gnu/-/resolver-binding-linux-ppc64-gnu-1.11.1.tgz", + "integrity": "sha512-D8Vae74A4/a+mZH0FbOkFJL9DSK2R6TFPC9M+jCWYia/q2einCubX10pecpDiTmkJVUH+y8K3BZClycD8nCShA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-riscv64-gnu": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-riscv64-gnu/-/resolver-binding-linux-riscv64-gnu-1.11.1.tgz", + "integrity": "sha512-frxL4OrzOWVVsOc96+V3aqTIQl1O2TjgExV4EKgRY09AJ9leZpEg8Ak9phadbuX0BA4k8U5qtvMSQQGGmaJqcQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-riscv64-musl": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-riscv64-musl/-/resolver-binding-linux-riscv64-musl-1.11.1.tgz", + "integrity": "sha512-mJ5vuDaIZ+l/acv01sHoXfpnyrNKOk/3aDoEdLO/Xtn9HuZlDD6jKxHlkN8ZhWyLJsRBxfv9GYM2utQ1SChKew==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-s390x-gnu": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-s390x-gnu/-/resolver-binding-linux-s390x-gnu-1.11.1.tgz", + "integrity": "sha512-kELo8ebBVtb9sA7rMe1Cph4QHreByhaZ2QEADd9NzIQsYNQpt9UkM9iqr2lhGr5afh885d/cB5QeTXSbZHTYPg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-x64-gnu": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-x64-gnu/-/resolver-binding-linux-x64-gnu-1.11.1.tgz", + "integrity": "sha512-C3ZAHugKgovV5YvAMsxhq0gtXuwESUKc5MhEtjBpLoHPLYM+iuwSj3lflFwK3DPm68660rZ7G8BMcwSro7hD5w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-x64-musl": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-x64-musl/-/resolver-binding-linux-x64-musl-1.11.1.tgz", + "integrity": "sha512-rV0YSoyhK2nZ4vEswT/QwqzqQXw5I6CjoaYMOX0TqBlWhojUf8P94mvI7nuJTeaCkkds3QE4+zS8Ko+GdXuZtA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-wasm32-wasi": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-wasm32-wasi/-/resolver-binding-wasm32-wasi-1.11.1.tgz", + "integrity": "sha512-5u4RkfxJm+Ng7IWgkzi3qrFOvLvQYnPBmjmZQ8+szTK/b31fQCnleNl1GgEt7nIsZRIf5PLhPwT0WM+q45x/UQ==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@napi-rs/wasm-runtime": "^0.2.11" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@unrs/resolver-binding-win32-arm64-msvc": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-arm64-msvc/-/resolver-binding-win32-arm64-msvc-1.11.1.tgz", + "integrity": "sha512-nRcz5Il4ln0kMhfL8S3hLkxI85BXs3o8EYoattsJNdsX4YUU89iOkVn7g0VHSRxFuVMdM4Q1jEpIId1Ihim/Uw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@unrs/resolver-binding-win32-ia32-msvc": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-ia32-msvc/-/resolver-binding-win32-ia32-msvc-1.11.1.tgz", + "integrity": "sha512-DCEI6t5i1NmAZp6pFonpD5m7i6aFrpofcp4LA2i8IIq60Jyo28hamKBxNrZcyOwVOZkgsRp9O2sXWBWP8MnvIQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@unrs/resolver-binding-win32-x64-msvc": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-x64-msvc/-/resolver-binding-win32-x64-msvc-1.11.1.tgz", + "integrity": "sha512-lrW200hZdbfRtztbygyaq/6jP6AKE8qQN2KvPcJ+x7wiD038YtnYtZ82IMNJ69GJibV7bwL3y9FgK+5w/pYt6g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, "node_modules/@vitest/expect": { "version": "3.2.4", "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-3.2.4.tgz", @@ -6900,6 +7228,31 @@ } } }, + "node_modules/eslint-import-context": { + "version": "0.1.9", + "resolved": "https://registry.npmjs.org/eslint-import-context/-/eslint-import-context-0.1.9.tgz", + "integrity": "sha512-K9Hb+yRaGAGUbwjhFNHvSmmkZs9+zbuoe3kFQ4V1wYjrepUFYM2dZAfNtjbbj3qsPfUfsA68Bx/ICWQMi+C8Eg==", + "dev": true, + "license": "MIT", + "dependencies": { + "get-tsconfig": "^4.10.1", + "stable-hash-x": "^0.2.0" + }, + "engines": { + "node": "^12.20.0 || ^14.18.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint-import-context" + }, + "peerDependencies": { + "unrs-resolver": "^1.0.0" + }, + "peerDependenciesMeta": { + "unrs-resolver": { + "optional": true + } + } + }, "node_modules/eslint-import-resolver-node": { "version": "0.3.9", "resolved": "https://registry.npmjs.org/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.9.tgz", @@ -6922,6 +7275,41 @@ "ms": "^2.1.1" } }, + "node_modules/eslint-import-resolver-typescript": { + "version": "4.4.4", + "resolved": "https://registry.npmjs.org/eslint-import-resolver-typescript/-/eslint-import-resolver-typescript-4.4.4.tgz", + "integrity": "sha512-1iM2zeBvrYmUNTj2vSC/90JTHDth+dfOfiNKkxApWRsTJYNrc8rOdxxIf5vazX+BiAXTeOT0UvWpGI/7qIWQOw==", + "dev": true, + "license": "ISC", + "dependencies": { + "debug": "^4.4.1", + "eslint-import-context": "^0.1.8", + "get-tsconfig": "^4.10.1", + "is-bun-module": "^2.0.0", + "stable-hash-x": "^0.2.0", + "tinyglobby": "^0.2.14", + "unrs-resolver": "^1.7.11" + }, + "engines": { + "node": "^16.17.0 || >=18.6.0" + }, + "funding": { + "url": "https://opencollective.com/eslint-import-resolver-typescript" + }, + "peerDependencies": { + "eslint": "*", + "eslint-plugin-import": "*", + "eslint-plugin-import-x": "*" + }, + "peerDependenciesMeta": { + "eslint-plugin-import": { + "optional": true + }, + "eslint-plugin-import-x": { + "optional": true + } + } + }, "node_modules/eslint-module-utils": { "version": "2.12.1", "resolved": "https://registry.npmjs.org/eslint-module-utils/-/eslint-module-utils-2.12.1.tgz", @@ -9089,6 +9477,16 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/is-bun-module": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-bun-module/-/is-bun-module-2.0.0.tgz", + "integrity": "sha512-gNCGbnnnnFAUGKeZ9PdbyeGYJqewpmc2aKHUEMO5nQPWU9lOmv7jcmQIv+qHD8fXW6W7qfuCwX4rY9LNRjXrkQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "semver": "^7.7.1" + } + }, "node_modules/is-callable": { "version": "1.2.7", "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz", @@ -10373,6 +10771,22 @@ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" } }, + "node_modules/napi-postinstall": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/napi-postinstall/-/napi-postinstall-0.3.2.tgz", + "integrity": "sha512-tWVJxJHmBWLy69PvO96TZMZDrzmw5KeiZBz3RHmiM2XZ9grBJ2WgMAFVVg25nqp3ZjTFUs2Ftw1JhscL3Teliw==", + "dev": true, + "license": "MIT", + "bin": { + "napi-postinstall": "lib/cli.js" + }, + "engines": { + "node": "^12.20.0 || ^14.18.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/napi-postinstall" + } + }, "node_modules/natural-compare": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", @@ -15323,6 +15737,16 @@ "through2": "~2.0.0" } }, + "node_modules/stable-hash-x": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/stable-hash-x/-/stable-hash-x-0.2.0.tgz", + "integrity": "sha512-o3yWv49B/o4QZk5ZcsALc6t0+eCelPc44zZsLtCQnZPDwFpDYSWcDnrv2TtMmMbQ7uKo3J0HTURCqckw23czNQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/stack-trace": { "version": "0.0.10", "resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz", @@ -16345,6 +16769,41 @@ "node": ">= 0.8" } }, + "node_modules/unrs-resolver": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/unrs-resolver/-/unrs-resolver-1.11.1.tgz", + "integrity": "sha512-bSjt9pjaEBnNiGgc9rUiHGKv5l4/TGzDmYw3RhnkJGtLhbnnA/5qJj7x3dNDCRx/PJxu774LlH8lCOlB4hEfKg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "napi-postinstall": "^0.3.0" + }, + "funding": { + "url": "https://opencollective.com/unrs-resolver" + }, + "optionalDependencies": { + "@unrs/resolver-binding-android-arm-eabi": "1.11.1", + "@unrs/resolver-binding-android-arm64": "1.11.1", + "@unrs/resolver-binding-darwin-arm64": "1.11.1", + "@unrs/resolver-binding-darwin-x64": "1.11.1", + "@unrs/resolver-binding-freebsd-x64": "1.11.1", + "@unrs/resolver-binding-linux-arm-gnueabihf": "1.11.1", + "@unrs/resolver-binding-linux-arm-musleabihf": "1.11.1", + "@unrs/resolver-binding-linux-arm64-gnu": "1.11.1", + "@unrs/resolver-binding-linux-arm64-musl": "1.11.1", + "@unrs/resolver-binding-linux-ppc64-gnu": "1.11.1", + "@unrs/resolver-binding-linux-riscv64-gnu": "1.11.1", + "@unrs/resolver-binding-linux-riscv64-musl": "1.11.1", + "@unrs/resolver-binding-linux-s390x-gnu": "1.11.1", + "@unrs/resolver-binding-linux-x64-gnu": "1.11.1", + "@unrs/resolver-binding-linux-x64-musl": "1.11.1", + "@unrs/resolver-binding-wasm32-wasi": "1.11.1", + "@unrs/resolver-binding-win32-arm64-msvc": "1.11.1", + "@unrs/resolver-binding-win32-ia32-msvc": "1.11.1", + "@unrs/resolver-binding-win32-x64-msvc": "1.11.1" + } + }, "node_modules/uri-js": { "version": "4.4.1", "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", diff --git a/package.json b/package.json index 5c15b4726..9cedf9f2c 100644 --- a/package.json +++ b/package.json @@ -95,6 +95,7 @@ "conventional-changelog-conventionalcommits": "^9.1.0", "cross-env": "^7.0.3", "eslint": "^9.32.0", + "eslint-import-resolver-typescript": "^4.4.4", "eslint-plugin-import": "^2.32.0", "eslint-plugin-unused-imports": "^4.1.4", "execa": "^9.6.0", diff --git a/src/CLIPlatformClient.ts b/src/CLIPlatformClient.ts index c815cf582..e919825b2 100644 --- a/src/CLIPlatformClient.ts +++ b/src/CLIPlatformClient.ts @@ -1,3 +1,7 @@ +import * as fs from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; + import { FQSN, PlatformClient, @@ -6,9 +10,6 @@ import { } from "@continuedev/config-yaml"; import { DefaultApiInterface } from "@continuedev/sdk/dist/api"; import * as dotenv from "dotenv"; -import * as fs from "node:fs"; -import * as os from "node:os"; -import * as path from "node:path"; export class CLIPlatformClient implements PlatformClient { constructor( diff --git a/src/MCPConnection.ts b/src/MCPConnection.ts new file mode 100644 index 000000000..0baaea017 --- /dev/null +++ b/src/MCPConnection.ts @@ -0,0 +1,57 @@ +import { type AssistantConfig } from "@continuedev/sdk"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; + +import { logger } from "./util/logger.js"; + +export class MCPConnection { + prompts: Awaited>["prompts"] = []; + tools: Awaited>["tools"] = []; + + private constructor(public readonly client: Client) {} + + public static async create( + config: NonNullable[number] + ) { + const client = new Client( + { + name: "continue-cli-client", + version: "1.0.0", + }, + { capabilities: {} } + ); + + // Construct transport + const env: Record = config?.env || {}; + if (process.env.PATH !== undefined) { + env.PATH = process.env.PATH; + } + + if (!config?.command) { + throw new Error("MCP server command is not specified"); + } + + const transport = new StdioClientTransport({ + command: config.command, + args: config?.args, + env, + }); + + // Connect and get all prompts and tools + const connection = new MCPConnection(client); + logger.debug('Connecting to MCP server', { command: config.command }); + await client.connect(transport); + const capabilities = client.getServerCapabilities(); + logger.debug('MCP server capabilities', { hasPrompts: !!capabilities?.prompts, hasTools: !!capabilities?.tools }); + + if (capabilities?.prompts) { + connection.prompts = (await client.listPrompts()).prompts; + } + + if (capabilities?.tools) { + connection.tools = (await client.listTools()).tools; + } + + return connection; + } +} \ No newline at end of file diff --git a/src/args.test.ts b/src/args.test.ts index aa0dc9e04..149e6d19a 100644 --- a/src/args.test.ts +++ b/src/args.test.ts @@ -1,4 +1,5 @@ import { vi } from 'vitest'; + import { parseArgs, processRule } from "./args.js"; describe("parseArgs", () => { diff --git a/src/args.ts b/src/args.ts index d783fd309..8031d3909 100644 --- a/src/args.ts +++ b/src/args.ts @@ -1,6 +1,8 @@ import * as fs from "fs"; -import JSZip from "jszip"; import * as path from "path"; + +import JSZip from "jszip"; + import { env } from "./env.js"; export interface CommandLineArgs { diff --git a/src/asciiArt.ts b/src/asciiArt.ts index b5b853c59..772772d49 100644 --- a/src/asciiArt.ts +++ b/src/asciiArt.ts @@ -1,4 +1,5 @@ import chalk from "chalk"; + import { getVersion } from "./version.js"; const b = chalk.bold.magenta; diff --git a/src/auth/ensureAuth.ts b/src/auth/ensureAuth.ts index 067e8b5da..8ee8e4402 100644 --- a/src/auth/ensureAuth.ts +++ b/src/auth/ensureAuth.ts @@ -1,4 +1,5 @@ import chalk from "chalk"; + import { isAuthenticated, login } from "./workos.js"; /** @@ -22,7 +23,7 @@ export async function ensureAuthenticated( await login(); return true; } catch (error) { - console.error(chalk.red("Failed to authenticate.")); + console.error(chalk.red("Failed to authenticate."), error); return false; } } diff --git a/src/auth/workos.ts b/src/auth/workos.ts index 83589cfd9..6b2849370 100644 --- a/src/auth/workos.ts +++ b/src/auth/workos.ts @@ -1,14 +1,14 @@ -import chalk from "chalk"; import * as fs from "fs"; -import open from "open"; import * as os from "os"; import * as path from "path"; -import { createInterface } from "readline"; -import { env } from "../env.js"; +import chalk from "chalk"; // Polyfill fetch for Node < 18 import nodeFetch from "node-fetch"; +import open from "open"; + import { getApiClient } from "../config.js"; +import { env } from "../env.js"; if (!globalThis.fetch) { globalThis.fetch = nodeFetch as unknown as typeof globalThis.fetch; } @@ -271,23 +271,6 @@ export function isAuthenticated(): boolean { return true; } -/** - * Prompt the user for input - */ -function prompt(question: string): Promise { - const rl = createInterface({ - input: process.stdin, - output: process.stdout, - }); - - return new Promise((resolve) => { - rl.question(question, (answer) => { - rl.close(); - resolve(answer); - }); - }); -} - /** * Device authorization response from WorkOS */ @@ -524,7 +507,7 @@ export async function login(): Promise { // Try to open the complete verification URL in browser try { await open(deviceAuth.verification_uri_complete); - } catch (error) { + } catch { console.info(chalk.yellow("Unable to open browser automatically")); } @@ -665,7 +648,7 @@ export async function listUserOrganizations(): Promise< try { const resp = await apiClient.listOrganizations(); return resp.organizations || []; - } catch (error) { + } catch { return null; } } diff --git a/src/commands/chat.ts b/src/commands/chat.ts index b4d4ca68e..e9ab745fa 100644 --- a/src/commands/chat.ts +++ b/src/commands/chat.ts @@ -2,6 +2,7 @@ import { ModelConfig } from "@continuedev/config-yaml"; import chalk from "chalk"; import { ChatCompletionMessageParam } from "openai/resources.mjs"; import * as readlineSync from "readline-sync"; + import { CONTINUE_ASCII_ART } from "../asciiArt.js"; import { loadAuthConfig } from "../auth/workos.js"; import { @@ -19,16 +20,17 @@ import { loadSession, saveSession } from "../session.js"; import { streamChatResponse } from "../streamChatResponse.js"; import { constructSystemMessage } from "../systemMessage.js"; import { posthogService } from "../telemetry/posthogService.js"; -import telemetryService from "../telemetry/telemetryService.js"; +import { telemetryService } from "../telemetry/telemetryService.js"; import { startTUIChat } from "../ui/index.js"; import { safeStdout } from "../util/consoleOverride.js"; import { formatError } from "../util/formatError.js"; -import logger from "../util/logger.js"; +import { logger } from "../util/logger.js"; import { calculateContextUsagePercentage, countChatHistoryTokens, shouldAutoCompact, } from "../util/tokenizer.js"; + import { ExtendedCommandOptions } from "./BaseCommandOptions.js"; /** @@ -44,7 +46,7 @@ function processJsonOutput(response: string): string { JSON.parse(trimmedResponse); // If it parses successfully, return as-is return trimmedResponse; - } catch (error) { + } catch { // If it's not valid JSON, wrap it in a JSON object return JSON.stringify({ response: trimmedResponse, diff --git a/src/commands/commands.integration.test.ts b/src/commands/commands.integration.test.ts index cd956b674..7b684f29d 100644 --- a/src/commands/commands.integration.test.ts +++ b/src/commands/commands.integration.test.ts @@ -1,5 +1,6 @@ -import { beforeEach, describe, expect, it } from 'vitest'; import type { AssistantConfig } from '@continuedev/sdk'; +import { describe, expect, it } from 'vitest'; + import { getAllSlashCommands } from './commands.js'; describe('Slash Commands Integration', () => { diff --git a/src/commands/login.ts b/src/commands/login.ts index d7d96a827..5786904ae 100644 --- a/src/commands/login.ts +++ b/src/commands/login.ts @@ -1,4 +1,5 @@ import chalk from "chalk"; + import { login as workosLogin } from "../auth/workos.js"; export async function login() { diff --git a/src/commands/remote-test.ts b/src/commands/remote-test.ts index 119cbc1d0..7738b0f8e 100644 --- a/src/commands/remote-test.ts +++ b/src/commands/remote-test.ts @@ -1,7 +1,8 @@ import chalk from "chalk"; -import telemetryService from "../telemetry/telemetryService.js"; + +import { telemetryService } from "../telemetry/telemetryService.js"; import { startRemoteTUIChat } from "../ui/index.js"; -import logger from "../util/logger.js"; +import { logger } from "../util/logger.js"; export async function remoteTest( prompt?: string, diff --git a/src/commands/remote.ts b/src/commands/remote.ts index e95c912c0..8f4f42c3d 100644 --- a/src/commands/remote.ts +++ b/src/commands/remote.ts @@ -1,13 +1,14 @@ import chalk from "chalk"; + import { getAccessToken, isAuthenticatedConfig, loadAuthConfig, } from "../auth/workos.js"; import { env } from "../env.js"; -import telemetryService from "../telemetry/telemetryService.js"; +import { telemetryService } from "../telemetry/telemetryService.js"; import { startRemoteTUIChat } from "../ui/index.js"; -import logger from "../util/logger.js"; +import { logger } from "../util/logger.js"; export async function remote( prompt: string | undefined, diff --git a/src/commands/serve.test.ts b/src/commands/serve.test.ts index 0c8f662e9..23c762460 100644 --- a/src/commands/serve.test.ts +++ b/src/commands/serve.test.ts @@ -1,3 +1,5 @@ +import type { Server } from "http"; + import { afterEach, beforeEach, @@ -6,13 +8,12 @@ import { it, vi, } from "vitest"; -import type { Server } from "http"; + import { createMinimalTestContext } from "../test-helpers/ui-test-context.js"; describe("serve command", () => { let context: any; let originalProcessExit: typeof process.exit; - let serverPromise: Promise; let serverRef: Server | null = null; beforeEach(() => { diff --git a/src/commands/serve.ts b/src/commands/serve.ts index 137591b0d..5aa17f648 100644 --- a/src/commands/serve.ts +++ b/src/commands/serve.ts @@ -1,12 +1,14 @@ -import chalk from "chalk"; import { exec } from "child_process"; -import express, { Request, Response } from "express"; -import type { ChatCompletionMessageParam } from "openai/resources.mjs"; import path from "path"; import { promisify } from "util"; + +import chalk from "chalk"; +import express, { Request, Response } from "express"; +import type { ChatCompletionMessageParam } from "openai/resources.mjs"; + + import { getAssistantSlug } from "../auth/workos.js"; import { toolPermissionManager } from "../permissions/permissionManager.js"; -import { saveSession } from "../session.js"; import { getService, initializeServices, @@ -17,17 +19,19 @@ import { ConfigServiceState, ModelServiceState, } from "../services/types.js"; +import { saveSession } from "../session.js"; import { streamChatResponse, type StreamCallbacks, } from "../streamChatResponse.js"; import { constructSystemMessage } from "../systemMessage.js"; -import telemetryService from "../telemetry/telemetryService.js"; +import { telemetryService } from "../telemetry/telemetryService.js"; +import { getToolDisplayName } from "../tools/index.js"; import { DisplayMessage } from "../ui/types.js"; import { formatError } from "../util/formatError.js"; -import logger from "../util/logger.js"; +import { logger } from "../util/logger.js"; + import { ExtendedCommandOptions } from "./BaseCommandOptions.js"; -import { getToolDisplayName } from "../tools/index.js"; const execAsync = promisify(exec); @@ -125,7 +129,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { } // Initialize chat history - let chatHistory: ChatCompletionMessageParam[] = []; + const chatHistory: ChatCompletionMessageParam[] = []; const systemMessage = await constructSystemMessage("", options.rule, undefined, true); if (systemMessage) { chatHistory.push({ role: "system", content: systemMessage }); diff --git a/src/compaction.test.ts b/src/compaction.test.ts index 896b6c39f..011a16677 100644 --- a/src/compaction.test.ts +++ b/src/compaction.test.ts @@ -1,9 +1,11 @@ -import { describe, it, expect, vi } from "vitest"; -import { ChatCompletionMessageParam } from "openai/resources.mjs"; -import { compactChatHistory, findCompactionIndex, getHistoryForLLM, COMPACTION_MARKER } from "./compaction.js"; -import { streamChatResponse } from "./streamChatResponse.js"; 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, findCompactionIndex, getHistoryForLLM, COMPACTION_MARKER } from "./compaction.js"; +import { streamChatResponse } from "./streamChatResponse.js"; + // Mock the streamChatResponse function vi.mock("./streamChatResponse.js", () => ({ diff --git a/src/compaction.ts b/src/compaction.ts index ae38cb0d2..484866476 100644 --- a/src/compaction.ts +++ b/src/compaction.ts @@ -1,8 +1,9 @@ import { ModelConfig } from "@continuedev/config-yaml"; import { BaseLlmApi } from "@continuedev/openai-adapters"; import { ChatCompletionMessageParam } from "openai/resources.mjs"; + import { StreamCallbacks, streamChatResponse } from "./streamChatResponse.js"; -import logger from "./util/logger.js"; +import { logger } from "./util/logger.js"; export const COMPACTION_MARKER = "[COMPACTED HISTORY]"; diff --git a/src/config.ts b/src/config.ts index ec91eb263..86b8dd8e8 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1,8 +1,7 @@ + import { AssistantUnrolled, ModelConfig, - RegistryClient, - unrollAssistant, } from "@continuedev/config-yaml"; import { BaseLlmApi, @@ -14,14 +13,12 @@ import { DefaultApi, DefaultApiInterface, } from "@continuedev/sdk/dist/api/dist/index.js"; -import chalk from "chalk"; -import { dirname } from "node:path"; + import { AuthConfig, getAccessToken, getOrganizationId, } from "./auth/workos.js"; -import { CLIPlatformClient } from "./CLIPlatformClient.js"; import { loadConfiguration } from "./configLoader.js"; import { env } from "./env.js"; import { MCPService } from "./mcp.js"; @@ -77,43 +74,6 @@ export function getLlmApi( return [llmApi, model]; } -async function loadConfigYaml( - accessToken: string | null, - filePath: string, - organizationId: string | null, - apiClient: DefaultApiInterface -): Promise { - const unrollResult = await unrollAssistant( - { filePath, uriType: "file" }, - new RegistryClient({ - accessToken: accessToken ?? undefined, - apiBase: env.apiBase, - rootPath: dirname(filePath), - }), - { - currentUserSlug: "", - alwaysUseProxy: false, - orgScopeId: organizationId, - renderSecrets: true, - platformClient: new CLIPlatformClient(organizationId, apiClient), - onPremProxyUrl: null, - } - ); - - const errorDetails = unrollResult.errors; - if (!unrollResult.config) { - throw new Error(`Failed to load config file:\n${errorDetails}`); - } else if (errorDetails?.length) { - const warnings = - errorDetails?.length > 1 - ? errorDetails.map((d) => `\n- ${d.message}`) - : errorDetails[0].message; - console.warn(chalk.dim(`Warning: ${warnings}`)); - } - - return unrollResult.config; -} - export function getApiClient( accessToken: string | undefined | null ): DefaultApi { diff --git a/src/configLoader.ts b/src/configLoader.ts index 3c54366c9..208c64b45 100644 --- a/src/configLoader.ts +++ b/src/configLoader.ts @@ -1,3 +1,8 @@ +import * as fs from "fs"; +import { dirname } from "node:path"; +import * as os from "os"; +import * as path from "path"; + import { AssistantUnrolled, RegistryClient, @@ -5,10 +10,7 @@ import { } from "@continuedev/config-yaml"; import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js"; import chalk from "chalk"; -import * as fs from "fs"; -import { dirname } from "node:path"; -import * as os from "os"; -import * as path from "path"; + import { AuthConfig, getAccessToken, diff --git a/src/continueSDK.ts b/src/continueSDK.ts index 77e23f94d..2867176dd 100644 --- a/src/continueSDK.ts +++ b/src/continueSDK.ts @@ -1,7 +1,8 @@ import { Continue, ContinueClient } from "@continuedev/sdk"; -import { env } from "./env.js"; import chalk from "chalk"; +import { env } from "./env.js"; + /** * Initialize the Continue SDK with the given parameters * @param apiKey - API key to use for authentication diff --git a/src/e2e/auth.test.ts b/src/e2e/auth.test.ts index 28ef5d87d..7d7e529a5 100644 --- a/src/e2e/auth.test.ts +++ b/src/e2e/auth.test.ts @@ -1,5 +1,6 @@ import fs from "fs/promises"; import path from "path"; + import { cleanupTestContext, createTestContext, diff --git a/src/e2e/headless-dynamic-responses.test.ts b/src/e2e/headless-dynamic-responses.test.ts index f4b4722b2..0414d0838 100644 --- a/src/e2e/headless-dynamic-responses.test.ts +++ b/src/e2e/headless-dynamic-responses.test.ts @@ -1,3 +1,6 @@ +import * as fs from "fs/promises"; +import * as path from "path"; + import { cleanupTestContext, createTestContext, @@ -10,8 +13,6 @@ import { createMockLLMConfig, type MockLLMServer, } from "../test-helpers/mock-llm-server.js"; -import * as fs from "fs/promises"; -import * as path from "path"; describe("E2E: Headless Mode with Dynamic Responses", () => { let context: any; diff --git a/src/e2e/headless-minimal.test.ts b/src/e2e/headless-minimal.test.ts index 2312d22f9..5e7ace9db 100644 --- a/src/e2e/headless-minimal.test.ts +++ b/src/e2e/headless-minimal.test.ts @@ -1,5 +1,6 @@ import fs from "fs/promises"; import path from "path"; + import { cleanupTestContext, createTestContext, diff --git a/src/e2e/headless-tool-calls.test.ts b/src/e2e/headless-tool-calls.test.ts index c7d94cfca..0f2887f2b 100644 --- a/src/e2e/headless-tool-calls.test.ts +++ b/src/e2e/headless-tool-calls.test.ts @@ -1,4 +1,5 @@ import * as http from "http"; + import { cleanupTestContext, createTestContext, diff --git a/src/e2e/resume-flag.test.ts b/src/e2e/resume-flag.test.ts index bed9432d8..87e105b06 100644 --- a/src/e2e/resume-flag.test.ts +++ b/src/e2e/resume-flag.test.ts @@ -1,3 +1,6 @@ +import * as fs from "fs/promises"; +import * as path from "path"; + import { cleanupTestContext, createTestContext, @@ -8,8 +11,6 @@ import { cleanupMockLLMServer, type MockLLMServer, } from "../test-helpers/mock-llm-server.js"; -import * as fs from "fs/promises"; -import * as path from "path"; describe("E2E: Resume Flag", () => { let context: any; @@ -130,7 +131,7 @@ describe("E2E: Resume Flag", () => { expect(firstResult.stdout).toContain("First response"); // Verify the first session was saved correctly - let sessionDir = path.join(context.testDir, ".continue-cli", "sessions"); + const sessionDir = path.join(context.testDir, ".continue-cli", "sessions"); let sessionFiles = await fs.readdir(sessionDir); expect(sessionFiles).toHaveLength(1); diff --git a/src/freeTrialTransition.ts b/src/freeTrialTransition.ts index 2387027d5..514e2f107 100644 --- a/src/freeTrialTransition.ts +++ b/src/freeTrialTransition.ts @@ -1,13 +1,15 @@ -import chalk from "chalk"; import { spawn } from "child_process"; import * as fs from "fs"; -import open from "open"; import * as os from "os"; import * as path from "path"; + +import chalk from "chalk"; +import open from "open"; import * as readlineSync from "readline-sync"; -import { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js"; -import { isValidAnthropicApiKey, getApiKeyValidationError } from "./util/apiKeyValidation.js"; + import { env } from "./env.js"; +import { isValidAnthropicApiKey, getApiKeyValidationError } from "./util/apiKeyValidation.js"; +import { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js"; const CONFIG_PATH = path.join(os.homedir(), ".continue", "config.yaml"); @@ -63,7 +65,7 @@ export async function handleMaxedOutFreeTrial(onReload?: () => Promise): P "After setting up your models subscription, restart the CLI to continue." ) ); - } catch (error) { + } catch { console.log(chalk.yellow("\n⚠ Could not open browser automatically")); console.log(chalk.white(`Please visit: ${modelsUrl}`)); console.log( diff --git a/src/hooks/useService.ts b/src/hooks/useService.ts index ccbe34093..c78eff3c3 100644 --- a/src/hooks/useService.ts +++ b/src/hooks/useService.ts @@ -1,4 +1,5 @@ import { useEffect, useState } from 'react'; + import { useServiceContainer } from '../services/ServiceContainerContext.js'; import { ServiceResult } from '../services/types.js'; @@ -104,25 +105,20 @@ export function useServices>( const newServices: Partial = {}; let hasLoading = false; let hasError: Error | null = null; - let allReady = true; for (const serviceName of serviceNames) { const result = container.getSync(serviceName as string); if (result.state === 'loading') { hasLoading = true; - allReady = false; } else if (result.state === 'error') { hasError = result.error; - allReady = false; } else if (result.state === 'idle') { - allReady = false; // Auto-load idle services container.load(serviceName as string).catch(() => {}); } else if (result.state === 'ready' && result.value !== null) { newServices[serviceName] = result.value as T[keyof T]; } else { - allReady = false; } } diff --git a/src/index.ts b/src/index.ts index bf6799f94..3156a398e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,6 +1,7 @@ #!/usr/bin/env node import { Command } from "commander"; + import { chat } from "./commands/chat.js"; import { login } from "./commands/login.js"; import { logout } from "./commands/logout.js"; @@ -9,7 +10,7 @@ import { remote } from "./commands/remote.js"; import { serve } from "./commands/serve.js"; import { addCommonOptions, mergeParentOptions } from "./shared-options.js"; import { configureConsoleForHeadless } from "./util/consoleOverride.js"; -import logger from "./util/logger.js"; +import { logger } from "./util/logger.js"; import { readStdinSync } from "./util/stdin.js"; import { getVersion } from "./version.js"; diff --git a/src/logging.test.ts b/src/logging.test.ts index 96167a452..fb4bf63f9 100644 --- a/src/logging.test.ts +++ b/src/logging.test.ts @@ -1,3 +1,6 @@ +import chalk from 'chalk'; +import { vi } from 'vitest'; + import { configureLogger, isLoggingEnabled, @@ -7,8 +10,6 @@ import { warn, loggers } from './logging.js'; -import { vi } from 'vitest'; -import chalk from 'chalk'; describe('logging utilities', () => { let consoleInfoSpy: ReturnType; diff --git a/src/mcp.ts b/src/mcp.ts index 10489d553..9a5a32e79 100644 --- a/src/mcp.ts +++ b/src/mcp.ts @@ -1,7 +1,7 @@ import { type AssistantConfig } from "@continuedev/sdk"; -import { Client } from "@modelcontextprotocol/sdk/client/index.js"; -import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; -import logger from "./util/logger.js"; + +import { MCPConnection } from "./MCPConnection.js"; +import { logger } from "./util/logger.js"; export class MCPService { private readonly connections: MCPConnection[] = []; @@ -60,55 +60,3 @@ export class MCPService { throw new Error(`Tool ${name} not found`); } } - -export class MCPConnection { - prompts: Awaited>["prompts"] = []; - tools: Awaited>["tools"] = []; - - private constructor(public readonly client: Client) {} - - public static async create( - config: NonNullable[number] - ) { - const client = new Client( - { - name: "continue-cli-client", - version: "1.0.0", - }, - { capabilities: {} } - ); - - // Construct transport - const env: Record = config?.env || {}; - if (process.env.PATH !== undefined) { - env.PATH = process.env.PATH; - } - - if (!config?.command) { - throw new Error("MCP server command is not specified"); - } - - const transport = new StdioClientTransport({ - command: config.command, - args: config?.args, - env, - }); - - // Connect and get all prompts and tools - const connection = new MCPConnection(client); - logger.debug('Connecting to MCP server', { command: config.command }); - await client.connect(transport); - const capabilities = client.getServerCapabilities(); - logger.debug('MCP server capabilities', { hasPrompts: !!capabilities?.prompts, hasTools: !!capabilities?.tools }); - - if (capabilities?.prompts) { - connection.prompts = (await client.listPrompts()).prompts; - } - - if (capabilities?.tools) { - connection.tools = (await client.listTools()).tools; - } - - return connection; - } -} diff --git a/src/onboarding.ts b/src/onboarding.ts index 4f8594d7a..b379f368d 100644 --- a/src/onboarding.ts +++ b/src/onboarding.ts @@ -1,16 +1,19 @@ +import * as fs from "fs"; +import * as os from "os"; +import * as path from "path"; + import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; import { BaseLlmApi } from "@continuedev/openai-adapters"; import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js"; import chalk from "chalk"; -import * as fs from "fs"; -import * as os from "os"; -import * as path from "path"; import * as readlineSync from "readline-sync"; + import { processRule } from "./args.js"; import { AuthConfig, isAuthenticated, login } from "./auth/workos.js"; import { initialize } from "./config.js"; import { MCPService } from "./mcp.js"; import { isValidAnthropicApiKey, getApiKeyValidationError } from "./util/apiKeyValidation.js"; +import { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js"; const CONFIG_PATH = path.join(os.homedir(), ".continue", "config.yaml"); @@ -33,13 +36,11 @@ export async function checkHasAcceptableModel( const content = fs.readFileSync(configPath, "utf8"); return content.includes("claude"); - } catch (error) { + } catch { return false; } } -import { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js"; - export async function createOrUpdateConfig(apiKey: string): Promise { const configDir = path.dirname(CONFIG_PATH); @@ -111,7 +112,7 @@ export async function runNormalFlow( ): Promise { // Step 1: Check if --config flag is provided if (configPath) { - let result = await initialize(authConfig, configPath); + const result = await initialize(authConfig, configPath); // Inject rules into the config if provided if (rules && rules.length > 0) { result.config = await injectRulesIntoConfig(result.config, rules); @@ -122,25 +123,27 @@ export async function runNormalFlow( // Step 2: If user is logged in, look for first assistant in selected org if (isAuthenticated()) { try { - let result = await initialize(authConfig, undefined); + const result = await initialize(authConfig, undefined); // Inject rules into the config if provided if (rules && rules.length > 0) { result.config = await injectRulesIntoConfig(result.config, rules); } return { ...result, wasOnboarded: false }; - } catch (error) {} + } catch { + // Silently ignore errors when loading default assistant + } } // Step 3: Look for local ~/.continue/config.yaml if (fs.existsSync(CONFIG_PATH)) { try { - let result = await initialize(authConfig, CONFIG_PATH); + const result = await initialize(authConfig, CONFIG_PATH); // Inject rules into the config if provided if (rules && rules.length > 0) { result.config = await injectRulesIntoConfig(result.config, rules); } return { ...result, wasOnboarded: false }; - } catch (error) { + } catch { console.log(chalk.yellow("⚠ Invalid config file found")); } } @@ -150,7 +153,7 @@ export async function runNormalFlow( console.log(chalk.blue("✓ Using ANTHROPIC_API_KEY from environment")); await createOrUpdateConfig(process.env.ANTHROPIC_API_KEY); console.log(chalk.gray(` Config saved to: ${CONFIG_PATH}`)); - let result = await initialize(authConfig, CONFIG_PATH); + const result = await initialize(authConfig, CONFIG_PATH); // Inject rules into the config if provided if (rules && rules.length > 0) { result.config = await injectRulesIntoConfig(result.config, rules); @@ -193,7 +196,7 @@ async function injectRulesIntoConfig( return config; } - let processedRules: string[] = []; + const processedRules: string[] = []; for (const ruleSpec of rules) { try { const processedRule = await processRule(ruleSpec); diff --git a/src/permissions/headlessPermissions.integration.test.ts b/src/permissions/headlessPermissions.integration.test.ts index 7b9ec4a14..1fc7fa773 100644 --- a/src/permissions/headlessPermissions.integration.test.ts +++ b/src/permissions/headlessPermissions.integration.test.ts @@ -1,6 +1,6 @@ -import { resolvePermissionPrecedence } from "./precedenceResolver.js"; import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js"; import { checkToolPermission } from "./permissionChecker.js"; +import { resolvePermissionPrecedence } from "./precedenceResolver.js"; describe("Headless Permissions Integration", () => { describe("precedence resolution", () => { diff --git a/src/permissions/permissionChecker.integration.test.ts b/src/permissions/permissionChecker.integration.test.ts index fffe1d822..5ebd5eab4 100644 --- a/src/permissions/permissionChecker.integration.test.ts +++ b/src/permissions/permissionChecker.integration.test.ts @@ -1,5 +1,7 @@ -import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { describe, it, expect, beforeEach } from 'vitest'; + import { ToolPermissionService } from '../services/ToolPermissionService.js'; + import { checkToolPermission } from './permissionChecker.js'; describe('Permission Integration Tests', () => { diff --git a/src/permissions/permissionChecker.ts b/src/permissions/permissionChecker.ts index e277783ea..ad74c91ed 100644 --- a/src/permissions/permissionChecker.ts +++ b/src/permissions/permissionChecker.ts @@ -1,6 +1,7 @@ import { getServiceSync } from "../services/index.js"; import type { ToolPermissionServiceState } from "../services/types.js"; import { SERVICE_NAMES } from "../services/types.js"; + import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js"; import { PermissionCheckResult, diff --git a/src/permissions/permissionManager.ts b/src/permissions/permissionManager.ts index bf7a13b84..4b4c7a3ba 100644 --- a/src/permissions/permissionManager.ts +++ b/src/permissions/permissionManager.ts @@ -1,4 +1,5 @@ import { EventEmitter } from "events"; + import { ToolCallRequest } from "./types.js"; export interface PermissionRequestResult { diff --git a/src/permissions/permissionsYamlLoader.ts b/src/permissions/permissionsYamlLoader.ts index 2f44931d5..aea72fc8a 100644 --- a/src/permissions/permissionsYamlLoader.ts +++ b/src/permissions/permissionsYamlLoader.ts @@ -1,8 +1,11 @@ import * as fs from "fs"; import * as os from "os"; import * as path from "path"; + import * as yaml from "yaml"; -import logger from "../util/logger.js"; + +import { logger } from "../util/logger.js"; + import { normalizeToolName } from "./toolNameMapping.js"; import { PermissionPolicy, ToolPermissionPolicy } from "./types.js"; diff --git a/src/permissions/policyWriter.ts b/src/permissions/policyWriter.ts index 33e8415bc..d21b4a629 100644 --- a/src/permissions/policyWriter.ts +++ b/src/permissions/policyWriter.ts @@ -1,8 +1,11 @@ import * as fs from "fs"; + import * as yaml from "yaml"; + +import { logger } from "../util/logger.js"; + import { PERMISSIONS_YAML_PATH, PermissionsYamlConfig, loadPermissionsYaml } from "./permissionsYamlLoader.js"; import { normalizeToolName, getDisplayName } from "./toolNameMapping.js"; -import logger from "../util/logger.js"; /** * Generates a policy rule for a given tool call @@ -34,7 +37,7 @@ export function generatePolicyRule(toolName: string, toolArgs: any): string { export async function addPolicyToYaml(policyRule: string): Promise { try { // Load existing config or create empty one - let config: PermissionsYamlConfig = loadPermissionsYaml() || {}; + const config: PermissionsYamlConfig = loadPermissionsYaml() || {}; // Ensure allow array exists if (!config.allow) { diff --git a/src/permissions/precedenceResolver.test.ts b/src/permissions/precedenceResolver.test.ts index bd5c3fe22..736f844af 100644 --- a/src/permissions/precedenceResolver.test.ts +++ b/src/permissions/precedenceResolver.test.ts @@ -1,4 +1,3 @@ -import { vi } from "vitest"; import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js"; import { resolvePermissionPrecedence } from "./precedenceResolver.js"; import { ToolPermissionPolicy } from "./types.js"; diff --git a/src/permissions/precedenceResolver.ts b/src/permissions/precedenceResolver.ts index b3a6da6e9..2a4c54d71 100644 --- a/src/permissions/precedenceResolver.ts +++ b/src/permissions/precedenceResolver.ts @@ -1,8 +1,9 @@ +import { logger } from "../util/logger.js"; + import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js"; import { loadPermissionsYaml, yamlConfigToPolicies } from "./permissionsYamlLoader.js"; import { normalizeToolName } from "./toolNameMapping.js"; import { ToolPermissionPolicy } from "./types.js"; -import logger from "../util/logger.js"; export interface PermissionSources { /** Command line flags - highest precedence */ diff --git a/src/permissions/yamlPermissions.test.ts b/src/permissions/yamlPermissions.test.ts index dfbe7e3b0..67af0a898 100644 --- a/src/permissions/yamlPermissions.test.ts +++ b/src/permissions/yamlPermissions.test.ts @@ -1,7 +1,7 @@ import { describe, it, expect, beforeEach, vi } from 'vitest'; -import * as fs from 'fs'; -import { loadPermissionsYaml, yamlConfigToPolicies } from './permissionsYamlLoader.js'; + import { checkToolPermission } from './permissionChecker.js'; +import { yamlConfigToPolicies } from './permissionsYamlLoader.js'; // Mock fs module vi.mock('fs'); diff --git a/src/services/ApiClientService.test.ts b/src/services/ApiClientService.test.ts index 00aeeb89d..9c769ae7a 100644 --- a/src/services/ApiClientService.test.ts +++ b/src/services/ApiClientService.test.ts @@ -1,10 +1,11 @@ import { describe, expect, test, beforeEach, vi } from 'vitest'; -import { ApiClientService } from './ApiClientService.js'; // Mock the config module vi.mock('../config.js'); import * as config from '../config.js'; +import { ApiClientService } from './ApiClientService.js'; + describe('ApiClientService', () => { let service: ApiClientService; const mockApiClient = { diff --git a/src/services/ApiClientService.ts b/src/services/ApiClientService.ts index f4223cceb..f27242232 100644 --- a/src/services/ApiClientService.ts +++ b/src/services/ApiClientService.ts @@ -1,8 +1,9 @@ import { AuthConfig } from "../auth/workos.js"; import { getApiClient } from "../config.js"; -import logger from "../util/logger.js"; -import { ApiClientServiceState } from "./types.js"; +import { logger } from "../util/logger.js"; + import { BaseService, ServiceWithDependencies } from "./BaseService.js"; +import { ApiClientServiceState } from "./types.js"; /** * Service for managing API client state diff --git a/src/services/AuthService.refactored.ts b/src/services/AuthService.refactored.ts index 79ac6192f..da9e77927 100644 --- a/src/services/AuthService.refactored.ts +++ b/src/services/AuthService.refactored.ts @@ -8,9 +8,10 @@ import { loadAuthConfig, saveAuthConfig, } from "../auth/workos.js"; -import logger from "../util/logger.js"; -import { AuthServiceState } from "./types.js"; +import { logger } from "../util/logger.js"; + import { BaseService } from "./BaseService.js"; +import { AuthServiceState } from "./types.js"; /** * Service for managing authentication state and operations diff --git a/src/services/AuthService.test.ts b/src/services/AuthService.test.ts index 6d62273f0..0ee08a098 100644 --- a/src/services/AuthService.test.ts +++ b/src/services/AuthService.test.ts @@ -1,5 +1,4 @@ import { describe, expect, test, beforeEach, vi } from 'vitest'; -import { AuthService } from './AuthService.js'; // Mock the workos module vi.mock('../auth/workos.js'); @@ -15,6 +14,8 @@ import { listUserOrganizations } from '../auth/workos.js'; +import { AuthService } from './AuthService.js'; + describe('AuthService', () => { let service: AuthService; const mockAuthConfig = { diff --git a/src/services/AuthService.ts b/src/services/AuthService.ts index cc0f7a53d..75320fe4a 100644 --- a/src/services/AuthService.ts +++ b/src/services/AuthService.ts @@ -8,9 +8,10 @@ import { loadAuthConfig, saveAuthConfig, } from "../auth/workos.js"; -import logger from "../util/logger.js"; -import { AuthServiceState } from "./types.js"; +import { logger } from "../util/logger.js"; + import { BaseService } from "./BaseService.js"; +import { AuthServiceState } from "./types.js"; /** * Service for managing authentication state and operations diff --git a/src/services/BaseService.test.ts b/src/services/BaseService.test.ts index ad2f11a60..824f731c9 100644 --- a/src/services/BaseService.test.ts +++ b/src/services/BaseService.test.ts @@ -1,4 +1,5 @@ import { describe, expect, test, beforeEach, vi } from 'vitest'; + import { BaseService, hasDependencies, ServiceWithDependencies } from './BaseService.js'; // Test implementation of BaseService diff --git a/src/services/BaseService.ts b/src/services/BaseService.ts index 2604fed98..bfbdb1108 100644 --- a/src/services/BaseService.ts +++ b/src/services/BaseService.ts @@ -1,5 +1,6 @@ import { EventEmitter } from "events"; -import logger from "../util/logger.js"; + +import { logger } from "../util/logger.js"; /** * Base abstract class for all services diff --git a/src/services/ConfigService.test.ts b/src/services/ConfigService.test.ts index f7462c96c..f4c8b8afc 100644 --- a/src/services/ConfigService.test.ts +++ b/src/services/ConfigService.test.ts @@ -1,6 +1,4 @@ import { beforeEach, describe, expect, vi, test } from "vitest"; -import { ConfigService } from "./ConfigService.js"; -import { SERVICE_NAMES } from "./types.js"; // Mock modules vi.mock("../auth/workos.js"); @@ -8,10 +6,13 @@ vi.mock("../configLoader.js"); vi.mock("../args.js"); vi.mock("./ServiceContainer.js"); +import * as args from "../args.js"; import * as workos from "../auth/workos.js"; import * as configLoader from "../configLoader.js"; -import * as args from "../args.js"; + +import { ConfigService } from "./ConfigService.js"; import { serviceContainer } from "./ServiceContainer.js"; +import { SERVICE_NAMES } from "./types.js"; describe("ConfigService", () => { let service: ConfigService; @@ -226,11 +227,7 @@ describe("ConfigService", () => { // Mock service container vi.mocked(workos.loadAuthConfig) .mockReturnValue({ accessToken: "token", organizationId: "org-123" } as any); - vi.mocked(serviceContainer.get).mockResolvedValueOnce({ - authConfig: { accessToken: "token", organizationId: "org-123" } as any, - isAuthenticated: true, - }); - vi.mocked(serviceContainer.get).mockResolvedValueOnce({ + vi.mocked(serviceContainer.get).mockResolvedValue({ apiClient: mockApiClient, }); @@ -269,11 +266,7 @@ describe("ConfigService", () => { vi.mocked(workos.loadAuthConfig) .mockReturnValue({ accessToken: "token", organizationId: "org-123" } as any); - vi.mocked(serviceContainer.get).mockResolvedValueOnce({ - authConfig: { accessToken: "token", organizationId: "org-123" } as any, - isAuthenticated: true, - }); - vi.mocked(serviceContainer.get).mockResolvedValueOnce({ + vi.mocked(serviceContainer.get).mockResolvedValue({ apiClient: null, }); diff --git a/src/services/ConfigService.ts b/src/services/ConfigService.ts index 145795718..6e131633b 100644 --- a/src/services/ConfigService.ts +++ b/src/services/ConfigService.ts @@ -1,19 +1,20 @@ 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 logger from "../util/logger.js"; +import { logger } from "../util/logger.js"; + +import { BaseService, ServiceWithDependencies } from "./BaseService.js"; import { serviceContainer } from "./ServiceContainer.js"; import { ApiClientServiceState, - AuthServiceState, ConfigServiceState, SERVICE_NAMES, } from "./types.js"; -import { BaseService, ServiceWithDependencies } from "./BaseService.js"; /** * Service for managing configuration state and operations @@ -146,7 +147,7 @@ export class ConfigService extends BaseService implements Se return config; } - let processedRules: string[] = []; + const processedRules: string[] = []; for (const ruleSpec of rules) { try { @@ -192,9 +193,6 @@ export class ConfigService extends BaseService implements Se try { // Get current auth and API client state needed for config loading const authConfig = loadAuthConfig(); - const authState = await serviceContainer.get( - SERVICE_NAMES.AUTH - ); const apiClientState = await serviceContainer.get( SERVICE_NAMES.API_CLIENT ); diff --git a/src/services/MCPServiceWrapper.ts b/src/services/MCPServiceWrapper.ts index 8c1e3ac52..8d584c5a1 100644 --- a/src/services/MCPServiceWrapper.ts +++ b/src/services/MCPServiceWrapper.ts @@ -1,6 +1,8 @@ import { AssistantUnrolled } from "@continuedev/config-yaml"; + import { MCPService } from '../mcp.js'; -import logger from '../util/logger.js'; +import { logger } from '../util/logger.js'; + import { MCPServiceState } from './types.js'; /** diff --git a/src/services/ModeService.test.ts b/src/services/ModeService.test.ts index 9aa93fe34..ae634d7c7 100644 --- a/src/services/ModeService.test.ts +++ b/src/services/ModeService.test.ts @@ -1,6 +1,6 @@ -import { beforeEach, afterEach, describe, expect, it, vi, test } from 'vitest'; +import { beforeEach, afterEach, describe, expect, vi, test } from 'vitest'; + import { ModeService } from './ModeService.js'; -import { PermissionMode } from '../permissions/types.js'; describe('ModeService', () => { let modeService: ModeService; diff --git a/src/services/ModeService.ts b/src/services/ModeService.ts index 55a79a25c..fdd09d2bb 100644 --- a/src/services/ModeService.ts +++ b/src/services/ModeService.ts @@ -1,7 +1,8 @@ import { PermissionMode } from "../permissions/types.js"; -import logger from "../util/logger.js"; -import { ToolPermissionService } from "./ToolPermissionService.js"; +import { logger } from "../util/logger.js"; + import { BaseService } from "./BaseService.js"; +import { ToolPermissionService } from "./ToolPermissionService.js"; export interface ModeServiceState { mode: PermissionMode; @@ -70,7 +71,7 @@ export class ModeService extends BaseService { */ public switchMode(mode: PermissionMode): void { const previousMode = this.currentState.mode; - const newState = this.currentState.toolPermissionService.switchMode(mode); + this.currentState.toolPermissionService.switchMode(mode); this.setState({ mode }); diff --git a/src/services/ModelService.refactored.ts b/src/services/ModelService.refactored.ts index 90d6eee05..a2d0d58f4 100644 --- a/src/services/ModelService.refactored.ts +++ b/src/services/ModelService.refactored.ts @@ -1,10 +1,12 @@ import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; -import { BaseLlmApi, constructLlmApi, LLMConfig } from "@continuedev/openai-adapters"; -import { getLlmApi } from '../config.js'; +import { constructLlmApi, LLMConfig } from "@continuedev/openai-adapters"; + import { AuthConfig, getAccessToken, getOrganizationId, getModelName } from '../auth/workos.js'; -import logger from '../util/logger.js'; -import { ModelServiceState } from './types.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 diff --git a/src/services/ModelService.test.ts b/src/services/ModelService.test.ts index 8350902d7..4600079ce 100644 --- a/src/services/ModelService.test.ts +++ b/src/services/ModelService.test.ts @@ -1,16 +1,17 @@ -import { describe, it, expect, beforeEach, vi, test } from 'vitest'; +import { AssistantUnrolled, ModelConfig } from '@continuedev/config-yaml'; +import * as openaiAdapters from '@continuedev/openai-adapters'; +import { describe, expect, beforeEach, vi, test } from 'vitest'; // Mock dependencies before imports vi.mock('@continuedev/openai-adapters'); vi.mock('../config.js'); vi.mock('../auth/workos.js'); -import { ModelService } from './ModelService.js'; -import { AssistantUnrolled, ModelConfig } from '@continuedev/config-yaml'; import { AuthConfig } from '../auth/workos.js'; -import * as config from '../config.js'; import * as workos from '../auth/workos.js'; -import * as openaiAdapters from '@continuedev/openai-adapters'; +import * as config from '../config.js'; + +import { ModelService } from './ModelService.js'; describe('ModelService', () => { let service: ModelService; diff --git a/src/services/ModelService.ts b/src/services/ModelService.ts index f022bd87f..93e854087 100644 --- a/src/services/ModelService.ts +++ b/src/services/ModelService.ts @@ -1,10 +1,12 @@ import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; -import { BaseLlmApi, constructLlmApi, LLMConfig } from "@continuedev/openai-adapters"; -import { getLlmApi } from '../config.js'; +import { constructLlmApi, LLMConfig } from "@continuedev/openai-adapters"; + import { AuthConfig, getAccessToken, getOrganizationId, getModelName } from '../auth/workos.js'; -import logger from '../util/logger.js'; -import { ModelServiceState } from './types.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 diff --git a/src/services/ServiceContainer.test.ts b/src/services/ServiceContainer.test.ts index 26d8067df..4c6cbd22c 100644 --- a/src/services/ServiceContainer.test.ts +++ b/src/services/ServiceContainer.test.ts @@ -1,4 +1,5 @@ import { describe, expect, test, beforeEach, vi } from 'vitest'; + import { ServiceContainer } from './ServiceContainer.js'; describe('ServiceContainer', () => { diff --git a/src/services/ServiceContainer.ts b/src/services/ServiceContainer.ts index 1524568a6..af085cb78 100644 --- a/src/services/ServiceContainer.ts +++ b/src/services/ServiceContainer.ts @@ -1,6 +1,8 @@ import { EventEmitter } from 'events'; -import logger from '../util/logger.js'; -import { ServiceResult, ServiceState, ServiceEvents } from './types.js'; + +import { logger } from '../util/logger.js'; + +import { ServiceResult, ServiceState } from './types.js'; /** * Central service container that manages service lifecycle and dependencies diff --git a/src/services/ServiceContainerContext.tsx b/src/services/ServiceContainerContext.tsx index 9f08e3119..630018309 100644 --- a/src/services/ServiceContainerContext.tsx +++ b/src/services/ServiceContainerContext.tsx @@ -1,5 +1,7 @@ import React, { createContext, useContext } from 'react'; + import { ServiceContainer } from './ServiceContainer.js'; + import { serviceContainer as defaultContainer } from './index.js'; const ServiceContainerContext = createContext(defaultContainer); diff --git a/src/services/ToolPermissionService.debug.test.ts b/src/services/ToolPermissionService.debug.test.ts index 41930bdf9..501a6b5b8 100644 --- a/src/services/ToolPermissionService.debug.test.ts +++ b/src/services/ToolPermissionService.debug.test.ts @@ -1,5 +1,7 @@ import { beforeEach, describe, expect, it } from "vitest"; + import { PermissionMode } from "../permissions/types.js"; + import { ToolPermissionService } from "./ToolPermissionService.js"; describe("ToolPermissionService - Debug Tool Permissions", () => { diff --git a/src/services/ToolPermissionService.integration.test.ts b/src/services/ToolPermissionService.integration.test.ts index bbfdc77f7..863308076 100644 --- a/src/services/ToolPermissionService.integration.test.ts +++ b/src/services/ToolPermissionService.integration.test.ts @@ -1,5 +1,5 @@ -import { vi } from "vitest"; import { DEFAULT_TOOL_POLICIES } from "../permissions/defaultPolicies.js"; + import { ToolPermissionService } from "./ToolPermissionService.js"; describe("ToolPermissionService E2E", () => { diff --git a/src/services/ToolPermissionService.modes.test.ts b/src/services/ToolPermissionService.modes.test.ts index 85f72a183..9a83f758d 100644 --- a/src/services/ToolPermissionService.modes.test.ts +++ b/src/services/ToolPermissionService.modes.test.ts @@ -1,6 +1,6 @@ import { beforeEach, describe, expect, it } from 'vitest'; + import { ToolPermissionService } from './ToolPermissionService.js'; -import { PermissionMode } from '../permissions/types.js'; describe('ToolPermissionService - Mode Functionality', () => { let service: ToolPermissionService; diff --git a/src/services/ToolPermissionService.real.test.ts b/src/services/ToolPermissionService.real.test.ts index 7baa4d248..3901cc08e 100644 --- a/src/services/ToolPermissionService.real.test.ts +++ b/src/services/ToolPermissionService.real.test.ts @@ -1,7 +1,9 @@ import { describe, it, expect, beforeEach } from 'vitest'; -import { ToolPermissionService } from './ToolPermissionService.js'; + import { checkToolPermission } from '../permissions/permissionChecker.js'; +import { ToolPermissionService } from './ToolPermissionService.js'; + describe('ToolPermissionService - Real Tool Permission Test', () => { let service: ToolPermissionService; diff --git a/src/services/ToolPermissionService.test.ts b/src/services/ToolPermissionService.test.ts index 6a0a1310c..722de11bf 100644 --- a/src/services/ToolPermissionService.test.ts +++ b/src/services/ToolPermissionService.test.ts @@ -1,13 +1,13 @@ import { describe, expect, test, beforeEach, vi } from 'vitest'; -import { ToolPermissionService } from "./ToolPermissionService.js"; -import { PermissionMode, ToolPermissionPolicy } from '../permissions/types.js'; // Mock modules vi.mock('../permissions/permissionsYamlLoader.js'); vi.mock('../permissions/precedenceResolver.js'); -import * as permissionsYamlLoader from '../permissions/permissionsYamlLoader.js'; import * as precedenceResolver from '../permissions/precedenceResolver.js'; +import { ToolPermissionPolicy } from '../permissions/types.js'; + +import { ToolPermissionService } from "./ToolPermissionService.js"; describe("ToolPermissionService", () => { let service: ToolPermissionService; diff --git a/src/services/ToolPermissionService.ts b/src/services/ToolPermissionService.ts index b800c93f8..1ec8d29ca 100644 --- a/src/services/ToolPermissionService.ts +++ b/src/services/ToolPermissionService.ts @@ -5,7 +5,8 @@ import { ToolPermissionPolicy, ToolPermissions, } from "../permissions/types.js"; -import logger from "../util/logger.js"; +import { logger } from "../util/logger.js"; + import { BaseService } from "./BaseService.js"; export interface ToolPermissionServiceState { diff --git a/src/services/circular-dependencies.test.ts b/src/services/circular-dependencies.test.ts index 287a5716c..88a489083 100644 --- a/src/services/circular-dependencies.test.ts +++ b/src/services/circular-dependencies.test.ts @@ -1,6 +1,6 @@ import { ServiceContainer } from './ServiceContainer.js'; + import { initializeServices } from './index.js'; -import { SERVICE_NAMES } from './types.js'; describe('Service Circular Dependencies', () => { it('should not have circular dependencies in service setup', async () => { diff --git a/src/services/index.initialization.test.ts b/src/services/index.initialization.test.ts index b5208f8a2..ed77d9b80 100644 --- a/src/services/index.initialization.test.ts +++ b/src/services/index.initialization.test.ts @@ -1,8 +1,10 @@ import { beforeEach, describe, expect, it } from 'vitest'; -import { initializeServices, getServiceSync, SERVICE_NAMES } from './index.js'; + import { serviceContainer } from './ServiceContainer.js'; import type { ToolPermissionServiceState } from './ToolPermissionService.js'; +import { initializeServices, getServiceSync, SERVICE_NAMES } from './index.js'; + describe('Service Initialization', () => { beforeEach(() => { // Clean up service container state diff --git a/src/services/index.test.ts b/src/services/index.test.ts index 895f1adaa..8d14fee3b 100644 --- a/src/services/index.test.ts +++ b/src/services/index.test.ts @@ -1,8 +1,9 @@ import { vi } from "vitest"; -import { initializeServices } from "./index.js"; import { modeService } from "./ModeService.js"; +import { initializeServices } from "./index.js"; + describe("initializeServices", () => { let mockModeService: any; diff --git a/src/services/index.ts b/src/services/index.ts index 9e5542e65..1b6a7fdd7 100644 --- a/src/services/index.ts +++ b/src/services/index.ts @@ -1,10 +1,11 @@ -import logger from "../util/logger.js"; +import { logger } from "../util/logger.js"; + import { ApiClientService } from "./ApiClientService.js"; import { AuthService } from "./AuthService.js"; import { ConfigService } from "./ConfigService.js"; import { MCPServiceWrapper } from "./MCPServiceWrapper.js"; -import { modeService } from "./ModeService.js"; import { ModelService } from "./ModelService.js"; +import { modeService } from "./ModeService.js"; import { serviceContainer } from "./ServiceContainer.js"; import { ApiClientServiceState, @@ -28,7 +29,6 @@ export async function initializeServices(options: ServiceInitOptions = {}) { logger.debug("Initializing service registry"); // Initialize mode service with tool permission overrides - let modeServiceInitialized = false; if (options.toolPermissionOverrides) { const overrides = { ...options.toolPermissionOverrides }; @@ -49,13 +49,11 @@ export async function initializeServices(options: ServiceInitOptions = {}) { // If mode is "normal" or undefined, no flags are set await modeService.initialize(initArgs); - modeServiceInitialized = true; } else { // Even if no overrides, we need to initialize with defaults await modeService.initialize({ isHeadless: options.headless }); - modeServiceInitialized = true; } // Register the TOOL_PERMISSIONS service with immediate value diff --git a/src/services/types.ts b/src/services/types.ts index 52ed50e35..fe85edfef 100644 --- a/src/services/types.ts +++ b/src/services/types.ts @@ -1,6 +1,7 @@ import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; import { BaseLlmApi } from "@continuedev/openai-adapters"; import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js"; + import { AuthConfig } from "../auth/workos.js"; import { MCPService } from "../mcp.js"; import { PermissionMode, ToolPermissions } from "../permissions/types.js"; diff --git a/src/session.ts b/src/session.ts index b78f1d904..4a2e92010 100644 --- a/src/session.ts +++ b/src/session.ts @@ -1,9 +1,11 @@ import { execSync } from "child_process"; import fs from "fs"; -import { ChatCompletionMessageParam } from "openai/resources.mjs"; import os from "os"; import path from "path"; -import logger from "./util/logger.js"; + +import { ChatCompletionMessageParam } from "openai/resources.mjs"; + +import { logger } from "./util/logger.js"; /** * Get the terminal process ID by walking up the process tree @@ -54,12 +56,12 @@ function getTerminalProcessId(): string | null { const nextPid = parseInt(ppid); if (isNaN(nextPid) || nextPid <= 1) break; currentPid = nextPid; - } catch (innerError) { + } catch { // Continue to next iteration if this process lookup fails break; } } - } catch (error) { + } catch { // Silently fail - this is a fallback mechanism } @@ -93,7 +95,7 @@ function getTtyPath(): string | null { return ttyPath.replace("/dev/", ""); } } - } catch (error) { + } catch { // Silently fail - this is a fallback mechanism } diff --git a/src/slashCommands.test.ts b/src/slashCommands.test.ts index da74dafae..9318dfb9e 100644 --- a/src/slashCommands.test.ts +++ b/src/slashCommands.test.ts @@ -1,3 +1,6 @@ + +// Import after mocking +import { AssistantUnrolled } from "@continuedev/config-yaml"; import { afterEach, beforeEach, @@ -6,13 +9,11 @@ import { vi, test, } from "vitest"; -import type { AuthServiceState } from "./services/types.js"; -// Import after mocking -import { AssistantUnrolled } from "@continuedev/config-yaml"; 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 { handleSlashCommands } from "./slashCommands.js"; // The imports are already mocked via vitest.setup.ts, so we can use them directly diff --git a/src/slashCommands.ts b/src/slashCommands.ts index d64e65bbe..3a508b837 100644 --- a/src/slashCommands.ts +++ b/src/slashCommands.ts @@ -1,5 +1,6 @@ import { type AssistantConfig } from "@continuedev/sdk"; import chalk from "chalk"; + import { isAuthenticated, isAuthenticatedConfig, @@ -11,8 +12,7 @@ import { posthogService } from "./telemetry/posthogService.js"; export async function handleSlashCommands( input: string, - assistant: AssistantConfig, - onLoginPrompt?: (promptText: string) => Promise + assistant: AssistantConfig ): Promise<{ output?: string; exit?: boolean; @@ -95,7 +95,7 @@ export async function handleSlashCommands( exit: true, output: "Logged out successfully", }; - } catch (error: any) { + } catch { return { exit: true, output: "Logged out successfully", diff --git a/src/streamChatResponse.getAllTools.test.ts b/src/streamChatResponse.getAllTools.test.ts index 7cb3fc1d6..ce861f550 100644 --- a/src/streamChatResponse.getAllTools.test.ts +++ b/src/streamChatResponse.getAllTools.test.ts @@ -1,8 +1,9 @@ import { describe, test, expect, beforeEach } from 'vitest'; + import { initializeServices, getServiceSync, SERVICE_NAMES } from './services/index.js'; import { serviceContainer } from './services/ServiceContainer.js'; -import { getAllTools } from './streamChatResponse.js'; import type { ToolPermissionServiceState } from './services/ToolPermissionService.js'; +import { getAllTools } from './streamChatResponse.js'; describe('getAllTools - Tool Filtering', () => { beforeEach(() => { diff --git a/src/streamChatResponse.test.ts b/src/streamChatResponse.test.ts index 32d05cce3..8fb522dd9 100644 --- a/src/streamChatResponse.test.ts +++ b/src/streamChatResponse.test.ts @@ -1,22 +1,23 @@ -import { vi } from 'vitest'; - +import { ModelConfig } from "@continuedev/config-yaml"; +import { BaseLlmApi } from "@continuedev/openai-adapters"; import type { ChatCompletionChunk, ChatCompletionMessageParam, } from "openai/resources/chat/completions.mjs"; +import { vi } from 'vitest'; + +import { toolPermissionManager } from "./permissions/permissionManager.js"; import { preprocessStreamedToolCalls, executeStreamedToolCalls, processStreamingResponse, } from "./streamChatResponse.js"; import { ToolCall } from "./tools/index.js"; -import { PreprocessedToolCall } from "./tools/types.js"; -import { toolPermissionManager } from "./permissions/permissionManager.js"; import { readFileTool } from "./tools/readFile.js"; import { searchCodeTool } from "./tools/searchCode.js"; +import { PreprocessedToolCall } from "./tools/types.js"; import { writeFileTool } from "./tools/writeFile.js"; -import { BaseLlmApi } from "@continuedev/openai-adapters"; -import { ModelConfig } from "@continuedev/config-yaml"; + // Test the chunk processing logic that was identified as buggy describe("processStreamingResponse - content preservation", () => { diff --git a/src/streamChatResponse.ts b/src/streamChatResponse.ts index 6a9f42ad9..50b1b8336 100644 --- a/src/streamChatResponse.ts +++ b/src/streamChatResponse.ts @@ -8,8 +8,7 @@ import type { ChatCompletionTool, ChatCompletionToolMessageParam, } from "openai/resources.mjs"; -import { getServiceSync, SERVICE_NAMES } from "./services/index.js"; -import type { ToolPermissionServiceState } from "./services/ToolPermissionService.js"; + import { MCPService } from "./mcp.js"; import { checkToolPermission, @@ -17,23 +16,24 @@ import { ToolCallRequest, } from "./permissions/index.js"; import { toolPermissionManager } from "./permissions/permissionManager.js"; -import telemetryService from "./telemetry/telemetryService.js"; +import { getServiceSync, SERVICE_NAMES } from "./services/index.js"; +import type { ToolPermissionServiceState } from "./services/ToolPermissionService.js"; +import { telemetryService } from "./telemetry/telemetryService.js"; import { calculateTokenCost } from "./telemetry/utils.js"; import { getAllBuiltinTools, executeToolCall, getAvailableTools, - getToolDisplayName, Tool, ToolCall, validateToolCallArgsPresent, } from "./tools/index.js"; +import { PreprocessedToolCall, ToolCallPreview } from "./tools/types.js"; import { chatCompletionStreamWithBackoff, withExponentialBackoff, } from "./util/exponentialBackoff.js"; -import logger from "./util/logger.js"; -import { PreprocessedToolCall, ToolCallPreview } from "./tools/types.js"; +import { logger } from "./util/logger.js"; dotenv.config(); @@ -300,7 +300,7 @@ export async function processStreamingResponse( // Don't notify onToolStart here anymore - wait until after permission check toolCall.startNotified = true; - } catch (e) { + } catch { // JSON not complete yet, continue } } diff --git a/src/systemMessage.ts b/src/systemMessage.ts index f4e006f2f..2a032ec15 100644 --- a/src/systemMessage.ts +++ b/src/systemMessage.ts @@ -1,8 +1,10 @@ import { execSync } from "child_process"; import * as fs from "fs"; +import * as path from "path"; + import pkg from "ignore-walk"; import { Minimatch } from "minimatch"; -import * as path from "path"; + import { processRule } from "./args.js"; const { WalkerSync } = pkg; @@ -126,7 +128,7 @@ export async function constructSystemMessage( } // Process additional rules from --rule flags - let processedRules: string[] = []; + const processedRules: string[] = []; if (additionalRules && additionalRules.length > 0) { for (const ruleSpec of additionalRules) { try { diff --git a/src/telemetry/telemetryService.ts b/src/telemetry/telemetryService.ts index b9f77aa6e..c3e5a6929 100644 --- a/src/telemetry/telemetryService.ts +++ b/src/telemetry/telemetryService.ts @@ -1,3 +1,5 @@ +import os from "os"; + import { metrics } from "@opentelemetry/api"; import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-http"; import { resourceFromAttributes } from "@opentelemetry/resources"; @@ -13,9 +15,9 @@ import { SEMRESATTRS_SERVICE_NAME, SEMRESATTRS_SERVICE_VERSION, } from "@opentelemetry/semantic-conventions"; -import os from "os"; import { v4 as uuidv4 } from "uuid"; -import logger from "../util/logger.js"; + +import { logger } from "../util/logger.js"; import { getVersion } from "../version.js"; export interface TelemetryConfig { @@ -545,4 +547,3 @@ class TelemetryService { // Export the singleton instance directly export const telemetryService = new TelemetryService(); -export default telemetryService; diff --git a/src/telemetry/utils.ts b/src/telemetry/utils.ts index 132ce9b6c..43aaa92c7 100644 --- a/src/telemetry/utils.ts +++ b/src/telemetry/utils.ts @@ -1,6 +1,7 @@ -import { diffLines } from "diff"; import path from "path"; +import { diffLines } from "diff"; + /** * Calculate lines of code added/removed from a file diff */ diff --git a/src/test-helpers/__tests__/testServiceContainer.test.ts b/src/test-helpers/__tests__/testServiceContainer.test.ts index c97a531b1..b341d0008 100644 --- a/src/test-helpers/__tests__/testServiceContainer.test.ts +++ b/src/test-helpers/__tests__/testServiceContainer.test.ts @@ -1,4 +1,5 @@ import { vi } from "vitest"; + import { createTestServiceContainer } from '../testServiceContainer.js'; describe('TestServiceContainer', () => { diff --git a/src/test-helpers/adapter-mocks.ts b/src/test-helpers/adapter-mocks.ts index 1dd6e4510..0213cb7c8 100644 --- a/src/test-helpers/adapter-mocks.ts +++ b/src/test-helpers/adapter-mocks.ts @@ -1,5 +1,8 @@ import { vi } from "vitest"; +// Mock BaseLlmApi class to avoid inline class definitions +class MockBaseLlmApi {} + /** * Mock the constructLlmApi function to return a mock LLM API */ @@ -38,7 +41,7 @@ export function mockLLMResponse(response: string) { vi.doMock("@continuedev/openai-adapters", () => ({ constructLlmApi: () => mockApi, - BaseLlmApi: class {}, + BaseLlmApi: MockBaseLlmApi, LLMConfig: {} })); @@ -82,7 +85,7 @@ export function mockLLMStreamResponse(chunks: string[]) { vi.doMock("@continuedev/openai-adapters", () => ({ constructLlmApi: () => mockApi, - BaseLlmApi: class {}, + BaseLlmApi: MockBaseLlmApi, LLMConfig: {} })); @@ -113,7 +116,7 @@ export function mockLLMError(errorMessage: string) { vi.doMock("@continuedev/openai-adapters", () => ({ constructLlmApi: () => mockApi, - BaseLlmApi: class {}, + BaseLlmApi: MockBaseLlmApi, LLMConfig: {} })); diff --git a/src/test-helpers/cli-helpers.ts b/src/test-helpers/cli-helpers.ts index 78ab07329..341af220a 100644 --- a/src/test-helpers/cli-helpers.ts +++ b/src/test-helpers/cli-helpers.ts @@ -1,8 +1,9 @@ -import { execaNode, type Subprocess } from "execa"; import fs from "fs/promises"; import os from "os"; import path from "path"; +import { execaNode, type Subprocess } from "execa"; + export interface CLITestContext { cliPath: string; testDir: string; @@ -35,7 +36,7 @@ export async function createTestContext(): Promise { // Ensure the CLI file exists before returning the context try { await fs.access(cliPath); - } catch (error) { + } catch { throw new Error(`CLI file not found at ${cliPath}. Please run 'npm run build' first.`); } @@ -53,7 +54,7 @@ export async function cleanupTestContext( ): Promise { try { await fs.rm(context.testDir, { recursive: true, force: true }); - } catch (error) { + } catch { // Ignore cleanup errors } } @@ -165,7 +166,7 @@ export async function readSession( const content = await fs.readFile(sessionPath, "utf-8"); return JSON.parse(content); - } catch (error) { + } catch { return null; } } diff --git a/src/test-helpers/mock-helpers.ts b/src/test-helpers/mock-helpers.ts index 220516c4c..91f09b5f3 100644 --- a/src/test-helpers/mock-helpers.ts +++ b/src/test-helpers/mock-helpers.ts @@ -64,7 +64,7 @@ export function mockOpenAIStream( return scope.reply(500, { error: { message: "Internal server error" } }); } - return scope.reply(200, (uri, requestBody) => { + return scope.reply(200, () => { // Return a stream of Server-Sent Events const events = chunks.map((chunk, index) => { const data = { diff --git a/src/test-helpers/mock-llm-server.ts b/src/test-helpers/mock-llm-server.ts index 7bc954d00..292416338 100644 --- a/src/test-helpers/mock-llm-server.ts +++ b/src/test-helpers/mock-llm-server.ts @@ -1,6 +1,7 @@ import * as fs from "fs/promises"; import * as http from "http"; import * as path from "path"; + import { CLITestContext } from "./cli-helpers.js"; export interface MockLLMServerOptions { @@ -78,7 +79,7 @@ export async function createMockLLMServer( ? (() => { try { return JSON.parse(body); - } catch (e) { + } catch { return body; } })() diff --git a/src/test-helpers/renderWithServices.tsx b/src/test-helpers/renderWithServices.tsx index d6339c20e..64e4b46ac 100644 --- a/src/test-helpers/renderWithServices.tsx +++ b/src/test-helpers/renderWithServices.tsx @@ -1,6 +1,8 @@ import { render } from 'ink-testing-library'; import React from 'react'; + import { ServiceContainerProvider } from '../services/ServiceContainerContext.js'; + import { createTestServiceContainer, TestServiceContainer } from './testServiceContainer.js'; export interface RenderWithServicesOptions { diff --git a/src/test-helpers/testServiceContainer.ts b/src/test-helpers/testServiceContainer.ts index 3a807a0f2..5e8913eb9 100644 --- a/src/test-helpers/testServiceContainer.ts +++ b/src/test-helpers/testServiceContainer.ts @@ -17,7 +17,6 @@ export function createTestServiceContainer(): TestServiceContainer { }>(); // Override load instead of register to have more control - const originalLoad = container.load.bind(container); container.load = async function(serviceName: string) { // Check if we already have a resolver for this service const existing = serviceResolvers.get(serviceName); diff --git a/src/tools/exit.ts b/src/tools/exit.ts index 840314412..ebed5ecde 100644 --- a/src/tools/exit.ts +++ b/src/tools/exit.ts @@ -8,7 +8,7 @@ export const exitTool: Tool = { parameters: {}, readonly: false, isBuiltIn: true, - run: async (args: { dirpath: string }): Promise => { + run: async (): Promise => { process.exit(1); }, }; diff --git a/src/tools/fetch.ts b/src/tools/fetch.ts index 110080b0f..d2ca53bdd 100644 --- a/src/tools/fetch.ts +++ b/src/tools/fetch.ts @@ -1,4 +1,5 @@ import TurndownService from "turndown"; + import { Tool } from "./types.js"; const turndownService = new TurndownService({ diff --git a/src/tools/formatters.test.ts b/src/tools/formatters.test.ts index 2542f3fd4..2dd0d8a35 100644 --- a/src/tools/formatters.test.ts +++ b/src/tools/formatters.test.ts @@ -1,5 +1,7 @@ import { vi } from "vitest"; + import { formatToolArgument } from "./formatters.js"; + import { formatToolCall } from "./index.js"; describe("formatToolCall", () => { diff --git a/src/tools/index.ts b/src/tools/index.ts index 6e09a248f..17141a360 100644 --- a/src/tools/index.ts +++ b/src/tools/index.ts @@ -1,8 +1,9 @@ +import { MCPService } from "../mcp.js"; import { getServiceSync, SERVICE_NAMES } from "../services/index.js"; import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js"; -import { MCPService } from "../mcp.js"; -import telemetryService from "../telemetry/telemetryService.js"; -import logger from "../util/logger.js"; +import { telemetryService } from "../telemetry/telemetryService.js"; +import { logger } from "../util/logger.js"; + import { exitTool } from "./exit.js"; import { fetchTool } from "./fetch.js"; import { formatToolArgument } from "./formatters.js"; @@ -51,7 +52,7 @@ function getDynamicTools(): Tool[] { if (isHeadless) { dynamicTools.push(exitTool); } - } catch (error) { + } catch { // Service not ready yet, no dynamic tools } @@ -86,7 +87,7 @@ export function extractToolCalls( arguments: toolCallJson.arguments, }); } - } catch (e) { + } catch { logger.error("Failed to parse tool call:", { toolCall: match[1] }); } } diff --git a/src/tools/listFiles.ts b/src/tools/listFiles.ts index d302725df..181d4a9f1 100644 --- a/src/tools/listFiles.ts +++ b/src/tools/listFiles.ts @@ -1,7 +1,8 @@ import * as fs from "fs"; import * as path from "path"; -import { Tool } from "./types.js"; + import { formatToolArgument } from "./formatters.js"; +import { Tool } from "./types.js"; // List files in a directory export const listFilesTool: Tool = { diff --git a/src/tools/preprocess.test.ts b/src/tools/preprocess.test.ts index 9b4b7c3f1..e032a5e77 100644 --- a/src/tools/preprocess.test.ts +++ b/src/tools/preprocess.test.ts @@ -1,4 +1,7 @@ -import { vi } from 'vitest'; +import * as fs from "fs"; + +import * as diff from "diff"; +import { describe, it, expect, beforeEach, vi } from 'vitest'; // Mock fs module vi.mock("fs", async () => { @@ -18,10 +21,6 @@ vi.mock("diff", () => ({ createTwoFilesPatch: vi.fn(), })); -// Import mocked modules -import * as fs from "fs"; -import * as diff from "diff"; - // Get mocked functions using vi.mocked const mockExistsSync = vi.mocked(fs.existsSync); const mockReadFileSync = vi.mocked(fs.readFileSync); diff --git a/src/tools/readFile.ts b/src/tools/readFile.ts index 21f3ba1d9..3600b5966 100644 --- a/src/tools/readFile.ts +++ b/src/tools/readFile.ts @@ -1,6 +1,7 @@ import * as fs from "fs"; -import { Tool } from "./types.js"; + import { formatToolArgument } from "./formatters.js"; +import { Tool } from "./types.js"; export const readFileTool: Tool = { name: "Read", diff --git a/src/tools/runTerminalCommand.ts b/src/tools/runTerminalCommand.ts index f9c730ac7..3c32f13e5 100644 --- a/src/tools/runTerminalCommand.ts +++ b/src/tools/runTerminalCommand.ts @@ -1,9 +1,11 @@ import { spawn } from "child_process"; -import telemetryService from "../telemetry/telemetryService.js"; + +import { telemetryService } from "../telemetry/telemetryService.js"; import { isGitCommitCommand, isPullRequestCommand, } from "../telemetry/utils.js"; + import { Tool } from "./types.js"; export const runTerminalCommandTool: Tool = { @@ -41,7 +43,6 @@ export const runTerminalCommandTool: Tool = { const child = spawn("sh", ["-c", command]); let stdout = ""; let stderr = ""; - let lastOutputTime = Date.now(); let timeoutId: NodeJS.Timeout; let isResolved = false; @@ -69,13 +70,11 @@ export const runTerminalCommandTool: Tool = { child.stdout.on("data", (data) => { stdout += data.toString(); - lastOutputTime = Date.now(); resetTimeout(); }); child.stderr.on("data", (data) => { stderr += data.toString(); - lastOutputTime = Date.now(); resetTimeout(); }); diff --git a/src/tools/searchAndReplace/index.ts b/src/tools/searchAndReplace/index.ts index e4f2369f9..86e27552b 100644 --- a/src/tools/searchAndReplace/index.ts +++ b/src/tools/searchAndReplace/index.ts @@ -1,14 +1,16 @@ -import { findSearchMatch } from "./findSearchMatch.js"; -import { parseAllSearchReplaceBlocks } from "./parseBlock.js"; -import { Tool } from "../types.js"; -import { generateDiff } from "../writeFile.js"; import * as fs from "fs"; -import telemetryService from "../../telemetry/telemetryService.js"; + +import { telemetryService } from "../../telemetry/telemetryService.js"; import { calculateLinesOfCodeDiff, getLanguageFromFilePath, } from "../../telemetry/utils.js"; +import { Tool } from "../types.js"; +import { generateDiff } from "../writeFile.js"; + +import { findSearchMatch } from "./findSearchMatch.js"; import { parseSearchAndReplaceArgs } from "./parseArgs.js"; +import { parseAllSearchReplaceBlocks } from "./parseBlock.js"; export interface SearchAndReplaceInFileArgs { filepath: string; diff --git a/src/tools/searchCode.test.ts b/src/tools/searchCode.test.ts index 96e786598..ffaab5fca 100644 --- a/src/tools/searchCode.test.ts +++ b/src/tools/searchCode.test.ts @@ -1,4 +1,3 @@ -import { searchCodeTool } from "./searchCode.js"; // Since we want to test just the interface and not the internals, // let's create a simplified version of the run function to test the truncation logic diff --git a/src/tools/searchCode.ts b/src/tools/searchCode.ts index 776aa0fc2..cf5b5a4a7 100644 --- a/src/tools/searchCode.ts +++ b/src/tools/searchCode.ts @@ -1,6 +1,7 @@ import * as child_process from "child_process"; import * as fs from "fs"; import * as util from "util"; + import { Tool } from "./types.js"; const execPromise = util.promisify(child_process.exec); diff --git a/src/tools/viewDiff.ts b/src/tools/viewDiff.ts index 60e832954..f8c9d2ff3 100644 --- a/src/tools/viewDiff.ts +++ b/src/tools/viewDiff.ts @@ -1,6 +1,7 @@ import * as child_process from "child_process"; import * as fs from "fs"; import * as util from "util"; + import { Tool } from "./types.js"; const execPromise = util.promisify(child_process.exec); @@ -41,7 +42,7 @@ export const viewDiffTool: Tool = { await execPromise("git rev-parse --is-inside-work-tree", { cwd: repoPath, }); - } catch (error) { + } catch { return `Error: The specified path is not a git repository: ${repoPath}`; } diff --git a/src/tools/writeFile.ts b/src/tools/writeFile.ts index 8d577f1ee..9a3b3a770 100644 --- a/src/tools/writeFile.ts +++ b/src/tools/writeFile.ts @@ -1,11 +1,14 @@ -import { createTwoFilesPatch } from "diff"; import * as fs from "fs"; import * as path from "path"; -import telemetryService from "../telemetry/telemetryService.js"; + +import { createTwoFilesPatch } from "diff"; + +import { telemetryService } from "../telemetry/telemetryService.js"; import { calculateLinesOfCodeDiff, getLanguageFromFilePath, } from "../telemetry/utils.js"; + import { Tool, ToolCallPreview } from "./types.js"; export function generateDiff( @@ -72,7 +75,7 @@ export const writeFileTool: Tool = { ], }; } - } catch (e) { + } catch { // do nothing } const lines: string[] = args.content.split("\n"); diff --git a/src/ui/ColoredDiff.test.ts b/src/ui/ColoredDiff.test.ts index e967d496b..706fab0b8 100644 --- a/src/ui/ColoredDiff.test.ts +++ b/src/ui/ColoredDiff.test.ts @@ -1,5 +1,6 @@ import { render } from "ink-testing-library"; import React from "react"; + import { ColoredDiff } from "./ColoredDiff.js"; describe("ColoredDiff", () => { diff --git a/src/ui/ConfigSelector.tsx b/src/ui/ConfigSelector.tsx index b0a228812..12ee768b0 100644 --- a/src/ui/ConfigSelector.tsx +++ b/src/ui/ConfigSelector.tsx @@ -1,7 +1,9 @@ import * as fs from "fs"; import * as os from "os"; import * as path from "path"; + import React, { useEffect, useState } from "react"; + import { getAccessToken, getOrganizationId, @@ -9,7 +11,8 @@ import { getAssistantSlug, } from "../auth/workos.js"; import { getApiClient } from "../config.js"; -import Selector, { SelectorOption } from "./Selector.js"; + +import { Selector, SelectorOption } from "./Selector.js"; interface ConfigOption extends SelectorOption { type: "local" | "assistant" | "create"; @@ -124,4 +127,4 @@ const ConfigSelector: React.FC = ({ ); }; -export default ConfigSelector; +export { ConfigSelector }; diff --git a/src/ui/FileSearchUI.tsx b/src/ui/FileSearchUI.tsx index 1d7205cc1..0fb65c15d 100644 --- a/src/ui/FileSearchUI.tsx +++ b/src/ui/FileSearchUI.tsx @@ -1,6 +1,7 @@ -import { Box, Text } from "ink"; -import React, { useEffect, useState, useRef } from "react"; import { glob, GlobOptionsWithFileTypesFalse } from "glob"; +import { Box, Text } from "ink"; +import React, { useEffect, useState } from "react"; + import { isGitRepo } from "../util/git.js"; interface FileSearchUIProps { @@ -192,7 +193,6 @@ const filterFiles = (filterText: string): FileItem[] => { const FileSearchUI: React.FC = ({ filter, selectedIndex, - onSelect, onFilesUpdated, }) => { const [files, setFiles] = useState([]); @@ -257,7 +257,7 @@ const FileSearchUI: React.FC = ({ ); }; -export default FileSearchUI; +export { FileSearchUI }; export async function throttledGlob( patterns: string[], diff --git a/src/ui/FreeTrialStatus.tsx b/src/ui/FreeTrialStatus.tsx index 47a7a9c1a..ecd1e42e4 100644 --- a/src/ui/FreeTrialStatus.tsx +++ b/src/ui/FreeTrialStatus.tsx @@ -40,7 +40,7 @@ const FreeTrialStatus: React.FC = ({ const response = await apiClient.getFreeTrialStatus(); setStatus(response); setLoading(false); - } catch (error) { + } catch { // Silently handle errors - component returns null if no status setStatus(null); setLoading(false); @@ -105,4 +105,4 @@ const FreeTrialStatus: React.FC = ({ ); }; -export default FreeTrialStatus; +export { FreeTrialStatus }; diff --git a/src/ui/FreeTrialTransitionUI.tsx b/src/ui/FreeTrialTransitionUI.tsx index 4d4e7e15c..fc52cf034 100644 --- a/src/ui/FreeTrialTransitionUI.tsx +++ b/src/ui/FreeTrialTransitionUI.tsx @@ -1,12 +1,14 @@ import * as fs from "fs"; -import { Box, Text, useInput } from "ink"; -import open from "open"; import * as os from "os"; import * as path from "path"; + +import { Box, Text, useInput } from "ink"; +import open from "open"; import React, { useState } from "react"; -import { updateAnthropicModelInYaml } from "../util/yamlConfigUpdater.js"; -import { isValidAnthropicApiKey, getApiKeyValidationError } from "../util/apiKeyValidation.js"; + import { env } from "../env.js"; +import { isValidAnthropicApiKey, getApiKeyValidationError } from "../util/apiKeyValidation.js"; +import { updateAnthropicModelInYaml } from "../util/yamlConfigUpdater.js"; const CONFIG_PATH = path.join(os.homedir(), ".continue", "config.yaml"); @@ -104,7 +106,7 @@ const FreeTrialTransitionUI: React.FC = ({ `Browser opened to ${modelsUrl}. After setting up your models subscription, press Enter to continue.` ); setCurrentStep("success"); - } catch (error) { + } catch { setErrorMessage( `Could not open browser automatically. Please visit: ${modelsUrl}. After setting up your models subscription, press Enter to continue.` ); @@ -266,4 +268,4 @@ const FreeTrialTransitionUI: React.FC = ({ return null; }; -export default FreeTrialTransitionUI; +export { FreeTrialTransitionUI }; diff --git a/src/ui/IntroMessage.tsx b/src/ui/IntroMessage.tsx index f324e6743..cbf5f378a 100644 --- a/src/ui/IntroMessage.tsx +++ b/src/ui/IntroMessage.tsx @@ -1,11 +1,13 @@ import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; import { Box, Text } from "ink"; import React from "react"; + import { parseArgs } from "../args.js"; import { getAllSlashCommands } from "../commands/commands.js"; import { MCPService } from "../mcp.js"; import { isModelCapable } from "../utils/modelCapability.js"; -import ModelCapabilityWarning from "./ModelCapabilityWarning.js"; + +import { ModelCapabilityWarning } from "./ModelCapabilityWarning.js"; interface IntroMessageProps { config: AssistantUnrolled; @@ -18,7 +20,6 @@ const IntroMessage: React.FC = ({ model, mcpService, }) => { - const mcpTools = mcpService.getTools() ?? []; const mcpPrompts = mcpService.getPrompts() ?? []; // Get all slash commands from central definition @@ -107,4 +108,4 @@ const IntroMessage: React.FC = ({ ); }; -export default IntroMessage; \ No newline at end of file +export { IntroMessage }; \ No newline at end of file diff --git a/src/ui/LoadingAnimation.tsx b/src/ui/LoadingAnimation.tsx index 4debfe1a3..8954c7d64 100644 --- a/src/ui/LoadingAnimation.tsx +++ b/src/ui/LoadingAnimation.tsx @@ -1,77 +1,7 @@ import { Text } from "ink"; import React, { useEffect, useState } from "react"; -const SPINNER_BARS = "▁▂▃▄▅▆▇█▇▆▅▄▃▁"; -const SPINNER_BLOCKS = "▉▊▋▌▍▎▏▎▍▌▋▊▉"; -const SPINNER_CORNERS = "▖▘▝▗"; -const SPINNER_CLASSIC = "-/|\\-/|"; -const SPINNER_BOX = "┤┘┴└├┌┬┐"; -const SPINNER_DOUBLE_BARS = [ - "▁▁", - "▁▂", - "▁▃", - "▁▄", - "▁▅", - "▁▆", - "▁▇", - "▁█", - "▂▇", - "▃▆", - "▄▅", - "▅▄", - "▆▃", - "▇▂", - "█▁", - "▇▁", - "▆▁", - "▅▁", - "▄▁", - "▃▁", - "▂▁", -]; -const SPINNER_SHADES = "░▒▓█▓▒░"; -const SPINNER_RINGS = "○◔◑◕●◐◓◑◒"; -const SPINNER_SPARKLES = "✢✣✤✥✦✧✬✱✲✳✴✵✶✷✸"; -const SPINNER_PULSE = "·∙●⬤●∙·"; -const MITOSIS_FRAMES = [ - "●", - "●●", - "● ●", // regular space - "●\u2004●", // 1/3 em space - "●\u2002●", // 1/2 em space - "● ●", // regular space - "●●", - "●", -]; -const DANCING_NOTES_FRAMES = [ - "♪ ", - "♫ ", - "♪ ♫ ", - "♫ ♪ ", - "♬ ♩ ", - "♩ ♬ ", - "♫ ♪ ", - "♪ ♫ ", - "♫ ", - "♪ ", -]; -const MITOSIS_2 = [ - "⚬ ", - "⚭ ", - "⚮ ", - "⚯ ", - "○ ○", - "⚯ ", - "⚮ ", - "⚭ ", - "⚬ ", -]; - -// Generate all possible Braille characters (from U+2800 to U+28FF) -const BRAILLE_CHARS = Array.from({ length: 256 }, (_, i) => - String.fromCharCode(0x2800 + i) -); const BRAILLE_BY_DENSITY: { [key: number]: string[] } = { 0: ["⠀"], // No dots @@ -136,10 +66,6 @@ const STATIC_FADE = [ ...generateEasedStaticFade(TIMING_CURVE), ]; -// Linear (same speed throughout) -const STATIC_FADE_LINEAR = generateEasedStaticFade([2, 2, 2, 2, 2, 2, 2, 2, 2]); - -const STARS = "·+✣✤✻✽❊❈❈❈❈❊✽✻✤✣+"; const SPINNER: string | string[] = STATIC_FADE; @@ -171,4 +97,4 @@ const LoadingAnimation: React.FC = ({ return {animationChars[currentIndex]}; }; -export default LoadingAnimation; +export { LoadingAnimation }; diff --git a/src/ui/MarkdownRenderer.test.tsx b/src/ui/MarkdownRenderer.test.tsx index d9cd7abc3..913d6d169 100644 --- a/src/ui/MarkdownRenderer.test.tsx +++ b/src/ui/MarkdownRenderer.test.tsx @@ -1,6 +1,7 @@ import { Text } from "ink"; import React from "react"; -import MarkdownRenderer from "./MarkdownRenderer.js"; + +import { MarkdownRenderer } from "./MarkdownRenderer.js"; describe("MarkdownRenderer", () => { // Helper function to simulate calling the component function directly diff --git a/src/ui/MarkdownRenderer.tsx b/src/ui/MarkdownRenderer.tsx index f85d9dae3..008009876 100644 --- a/src/ui/MarkdownRenderer.tsx +++ b/src/ui/MarkdownRenderer.tsx @@ -1,5 +1,6 @@ import { Text } from "ink"; import React from "react"; + import { highlightCode, detectLanguage, SyntaxHighlighterTheme, defaultTheme } from "./SyntaxHighlighter.js"; interface MarkdownRendererProps { @@ -16,7 +17,7 @@ const MarkdownRenderer: React.FC = React.memo(({ content, const patterns: MarkdownPattern[] = [ { regex: /```(?:(\w+)\n)?([\s\S]*?)```/g, - render: (content, key) => { + render: (_content, _key) => { // content here is the captured group, but we need to parse the full match return null; // This will be handled separately }, @@ -160,7 +161,7 @@ const MarkdownRenderer: React.FC = React.memo(({ content, combinedMatches.sort((a, b) => a.index - b.index); // Process matches, avoiding overlaps - let processedMatches: typeof combinedMatches = []; + const processedMatches: typeof combinedMatches = []; for (const match of combinedMatches) { const overlaps = processedMatches.some( (processed) => @@ -210,6 +211,6 @@ const MarkdownRenderer: React.FC = React.memo(({ content, MarkdownRenderer.displayName = "MarkdownRenderer"; -export default MarkdownRenderer; +export { MarkdownRenderer }; export type { SyntaxHighlighterTheme }; export { defaultTheme }; \ No newline at end of file diff --git a/src/ui/ModelCapabilityWarning.test.tsx b/src/ui/ModelCapabilityWarning.test.tsx index 46b744493..cc22d0cb7 100644 --- a/src/ui/ModelCapabilityWarning.test.tsx +++ b/src/ui/ModelCapabilityWarning.test.tsx @@ -1,7 +1,8 @@ import { render } from 'ink-testing-library'; import React from 'react'; import { describe, expect, test } from 'vitest'; -import ModelCapabilityWarning from './ModelCapabilityWarning.js'; + +import { ModelCapabilityWarning } from './ModelCapabilityWarning.js'; describe('ModelCapabilityWarning', () => { test('should render warning message with model name', () => { diff --git a/src/ui/ModelCapabilityWarning.tsx b/src/ui/ModelCapabilityWarning.tsx index 87737abe7..e74c0384f 100644 --- a/src/ui/ModelCapabilityWarning.tsx +++ b/src/ui/ModelCapabilityWarning.tsx @@ -24,4 +24,4 @@ const ModelCapabilityWarning: React.FC = ({ ); }; -export default ModelCapabilityWarning; +export { ModelCapabilityWarning }; diff --git a/src/ui/ModelSelector.tsx b/src/ui/ModelSelector.tsx index 5cf04a8d3..34829173d 100644 --- a/src/ui/ModelSelector.tsx +++ b/src/ui/ModelSelector.tsx @@ -1,6 +1,8 @@ import React, { useEffect, useState } from "react"; + import { services } from "../services/index.js"; -import Selector, { SelectorOption } from "./Selector.js"; + +import { Selector, SelectorOption } from "./Selector.js"; interface ModelOption extends SelectorOption { index: number; @@ -70,4 +72,4 @@ const ModelSelector: React.FC = ({ ); }; -export default ModelSelector; \ No newline at end of file +export { ModelSelector }; \ No newline at end of file diff --git a/src/ui/OrganizationSelector.tsx b/src/ui/OrganizationSelector.tsx index ca2a9c237..629636c5f 100644 --- a/src/ui/OrganizationSelector.tsx +++ b/src/ui/OrganizationSelector.tsx @@ -1,10 +1,12 @@ import React, { useEffect, useState } from "react"; + import { getOrganizationId, listUserOrganizations, loadAuthConfig, } from "../auth/workos.js"; -import Selector, { SelectorOption } from "./Selector.js"; + +import { Selector, SelectorOption } from "./Selector.js"; interface Organization extends SelectorOption {} @@ -79,4 +81,4 @@ const OrganizationSelector: React.FC = ({ ); }; -export default OrganizationSelector; +export { OrganizationSelector }; diff --git a/src/ui/Selector.tsx b/src/ui/Selector.tsx index cf58d7a3a..5d3b7c65c 100644 --- a/src/ui/Selector.tsx +++ b/src/ui/Selector.tsx @@ -25,7 +25,7 @@ interface SelectorProps { ) => ReactNode; } -export default function Selector({ +export function Selector({ title, options, selectedIndex, diff --git a/src/ui/ServiceDebugger.tsx b/src/ui/ServiceDebugger.tsx index d075a4e50..d8b50a2b9 100644 --- a/src/ui/ServiceDebugger.tsx +++ b/src/ui/ServiceDebugger.tsx @@ -1,5 +1,6 @@ import { Box, Text } from "ink"; import React from "react"; + import { ApiClientServiceState, AuthServiceState, @@ -111,4 +112,4 @@ const ServiceDebugger: React.FC = ({ ); }; -export default ServiceDebugger; \ No newline at end of file +export { ServiceDebugger }; \ No newline at end of file diff --git a/src/ui/SlashCommandUI.tsx b/src/ui/SlashCommandUI.tsx index ac7389e4e..55f673669 100644 --- a/src/ui/SlashCommandUI.tsx +++ b/src/ui/SlashCommandUI.tsx @@ -79,4 +79,4 @@ const SlashCommandUI: React.FC = ({ ); }; -export default SlashCommandUI; \ No newline at end of file +export { SlashCommandUI }; \ No newline at end of file diff --git a/src/ui/SyntaxHighlighter.ts b/src/ui/SyntaxHighlighter.ts index ccfc14abd..35931b1de 100644 --- a/src/ui/SyntaxHighlighter.ts +++ b/src/ui/SyntaxHighlighter.ts @@ -191,7 +191,7 @@ export function highlightCode( } return elements; - } catch (error) { + } catch { // Fallback to plain text on error return [ React.createElement( diff --git a/src/ui/TUIChat.tsx b/src/ui/TUIChat.tsx index 7fa5c4fc0..90d9e18cd 100644 --- a/src/ui/TUIChat.tsx +++ b/src/ui/TUIChat.tsx @@ -1,6 +1,9 @@ -import { Box, Text, useApp, useStdout } from "ink"; +import { Box, Text } from "ink"; import React, { useEffect, useMemo, useState } from "react"; + import { useServices } from "../hooks/useService.js"; +import type { PermissionMode } from "../permissions/types.js"; +import { modeService } from "../services/ModeService.js"; import { ApiClientServiceState, AuthServiceState, @@ -8,28 +11,27 @@ import { MCPServiceState, ModelServiceState, } from "../services/types.js"; +import { getGitRemoteUrl, isGitRepo } from "../util/git.js"; + +import { ModeIndicator } from "./components/ModeIndicator.js"; import { ToolPermissionSelector } from "./components/ToolPermissionSelector.js"; -import ConfigSelector from "./ConfigSelector.js"; +import { ConfigSelector } from "./ConfigSelector.js"; import { startFileIndexing } from "./FileSearchUI.js"; -import FreeTrialStatus from "./FreeTrialStatus.js"; -import FreeTrialTransitionUI from "./FreeTrialTransitionUI.js"; +import { FreeTrialStatus } from "./FreeTrialStatus.js"; +import { FreeTrialTransitionUI } from "./FreeTrialTransitionUI.js"; import { useChat } from "./hooks/useChat.js"; import { useConfigSelector } from "./hooks/useConfigSelector.js"; import { useMessageRenderer } from "./hooks/useMessageRenderer.js"; import { useModelSelector } from "./hooks/useModelSelector.js"; import { useOrganizationSelector } from "./hooks/useOrganizationSelector.js"; -import IntroMessage from "./IntroMessage.js"; -import LoadingAnimation from "./LoadingAnimation.js"; -import ModelSelector from "./ModelSelector.js"; -import OrganizationSelector from "./OrganizationSelector.js"; -import Timer from "./Timer.js"; -import UpdateNotification from "./UpdateNotification.js"; -import UserInput from "./UserInput.js"; -import ModeIndicator from "./components/ModeIndicator.js"; -import { getGitRemoteUrl, getRepoUrl, isGitRepo } from "../util/git.js"; -import useTerminalSize from "./hooks/useTerminalSize.js"; -import { modeService } from "../services/ModeService.js"; -import type { PermissionMode } from "../permissions/types.js"; +import { IntroMessage } from "./IntroMessage.js"; +import { LoadingAnimation } from "./LoadingAnimation.js"; +import { ModelSelector } from "./ModelSelector.js"; +import { OrganizationSelector } from "./OrganizationSelector.js"; +import { Timer } from "./Timer.js"; +import { UpdateNotification } from "./UpdateNotification.js"; +import { UserInput } from "./UserInput.js"; + interface TUIChatProps { // Remote mode props @@ -77,8 +79,6 @@ const TUIChat: React.FC = ({ // Get all services reactively - only in normal mode const { services, - loading: servicesLoading, - error: servicesError, allReady: allServicesReady, } = useServices<{ auth: AuthServiceState; @@ -93,7 +93,6 @@ const TUIChat: React.FC = ({ text: string; resolve: (value: string) => void; } | null>(null); - const [loginToken, setLoginToken] = useState(""); // State for free trial transition const [isShowingFreeTrialTransition, setIsShowingFreeTrialTransition] = @@ -160,7 +159,6 @@ const TUIChat: React.FC = ({ // Handle login token submission const handleLoginTokenSubmit = (token: string) => { if (loginPrompt) { - setLoginToken(""); loginPrompt.resolve(token); setLoginPrompt(null); } @@ -181,7 +179,6 @@ const TUIChat: React.FC = ({ isWaitingForResponse, responseStartTime, inputMode, - attachedFiles, activePermissionRequest, handleUserMessage, handleInterrupt, @@ -214,7 +211,7 @@ const TUIChat: React.FC = ({ showOrganizationSelector, } = useOrganizationSelector({ configPath, - onAssistantChange: (newAssistant, newModel, newLlmApi, newMcpService) => {}, + onAssistantChange: () => {}, onMessage: (message) => { setMessages((prev) => [...prev, message]); }, @@ -441,4 +438,4 @@ const TUIChat: React.FC = ({ ); }; -export default TUIChat; +export { TUIChat }; diff --git a/src/ui/Timer.tsx b/src/ui/Timer.tsx index 32fc2e090..dc72904a9 100644 --- a/src/ui/Timer.tsx +++ b/src/ui/Timer.tsx @@ -22,4 +22,4 @@ const Timer: React.FC = ({ startTime, color = "gray" }) => { return {elapsed}s; }; -export default Timer; \ No newline at end of file +export { Timer }; \ No newline at end of file diff --git a/src/ui/ToolResultSummary.tsx b/src/ui/ToolResultSummary.tsx index 70fb84f26..4c7a439f8 100644 --- a/src/ui/ToolResultSummary.tsx +++ b/src/ui/ToolResultSummary.tsx @@ -1,7 +1,10 @@ -import { Box, Text } from "ink"; import path from "path"; + +import { Box, Text } from "ink"; import React from "react"; + import { getToolDisplayName } from "../tools/index.js"; + import { ColoredDiff } from "./ColoredDiff.js"; import { ChecklistDisplay } from "./components/ChecklistDisplay.js"; @@ -173,4 +176,4 @@ const ToolResultSummary: React.FC = ({ ); }; -export default ToolResultSummary; +export { ToolResultSummary }; diff --git a/src/ui/UpdateNotification.tsx b/src/ui/UpdateNotification.tsx index ffd5669fb..c893da02e 100644 --- a/src/ui/UpdateNotification.tsx +++ b/src/ui/UpdateNotification.tsx @@ -1,7 +1,9 @@ -import { Text, useStdout } from "ink"; +import { Text } from "ink"; import React, { useEffect, useMemo, useState } from "react"; + import { compareVersions, getLatestVersion, getVersion } from "../version.js"; -import useTerminalSize from "./hooks/useTerminalSize.js"; + +import { useTerminalSize } from "./hooks/useTerminalSize.js"; interface UpdateNotificationProps { isRemoteMode?: boolean; @@ -65,4 +67,4 @@ const UpdateNotification: React.FC = ({ return {text}; }; -export default UpdateNotification; +export { UpdateNotification }; diff --git a/src/ui/UserInput.keyboard.test.ts b/src/ui/UserInput.keyboard.test.ts index 47309aa78..53b8ccbc1 100644 --- a/src/ui/UserInput.keyboard.test.ts +++ b/src/ui/UserInput.keyboard.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it, beforeEach } from 'vitest'; + import { modeService } from '../services/ModeService.js'; describe('UserInput Keyboard Shortcuts', () => { diff --git a/src/ui/UserInput.tsx b/src/ui/UserInput.tsx index cb6cd6e36..8b602d649 100644 --- a/src/ui/UserInput.tsx +++ b/src/ui/UserInput.tsx @@ -1,14 +1,16 @@ import { type AssistantConfig } from "@continuedev/sdk"; import { Box, Text, useApp, useInput } from "ink"; import React, { useState } from "react"; + import { getAllSlashCommands } from "../commands/commands.js"; -import { modeService } from "../services/ModeService.js"; -import { reloadService, SERVICE_NAMES } from "../services/index.js"; import type { PermissionMode } from "../permissions/types.js"; +import { reloadService, SERVICE_NAMES } from "../services/index.js"; +import { modeService } from "../services/ModeService.js"; import { InputHistory } from "../util/inputHistory.js"; -import logger from "../util/logger.js"; -import FileSearchUI from "./FileSearchUI.js"; -import SlashCommandUI from "./SlashCommandUI.js"; +import { logger } from "../util/logger.js"; + +import { FileSearchUI } from "./FileSearchUI.js"; +import { SlashCommandUI } from "./SlashCommandUI.js"; import { TextBuffer } from "./TextBuffer.js"; interface UserInputProps { @@ -369,7 +371,7 @@ const UserInput: React.FC = ({ } if (key.downArrow) { - const historyEntry = inputHistory.navigateDown(inputText); + const historyEntry = inputHistory.navigateDown(); if (historyEntry !== null) { textBuffer.setText(historyEntry); textBuffer.setCursor(historyEntry.length); @@ -547,4 +549,4 @@ const UserInput: React.FC = ({ ); }; -export default UserInput; \ No newline at end of file +export { UserInput }; \ No newline at end of file diff --git a/src/ui/__mocks__/FreeTrialStatus.tsx b/src/ui/__mocks__/FreeTrialStatus.tsx index 1f0ab6c20..517dcf3f7 100644 --- a/src/ui/__mocks__/FreeTrialStatus.tsx +++ b/src/ui/__mocks__/FreeTrialStatus.tsx @@ -5,7 +5,7 @@ const FreeTrialStatus: React.FC = () => { return null; }; -export default FreeTrialStatus; +export { FreeTrialStatus }; export function isModelUsingFreeTrial(): boolean { return false; } \ No newline at end of file diff --git a/src/ui/__mocks__/SyntaxHighlighter.ts b/src/ui/__mocks__/SyntaxHighlighter.ts index c0f7a4633..041f75b44 100644 --- a/src/ui/__mocks__/SyntaxHighlighter.ts +++ b/src/ui/__mocks__/SyntaxHighlighter.ts @@ -1,4 +1,3 @@ -import { Text } from 'ink'; import React from 'react'; export interface SyntaxHighlighterTheme { @@ -17,12 +16,12 @@ export const defaultTheme: SyntaxHighlighterTheme = { operator: 'cyan', }; -export function highlightCode(code: string, language?: string): React.ReactNode[] { +export function highlightCode(code: string): React.ReactNode[] { // Mock implementation that just returns the code as plain text return [React.createElement('ink-text', { key: 'mock-code' }, code)]; } -export function detectLanguage(code: string): string { +export function detectLanguage(): string { // Mock implementation return 'javascript'; } \ No newline at end of file diff --git a/src/ui/__tests__/FreeTrialTransitionUI.test.tsx b/src/ui/__tests__/FreeTrialTransitionUI.test.tsx index e6fdec8af..5029fdfc8 100644 --- a/src/ui/__tests__/FreeTrialTransitionUI.test.tsx +++ b/src/ui/__tests__/FreeTrialTransitionUI.test.tsx @@ -1,7 +1,8 @@ import { render } from "ink-testing-library"; import React from "react"; import { vi } from "vitest"; -import FreeTrialTransitionUI from "../FreeTrialTransitionUI.js"; + +import { FreeTrialTransitionUI } from "../FreeTrialTransitionUI.js"; // Mock the 'open' module to prevent actual URL opening during tests vi.mock("open", () => ({ diff --git a/src/ui/__tests__/TUIChat.basic.test.tsx b/src/ui/__tests__/TUIChat.basic.test.tsx index a869ecf95..bc31f6af6 100644 --- a/src/ui/__tests__/TUIChat.basic.test.tsx +++ b/src/ui/__tests__/TUIChat.basic.test.tsx @@ -1,7 +1,8 @@ import { render } from "ink-testing-library"; import React from "react"; + import { createUITestContext } from "../../test-helpers/ui-test-context.js"; -import TUIChat from "../TUIChat.js"; +import { TUIChat } from "../TUIChat.js"; describe("TUIChat - Basic UI Tests", () => { let context: any; diff --git a/src/ui/__tests__/TUIChat.dualModeHelper.tsx b/src/ui/__tests__/TUIChat.dualModeHelper.tsx index 2ed8543be..4904459ed 100644 --- a/src/ui/__tests__/TUIChat.dualModeHelper.tsx +++ b/src/ui/__tests__/TUIChat.dualModeHelper.tsx @@ -1,7 +1,8 @@ import { render } from "ink-testing-library"; import React from "react"; + import { createUITestContext } from "../../test-helpers/ui-test-context.js"; -import TUIChat from "../TUIChat.js"; +import { TUIChat } from "../TUIChat.js"; export type TestMode = 'local' | 'remote'; diff --git a/src/ui/__tests__/TUIChat.freeTrialTransition.test.tsx b/src/ui/__tests__/TUIChat.freeTrialTransition.test.tsx index 926c4987d..ac28ac959 100644 --- a/src/ui/__tests__/TUIChat.freeTrialTransition.test.tsx +++ b/src/ui/__tests__/TUIChat.freeTrialTransition.test.tsx @@ -1,5 +1,4 @@ // Integration tests for free trial transition - simplified version -import { vi } from "vitest"; describe("TUIChat - Free Trial Transition Integration", () => { it("should integrate free trial transition with config selector", () => { diff --git a/src/ui/__tests__/TUIChat.messages.test.tsx b/src/ui/__tests__/TUIChat.messages.test.tsx index 3c877c674..bad8e3eb2 100644 --- a/src/ui/__tests__/TUIChat.messages.test.tsx +++ b/src/ui/__tests__/TUIChat.messages.test.tsx @@ -1,5 +1,5 @@ -import type { ChatCompletionMessageParam } from "openai/resources/index.js"; import { createUITestContext } from "../../test-helpers/ui-test-context.js"; + import { testBothModes, renderInMode } from "./TUIChat.dualModeHelper.js"; describe("TUIChat - Message Display Tests", () => { diff --git a/src/ui/__tests__/TUIChat.remote.test.tsx b/src/ui/__tests__/TUIChat.remote.test.tsx index adc5e86b5..6911ce550 100644 --- a/src/ui/__tests__/TUIChat.remote.test.tsx +++ b/src/ui/__tests__/TUIChat.remote.test.tsx @@ -1,7 +1,8 @@ import { render } from "ink-testing-library"; import React from "react"; + import { createUITestContext } from "../../test-helpers/ui-test-context.js"; -import TUIChat from "../TUIChat.js"; +import { TUIChat } from "../TUIChat.js"; describe("TUIChat - Remote Server Tests", () => { let context: any; diff --git a/src/ui/__tests__/TUIChat.setup.ts b/src/ui/__tests__/TUIChat.setup.ts index c28fc1f02..6ac658ad3 100644 --- a/src/ui/__tests__/TUIChat.setup.ts +++ b/src/ui/__tests__/TUIChat.setup.ts @@ -1,66 +1,12 @@ import type { AssistantUnrolled } from "@continuedev/config-yaml"; import { vi } from "vitest"; -// Minimal mock for LLM API (just enough to prevent errors) -export class MockLlmApi { - async chatCompletionStream(): Promise> { - return (async function* () { - yield { choices: [{ delta: {}, index: 0, finish_reason: "stop" }] }; - })(); - } - async chatCompletionNonStream() { - throw new Error("Not implemented"); - } - async completionStream() { - throw new Error("Not implemented"); - } - async completionNonStream() { - throw new Error("Not implemented"); - } - async streamChat() { - return this.chatCompletionStream(); - } - async completions() { - throw new Error("Not implemented"); - } - async streamCompletion() { - throw new Error("Not implemented"); - } - async chat() { - throw new Error("Not implemented"); - } - async rerank() { - return { results: [] }; - } - async embed() { - return { data: [], usage: {} }; - } - async fimComplete() { - throw new Error("Not implemented"); - } -} +import { MockApiClient } from "./mocks/MockApiClient.js"; +import { MockLlmApi } from "./mocks/MockLlmApi.js"; +import { MockMCPService } from "./mocks/MockMCPService.js"; -// Mock MCP Service -export class MockMCPService { - connections = []; - assistant = {} as any; - getTools() { - return []; - } - getPrompts() { - return []; - } - async runTool() { - return { result: "Mock result" }; - } - async executeToolCall() { - return { result: "Mock result" }; - } - async close() {} - isInitialized() { - return true; - } -} +// Re-export the mocks for backward compatibility +export { MockApiClient, MockLlmApi, MockMCPService }; // Mock Assistant config export const mockAssistant: AssistantUnrolled = { @@ -95,29 +41,6 @@ vi.mock("glob", () => ({ ]), })); -// Mock API Client -export class MockApiClient { - async getFreeTrialStatus() { - return { - optedInToFreeTrial: true, - chatCount: 5, - chatLimit: 100, - }; - } - async listAssistants() { - return []; - } - async getAssistant() { - return { configResult: { config: mockAssistant } }; - } - async listOrganizations() { - return { organizations: [] }; - } - async syncSecrets() { - return []; - } -} - export const createProps = (overrides: any = {}) => ({ config: mockAssistant, model: "test-model", diff --git a/src/ui/__tests__/TUIChat.slashCommands.test.tsx b/src/ui/__tests__/TUIChat.slashCommands.test.tsx index 722dd9e21..068ed40db 100644 --- a/src/ui/__tests__/TUIChat.slashCommands.test.tsx +++ b/src/ui/__tests__/TUIChat.slashCommands.test.tsx @@ -1,4 +1,3 @@ -import { vi } from "vitest"; import { testBothModes, renderInMode } from "./TUIChat.dualModeHelper.js"; describe("TUIChat - Slash Commands Tests", () => { diff --git a/src/ui/__tests__/TUIChat.streamStopping.test.tsx b/src/ui/__tests__/TUIChat.streamStopping.test.tsx index f23e0f726..96a9fff39 100644 --- a/src/ui/__tests__/TUIChat.streamStopping.test.tsx +++ b/src/ui/__tests__/TUIChat.streamStopping.test.tsx @@ -1,6 +1,7 @@ -import { vi } from "vitest"; import { render } from "ink-testing-library"; import React from "react"; +import { vi } from "vitest"; + import { ToolPermissionSelector } from "../components/ToolPermissionSelector.js"; describe("TUIChat - Stream Stopping on Tool Rejection", () => { diff --git a/src/ui/__tests__/TUIChat.testHelper.ts b/src/ui/__tests__/TUIChat.testHelper.ts index e7424aae6..1d8af2799 100644 --- a/src/ui/__tests__/TUIChat.testHelper.ts +++ b/src/ui/__tests__/TUIChat.testHelper.ts @@ -1,14 +1,16 @@ -import { vi } from "vitest"; import { render } from "ink-testing-library"; import React from "react"; -import TUIChat from "../TUIChat.js"; +import { vi } from "vitest"; + +import { TUIChat } from "../TUIChat.js"; + +import { MockRemoteServer } from "./mockRemoteServer.js"; import { MockApiClient, mockAssistant, MockLlmApi, MockMCPService, } from "./TUIChat.setup.js"; -import { MockRemoteServer } from "./mockRemoteServer.js"; // Define RenderResult type to match ink-testing-library's Instance interface RenderResult { @@ -122,7 +124,7 @@ export function runTest( allReady: true, }); - mockUseService.mockImplementation((serviceName: string) => ({ + mockUseService.mockImplementation((serviceName: string) => ({ value: (() => { switch (serviceName) { case "auth": @@ -274,7 +276,7 @@ export function runTestSuite( allReady: true, }); - mockUseService.mockImplementation((serviceName: string) => ({ + mockUseService.mockImplementation((serviceName: string) => ({ value: (() => { switch (serviceName) { case "auth": diff --git a/src/ui/__tests__/TUIChat.toolDisplay.test.tsx b/src/ui/__tests__/TUIChat.toolDisplay.test.tsx index d2f179918..e15389e39 100644 --- a/src/ui/__tests__/TUIChat.toolDisplay.test.tsx +++ b/src/ui/__tests__/TUIChat.toolDisplay.test.tsx @@ -1,7 +1,8 @@ import { render } from "ink-testing-library"; import React from "react"; + import { createUITestContext } from "../../test-helpers/ui-test-context.js"; -import TUIChat from "../TUIChat.js"; +import { TUIChat } from "../TUIChat.js"; describe("TUIChat - Tool Display Tests", () => { let context: any; diff --git a/src/ui/__tests__/TUIChat.toolPermission.test.tsx b/src/ui/__tests__/TUIChat.toolPermission.test.tsx index 37fe7935c..d90b8a2ec 100644 --- a/src/ui/__tests__/TUIChat.toolPermission.test.tsx +++ b/src/ui/__tests__/TUIChat.toolPermission.test.tsx @@ -1,6 +1,7 @@ -import { vi } from "vitest"; import { render } from "ink-testing-library"; import React from "react"; +import { vi } from "vitest"; + import { ToolPermissionSelector } from "../components/ToolPermissionSelector.js"; describe("TUIChat - Tool Permission Tests", () => { @@ -145,7 +146,7 @@ describe("TUIChat - Tool Permission Tests", () => { await vi.advanceTimersByTimeAsync(50); // Initial state should show "> Continue" selected - let frame = lastFrame(); + const frame = lastFrame(); expect(frame).toMatch(/>\s+Continue/); // Test that pressing Enter on default selection triggers approval @@ -190,7 +191,7 @@ describe("TUIChat - Tool Permission Tests", () => { it("shows tool result with red dot and 'Cancelled by user' message", async () => { // Import the components we need for this test - const { default: ToolResultSummary } = await import( + const { ToolResultSummary } = await import( "../ToolResultSummary.js" ); const { MemoizedMessage } = await import( diff --git a/src/ui/__tests__/mockRemoteServer.ts b/src/ui/__tests__/mockRemoteServer.ts index 999ff325f..3831b75eb 100644 --- a/src/ui/__tests__/mockRemoteServer.ts +++ b/src/ui/__tests__/mockRemoteServer.ts @@ -1,6 +1,8 @@ -import { describe, expect, test } from "vitest"; -import express from "express"; import { Server } from "http"; + +import express from "express"; +import { describe, expect, test } from "vitest"; + import { DisplayMessage } from "../types.js"; export interface MockRemoteServerConfig { diff --git a/src/ui/__tests__/mocks/MockApiClient.ts b/src/ui/__tests__/mocks/MockApiClient.ts new file mode 100644 index 000000000..41184578b --- /dev/null +++ b/src/ui/__tests__/mocks/MockApiClient.ts @@ -0,0 +1,39 @@ +// Mock API Client +export class MockApiClient { + async getFreeTrialStatus() { + return { + optedInToFreeTrial: true, + chatCount: 5, + chatLimit: 100, + }; + } + async listAssistants() { + return []; + } + async getAssistant() { + // Return a minimal assistant config + return { + configResult: { + config: { + name: "test-assistant", + models: [ + { + provider: "openai", + name: "test-model", + model: "test-model", + }, + ], + systemMessage: "You are a helpful assistant", + tools: [], + mcpServers: [], + } + } + }; + } + async listOrganizations() { + return { organizations: [] }; + } + async syncSecrets() { + return []; + } +} \ No newline at end of file diff --git a/src/ui/__tests__/mocks/MockLlmApi.ts b/src/ui/__tests__/mocks/MockLlmApi.ts new file mode 100644 index 000000000..da19ee2ff --- /dev/null +++ b/src/ui/__tests__/mocks/MockLlmApi.ts @@ -0,0 +1,38 @@ +// Minimal mock for LLM API (just enough to prevent errors) +export class MockLlmApi { + async chatCompletionStream(): Promise> { + return (async function* () { + yield { choices: [{ delta: {}, index: 0, finish_reason: "stop" }] }; + })(); + } + async chatCompletionNonStream() { + throw new Error("Not implemented"); + } + async completionStream() { + throw new Error("Not implemented"); + } + async completionNonStream() { + throw new Error("Not implemented"); + } + async streamChat() { + return this.chatCompletionStream(); + } + async completions() { + throw new Error("Not implemented"); + } + async streamCompletion() { + throw new Error("Not implemented"); + } + async chat() { + throw new Error("Not implemented"); + } + async rerank() { + return { results: [] }; + } + async embed() { + return { data: [], usage: {} }; + } + async fimComplete() { + throw new Error("Not implemented"); + } +} \ No newline at end of file diff --git a/src/ui/__tests__/mocks/MockMCPService.ts b/src/ui/__tests__/mocks/MockMCPService.ts new file mode 100644 index 000000000..c1ca17860 --- /dev/null +++ b/src/ui/__tests__/mocks/MockMCPService.ts @@ -0,0 +1,21 @@ +// Mock MCP Service +export class MockMCPService { + connections = []; + assistant = {} as any; + getTools() { + return []; + } + getPrompts() { + return []; + } + async runTool() { + return { result: "Mock result" }; + } + async executeToolCall() { + return { result: "Mock result" }; + } + async close() {} + isInitialized() { + return true; + } +} \ No newline at end of file diff --git a/src/ui/__tests__/throttledGlob.test.ts b/src/ui/__tests__/throttledGlob.test.ts index e07382fdc..547b338ad 100644 --- a/src/ui/__tests__/throttledGlob.test.ts +++ b/src/ui/__tests__/throttledGlob.test.ts @@ -1,3 +1,5 @@ +import { EventEmitter } from "events"; + import { vi, describe, @@ -6,7 +8,7 @@ import { it, expect, } from "vitest"; -import { EventEmitter } from "events"; + import { throttledGlob } from "../FileSearchUI.js"; // Define a custom interface for our mock diff --git a/src/ui/components/MemoizedMessage.tsx b/src/ui/components/MemoizedMessage.tsx index 71165c3bb..addbbcf32 100644 --- a/src/ui/components/MemoizedMessage.tsx +++ b/src/ui/components/MemoizedMessage.tsx @@ -1,7 +1,8 @@ import { Box, Text } from "ink"; import React, { memo } from "react"; -import MarkdownRenderer from "../MarkdownRenderer.js"; -import ToolResultSummary from "../ToolResultSummary.js"; + +import { MarkdownRenderer } from "../MarkdownRenderer.js"; +import { ToolResultSummary } from "../ToolResultSummary.js"; import { DisplayMessage } from "../types.js"; interface MemoizedMessageProps { diff --git a/src/ui/components/ModeIndicator.test.tsx b/src/ui/components/ModeIndicator.test.tsx index d1119afd7..6fb93aeb8 100644 --- a/src/ui/components/ModeIndicator.test.tsx +++ b/src/ui/components/ModeIndicator.test.tsx @@ -1,9 +1,12 @@ -import { describe, expect, it, beforeEach } from 'vitest'; import { render } from 'ink-testing-library'; import React from 'react'; -import ModeIndicator from './ModeIndicator.js'; +import { describe, expect, it, beforeEach } from 'vitest'; + import { modeService } from '../../services/ModeService.js'; +import { ModeIndicator } from './ModeIndicator.js'; + + describe('ModeIndicator', () => { beforeEach(() => { // Reset to normal mode for each test diff --git a/src/ui/components/ModeIndicator.tsx b/src/ui/components/ModeIndicator.tsx index 2a2d8755b..ee95160bf 100644 --- a/src/ui/components/ModeIndicator.tsx +++ b/src/ui/components/ModeIndicator.tsx @@ -1,7 +1,8 @@ import { Text } from "ink"; import React, { useEffect, useState } from "react"; -import { modeService } from "../../services/ModeService.js"; + import type { PermissionMode } from "../../permissions/types.js"; +import { modeService } from "../../services/ModeService.js"; interface ModeIndicatorProps { mode?: PermissionMode; @@ -59,4 +60,4 @@ const ModeIndicator: React.FC = ({ mode }) => { ); }; -export default ModeIndicator; \ No newline at end of file +export { ModeIndicator }; \ No newline at end of file diff --git a/src/ui/components/ToolPermissionRequest.tsx b/src/ui/components/ToolPermissionRequest.tsx index 468becebe..bb9abe80d 100644 --- a/src/ui/components/ToolPermissionRequest.tsx +++ b/src/ui/components/ToolPermissionRequest.tsx @@ -16,7 +16,7 @@ export const ToolPermissionRequest: React.FC = ({ }) => { const [responded, setResponded] = useState(false); - useInput((input, key) => { + useInput((input) => { if (responded) return; if (input === "y" || input === "Y") { diff --git a/src/ui/components/ToolPermissionSelector.tsx b/src/ui/components/ToolPermissionSelector.tsx index 7cc8c1a44..9be8e88d4 100644 --- a/src/ui/components/ToolPermissionSelector.tsx +++ b/src/ui/components/ToolPermissionSelector.tsx @@ -1,9 +1,11 @@ import { Box, Text, useInput } from "ink"; import React, { useState } from "react"; + import { formatToolCall } from "../../tools/index.js"; -import { ToolPreview } from "./ToolPreview.js"; import { ToolCallPreview } from "../../tools/types.js"; +import { ToolPreview } from "./ToolPreview.js"; + interface PermissionOption { id: string; name: string; diff --git a/src/ui/components/ToolPreview.tsx b/src/ui/components/ToolPreview.tsx index 2b91f0907..e6c5e83d4 100644 --- a/src/ui/components/ToolPreview.tsx +++ b/src/ui/components/ToolPreview.tsx @@ -1,8 +1,10 @@ import { Box, Text } from "ink"; import React from "react"; -import { ColoredDiff } from "../ColoredDiff.js"; -import { ToolCallPreview } from "../../tools/types.js"; + import { getToolDisplayName } from "../../tools/index.js"; +import { ToolCallPreview } from "../../tools/types.js"; +import { ColoredDiff } from "../ColoredDiff.js"; + import { ChecklistDisplay } from "./ChecklistDisplay.js"; interface ToolPreviewProps { diff --git a/src/ui/hooks/useChat.test.ts b/src/ui/hooks/useChat.test.ts index b7363d4cb..4ad7bf5a6 100644 --- a/src/ui/hooks/useChat.test.ts +++ b/src/ui/hooks/useChat.test.ts @@ -6,6 +6,7 @@ import { it, vi, } from "vitest"; + import { createMinimalTestContext } from "../../test-helpers/ui-test-context.js"; describe("useChat", () => { diff --git a/src/ui/hooks/useChat.ts b/src/ui/hooks/useChat.ts index af47e19ee..e20a56998 100644 --- a/src/ui/hooks/useChat.ts +++ b/src/ui/hooks/useChat.ts @@ -3,16 +3,6 @@ import { BaseLlmApi } from "@continuedev/openai-adapters"; import { useApp } from "ink"; import { ChatCompletionMessageParam } from "openai/resources.mjs"; import { useEffect, useState } from "react"; -import { toolPermissionManager } from "../../permissions/permissionManager.js"; -import { loadSession, saveSession } from "../../session.js"; -import { handleSlashCommands } from "../../slashCommands.js"; -import { - StreamCallbacks, - streamChatResponse, -} from "../../streamChatResponse.js"; -import telemetryService from "../../telemetry/telemetryService.js"; -import { formatError } from "../../util/formatError.js"; -import logger from "../../util/logger.js"; import { initializeChatHistory } from "../../commands/chat.js"; import { @@ -20,9 +10,19 @@ import { findCompactionIndex, getHistoryForLLM, } from "../../compaction.js"; +import { toolPermissionManager } from "../../permissions/permissionManager.js"; +import { loadSession, saveSession } from "../../session.js"; +import { handleSlashCommands } from "../../slashCommands.js"; +import { + StreamCallbacks, + streamChatResponse, +} from "../../streamChatResponse.js"; import { posthogService } from "../../telemetry/posthogService.js"; +import { telemetryService } from "../../telemetry/telemetryService.js"; import { formatToolCall } from "../../tools/index.js"; import { ToolCallPreview } from "../../tools/types.js"; +import { formatError } from "../../util/formatError.js"; +import { logger } from "../../util/logger.js"; import { shouldAutoCompact } from "../../util/tokenizer.js"; import { DisplayMessage } from "../types.js"; @@ -53,8 +53,7 @@ export function useChat({ onShowOrgSelector, onShowConfigSelector, onShowModelSelector, - onLoginPrompt, - onReload, + onLoginPrompt: _onLoginPrompt, isRemoteMode = false, remoteUrl, }: UseChatProps) { @@ -68,17 +67,7 @@ export function useChat({ } // Synchronously initialize chat history to prevent race conditions - // This ensures system message is always loaded before handleUserMessage runs - let initialHistory: ChatCompletionMessageParam[] = []; - // Load previous session if resume flag is used - if (resume) { - const savedHistory = loadSession(); - if (savedHistory) { - initialHistory = savedHistory; - } - } - // If no session loaded or not resuming, we'll need to add system message // We can't make this async, so we'll handle it in the useEffect return resume ? loadSession() ?? [] : []; @@ -351,8 +340,7 @@ export function useChat({ if (!isRemoteMode && assistant) { const commandResult = await handleSlashCommands( message, - assistant, - onLoginPrompt + assistant ); if (commandResult) { if (commandResult.exit) { diff --git a/src/ui/hooks/useConfigSelector.ts b/src/ui/hooks/useConfigSelector.ts index e32e739c1..f392f98cd 100644 --- a/src/ui/hooks/useConfigSelector.ts +++ b/src/ui/hooks/useConfigSelector.ts @@ -1,9 +1,10 @@ import { exec } from "child_process"; import * as os from "os"; import * as path from "path"; + import { useState } from "react"; -import { loadAuthConfig, updateAssistantSlug } from "../../auth/workos.js"; -import { reloadService, services, SERVICE_NAMES } from "../../services/index.js"; + +import { services } from "../../services/index.js"; interface ConfigOption { id: string; @@ -25,7 +26,6 @@ interface UseConfigSelectorProps { const CONFIG_PATH = path.join(os.homedir(), ".continue", "config.yaml"); export function useConfigSelector({ - configPath, onMessage, onChatReset, }: UseConfigSelectorProps) { @@ -60,7 +60,7 @@ export function useConfigSelector({ content: `Opening ${url} in your browser to create a new assistant...`, messageType: "system" as const, }); - } catch (error) { + } catch { onMessage({ role: "system", content: `Please visit ${url} to create a new assistant`, diff --git a/src/ui/hooks/useMessageRenderer.tsx b/src/ui/hooks/useMessageRenderer.tsx index bb8e719d6..888b03cce 100644 --- a/src/ui/hooks/useMessageRenderer.tsx +++ b/src/ui/hooks/useMessageRenderer.tsx @@ -1,4 +1,5 @@ import React, { useCallback } from "react"; + import { MemoizedMessage } from "../components/MemoizedMessage.js"; import { DisplayMessage } from "../types.js"; diff --git a/src/ui/hooks/useModelSelector.ts b/src/ui/hooks/useModelSelector.ts index de8f3ae19..f4917f847 100644 --- a/src/ui/hooks/useModelSelector.ts +++ b/src/ui/hooks/useModelSelector.ts @@ -1,7 +1,8 @@ import { useState } from "react"; + +import { updateModelName } from "../../auth/workos.js"; import { services, serviceContainer, SERVICE_NAMES } from "../../services/index.js"; import { ModelServiceState } from "../../services/types.js"; -import { updateModelName } from "../../auth/workos.js"; interface ModelOption { id: string; diff --git a/src/ui/hooks/useOrganizationSelector.ts b/src/ui/hooks/useOrganizationSelector.ts index 6c8742048..73465b42a 100644 --- a/src/ui/hooks/useOrganizationSelector.ts +++ b/src/ui/hooks/useOrganizationSelector.ts @@ -1,6 +1,7 @@ import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; import { BaseLlmApi } from "@continuedev/openai-adapters"; import { useState } from "react"; + import { isAuthenticatedConfig, loadAuthConfig, diff --git a/src/ui/hooks/useTerminalSize.ts b/src/ui/hooks/useTerminalSize.ts index 41bcbcfd3..8b1f08d15 100644 --- a/src/ui/hooks/useTerminalSize.ts +++ b/src/ui/hooks/useTerminalSize.ts @@ -1,5 +1,5 @@ -import { useEffect, useState } from "react"; import { useStdout } from "ink"; +import { useEffect, useState } from "react"; const DEFAULT_ROWS = 24; const DEFAULT_COLS = 80; @@ -43,4 +43,4 @@ const useTerminalSize = (debounce = 100) => { return { ...dimensions, isResizing }; }; -export default useTerminalSize; +export { useTerminalSize }; diff --git a/src/ui/index.ts b/src/ui/index.ts index bebd1d509..ffba48ec2 100644 --- a/src/ui/index.ts +++ b/src/ui/index.ts @@ -1,11 +1,13 @@ import { render } from "ink"; import React from "react"; + import { PermissionMode } from "../permissions/types.js"; import { initializeServices } from "../services/index.js"; import { ServiceContainerProvider } from "../services/ServiceContainerContext.js"; -import TUIChat from "./TUIChat.js"; -export { default as MarkdownRenderer } from "./MarkdownRenderer.js"; +import { TUIChat } from "./TUIChat.js"; + +export { MarkdownRenderer } from "./MarkdownRenderer.js"; export async function startTUIChat( initialPrompt?: string, diff --git a/src/util/exponentialBackoff.test.ts b/src/util/exponentialBackoff.test.ts index 5b1b44f84..05fd9f30a 100644 --- a/src/util/exponentialBackoff.test.ts +++ b/src/util/exponentialBackoff.test.ts @@ -1,4 +1,5 @@ import { vi } from "vitest"; + import { ExponentialBackoffOptions } from "./exponentialBackoff.js"; // Since the functions are not exported, we need to recreate them for testing diff --git a/src/util/exponentialBackoff.ts b/src/util/exponentialBackoff.ts index 18c73abb8..7ab424bec 100644 --- a/src/util/exponentialBackoff.ts +++ b/src/util/exponentialBackoff.ts @@ -1,8 +1,10 @@ import { BaseLlmApi } from "@continuedev/openai-adapters"; import type { ChatCompletionCreateParamsStreaming } from "openai/resources.mjs"; + import { error, warn } from "../logging.js"; + import { formatError } from "./formatError.js"; -import logger from "./logger.js"; +import { logger } from "./logger.js"; export interface ExponentialBackoffOptions { /** Maximum number of retry attempts */ @@ -157,7 +159,7 @@ export async function* withExponentialBackoff( let lastError: any; for (let attempt = 0; attempt <= opts.maxRetries; attempt++) { - let yieldedValues: T[] = []; + const yieldedValues: T[] = []; try { // Check if we should abort before creating the generator diff --git a/src/util/inputHistory.ts b/src/util/inputHistory.ts index 1ec172adc..f6c528273 100644 --- a/src/util/inputHistory.ts +++ b/src/util/inputHistory.ts @@ -1,6 +1,6 @@ import fs from 'fs'; -import path from 'path'; import os from 'os'; +import path from 'path'; const HISTORY_FILE = path.join(os.homedir(), '.continue', 'input_history.json'); const MAX_HISTORY_SIZE = 1000; @@ -84,7 +84,7 @@ export class InputHistory { return this.history[this.currentIndex]?.text || null; } - navigateDown(currentInput: string): string | null { + navigateDown(): string | null { if (this.currentIndex === -1) return null; if (this.currentIndex > 0) { diff --git a/src/util/logger.ts b/src/util/logger.ts index 1c3c180d7..76df80408 100644 --- a/src/util/logger.ts +++ b/src/util/logger.ts @@ -1,9 +1,10 @@ -import winston from 'winston'; -import path from 'path'; -import os from 'os'; -import fs from 'fs'; import crypto from 'crypto'; +import fs from 'fs'; +import os from 'os'; +import path from 'path'; + import chalk from 'chalk'; +import winston from 'winston'; const { combine, timestamp, printf, errors } = winston.format; @@ -82,7 +83,7 @@ const logFormat = printf(({ level, message, timestamp, stack, ...metadata }) => let isHeadlessMode = false; // Create the logger instance -const logger = winston.createLogger({ +const winstonLogger = winston.createLogger({ level: 'info', // Default level format: combine( errors({ stack: true }), @@ -101,7 +102,7 @@ const logger = winston.createLogger({ // Function to set log level export function setLogLevel(level: string) { - logger.level = level; + winstonLogger.level = level; } // Function to configure headless mode @@ -109,18 +110,18 @@ export function configureHeadlessMode(headless: boolean) { isHeadlessMode = headless; } -// Export logger methods -export default { - debug: (message: string, meta?: any) => logger.debug(message, meta), - info: (message: string, meta?: any) => logger.info(message, meta), - warn: (message: string, meta?: any) => logger.warn(message, meta), +// Export logger methods +export const logger = { + debug: (message: string, meta?: any) => winstonLogger.debug(message, meta), + info: (message: string, meta?: any) => winstonLogger.info(message, meta), + warn: (message: string, meta?: any) => winstonLogger.warn(message, meta), error: (message: string, error?: Error | any, meta?: any) => { if (error instanceof Error) { - logger.error(message, { ...meta, error: error.message, stack: error.stack }); + winstonLogger.error(message, { ...meta, error: error.message, stack: error.stack }); } else if (error) { - logger.error(message, { ...meta, error }); + winstonLogger.error(message, { ...meta, error }); } else { - logger.error(message, meta); + winstonLogger.error(message, meta); } // In headless mode, also output to stderr diff --git a/src/util/stdin.ts b/src/util/stdin.ts index acc6a11de..b1de966bf 100644 --- a/src/util/stdin.ts +++ b/src/util/stdin.ts @@ -27,7 +27,7 @@ export function readStdinSync(): string | null { // If isTTY is explicitly false, try to read stdin const stdinData = fs.readFileSync(0, "utf8"); return stdinData.trim(); - } catch (error) { + } catch { return null; } } \ No newline at end of file diff --git a/src/util/tokenizer.ts b/src/util/tokenizer.ts index d3b3aea64..a2ff9dfd6 100644 --- a/src/util/tokenizer.ts +++ b/src/util/tokenizer.ts @@ -1,7 +1,8 @@ import { ModelConfig } from "@continuedev/config-yaml"; import { encode } from "gpt-tokenizer"; import { ChatCompletionMessageParam } from "openai/resources.mjs"; -import logger from "./logger.js"; + +import { logger } from "./logger.js"; // Global auto-compact threshold (80% of context limit) // This is intentionally not configurable to ensure consistent behavior diff --git a/src/util/withExponentialBackoff.test.ts b/src/util/withExponentialBackoff.test.ts index 2561dca7d..242a408af 100644 --- a/src/util/withExponentialBackoff.test.ts +++ b/src/util/withExponentialBackoff.test.ts @@ -1,5 +1,7 @@ import { vi } from "vitest"; + import { createMinimalTestContext } from "../test-helpers/ui-test-context.js"; + import { withExponentialBackoff } from "./exponentialBackoff.js"; describe("withExponentialBackoff", () => { diff --git a/src/util/yamlConfigUpdater.test.ts b/src/util/yamlConfigUpdater.test.ts index 838d5d600..d16eda873 100644 --- a/src/util/yamlConfigUpdater.test.ts +++ b/src/util/yamlConfigUpdater.test.ts @@ -1,6 +1,7 @@ -import { updateAnthropicModelInYaml } from './yamlConfigUpdater.js'; import { parse } from 'yaml'; +import { updateAnthropicModelInYaml } from './yamlConfigUpdater.js'; + describe('updateAnthropicModelInYaml', () => { const testApiKey = 'sk-ant-test123456789'; diff --git a/src/util/yamlConfigUpdater.ts b/src/util/yamlConfigUpdater.ts index 059bdf8f7..ee63bb2ed 100644 --- a/src/util/yamlConfigUpdater.ts +++ b/src/util/yamlConfigUpdater.ts @@ -69,7 +69,7 @@ export function updateAnthropicModelInYaml(yamlContent: string, apiKey: string): doc.set('models', config.models); return doc.toString(); - } catch (error) { + } catch { // If parsing fails completely, create a new config const defaultConfig: ConfigStructure = { name: "Local Config", diff --git a/src/version.ts b/src/version.ts index 9d7a2282a..bf0906fc4 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1,7 +1,8 @@ import { readFileSync } from "fs"; import { dirname, join } from "path"; import { fileURLToPath } from "url"; -import logger from "./util/logger.js"; + +import { logger } from "./util/logger.js"; export function getVersion(): string { try { @@ -10,7 +11,7 @@ export function getVersion(): string { const packageJsonPath = join(__dirname, "../package.json"); const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf8")); return packageJson.version; - } catch (error) { + } catch { console.warn("Warning: Could not read version from package.json"); return "unknown"; } diff --git a/tsconfig.json b/tsconfig.json index c017885ba..1f00342ee 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -21,5 +21,5 @@ "inlineSources": true, "jsx": "react" }, - "include": ["src/**/*"] + "include": ["src/**/*", "vitest.setup.ts"] } diff --git a/vitest.setup.ts b/vitest.setup.ts index cc69749ee..86715ac60 100644 --- a/vitest.setup.ts +++ b/vitest.setup.ts @@ -1,4 +1,5 @@ import { vi } from "vitest"; + import { resetConsoleOverrides } from "./src/util/consoleOverride.js"; // Disable telemetry for tests @@ -17,7 +18,7 @@ afterEach(() => { // Reset console overrides to ensure clean state for each test try { resetConsoleOverrides(); - } catch (e) { + } catch { // Ignore errors when resetting console } }); \ No newline at end of file