Changesets · Branches · Tags · Compare
| Changeset | d0cd3fef8227dd9ea8a9f9448ea8cb8099a405db6caace20531b1ee56e80abc7 |
|---|---|
| Author | uinstinct <61635505+uinstinct@users.noreply.github.com> · 2025-06-19 13:05 +05:30 |
| Committer | uinstinct <61635505+uinstinct@users.noreply.github.com> · 2025-06-19 13:05 +05:30 |
| Parents | 16439cbc6ccd, 05a393b2fd55 |
113 files changed
modified .continue/rules/documentation-standards.md +105 −10
| @@ -1,16 +1,111 @@ | ||
| 1 | 1 | --- |
| 2 | -globs: docs/**/*.{md,mdx} | |
| 3 | -description: Standards for writing and maintaining Continue Docs | |
| 2 | +globs: docs/\*_/_.{md,mdx} | |
| 3 | +description: This style guide should be used as a reference for maintaining consistency across all Continue documentation | |
| 4 | +alwaysApply: false | |
| 4 | 5 | --- |
| 5 | 6 | |
| 6 | -# Continue Docs Standards | |
| 7 | +# Continue Documentation Style Guide | |
| 8 | + | |
| 9 | +## Overview | |
| 10 | + | |
| 11 | +## Writing Tone & Voice | |
| 12 | + | |
| 13 | +### Conversational and Direct | |
| 7 | 14 | |
| 8 | 15 | - Follow Docusaurus documentation standards |
| 9 | -- Include YAML frontmatter with title, description, and keywords | |
| 10 | -- Use consistent heading hierarchy starting with h2 (##) | |
| 11 | -- Include relevant Admonition components for tips, warnings, and info | |
| 12 | -- Use descriptive alt text for images | |
| 13 | -- Include cross-references to related documentation | |
| 14 | -- Reference other docs with relative paths | |
| 16 | +- Use simple, conversational language that gets straight to the point | |
| 17 | +- Avoid overly technical jargon when simpler terms work | |
| 18 | +- Write as if speaking directly to the developer using the tool | |
| 15 | 19 | - Keep paragraphs concise and scannable |
| 16 | -- Use code blocks with appropriate language tags | |
| 20 | + | |
| 21 | +**Example:** | |
| 22 | +✅ "You send it a question, and it replies with an answer" | |
| 23 | +❌ "The system processes user queries and generates corresponding responses" | |
| 24 | + | |
| 25 | +### Helpful and Instructional | |
| 26 | + | |
| 27 | +- Focus on helping users accomplish their goals | |
| 28 | +- Use active voice and imperative mood for instructions | |
| 29 | +- Assume users want to get things done quickly | |
| 30 | +- Include relevant Admonition components for tips, warnings, and info | |
| 31 | + | |
| 32 | +**Example:** | |
| 33 | +✅ "Press cmd/ctrl + L to begin a new session" | |
| 34 | +❌ "A new session can be initiated by pressing cmd/ctrl + L" | |
| 35 | + | |
| 36 | +### Practical and Task-Oriented | |
| 37 | + | |
| 38 | +- Emphasize what users can accomplish with each feature | |
| 39 | +- Lead with benefits and use cases before diving into mechanics | |
| 40 | +- Keep explanations grounded in real-world scenarios | |
| 41 | + | |
| 42 | +## Content Structure | |
| 43 | + | |
| 44 | +### Page Organization | |
| 45 | + | |
| 46 | +1. **Visual Introduction**: Lead with GIFs or images showing the feature in action | |
| 47 | +2. **Purpose Statement**: Brief explanation of what the feature does and when to use it | |
| 48 | +3. **Step-by-Step Instructions**: Clear, actionable steps with keyboard shortcuts | |
| 49 | +4. **Platform-Specific Notes**: Separate sections for VS Code and JetBrains when needed | |
| 50 | +5. **Additional Tips**: Advanced usage or troubleshooting notes | |
| 51 | + | |
| 52 | +### Section Headers | |
| 53 | + | |
| 54 | +- Use consistent heading hierarchy starting with h2 (##) | |
| 55 | +- Include YAML frontmatter with title, description, and keywords | |
| 56 | +- Use action-oriented headers that describe what users will do | |
| 57 | +- Format: "Verb + object" (e.g., "Type a request and press enter") | |
| 58 | +- Keep headers concise but descriptive | |
| 59 | +- Use title case | |
| 60 | + | |
| 61 | +**Examples:** | |
| 62 | +✅ "Highlight code and activate" | |
| 63 | +✅ "Accept or reject changes" | |
| 64 | +✅ "Switch between different models" | |
| 65 | + | |
| 66 | +### Lists and Steps | |
| 67 | + | |
| 68 | +- Use numbered lists for sequential steps | |
| 69 | +- Use bullet points for feature lists or options | |
| 70 | +- Keep list items parallel in structure | |
| 71 | +- Start action items with verbs | |
| 72 | + | |
| 73 | +## Technical Writing Standards | |
| 74 | + | |
| 75 | +### Code and Keyboard Shortcuts | |
| 76 | + | |
| 77 | +- Use `backticks` for inline code elements | |
| 78 | +- Format keyboard shortcuts consistently: `cmd/ctrl + L` | |
| 79 | +- Always provide shortcuts for Mac/Windows/Linux | |
| 80 | +- Use code blocks for configuration examples with proper syntax highlighting | |
| 81 | + | |
| 82 | +### Cross-References | |
| 83 | + | |
| 84 | +- Link to related sections using descriptive anchor text | |
| 85 | +- Use relative links to other documentation pages | |
| 86 | +- Format: `[descriptive text](/path/to/page)` | |
| 87 | + | |
| 88 | +### Platform Differences | |
| 89 | + | |
| 90 | +- Always address both VS Code and JetBrains when applicable | |
| 91 | +- Use clear subheadings to separate platform-specific instructions | |
| 92 | +- Lead with the more common platform (typically VS Code) when both are covered | |
| 93 | + | |
| 94 | +## Language Conventions | |
| 95 | + | |
| 96 | +### Terminology | |
| 97 | + | |
| 98 | +- **Consistent Terms**: Use the same terms throughout (e.g., "LLM" not "AI model" in some places) | |
| 99 | +- **Product Names**: Capitalize product names correctly (VS Code, JetBrains, Continue) | |
| 100 | +- **Feature Names**: Use consistent capitalization for Continue features (Chat, Edit, Agent, Autocomplete) | |
| 101 | + | |
| 102 | +### Abbreviations | |
| 103 | + | |
| 104 | +- Spell out acronyms on first use, then use abbreviation consistently | |
| 105 | +- Common abbreviations: LLM, IDE, API, URL | |
| 106 | + | |
| 107 | +### Pronouns | |
| 108 | + | |
| 109 | +- Use "you" to address the user directly | |
| 110 | +- Use "it" to refer to the tool/model | |
| 111 | +- Avoid "we" unless referring to the Continue team |
modified .eslintrc.shared.json +1 −0
| @@ -10,6 +10,7 @@ | ||
| 10 | 10 | "@typescript-eslint/naming-convention": "off", |
| 11 | 11 | "@typescript-eslint/no-floating-promises": "warn", |
| 12 | 12 | "@typescript-eslint/semi": "warn", |
| 13 | + "@typescript-eslint/no-misused-promises": "error", | |
| 13 | 14 | "curly": "warn", |
| 14 | 15 | "eqeqeq": "warn", |
| 15 | 16 | "no-throw-literal": "warn", |
modified .github/workflows/pr_checks.yaml +6 −1
| @@ -396,6 +396,11 @@ | ||
| 396 | 396 | npx tsc --noEmit |
| 397 | 397 | npm run lint |
| 398 | 398 | |
| 399 | + - name: Run vitest tests | |
| 400 | + run: | | |
| 401 | + cd extensions/vscode | |
| 402 | + npm run vitest | |
| 403 | + | |
| 399 | 404 | core-tests: |
| 400 | 405 | needs: [install-core, install-config-yaml] |
| 401 | 406 | runs-on: ubuntu-latest |
| @@ -434,7 +439,7 @@ | ||
| 434 | 439 | GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} |
| 435 | 440 | MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }} |
| 436 | 441 | AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }} |
| 437 | - AZURE_FOUNDRY_API_KEY: ${{ secrets.AZURE_FOUNDRY_API_KEY }} | |
| 442 | + AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }} | |
| 438 | 443 | AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }} |
| 439 | 444 | AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }} |
| 440 | 445 |
modified binary/package-lock.json +13 −1
| @@ -20,6 +20,7 @@ | ||
| 20 | 20 | "posthog-node": "^3.6.3", |
| 21 | 21 | "system-ca": "^1.0.2", |
| 22 | 22 | "tar": "^7.4.3", |
| 23 | + "undici": "^7.10.0", | |
| 23 | 24 | "uuid": "^9.0.1", |
| 24 | 25 | "vectordb": "^0.4.20", |
| 25 | 26 | "win-ca": "^3.5.1" |
| @@ -54,7 +55,7 @@ | ||
| 54 | 55 | "@continuedev/config-yaml": "file:../packages/config-yaml", |
| 55 | 56 | "@continuedev/fetch": "^1.0.13", |
| 56 | 57 | "@continuedev/llm-info": "^1.0.8", |
| 57 | - "@continuedev/openai-adapters": "^1.0.25", | |
| 58 | + "@continuedev/openai-adapters": "^1.0.32", | |
| 58 | 59 | "@modelcontextprotocol/sdk": "^1.12.0", |
| 59 | 60 | "@mozilla/readability": "^0.5.0", |
| 60 | 61 | "@octokit/rest": "^20.1.1", |
| @@ -105,6 +106,7 @@ | ||
| 105 | 106 | "sqlite3": "^5.1.7", |
| 106 | 107 | "system-ca": "^1.0.3", |
| 107 | 108 | "tar": "^7.4.3", |
| 109 | + "tree-sitter-structured-text": "^0.0.1", | |
| 108 | 110 | "tree-sitter-wasms": "^0.1.11", |
| 109 | 111 | "uuid": "^9.0.1", |
| 110 | 112 | "vectordb": "^0.4.20", |
| @@ -143,6 +145,7 @@ | ||
| 143 | 145 | "myers-diff": "^2.1.0", |
| 144 | 146 | "onnxruntime-common": "1.14.0", |
| 145 | 147 | "onnxruntime-web": "1.14.0", |
| 148 | + "tree-sitter-cli": "^0.22.5", | |
| 146 | 149 | "ts-jest": "^29.1.1", |
| 147 | 150 | "typescript": "^5.6.3", |
| 148 | 151 | "vitest": "^3.1.4" |
| @@ -6774,6 +6777,15 @@ | ||
| 6774 | 6777 | "node": ">=8" |
| 6775 | 6778 | } |
| 6776 | 6779 | }, |
| 6780 | + "node_modules/undici": { | |
| 6781 | + "version": "7.10.0", | |
| 6782 | + "resolved": "https://registry.npmmirror.com/undici/-/undici-7.10.0.tgz", | |
| 6783 | + "integrity": "sha512-u5otvFBOBZvmdjWLVW+5DAc9Nkq8f24g0O9oY7qw2JVIF1VocIFoyz9JFkuVOS2j41AufeO0xnlweJ2RLT8nGw==", | |
| 6784 | + "license": "MIT", | |
| 6785 | + "engines": { | |
| 6786 | + "node": ">=20.18.1" | |
| 6787 | + } | |
| 6788 | + }, | |
| 6777 | 6789 | "node_modules/universal-user-agent": { |
| 6778 | 6790 | "version": "6.0.1", |
| 6779 | 6791 | "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.1.tgz", |
modified binary/package.json +1 −0
| @@ -53,6 +53,7 @@ | ||
| 53 | 53 | "posthog-node": "^3.6.3", |
| 54 | 54 | "system-ca": "^1.0.2", |
| 55 | 55 | "tar": "^7.4.3", |
| 56 | + "undici": "^7.10.0", | |
| 56 | 57 | "uuid": "^9.0.1", |
| 57 | 58 | "vectordb": "^0.4.20", |
| 58 | 59 | "win-ca": "^3.5.1" |
modified binary/utils/ripgrep.js +6 −0
| @@ -4,6 +4,7 @@ | ||
| 4 | 4 | const tar = require("tar"); |
| 5 | 5 | const { RIPGREP_VERSION, TARGET_TO_RIPGREP_RELEASE } = require("./targets"); |
| 6 | 6 | const AdmZip = require("adm-zip"); |
| 7 | +const { ProxyAgent } = require("undici"); | |
| 7 | 8 | |
| 8 | 9 | const RIPGREP_BASE_URL = `https://github.com/BurntSushi/ripgrep/releases/download/${RIPGREP_VERSION}`; |
| 9 | 10 | |
| @@ -16,8 +17,13 @@ | ||
| 16 | 17 | */ |
| 17 | 18 | async function downloadFile(url, destPath) { |
| 18 | 19 | // Use the built-in fetch API instead of node-fetch |
| 20 | + // Use proxy if set in environment variables | |
| 21 | + const proxy = process.env.https_proxy || process.env.HTTPS_PROXY; | |
| 22 | + const agent = proxy ? new ProxyAgent(proxy) : undefined; | |
| 23 | + | |
| 19 | 24 | const response = await fetch(url, { |
| 20 | 25 | redirect: "follow", // Automatically follow redirects |
| 26 | + dispatcher: agent, | |
| 21 | 27 | }); |
| 22 | 28 | |
| 23 | 29 | if (!response.ok) { |
deleted core/autocomplete/context/root-path-context/test/RootPathContextService.test.ts +0 −56
| @@ -1,56 +0,0 @@ | ||
| 1 | -import { PYTHON_TEST_CASES, TYPESCRIPT_TEST_CASES } from "./testCases"; | |
| 2 | -import { testRootPathContext } from "./testUtils"; | |
| 3 | - | |
| 4 | -const TEST_CASES = [ | |
| 5 | - ...PYTHON_TEST_CASES, | |
| 6 | - ...TYPESCRIPT_TEST_CASES, | |
| 7 | - { | |
| 8 | - nodeType: "function_definition", | |
| 9 | - fileName: "file1.php", | |
| 10 | - language: "PHP", | |
| 11 | - cursorPosition: { line: 12, character: 32 }, | |
| 12 | - definitionPositions: [ | |
| 13 | - { row: 10, column: 26 }, // Person | |
| 14 | - { row: 10, column: 44 }, // Address | |
| 15 | - ], | |
| 16 | - }, | |
| 17 | - { | |
| 18 | - nodeType: "method_declaration", | |
| 19 | - fileName: "file1.php", | |
| 20 | - language: "PHP", | |
| 21 | - cursorPosition: { line: 26, character: 35 }, | |
| 22 | - definitionPositions: [ | |
| 23 | - { row: 15, column: 29 }, // BaseClass | |
| 24 | - { row: 15, column: 55 }, // FirstInterface | |
| 25 | - { row: 15, column: 72 }, // SecondInterface | |
| 26 | - { row: 25, column: 43 }, // Person | |
| 27 | - { row: 25, column: 61 }, // Address | |
| 28 | - ], | |
| 29 | - }, | |
| 30 | - { | |
| 31 | - nodeType: "function_declaration", | |
| 32 | - fileName: "file1.go", | |
| 33 | - language: "Go", | |
| 34 | - cursorPosition: { line: 7, character: 21 }, | |
| 35 | - definitionPositions: [ | |
| 36 | - { row: 6, column: 33 }, // models.User | |
| 37 | - { row: 6, column: 50 }, // models.Address | |
| 38 | - ], | |
| 39 | - }, | |
| 40 | -]; | |
| 41 | - | |
| 42 | -describe("RootPathContextService", () => { | |
| 43 | - describe("should look for correct type definitions", () => { | |
| 44 | - test.each(TEST_CASES)( | |
| 45 | - "$language: $nodeType", | |
| 46 | - async ({ fileName, cursorPosition, definitionPositions }) => { | |
| 47 | - await testRootPathContext( | |
| 48 | - "files", | |
| 49 | - fileName, | |
| 50 | - cursorPosition, | |
| 51 | - definitionPositions, | |
| 52 | - ); | |
| 53 | - }, | |
| 54 | - ); | |
| 55 | - }); | |
| 56 | -}); |
added core/autocomplete/context/root-path-context/test/RootPathContextService.vitest.ts +57 −0
| @@ -0,0 +1,57 @@ | ||
| 1 | +import { describe, test } from "vitest"; | |
| 2 | +import { PYTHON_TEST_CASES, TYPESCRIPT_TEST_CASES } from "./testCases"; | |
| 3 | +import { testRootPathContext } from "./testUtils"; | |
| 4 | + | |
| 5 | +const TEST_CASES = [ | |
| 6 | + ...PYTHON_TEST_CASES, | |
| 7 | + ...TYPESCRIPT_TEST_CASES, | |
| 8 | + { | |
| 9 | + nodeType: "function_definition", | |
| 10 | + fileName: "file1.php", | |
| 11 | + language: "PHP", | |
| 12 | + cursorPosition: { line: 12, character: 32 }, | |
| 13 | + definitionPositions: [ | |
| 14 | + { row: 10, column: 26 }, // Person | |
| 15 | + { row: 10, column: 44 }, // Address | |
| 16 | + ], | |
| 17 | + }, | |
| 18 | + { | |
| 19 | + nodeType: "method_declaration", | |
| 20 | + fileName: "file1.php", | |
| 21 | + language: "PHP", | |
| 22 | + cursorPosition: { line: 26, character: 35 }, | |
| 23 | + definitionPositions: [ | |
| 24 | + { row: 15, column: 29 }, // BaseClass | |
| 25 | + { row: 15, column: 55 }, // FirstInterface | |
| 26 | + { row: 15, column: 72 }, // SecondInterface | |
| 27 | + { row: 25, column: 43 }, // Person | |
| 28 | + { row: 25, column: 61 }, // Address | |
| 29 | + ], | |
| 30 | + }, | |
| 31 | + { | |
| 32 | + nodeType: "function_declaration", | |
| 33 | + fileName: "file1.go", | |
| 34 | + language: "Go", | |
| 35 | + cursorPosition: { line: 7, character: 21 }, | |
| 36 | + definitionPositions: [ | |
| 37 | + { row: 6, column: 33 }, // models.User | |
| 38 | + { row: 6, column: 50 }, // models.Address | |
| 39 | + ], | |
| 40 | + }, | |
| 41 | +]; | |
| 42 | + | |
| 43 | +describe("RootPathContextService", () => { | |
| 44 | + describe("should look for correct type definitions", () => { | |
| 45 | + test.each(TEST_CASES)( | |
| 46 | + "$language: $nodeType", | |
| 47 | + async ({ fileName, cursorPosition, definitionPositions }) => { | |
| 48 | + await testRootPathContext( | |
| 49 | + "files", | |
| 50 | + fileName, | |
| 51 | + cursorPosition, | |
| 52 | + definitionPositions, | |
| 53 | + ); | |
| 54 | + }, | |
| 55 | + ); | |
| 56 | + }); | |
| 57 | +}); |
modified core/autocomplete/context/root-path-context/test/testUtils.ts +4 −4
| @@ -1,6 +1,6 @@ | ||
| 1 | -import { jest } from "@jest/globals"; | |
| 2 | 1 | import fs from "fs"; |
| 3 | 2 | import path from "path"; |
| 3 | +import { expect, vi } from "vitest"; | |
| 4 | 4 | |
| 5 | 5 | import Parser from "web-tree-sitter"; |
| 6 | 6 | import { Position } from "../../../.."; |
| @@ -36,17 +36,17 @@ | ||
| 36 | 36 | const importDefinitionsService = new ImportDefinitionsService(ide); |
| 37 | 37 | const service = new RootPathContextService(importDefinitionsService, ide); |
| 38 | 38 | |
| 39 | - const getSnippetsMock = jest | |
| 39 | + const getSnippetsMock = vi | |
| 40 | 40 | // @ts-ignore |
| 41 | 41 | .spyOn(service, "getSnippets") |
| 42 | 42 | // @ts-ignore |
| 43 | - .mockImplementation(async (_filepath, _endPosition) => { | |
| 43 | + .mockImplementation((_filePath, _endPosition) => { | |
| 44 | 44 | return []; |
| 45 | 45 | }); |
| 46 | 46 | |
| 47 | 47 | // Copy the folder to the test directory |
| 48 | 48 | const folderPath = path.join( |
| 49 | - __dirname, | |
| 49 | + process.cwd(), | |
| 50 | 50 | "autocomplete", |
| 51 | 51 | "context", |
| 52 | 52 | "root-path-context", |
deleted core/autocomplete/filtering/streamTransforms/charStream.test.ts +0 −215
| @@ -1,215 +0,0 @@ | ||
| 1 | -import { stopAtStartOf, stopAtStopTokens } from "./charStream"; | |
| 2 | - | |
| 3 | -async function* createMockStream(chunks: string[]): AsyncGenerator<string> { | |
| 4 | - for (const chunk of chunks) { | |
| 5 | - yield chunk; | |
| 6 | - } | |
| 7 | -} | |
| 8 | - | |
| 9 | -async function streamToString(stream: AsyncGenerator<string>): Promise<string> { | |
| 10 | - let result = ""; | |
| 11 | - for await (const chunk of stream) { | |
| 12 | - result += chunk; | |
| 13 | - } | |
| 14 | - return result; | |
| 15 | -} | |
| 16 | - | |
| 17 | -describe("stopAtStopTokens", () => { | |
| 18 | - it("should yield characters until a stop token is encountered", async () => { | |
| 19 | - const mockStream = createMockStream(["Hello", " world", "! Stop", "here"]); | |
| 20 | - const stopTokens = ["Stop"]; | |
| 21 | - const result = stopAtStopTokens(mockStream, stopTokens); | |
| 22 | - | |
| 23 | - const output = []; | |
| 24 | - for await (const char of result) { | |
| 25 | - output.push(char); | |
| 26 | - } | |
| 27 | - | |
| 28 | - expect(output.join("")).toBe("Hello world! "); | |
| 29 | - }); | |
| 30 | - | |
| 31 | - it("should handle multiple stop tokens", async () => { | |
| 32 | - const mockStream = createMockStream([ | |
| 33 | - "This", | |
| 34 | - " is a ", | |
| 35 | - "test. END", | |
| 36 | - " of stream", | |
| 37 | - ]); | |
| 38 | - const stopTokens = ["END", "STOP", "HALT"]; | |
| 39 | - const result = stopAtStopTokens(mockStream, stopTokens); | |
| 40 | - | |
| 41 | - expect(await streamToString(result)).toBe("This is a test. "); | |
| 42 | - }); | |
| 43 | - | |
| 44 | - it("should handle stop tokens split across chunks", async () => { | |
| 45 | - const mockStream = createMockStream([ | |
| 46 | - "Hello", | |
| 47 | - " wo", | |
| 48 | - "r", | |
| 49 | - "ld! ST", | |
| 50 | - "OP now", | |
| 51 | - ]); | |
| 52 | - const stopTokens = ["STOP"]; | |
| 53 | - const result = stopAtStopTokens(mockStream, stopTokens); | |
| 54 | - | |
| 55 | - const output = []; | |
| 56 | - for await (const char of result) { | |
| 57 | - output.push(char); | |
| 58 | - } | |
| 59 | - | |
| 60 | - expect(output.join("")).toBe("Hello world! "); | |
| 61 | - }); | |
| 62 | - | |
| 63 | - it("should yield all characters if no stop token is encountered", async () => { | |
| 64 | - const mockStream = createMockStream([ | |
| 65 | - "This", | |
| 66 | - " is ", | |
| 67 | - "a complete", | |
| 68 | - " stream", | |
| 69 | - ]); | |
| 70 | - const stopTokens = ["END"]; | |
| 71 | - const result = stopAtStopTokens(mockStream, stopTokens); | |
| 72 | - | |
| 73 | - expect(await streamToString(result)).toBe("This is a complete stream"); | |
| 74 | - }); | |
| 75 | - | |
| 76 | - it("should handle empty chunks", async () => { | |
| 77 | - const mockStream = createMockStream(["Hello", "", " world", "", "! STOP"]); | |
| 78 | - const stopTokens = ["STOP"]; | |
| 79 | - const result = stopAtStopTokens(mockStream, stopTokens); | |
| 80 | - | |
| 81 | - expect(await streamToString(result)).toBe("Hello world! "); | |
| 82 | - }); | |
| 83 | - | |
| 84 | - it("should handle stop token at the beginning of the stream", async () => { | |
| 85 | - const mockStream = createMockStream(["STOP", "Hello world"]); | |
| 86 | - const stopTokens = ["STOP"]; | |
| 87 | - const result = stopAtStopTokens(mockStream, stopTokens); | |
| 88 | - | |
| 89 | - const output = []; | |
| 90 | - for await (const char of result) { | |
| 91 | - output.push(char); | |
| 92 | - } | |
| 93 | - | |
| 94 | - expect(output.join("")).toBe(""); | |
| 95 | - }); | |
| 96 | - | |
| 97 | - it("should handle stop token at the end of the stream", async () => { | |
| 98 | - const mockStream = createMockStream(["Hello world", "STOP"]); | |
| 99 | - const stopTokens = ["STOP"]; | |
| 100 | - const result = stopAtStopTokens(mockStream, stopTokens); | |
| 101 | - | |
| 102 | - expect(await streamToString(result)).toBe("Hello world"); | |
| 103 | - }); | |
| 104 | - | |
| 105 | - it("should handle multiple stop tokens of different lengths", async () => { | |
| 106 | - const mockStream = createMockStream([ | |
| 107 | - "This is a ", | |
| 108 | - "test with ", | |
| 109 | - "multiple STOP", | |
| 110 | - " tokens END", | |
| 111 | - ]); | |
| 112 | - const stopTokens = ["STOP", "END", "HALT"]; | |
| 113 | - const result = stopAtStopTokens(mockStream, stopTokens); | |
| 114 | - | |
| 115 | - expect(await streamToString(result)).toBe("This is a test with multiple "); | |
| 116 | - }); | |
| 117 | - | |
| 118 | - it("should handle an empty stream", async () => { | |
| 119 | - const mockStream = createMockStream([]); | |
| 120 | - const stopTokens = ["STOP"]; | |
| 121 | - const result = stopAtStopTokens(mockStream, stopTokens); | |
| 122 | - | |
| 123 | - expect(await streamToString(result)).toBe(""); | |
| 124 | - }); | |
| 125 | - | |
| 126 | - it("should handle an empty stop tokens array", async () => { | |
| 127 | - const mockStream = createMockStream(["Hello", " world!"]); | |
| 128 | - const stopTokens: string[] = []; | |
| 129 | - const result = stopAtStopTokens(mockStream, stopTokens); | |
| 130 | - | |
| 131 | - const output = []; | |
| 132 | - for await (const char of result) { | |
| 133 | - output.push(char); | |
| 134 | - } | |
| 135 | - | |
| 136 | - expect(output.join("")).toBe("Hello world!"); | |
| 137 | - }); | |
| 138 | - | |
| 139 | - it("should handle stop token when remaining buffer is smaller than maximum stop token length", async () => { | |
| 140 | - const mockStream = createMockStream(["Hello world!STOP"]); | |
| 141 | - const stopTokens: string[] = [ | |
| 142 | - "STOP", | |
| 143 | - "STOP_TOKEN_THAT_IS_LARGER_THAN_BUFFER", | |
| 144 | - ]; | |
| 145 | - const result = stopAtStopTokens(mockStream, stopTokens); | |
| 146 | - | |
| 147 | - expect(await streamToString(result)).toBe("Hello world!"); | |
| 148 | - }); | |
| 149 | -}); | |
| 150 | - | |
| 151 | -describe("stopAtStartOf", () => { | |
| 152 | - const sampleCode = ` { | |
| 153 | - method: "GET", | |
| 154 | - headers: { | |
| 155 | - "Content-Type": "application/json", | |
| 156 | - Authorization: \`Bearer \${this.workOsAccessToken}\`, | |
| 157 | - }, | |
| 158 | - }, | |
| 159 | - ); | |
| 160 | - const data = await response.json(); | |
| 161 | - return data.items; | |
| 162 | - } | |
| 163 | - | |
| 164 | - async getContextItems( | |
| 165 | - query: string, | |
| 166 | - extras: ContextProviderExtras, | |
| 167 | - ): Promise<ContextItem[]> { | |
| 168 | - const response = await extras.fetch( | |
| 169 | - new URL( | |
| 170 | - \`/proxy/context/\${this.options.id}/retrieve\`, | |
| 171 | - controlPlaneEnv.CONTROL_PLANE_URL, | |
| 172 | - ), | |
| 173 | -`; | |
| 174 | - | |
| 175 | - /* Some LLMs, such as Codestral, repeat the suffix of the query. To test our filtering, we cut the sample code at random positions, remove a part of the input | |
| 176 | -and construct a response, containing the removed part and the suffix. The goal of the stopAtStartOf() method is to detect the start of the suffix in the response */ | |
| 177 | - it("should stop if the start of the suffix is reached", async () => { | |
| 178 | - const suffix = ` | |
| 179 | - const data = await response.json(); | |
| 180 | - return data.items; | |
| 181 | -}`; | |
| 182 | - const mockStream = createMockStream(sampleCode.split(/(?! )/g)); | |
| 183 | - const result = stopAtStartOf(mockStream, suffix); | |
| 184 | - | |
| 185 | - const resultStr = await streamToString(result); | |
| 186 | - expect(resultStr).toBe(` { | |
| 187 | - method: "GET", | |
| 188 | - headers: { | |
| 189 | - "Content-Type": "application/json", | |
| 190 | - Authorization: \`Bearer \${this.workOsAccessToken}\`, | |
| 191 | - }, | |
| 192 | - }, | |
| 193 | - ); | |
| 194 | - `); | |
| 195 | - }); | |
| 196 | - it("should stop if the start of the suffix is reached, even if the suffix has a prefix", async () => { | |
| 197 | - const suffix = ` | |
| 198 | - xxxconst data = await response.json(); | |
| 199 | - return data.items; | |
| 200 | -}`; | |
| 201 | - const mockStream = createMockStream(sampleCode.split(/(?! )/g)); | |
| 202 | - const result = stopAtStartOf(mockStream, suffix); | |
| 203 | - | |
| 204 | - const resultStr = await streamToString(result); | |
| 205 | - expect(resultStr).toBe(` { | |
| 206 | - method: "GET", | |
| 207 | - headers: { | |
| 208 | - "Content-Type": "application/json", | |
| 209 | - Authorization: \`Bearer \${this.workOsAccessToken}\`, | |
| 210 | - }, | |
| 211 | - }, | |
| 212 | - ); | |
| 213 | - `); | |
| 214 | - }); | |
| 215 | -}); |
added core/autocomplete/filtering/streamTransforms/charStream.vitest.ts +216 −0
| @@ -0,0 +1,216 @@ | ||
| 1 | +import { describe, expect, it } from "vitest"; | |
| 2 | +import { stopAtStartOf, stopAtStopTokens } from "./charStream"; | |
| 3 | + | |
| 4 | +async function* createMockStream(chunks: string[]): AsyncGenerator<string> { | |
| 5 | + for (const chunk of chunks) { | |
| 6 | + yield chunk; | |
| 7 | + } | |
| 8 | +} | |
| 9 | + | |
| 10 | +async function streamToString(stream: AsyncGenerator<string>): Promise<string> { | |
| 11 | + let result = ""; | |
| 12 | + for await (const chunk of stream) { | |
| 13 | + result += chunk; | |
| 14 | + } | |
| 15 | + return result; | |
| 16 | +} | |
| 17 | + | |
| 18 | +describe("stopAtStopTokens", () => { | |
| 19 | + it("should yield characters until a stop token is encountered", async () => { | |
| 20 | + const mockStream = createMockStream(["Hello", " world", "! Stop", "here"]); | |
| 21 | + const stopTokens = ["Stop"]; | |
| 22 | + const result = stopAtStopTokens(mockStream, stopTokens); | |
| 23 | + | |
| 24 | + const output = []; | |
| 25 | + for await (const char of result) { | |
| 26 | + output.push(char); | |
| 27 | + } | |
| 28 | + | |
| 29 | + expect(output.join("")).toBe("Hello world! "); | |
| 30 | + }); | |
| 31 | + | |
| 32 | + it("should handle multiple stop tokens", async () => { | |
| 33 | + const mockStream = createMockStream([ | |
| 34 | + "This", | |
| 35 | + " is a ", | |
| 36 | + "test. END", | |
| 37 | + " of stream", | |
| 38 | + ]); | |
| 39 | + const stopTokens = ["END", "STOP", "HALT"]; | |
| 40 | + const result = stopAtStopTokens(mockStream, stopTokens); | |
| 41 | + | |
| 42 | + expect(await streamToString(result)).toBe("This is a test. "); | |
| 43 | + }); | |
| 44 | + | |
| 45 | + it("should handle stop tokens split across chunks", async () => { | |
| 46 | + const mockStream = createMockStream([ | |
| 47 | + "Hello", | |
| 48 | + " wo", | |
| 49 | + "r", | |
| 50 | + "ld! ST", | |
| 51 | + "OP now", | |
| 52 | + ]); | |
| 53 | + const stopTokens = ["STOP"]; | |
| 54 | + const result = stopAtStopTokens(mockStream, stopTokens); | |
| 55 | + | |
| 56 | + const output = []; | |
| 57 | + for await (const char of result) { | |
| 58 | + output.push(char); | |
| 59 | + } | |
| 60 | + | |
| 61 | + expect(output.join("")).toBe("Hello world! "); | |
| 62 | + }); | |
| 63 | + | |
| 64 | + it("should yield all characters if no stop token is encountered", async () => { | |
| 65 | + const mockStream = createMockStream([ | |
| 66 | + "This", | |
| 67 | + " is ", | |
| 68 | + "a complete", | |
| 69 | + " stream", | |
| 70 | + ]); | |
| 71 | + const stopTokens = ["END"]; | |
| 72 | + const result = stopAtStopTokens(mockStream, stopTokens); | |
| 73 | + | |
| 74 | + expect(await streamToString(result)).toBe("This is a complete stream"); | |
| 75 | + }); | |
| 76 | + | |
| 77 | + it("should handle empty chunks", async () => { | |
| 78 | + const mockStream = createMockStream(["Hello", "", " world", "", "! STOP"]); | |
| 79 | + const stopTokens = ["STOP"]; | |
| 80 | + const result = stopAtStopTokens(mockStream, stopTokens); | |
| 81 | + | |
| 82 | + expect(await streamToString(result)).toBe("Hello world! "); | |
| 83 | + }); | |
| 84 | + | |
| 85 | + it("should handle stop token at the beginning of the stream", async () => { | |
| 86 | + const mockStream = createMockStream(["STOP", "Hello world"]); | |
| 87 | + const stopTokens = ["STOP"]; | |
| 88 | + const result = stopAtStopTokens(mockStream, stopTokens); | |
| 89 | + | |
| 90 | + const output = []; | |
| 91 | + for await (const char of result) { | |
| 92 | + output.push(char); | |
| 93 | + } | |
| 94 | + | |
| 95 | + expect(output.join("")).toBe(""); | |
| 96 | + }); | |
| 97 | + | |
| 98 | + it("should handle stop token at the end of the stream", async () => { | |
| 99 | + const mockStream = createMockStream(["Hello world", "STOP"]); | |
| 100 | + const stopTokens = ["STOP"]; | |
| 101 | + const result = stopAtStopTokens(mockStream, stopTokens); | |
| 102 | + | |
| 103 | + expect(await streamToString(result)).toBe("Hello world"); | |
| 104 | + }); | |
| 105 | + | |
| 106 | + it("should handle multiple stop tokens of different lengths", async () => { | |
| 107 | + const mockStream = createMockStream([ | |
| 108 | + "This is a ", | |
| 109 | + "test with ", | |
| 110 | + "multiple STOP", | |
| 111 | + " tokens END", | |
| 112 | + ]); | |
| 113 | + const stopTokens = ["STOP", "END", "HALT"]; | |
| 114 | + const result = stopAtStopTokens(mockStream, stopTokens); | |
| 115 | + | |
| 116 | + expect(await streamToString(result)).toBe("This is a test with multiple "); | |
| 117 | + }); | |
| 118 | + | |
| 119 | + it("should handle an empty stream", async () => { | |
| 120 | + const mockStream = createMockStream([]); | |
| 121 | + const stopTokens = ["STOP"]; | |
| 122 | + const result = stopAtStopTokens(mockStream, stopTokens); | |
| 123 | + | |
| 124 | + expect(await streamToString(result)).toBe(""); | |
| 125 | + }); | |
| 126 | + | |
| 127 | + it("should handle an empty stop tokens array", async () => { | |
| 128 | + const mockStream = createMockStream(["Hello", " world!"]); | |
| 129 | + const stopTokens: string[] = []; | |
| 130 | + const result = stopAtStopTokens(mockStream, stopTokens); | |
| 131 | + | |
| 132 | + const output = []; | |
| 133 | + for await (const char of result) { | |
| 134 | + output.push(char); | |
| 135 | + } | |
| 136 | + | |
| 137 | + expect(output.join("")).toBe("Hello world!"); | |
| 138 | + }); | |
| 139 | + | |
| 140 | + it("should handle stop token when remaining buffer is smaller than maximum stop token length", async () => { | |
| 141 | + const mockStream = createMockStream(["Hello world!STOP"]); | |
| 142 | + const stopTokens: string[] = [ | |
| 143 | + "STOP", | |
| 144 | + "STOP_TOKEN_THAT_IS_LARGER_THAN_BUFFER", | |
| 145 | + ]; | |
| 146 | + const result = stopAtStopTokens(mockStream, stopTokens); | |
| 147 | + | |
| 148 | + expect(await streamToString(result)).toBe("Hello world!"); | |
| 149 | + }); | |
| 150 | +}); | |
| 151 | + | |
| 152 | +describe("stopAtStartOf", () => { | |
| 153 | + const sampleCode = ` { | |
| 154 | + method: "GET", | |
| 155 | + headers: { | |
| 156 | + "Content-Type": "application/json", | |
| 157 | + Authorization: \`Bearer \${this.workOsAccessToken}\`, | |
| 158 | + }, | |
| 159 | + }, | |
| 160 | + ); | |
| 161 | + const data = await response.json(); | |
| 162 | + return data.items; | |
| 163 | + } | |
| 164 | + | |
| 165 | + async getContextItems( | |
| 166 | + query: string, | |
| 167 | + extras: ContextProviderExtras, | |
| 168 | + ): Promise<ContextItem[]> { | |
| 169 | + const response = await extras.fetch( | |
| 170 | + new URL( | |
| 171 | + \`/proxy/context/\${this.options.id}/retrieve\`, | |
| 172 | + controlPlaneEnv.CONTROL_PLANE_URL, | |
| 173 | + ), | |
| 174 | +`; | |
| 175 | + | |
| 176 | + /* Some LLMs, such as Codestral, repeat the suffix of the query. To test our filtering, we cut the sample code at random positions, remove a part of the input | |
| 177 | +and construct a response, containing the removed part and the suffix. The goal of the stopAtStartOf() method is to detect the start of the suffix in the response */ | |
| 178 | + it("should stop if the start of the suffix is reached", async () => { | |
| 179 | + const suffix = ` | |
| 180 | + const data = await response.json(); | |
| 181 | + return data.items; | |
| 182 | +}`; | |
| 183 | + const mockStream = createMockStream(sampleCode.split(/(?! )/g)); | |
| 184 | + const result = stopAtStartOf(mockStream, suffix); | |
| 185 | + | |
| 186 | + const resultStr = await streamToString(result); | |
| 187 | + expect(resultStr).toBe(` { | |
| 188 | + method: "GET", | |
| 189 | + headers: { | |
| 190 | + "Content-Type": "application/json", | |
| 191 | + Authorization: \`Bearer \${this.workOsAccessToken}\`, | |
| 192 | + }, | |
| 193 | + }, | |
| 194 | + ); | |
| 195 | + `); | |
| 196 | + }); | |
| 197 | + it("should stop if the start of the suffix is reached, even if the suffix has a prefix", async () => { | |
| 198 | + const suffix = ` | |
| 199 | + xxxconst data = await response.json(); | |
| 200 | + return data.items; | |
| 201 | +}`; | |
| 202 | + const mockStream = createMockStream(sampleCode.split(/(?! )/g)); | |
| 203 | + const result = stopAtStartOf(mockStream, suffix); | |
| 204 | + | |
| 205 | + const resultStr = await streamToString(result); | |
| 206 | + expect(resultStr).toBe(` { | |
| 207 | + method: "GET", | |
| 208 | + headers: { | |
| 209 | + "Content-Type": "application/json", | |
| 210 | + Authorization: \`Bearer \${this.workOsAccessToken}\`, | |
| 211 | + }, | |
| 212 | + }, | |
| 213 | + ); | |
| 214 | + `); | |
| 215 | + }); | |
| 216 | +}); |
deleted core/autocomplete/filtering/streamTransforms/lineStream.test.ts +0 −616
| @@ -1,616 +0,0 @@ | ||
| 1 | -import { jest } from "@jest/globals"; | |
| 2 | - | |
| 3 | -import * as lineStream from "./lineStream"; | |
| 4 | - | |
| 5 | -// eslint-disable-next-line max-lines-per-function | |
| 6 | -describe("lineStream", () => { | |
| 7 | - let mockFullStop: jest.Mock; | |
| 8 | - | |
| 9 | - async function getLineGenerator(lines: any) { | |
| 10 | - return (async function* () { | |
| 11 | - for (const line of lines) { | |
| 12 | - yield line; | |
| 13 | - } | |
| 14 | - })(); | |
| 15 | - } | |
| 16 | - | |
| 17 | - async function getFilteredLines(results: any) { | |
| 18 | - const output = []; | |
| 19 | - | |
| 20 | - for await (const line of results) { | |
| 21 | - output.push(line); | |
| 22 | - } | |
| 23 | - | |
| 24 | - return output; | |
| 25 | - } | |
| 26 | - | |
| 27 | - beforeEach(() => { | |
| 28 | - mockFullStop = jest.fn(); | |
| 29 | - }); | |
| 30 | - | |
| 31 | - describe("noTopLevelKeywordsMidline", () => { | |
| 32 | - it.todo("Need some sample inputs to properly test this"); | |
| 33 | - }); | |
| 34 | - | |
| 35 | - describe("avoidPathLine", () => { | |
| 36 | - it("should filter out path lines", async () => { | |
| 37 | - const linesGenerator = await getLineGenerator([ | |
| 38 | - "// Path: src/index.ts", | |
| 39 | - "const x = 5;", | |
| 40 | - "//", | |
| 41 | - "console.log(x);", | |
| 42 | - ]); | |
| 43 | - const result = lineStream.avoidPathLine(linesGenerator, "//"); | |
| 44 | - const filteredLines = await getFilteredLines(result); | |
| 45 | - expect(filteredLines).toEqual(["const x = 5;", "//", "console.log(x);"]); | |
| 46 | - }); | |
| 47 | - }); | |
| 48 | - | |
| 49 | - describe("avoidEmptyComments", () => { | |
| 50 | - it("should filter out empty comments", async () => { | |
| 51 | - const linesGenerator = await getLineGenerator([ | |
| 52 | - "// Path: src/index.ts", | |
| 53 | - "const x = 5;", | |
| 54 | - "//", | |
| 55 | - "console.log(x);", | |
| 56 | - ]); | |
| 57 | - const result = lineStream.avoidEmptyComments(linesGenerator, "//"); | |
| 58 | - const filteredLines = await getFilteredLines(result); | |
| 59 | - expect(filteredLines).toEqual([ | |
| 60 | - "// Path: src/index.ts", | |
| 61 | - "const x = 5;", | |
| 62 | - "console.log(x);", | |
| 63 | - ]); | |
| 64 | - }); | |
| 65 | - }); | |
| 66 | - | |
| 67 | - describe("streamWithNewLines", () => { | |
| 68 | - it("should add newlines between lines", async () => { | |
| 69 | - const linesGenerator = await getLineGenerator([ | |
| 70 | - "line1", | |
| 71 | - "line2", | |
| 72 | - "line3", | |
| 73 | - ]); | |
| 74 | - | |
| 75 | - const result = lineStream.streamWithNewLines(linesGenerator); | |
| 76 | - const filteredLines = await getFilteredLines(result); | |
| 77 | - | |
| 78 | - expect(filteredLines).toEqual(["line1", "\n", "line2", "\n", "line3"]); | |
| 79 | - }); | |
| 80 | - }); | |
| 81 | - | |
| 82 | - describe("lineIsRepeated", () => { | |
| 83 | - it("should return true for similar lines", () => { | |
| 84 | - expect(lineStream.lineIsRepeated("const x = 5;", "const x = 6;")).toBe( | |
| 85 | - true, | |
| 86 | - ); | |
| 87 | - }); | |
| 88 | - | |
| 89 | - it("should return false for different lines", () => { | |
| 90 | - expect(lineStream.lineIsRepeated("const x = 5;", "let y = 10;")).toBe( | |
| 91 | - false, | |
| 92 | - ); | |
| 93 | - }); | |
| 94 | - | |
| 95 | - it("should return false for short lines", () => { | |
| 96 | - expect(lineStream.lineIsRepeated("x=5", "x=6")).toBe(false); | |
| 97 | - }); | |
| 98 | - }); | |
| 99 | - | |
| 100 | - describe("stopAtSimilarLine", () => { | |
| 101 | - it("should stop at the exact same line", async () => { | |
| 102 | - const lineToTest = "const x = 6"; | |
| 103 | - const linesGenerator = await getLineGenerator([ | |
| 104 | - "console.log();", | |
| 105 | - "const y = () => {};", | |
| 106 | - lineToTest, | |
| 107 | - ]); | |
| 108 | - | |
| 109 | - const result = lineStream.stopAtSimilarLine( | |
| 110 | - linesGenerator, | |
| 111 | - lineToTest, | |
| 112 | - mockFullStop, | |
| 113 | - ); | |
| 114 | - const filteredLines = await getFilteredLines(result); | |
| 115 | - | |
| 116 | - expect(filteredLines).toEqual(["console.log();", "const y = () => {};"]); | |
| 117 | - expect(mockFullStop).toHaveBeenCalledTimes(1); | |
| 118 | - }); | |
| 119 | - | |
| 120 | - it("should stop at a similar line", async () => { | |
| 121 | - const lineToTest = "const x = 6;"; | |
| 122 | - const linesGenerator = await getLineGenerator([ | |
| 123 | - "console.log();", | |
| 124 | - "const y = () => {};", | |
| 125 | - lineToTest, | |
| 126 | - ]); | |
| 127 | - | |
| 128 | - const result = lineStream.stopAtSimilarLine( | |
| 129 | - linesGenerator, | |
| 130 | - "a" + lineToTest, | |
| 131 | - mockFullStop, | |
| 132 | - ); | |
| 133 | - const filteredLines = await getFilteredLines(result); | |
| 134 | - | |
| 135 | - expect(filteredLines).toEqual(["console.log();", "const y = () => {};"]); | |
| 136 | - expect(mockFullStop).toHaveBeenCalledTimes(1); | |
| 137 | - }); | |
| 138 | - | |
| 139 | - it("should continue on bracket ending lines", async () => { | |
| 140 | - const linesGenerator = await getLineGenerator([ | |
| 141 | - " if (x > 0) {", | |
| 142 | - " console.log(x);", | |
| 143 | - " }", | |
| 144 | - ]); | |
| 145 | - | |
| 146 | - const result = lineStream.stopAtSimilarLine( | |
| 147 | - linesGenerator, | |
| 148 | - "}", | |
| 149 | - mockFullStop, | |
| 150 | - ); | |
| 151 | - const filteredLines = await getFilteredLines(result); | |
| 152 | - | |
| 153 | - expect(filteredLines).toEqual([ | |
| 154 | - " if (x > 0) {", | |
| 155 | - " console.log(x);", | |
| 156 | - " }", | |
| 157 | - ]); | |
| 158 | - expect(mockFullStop).toHaveBeenCalledTimes(0); | |
| 159 | - }); | |
| 160 | - }); | |
| 161 | - | |
| 162 | - describe("stopAtLines", () => { | |
| 163 | - it("should stop at specified lines", async () => { | |
| 164 | - const linesGenerator = await getLineGenerator([ | |
| 165 | - "const x = 5;", | |
| 166 | - "let y = 10;", | |
| 167 | - lineStream.LINES_TO_STOP_AT[0], | |
| 168 | - "const z = 15;", | |
| 169 | - ]); | |
| 170 | - | |
| 171 | - const result = lineStream.stopAtLines(linesGenerator, mockFullStop); | |
| 172 | - const filteredLines = await getFilteredLines(result); | |
| 173 | - | |
| 174 | - expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); | |
| 175 | - expect(mockFullStop).toHaveBeenCalledTimes(1); | |
| 176 | - }); | |
| 177 | - }); | |
| 178 | - | |
| 179 | - describe("skipPrefixes", () => { | |
| 180 | - it("should skip specified prefixes", async () => { | |
| 181 | - const linesGenerator = await getLineGenerator([ | |
| 182 | - `${lineStream.PREFIXES_TO_SKIP[0]}const x = 5;`, | |
| 183 | - "let y = 10;", | |
| 184 | - ]); | |
| 185 | - | |
| 186 | - const result = lineStream.skipPrefixes(linesGenerator); | |
| 187 | - const filteredLines = await getFilteredLines(result); | |
| 188 | - | |
| 189 | - expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); | |
| 190 | - }); | |
| 191 | - }); | |
| 192 | - | |
| 193 | - describe("skipLines", () => { | |
| 194 | - it("should skip specified lines", async () => { | |
| 195 | - const linesGenerator = await getLineGenerator([ | |
| 196 | - `${lineStream.LINES_TO_SKIP[0]}const x = 5;`, | |
| 197 | - "let y = 10;", | |
| 198 | - ]); | |
| 199 | - | |
| 200 | - const result = lineStream.skipLines(linesGenerator); | |
| 201 | - const filteredLines = await getFilteredLines(result); | |
| 202 | - | |
| 203 | - expect(filteredLines).toEqual(["let y = 10;"]); | |
| 204 | - }); | |
| 205 | - }); | |
| 206 | - | |
| 207 | - describe("filterCodeBlockLines", () => { | |
| 208 | - it("should handle unfenced code", async () => { | |
| 209 | - const linesGenerator = await getLineGenerator(["const x = 5;"]); | |
| 210 | - | |
| 211 | - const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 212 | - const filteredLines = await getFilteredLines(result); | |
| 213 | - | |
| 214 | - expect(filteredLines).toEqual(["const x = 5;"]); | |
| 215 | - }); | |
| 216 | - | |
| 217 | - it("should handle unfenced code with a code block", async () => { | |
| 218 | - const linesGenerator = await getLineGenerator([ | |
| 219 | - "const x = 5;", | |
| 220 | - "```bash", | |
| 221 | - "ls -al", | |
| 222 | - "```", | |
| 223 | - ]); | |
| 224 | - | |
| 225 | - const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 226 | - const filteredLines = await getFilteredLines(result); | |
| 227 | - | |
| 228 | - expect(filteredLines).toEqual([ | |
| 229 | - "const x = 5;", | |
| 230 | - "```bash", | |
| 231 | - "ls -al", | |
| 232 | - "```", | |
| 233 | - ]); | |
| 234 | - }); | |
| 235 | - | |
| 236 | - it("should handle unfenced code with two code blocks", async () => { | |
| 237 | - const linesGenerator = await getLineGenerator([ | |
| 238 | - "const x = 5;", | |
| 239 | - "```bash", | |
| 240 | - "ls -al", | |
| 241 | - "```", | |
| 242 | - "```bash", | |
| 243 | - "ls -al", | |
| 244 | - "```", | |
| 245 | - ]); | |
| 246 | - | |
| 247 | - const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 248 | - const filteredLines = await getFilteredLines(result); | |
| 249 | - | |
| 250 | - expect(filteredLines).toEqual([ | |
| 251 | - "const x = 5;", | |
| 252 | - "```bash", | |
| 253 | - "ls -al", | |
| 254 | - "```", | |
| 255 | - "```bash", | |
| 256 | - "ls -al", | |
| 257 | - "```", | |
| 258 | - ]); | |
| 259 | - }); | |
| 260 | - | |
| 261 | - it("should remove lines before the first valid line", async () => { | |
| 262 | - const linesGenerator = await getLineGenerator(["```ts", "const x = 5;"]); | |
| 263 | - | |
| 264 | - const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 265 | - const filteredLines = await getFilteredLines(result); | |
| 266 | - | |
| 267 | - expect(filteredLines).toEqual(["const x = 5;"]); | |
| 268 | - }); | |
| 269 | - | |
| 270 | - it("should remove outer blocks", async () => { | |
| 271 | - const linesGenerator = await getLineGenerator([ | |
| 272 | - "```ts", | |
| 273 | - "const x = 5;", | |
| 274 | - "```", | |
| 275 | - ]); | |
| 276 | - | |
| 277 | - const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 278 | - const filteredLines = await getFilteredLines(result); | |
| 279 | - | |
| 280 | - expect(filteredLines).toEqual(["const x = 5;"]); | |
| 281 | - }); | |
| 282 | - | |
| 283 | - it("should leave inner blocks intact", async () => { | |
| 284 | - const linesGenerator = await getLineGenerator([ | |
| 285 | - "```md", | |
| 286 | - "const x = 5;", | |
| 287 | - "```bash", | |
| 288 | - "ls -al", | |
| 289 | - "```", | |
| 290 | - "```", | |
| 291 | - ]); | |
| 292 | - | |
| 293 | - const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 294 | - const filteredLines = await getFilteredLines(result); | |
| 295 | - | |
| 296 | - expect(filteredLines).toEqual([ | |
| 297 | - "const x = 5;", | |
| 298 | - "```bash", | |
| 299 | - "ls -al", | |
| 300 | - "```", | |
| 301 | - ]); | |
| 302 | - }); | |
| 303 | - | |
| 304 | - it("should handle included inner ticks", async () => { | |
| 305 | - const linesGenerator = await getLineGenerator([ | |
| 306 | - "```md", | |
| 307 | - "const x = 5;", | |
| 308 | - "```bash", | |
| 309 | - "echo ```test```", | |
| 310 | - "```", | |
| 311 | - "```", | |
| 312 | - ]); | |
| 313 | - | |
| 314 | - const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 315 | - const filteredLines = await getFilteredLines(result); | |
| 316 | - | |
| 317 | - expect(filteredLines).toEqual([ | |
| 318 | - "const x = 5;", | |
| 319 | - "```bash", | |
| 320 | - "echo ```test```", | |
| 321 | - "```", | |
| 322 | - ]); | |
| 323 | - }); | |
| 324 | - | |
| 325 | - it("should leave single inner blocks intact but not return trailing text", async () => { | |
| 326 | - const linesGenerator = await getLineGenerator([ | |
| 327 | - "```md", | |
| 328 | - "const x = 5;", | |
| 329 | - "```bash", | |
| 330 | - "ls -al", | |
| 331 | - "```", | |
| 332 | - "```", | |
| 333 | - "trailing text", | |
| 334 | - ]); | |
| 335 | - | |
| 336 | - const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 337 | - const filteredLines = await getFilteredLines(result); | |
| 338 | - | |
| 339 | - expect(filteredLines).toEqual([ | |
| 340 | - "const x = 5;", | |
| 341 | - "```bash", | |
| 342 | - "ls -al", | |
| 343 | - "```", | |
| 344 | - ]); | |
| 345 | - }); | |
| 346 | - | |
| 347 | - it("should leave double inner blocks intact but not return trailing text", async () => { | |
| 348 | - const linesGenerator = await getLineGenerator([ | |
| 349 | - "```md", | |
| 350 | - "const x = 5;", | |
| 351 | - "```bash", | |
| 352 | - "ls -al", | |
| 353 | - "```", | |
| 354 | - "const y = 10;", | |
| 355 | - "```sh", | |
| 356 | - "echo `hello world`", | |
| 357 | - "```", | |
| 358 | - "```", | |
| 359 | - "trailing text", | |
| 360 | - ]); | |
| 361 | - | |
| 362 | - const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 363 | - const filteredLines = await getFilteredLines(result); | |
| 364 | - | |
| 365 | - expect(filteredLines).toEqual([ | |
| 366 | - "const x = 5;", | |
| 367 | - "```bash", | |
| 368 | - "ls -al", | |
| 369 | - "```", | |
| 370 | - "const y = 10;", | |
| 371 | - "```sh", | |
| 372 | - "echo `hello world`", | |
| 373 | - "```", | |
| 374 | - ]); | |
| 375 | - }); | |
| 376 | - | |
| 377 | - it("should leave inner blocks intact but not return trailing or leading text", async () => { | |
| 378 | - const linesGenerator = await getLineGenerator([ | |
| 379 | - "[CODE]", | |
| 380 | - "const x = 5;", | |
| 381 | - "```bash", | |
| 382 | - "ls -al", | |
| 383 | - "```", | |
| 384 | - "[/CODE]", | |
| 385 | - "trailing text", | |
| 386 | - ]); | |
| 387 | - | |
| 388 | - const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 389 | - const filteredLines = await getFilteredLines(result); | |
| 390 | - | |
| 391 | - expect(filteredLines).toEqual([ | |
| 392 | - "const x = 5;", | |
| 393 | - "```bash", | |
| 394 | - "ls -al", | |
| 395 | - "```", | |
| 396 | - ]); | |
| 397 | - }); | |
| 398 | - }); | |
| 399 | - | |
| 400 | - describe("filterEnglishLinesAtStart", () => { | |
| 401 | - it("should skip initial empty line", async () => { | |
| 402 | - const linesGenerator = await getLineGenerator([ | |
| 403 | - "", | |
| 404 | - "const x = 5;", | |
| 405 | - "let y = 10;", | |
| 406 | - ]); | |
| 407 | - | |
| 408 | - const result = lineStream.filterEnglishLinesAtStart(linesGenerator); | |
| 409 | - const filteredLines = await getFilteredLines(result); | |
| 410 | - | |
| 411 | - expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); | |
| 412 | - }); | |
| 413 | - | |
| 414 | - it("should filter out English first line", async () => { | |
| 415 | - const linesGenerator = await getLineGenerator([ | |
| 416 | - lineStream.ENGLISH_START_PHRASES[0], | |
| 417 | - "let y = 10;", | |
| 418 | - ]); | |
| 419 | - | |
| 420 | - const result = lineStream.filterEnglishLinesAtStart(linesGenerator); | |
| 421 | - const filteredLines = await getFilteredLines(result); | |
| 422 | - | |
| 423 | - expect(filteredLines).toEqual(["let y = 10;"]); | |
| 424 | - }); | |
| 425 | - | |
| 426 | - it("should not filter out non-English first line", async () => { | |
| 427 | - const linesGenerator = await getLineGenerator([ | |
| 428 | - "const x = 5;", | |
| 429 | - "let y = 10;", | |
| 430 | - ]); | |
| 431 | - | |
| 432 | - const result = lineStream.filterEnglishLinesAtStart(linesGenerator); | |
| 433 | - const filteredLines = await getFilteredLines(result); | |
| 434 | - | |
| 435 | - expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); | |
| 436 | - }); | |
| 437 | - | |
| 438 | - it("should filter out empty newline after first line english word", async () => { | |
| 439 | - const linesGenerator = await getLineGenerator([ | |
| 440 | - lineStream.ENGLISH_START_PHRASES[0], | |
| 441 | - "", | |
| 442 | - "const x = 5;", | |
| 443 | - ]); | |
| 444 | - | |
| 445 | - const result = lineStream.filterEnglishLinesAtStart(linesGenerator); | |
| 446 | - const filteredLines = await getFilteredLines(result); | |
| 447 | - | |
| 448 | - expect(filteredLines).toEqual(["const x = 5;"]); | |
| 449 | - }); | |
| 450 | - | |
| 451 | - it("should filter out sentences ending in a semi-colon that are not code keywords", async () => { | |
| 452 | - const linesGenerator = await getLineGenerator([ | |
| 453 | - "a" + lineStream.CODE_KEYWORDS_ENDING_IN_SEMICOLON[0] + ":", | |
| 454 | - "const x = 5;", | |
| 455 | - ]); | |
| 456 | - | |
| 457 | - const result = lineStream.filterEnglishLinesAtStart(linesGenerator); | |
| 458 | - const filteredLines = await getFilteredLines(result); | |
| 459 | - | |
| 460 | - expect(filteredLines).toEqual(["const x = 5;"]); | |
| 461 | - }); | |
| 462 | - | |
| 463 | - it("should not filter out sentences ending in a semi-colon that are code keywords", async () => { | |
| 464 | - const keyword = lineStream.CODE_KEYWORDS_ENDING_IN_SEMICOLON[0] + ":"; | |
| 465 | - | |
| 466 | - const linesGenerator = await getLineGenerator([keyword, "const x = 5;"]); | |
| 467 | - | |
| 468 | - const result = lineStream.filterEnglishLinesAtStart(linesGenerator); | |
| 469 | - const filteredLines = await getFilteredLines(result); | |
| 470 | - | |
| 471 | - expect(filteredLines).toEqual([keyword, "const x = 5;"]); | |
| 472 | - }); | |
| 473 | - }); | |
| 474 | - | |
| 475 | - describe("filterEnglishLinesAtEnd", () => { | |
| 476 | - it("should stop at English explanation after code block", async () => { | |
| 477 | - const linesGenerator = await getLineGenerator([ | |
| 478 | - "const x = 5;", | |
| 479 | - "```", | |
| 480 | - lineStream.ENGLISH_POST_PHRASES[0], | |
| 481 | - ]); | |
| 482 | - | |
| 483 | - const result = lineStream.filterEnglishLinesAtEnd(linesGenerator); | |
| 484 | - const filteredLines = await getFilteredLines(result); | |
| 485 | - | |
| 486 | - expect(filteredLines).toEqual(["const x = 5;", "```"]); | |
| 487 | - }); | |
| 488 | - }); | |
| 489 | - | |
| 490 | - describe("fixCodeLlamaFirstLineIndentation", () => { | |
| 491 | - it("should fix indentation of the first line", async () => { | |
| 492 | - const linesGenerator = await getLineGenerator([ | |
| 493 | - " const x = 5;", | |
| 494 | - "let y = 10;", | |
| 495 | - ]); | |
| 496 | - | |
| 497 | - const result = | |
| 498 | - lineStream.fixCodeLlamaFirstLineIndentation(linesGenerator); | |
| 499 | - const filteredLines = await getFilteredLines(result); | |
| 500 | - | |
| 501 | - expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); | |
| 502 | - }); | |
| 503 | - }); | |
| 504 | - | |
| 505 | - describe("filterLeadingAndTrailingNewLineInsertion", () => { | |
| 506 | - it("should ignore 'useless' new first lines", async () => { | |
| 507 | - const linesGenerator = await getLineGenerator([ | |
| 508 | - { type: "new", line: lineStream.USELESS_LINES[0] }, | |
| 509 | - { type: "new", line: "const x = 5;" }, | |
| 510 | - ]); | |
| 511 | - | |
| 512 | - const result = | |
| 513 | - lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator); | |
| 514 | - const filteredLines = await getFilteredLines(result); | |
| 515 | - | |
| 516 | - expect(filteredLines).toEqual([{ type: "new", line: "const x = 5;" }]); | |
| 517 | - }); | |
| 518 | - | |
| 519 | - it("should handle preserve newlines chars in old lines", async () => { | |
| 520 | - const linesGenerator = await getLineGenerator([ | |
| 521 | - { type: "new", line: "const x = 5;" }, | |
| 522 | - { type: "old", line: "let y = 10;" }, | |
| 523 | - { type: "old", line: "" }, | |
| 524 | - { type: "new", line: "const z = 15;" }, | |
| 525 | - ]); | |
| 526 | - | |
| 527 | - const result = | |
| 528 | - lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator); | |
| 529 | - const filteredLines = await getFilteredLines(result); | |
| 530 | - | |
| 531 | - expect(filteredLines).toEqual([ | |
| 532 | - { type: "new", line: "const x = 5;" }, | |
| 533 | - { type: "old", line: "let y = 10;" }, | |
| 534 | - { type: "old", line: "" }, | |
| 535 | - { type: "new", line: "const z = 15;" }, | |
| 536 | - ]); | |
| 537 | - }); | |
| 538 | - | |
| 539 | - it("should filter leading and trailing new line insertions", async () => { | |
| 540 | - const linesGenerator = await getLineGenerator([ | |
| 541 | - { type: "new", line: "" }, | |
| 542 | - { type: "new", line: "const x = 5;" }, | |
| 543 | - { type: "new", line: "let y = 10;" }, | |
| 544 | - { type: "new", line: "" }, | |
| 545 | - ]); | |
| 546 | - | |
| 547 | - const result = | |
| 548 | - lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator); | |
| 549 | - const filteredLines = await getFilteredLines(result); | |
| 550 | - | |
| 551 | - expect(filteredLines).toEqual([ | |
| 552 | - { type: "new", line: "const x = 5;" }, | |
| 553 | - { type: "new", line: "let y = 10;" }, | |
| 554 | - ]); | |
| 555 | - }); | |
| 556 | - | |
| 557 | - it("should buffer newline chars and then render them if we encounter another non-empty line", async () => { | |
| 558 | - const linesGenerator = await getLineGenerator([ | |
| 559 | - { type: "new", line: "const x = 5;" }, | |
| 560 | - { type: "new", line: "" }, | |
| 561 | - { type: "new", line: "let y = 10;" }, | |
| 562 | - ]); | |
| 563 | - | |
| 564 | - const result = | |
| 565 | - lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator); | |
| 566 | - const filteredLines = await getFilteredLines(result); | |
| 567 | - | |
| 568 | - expect(filteredLines).toEqual([ | |
| 569 | - { type: "new", line: "const x = 5;" }, | |
| 570 | - { type: "new", line: "" }, | |
| 571 | - { type: "new", line: "let y = 10;" }, | |
| 572 | - ]); | |
| 573 | - }); | |
| 574 | - }); | |
| 575 | - | |
| 576 | - describe("stopAtRepeatingLines", () => { | |
| 577 | - it("should handle non-repeating lines correctly", async () => { | |
| 578 | - const linesGenerator = await getLineGenerator([ | |
| 579 | - "const x = 5;", | |
| 580 | - "let y = 10;", | |
| 581 | - "const z = 15;", | |
| 582 | - ]); | |
| 583 | - | |
| 584 | - const result = lineStream.stopAtRepeatingLines( | |
| 585 | - linesGenerator, | |
| 586 | - mockFullStop, | |
| 587 | - ); | |
| 588 | - const filteredLines = await getFilteredLines(result); | |
| 589 | - | |
| 590 | - expect(filteredLines).toEqual([ | |
| 591 | - "const x = 5;", | |
| 592 | - "let y = 10;", | |
| 593 | - "const z = 15;", | |
| 594 | - ]); | |
| 595 | - }); | |
| 596 | - | |
| 597 | - it("should stop at repeating lines", async () => { | |
| 598 | - const linesGenerator = await getLineGenerator([ | |
| 599 | - "const x = 5;", | |
| 600 | - "let y = 10;", | |
| 601 | - "let y = 10;", | |
| 602 | - "let y = 10;", | |
| 603 | - "const z = 15;", | |
| 604 | - ]); | |
| 605 | - | |
| 606 | - const result = lineStream.stopAtRepeatingLines( | |
| 607 | - linesGenerator, | |
| 608 | - mockFullStop, | |
| 609 | - ); | |
| 610 | - const filteredLines = await getFilteredLines(result); | |
| 611 | - | |
| 612 | - expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); | |
| 613 | - expect(mockFullStop).toHaveBeenCalledTimes(1); | |
| 614 | - }); | |
| 615 | - }); | |
| 616 | -}); |
added core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts +616 −0
| @@ -0,0 +1,616 @@ | ||
| 1 | +import { beforeEach, describe, expect, it, Mock, vi } from "vitest"; | |
| 2 | + | |
| 3 | +import * as lineStream from "./lineStream"; | |
| 4 | + | |
| 5 | +// eslint-disable-next-line max-lines-per-function | |
| 6 | +describe("lineStream", () => { | |
| 7 | + let mockFullStop: Mock; | |
| 8 | + | |
| 9 | + async function getLineGenerator(lines: any) { | |
| 10 | + return (async function* () { | |
| 11 | + for (const line of lines) { | |
| 12 | + yield line; | |
| 13 | + } | |
| 14 | + })(); | |
| 15 | + } | |
| 16 | + | |
| 17 | + async function getFilteredLines(results: any) { | |
| 18 | + const output = []; | |
| 19 | + | |
| 20 | + for await (const line of results) { | |
| 21 | + output.push(line); | |
| 22 | + } | |
| 23 | + | |
| 24 | + return output; | |
| 25 | + } | |
| 26 | + | |
| 27 | + beforeEach(() => { | |
| 28 | + mockFullStop = vi.fn(); | |
| 29 | + }); | |
| 30 | + | |
| 31 | + describe("noTopLevelKeywordsMidline", () => { | |
| 32 | + it.todo("Need some sample inputs to properly test this"); | |
| 33 | + }); | |
| 34 | + | |
| 35 | + describe("avoidPathLine", () => { | |
| 36 | + it("should filter out path lines", async () => { | |
| 37 | + const linesGenerator = await getLineGenerator([ | |
| 38 | + "// Path: src/index.ts", | |
| 39 | + "const x = 5;", | |
| 40 | + "//", | |
| 41 | + "console.log(x);", | |
| 42 | + ]); | |
| 43 | + const result = lineStream.avoidPathLine(linesGenerator, "//"); | |
| 44 | + const filteredLines = await getFilteredLines(result); | |
| 45 | + expect(filteredLines).toEqual(["const x = 5;", "//", "console.log(x);"]); | |
| 46 | + }); | |
| 47 | + }); | |
| 48 | + | |
| 49 | + describe("avoidEmptyComments", () => { | |
| 50 | + it("should filter out empty comments", async () => { | |
| 51 | + const linesGenerator = await getLineGenerator([ | |
| 52 | + "// Path: src/index.ts", | |
| 53 | + "const x = 5;", | |
| 54 | + "//", | |
| 55 | + "console.log(x);", | |
| 56 | + ]); | |
| 57 | + const result = lineStream.avoidEmptyComments(linesGenerator, "//"); | |
| 58 | + const filteredLines = await getFilteredLines(result); | |
| 59 | + expect(filteredLines).toEqual([ | |
| 60 | + "// Path: src/index.ts", | |
| 61 | + "const x = 5;", | |
| 62 | + "console.log(x);", | |
| 63 | + ]); | |
| 64 | + }); | |
| 65 | + }); | |
| 66 | + | |
| 67 | + describe("streamWithNewLines", () => { | |
| 68 | + it("should add newlines between lines", async () => { | |
| 69 | + const linesGenerator = await getLineGenerator([ | |
| 70 | + "line1", | |
| 71 | + "line2", | |
| 72 | + "line3", | |
| 73 | + ]); | |
| 74 | + | |
| 75 | + const result = lineStream.streamWithNewLines(linesGenerator); | |
| 76 | + const filteredLines = await getFilteredLines(result); | |
| 77 | + | |
| 78 | + expect(filteredLines).toEqual(["line1", "\n", "line2", "\n", "line3"]); | |
| 79 | + }); | |
| 80 | + }); | |
| 81 | + | |
| 82 | + describe("lineIsRepeated", () => { | |
| 83 | + it("should return true for similar lines", () => { | |
| 84 | + expect(lineStream.lineIsRepeated("const x = 5;", "const x = 6;")).toBe( | |
| 85 | + true, | |
| 86 | + ); | |
| 87 | + }); | |
| 88 | + | |
| 89 | + it("should return false for different lines", () => { | |
| 90 | + expect(lineStream.lineIsRepeated("const x = 5;", "let y = 10;")).toBe( | |
| 91 | + false, | |
| 92 | + ); | |
| 93 | + }); | |
| 94 | + | |
| 95 | + it("should return false for short lines", () => { | |
| 96 | + expect(lineStream.lineIsRepeated("x=5", "x=6")).toBe(false); | |
| 97 | + }); | |
| 98 | + }); | |
| 99 | + | |
| 100 | + describe("stopAtSimilarLine", () => { | |
| 101 | + it("should stop at the exact same line", async () => { | |
| 102 | + const lineToTest = "const x = 6"; | |
| 103 | + const linesGenerator = await getLineGenerator([ | |
| 104 | + "console.log();", | |
| 105 | + "const y = () => {};", | |
| 106 | + lineToTest, | |
| 107 | + ]); | |
| 108 | + | |
| 109 | + const result = lineStream.stopAtSimilarLine( | |
| 110 | + linesGenerator, | |
| 111 | + lineToTest, | |
| 112 | + mockFullStop, | |
| 113 | + ); | |
| 114 | + const filteredLines = await getFilteredLines(result); | |
| 115 | + | |
| 116 | + expect(filteredLines).toEqual(["console.log();", "const y = () => {};"]); | |
| 117 | + expect(mockFullStop).toHaveBeenCalledTimes(1); | |
| 118 | + }); | |
| 119 | + | |
| 120 | + it("should stop at a similar line", async () => { | |
| 121 | + const lineToTest = "const x = 6;"; | |
| 122 | + const linesGenerator = await getLineGenerator([ | |
| 123 | + "console.log();", | |
| 124 | + "const y = () => {};", | |
| 125 | + lineToTest, | |
| 126 | + ]); | |
| 127 | + | |
| 128 | + const result = lineStream.stopAtSimilarLine( | |
| 129 | + linesGenerator, | |
| 130 | + "a" + lineToTest, | |
| 131 | + mockFullStop, | |
| 132 | + ); | |
| 133 | + const filteredLines = await getFilteredLines(result); | |
| 134 | + | |
| 135 | + expect(filteredLines).toEqual(["console.log();", "const y = () => {};"]); | |
| 136 | + expect(mockFullStop).toHaveBeenCalledTimes(1); | |
| 137 | + }); | |
| 138 | + | |
| 139 | + it("should continue on bracket ending lines", async () => { | |
| 140 | + const linesGenerator = await getLineGenerator([ | |
| 141 | + " if (x > 0) {", | |
| 142 | + " console.log(x);", | |
| 143 | + " }", | |
| 144 | + ]); | |
| 145 | + | |
| 146 | + const result = lineStream.stopAtSimilarLine( | |
| 147 | + linesGenerator, | |
| 148 | + "}", | |
| 149 | + mockFullStop, | |
| 150 | + ); | |
| 151 | + const filteredLines = await getFilteredLines(result); | |
| 152 | + | |
| 153 | + expect(filteredLines).toEqual([ | |
| 154 | + " if (x > 0) {", | |
| 155 | + " console.log(x);", | |
| 156 | + " }", | |
| 157 | + ]); | |
| 158 | + expect(mockFullStop).toHaveBeenCalledTimes(0); | |
| 159 | + }); | |
| 160 | + }); | |
| 161 | + | |
| 162 | + describe("stopAtLines", () => { | |
| 163 | + it("should stop at specified lines", async () => { | |
| 164 | + const linesGenerator = await getLineGenerator([ | |
| 165 | + "const x = 5;", | |
| 166 | + "let y = 10;", | |
| 167 | + lineStream.LINES_TO_STOP_AT[0], | |
| 168 | + "const z = 15;", | |
| 169 | + ]); | |
| 170 | + | |
| 171 | + const result = lineStream.stopAtLines(linesGenerator, mockFullStop); | |
| 172 | + const filteredLines = await getFilteredLines(result); | |
| 173 | + | |
| 174 | + expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); | |
| 175 | + expect(mockFullStop).toHaveBeenCalledTimes(1); | |
| 176 | + }); | |
| 177 | + }); | |
| 178 | + | |
| 179 | + describe("skipPrefixes", () => { | |
| 180 | + it("should skip specified prefixes", async () => { | |
| 181 | + const linesGenerator = await getLineGenerator([ | |
| 182 | + `${lineStream.PREFIXES_TO_SKIP[0]}const x = 5;`, | |
| 183 | + "let y = 10;", | |
| 184 | + ]); | |
| 185 | + | |
| 186 | + const result = lineStream.skipPrefixes(linesGenerator); | |
| 187 | + const filteredLines = await getFilteredLines(result); | |
| 188 | + | |
| 189 | + expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); | |
| 190 | + }); | |
| 191 | + }); | |
| 192 | + | |
| 193 | + describe("skipLines", () => { | |
| 194 | + it("should skip specified lines", async () => { | |
| 195 | + const linesGenerator = await getLineGenerator([ | |
| 196 | + `${lineStream.LINES_TO_SKIP[0]}const x = 5;`, | |
| 197 | + "let y = 10;", | |
| 198 | + ]); | |
| 199 | + | |
| 200 | + const result = lineStream.skipLines(linesGenerator); | |
| 201 | + const filteredLines = await getFilteredLines(result); | |
| 202 | + | |
| 203 | + expect(filteredLines).toEqual(["let y = 10;"]); | |
| 204 | + }); | |
| 205 | + }); | |
| 206 | + | |
| 207 | + describe("filterCodeBlockLines", () => { | |
| 208 | + it("should handle unfenced code", async () => { | |
| 209 | + const linesGenerator = await getLineGenerator(["const x = 5;"]); | |
| 210 | + | |
| 211 | + const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 212 | + const filteredLines = await getFilteredLines(result); | |
| 213 | + | |
| 214 | + expect(filteredLines).toEqual(["const x = 5;"]); | |
| 215 | + }); | |
| 216 | + | |
| 217 | + it("should handle unfenced code with a code block", async () => { | |
| 218 | + const linesGenerator = await getLineGenerator([ | |
| 219 | + "const x = 5;", | |
| 220 | + "```bash", | |
| 221 | + "ls -al", | |
| 222 | + "```", | |
| 223 | + ]); | |
| 224 | + | |
| 225 | + const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 226 | + const filteredLines = await getFilteredLines(result); | |
| 227 | + | |
| 228 | + expect(filteredLines).toEqual([ | |
| 229 | + "const x = 5;", | |
| 230 | + "```bash", | |
| 231 | + "ls -al", | |
| 232 | + "```", | |
| 233 | + ]); | |
| 234 | + }); | |
| 235 | + | |
| 236 | + it("should handle unfenced code with two code blocks", async () => { | |
| 237 | + const linesGenerator = await getLineGenerator([ | |
| 238 | + "const x = 5;", | |
| 239 | + "```bash", | |
| 240 | + "ls -al", | |
| 241 | + "```", | |
| 242 | + "```bash", | |
| 243 | + "ls -al", | |
| 244 | + "```", | |
| 245 | + ]); | |
| 246 | + | |
| 247 | + const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 248 | + const filteredLines = await getFilteredLines(result); | |
| 249 | + | |
| 250 | + expect(filteredLines).toEqual([ | |
| 251 | + "const x = 5;", | |
| 252 | + "```bash", | |
| 253 | + "ls -al", | |
| 254 | + "```", | |
| 255 | + "```bash", | |
| 256 | + "ls -al", | |
| 257 | + "```", | |
| 258 | + ]); | |
| 259 | + }); | |
| 260 | + | |
| 261 | + it("should remove lines before the first valid line", async () => { | |
| 262 | + const linesGenerator = await getLineGenerator(["```ts", "const x = 5;"]); | |
| 263 | + | |
| 264 | + const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 265 | + const filteredLines = await getFilteredLines(result); | |
| 266 | + | |
| 267 | + expect(filteredLines).toEqual(["const x = 5;"]); | |
| 268 | + }); | |
| 269 | + | |
| 270 | + it("should remove outer blocks", async () => { | |
| 271 | + const linesGenerator = await getLineGenerator([ | |
| 272 | + "```ts", | |
| 273 | + "const x = 5;", | |
| 274 | + "```", | |
| 275 | + ]); | |
| 276 | + | |
| 277 | + const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 278 | + const filteredLines = await getFilteredLines(result); | |
| 279 | + | |
| 280 | + expect(filteredLines).toEqual(["const x = 5;"]); | |
| 281 | + }); | |
| 282 | + | |
| 283 | + it("should leave inner blocks intact", async () => { | |
| 284 | + const linesGenerator = await getLineGenerator([ | |
| 285 | + "```md", | |
| 286 | + "const x = 5;", | |
| 287 | + "```bash", | |
| 288 | + "ls -al", | |
| 289 | + "```", | |
| 290 | + "```", | |
| 291 | + ]); | |
| 292 | + | |
| 293 | + const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 294 | + const filteredLines = await getFilteredLines(result); | |
| 295 | + | |
| 296 | + expect(filteredLines).toEqual([ | |
| 297 | + "const x = 5;", | |
| 298 | + "```bash", | |
| 299 | + "ls -al", | |
| 300 | + "```", | |
| 301 | + ]); | |
| 302 | + }); | |
| 303 | + | |
| 304 | + it("should handle included inner ticks", async () => { | |
| 305 | + const linesGenerator = await getLineGenerator([ | |
| 306 | + "```md", | |
| 307 | + "const x = 5;", | |
| 308 | + "```bash", | |
| 309 | + "echo ```test```", | |
| 310 | + "```", | |
| 311 | + "```", | |
| 312 | + ]); | |
| 313 | + | |
| 314 | + const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 315 | + const filteredLines = await getFilteredLines(result); | |
| 316 | + | |
| 317 | + expect(filteredLines).toEqual([ | |
| 318 | + "const x = 5;", | |
| 319 | + "```bash", | |
| 320 | + "echo ```test```", | |
| 321 | + "```", | |
| 322 | + ]); | |
| 323 | + }); | |
| 324 | + | |
| 325 | + it("should leave single inner blocks intact but not return trailing text", async () => { | |
| 326 | + const linesGenerator = await getLineGenerator([ | |
| 327 | + "```md", | |
| 328 | + "const x = 5;", | |
| 329 | + "```bash", | |
| 330 | + "ls -al", | |
| 331 | + "```", | |
| 332 | + "```", | |
| 333 | + "trailing text", | |
| 334 | + ]); | |
| 335 | + | |
| 336 | + const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 337 | + const filteredLines = await getFilteredLines(result); | |
| 338 | + | |
| 339 | + expect(filteredLines).toEqual([ | |
| 340 | + "const x = 5;", | |
| 341 | + "```bash", | |
| 342 | + "ls -al", | |
| 343 | + "```", | |
| 344 | + ]); | |
| 345 | + }); | |
| 346 | + | |
| 347 | + it("should leave double inner blocks intact but not return trailing text", async () => { | |
| 348 | + const linesGenerator = await getLineGenerator([ | |
| 349 | + "```md", | |
| 350 | + "const x = 5;", | |
| 351 | + "```bash", | |
| 352 | + "ls -al", | |
| 353 | + "```", | |
| 354 | + "const y = 10;", | |
| 355 | + "```sh", | |
| 356 | + "echo `hello world`", | |
| 357 | + "```", | |
| 358 | + "```", | |
| 359 | + "trailing text", | |
| 360 | + ]); | |
| 361 | + | |
| 362 | + const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 363 | + const filteredLines = await getFilteredLines(result); | |
| 364 | + | |
| 365 | + expect(filteredLines).toEqual([ | |
| 366 | + "const x = 5;", | |
| 367 | + "```bash", | |
| 368 | + "ls -al", | |
| 369 | + "```", | |
| 370 | + "const y = 10;", | |
| 371 | + "```sh", | |
| 372 | + "echo `hello world`", | |
| 373 | + "```", | |
| 374 | + ]); | |
| 375 | + }); | |
| 376 | + | |
| 377 | + it("should leave inner blocks intact but not return trailing or leading text", async () => { | |
| 378 | + const linesGenerator = await getLineGenerator([ | |
| 379 | + "[CODE]", | |
| 380 | + "const x = 5;", | |
| 381 | + "```bash", | |
| 382 | + "ls -al", | |
| 383 | + "```", | |
| 384 | + "[/CODE]", | |
| 385 | + "trailing text", | |
| 386 | + ]); | |
| 387 | + | |
| 388 | + const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 389 | + const filteredLines = await getFilteredLines(result); | |
| 390 | + | |
| 391 | + expect(filteredLines).toEqual([ | |
| 392 | + "const x = 5;", | |
| 393 | + "```bash", | |
| 394 | + "ls -al", | |
| 395 | + "```", | |
| 396 | + ]); | |
| 397 | + }); | |
| 398 | + }); | |
| 399 | + | |
| 400 | + describe("filterEnglishLinesAtStart", () => { | |
| 401 | + it("should skip initial empty line", async () => { | |
| 402 | + const linesGenerator = await getLineGenerator([ | |
| 403 | + "", | |
| 404 | + "const x = 5;", | |
| 405 | + "let y = 10;", | |
| 406 | + ]); | |
| 407 | + | |
| 408 | + const result = lineStream.filterEnglishLinesAtStart(linesGenerator); | |
| 409 | + const filteredLines = await getFilteredLines(result); | |
| 410 | + | |
| 411 | + expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); | |
| 412 | + }); | |
| 413 | + | |
| 414 | + it("should filter out English first line", async () => { | |
| 415 | + const linesGenerator = await getLineGenerator([ | |
| 416 | + lineStream.ENGLISH_START_PHRASES[0], | |
| 417 | + "let y = 10;", | |
| 418 | + ]); | |
| 419 | + | |
| 420 | + const result = lineStream.filterEnglishLinesAtStart(linesGenerator); | |
| 421 | + const filteredLines = await getFilteredLines(result); | |
| 422 | + | |
| 423 | + expect(filteredLines).toEqual(["let y = 10;"]); | |
| 424 | + }); | |
| 425 | + | |
| 426 | + it("should not filter out non-English first line", async () => { | |
| 427 | + const linesGenerator = await getLineGenerator([ | |
| 428 | + "const x = 5;", | |
| 429 | + "let y = 10;", | |
| 430 | + ]); | |
| 431 | + | |
| 432 | + const result = lineStream.filterEnglishLinesAtStart(linesGenerator); | |
| 433 | + const filteredLines = await getFilteredLines(result); | |
| 434 | + | |
| 435 | + expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); | |
| 436 | + }); | |
| 437 | + | |
| 438 | + it("should filter out empty newline after first line english word", async () => { | |
| 439 | + const linesGenerator = await getLineGenerator([ | |
| 440 | + lineStream.ENGLISH_START_PHRASES[0], | |
| 441 | + "", | |
| 442 | + "const x = 5;", | |
| 443 | + ]); | |
| 444 | + | |
| 445 | + const result = lineStream.filterEnglishLinesAtStart(linesGenerator); | |
| 446 | + const filteredLines = await getFilteredLines(result); | |
| 447 | + | |
| 448 | + expect(filteredLines).toEqual(["const x = 5;"]); | |
| 449 | + }); | |
| 450 | + | |
| 451 | + it("should filter out sentences ending in a semi-colon that are not code keywords", async () => { | |
| 452 | + const linesGenerator = await getLineGenerator([ | |
| 453 | + "a" + lineStream.CODE_KEYWORDS_ENDING_IN_SEMICOLON[0] + ":", | |
| 454 | + "const x = 5;", | |
| 455 | + ]); | |
| 456 | + | |
| 457 | + const result = lineStream.filterEnglishLinesAtStart(linesGenerator); | |
| 458 | + const filteredLines = await getFilteredLines(result); | |
| 459 | + | |
| 460 | + expect(filteredLines).toEqual(["const x = 5;"]); | |
| 461 | + }); | |
| 462 | + | |
| 463 | + it("should not filter out sentences ending in a semi-colon that are code keywords", async () => { | |
| 464 | + const keyword = lineStream.CODE_KEYWORDS_ENDING_IN_SEMICOLON[0] + ":"; | |
| 465 | + | |
| 466 | + const linesGenerator = await getLineGenerator([keyword, "const x = 5;"]); | |
| 467 | + | |
| 468 | + const result = lineStream.filterEnglishLinesAtStart(linesGenerator); | |
| 469 | + const filteredLines = await getFilteredLines(result); | |
| 470 | + | |
| 471 | + expect(filteredLines).toEqual([keyword, "const x = 5;"]); | |
| 472 | + }); | |
| 473 | + }); | |
| 474 | + | |
| 475 | + describe("filterEnglishLinesAtEnd", () => { | |
| 476 | + it("should stop at English explanation after code block", async () => { | |
| 477 | + const linesGenerator = await getLineGenerator([ | |
| 478 | + "const x = 5;", | |
| 479 | + "```", | |
| 480 | + lineStream.ENGLISH_POST_PHRASES[0], | |
| 481 | + ]); | |
| 482 | + | |
| 483 | + const result = lineStream.filterEnglishLinesAtEnd(linesGenerator); | |
| 484 | + const filteredLines = await getFilteredLines(result); | |
| 485 | + | |
| 486 | + expect(filteredLines).toEqual(["const x = 5;", "```"]); | |
| 487 | + }); | |
| 488 | + }); | |
| 489 | + | |
| 490 | + describe("fixCodeLlamaFirstLineIndentation", () => { | |
| 491 | + it("should fix indentation of the first line", async () => { | |
| 492 | + const linesGenerator = await getLineGenerator([ | |
| 493 | + " const x = 5;", | |
| 494 | + "let y = 10;", | |
| 495 | + ]); | |
| 496 | + | |
| 497 | + const result = | |
| 498 | + lineStream.fixCodeLlamaFirstLineIndentation(linesGenerator); | |
| 499 | + const filteredLines = await getFilteredLines(result); | |
| 500 | + | |
| 501 | + expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); | |
| 502 | + }); | |
| 503 | + }); | |
| 504 | + | |
| 505 | + describe("filterLeadingAndTrailingNewLineInsertion", () => { | |
| 506 | + it("should ignore 'useless' new first lines", async () => { | |
| 507 | + const linesGenerator = await getLineGenerator([ | |
| 508 | + { type: "new", line: lineStream.USELESS_LINES[0] }, | |
| 509 | + { type: "new", line: "const x = 5;" }, | |
| 510 | + ]); | |
| 511 | + | |
| 512 | + const result = | |
| 513 | + lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator); | |
| 514 | + const filteredLines = await getFilteredLines(result); | |
| 515 | + | |
| 516 | + expect(filteredLines).toEqual([{ type: "new", line: "const x = 5;" }]); | |
| 517 | + }); | |
| 518 | + | |
| 519 | + it("should handle preserve newlines chars in old lines", async () => { | |
| 520 | + const linesGenerator = await getLineGenerator([ | |
| 521 | + { type: "new", line: "const x = 5;" }, | |
| 522 | + { type: "old", line: "let y = 10;" }, | |
| 523 | + { type: "old", line: "" }, | |
| 524 | + { type: "new", line: "const z = 15;" }, | |
| 525 | + ]); | |
| 526 | + | |
| 527 | + const result = | |
| 528 | + lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator); | |
| 529 | + const filteredLines = await getFilteredLines(result); | |
| 530 | + | |
| 531 | + expect(filteredLines).toEqual([ | |
| 532 | + { type: "new", line: "const x = 5;" }, | |
| 533 | + { type: "old", line: "let y = 10;" }, | |
| 534 | + { type: "old", line: "" }, | |
| 535 | + { type: "new", line: "const z = 15;" }, | |
| 536 | + ]); | |
| 537 | + }); | |
| 538 | + | |
| 539 | + it("should filter leading and trailing new line insertions", async () => { | |
| 540 | + const linesGenerator = await getLineGenerator([ | |
| 541 | + { type: "new", line: "" }, | |
| 542 | + { type: "new", line: "const x = 5;" }, | |
| 543 | + { type: "new", line: "let y = 10;" }, | |
| 544 | + { type: "new", line: "" }, | |
| 545 | + ]); | |
| 546 | + | |
| 547 | + const result = | |
| 548 | + lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator); | |
| 549 | + const filteredLines = await getFilteredLines(result); | |
| 550 | + | |
| 551 | + expect(filteredLines).toEqual([ | |
| 552 | + { type: "new", line: "const x = 5;" }, | |
| 553 | + { type: "new", line: "let y = 10;" }, | |
| 554 | + ]); | |
| 555 | + }); | |
| 556 | + | |
| 557 | + it("should buffer newline chars and then render them if we encounter another non-empty line", async () => { | |
| 558 | + const linesGenerator = await getLineGenerator([ | |
| 559 | + { type: "new", line: "const x = 5;" }, | |
| 560 | + { type: "new", line: "" }, | |
| 561 | + { type: "new", line: "let y = 10;" }, | |
| 562 | + ]); | |
| 563 | + | |
| 564 | + const result = | |
| 565 | + lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator); | |
| 566 | + const filteredLines = await getFilteredLines(result); | |
| 567 | + | |
| 568 | + expect(filteredLines).toEqual([ | |
| 569 | + { type: "new", line: "const x = 5;" }, | |
| 570 | + { type: "new", line: "" }, | |
| 571 | + { type: "new", line: "let y = 10;" }, | |
| 572 | + ]); | |
| 573 | + }); | |
| 574 | + }); | |
| 575 | + | |
| 576 | + describe("stopAtRepeatingLines", () => { | |
| 577 | + it("should handle non-repeating lines correctly", async () => { | |
| 578 | + const linesGenerator = await getLineGenerator([ | |
| 579 | + "const x = 5;", | |
| 580 | + "let y = 10;", | |
| 581 | + "const z = 15;", | |
| 582 | + ]); | |
| 583 | + | |
| 584 | + const result = lineStream.stopAtRepeatingLines( | |
| 585 | + linesGenerator, | |
| 586 | + mockFullStop, | |
| 587 | + ); | |
| 588 | + const filteredLines = await getFilteredLines(result); | |
| 589 | + | |
| 590 | + expect(filteredLines).toEqual([ | |
| 591 | + "const x = 5;", | |
| 592 | + "let y = 10;", | |
| 593 | + "const z = 15;", | |
| 594 | + ]); | |
| 595 | + }); | |
| 596 | + | |
| 597 | + it("should stop at repeating lines", async () => { | |
| 598 | + const linesGenerator = await getLineGenerator([ | |
| 599 | + "const x = 5;", | |
| 600 | + "let y = 10;", | |
| 601 | + "let y = 10;", | |
| 602 | + "let y = 10;", | |
| 603 | + "const z = 15;", | |
| 604 | + ]); | |
| 605 | + | |
| 606 | + const result = lineStream.stopAtRepeatingLines( | |
| 607 | + linesGenerator, | |
| 608 | + mockFullStop, | |
| 609 | + ); | |
| 610 | + const filteredLines = await getFilteredLines(result); | |
| 611 | + | |
| 612 | + expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); | |
| 613 | + expect(mockFullStop).toHaveBeenCalledTimes(1); | |
| 614 | + }); | |
| 615 | + }); | |
| 616 | +}); |
deleted core/autocomplete/filtering/test/filter.test.ts +0 −48
| @@ -1,48 +0,0 @@ | ||
| 1 | -import { setUpTestDir, tearDownTestDir } from "../../../test/testDir"; | |
| 2 | - | |
| 3 | -import { TEST_CASES_WITH_DIFF, TEST_CASES_WITHOUT_DIFF } from "./testCases"; | |
| 4 | -import { | |
| 5 | - AutocompleteFileringTestInput, | |
| 6 | - testAutocompleteFiltering, | |
| 7 | -} from "./util"; | |
| 8 | - | |
| 9 | -const filterTestCases = (tests: AutocompleteFileringTestInput[]) => { | |
| 10 | - if (tests.some((test) => test.options?.only)) { | |
| 11 | - return tests.filter((test) => test.options?.only); | |
| 12 | - } | |
| 13 | - | |
| 14 | - return tests; | |
| 15 | -}; | |
| 16 | - | |
| 17 | -describe("Autocomplete filtering tests", () => { | |
| 18 | - beforeAll(async () => { | |
| 19 | - tearDownTestDir(); | |
| 20 | - setUpTestDir(); | |
| 21 | - }); | |
| 22 | - | |
| 23 | - afterAll(async () => { | |
| 24 | - tearDownTestDir(); | |
| 25 | - }); | |
| 26 | - | |
| 27 | - beforeEach(async () => { | |
| 28 | - await new Promise((resolve) => setTimeout(resolve, 50)); | |
| 29 | - }); | |
| 30 | - | |
| 31 | - describe("Should return unmodified LLM output", () => { | |
| 32 | - it.each(filterTestCases(TEST_CASES_WITHOUT_DIFF))( | |
| 33 | - "$description", | |
| 34 | - async (testCase) => { | |
| 35 | - await testAutocompleteFiltering(testCase); | |
| 36 | - }, | |
| 37 | - ); | |
| 38 | - }); | |
| 39 | - | |
| 40 | - describe("Should return modified LLM output", () => { | |
| 41 | - it.each(filterTestCases(TEST_CASES_WITH_DIFF))( | |
| 42 | - "$description", | |
| 43 | - async (testCase) => { | |
| 44 | - await testAutocompleteFiltering(testCase); | |
| 45 | - }, | |
| 46 | - ); | |
| 47 | - }); | |
| 48 | -}); |
added core/autocomplete/filtering/test/filter.vitest.ts +54 −0
| @@ -0,0 +1,54 @@ | ||
| 1 | +import { afterAll, beforeAll, beforeEach, describe, it } from "vitest"; | |
| 2 | +import { | |
| 3 | + addToTestDir, | |
| 4 | + setUpTestDir, | |
| 5 | + tearDownTestDir, | |
| 6 | +} from "../../../test/testDir"; | |
| 7 | + | |
| 8 | +import { TEST_CASES_WITH_DIFF, TEST_CASES_WITHOUT_DIFF } from "./testCases"; | |
| 9 | +import { | |
| 10 | + AutocompleteFileringTestInput, | |
| 11 | + testAutocompleteFiltering, | |
| 12 | +} from "./util"; | |
| 13 | + | |
| 14 | +const filterTestCases = (tests: AutocompleteFileringTestInput[]) => { | |
| 15 | + if (tests.some((test) => test.options?.only)) { | |
| 16 | + return tests.filter((test) => test.options?.only); | |
| 17 | + } | |
| 18 | + | |
| 19 | + return tests; | |
| 20 | +}; | |
| 21 | + | |
| 22 | +describe("Autocomplete filtering tests", () => { | |
| 23 | + beforeAll(async () => { | |
| 24 | + tearDownTestDir(); | |
| 25 | + setUpTestDir(); | |
| 26 | + addToTestDir([".continueignore"]); | |
| 27 | + }); | |
| 28 | + | |
| 29 | + afterAll(async () => { | |
| 30 | + tearDownTestDir(); | |
| 31 | + }); | |
| 32 | + | |
| 33 | + beforeEach(async () => { | |
| 34 | + await new Promise((resolve) => setTimeout(resolve, 50)); | |
| 35 | + }); | |
| 36 | + | |
| 37 | + describe("Should return unmodified LLM output", () => { | |
| 38 | + it.each(filterTestCases(TEST_CASES_WITHOUT_DIFF))( | |
| 39 | + "$description", | |
| 40 | + async (testCase) => { | |
| 41 | + await testAutocompleteFiltering(testCase); | |
| 42 | + }, | |
| 43 | + ); | |
| 44 | + }); | |
| 45 | + | |
| 46 | + describe("Should return modified LLM output", () => { | |
| 47 | + it.each(filterTestCases(TEST_CASES_WITH_DIFF))( | |
| 48 | + "$description", | |
| 49 | + async (testCase) => { | |
| 50 | + await testAutocompleteFiltering(testCase); | |
| 51 | + }, | |
| 52 | + ); | |
| 53 | + }); | |
| 54 | +}); |
modified core/autocomplete/filtering/test/util.ts +1 −0
| @@ -1,3 +1,4 @@ | ||
| 1 | +import { expect } from "vitest"; | |
| 1 | 2 | import MockLLM from "../../../llm/llms/Mock"; |
| 2 | 3 | import { testConfigHandler, testIde } from "../../../test/fixtures"; |
| 3 | 4 | import { joinPathsToUri } from "../../../util/uri"; |
deleted core/autocomplete/generation/GeneratorReuseManager.test.ts +0 −215
| @@ -1,215 +0,0 @@ | ||
| 1 | -import { jest } from "@jest/globals"; | |
| 2 | -import { GeneratorReuseManager } from "./GeneratorReuseManager"; | |
| 3 | - | |
| 4 | -function createMockGenerator( | |
| 5 | - data: string[], | |
| 6 | - delay: number = 0, | |
| 7 | -): (abortSignal: AbortSignal) => AsyncGenerator<string> { | |
| 8 | - const mockGenerator = async function* () { | |
| 9 | - for (const chunk of data) { | |
| 10 | - yield chunk; | |
| 11 | - | |
| 12 | - if (delay > 0) { | |
| 13 | - await new Promise((resolve) => setTimeout(resolve, delay)); | |
| 14 | - } | |
| 15 | - } | |
| 16 | - }; | |
| 17 | - const newGenerator = jest | |
| 18 | - .fn<() => AsyncGenerator<string>>() | |
| 19 | - .mockReturnValue(mockGenerator()); | |
| 20 | - | |
| 21 | - return newGenerator; | |
| 22 | -} | |
| 23 | - | |
| 24 | -describe("GeneratorReuseManager", () => { | |
| 25 | - let reuseManager: GeneratorReuseManager; | |
| 26 | - let onErrorMock: jest.Mock; | |
| 27 | - | |
| 28 | - beforeEach(() => { | |
| 29 | - onErrorMock = jest.fn(); | |
| 30 | - reuseManager = new GeneratorReuseManager(onErrorMock); | |
| 31 | - }); | |
| 32 | - | |
| 33 | - afterEach(() => { | |
| 34 | - jest.clearAllMocks(); | |
| 35 | - }); | |
| 36 | - | |
| 37 | - test("creates new generator when there is no current generator", async () => { | |
| 38 | - const data = ["hello ", "world"]; | |
| 39 | - const newGenerator = createMockGenerator(data); | |
| 40 | - | |
| 41 | - const prefix = ""; | |
| 42 | - | |
| 43 | - const generator = reuseManager.getGenerator(prefix, newGenerator, true); | |
| 44 | - | |
| 45 | - const output: string[] = []; | |
| 46 | - for await (const chunk of generator) { | |
| 47 | - output.push(chunk); | |
| 48 | - } | |
| 49 | - | |
| 50 | - expect(output).toEqual(data); | |
| 51 | - expect(newGenerator).toHaveBeenCalledTimes(1); | |
| 52 | - }); | |
| 53 | - | |
| 54 | - test("reuses generator when prefix matches pending completion", async () => { | |
| 55 | - const newGenerator = createMockGenerator(["llo ", "world"]); | |
| 56 | - | |
| 57 | - // First call with initial prefix | |
| 58 | - const prefix1 = "he"; | |
| 59 | - const generator1 = reuseManager.getGenerator(prefix1, newGenerator, true); | |
| 60 | - | |
| 61 | - const output1: string[] = []; | |
| 62 | - for await (const chunk of generator1) { | |
| 63 | - output1.push(chunk); | |
| 64 | - } | |
| 65 | - | |
| 66 | - expect(output1).toEqual(["llo ", "world"]); | |
| 67 | - | |
| 68 | - // Second call with extended prefix that matches pending completion | |
| 69 | - const prefix2 = "hello "; | |
| 70 | - const generator2 = reuseManager.getGenerator(prefix2, newGenerator, true); | |
| 71 | - | |
| 72 | - const output2: string[] = []; | |
| 73 | - for await (const chunk of generator2) { | |
| 74 | - output2.push(chunk); | |
| 75 | - } | |
| 76 | - | |
| 77 | - expect(output2).toEqual(["world"]); | |
| 78 | - | |
| 79 | - // Ensure generator was reused (newGenerator should be called only once) | |
| 80 | - expect(newGenerator).toHaveBeenCalledTimes(1); | |
| 81 | - }); | |
| 82 | - | |
| 83 | - test("creates new generator when prefix does not match pending completion", async () => { | |
| 84 | - const data = ["goodbye ", "world"]; | |
| 85 | - const newGenerator = createMockGenerator(data); | |
| 86 | - | |
| 87 | - // Initial generator with different prefix | |
| 88 | - reuseManager.pendingGeneratorPrefix = "hello "; | |
| 89 | - reuseManager.pendingCompletion = "world"; | |
| 90 | - | |
| 91 | - const prefix = "good"; | |
| 92 | - const generator = reuseManager.getGenerator(prefix, newGenerator, true); | |
| 93 | - | |
| 94 | - const output: string[] = []; | |
| 95 | - for await (const chunk of generator) { | |
| 96 | - output.push(chunk); | |
| 97 | - } | |
| 98 | - | |
| 99 | - expect(output).toEqual(data); | |
| 100 | - // Ensure a new generator was created | |
| 101 | - expect(newGenerator).toHaveBeenCalledTimes(1); | |
| 102 | - }); | |
| 103 | - | |
| 104 | - test("handles multiline=false by stopping at newline", async () => { | |
| 105 | - const data = ["first line\n", "second line"]; | |
| 106 | - const newGenerator = createMockGenerator(data); | |
| 107 | - | |
| 108 | - const prefix = ""; | |
| 109 | - const generator = reuseManager.getGenerator(prefix, newGenerator, false); | |
| 110 | - | |
| 111 | - const output: string[] = []; | |
| 112 | - for await (const chunk of generator) { | |
| 113 | - output.push(chunk); | |
| 114 | - } | |
| 115 | - | |
| 116 | - expect(output).toEqual(["first line"]); | |
| 117 | - // Ensure it stops after the first newline | |
| 118 | - }); | |
| 119 | - | |
| 120 | - test("handles multiline=true by not stopping at newline", async () => { | |
| 121 | - const data = ["first line\n", "second line"]; | |
| 122 | - const newGenerator = createMockGenerator(data); | |
| 123 | - | |
| 124 | - const prefix = ""; | |
| 125 | - const generator = reuseManager.getGenerator(prefix, newGenerator, true); | |
| 126 | - | |
| 127 | - const output: string[] = []; | |
| 128 | - for await (const chunk of generator) { | |
| 129 | - output.push(chunk); | |
| 130 | - } | |
| 131 | - | |
| 132 | - expect(output).toEqual(data); | |
| 133 | - }); | |
| 134 | - | |
| 135 | - test("cancels previous generator when creating a new one", async () => { | |
| 136 | - const data1 = ["data from generator 1", "not generated"]; | |
| 137 | - const data2 = ["data from generator 2"]; | |
| 138 | - | |
| 139 | - const newGenerator1 = createMockGenerator(data1, 1000); // Delay so we have the chance to cancel it | |
| 140 | - const newGenerator2 = createMockGenerator(data2); | |
| 141 | - | |
| 142 | - const prefix1 = "prefix1"; | |
| 143 | - const prefix2 = "prefix2"; | |
| 144 | - | |
| 145 | - // First generator | |
| 146 | - const generator1 = reuseManager.getGenerator(prefix1, newGenerator1, true); | |
| 147 | - const output1: string[] = []; | |
| 148 | - for await (const chunk of generator1) { | |
| 149 | - output1.push(chunk); | |
| 150 | - // Simulate the generator being canceled before completing | |
| 151 | - reuseManager.currentGenerator?.cancel(); | |
| 152 | - } | |
| 153 | - | |
| 154 | - expect(output1.length).toEqual(1); | |
| 155 | - expect(output1[0]).toEqual(data1[0]); | |
| 156 | - | |
| 157 | - // Second generator | |
| 158 | - const generator2 = reuseManager.getGenerator(prefix2, newGenerator2, true); | |
| 159 | - const output2: string[] = []; | |
| 160 | - for await (const chunk of generator2) { | |
| 161 | - output2.push(chunk); | |
| 162 | - } | |
| 163 | - | |
| 164 | - expect(output2).toEqual(data2); | |
| 165 | - }); | |
| 166 | - | |
| 167 | - test("calls onError when generator throws an error", async () => { | |
| 168 | - const error = new Error("Generator error"); | |
| 169 | - const mockGenerator = async function* () { | |
| 170 | - throw error; | |
| 171 | - }; | |
| 172 | - const newGenerator = jest | |
| 173 | - .fn<() => AsyncGenerator<string>>() | |
| 174 | - .mockReturnValue(mockGenerator()); | |
| 175 | - | |
| 176 | - const prefix = ""; | |
| 177 | - const generator = reuseManager.getGenerator(prefix, newGenerator, true); | |
| 178 | - | |
| 179 | - const output: string[] = []; | |
| 180 | - await expect(async () => { | |
| 181 | - for await (const chunk of generator) { | |
| 182 | - output.push(chunk); | |
| 183 | - } | |
| 184 | - }).not.toThrow(); // getGenerator handles errors internally | |
| 185 | - | |
| 186 | - expect(onErrorMock).toHaveBeenCalledWith(error); | |
| 187 | - expect(output).toEqual([]); | |
| 188 | - }); | |
| 189 | - | |
| 190 | - test("handles backspacing by creating new generator when prefix is shorter", async () => { | |
| 191 | - const data = ["hello world"]; | |
| 192 | - const newGenerator1 = createMockGenerator(data); | |
| 193 | - const newGenerator2 = createMockGenerator(data); | |
| 194 | - | |
| 195 | - // First prefix | |
| 196 | - const prefix1 = "hello world"; | |
| 197 | - const generator1 = reuseManager.getGenerator(prefix1, newGenerator1, true); | |
| 198 | - const output1: string[] = []; | |
| 199 | - for await (const chunk of generator1) { | |
| 200 | - output1.push(chunk); | |
| 201 | - } | |
| 202 | - | |
| 203 | - // Simulate backspace (prefix is shorter) | |
| 204 | - const prefix2 = "hello worl"; | |
| 205 | - const generator2 = reuseManager.getGenerator(prefix2, newGenerator2, true); | |
| 206 | - const output2: string[] = []; | |
| 207 | - for await (const chunk of generator2) { | |
| 208 | - output2.push(chunk); | |
| 209 | - } | |
| 210 | - | |
| 211 | - // Ensure a new generator was created | |
| 212 | - expect(newGenerator1).toHaveBeenCalledTimes(1); | |
| 213 | - expect(newGenerator2).toHaveBeenCalledTimes(1); | |
| 214 | - }); | |
| 215 | -}); |
added core/autocomplete/generation/GeneratorReuseManager.vitest.ts +223 −0
| @@ -0,0 +1,223 @@ | ||
| 1 | +import { | |
| 2 | + afterEach, | |
| 3 | + beforeEach, | |
| 4 | + describe, | |
| 5 | + expect, | |
| 6 | + Mock, | |
| 7 | + test, | |
| 8 | + vi, | |
| 9 | +} from "vitest"; | |
| 10 | +import { GeneratorReuseManager } from "./GeneratorReuseManager"; | |
| 11 | + | |
| 12 | +function createMockGenerator( | |
| 13 | + data: string[], | |
| 14 | + delay: number = 0, | |
| 15 | +): (abortSignal: AbortSignal) => AsyncGenerator<string> { | |
| 16 | + const mockGenerator = async function* () { | |
| 17 | + for (const chunk of data) { | |
| 18 | + yield chunk; | |
| 19 | + | |
| 20 | + if (delay > 0) { | |
| 21 | + await new Promise((resolve) => setTimeout(resolve, delay)); | |
| 22 | + } | |
| 23 | + } | |
| 24 | + }; | |
| 25 | + const newGenerator = vi | |
| 26 | + .fn<() => AsyncGenerator<string>>() | |
| 27 | + .mockReturnValue(mockGenerator()); | |
| 28 | + | |
| 29 | + return newGenerator; | |
| 30 | +} | |
| 31 | + | |
| 32 | +describe("GeneratorReuseManager", () => { | |
| 33 | + let reuseManager: GeneratorReuseManager; | |
| 34 | + let onErrorMock: Mock; | |
| 35 | + | |
| 36 | + beforeEach(() => { | |
| 37 | + onErrorMock = vi.fn(); | |
| 38 | + reuseManager = new GeneratorReuseManager(onErrorMock); | |
| 39 | + }); | |
| 40 | + | |
| 41 | + afterEach(() => { | |
| 42 | + vi.clearAllMocks(); | |
| 43 | + }); | |
| 44 | + | |
| 45 | + test("creates new generator when there is no current generator", async () => { | |
| 46 | + const data = ["hello ", "world"]; | |
| 47 | + const newGenerator = createMockGenerator(data); | |
| 48 | + | |
| 49 | + const prefix = ""; | |
| 50 | + | |
| 51 | + const generator = reuseManager.getGenerator(prefix, newGenerator, true); | |
| 52 | + | |
| 53 | + const output: string[] = []; | |
| 54 | + for await (const chunk of generator) { | |
| 55 | + output.push(chunk); | |
| 56 | + } | |
| 57 | + | |
| 58 | + expect(output).toEqual(data); | |
| 59 | + expect(newGenerator).toHaveBeenCalledTimes(1); | |
| 60 | + }); | |
| 61 | + | |
| 62 | + test("reuses generator when prefix matches pending completion", async () => { | |
| 63 | + const newGenerator = createMockGenerator(["llo ", "world"]); | |
| 64 | + | |
| 65 | + // First call with initial prefix | |
| 66 | + const prefix1 = "he"; | |
| 67 | + const generator1 = reuseManager.getGenerator(prefix1, newGenerator, true); | |
| 68 | + | |
| 69 | + const output1: string[] = []; | |
| 70 | + for await (const chunk of generator1) { | |
| 71 | + output1.push(chunk); | |
| 72 | + } | |
| 73 | + | |
| 74 | + expect(output1).toEqual(["llo ", "world"]); | |
| 75 | + | |
| 76 | + // Second call with extended prefix that matches pending completion | |
| 77 | + const prefix2 = "hello "; | |
| 78 | + const generator2 = reuseManager.getGenerator(prefix2, newGenerator, true); | |
| 79 | + | |
| 80 | + const output2: string[] = []; | |
| 81 | + for await (const chunk of generator2) { | |
| 82 | + output2.push(chunk); | |
| 83 | + } | |
| 84 | + | |
| 85 | + expect(output2).toEqual(["world"]); | |
| 86 | + | |
| 87 | + // Ensure generator was reused (newGenerator should be called only once) | |
| 88 | + expect(newGenerator).toHaveBeenCalledTimes(1); | |
| 89 | + }); | |
| 90 | + | |
| 91 | + test("creates new generator when prefix does not match pending completion", async () => { | |
| 92 | + const data = ["goodbye ", "world"]; | |
| 93 | + const newGenerator = createMockGenerator(data); | |
| 94 | + | |
| 95 | + // Initial generator with different prefix | |
| 96 | + reuseManager.pendingGeneratorPrefix = "hello "; | |
| 97 | + reuseManager.pendingCompletion = "world"; | |
| 98 | + | |
| 99 | + const prefix = "good"; | |
| 100 | + const generator = reuseManager.getGenerator(prefix, newGenerator, true); | |
| 101 | + | |
| 102 | + const output: string[] = []; | |
| 103 | + for await (const chunk of generator) { | |
| 104 | + output.push(chunk); | |
| 105 | + } | |
| 106 | + | |
| 107 | + expect(output).toEqual(data); | |
| 108 | + // Ensure a new generator was created | |
| 109 | + expect(newGenerator).toHaveBeenCalledTimes(1); | |
| 110 | + }); | |
| 111 | + | |
| 112 | + test("handles multiline=false by stopping at newline", async () => { | |
| 113 | + const data = ["first line\n", "second line"]; | |
| 114 | + const newGenerator = createMockGenerator(data); | |
| 115 | + | |
| 116 | + const prefix = ""; | |
| 117 | + const generator = reuseManager.getGenerator(prefix, newGenerator, false); | |
| 118 | + | |
| 119 | + const output: string[] = []; | |
| 120 | + for await (const chunk of generator) { | |
| 121 | + output.push(chunk); | |
| 122 | + } | |
| 123 | + | |
| 124 | + expect(output).toEqual(["first line"]); | |
| 125 | + // Ensure it stops after the first newline | |
| 126 | + }); | |
| 127 | + | |
| 128 | + test("handles multiline=true by not stopping at newline", async () => { | |
| 129 | + const data = ["first line\n", "second line"]; | |
| 130 | + const newGenerator = createMockGenerator(data); | |
| 131 | + | |
| 132 | + const prefix = ""; | |
| 133 | + const generator = reuseManager.getGenerator(prefix, newGenerator, true); | |
| 134 | + | |
| 135 | + const output: string[] = []; | |
| 136 | + for await (const chunk of generator) { | |
| 137 | + output.push(chunk); | |
| 138 | + } | |
| 139 | + | |
| 140 | + expect(output).toEqual(data); | |
| 141 | + }); | |
| 142 | + | |
| 143 | + test("cancels previous generator when creating a new one", async () => { | |
| 144 | + const data1 = ["data from generator 1", "not generated"]; | |
| 145 | + const data2 = ["data from generator 2"]; | |
| 146 | + | |
| 147 | + const newGenerator1 = createMockGenerator(data1, 1000); // Delay so we have the chance to cancel it | |
| 148 | + const newGenerator2 = createMockGenerator(data2); | |
| 149 | + | |
| 150 | + const prefix1 = "prefix1"; | |
| 151 | + const prefix2 = "prefix2"; | |
| 152 | + | |
| 153 | + // First generator | |
| 154 | + const generator1 = reuseManager.getGenerator(prefix1, newGenerator1, true); | |
| 155 | + const output1: string[] = []; | |
| 156 | + for await (const chunk of generator1) { | |
| 157 | + output1.push(chunk); | |
| 158 | + // Simulate the generator being canceled before completing | |
| 159 | + reuseManager.currentGenerator?.cancel(); | |
| 160 | + } | |
| 161 | + | |
| 162 | + expect(output1.length).toEqual(1); | |
| 163 | + expect(output1[0]).toEqual(data1[0]); | |
| 164 | + | |
| 165 | + // Second generator | |
| 166 | + const generator2 = reuseManager.getGenerator(prefix2, newGenerator2, true); | |
| 167 | + const output2: string[] = []; | |
| 168 | + for await (const chunk of generator2) { | |
| 169 | + output2.push(chunk); | |
| 170 | + } | |
| 171 | + | |
| 172 | + expect(output2).toEqual(data2); | |
| 173 | + }); | |
| 174 | + | |
| 175 | + test("calls onError when generator throws an error", async () => { | |
| 176 | + const error = new Error("Generator error"); | |
| 177 | + const mockGenerator = async function* () { | |
| 178 | + throw error; | |
| 179 | + }; | |
| 180 | + const newGenerator = vi | |
| 181 | + .fn<() => AsyncGenerator<string>>() | |
| 182 | + .mockReturnValue(mockGenerator()); | |
| 183 | + | |
| 184 | + const prefix = ""; | |
| 185 | + const generator = reuseManager.getGenerator(prefix, newGenerator, true); | |
| 186 | + | |
| 187 | + const output: string[] = []; | |
| 188 | + await expect(async () => { | |
| 189 | + for await (const chunk of generator) { | |
| 190 | + output.push(chunk); | |
| 191 | + } | |
| 192 | + }).not.toThrow(); // getGenerator handles errors internally | |
| 193 | + | |
| 194 | + expect(onErrorMock).toHaveBeenCalledWith(error); | |
| 195 | + expect(output).toEqual([]); | |
| 196 | + }); | |
| 197 | + | |
| 198 | + test("handles backspacing by creating new generator when prefix is shorter", async () => { | |
| 199 | + const data = ["hello world"]; | |
| 200 | + const newGenerator1 = createMockGenerator(data); | |
| 201 | + const newGenerator2 = createMockGenerator(data); | |
| 202 | + | |
| 203 | + // First prefix | |
| 204 | + const prefix1 = "hello world"; | |
| 205 | + const generator1 = reuseManager.getGenerator(prefix1, newGenerator1, true); | |
| 206 | + const output1: string[] = []; | |
| 207 | + for await (const chunk of generator1) { | |
| 208 | + output1.push(chunk); | |
| 209 | + } | |
| 210 | + | |
| 211 | + // Simulate backspace (prefix is shorter) | |
| 212 | + const prefix2 = "hello worl"; | |
| 213 | + const generator2 = reuseManager.getGenerator(prefix2, newGenerator2, true); | |
| 214 | + const output2: string[] = []; | |
| 215 | + for await (const chunk of generator2) { | |
| 216 | + output2.push(chunk); | |
| 217 | + } | |
| 218 | + | |
| 219 | + // Ensure a new generator was created | |
| 220 | + expect(newGenerator1).toHaveBeenCalledTimes(1); | |
| 221 | + expect(newGenerator2).toHaveBeenCalledTimes(1); | |
| 222 | + }); | |
| 223 | +}); |
deleted core/autocomplete/generation/ListenableGenerator.test.ts +0 −174
| @@ -1,174 +0,0 @@ | ||
| 1 | -import { jest } from "@jest/globals"; | |
| 2 | - | |
| 3 | -import { ListenableGenerator } from "./ListenableGenerator"; | |
| 4 | - | |
| 5 | -describe("ListenableGenerator", () => { | |
| 6 | - // Helper function to create an async generator | |
| 7 | - async function* asyncGenerator<T>(values: T[], delay = 0) { | |
| 8 | - for (const value of values) { | |
| 9 | - if (delay > 0) { | |
| 10 | - await new Promise((resolve) => setTimeout(resolve, delay)); | |
| 11 | - } | |
| 12 | - yield value; | |
| 13 | - } | |
| 14 | - } | |
| 15 | - | |
| 16 | - it("should yield values from the source generator via tee()", async () => { | |
| 17 | - const values = [1, 2, 3]; | |
| 18 | - const source = asyncGenerator(values); | |
| 19 | - const onError = jest.fn(); | |
| 20 | - | |
| 21 | - const lg = new ListenableGenerator<number>( | |
| 22 | - source, | |
| 23 | - onError, | |
| 24 | - new AbortController(), | |
| 25 | - ); | |
| 26 | - | |
| 27 | - const result: number[] = []; | |
| 28 | - for await (const value of lg.tee()) { | |
| 29 | - result.push(value); | |
| 30 | - } | |
| 31 | - | |
| 32 | - expect(result).toEqual(values); | |
| 33 | - expect(onError).not.toHaveBeenCalled(); | |
| 34 | - }); | |
| 35 | - | |
| 36 | - it("should allow listeners to receive values", async () => { | |
| 37 | - const values = [1, 2, 3]; | |
| 38 | - const source = asyncGenerator(values, 10); // Introduce delay to simulate async behavior | |
| 39 | - const onError = jest.fn(); | |
| 40 | - | |
| 41 | - const lg = new ListenableGenerator<number>( | |
| 42 | - source, | |
| 43 | - onError, | |
| 44 | - new AbortController(), | |
| 45 | - ); | |
| 46 | - | |
| 47 | - const listener = jest.fn(); | |
| 48 | - | |
| 49 | - // Add listener after some delay to simulate late subscription | |
| 50 | - setTimeout(() => { | |
| 51 | - lg.listen(listener); | |
| 52 | - }, 15); | |
| 53 | - | |
| 54 | - // Wait for generator to finish | |
| 55 | - await new Promise((resolve) => setTimeout(resolve, 50)); | |
| 56 | - | |
| 57 | - expect(listener).toHaveBeenCalledWith(1); | |
| 58 | - expect(listener).toHaveBeenCalledWith(2); | |
| 59 | - expect(listener).toHaveBeenCalledWith(3); | |
| 60 | - // Listener should receive null at the end | |
| 61 | - expect(listener).toHaveBeenCalledWith(null); | |
| 62 | - }); | |
| 63 | - | |
| 64 | - it("should buffer values for listeners added after some values have been yielded", async () => { | |
| 65 | - const values = [1, 2, 3]; | |
| 66 | - const source = asyncGenerator(values, 10); | |
| 67 | - const onError = jest.fn(); | |
| 68 | - | |
| 69 | - const lg = new ListenableGenerator<number>( | |
| 70 | - source, | |
| 71 | - onError, | |
| 72 | - new AbortController(), | |
| 73 | - ); | |
| 74 | - | |
| 75 | - const initialListener = jest.fn(); | |
| 76 | - | |
| 77 | - lg.listen(initialListener); | |
| 78 | - | |
| 79 | - // Wait for the first value to be yielded | |
| 80 | - await new Promise((resolve) => setTimeout(resolve, 15)); | |
| 81 | - | |
| 82 | - // Add a second listener | |
| 83 | - const newListener = jest.fn(); | |
| 84 | - lg.listen(newListener); | |
| 85 | - | |
| 86 | - // Wait for generator to finish | |
| 87 | - await new Promise((resolve) => setTimeout(resolve, 50)); | |
| 88 | - | |
| 89 | - // Both listeners should have received all values | |
| 90 | - [initialListener, newListener].forEach((listener) => { | |
| 91 | - expect(listener).toHaveBeenCalledWith(1); | |
| 92 | - expect(listener).toHaveBeenCalledWith(2); | |
| 93 | - expect(listener).toHaveBeenCalledWith(3); | |
| 94 | - expect(listener).toHaveBeenCalledWith(null); | |
| 95 | - }); | |
| 96 | - }); | |
| 97 | - | |
| 98 | - it("should handle cancellation", async () => { | |
| 99 | - const values = [1, 2, 3, 4, 5]; | |
| 100 | - const source = asyncGenerator(values, 10); | |
| 101 | - const onError = jest.fn(); | |
| 102 | - | |
| 103 | - const lg = new ListenableGenerator<number>( | |
| 104 | - source, | |
| 105 | - onError, | |
| 106 | - new AbortController(), | |
| 107 | - ); | |
| 108 | - | |
| 109 | - const result: number[] = []; | |
| 110 | - const teeIterator = lg.tee(); | |
| 111 | - | |
| 112 | - const consume = async () => { | |
| 113 | - for await (const value of teeIterator) { | |
| 114 | - result.push(value); | |
| 115 | - if (value === 3) { | |
| 116 | - lg.cancel(); | |
| 117 | - } | |
| 118 | - } | |
| 119 | - }; | |
| 120 | - | |
| 121 | - await consume(); | |
| 122 | - | |
| 123 | - expect(result).toEqual([1, 2, 3]); | |
| 124 | - expect(lg["_isEnded"]).toBe(true); | |
| 125 | - }); | |
| 126 | - | |
| 127 | - it("should call onError when the source generator throws an error", async () => { | |
| 128 | - async function* errorGenerator() { | |
| 129 | - yield 1; | |
| 130 | - throw new Error("Test error"); | |
| 131 | - } | |
| 132 | - | |
| 133 | - const source = errorGenerator(); | |
| 134 | - const onError = jest.fn(); | |
| 135 | - | |
| 136 | - const lg = new ListenableGenerator<number>( | |
| 137 | - source, | |
| 138 | - onError, | |
| 139 | - new AbortController(), | |
| 140 | - ); | |
| 141 | - | |
| 142 | - const result: number[] = []; | |
| 143 | - for await (const value of lg.tee()) { | |
| 144 | - result.push(value); | |
| 145 | - } | |
| 146 | - | |
| 147 | - expect(result).toEqual([1]); | |
| 148 | - expect(onError).toHaveBeenCalledTimes(1); | |
| 149 | - expect(onError).toHaveBeenCalledWith(new Error("Test error")); | |
| 150 | - }); | |
| 151 | - | |
| 152 | - it("should notify listeners when the generator ends", async () => { | |
| 153 | - const values = [1, 2, 3]; | |
| 154 | - const source = asyncGenerator(values); | |
| 155 | - const onError = jest.fn(); | |
| 156 | - | |
| 157 | - const lg = new ListenableGenerator<number>( | |
| 158 | - source, | |
| 159 | - onError, | |
| 160 | - new AbortController(), | |
| 161 | - ); | |
| 162 | - | |
| 163 | - const listener = jest.fn(); | |
| 164 | - lg.listen(listener); | |
| 165 | - | |
| 166 | - // Wait for the generator to finish | |
| 167 | - await new Promise((resolve) => setTimeout(resolve, 10)); | |
| 168 | - | |
| 169 | - expect(listener).toHaveBeenCalledWith(1); | |
| 170 | - expect(listener).toHaveBeenCalledWith(2); | |
| 171 | - expect(listener).toHaveBeenCalledWith(3); | |
| 172 | - expect(listener).toHaveBeenCalledWith(null); | |
| 173 | - }); | |
| 174 | -}); |
added core/autocomplete/generation/ListenableGenerator.vitest.ts +174 −0
| @@ -0,0 +1,174 @@ | ||
| 1 | +import { describe, expect, it, vi } from "vitest"; | |
| 2 | + | |
| 3 | +import { ListenableGenerator } from "./ListenableGenerator"; | |
| 4 | + | |
| 5 | +describe("ListenableGenerator", () => { | |
| 6 | + // Helper function to create an async generator | |
| 7 | + async function* asyncGenerator<T>(values: T[], delay = 0) { | |
| 8 | + for (const value of values) { | |
| 9 | + if (delay > 0) { | |
| 10 | + await new Promise((resolve) => setTimeout(resolve, delay)); | |
| 11 | + } | |
| 12 | + yield value; | |
| 13 | + } | |
| 14 | + } | |
| 15 | + | |
| 16 | + it("should yield values from the source generator via tee()", async () => { | |
| 17 | + const values = [1, 2, 3]; | |
| 18 | + const source = asyncGenerator(values); | |
| 19 | + const onError = vi.fn(); | |
| 20 | + | |
| 21 | + const lg = new ListenableGenerator<number>( | |
| 22 | + source, | |
| 23 | + onError, | |
| 24 | + new AbortController(), | |
| 25 | + ); | |
| 26 | + | |
| 27 | + const result: number[] = []; | |
| 28 | + for await (const value of lg.tee()) { | |
| 29 | + result.push(value); | |
| 30 | + } | |
| 31 | + | |
| 32 | + expect(result).toEqual(values); | |
| 33 | + expect(onError).not.toHaveBeenCalled(); | |
| 34 | + }); | |
| 35 | + | |
| 36 | + it("should allow listeners to receive values", async () => { | |
| 37 | + const values = [1, 2, 3]; | |
| 38 | + const source = asyncGenerator(values, 10); // Introduce delay to simulate async behavior | |
| 39 | + const onError = vi.fn(); | |
| 40 | + | |
| 41 | + const lg = new ListenableGenerator<number>( | |
| 42 | + source, | |
| 43 | + onError, | |
| 44 | + new AbortController(), | |
| 45 | + ); | |
| 46 | + | |
| 47 | + const listener = vi.fn(); | |
| 48 | + | |
| 49 | + // Add listener after some delay to simulate late subscription | |
| 50 | + setTimeout(() => { | |
| 51 | + lg.listen(listener); | |
| 52 | + }, 15); | |
| 53 | + | |
| 54 | + // Wait for generator to finish | |
| 55 | + await new Promise((resolve) => setTimeout(resolve, 50)); | |
| 56 | + | |
| 57 | + expect(listener).toHaveBeenCalledWith(1); | |
| 58 | + expect(listener).toHaveBeenCalledWith(2); | |
| 59 | + expect(listener).toHaveBeenCalledWith(3); | |
| 60 | + // Listener should receive null at the end | |
| 61 | + expect(listener).toHaveBeenCalledWith(null); | |
| 62 | + }); | |
| 63 | + | |
| 64 | + it("should buffer values for listeners added after some values have been yielded", async () => { | |
| 65 | + const values = [1, 2, 3]; | |
| 66 | + const source = asyncGenerator(values, 10); | |
| 67 | + const onError = vi.fn(); | |
| 68 | + | |
| 69 | + const lg = new ListenableGenerator<number>( | |
| 70 | + source, | |
| 71 | + onError, | |
| 72 | + new AbortController(), | |
| 73 | + ); | |
| 74 | + | |
| 75 | + const initialListener = vi.fn(); | |
| 76 | + | |
| 77 | + lg.listen(initialListener); | |
| 78 | + | |
| 79 | + // Wait for the first value to be yielded | |
| 80 | + await new Promise((resolve) => setTimeout(resolve, 15)); | |
| 81 | + | |
| 82 | + // Add a second listener | |
| 83 | + const newListener = vi.fn(); | |
| 84 | + lg.listen(newListener); | |
| 85 | + | |
| 86 | + // Wait for generator to finish | |
| 87 | + await new Promise((resolve) => setTimeout(resolve, 50)); | |
| 88 | + | |
| 89 | + // Both listeners should have received all values | |
| 90 | + [initialListener, newListener].forEach((listener) => { | |
| 91 | + expect(listener).toHaveBeenCalledWith(1); | |
| 92 | + expect(listener).toHaveBeenCalledWith(2); | |
| 93 | + expect(listener).toHaveBeenCalledWith(3); | |
| 94 | + expect(listener).toHaveBeenCalledWith(null); | |
| 95 | + }); | |
| 96 | + }); | |
| 97 | + | |
| 98 | + it("should handle cancellation", async () => { | |
| 99 | + const values = [1, 2, 3, 4, 5]; | |
| 100 | + const source = asyncGenerator(values, 10); | |
| 101 | + const onError = vi.fn(); | |
| 102 | + | |
| 103 | + const lg = new ListenableGenerator<number>( | |
| 104 | + source, | |
| 105 | + onError, | |
| 106 | + new AbortController(), | |
| 107 | + ); | |
| 108 | + | |
| 109 | + const result: number[] = []; | |
| 110 | + const teeIterator = lg.tee(); | |
| 111 | + | |
| 112 | + const consume = async () => { | |
| 113 | + for await (const value of teeIterator) { | |
| 114 | + result.push(value); | |
| 115 | + if (value === 3) { | |
| 116 | + lg.cancel(); | |
| 117 | + } | |
| 118 | + } | |
| 119 | + }; | |
| 120 | + | |
| 121 | + await consume(); | |
| 122 | + | |
| 123 | + expect(result).toEqual([1, 2, 3]); | |
| 124 | + expect(lg["_isEnded"]).toBe(true); | |
| 125 | + }); | |
| 126 | + | |
| 127 | + it("should call onError when the source generator throws an error", async () => { | |
| 128 | + async function* errorGenerator() { | |
| 129 | + yield 1; | |
| 130 | + throw new Error("Test error"); | |
| 131 | + } | |
| 132 | + | |
| 133 | + const source = errorGenerator(); | |
| 134 | + const onError = vi.fn(); | |
| 135 | + | |
| 136 | + const lg = new ListenableGenerator<number>( | |
| 137 | + source, | |
| 138 | + onError, | |
| 139 | + new AbortController(), | |
| 140 | + ); | |
| 141 | + | |
| 142 | + const result: number[] = []; | |
| 143 | + for await (const value of lg.tee()) { | |
| 144 | + result.push(value); | |
| 145 | + } | |
| 146 | + | |
| 147 | + expect(result).toEqual([1]); | |
| 148 | + expect(onError).toHaveBeenCalledTimes(1); | |
| 149 | + expect(onError).toHaveBeenCalledWith(new Error("Test error")); | |
| 150 | + }); | |
| 151 | + | |
| 152 | + it("should notify listeners when the generator ends", async () => { | |
| 153 | + const values = [1, 2, 3]; | |
| 154 | + const source = asyncGenerator(values); | |
| 155 | + const onError = vi.fn(); | |
| 156 | + | |
| 157 | + const lg = new ListenableGenerator<number>( | |
| 158 | + source, | |
| 159 | + onError, | |
| 160 | + new AbortController(), | |
| 161 | + ); | |
| 162 | + | |
| 163 | + const listener = vi.fn(); | |
| 164 | + lg.listen(listener); | |
| 165 | + | |
| 166 | + // Wait for the generator to finish | |
| 167 | + await new Promise((resolve) => setTimeout(resolve, 10)); | |
| 168 | + | |
| 169 | + expect(listener).toHaveBeenCalledWith(1); | |
| 170 | + expect(listener).toHaveBeenCalledWith(2); | |
| 171 | + expect(listener).toHaveBeenCalledWith(3); | |
| 172 | + expect(listener).toHaveBeenCalledWith(null); | |
| 173 | + }); | |
| 174 | +}); |
deleted core/autocomplete/generation/utils.test.ts +0 −138
| @@ -1,138 +0,0 @@ | ||
| 1 | -import { jest } from "@jest/globals"; | |
| 2 | -import { stopAfterMaxProcessingTime } from "./utils"; | |
| 3 | - | |
| 4 | -describe("stopAfterMaxProcessingTime", () => { | |
| 5 | - beforeEach(() => { | |
| 6 | - jest.useFakeTimers(); | |
| 7 | - }); | |
| 8 | - | |
| 9 | - afterEach(() => { | |
| 10 | - jest.useRealTimers(); | |
| 11 | - }); | |
| 12 | - | |
| 13 | - async function* createMockStream(chunks: string[]): AsyncGenerator<string> { | |
| 14 | - for (const chunk of chunks) { | |
| 15 | - yield chunk; | |
| 16 | - } | |
| 17 | - } | |
| 18 | - | |
| 19 | - async function streamToString( | |
| 20 | - stream: AsyncGenerator<string>, | |
| 21 | - ): Promise<string> { | |
| 22 | - let result = ""; | |
| 23 | - for await (const chunk of stream) { | |
| 24 | - result += chunk; | |
| 25 | - } | |
| 26 | - return result; | |
| 27 | - } | |
| 28 | - | |
| 29 | - it("should yield all chunks when maxTimeMs is not reached", async () => { | |
| 30 | - const mockStream = createMockStream(["Hello", " world", "!"]); | |
| 31 | - const fullStop = jest.fn(); | |
| 32 | - const result = stopAfterMaxProcessingTime(mockStream, 1000, fullStop); | |
| 33 | - | |
| 34 | - const output = await streamToString(result); | |
| 35 | - | |
| 36 | - expect(output).toBe("Hello world!"); | |
| 37 | - expect(fullStop).not.toHaveBeenCalled(); | |
| 38 | - }); | |
| 39 | - | |
| 40 | - it.only("should stop processing after max time is reached", async () => { | |
| 41 | - // Mock implementation of Date.now | |
| 42 | - let currentTime = 0; | |
| 43 | - const originalDateNow = Date.now; | |
| 44 | - Date.now = jest.fn(() => currentTime); | |
| 45 | - | |
| 46 | - // Create a generator that we can control | |
| 47 | - async function* controlledGenerator(): AsyncGenerator<string> { | |
| 48 | - for (let i = 0; i < 100; i++) { | |
| 49 | - // After yielding 10 chunks, simulate time passing beyond our limit | |
| 50 | - if (i === 10) { | |
| 51 | - currentTime = 1000; // This exceeds our 500ms limit | |
| 52 | - } | |
| 53 | - yield `chunk-${i}`; | |
| 54 | - } | |
| 55 | - } | |
| 56 | - | |
| 57 | - const fullStop = jest.fn(); | |
| 58 | - const maxTimeMs = 500; | |
| 59 | - | |
| 60 | - const transformedGenerator = stopAfterMaxProcessingTime( | |
| 61 | - controlledGenerator(), | |
| 62 | - maxTimeMs, | |
| 63 | - fullStop, | |
| 64 | - ); | |
| 65 | - | |
| 66 | - // Consume the generator and collect outputs | |
| 67 | - const outputs: string[] = []; | |
| 68 | - for await (const chunk of transformedGenerator) { | |
| 69 | - outputs.push(chunk); | |
| 70 | - } | |
| 71 | - | |
| 72 | - // We expect: | |
| 73 | - // 1. Not all chunks were processed (less than 100) | |
| 74 | - // 2. fullStop was called | |
| 75 | - // 3. We processed at least the chunks before time was exceeded | |
| 76 | - expect(outputs.length).toBeLessThan(100); | |
| 77 | - expect(outputs.length).toBeGreaterThanOrEqual(10); // We should get at least the first 10 chunks | |
| 78 | - expect(fullStop).toHaveBeenCalled(); | |
| 79 | - | |
| 80 | - // Restore Date.now | |
| 81 | - Date.now = originalDateNow; | |
| 82 | - }); | |
| 83 | - | |
| 84 | - it("should check time only periodically based on checkInterval", async () => { | |
| 85 | - const chunks = Array(100).fill("x"); | |
| 86 | - const mockStream = createMockStream(chunks); | |
| 87 | - const fullStop = jest.fn(); | |
| 88 | - | |
| 89 | - // Spy on Date.now to count how many times it's called | |
| 90 | - const dateSpy = jest.spyOn(Date, "now"); | |
| 91 | - | |
| 92 | - // Stream should complete normally (not hitting the timeout) | |
| 93 | - await streamToString( | |
| 94 | - stopAfterMaxProcessingTime(mockStream, 10000, fullStop), | |
| 95 | - ); | |
| 96 | - | |
| 97 | - // The first call is to set startTime, then once every checkInterval (10) chunks | |
| 98 | - // So for 100 chunks, we expect startTime + ~10 checks = ~11 calls | |
| 99 | - // We use a range because implementation details might vary slightly | |
| 100 | - expect(dateSpy.mock.calls.length).toBeGreaterThanOrEqual(1); | |
| 101 | - expect(dateSpy.mock.calls.length).toBeLessThanOrEqual(15); | |
| 102 | - | |
| 103 | - dateSpy.mockRestore(); | |
| 104 | - }); | |
| 105 | - | |
| 106 | - it("should handle empty stream gracefully", async () => { | |
| 107 | - const mockStream = createMockStream([]); | |
| 108 | - const fullStop = jest.fn(); | |
| 109 | - const result = stopAfterMaxProcessingTime(mockStream, 1000, fullStop); | |
| 110 | - | |
| 111 | - const output = await streamToString(result); | |
| 112 | - | |
| 113 | - expect(output).toBe(""); | |
| 114 | - expect(fullStop).not.toHaveBeenCalled(); | |
| 115 | - }); | |
| 116 | - | |
| 117 | - it("should pass through all chunks if there's no timeout", async () => { | |
| 118 | - const chunks = Array(100).fill("test chunk"); | |
| 119 | - const mockStream = createMockStream(chunks); | |
| 120 | - const fullStop = jest.fn(); | |
| 121 | - | |
| 122 | - // Use undefined as timeout to simulate no timeout | |
| 123 | - const result = stopAfterMaxProcessingTime( | |
| 124 | - mockStream, | |
| 125 | - undefined as any, | |
| 126 | - fullStop, | |
| 127 | - ); | |
| 128 | - | |
| 129 | - // Process the stream | |
| 130 | - const processedChunks = []; | |
| 131 | - for await (const chunk of result) { | |
| 132 | - processedChunks.push(chunk); | |
| 133 | - } | |
| 134 | - | |
| 135 | - expect(processedChunks.length).toBe(chunks.length); | |
| 136 | - expect(fullStop).not.toHaveBeenCalled(); | |
| 137 | - }); | |
| 138 | -}); |
added core/autocomplete/generation/utils.vitest.ts +138 −0
| @@ -0,0 +1,138 @@ | ||
| 1 | +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; | |
| 2 | +import { stopAfterMaxProcessingTime } from "./utils"; | |
| 3 | + | |
| 4 | +describe("stopAfterMaxProcessingTime", () => { | |
| 5 | + beforeEach(() => { | |
| 6 | + vi.useFakeTimers(); | |
| 7 | + }); | |
| 8 | + | |
| 9 | + afterEach(() => { | |
| 10 | + vi.useRealTimers(); | |
| 11 | + }); | |
| 12 | + | |
| 13 | + async function* createMockStream(chunks: string[]): AsyncGenerator<string> { | |
| 14 | + for (const chunk of chunks) { | |
| 15 | + yield chunk; | |
| 16 | + } | |
| 17 | + } | |
| 18 | + | |
| 19 | + async function streamToString( | |
| 20 | + stream: AsyncGenerator<string>, | |
| 21 | + ): Promise<string> { | |
| 22 | + let result = ""; | |
| 23 | + for await (const chunk of stream) { | |
| 24 | + result += chunk; | |
| 25 | + } | |
| 26 | + return result; | |
| 27 | + } | |
| 28 | + | |
| 29 | + it("should yield all chunks when maxTimeMs is not reached", async () => { | |
| 30 | + const mockStream = createMockStream(["Hello", " world", "!"]); | |
| 31 | + const fullStop = vi.fn(); | |
| 32 | + const result = stopAfterMaxProcessingTime(mockStream, 1000, fullStop); | |
| 33 | + | |
| 34 | + const output = await streamToString(result); | |
| 35 | + | |
| 36 | + expect(output).toBe("Hello world!"); | |
| 37 | + expect(fullStop).not.toHaveBeenCalled(); | |
| 38 | + }); | |
| 39 | + | |
| 40 | + it("should stop processing after max time is reached", async () => { | |
| 41 | + // Mock implementation of Date.now | |
| 42 | + let currentTime = 0; | |
| 43 | + const originalDateNow = Date.now; | |
| 44 | + Date.now = vi.fn(() => currentTime); | |
| 45 | + | |
| 46 | + // Create a generator that we can control | |
| 47 | + async function* controlledGenerator(): AsyncGenerator<string> { | |
| 48 | + for (let i = 0; i < 100; i++) { | |
| 49 | + // After yielding 10 chunks, simulate time passing beyond our limit | |
| 50 | + if (i === 10) { | |
| 51 | + currentTime = 1000; // This exceeds our 500ms limit | |
| 52 | + } | |
| 53 | + yield `chunk-${i}`; | |
| 54 | + } | |
| 55 | + } | |
| 56 | + | |
| 57 | + const fullStop = vi.fn(); | |
| 58 | + const maxTimeMs = 500; | |
| 59 | + | |
| 60 | + const transformedGenerator = stopAfterMaxProcessingTime( | |
| 61 | + controlledGenerator(), | |
| 62 | + maxTimeMs, | |
| 63 | + fullStop, | |
| 64 | + ); | |
| 65 | + | |
| 66 | + // Consume the generator and collect outputs | |
| 67 | + const outputs: string[] = []; | |
| 68 | + for await (const chunk of transformedGenerator) { | |
| 69 | + outputs.push(chunk); | |
| 70 | + } | |
| 71 | + | |
| 72 | + // We expect: | |
| 73 | + // 1. Not all chunks were processed (less than 100) | |
| 74 | + // 2. fullStop was called | |
| 75 | + // 3. We processed at least the chunks before time was exceeded | |
| 76 | + expect(outputs.length).toBeLessThan(100); | |
| 77 | + expect(outputs.length).toBeGreaterThanOrEqual(10); // We should get at least the first 10 chunks | |
| 78 | + expect(fullStop).toHaveBeenCalled(); | |
| 79 | + | |
| 80 | + // Restore Date.now | |
| 81 | + Date.now = originalDateNow; | |
| 82 | + }); | |
| 83 | + | |
| 84 | + it("should check time only periodically based on checkInterval", async () => { | |
| 85 | + const chunks = Array(100).fill("x"); | |
| 86 | + const mockStream = createMockStream(chunks); | |
| 87 | + const fullStop = vi.fn(); | |
| 88 | + | |
| 89 | + // Spy on Date.now to count how many times it's called | |
| 90 | + const dateSpy = vi.spyOn(Date, "now"); | |
| 91 | + | |
| 92 | + // Stream should complete normally (not hitting the timeout) | |
| 93 | + await streamToString( | |
| 94 | + stopAfterMaxProcessingTime(mockStream, 10000, fullStop), | |
| 95 | + ); | |
| 96 | + | |
| 97 | + // The first call is to set startTime, then once every checkInterval (10) chunks | |
| 98 | + // So for 100 chunks, we expect startTime + ~10 checks = ~11 calls | |
| 99 | + // We use a range because implementation details might vary slightly | |
| 100 | + expect(dateSpy.mock.calls.length).toBeGreaterThanOrEqual(1); | |
| 101 | + expect(dateSpy.mock.calls.length).toBeLessThanOrEqual(15); | |
| 102 | + | |
| 103 | + dateSpy.mockRestore(); | |
| 104 | + }); | |
| 105 | + | |
| 106 | + it("should handle empty stream gracefully", async () => { | |
| 107 | + const mockStream = createMockStream([]); | |
| 108 | + const fullStop = vi.fn(); | |
| 109 | + const result = stopAfterMaxProcessingTime(mockStream, 1000, fullStop); | |
| 110 | + | |
| 111 | + const output = await streamToString(result); | |
| 112 | + | |
| 113 | + expect(output).toBe(""); | |
| 114 | + expect(fullStop).not.toHaveBeenCalled(); | |
| 115 | + }); | |
| 116 | + | |
| 117 | + it("should pass through all chunks if there's no timeout", async () => { | |
| 118 | + const chunks = Array(100).fill("test chunk"); | |
| 119 | + const mockStream = createMockStream(chunks); | |
| 120 | + const fullStop = vi.fn(); | |
| 121 | + | |
| 122 | + // Use undefined as timeout to simulate no timeout | |
| 123 | + const result = stopAfterMaxProcessingTime( | |
| 124 | + mockStream, | |
| 125 | + undefined as any, | |
| 126 | + fullStop, | |
| 127 | + ); | |
| 128 | + | |
| 129 | + // Process the stream | |
| 130 | + const processedChunks = []; | |
| 131 | + for await (const chunk of result) { | |
| 132 | + processedChunks.push(chunk); | |
| 133 | + } | |
| 134 | + | |
| 135 | + expect(processedChunks.length).toBe(chunks.length); | |
| 136 | + expect(fullStop).not.toHaveBeenCalled(); | |
| 137 | + }); | |
| 138 | +}); |
deleted core/autocomplete/snippets/gitDiffCache.test.ts +0 −84
| @@ -1,84 +0,0 @@ | ||
| 1 | -import { GitDiffCache } from "./gitDiffCache"; | |
| 2 | - | |
| 3 | -beforeEach(() => { | |
| 4 | - // Add this line to GitDiffCache class to make instance accessible | |
| 5 | - (GitDiffCache as any).instance = null; | |
| 6 | -}); | |
| 7 | - | |
| 8 | -test("GitDiffCache returns cached results within cache time", async () => { | |
| 9 | - const mockDiff = ["file1.ts", "file2.ts"]; | |
| 10 | - const getDiffFn = jest.fn().mockResolvedValue(mockDiff); | |
| 11 | - const cache = GitDiffCache.getInstance(getDiffFn, 1); // 1 second cache | |
| 12 | - | |
| 13 | - const result1 = await cache.get(); | |
| 14 | - const result2 = await cache.get(); | |
| 15 | - | |
| 16 | - expect(result1).toEqual(mockDiff); | |
| 17 | - expect(result2).toEqual(mockDiff); | |
| 18 | - expect(getDiffFn).toHaveBeenCalledTimes(1); | |
| 19 | -}); | |
| 20 | - | |
| 21 | -test("GitDiffCache refreshes cache after expiration", async () => { | |
| 22 | - const mockDiff = ["file1.ts"]; | |
| 23 | - const getDiffFn = jest.fn().mockResolvedValue(mockDiff); | |
| 24 | - const cache = GitDiffCache.getInstance(getDiffFn, 0.1); // 100ms cache | |
| 25 | - | |
| 26 | - const result1 = await cache.get(); | |
| 27 | - await new Promise((resolve) => setTimeout(resolve, 200)); // Wait for cache to expire | |
| 28 | - const result2 = await cache.get(); | |
| 29 | - | |
| 30 | - expect(getDiffFn).toHaveBeenCalledTimes(2); | |
| 31 | -}); | |
| 32 | - | |
| 33 | -test("GitDiffCache returns empty array on error", async () => { | |
| 34 | - const getDiffFn = jest.fn().mockRejectedValue(new Error("Git error")); | |
| 35 | - const cache = GitDiffCache.getInstance(getDiffFn); | |
| 36 | - | |
| 37 | - const result = await cache.get(); | |
| 38 | - expect(result).toEqual([]); | |
| 39 | -}); | |
| 40 | - | |
| 41 | -test("GitDiffCache reuses pending request", async () => { | |
| 42 | - const mockDiff = ["file1.ts"]; | |
| 43 | - let resolvePromise: (value: string[]) => void; | |
| 44 | - const getDiffFn = jest.fn().mockImplementation(() => { | |
| 45 | - return new Promise((resolve) => { | |
| 46 | - resolvePromise = resolve; | |
| 47 | - }); | |
| 48 | - }); | |
| 49 | - | |
| 50 | - const cache = GitDiffCache.getInstance(getDiffFn); | |
| 51 | - | |
| 52 | - const promise1 = cache.get(); | |
| 53 | - const promise2 = cache.get(); | |
| 54 | - | |
| 55 | - resolvePromise!(mockDiff); | |
| 56 | - | |
| 57 | - const [result1, result2] = await Promise.all([promise1, promise2]); | |
| 58 | - | |
| 59 | - expect(result1).toEqual(mockDiff); | |
| 60 | - expect(result2).toEqual(mockDiff); | |
| 61 | - expect(getDiffFn).toHaveBeenCalledTimes(1); | |
| 62 | -}); | |
| 63 | - | |
| 64 | -test("GitDiffCache invalidate clears cache", async () => { | |
| 65 | - const mockDiff = ["file1.ts"]; | |
| 66 | - const getDiffFn = jest.fn().mockResolvedValue(mockDiff); | |
| 67 | - const cache = GitDiffCache.getInstance(getDiffFn); | |
| 68 | - | |
| 69 | - await cache.get(); | |
| 70 | - cache.invalidate(); | |
| 71 | - await cache.get(); | |
| 72 | - | |
| 73 | - expect(getDiffFn).toHaveBeenCalledTimes(2); | |
| 74 | -}); | |
| 75 | - | |
| 76 | -test("GitDiffCache maintains singleton instance", () => { | |
| 77 | - const getDiffFn1 = jest.fn(); | |
| 78 | - const getDiffFn2 = jest.fn(); | |
| 79 | - | |
| 80 | - const instance1 = GitDiffCache.getInstance(getDiffFn1); | |
| 81 | - const instance2 = GitDiffCache.getInstance(getDiffFn2); | |
| 82 | - | |
| 83 | - expect(instance1).toBe(instance2); | |
| 84 | -}); |
added core/autocomplete/snippets/gitDiffCache.vitest.ts +85 −0
| @@ -0,0 +1,85 @@ | ||
| 1 | +import { beforeEach, expect, test, vi } from "vitest"; | |
| 2 | +import { GitDiffCache } from "./gitDiffCache"; | |
| 3 | + | |
| 4 | +beforeEach(() => { | |
| 5 | + // Add this line to GitDiffCache class to make instance accessible | |
| 6 | + (GitDiffCache as any).instance = null; | |
| 7 | +}); | |
| 8 | + | |
| 9 | +test("GitDiffCache returns cached results within cache time", async () => { | |
| 10 | + const mockDiff = ["file1.ts", "file2.ts"]; | |
| 11 | + const getDiffFn = vi.fn().mockResolvedValue(mockDiff); | |
| 12 | + const cache = GitDiffCache.getInstance(getDiffFn, 1); // 1 second cache | |
| 13 | + | |
| 14 | + const result1 = await cache.get(); | |
| 15 | + const result2 = await cache.get(); | |
| 16 | + | |
| 17 | + expect(result1).toEqual(mockDiff); | |
| 18 | + expect(result2).toEqual(mockDiff); | |
| 19 | + expect(getDiffFn).toHaveBeenCalledTimes(1); | |
| 20 | +}); | |
| 21 | + | |
| 22 | +test("GitDiffCache refreshes cache after expiration", async () => { | |
| 23 | + const mockDiff = ["file1.ts"]; | |
| 24 | + const getDiffFn = vi.fn().mockResolvedValue(mockDiff); | |
| 25 | + const cache = GitDiffCache.getInstance(getDiffFn, 0.1); // 100ms cache | |
| 26 | + | |
| 27 | + const result1 = await cache.get(); | |
| 28 | + await new Promise((resolve) => setTimeout(resolve, 200)); // Wait for cache to expire | |
| 29 | + const result2 = await cache.get(); | |
| 30 | + | |
| 31 | + expect(getDiffFn).toHaveBeenCalledTimes(2); | |
| 32 | +}); | |
| 33 | + | |
| 34 | +test("GitDiffCache returns empty array on error", async () => { | |
| 35 | + const getDiffFn = vi.fn().mockRejectedValue(new Error("Git error")); | |
| 36 | + const cache = GitDiffCache.getInstance(getDiffFn); | |
| 37 | + | |
| 38 | + const result = await cache.get(); | |
| 39 | + expect(result).toEqual([]); | |
| 40 | +}); | |
| 41 | + | |
| 42 | +test("GitDiffCache reuses pending request", async () => { | |
| 43 | + const mockDiff = ["file1.ts"]; | |
| 44 | + let resolvePromise: (value: string[]) => void; | |
| 45 | + const getDiffFn = vi.fn().mockImplementation(() => { | |
| 46 | + return new Promise((resolve) => { | |
| 47 | + resolvePromise = resolve; | |
| 48 | + }); | |
| 49 | + }); | |
| 50 | + | |
| 51 | + const cache = GitDiffCache.getInstance(getDiffFn); | |
| 52 | + | |
| 53 | + const promise1 = cache.get(); | |
| 54 | + const promise2 = cache.get(); | |
| 55 | + | |
| 56 | + resolvePromise!(mockDiff); | |
| 57 | + | |
| 58 | + const [result1, result2] = await Promise.all([promise1, promise2]); | |
| 59 | + | |
| 60 | + expect(result1).toEqual(mockDiff); | |
| 61 | + expect(result2).toEqual(mockDiff); | |
| 62 | + expect(getDiffFn).toHaveBeenCalledTimes(1); | |
| 63 | +}); | |
| 64 | + | |
| 65 | +test("GitDiffCache invalidate clears cache", async () => { | |
| 66 | + const mockDiff = ["file1.ts"]; | |
| 67 | + const getDiffFn = vi.fn().mockResolvedValue(mockDiff); | |
| 68 | + const cache = GitDiffCache.getInstance(getDiffFn); | |
| 69 | + | |
| 70 | + await cache.get(); | |
| 71 | + cache.invalidate(); | |
| 72 | + await cache.get(); | |
| 73 | + | |
| 74 | + expect(getDiffFn).toHaveBeenCalledTimes(2); | |
| 75 | +}); | |
| 76 | + | |
| 77 | +test("GitDiffCache maintains singleton instance", () => { | |
| 78 | + const getDiffFn1 = vi.fn(); | |
| 79 | + const getDiffFn2 = vi.fn(); | |
| 80 | + | |
| 81 | + const instance1 = GitDiffCache.getInstance(getDiffFn1); | |
| 82 | + const instance2 = GitDiffCache.getInstance(getDiffFn2); | |
| 83 | + | |
| 84 | + expect(instance1).toBe(instance2); | |
| 85 | +}); |
deleted core/autocomplete/templating/__tests__/formatOpenedFilesContext.test.ts +0 −434
| @@ -1,434 +0,0 @@ | ||
| 1 | -/** | |
| 2 | - * Comprehensive tests for formatOpenedFilesContext.ts | |
| 3 | - * | |
| 4 | - */ | |
| 5 | - | |
| 6 | -import { | |
| 7 | - AutocompleteCodeSnippet, | |
| 8 | - AutocompleteDiffSnippet, | |
| 9 | - AutocompleteSnippetType, | |
| 10 | -} from "../../snippets/types"; | |
| 11 | -import { HelperVars } from "../../util/HelperVars"; | |
| 12 | -import { formatOpenedFilesContext } from "../formatOpenedFilesContext"; | |
| 13 | - | |
| 14 | -// Import the now-exported internal functions | |
| 15 | -import { | |
| 16 | - getRecencyAndSizeScore, | |
| 17 | - rankByScore, | |
| 18 | - setLogStats, | |
| 19 | - trimSnippetForContext, | |
| 20 | -} from "../formatOpenedFilesContext"; | |
| 21 | - | |
| 22 | -describe("formatOpenedFilesContext main function tests", () => { | |
| 23 | - const mockHelper = { | |
| 24 | - modelName: "test-model", | |
| 25 | - } as HelperVars; | |
| 26 | - | |
| 27 | - const TOKEN_BUFFER = 50; | |
| 28 | - | |
| 29 | - // Create sample code snippets with various sizes | |
| 30 | - const createCodeSnippet = ( | |
| 31 | - filepath: string, | |
| 32 | - content: string, | |
| 33 | - ): AutocompleteCodeSnippet => ({ | |
| 34 | - type: AutocompleteSnippetType.Code, | |
| 35 | - filepath, | |
| 36 | - content, | |
| 37 | - }); | |
| 38 | - | |
| 39 | - const createDiffSnippet = (content: string): AutocompleteDiffSnippet => ({ | |
| 40 | - type: AutocompleteSnippetType.Diff, | |
| 41 | - content, | |
| 42 | - }); | |
| 43 | - | |
| 44 | - test("should return empty array when no snippets are provided", () => { | |
| 45 | - const result = formatOpenedFilesContext( | |
| 46 | - [], | |
| 47 | - 1000, | |
| 48 | - mockHelper, | |
| 49 | - [], | |
| 50 | - TOKEN_BUFFER, | |
| 51 | - ); | |
| 52 | - expect(result).toEqual([]); | |
| 53 | - }); | |
| 54 | - | |
| 55 | - test("should handle zero remaining token count", () => { | |
| 56 | - const snippets = [ | |
| 57 | - createCodeSnippet("file1.ts", "content of file 1"), | |
| 58 | - createCodeSnippet("file2.ts", "content of file 2"), | |
| 59 | - ]; | |
| 60 | - | |
| 61 | - const result = formatOpenedFilesContext( | |
| 62 | - snippets, | |
| 63 | - 0, | |
| 64 | - mockHelper, | |
| 65 | - [], | |
| 66 | - TOKEN_BUFFER, | |
| 67 | - ); | |
| 68 | - | |
| 69 | - expect(result).toEqual([]); | |
| 70 | - }); | |
| 71 | - | |
| 72 | - test("should handle snippets with empty content", () => { | |
| 73 | - const emptySnippets = [ | |
| 74 | - createCodeSnippet("empty1.ts", ""), | |
| 75 | - createCodeSnippet("empty2.ts", ""), | |
| 76 | - ]; | |
| 77 | - | |
| 78 | - const result = formatOpenedFilesContext( | |
| 79 | - emptySnippets, | |
| 80 | - 1000, | |
| 81 | - mockHelper, | |
| 82 | - [], | |
| 83 | - TOKEN_BUFFER, | |
| 84 | - ); | |
| 85 | - | |
| 86 | - expect(result.length).toBe(emptySnippets.length); | |
| 87 | - }); | |
| 88 | - | |
| 89 | - test("should return all snippets when they all fit within token limit", () => { | |
| 90 | - const smallSnippets = [ | |
| 91 | - createCodeSnippet("small1.ts", "a"), | |
| 92 | - createCodeSnippet("small2.ts", "b"), | |
| 93 | - createCodeSnippet("small3.ts", "c"), | |
| 94 | - ]; | |
| 95 | - | |
| 96 | - const result = formatOpenedFilesContext( | |
| 97 | - smallSnippets, | |
| 98 | - 1000, | |
| 99 | - mockHelper, | |
| 100 | - [], | |
| 101 | - TOKEN_BUFFER, | |
| 102 | - ); | |
| 103 | - | |
| 104 | - expect(result.length).toBe(smallSnippets.length); | |
| 105 | - }); | |
| 106 | - | |
| 107 | - test("should handle limited token count", () => { | |
| 108 | - const snippets = Array(10) | |
| 109 | - .fill(0) | |
| 110 | - .map((_, i) => createCodeSnippet(`file${i}.ts`, `content of file ${i}`)); | |
| 111 | - | |
| 112 | - const result = formatOpenedFilesContext( | |
| 113 | - snippets, | |
| 114 | - 1, // Extremely small token count | |
| 115 | - mockHelper, | |
| 116 | - [], | |
| 117 | - TOKEN_BUFFER, | |
| 118 | - ); | |
| 119 | - | |
| 120 | - expect(Array.isArray(result)).toBe(true); | |
| 121 | - }); | |
| 122 | - | |
| 123 | - test("should accept valid inputs with adequate token count", () => { | |
| 124 | - const snippets = [ | |
| 125 | - createCodeSnippet("file1.ts", "Some content here"), | |
| 126 | - createCodeSnippet("file2.ts", "More content here"), | |
| 127 | - ]; | |
| 128 | - | |
| 129 | - const result = formatOpenedFilesContext( | |
| 130 | - snippets, | |
| 131 | - 1000, | |
| 132 | - mockHelper, | |
| 133 | - [], | |
| 134 | - TOKEN_BUFFER, | |
| 135 | - ); | |
| 136 | - | |
| 137 | - expect(result.length).toBeGreaterThan(0); | |
| 138 | - }); | |
| 139 | - | |
| 140 | - test("should handle already added snippets parameter", () => { | |
| 141 | - const snippets = [ | |
| 142 | - createCodeSnippet("file1.ts", "content of file 1"), | |
| 143 | - createCodeSnippet("file2.ts", "content of file 2"), | |
| 144 | - ]; | |
| 145 | - | |
| 146 | - const alreadyAddedSnippets = [createDiffSnippet("diff content")]; | |
| 147 | - | |
| 148 | - const result = formatOpenedFilesContext( | |
| 149 | - snippets, | |
| 150 | - 1000, | |
| 151 | - mockHelper, | |
| 152 | - alreadyAddedSnippets, | |
| 153 | - TOKEN_BUFFER, | |
| 154 | - ); | |
| 155 | - | |
| 156 | - expect(result.length).toBe(snippets.length); | |
| 157 | - }); | |
| 158 | - | |
| 159 | - test("should handle large snippets by trimming them", () => { | |
| 160 | - const largeSnippet = createCodeSnippet("large.ts", "x".repeat(10000)); | |
| 161 | - | |
| 162 | - const result = formatOpenedFilesContext( | |
| 163 | - [largeSnippet], | |
| 164 | - 200, | |
| 165 | - mockHelper, | |
| 166 | - [], | |
| 167 | - TOKEN_BUFFER, | |
| 168 | - ); | |
| 169 | - | |
| 170 | - expect(result.length).toBe(1); | |
| 171 | - expect(result[0].filepath).toBe(largeSnippet.filepath); | |
| 172 | - expect(result[0].content.length).toBeLessThan(largeSnippet.content.length); | |
| 173 | - }); | |
| 174 | - | |
| 175 | - test("should prioritize more recent snippets when not all fit", () => { | |
| 176 | - const snippets = [ | |
| 177 | - createCodeSnippet("recent1.ts", "a".repeat(10)), | |
| 178 | - createCodeSnippet("recent2.ts", "b".repeat(10000)), | |
| 179 | - createCodeSnippet("recent3.ts", "c".repeat(10000)), | |
| 180 | - ]; | |
| 181 | - | |
| 182 | - const result = formatOpenedFilesContext( | |
| 183 | - snippets, | |
| 184 | - 200, | |
| 185 | - mockHelper, | |
| 186 | - [], | |
| 187 | - TOKEN_BUFFER, | |
| 188 | - ); | |
| 189 | - | |
| 190 | - expect(result.length).toBeGreaterThan(0); | |
| 191 | - expect(result.some((s) => s.filepath === "recent1.ts")).toBe(true); | |
| 192 | - }); | |
| 193 | - | |
| 194 | - test("should handle a mix of large and small snippets effectively", () => { | |
| 195 | - const mixedSnippets = [ | |
| 196 | - createCodeSnippet("small1.ts", "a".repeat(10)), | |
| 197 | - createCodeSnippet("large1.ts", "b".repeat(5000)), | |
| 198 | - createCodeSnippet("small2.ts", "c".repeat(10)), | |
| 199 | - createCodeSnippet("large2.ts", "d".repeat(5000)), | |
| 200 | - ]; | |
| 201 | - | |
| 202 | - const result = formatOpenedFilesContext( | |
| 203 | - mixedSnippets, | |
| 204 | - 500, | |
| 205 | - mockHelper, | |
| 206 | - [], | |
| 207 | - TOKEN_BUFFER, | |
| 208 | - ); | |
| 209 | - | |
| 210 | - expect(result.length).toBeGreaterThan(0); | |
| 211 | - expect(result.some((s) => s.filepath.startsWith("small"))).toBe(true); | |
| 212 | - }); | |
| 213 | - | |
| 214 | - test("should respect minimum token threshold when trimming", () => { | |
| 215 | - const largeSnippets = [ | |
| 216 | - createCodeSnippet("large1.ts", "a".repeat(5000)), | |
| 217 | - createCodeSnippet("large2.ts", "b".repeat(5000)), | |
| 218 | - ]; | |
| 219 | - | |
| 220 | - const result = formatOpenedFilesContext( | |
| 221 | - largeSnippets, | |
| 222 | - 150, | |
| 223 | - mockHelper, | |
| 224 | - [], | |
| 225 | - TOKEN_BUFFER, | |
| 226 | - ); | |
| 227 | - | |
| 228 | - expect(result.length).toBeLessThanOrEqual(1); | |
| 229 | - | |
| 230 | - if (result.length > 0) { | |
| 231 | - expect(result[0].content.length).toBeLessThan( | |
| 232 | - largeSnippets[0].content.length, | |
| 233 | - ); | |
| 234 | - } | |
| 235 | - }); | |
| 236 | -}); | |
| 237 | - | |
| 238 | -// Tests for rankByScore function | |
| 239 | -describe("rankByScore function", () => { | |
| 240 | - const createCodeSnippet = ( | |
| 241 | - filepath: string, | |
| 242 | - content: string, | |
| 243 | - ): AutocompleteCodeSnippet => ({ | |
| 244 | - type: AutocompleteSnippetType.Code, | |
| 245 | - filepath, | |
| 246 | - content, | |
| 247 | - }); | |
| 248 | - | |
| 249 | - test("should return empty array when given empty array", () => { | |
| 250 | - const result = rankByScore([]); | |
| 251 | - expect(result).toEqual([]); | |
| 252 | - }); | |
| 253 | - | |
| 254 | - test("should rank snippets by score", () => { | |
| 255 | - // Initialize logMin and logMax by calling setLogStats first | |
| 256 | - const snippets = [ | |
| 257 | - createCodeSnippet("file1.ts", "a".repeat(10)), | |
| 258 | - createCodeSnippet("file2.ts", "b".repeat(1000)), | |
| 259 | - createCodeSnippet("file3.ts", "c".repeat(100)), | |
| 260 | - ]; | |
| 261 | - setLogStats(snippets); | |
| 262 | - | |
| 263 | - const result = rankByScore(snippets); | |
| 264 | - | |
| 265 | - expect(Array.isArray(result)).toBe(true); | |
| 266 | - expect(result.length).toBeGreaterThan(0); | |
| 267 | - | |
| 268 | - // The snippets should be ranked in some order, which may not match input order | |
| 269 | - expect(result.map((s: { filepath: any }) => s.filepath)).not.toEqual( | |
| 270 | - snippets.map((s) => s.filepath), | |
| 271 | - ); | |
| 272 | - }); | |
| 273 | - | |
| 274 | - test("should limit the number of ranked snippets to defaultNumFilesUsed", () => { | |
| 275 | - // Create more snippets than the default limit | |
| 276 | - const manySnippets = Array(10) | |
| 277 | - .fill(0) | |
| 278 | - .map((_, i) => createCodeSnippet(`file${i}.ts`, `content of file ${i}`)); | |
| 279 | - setLogStats(manySnippets); | |
| 280 | - | |
| 281 | - const result = rankByScore(manySnippets); | |
| 282 | - | |
| 283 | - // The function should limit the number of snippets (defaultNumFilesUsed is 5) | |
| 284 | - expect(result.length).toBeLessThanOrEqual(5); | |
| 285 | - }); | |
| 286 | -}); | |
| 287 | - | |
| 288 | -// Tests for getRecencyAndSizeScore function | |
| 289 | -describe("getRecencyAndSizeScore function", () => { | |
| 290 | - const createCodeSnippet = ( | |
| 291 | - filepath: string, | |
| 292 | - content: string, | |
| 293 | - ): AutocompleteCodeSnippet => ({ | |
| 294 | - type: AutocompleteSnippetType.Code, | |
| 295 | - filepath, | |
| 296 | - content, | |
| 297 | - }); | |
| 298 | - | |
| 299 | - test("recency score should decrease with higher index", () => { | |
| 300 | - // Initialize log stats first | |
| 301 | - const snippets = [ | |
| 302 | - createCodeSnippet("file1.ts", "a".repeat(100)), | |
| 303 | - createCodeSnippet("file2.ts", "b".repeat(100)), | |
| 304 | - ]; | |
| 305 | - setLogStats(snippets); | |
| 306 | - | |
| 307 | - // Test that score decreases with increasing index | |
| 308 | - const score0 = getRecencyAndSizeScore(0, snippets[0]); | |
| 309 | - const score1 = getRecencyAndSizeScore(1, snippets[0]); | |
| 310 | - const score2 = getRecencyAndSizeScore(2, snippets[0]); | |
| 311 | - | |
| 312 | - expect(score0).toBeGreaterThan(score1); | |
| 313 | - expect(score1).toBeGreaterThan(score2); | |
| 314 | - }); | |
| 315 | - | |
| 316 | - test("size score should be higher for smaller snippets", () => { | |
| 317 | - // Initialize log stats first | |
| 318 | - const snippets = [ | |
| 319 | - createCodeSnippet("small.ts", "a".repeat(50)), | |
| 320 | - createCodeSnippet("medium.ts", "b".repeat(200)), | |
| 321 | - createCodeSnippet("large.ts", "c".repeat(1000)), | |
| 322 | - ]; | |
| 323 | - setLogStats(snippets); | |
| 324 | - | |
| 325 | - // Test with same recency index but different sizes | |
| 326 | - const smallScore = getRecencyAndSizeScore(0, snippets[0]); | |
| 327 | - const mediumScore = getRecencyAndSizeScore(0, snippets[1]); | |
| 328 | - const largeScore = getRecencyAndSizeScore(0, snippets[2]); | |
| 329 | - | |
| 330 | - // Scores should reflect preference for smaller snippets | |
| 331 | - expect(smallScore).toBeGreaterThanOrEqual(mediumScore); | |
| 332 | - expect(mediumScore).toBeGreaterThanOrEqual(largeScore); | |
| 333 | - }); | |
| 334 | - | |
| 335 | - test("recency and size both affect the score with recency having more weight", () => { | |
| 336 | - // Initialize log stats first | |
| 337 | - const snippets = [ | |
| 338 | - createCodeSnippet("recent_large.ts", "a".repeat(1000)), | |
| 339 | - createCodeSnippet("old_small.ts", "b".repeat(50)), | |
| 340 | - ]; | |
| 341 | - setLogStats(snippets); | |
| 342 | - | |
| 343 | - // Test that recency and size both contribute to the score | |
| 344 | - const recentLargeScore = getRecencyAndSizeScore(0, snippets[0]); | |
| 345 | - const oldSmallScore = getRecencyAndSizeScore(1, snippets[1]); | |
| 346 | - | |
| 347 | - // We're not making a direct comparison, just verifying the scoring mechanism works | |
| 348 | - expect(recentLargeScore).toBeGreaterThan(0); | |
| 349 | - expect(oldSmallScore).toBeGreaterThan(0); | |
| 350 | - expect(oldSmallScore).toBeLessThan(1); | |
| 351 | - }); | |
| 352 | -}); | |
| 353 | - | |
| 354 | -// Tests for setLogStats function | |
| 355 | -describe("setLogStats function", () => { | |
| 356 | - const createCodeSnippet = ( | |
| 357 | - filepath: string, | |
| 358 | - content: string, | |
| 359 | - ): AutocompleteCodeSnippet => ({ | |
| 360 | - type: AutocompleteSnippetType.Code, | |
| 361 | - filepath, | |
| 362 | - content, | |
| 363 | - }); | |
| 364 | - | |
| 365 | - test("should set logMin and logMax based on snippet sizes", () => { | |
| 366 | - const snippets = [ | |
| 367 | - createCodeSnippet("small.ts", "a".repeat(50)), | |
| 368 | - createCodeSnippet("medium.ts", "b".repeat(200)), | |
| 369 | - createCodeSnippet("large.ts", "c".repeat(1000)), | |
| 370 | - ]; | |
| 371 | - | |
| 372 | - // We can't directly test logMin and logMax as they're private | |
| 373 | - // but we can verify that the function runs without errors | |
| 374 | - expect(() => setLogStats(snippets)).not.toThrow(); | |
| 375 | - }); | |
| 376 | - | |
| 377 | - test("should handle empty snippets", () => { | |
| 378 | - const emptySnippets = [ | |
| 379 | - createCodeSnippet("empty1.ts", ""), | |
| 380 | - createCodeSnippet("empty2.ts", ""), | |
| 381 | - ]; | |
| 382 | - | |
| 383 | - expect(() => setLogStats(emptySnippets)).not.toThrow(); | |
| 384 | - }); | |
| 385 | - | |
| 386 | - test("should handle single snippet", () => { | |
| 387 | - const singleSnippet = [createCodeSnippet("single.ts", "content")]; | |
| 388 | - | |
| 389 | - expect(() => setLogStats(singleSnippet)).not.toThrow(); | |
| 390 | - }); | |
| 391 | -}); | |
| 392 | - | |
| 393 | -// Tests for trimSnippetForContext function | |
| 394 | -describe("trimSnippetForContext function", () => { | |
| 395 | - const createCodeSnippet = ( | |
| 396 | - filepath: string, | |
| 397 | - content: string, | |
| 398 | - ): AutocompleteCodeSnippet => ({ | |
| 399 | - type: AutocompleteSnippetType.Code, | |
| 400 | - filepath, | |
| 401 | - content, | |
| 402 | - }); | |
| 403 | - | |
| 404 | - test("should return original snippet if it fits within token limit", () => { | |
| 405 | - const snippet = createCodeSnippet("small.ts", "small content"); | |
| 406 | - const modelName = "test-model"; | |
| 407 | - const maxTokens = 1000; // Large enough to fit the snippet | |
| 408 | - | |
| 409 | - const result = trimSnippetForContext(snippet, maxTokens, modelName); | |
| 410 | - | |
| 411 | - // Should return the original snippet with its token count | |
| 412 | - expect(result.newSnippet).toEqual(snippet); | |
| 413 | - expect(typeof result.newTokens).toBe("number"); | |
| 414 | - expect(result.newTokens).toBeGreaterThan(0); | |
| 415 | - }); | |
| 416 | - | |
| 417 | - test("should trim snippet content if it exceeds token limit", () => { | |
| 418 | - const snippet = createCodeSnippet("large.ts", "a".repeat(1000)); | |
| 419 | - const modelName = "test-model"; | |
| 420 | - const maxTokens = 10; // Small enough to require trimming | |
| 421 | - | |
| 422 | - const result = trimSnippetForContext(snippet, maxTokens, modelName); | |
| 423 | - | |
| 424 | - // Should return a trimmed snippet | |
| 425 | - expect(result.newSnippet.filepath).toBe(snippet.filepath); | |
| 426 | - expect(result.newSnippet.type).toBe(snippet.type); | |
| 427 | - expect(result.newSnippet.content.length).toBeLessThanOrEqual( | |
| 428 | - snippet.content.length, | |
| 429 | - ); | |
| 430 | - | |
| 431 | - // Token count should be less than or equal to maxTokens | |
| 432 | - expect(result.newTokens).toBeLessThanOrEqual(maxTokens); | |
| 433 | - }); | |
| 434 | -}); |
added core/autocomplete/templating/__tests__/formatOpenedFilesContext.vitest.ts +435 −0
| @@ -0,0 +1,435 @@ | ||
| 1 | +/** | |
| 2 | + * Comprehensive tests for formatOpenedFilesContext.ts | |
| 3 | + * | |
| 4 | + */ | |
| 5 | + | |
| 6 | +import { describe, expect, test } from "vitest"; | |
| 7 | +import { | |
| 8 | + AutocompleteCodeSnippet, | |
| 9 | + AutocompleteDiffSnippet, | |
| 10 | + AutocompleteSnippetType, | |
| 11 | +} from "../../snippets/types"; | |
| 12 | +import { HelperVars } from "../../util/HelperVars"; | |
| 13 | +import { formatOpenedFilesContext } from "../formatOpenedFilesContext"; | |
| 14 | + | |
| 15 | +// Import the now-exported internal functions | |
| 16 | +import { | |
| 17 | + getRecencyAndSizeScore, | |
| 18 | + rankByScore, | |
| 19 | + setLogStats, | |
| 20 | + trimSnippetForContext, | |
| 21 | +} from "../formatOpenedFilesContext"; | |
| 22 | + | |
| 23 | +describe("formatOpenedFilesContext main function tests", () => { | |
| 24 | + const mockHelper = { | |
| 25 | + modelName: "test-model", | |
| 26 | + } as HelperVars; | |
| 27 | + | |
| 28 | + const TOKEN_BUFFER = 50; | |
| 29 | + | |
| 30 | + // Create sample code snippets with various sizes | |
| 31 | + const createCodeSnippet = ( | |
| 32 | + filepath: string, | |
| 33 | + content: string, | |
| 34 | + ): AutocompleteCodeSnippet => ({ | |
| 35 | + type: AutocompleteSnippetType.Code, | |
| 36 | + filepath, | |
| 37 | + content, | |
| 38 | + }); | |
| 39 | + | |
| 40 | + const createDiffSnippet = (content: string): AutocompleteDiffSnippet => ({ | |
| 41 | + type: AutocompleteSnippetType.Diff, | |
| 42 | + content, | |
| 43 | + }); | |
| 44 | + | |
| 45 | + test("should return empty array when no snippets are provided", () => { | |
| 46 | + const result = formatOpenedFilesContext( | |
| 47 | + [], | |
| 48 | + 1000, | |
| 49 | + mockHelper, | |
| 50 | + [], | |
| 51 | + TOKEN_BUFFER, | |
| 52 | + ); | |
| 53 | + expect(result).toEqual([]); | |
| 54 | + }); | |
| 55 | + | |
| 56 | + test("should handle zero remaining token count", () => { | |
| 57 | + const snippets = [ | |
| 58 | + createCodeSnippet("file1.ts", "content of file 1"), | |
| 59 | + createCodeSnippet("file2.ts", "content of file 2"), | |
| 60 | + ]; | |
| 61 | + | |
| 62 | + const result = formatOpenedFilesContext( | |
| 63 | + snippets, | |
| 64 | + 0, | |
| 65 | + mockHelper, | |
| 66 | + [], | |
| 67 | + TOKEN_BUFFER, | |
| 68 | + ); | |
| 69 | + | |
| 70 | + expect(result).toEqual([]); | |
| 71 | + }); | |
| 72 | + | |
| 73 | + test("should handle snippets with empty content", () => { | |
| 74 | + const emptySnippets = [ | |
| 75 | + createCodeSnippet("empty1.ts", ""), | |
| 76 | + createCodeSnippet("empty2.ts", ""), | |
| 77 | + ]; | |
| 78 | + | |
| 79 | + const result = formatOpenedFilesContext( | |
| 80 | + emptySnippets, | |
| 81 | + 1000, | |
| 82 | + mockHelper, | |
| 83 | + [], | |
| 84 | + TOKEN_BUFFER, | |
| 85 | + ); | |
| 86 | + | |
| 87 | + expect(result.length).toBe(emptySnippets.length); | |
| 88 | + }); | |
| 89 | + | |
| 90 | + test("should return all snippets when they all fit within token limit", () => { | |
| 91 | + const smallSnippets = [ | |
| 92 | + createCodeSnippet("small1.ts", "a"), | |
| 93 | + createCodeSnippet("small2.ts", "b"), | |
| 94 | + createCodeSnippet("small3.ts", "c"), | |
| 95 | + ]; | |
| 96 | + | |
| 97 | + const result = formatOpenedFilesContext( | |
| 98 | + smallSnippets, | |
| 99 | + 1000, | |
| 100 | + mockHelper, | |
| 101 | + [], | |
| 102 | + TOKEN_BUFFER, | |
| 103 | + ); | |
| 104 | + | |
| 105 | + expect(result.length).toBe(smallSnippets.length); | |
| 106 | + }); | |
| 107 | + | |
| 108 | + test("should handle limited token count", () => { | |
| 109 | + const snippets = Array(10) | |
| 110 | + .fill(0) | |
| 111 | + .map((_, i) => createCodeSnippet(`file${i}.ts`, `content of file ${i}`)); | |
| 112 | + | |
| 113 | + const result = formatOpenedFilesContext( | |
| 114 | + snippets, | |
| 115 | + 1, // Extremely small token count | |
| 116 | + mockHelper, | |
| 117 | + [], | |
| 118 | + TOKEN_BUFFER, | |
| 119 | + ); | |
| 120 | + | |
| 121 | + expect(Array.isArray(result)).toBe(true); | |
| 122 | + }); | |
| 123 | + | |
| 124 | + test("should accept valid inputs with adequate token count", () => { | |
| 125 | + const snippets = [ | |
| 126 | + createCodeSnippet("file1.ts", "Some content here"), | |
| 127 | + createCodeSnippet("file2.ts", "More content here"), | |
| 128 | + ]; | |
| 129 | + | |
| 130 | + const result = formatOpenedFilesContext( | |
| 131 | + snippets, | |
| 132 | + 1000, | |
| 133 | + mockHelper, | |
| 134 | + [], | |
| 135 | + TOKEN_BUFFER, | |
| 136 | + ); | |
| 137 | + | |
| 138 | + expect(result.length).toBeGreaterThan(0); | |
| 139 | + }); | |
| 140 | + | |
| 141 | + test("should handle already added snippets parameter", () => { | |
| 142 | + const snippets = [ | |
| 143 | + createCodeSnippet("file1.ts", "content of file 1"), | |
| 144 | + createCodeSnippet("file2.ts", "content of file 2"), | |
| 145 | + ]; | |
| 146 | + | |
| 147 | + const alreadyAddedSnippets = [createDiffSnippet("diff content")]; | |
| 148 | + | |
| 149 | + const result = formatOpenedFilesContext( | |
| 150 | + snippets, | |
| 151 | + 1000, | |
| 152 | + mockHelper, | |
| 153 | + alreadyAddedSnippets, | |
| 154 | + TOKEN_BUFFER, | |
| 155 | + ); | |
| 156 | + | |
| 157 | + expect(result.length).toBe(snippets.length); | |
| 158 | + }); | |
| 159 | + | |
| 160 | + test("should handle large snippets by trimming them", () => { | |
| 161 | + const largeSnippet = createCodeSnippet("large.ts", "x".repeat(10000)); | |
| 162 | + | |
| 163 | + const result = formatOpenedFilesContext( | |
| 164 | + [largeSnippet], | |
| 165 | + 200, | |
| 166 | + mockHelper, | |
| 167 | + [], | |
| 168 | + TOKEN_BUFFER, | |
| 169 | + ); | |
| 170 | + | |
| 171 | + expect(result.length).toBe(1); | |
| 172 | + expect(result[0].filepath).toBe(largeSnippet.filepath); | |
| 173 | + expect(result[0].content.length).toBeLessThan(largeSnippet.content.length); | |
| 174 | + }); | |
| 175 | + | |
| 176 | + test("should prioritize more recent snippets when not all fit", () => { | |
| 177 | + const snippets = [ | |
| 178 | + createCodeSnippet("recent1.ts", "a".repeat(10)), | |
| 179 | + createCodeSnippet("recent2.ts", "b".repeat(10000)), | |
| 180 | + createCodeSnippet("recent3.ts", "c".repeat(10000)), | |
| 181 | + ]; | |
| 182 | + | |
| 183 | + const result = formatOpenedFilesContext( | |
| 184 | + snippets, | |
| 185 | + 200, | |
| 186 | + mockHelper, | |
| 187 | + [], | |
| 188 | + TOKEN_BUFFER, | |
| 189 | + ); | |
| 190 | + | |
| 191 | + expect(result.length).toBeGreaterThan(0); | |
| 192 | + expect(result.some((s) => s.filepath === "recent1.ts")).toBe(true); | |
| 193 | + }); | |
| 194 | + | |
| 195 | + test("should handle a mix of large and small snippets effectively", () => { | |
| 196 | + const mixedSnippets = [ | |
| 197 | + createCodeSnippet("small1.ts", "a".repeat(10)), | |
| 198 | + createCodeSnippet("large1.ts", "b".repeat(5000)), | |
| 199 | + createCodeSnippet("small2.ts", "c".repeat(10)), | |
| 200 | + createCodeSnippet("large2.ts", "d".repeat(5000)), | |
| 201 | + ]; | |
| 202 | + | |
| 203 | + const result = formatOpenedFilesContext( | |
| 204 | + mixedSnippets, | |
| 205 | + 500, | |
| 206 | + mockHelper, | |
| 207 | + [], | |
| 208 | + TOKEN_BUFFER, | |
| 209 | + ); | |
| 210 | + | |
| 211 | + expect(result.length).toBeGreaterThan(0); | |
| 212 | + expect(result.some((s) => s.filepath.startsWith("small"))).toBe(true); | |
| 213 | + }); | |
| 214 | + | |
| 215 | + test("should respect minimum token threshold when trimming", () => { | |
| 216 | + const largeSnippets = [ | |
| 217 | + createCodeSnippet("large1.ts", "a".repeat(5000)), | |
| 218 | + createCodeSnippet("large2.ts", "b".repeat(5000)), | |
| 219 | + ]; | |
| 220 | + | |
| 221 | + const result = formatOpenedFilesContext( | |
| 222 | + largeSnippets, | |
| 223 | + 150, | |
| 224 | + mockHelper, | |
| 225 | + [], | |
| 226 | + TOKEN_BUFFER, | |
| 227 | + ); | |
| 228 | + | |
| 229 | + expect(result.length).toBeLessThanOrEqual(1); | |
| 230 | + | |
| 231 | + if (result.length > 0) { | |
| 232 | + expect(result[0].content.length).toBeLessThan( | |
| 233 | + largeSnippets[0].content.length, | |
| 234 | + ); | |
| 235 | + } | |
| 236 | + }); | |
| 237 | +}); | |
| 238 | + | |
| 239 | +// Tests for rankByScore function | |
| 240 | +describe("rankByScore function", () => { | |
| 241 | + const createCodeSnippet = ( | |
| 242 | + filepath: string, | |
| 243 | + content: string, | |
| 244 | + ): AutocompleteCodeSnippet => ({ | |
| 245 | + type: AutocompleteSnippetType.Code, | |
| 246 | + filepath, | |
| 247 | + content, | |
| 248 | + }); | |
| 249 | + | |
| 250 | + test("should return empty array when given empty array", () => { | |
| 251 | + const result = rankByScore([]); | |
| 252 | + expect(result).toEqual([]); | |
| 253 | + }); | |
| 254 | + | |
| 255 | + test("should rank snippets by score", () => { | |
| 256 | + // Initialize logMin and logMax by calling setLogStats first | |
| 257 | + const snippets = [ | |
| 258 | + createCodeSnippet("file1.ts", "a".repeat(10)), | |
| 259 | + createCodeSnippet("file2.ts", "b".repeat(1000)), | |
| 260 | + createCodeSnippet("file3.ts", "c".repeat(100)), | |
| 261 | + ]; | |
| 262 | + setLogStats(snippets); | |
| 263 | + | |
| 264 | + const result = rankByScore(snippets); | |
| 265 | + | |
| 266 | + expect(Array.isArray(result)).toBe(true); | |
| 267 | + expect(result.length).toBeGreaterThan(0); | |
| 268 | + | |
| 269 | + // The snippets should be ranked in some order, which may not match input order | |
| 270 | + expect(result.map((s: { filepath: any }) => s.filepath)).not.toEqual( | |
| 271 | + snippets.map((s) => s.filepath), | |
| 272 | + ); | |
| 273 | + }); | |
| 274 | + | |
| 275 | + test("should limit the number of ranked snippets to defaultNumFilesUsed", () => { | |
| 276 | + // Create more snippets than the default limit | |
| 277 | + const manySnippets = Array(10) | |
| 278 | + .fill(0) | |
| 279 | + .map((_, i) => createCodeSnippet(`file${i}.ts`, `content of file ${i}`)); | |
| 280 | + setLogStats(manySnippets); | |
| 281 | + | |
| 282 | + const result = rankByScore(manySnippets); | |
| 283 | + | |
| 284 | + // The function should limit the number of snippets (defaultNumFilesUsed is 5) | |
| 285 | + expect(result.length).toBeLessThanOrEqual(5); | |
| 286 | + }); | |
| 287 | +}); | |
| 288 | + | |
| 289 | +// Tests for getRecencyAndSizeScore function | |
| 290 | +describe("getRecencyAndSizeScore function", () => { | |
| 291 | + const createCodeSnippet = ( | |
| 292 | + filepath: string, | |
| 293 | + content: string, | |
| 294 | + ): AutocompleteCodeSnippet => ({ | |
| 295 | + type: AutocompleteSnippetType.Code, | |
| 296 | + filepath, | |
| 297 | + content, | |
| 298 | + }); | |
| 299 | + | |
| 300 | + test("recency score should decrease with higher index", () => { | |
| 301 | + // Initialize log stats first | |
| 302 | + const snippets = [ | |
| 303 | + createCodeSnippet("file1.ts", "a".repeat(100)), | |
| 304 | + createCodeSnippet("file2.ts", "b".repeat(100)), | |
| 305 | + ]; | |
| 306 | + setLogStats(snippets); | |
| 307 | + | |
| 308 | + // Test that score decreases with increasing index | |
| 309 | + const score0 = getRecencyAndSizeScore(0, snippets[0]); | |
| 310 | + const score1 = getRecencyAndSizeScore(1, snippets[0]); | |
| 311 | + const score2 = getRecencyAndSizeScore(2, snippets[0]); | |
| 312 | + | |
| 313 | + expect(score0).toBeGreaterThan(score1); | |
| 314 | + expect(score1).toBeGreaterThan(score2); | |
| 315 | + }); | |
| 316 | + | |
| 317 | + test("size score should be higher for smaller snippets", () => { | |
| 318 | + // Initialize log stats first | |
| 319 | + const snippets = [ | |
| 320 | + createCodeSnippet("small.ts", "a".repeat(50)), | |
| 321 | + createCodeSnippet("medium.ts", "b".repeat(200)), | |
| 322 | + createCodeSnippet("large.ts", "c".repeat(1000)), | |
| 323 | + ]; | |
| 324 | + setLogStats(snippets); | |
| 325 | + | |
| 326 | + // Test with same recency index but different sizes | |
| 327 | + const smallScore = getRecencyAndSizeScore(0, snippets[0]); | |
| 328 | + const mediumScore = getRecencyAndSizeScore(0, snippets[1]); | |
| 329 | + const largeScore = getRecencyAndSizeScore(0, snippets[2]); | |
| 330 | + | |
| 331 | + // Scores should reflect preference for smaller snippets | |
| 332 | + expect(smallScore).toBeGreaterThanOrEqual(mediumScore); | |
| 333 | + expect(mediumScore).toBeGreaterThanOrEqual(largeScore); | |
| 334 | + }); | |
| 335 | + | |
| 336 | + test("recency and size both affect the score with recency having more weight", () => { | |
| 337 | + // Initialize log stats first | |
| 338 | + const snippets = [ | |
| 339 | + createCodeSnippet("recent_large.ts", "a".repeat(1000)), | |
| 340 | + createCodeSnippet("old_small.ts", "b".repeat(50)), | |
| 341 | + ]; | |
| 342 | + setLogStats(snippets); | |
| 343 | + | |
| 344 | + // Test that recency and size both contribute to the score | |
| 345 | + const recentLargeScore = getRecencyAndSizeScore(0, snippets[0]); | |
| 346 | + const oldSmallScore = getRecencyAndSizeScore(1, snippets[1]); | |
| 347 | + | |
| 348 | + // We're not making a direct comparison, just verifying the scoring mechanism works | |
| 349 | + expect(recentLargeScore).toBeGreaterThan(0); | |
| 350 | + expect(oldSmallScore).toBeGreaterThan(0); | |
| 351 | + expect(oldSmallScore).toBeLessThan(1); | |
| 352 | + }); | |
| 353 | +}); | |
| 354 | + | |
| 355 | +// Tests for setLogStats function | |
| 356 | +describe("setLogStats function", () => { | |
| 357 | + const createCodeSnippet = ( | |
| 358 | + filepath: string, | |
| 359 | + content: string, | |
| 360 | + ): AutocompleteCodeSnippet => ({ | |
| 361 | + type: AutocompleteSnippetType.Code, | |
| 362 | + filepath, | |
| 363 | + content, | |
| 364 | + }); | |
| 365 | + | |
| 366 | + test("should set logMin and logMax based on snippet sizes", () => { | |
| 367 | + const snippets = [ | |
| 368 | + createCodeSnippet("small.ts", "a".repeat(50)), | |
| 369 | + createCodeSnippet("medium.ts", "b".repeat(200)), | |
| 370 | + createCodeSnippet("large.ts", "c".repeat(1000)), | |
| 371 | + ]; | |
| 372 | + | |
| 373 | + // We can't directly test logMin and logMax as they're private | |
| 374 | + // but we can verify that the function runs without errors | |
| 375 | + expect(() => setLogStats(snippets)).not.toThrow(); | |
| 376 | + }); | |
| 377 | + | |
| 378 | + test("should handle empty snippets", () => { | |
| 379 | + const emptySnippets = [ | |
| 380 | + createCodeSnippet("empty1.ts", ""), | |
| 381 | + createCodeSnippet("empty2.ts", ""), | |
| 382 | + ]; | |
| 383 | + | |
| 384 | + expect(() => setLogStats(emptySnippets)).not.toThrow(); | |
| 385 | + }); | |
| 386 | + | |
| 387 | + test("should handle single snippet", () => { | |
| 388 | + const singleSnippet = [createCodeSnippet("single.ts", "content")]; | |
| 389 | + | |
| 390 | + expect(() => setLogStats(singleSnippet)).not.toThrow(); | |
| 391 | + }); | |
| 392 | +}); | |
| 393 | + | |
| 394 | +// Tests for trimSnippetForContext function | |
| 395 | +describe("trimSnippetForContext function", () => { | |
| 396 | + const createCodeSnippet = ( | |
| 397 | + filepath: string, | |
| 398 | + content: string, | |
| 399 | + ): AutocompleteCodeSnippet => ({ | |
| 400 | + type: AutocompleteSnippetType.Code, | |
| 401 | + filepath, | |
| 402 | + content, | |
| 403 | + }); | |
| 404 | + | |
| 405 | + test("should return original snippet if it fits within token limit", () => { | |
| 406 | + const snippet = createCodeSnippet("small.ts", "small content"); | |
| 407 | + const modelName = "test-model"; | |
| 408 | + const maxTokens = 1000; // Large enough to fit the snippet | |
| 409 | + | |
| 410 | + const result = trimSnippetForContext(snippet, maxTokens, modelName); | |
| 411 | + | |
| 412 | + // Should return the original snippet with its token count | |
| 413 | + expect(result.newSnippet).toEqual(snippet); | |
| 414 | + expect(typeof result.newTokens).toBe("number"); | |
| 415 | + expect(result.newTokens).toBeGreaterThan(0); | |
| 416 | + }); | |
| 417 | + | |
| 418 | + test("should trim snippet content if it exceeds token limit", () => { | |
| 419 | + const snippet = createCodeSnippet("large.ts", "a".repeat(1000)); | |
| 420 | + const modelName = "test-model"; | |
| 421 | + const maxTokens = 10; // Small enough to require trimming | |
| 422 | + | |
| 423 | + const result = trimSnippetForContext(snippet, maxTokens, modelName); | |
| 424 | + | |
| 425 | + // Should return a trimmed snippet | |
| 426 | + expect(result.newSnippet.filepath).toBe(snippet.filepath); | |
| 427 | + expect(result.newSnippet.type).toBe(snippet.type); | |
| 428 | + expect(result.newSnippet.content.length).toBeLessThanOrEqual( | |
| 429 | + snippet.content.length, | |
| 430 | + ); | |
| 431 | + | |
| 432 | + // Token count should be less than or equal to maxTokens | |
| 433 | + expect(result.newTokens).toBeLessThanOrEqual(maxTokens); | |
| 434 | + }); | |
| 435 | +}); |
deleted core/autocomplete/util/completionTestUtils.test.ts +0 −65
| @@ -1,65 +0,0 @@ | ||
| 1 | -import { | |
| 2 | - processTestCase, | |
| 3 | - type CompletionTestCase, | |
| 4 | -} from "./completionTestUtils"; | |
| 5 | - | |
| 6 | -describe("processTestCase utility", () => { | |
| 7 | - it("processes simple console.log completion", () => { | |
| 8 | - const testCase: CompletionTestCase = { | |
| 9 | - original: "console.log(|cur||till|)", | |
| 10 | - completion: '"foo,", bar', | |
| 11 | - }; | |
| 12 | - | |
| 13 | - expect(processTestCase(testCase)).toEqual({ | |
| 14 | - input: { | |
| 15 | - lastLineOfCompletionText: '"foo,", bar', | |
| 16 | - currentText: ")", | |
| 17 | - cursorPosition: "console.log(".length, | |
| 18 | - }, | |
| 19 | - expectedResult: { | |
| 20 | - completionText: '"foo,", bar', | |
| 21 | - }, | |
| 22 | - }); | |
| 23 | - }); | |
| 24 | - | |
| 25 | - it("processes simple console.log completion with overwriting", () => { | |
| 26 | - const testCase: CompletionTestCase = { | |
| 27 | - original: "console.log(|cur|)|till|", | |
| 28 | - completion: '"foo,", bar);', | |
| 29 | - }; | |
| 30 | - | |
| 31 | - expect(processTestCase(testCase)).toEqual({ | |
| 32 | - input: { | |
| 33 | - lastLineOfCompletionText: '"foo,", bar);', | |
| 34 | - currentText: ")", | |
| 35 | - cursorPosition: "console.log(".length, | |
| 36 | - }, | |
| 37 | - expectedResult: { | |
| 38 | - completionText: '"foo,", bar);', | |
| 39 | - range: { | |
| 40 | - start: "console.log(".length, | |
| 41 | - end: "console.log()".length, | |
| 42 | - }, | |
| 43 | - }, | |
| 44 | - }); | |
| 45 | - }); | |
| 46 | - | |
| 47 | - it("partially applying completion", () => { | |
| 48 | - const testCase: CompletionTestCase = { | |
| 49 | - original: '|cur||till|fetch("https://example.com");', | |
| 50 | - completion: 'await fetch("https://example.com");', | |
| 51 | - appliedCompletion: "await ", | |
| 52 | - }; | |
| 53 | - | |
| 54 | - expect(processTestCase(testCase)).toEqual({ | |
| 55 | - input: { | |
| 56 | - lastLineOfCompletionText: 'await fetch("https://example.com");', | |
| 57 | - currentText: 'fetch("https://example.com");', | |
| 58 | - cursorPosition: 0, | |
| 59 | - }, | |
| 60 | - expectedResult: { | |
| 61 | - completionText: "await ", | |
| 62 | - }, | |
| 63 | - }); | |
| 64 | - }); | |
| 65 | -}); |
added core/autocomplete/util/completionTestUtils.vitest.ts +66 −0
| @@ -0,0 +1,66 @@ | ||
| 1 | +import { describe, expect, it } from "vitest"; | |
| 2 | +import { | |
| 3 | + processTestCase, | |
| 4 | + type CompletionTestCase, | |
| 5 | +} from "./completionTestUtils"; | |
| 6 | + | |
| 7 | +describe("processTestCase utility", () => { | |
| 8 | + it("processes simple console.log completion", () => { | |
| 9 | + const testCase: CompletionTestCase = { | |
| 10 | + original: "console.log(|cur||till|)", | |
| 11 | + completion: '"foo,", bar', | |
| 12 | + }; | |
| 13 | + | |
| 14 | + expect(processTestCase(testCase)).toEqual({ | |
| 15 | + input: { | |
| 16 | + lastLineOfCompletionText: '"foo,", bar', | |
| 17 | + currentText: ")", | |
| 18 | + cursorPosition: "console.log(".length, | |
| 19 | + }, | |
| 20 | + expectedResult: { | |
| 21 | + completionText: '"foo,", bar', | |
| 22 | + }, | |
| 23 | + }); | |
| 24 | + }); | |
| 25 | + | |
| 26 | + it("processes simple console.log completion with overwriting", () => { | |
| 27 | + const testCase: CompletionTestCase = { | |
| 28 | + original: "console.log(|cur|)|till|", | |
| 29 | + completion: '"foo,", bar);', | |
| 30 | + }; | |
| 31 | + | |
| 32 | + expect(processTestCase(testCase)).toEqual({ | |
| 33 | + input: { | |
| 34 | + lastLineOfCompletionText: '"foo,", bar);', | |
| 35 | + currentText: ")", | |
| 36 | + cursorPosition: "console.log(".length, | |
| 37 | + }, | |
| 38 | + expectedResult: { | |
| 39 | + completionText: '"foo,", bar);', | |
| 40 | + range: { | |
| 41 | + start: "console.log(".length, | |
| 42 | + end: "console.log()".length, | |
| 43 | + }, | |
| 44 | + }, | |
| 45 | + }); | |
| 46 | + }); | |
| 47 | + | |
| 48 | + it("partially applying completion", () => { | |
| 49 | + const testCase: CompletionTestCase = { | |
| 50 | + original: '|cur||till|fetch("https://example.com");', | |
| 51 | + completion: 'await fetch("https://example.com");', | |
| 52 | + appliedCompletion: "await ", | |
| 53 | + }; | |
| 54 | + | |
| 55 | + expect(processTestCase(testCase)).toEqual({ | |
| 56 | + input: { | |
| 57 | + lastLineOfCompletionText: 'await fetch("https://example.com");', | |
| 58 | + currentText: 'fetch("https://example.com");', | |
| 59 | + cursorPosition: 0, | |
| 60 | + }, | |
| 61 | + expectedResult: { | |
| 62 | + completionText: "await ", | |
| 63 | + }, | |
| 64 | + }); | |
| 65 | + }); | |
| 66 | +}); |
deleted core/autocomplete/util/processSingleLineCompletion.test.ts +0 −95
| @@ -1,95 +0,0 @@ | ||
| 1 | -import { processTestCase } from "./completionTestUtils"; | |
| 2 | -import { processSingleLineCompletion } from "./processSingleLineCompletion"; | |
| 3 | - | |
| 4 | -describe("processSingleLineCompletion", () => { | |
| 5 | - it("should handle simple end of line completion", () => { | |
| 6 | - const testCase = processTestCase({ | |
| 7 | - original: "console.log(|cur|", | |
| 8 | - completion: '"Hello, world!")', | |
| 9 | - }); | |
| 10 | - | |
| 11 | - const result = processSingleLineCompletion( | |
| 12 | - testCase.input.lastLineOfCompletionText, | |
| 13 | - testCase.input.currentText, | |
| 14 | - testCase.input.cursorPosition, | |
| 15 | - ); | |
| 16 | - | |
| 17 | - expect(result).toEqual(testCase.expectedResult); | |
| 18 | - }); | |
| 19 | - | |
| 20 | - it("should handle midline insert repeating the end of line", () => { | |
| 21 | - const testCase = processTestCase({ | |
| 22 | - original: "console.log(|cur|);|till|", | |
| 23 | - completion: '"Hello, world!");', | |
| 24 | - }); | |
| 25 | - | |
| 26 | - const result = processSingleLineCompletion( | |
| 27 | - testCase.input.lastLineOfCompletionText, | |
| 28 | - testCase.input.currentText, | |
| 29 | - testCase.input.cursorPosition, | |
| 30 | - ); | |
| 31 | - | |
| 32 | - expect(result).toEqual(testCase.expectedResult); | |
| 33 | - }); | |
| 34 | - | |
| 35 | - it("should handle midline insert repeating the end of line plus adding a semicolon", () => { | |
| 36 | - const testCase = processTestCase({ | |
| 37 | - original: "console.log(|cur|)|till|", | |
| 38 | - completion: '"Hello, world!");', | |
| 39 | - }); | |
| 40 | - | |
| 41 | - const result = processSingleLineCompletion( | |
| 42 | - testCase.input.lastLineOfCompletionText, | |
| 43 | - testCase.input.currentText, | |
| 44 | - testCase.input.cursorPosition, | |
| 45 | - ); | |
| 46 | - | |
| 47 | - expect(result).toEqual(testCase.expectedResult); | |
| 48 | - }); | |
| 49 | - | |
| 50 | - it("should handle simple midline insert", () => { | |
| 51 | - const testCase = processTestCase({ | |
| 52 | - original: "console.log(|cur|)", | |
| 53 | - completion: '"Hello, world!"', | |
| 54 | - }); | |
| 55 | - | |
| 56 | - const result = processSingleLineCompletion( | |
| 57 | - testCase.input.lastLineOfCompletionText, | |
| 58 | - testCase.input.currentText, | |
| 59 | - testCase.input.cursorPosition, | |
| 60 | - ); | |
| 61 | - | |
| 62 | - expect(result).toEqual(testCase.expectedResult); | |
| 63 | - }); | |
| 64 | - | |
| 65 | - it("should handle complex dif with addition in the beginning", () => { | |
| 66 | - const testCase = processTestCase({ | |
| 67 | - original: 'console.log(|cur||till|, "param1", )', // TODO | |
| 68 | - completion: '"Hello world!", "param1", param1);', | |
| 69 | - appliedCompletion: '"Hello world!"', | |
| 70 | - }); | |
| 71 | - | |
| 72 | - const result = processSingleLineCompletion( | |
| 73 | - testCase.input.lastLineOfCompletionText, | |
| 74 | - testCase.input.currentText, | |
| 75 | - testCase.input.cursorPosition, | |
| 76 | - ); | |
| 77 | - | |
| 78 | - expect(result).toEqual(testCase.expectedResult); | |
| 79 | - }); | |
| 80 | - | |
| 81 | - it("should handle simple insertion even with random equality", () => { | |
| 82 | - const testCase = processTestCase({ | |
| 83 | - original: 'print(f"Foobar length: |cur||till|")', | |
| 84 | - completion: "{len(foobar)}", | |
| 85 | - }); | |
| 86 | - | |
| 87 | - const result = processSingleLineCompletion( | |
| 88 | - testCase.input.lastLineOfCompletionText, | |
| 89 | - testCase.input.currentText, | |
| 90 | - testCase.input.cursorPosition, | |
| 91 | - ); | |
| 92 | - | |
| 93 | - expect(result).toEqual(testCase.expectedResult); | |
| 94 | - }); | |
| 95 | -}); |
added core/autocomplete/util/processSingleLineCompletion.vitest.ts +96 −0
| @@ -0,0 +1,96 @@ | ||
| 1 | +import { describe, expect, it } from "vitest"; | |
| 2 | +import { processTestCase } from "./completionTestUtils"; | |
| 3 | +import { processSingleLineCompletion } from "./processSingleLineCompletion"; | |
| 4 | + | |
| 5 | +describe("processSingleLineCompletion", () => { | |
| 6 | + it("should handle simple end of line completion", () => { | |
| 7 | + const testCase = processTestCase({ | |
| 8 | + original: "console.log(|cur|", | |
| 9 | + completion: '"Hello, world!")', | |
| 10 | + }); | |
| 11 | + | |
| 12 | + const result = processSingleLineCompletion( | |
| 13 | + testCase.input.lastLineOfCompletionText, | |
| 14 | + testCase.input.currentText, | |
| 15 | + testCase.input.cursorPosition, | |
| 16 | + ); | |
| 17 | + | |
| 18 | + expect(result).toEqual(testCase.expectedResult); | |
| 19 | + }); | |
| 20 | + | |
| 21 | + it("should handle midline insert repeating the end of line", () => { | |
| 22 | + const testCase = processTestCase({ | |
| 23 | + original: "console.log(|cur|);|till|", | |
| 24 | + completion: '"Hello, world!");', | |
| 25 | + }); | |
| 26 | + | |
| 27 | + const result = processSingleLineCompletion( | |
| 28 | + testCase.input.lastLineOfCompletionText, | |
| 29 | + testCase.input.currentText, | |
| 30 | + testCase.input.cursorPosition, | |
| 31 | + ); | |
| 32 | + | |
| 33 | + expect(result).toEqual(testCase.expectedResult); | |
| 34 | + }); | |
| 35 | + | |
| 36 | + it("should handle midline insert repeating the end of line plus adding a semicolon", () => { | |
| 37 | + const testCase = processTestCase({ | |
| 38 | + original: "console.log(|cur|)|till|", | |
| 39 | + completion: '"Hello, world!");', | |
| 40 | + }); | |
| 41 | + | |
| 42 | + const result = processSingleLineCompletion( | |
| 43 | + testCase.input.lastLineOfCompletionText, | |
| 44 | + testCase.input.currentText, | |
| 45 | + testCase.input.cursorPosition, | |
| 46 | + ); | |
| 47 | + | |
| 48 | + expect(result).toEqual(testCase.expectedResult); | |
| 49 | + }); | |
| 50 | + | |
| 51 | + it("should handle simple midline insert", () => { | |
| 52 | + const testCase = processTestCase({ | |
| 53 | + original: "console.log(|cur|)", | |
| 54 | + completion: '"Hello, world!"', | |
| 55 | + }); | |
| 56 | + | |
| 57 | + const result = processSingleLineCompletion( | |
| 58 | + testCase.input.lastLineOfCompletionText, | |
| 59 | + testCase.input.currentText, | |
| 60 | + testCase.input.cursorPosition, | |
| 61 | + ); | |
| 62 | + | |
| 63 | + expect(result).toEqual(testCase.expectedResult); | |
| 64 | + }); | |
| 65 | + | |
| 66 | + it("should handle complex dif with addition in the beginning", () => { | |
| 67 | + const testCase = processTestCase({ | |
| 68 | + original: 'console.log(|cur||till|, "param1", )', // TODO | |
| 69 | + completion: '"Hello world!", "param1", param1);', | |
| 70 | + appliedCompletion: '"Hello world!"', | |
| 71 | + }); | |
| 72 | + | |
| 73 | + const result = processSingleLineCompletion( | |
| 74 | + testCase.input.lastLineOfCompletionText, | |
| 75 | + testCase.input.currentText, | |
| 76 | + testCase.input.cursorPosition, | |
| 77 | + ); | |
| 78 | + | |
| 79 | + expect(result).toEqual(testCase.expectedResult); | |
| 80 | + }); | |
| 81 | + | |
| 82 | + it("should handle simple insertion even with random equality", () => { | |
| 83 | + const testCase = processTestCase({ | |
| 84 | + original: 'print(f"Foobar length: |cur||till|")', | |
| 85 | + completion: "{len(foobar)}", | |
| 86 | + }); | |
| 87 | + | |
| 88 | + const result = processSingleLineCompletion( | |
| 89 | + testCase.input.lastLineOfCompletionText, | |
| 90 | + testCase.input.currentText, | |
| 91 | + testCase.input.cursorPosition, | |
| 92 | + ); | |
| 93 | + | |
| 94 | + expect(result).toEqual(testCase.expectedResult); | |
| 95 | + }); | |
| 96 | +}); |
modified core/config/ProfileLifecycleManager.ts +32 −30
| @@ -87,38 +87,40 @@ | ||
| 87 | 87 | } |
| 88 | 88 | |
| 89 | 89 | // Set pending config promise |
| 90 | - this.pendingConfigPromise = new Promise(async (resolve, reject) => { | |
| 91 | - let result: ConfigResult<ContinueConfig>; | |
| 92 | - // This try catch is expected to catch high-level errors that aren't block-specific | |
| 93 | - // Like invalid json, invalid yaml, file read errors, etc. | |
| 94 | - // NOT block-specific loading errors | |
| 95 | - try { | |
| 96 | - result = await this.profileLoader.doLoadConfig(); | |
| 97 | - } catch (e) { | |
| 98 | - const message = | |
| 99 | - e instanceof Error | |
| 100 | - ? `${e.message}\n${e.stack ? e.stack : ""}` | |
| 101 | - : "Error loading config"; | |
| 102 | - result = { | |
| 103 | - errors: [ | |
| 104 | - { | |
| 105 | - fatal: true, | |
| 106 | - message, | |
| 107 | - }, | |
| 108 | - ], | |
| 109 | - config: undefined, | |
| 110 | - configLoadInterrupted: true, | |
| 111 | - }; | |
| 112 | - } | |
| 90 | + this.pendingConfigPromise = new Promise((resolve) => { | |
| 91 | + void (async () => { | |
| 92 | + let result: ConfigResult<ContinueConfig>; | |
| 93 | + // This try catch is expected to catch high-level errors that aren't block-specific | |
| 94 | + // Like invalid json, invalid yaml, file read errors, etc. | |
| 95 | + // NOT block-specific loading errors | |
| 96 | + try { | |
| 97 | + result = await this.profileLoader.doLoadConfig(); | |
| 98 | + } catch (e) { | |
| 99 | + const message = | |
| 100 | + e instanceof Error | |
| 101 | + ? `${e.message}\n${e.stack ? e.stack : ""}` | |
| 102 | + : "Error loading config"; | |
| 103 | + result = { | |
| 104 | + errors: [ | |
| 105 | + { | |
| 106 | + fatal: true, | |
| 107 | + message, | |
| 108 | + }, | |
| 109 | + ], | |
| 110 | + config: undefined, | |
| 111 | + configLoadInterrupted: true, | |
| 112 | + }; | |
| 113 | + } | |
| 113 | 114 | |
| 114 | - if (result.config) { | |
| 115 | - // Add registered context providers | |
| 116 | - result.config.contextProviders = ( | |
| 117 | - result.config.contextProviders ?? [] | |
| 118 | - ).concat(additionalContextProviders); | |
| 119 | - } | |
| 115 | + if (result.config) { | |
| 116 | + // Add registered context providers | |
| 117 | + result.config.contextProviders = ( | |
| 118 | + result.config.contextProviders ?? [] | |
| 119 | + ).concat(additionalContextProviders); | |
| 120 | + } | |
| 120 | 121 | |
| 121 | - resolve(result); | |
| 122 | + resolve(result); | |
| 123 | + })(); | |
| 122 | 124 | }); |
| 123 | 125 | |
| 124 | 126 | // Wait for the config promise to resolve |
added core/config/loadLocalAssistants.test.ts +241 −0
| @@ -0,0 +1,241 @@ | ||
| 1 | +import { walkDirCache } from "../indexing/walkDir"; | |
| 2 | +import { testIde } from "../test/fixtures"; | |
| 3 | +import { addToTestDir, setUpTestDir, tearDownTestDir } from "../test/testDir"; | |
| 4 | +import { | |
| 5 | + getAllDotContinueDefinitionFiles, | |
| 6 | + LoadAssistantFilesOptions, | |
| 7 | +} from "./loadLocalAssistants"; | |
| 8 | +describe("getAllDotContinueDefinitionFiles with fileExtType option", () => { | |
| 9 | + beforeEach(() => { | |
| 10 | + setUpTestDir(); | |
| 11 | + walkDirCache.invalidate(); | |
| 12 | + | |
| 13 | + // Add test files to the test directory | |
| 14 | + addToTestDir([ | |
| 15 | + ".continue/assistants/", | |
| 16 | + [".continue/assistants/assistant1.yaml", "yaml content 1"], | |
| 17 | + [".continue/assistants/assistant2.yml", "yaml content 2"], | |
| 18 | + [".continue/assistants/assistant3.md", "markdown content 1"], | |
| 19 | + [".continue/assistants/assistant4.txt", "txt content"], | |
| 20 | + ]); | |
| 21 | + }); | |
| 22 | + | |
| 23 | + afterEach(() => { | |
| 24 | + tearDownTestDir(); | |
| 25 | + walkDirCache.invalidate(); | |
| 26 | + }); | |
| 27 | + | |
| 28 | + it("should return only YAML files when fileExtType is 'yaml'", async () => { | |
| 29 | + const options: LoadAssistantFilesOptions = { | |
| 30 | + includeGlobal: false, // Only test workspace for simplicity | |
| 31 | + includeWorkspace: true, | |
| 32 | + fileExtType: "yaml", | |
| 33 | + }; | |
| 34 | + | |
| 35 | + const result = await getAllDotContinueDefinitionFiles( | |
| 36 | + testIde, | |
| 37 | + options, | |
| 38 | + "assistants", | |
| 39 | + ); | |
| 40 | + expect(result).toHaveLength(2); | |
| 41 | + expect(result.map((f) => f.path.split("/").pop())).toEqual( | |
| 42 | + expect.arrayContaining(["assistant1.yaml", "assistant2.yml"]), | |
| 43 | + ); | |
| 44 | + expect(result.map((f) => f.path.split("/").pop())).not.toContain( | |
| 45 | + "assistant3.md", | |
| 46 | + ); | |
| 47 | + }); | |
| 48 | + | |
| 49 | + it("should return only Markdown files when fileExtType is 'markdown'", async () => { | |
| 50 | + const options: LoadAssistantFilesOptions = { | |
| 51 | + includeGlobal: false, | |
| 52 | + includeWorkspace: true, | |
| 53 | + fileExtType: "markdown", | |
| 54 | + }; | |
| 55 | + | |
| 56 | + const result = await getAllDotContinueDefinitionFiles( | |
| 57 | + testIde, | |
| 58 | + options, | |
| 59 | + "assistants", | |
| 60 | + ); | |
| 61 | + expect(result).toHaveLength(1); | |
| 62 | + expect(result.map((f) => f.path.split("/").pop())).toEqual([ | |
| 63 | + "assistant3.md", | |
| 64 | + ]); | |
| 65 | + expect(result.map((f) => f.path.split("/").pop())).not.toContain( | |
| 66 | + "assistant1.yaml", | |
| 67 | + ); | |
| 68 | + expect(result.map((f) => f.path.split("/").pop())).not.toContain( | |
| 69 | + "assistant2.yml", | |
| 70 | + ); | |
| 71 | + }); | |
| 72 | + | |
| 73 | + it("should return all supported files when fileExtType is not specified", async () => { | |
| 74 | + const options: LoadAssistantFilesOptions = { | |
| 75 | + includeGlobal: false, | |
| 76 | + includeWorkspace: true, | |
| 77 | + // fileExtType not specified | |
| 78 | + }; | |
| 79 | + | |
| 80 | + const result = await getAllDotContinueDefinitionFiles( | |
| 81 | + testIde, | |
| 82 | + options, | |
| 83 | + "assistants", | |
| 84 | + ); | |
| 85 | + expect(result).toHaveLength(3); | |
| 86 | + expect(result.map((f) => f.path.split("/").pop())).toEqual( | |
| 87 | + expect.arrayContaining([ | |
| 88 | + "assistant1.yaml", | |
| 89 | + "assistant2.yml", | |
| 90 | + "assistant3.md", | |
| 91 | + ]), | |
| 92 | + ); | |
| 93 | + // Should not include .txt files | |
| 94 | + expect(result.map((f) => f.path.split("/").pop())).not.toContain( | |
| 95 | + "assistant4.txt", | |
| 96 | + ); | |
| 97 | + }); | |
| 98 | + | |
| 99 | + it("should respect includeWorkspace option with fileExtType", async () => { | |
| 100 | + // Test with includeWorkspace: false | |
| 101 | + const workspaceOffOptions: LoadAssistantFilesOptions = { | |
| 102 | + includeGlobal: false, | |
| 103 | + includeWorkspace: false, | |
| 104 | + fileExtType: "yaml", | |
| 105 | + }; | |
| 106 | + | |
| 107 | + const noWorkspaceResult = await getAllDotContinueDefinitionFiles( | |
| 108 | + testIde, | |
| 109 | + workspaceOffOptions, | |
| 110 | + "assistants", | |
| 111 | + ); | |
| 112 | + expect(noWorkspaceResult).toHaveLength(0); | |
| 113 | + | |
| 114 | + // Test with includeWorkspace: true | |
| 115 | + const workspaceOnOptions: LoadAssistantFilesOptions = { | |
| 116 | + includeGlobal: false, | |
| 117 | + includeWorkspace: true, | |
| 118 | + fileExtType: "yaml", | |
| 119 | + }; | |
| 120 | + | |
| 121 | + const workspaceResult = await getAllDotContinueDefinitionFiles( | |
| 122 | + testIde, | |
| 123 | + workspaceOnOptions, | |
| 124 | + "assistants", | |
| 125 | + ); | |
| 126 | + expect(workspaceResult).toHaveLength(2); | |
| 127 | + expect(workspaceResult.map((f) => f.path.split("/").pop())).toEqual( | |
| 128 | + expect.arrayContaining(["assistant1.yaml", "assistant2.yml"]), | |
| 129 | + ); | |
| 130 | + }); | |
| 131 | + | |
| 132 | + it("should return empty array when no files match the specified extension type", async () => { | |
| 133 | + // Create a test directory with only non-matching files | |
| 134 | + tearDownTestDir(); | |
| 135 | + walkDirCache.invalidate(); | |
| 136 | + setUpTestDir(); | |
| 137 | + addToTestDir([ | |
| 138 | + ".continue/assistants/", | |
| 139 | + [".continue/assistants/nonmatch1.txt", "txt content"], | |
| 140 | + [".continue/assistants/nonmatch2.json", "json content"], | |
| 141 | + ]); | |
| 142 | + | |
| 143 | + const options: LoadAssistantFilesOptions = { | |
| 144 | + includeGlobal: false, | |
| 145 | + includeWorkspace: true, | |
| 146 | + | |
| 147 | + fileExtType: "yaml", | |
| 148 | + }; | |
| 149 | + | |
| 150 | + const result = await getAllDotContinueDefinitionFiles( | |
| 151 | + testIde, | |
| 152 | + options, | |
| 153 | + "assistants", | |
| 154 | + ); | |
| 155 | + expect(result).toHaveLength(0); | |
| 156 | + }); | |
| 157 | + | |
| 158 | + it("should handle directories that don't exist", async () => { | |
| 159 | + // Create a clean test directory without the assistants folder | |
| 160 | + tearDownTestDir(); | |
| 161 | + setUpTestDir(); | |
| 162 | + | |
| 163 | + const options: LoadAssistantFilesOptions = { | |
| 164 | + includeGlobal: false, | |
| 165 | + includeWorkspace: true, | |
| 166 | + fileExtType: "yaml", | |
| 167 | + }; | |
| 168 | + | |
| 169 | + const result = await getAllDotContinueDefinitionFiles( | |
| 170 | + testIde, | |
| 171 | + options, | |
| 172 | + "assistants", | |
| 173 | + ); | |
| 174 | + expect(result).toHaveLength(0); | |
| 175 | + }); | |
| 176 | + | |
| 177 | + it("should return correct file content", async () => { | |
| 178 | + const options: LoadAssistantFilesOptions = { | |
| 179 | + includeGlobal: false, | |
| 180 | + includeWorkspace: true, | |
| 181 | + fileExtType: "yaml", | |
| 182 | + }; | |
| 183 | + | |
| 184 | + const result = await getAllDotContinueDefinitionFiles( | |
| 185 | + testIde, | |
| 186 | + options, | |
| 187 | + "assistants", | |
| 188 | + ); | |
| 189 | + expect(result).toHaveLength(2); | |
| 190 | + const yamlFile = result.find((f) => f.path.includes("assistant1.yaml")); | |
| 191 | + expect(yamlFile?.content).toBe("yaml content 1"); | |
| 192 | + }); | |
| 193 | + | |
| 194 | + it("should filter by file extension case sensitively", async () => { | |
| 195 | + // Add files with uppercase extensions | |
| 196 | + addToTestDir([ | |
| 197 | + [".continue/assistants/assistant5.YAML", "uppercase yaml"], | |
| 198 | + [".continue/assistants/assistant6.YML", "uppercase yml"], | |
| 199 | + [".continue/assistants/assistant7.MD", "uppercase md"], | |
| 200 | + ]); | |
| 201 | + | |
| 202 | + const yamlOptions: LoadAssistantFilesOptions = { | |
| 203 | + includeGlobal: false, | |
| 204 | + includeWorkspace: true, | |
| 205 | + fileExtType: "yaml", | |
| 206 | + }; | |
| 207 | + | |
| 208 | + const yamlResult = await getAllDotContinueDefinitionFiles( | |
| 209 | + testIde, | |
| 210 | + yamlOptions, | |
| 211 | + "assistants", | |
| 212 | + ); | |
| 213 | + // Should only get lowercase extensions (current implementation) | |
| 214 | + expect(yamlResult).toHaveLength(2); | |
| 215 | + expect(yamlResult.map((f) => f.path.split("/").pop())).toEqual( | |
| 216 | + expect.arrayContaining(["assistant1.yaml", "assistant2.yml"]), | |
| 217 | + ); | |
| 218 | + expect(yamlResult.map((f) => f.path.split("/").pop())).not.toContain( | |
| 219 | + "assistant5.YAML", | |
| 220 | + ); | |
| 221 | + | |
| 222 | + const markdownOptions: LoadAssistantFilesOptions = { | |
| 223 | + includeGlobal: false, | |
| 224 | + includeWorkspace: true, | |
| 225 | + fileExtType: "markdown", | |
| 226 | + }; | |
| 227 | + | |
| 228 | + const markdownResult = await getAllDotContinueDefinitionFiles( | |
| 229 | + testIde, | |
| 230 | + markdownOptions, | |
| 231 | + "assistants", | |
| 232 | + ); | |
| 233 | + expect(markdownResult).toHaveLength(1); | |
| 234 | + expect(markdownResult.map((f) => f.path.split("/").pop())).toEqual([ | |
| 235 | + "assistant3.md", | |
| 236 | + ]); | |
| 237 | + expect(markdownResult.map((f) => f.path.split("/").pop())).not.toContain( | |
| 238 | + "assistant7.MD", | |
| 239 | + ); | |
| 240 | + }); | |
| 241 | +}); |
modified core/config/loadLocalAssistants.ts +27 −15
| @@ -1,4 +1,5 @@ | ||
| 1 | 1 | import ignore from "ignore"; |
| 2 | +import * as URI from "uri-js"; | |
| 2 | 3 | import { IDE } from ".."; |
| 3 | 4 | import { |
| 4 | 5 | DEFAULT_IGNORE_DIRS, |
| @@ -12,18 +13,19 @@ | ||
| 12 | 13 | export const ASSISTANTS = "assistants"; |
| 13 | 14 | export const ASSISTANTS_FOLDER = `.continue/${ASSISTANTS}`; |
| 14 | 15 | |
| 15 | -export function isLocalAssistantFile(uri: string): boolean { | |
| 16 | +export function isLocalDefinitionFile(uri: string): boolean { | |
| 16 | 17 | if (!uri.endsWith(".yaml") && !uri.endsWith(".yml") && !uri.endsWith(".md")) { |
| 17 | 18 | return false; |
| 18 | 19 | } |
| 19 | 20 | |
| 20 | - const normalizedUri = uri.replace(/\\/g, "/"); | |
| 21 | + const normalizedUri = URI.normalize(uri); | |
| 21 | 22 | return normalizedUri.includes(`/${ASSISTANTS_FOLDER}/`); |
| 22 | 23 | } |
| 23 | 24 | |
| 24 | 25 | async function getDefinitionFilesInDir( |
| 25 | 26 | ide: IDE, |
| 26 | 27 | dir: string, |
| 28 | + fileExtType?: "yaml" | "markdown", | |
| 27 | 29 | ): Promise<{ path: string; content: string }[]> { |
| 28 | 30 | try { |
| 29 | 31 | const exists = await ide.fileExists(dir); |
| @@ -40,9 +42,19 @@ | ||
| 40 | 42 | overrideDefaultIgnores, |
| 41 | 43 | source: "get assistant files", |
| 42 | 44 | }); |
| 43 | - const assistantFilePaths = uris.filter( | |
| 44 | - (p) => p.endsWith(".yaml") || p.endsWith(".yml") || p.endsWith(".md"), | |
| 45 | - ); | |
| 45 | + let assistantFilePaths: string[]; | |
| 46 | + if (fileExtType === "yaml") { | |
| 47 | + assistantFilePaths = uris.filter( | |
| 48 | + (p) => p.endsWith(".yaml") || p.endsWith(".yml"), | |
| 49 | + ); | |
| 50 | + } else if (fileExtType === "markdown") { | |
| 51 | + assistantFilePaths = uris.filter((p) => p.endsWith(".md")); | |
| 52 | + } else { | |
| 53 | + assistantFilePaths = uris.filter( | |
| 54 | + (p) => p.endsWith(".yaml") || p.endsWith(".yml") || p.endsWith(".md"), | |
| 55 | + ); | |
| 56 | + } | |
| 57 | + | |
| 46 | 58 | const results = assistantFilePaths.map(async (uri) => { |
| 47 | 59 | const content = await ide.readFile(uri); // make a try catch |
| 48 | 60 | return { path: uri, content }; |
| @@ -57,6 +69,7 @@ | ||
| 57 | 69 | export interface LoadAssistantFilesOptions { |
| 58 | 70 | includeGlobal: boolean; |
| 59 | 71 | includeWorkspace: boolean; |
| 72 | + fileExtType?: "yaml" | "markdown"; | |
| 60 | 73 | } |
| 61 | 74 | |
| 62 | 75 | export function getDotContinueSubDirs( |
| @@ -84,7 +97,7 @@ | ||
| 84 | 97 | |
| 85 | 98 | /** |
| 86 | 99 | * This method searches in both ~/.continue and workspace .continue |
| 87 | - * for all YAML files in the specified subdirctory, for example .continue/assistants or .continue/prompts | |
| 100 | + * for all YAML/Markdown files in the specified subdirectory, for example .continue/assistants or .continue/prompts | |
| 88 | 101 | */ |
| 89 | 102 | export async function getAllDotContinueDefinitionFiles( |
| 90 | 103 | ide: IDE, |
| @@ -101,15 +114,14 @@ | ||
| 101 | 114 | subDirName, |
| 102 | 115 | ); |
| 103 | 116 | |
| 104 | - // Get all assistant files from the directories | |
| 105 | - const assistantFiles = ( | |
| 106 | - await Promise.all(fullDirs.map((dir) => getDefinitionFilesInDir(ide, dir))) | |
| 117 | + // Get all definition files from the directories | |
| 118 | + const definitionFiles = ( | |
| 119 | + await Promise.all( | |
| 120 | + fullDirs.map((dir) => | |
| 121 | + getDefinitionFilesInDir(ide, dir, options.fileExtType), | |
| 122 | + ), | |
| 123 | + ) | |
| 107 | 124 | ).flat(); |
| 108 | 125 | |
| 109 | - return await Promise.all( | |
| 110 | - assistantFiles.map(async (file) => { | |
| 111 | - const content = await ide.readFile(file.path); | |
| 112 | - return { path: file.path, content }; | |
| 113 | - }), | |
| 114 | - ); | |
| 126 | + return definitionFiles; | |
| 115 | 127 | } |
deleted core/config/markdown/createMarkdownRule.test.ts +0 −157
| @@ -1,157 +0,0 @@ | ||
| 1 | -import { | |
| 2 | - createMarkdownWithFrontmatter, | |
| 3 | - createRuleFilePath, | |
| 4 | - createRuleMarkdown, | |
| 5 | - sanitizeRuleName, | |
| 6 | -} from "./createMarkdownRule"; | |
| 7 | -import { parseMarkdownRule } from "./parseMarkdownRule"; | |
| 8 | - | |
| 9 | -describe("sanitizeRuleName", () => { | |
| 10 | - it("should sanitize rule names for filenames", () => { | |
| 11 | - expect(sanitizeRuleName("My Test Rule")).toBe("my-test-rule"); | |
| 12 | - expect(sanitizeRuleName("Rule with @#$% chars")).toBe("rule-with-chars"); | |
| 13 | - expect(sanitizeRuleName("Multiple spaces")).toBe("multiple-spaces"); | |
| 14 | - expect(sanitizeRuleName("UPPERCASE-rule")).toBe("uppercase-rule"); | |
| 15 | - expect(sanitizeRuleName("already-sanitized")).toBe("already-sanitized"); | |
| 16 | - }); | |
| 17 | - | |
| 18 | - it("should handle empty and edge case inputs", () => { | |
| 19 | - expect(sanitizeRuleName("")).toBe(""); | |
| 20 | - expect(sanitizeRuleName(" ")).toBe(""); | |
| 21 | - expect(sanitizeRuleName("123")).toBe("123"); | |
| 22 | - expect(sanitizeRuleName("rule-with-numbers-123")).toBe( | |
| 23 | - "rule-with-numbers-123", | |
| 24 | - ); | |
| 25 | - }); | |
| 26 | -}); | |
| 27 | - | |
| 28 | -describe("createRuleFilePath", () => { | |
| 29 | - it("should create correct rule file path", () => { | |
| 30 | - const result = createRuleFilePath("/workspace", "My Test Rule"); | |
| 31 | - expect(result).toBe("/workspace/.continue/rules/my-test-rule.md"); | |
| 32 | - }); | |
| 33 | - | |
| 34 | - it("should handle special characters in rule name", () => { | |
| 35 | - const result = createRuleFilePath("/home/user", "Rule with @#$% chars"); | |
| 36 | - expect(result).toBe("/home/user/.continue/rules/rule-with-chars.md"); | |
| 37 | - }); | |
| 38 | - | |
| 39 | - it("should handle edge case rule names", () => { | |
| 40 | - const result = createRuleFilePath("/test", " Multiple Spaces "); | |
| 41 | - expect(result).toBe("/test/.continue/rules/multiple-spaces.md"); | |
| 42 | - }); | |
| 43 | -}); | |
| 44 | - | |
| 45 | -describe("createMarkdownWithFrontmatter", () => { | |
| 46 | - it("should create properly formatted markdown with frontmatter", () => { | |
| 47 | - const frontmatter = { | |
| 48 | - name: "Test Rule", | |
| 49 | - description: "A test rule", | |
| 50 | - globs: "*.ts", | |
| 51 | - }; | |
| 52 | - const markdown = "# Test Rule\n\nThis is a test rule."; | |
| 53 | - | |
| 54 | - const result = createMarkdownWithFrontmatter(frontmatter, markdown); | |
| 55 | - | |
| 56 | - // The exact quote style doesn't matter as long as it parses correctly | |
| 57 | - expect(result).toContain("name: Test Rule"); | |
| 58 | - expect(result).toContain("description: A test rule"); | |
| 59 | - expect(result).toContain("globs:"); | |
| 60 | - expect(result).toContain("*.ts"); | |
| 61 | - expect(result).toContain("---\n\n# Test Rule\n\nThis is a test rule."); | |
| 62 | - }); | |
| 63 | - | |
| 64 | - it("should handle empty frontmatter", () => { | |
| 65 | - const frontmatter = {}; | |
| 66 | - const markdown = "# Simple Rule\n\nJust markdown content."; | |
| 67 | - | |
| 68 | - const result = createMarkdownWithFrontmatter(frontmatter, markdown); | |
| 69 | - | |
| 70 | - const expected = `--- | |
| 71 | -{} | |
| 72 | ---- | |
| 73 | - | |
| 74 | -# Simple Rule | |
| 75 | - | |
| 76 | -Just markdown content.`; | |
| 77 | - | |
| 78 | - expect(result).toBe(expected); | |
| 79 | - }); | |
| 80 | - | |
| 81 | - it("should create content that can be parsed back correctly", () => { | |
| 82 | - const originalFrontmatter = { | |
| 83 | - name: "Roundtrip Test", | |
| 84 | - description: "Testing roundtrip parsing", | |
| 85 | - globs: ["*.js", "*.ts"], | |
| 86 | - alwaysApply: true, | |
| 87 | - }; | |
| 88 | - const originalMarkdown = | |
| 89 | - "# Roundtrip Test\n\nThis should parse back correctly."; | |
| 90 | - | |
| 91 | - const created = createMarkdownWithFrontmatter( | |
| 92 | - originalFrontmatter, | |
| 93 | - originalMarkdown, | |
| 94 | - ); | |
| 95 | - const parsed = parseMarkdownRule(created); | |
| 96 | - | |
| 97 | - expect(parsed.frontmatter).toEqual(originalFrontmatter); | |
| 98 | - expect(parsed.markdown).toBe(originalMarkdown); | |
| 99 | - }); | |
| 100 | -}); | |
| 101 | - | |
| 102 | -describe("createRuleMarkdown", () => { | |
| 103 | - it("should create rule markdown with all options", () => { | |
| 104 | - const result = createRuleMarkdown("Test Rule", "This is the rule content", { | |
| 105 | - description: "Test description", | |
| 106 | - globs: ["*.ts", "*.js"], | |
| 107 | - alwaysApply: true, | |
| 108 | - }); | |
| 109 | - | |
| 110 | - const parsed = parseMarkdownRule(result); | |
| 111 | - | |
| 112 | - expect(parsed.frontmatter.description).toBe("Test description"); | |
| 113 | - expect(parsed.frontmatter.globs).toEqual(["*.ts", "*.js"]); | |
| 114 | - expect(parsed.frontmatter.alwaysApply).toBe(true); | |
| 115 | - expect(parsed.markdown).toBe("# Test Rule\n\nThis is the rule content"); | |
| 116 | - }); | |
| 117 | - | |
| 118 | - it("should create rule markdown with minimal options", () => { | |
| 119 | - const result = createRuleMarkdown("Simple Rule", "Simple content"); | |
| 120 | - | |
| 121 | - const parsed = parseMarkdownRule(result); | |
| 122 | - | |
| 123 | - expect(parsed.frontmatter.description).toBeUndefined(); | |
| 124 | - expect(parsed.frontmatter.globs).toBeUndefined(); | |
| 125 | - expect(parsed.frontmatter.alwaysApply).toBeUndefined(); | |
| 126 | - expect(parsed.markdown).toBe("# Simple Rule\n\nSimple content"); | |
| 127 | - }); | |
| 128 | - | |
| 129 | - it("should handle string globs", () => { | |
| 130 | - const result = createRuleMarkdown("String Glob Rule", "Content", { | |
| 131 | - globs: "*.py", | |
| 132 | - }); | |
| 133 | - | |
| 134 | - const parsed = parseMarkdownRule(result); | |
| 135 | - expect(parsed.frontmatter.globs).toBe("*.py"); | |
| 136 | - }); | |
| 137 | - | |
| 138 | - it("should trim description and globs", () => { | |
| 139 | - const result = createRuleMarkdown("Trim Test", "Content", { | |
| 140 | - description: " spaced description ", | |
| 141 | - globs: " *.ts ", | |
| 142 | - }); | |
| 143 | - | |
| 144 | - const parsed = parseMarkdownRule(result); | |
| 145 | - expect(parsed.frontmatter.description).toBe("spaced description"); | |
| 146 | - expect(parsed.frontmatter.globs).toBe("*.ts"); | |
| 147 | - }); | |
| 148 | - | |
| 149 | - it("should handle alwaysApply false explicitly", () => { | |
| 150 | - const result = createRuleMarkdown("Always Apply False", "Content", { | |
| 151 | - alwaysApply: false, | |
| 152 | - }); | |
| 153 | - | |
| 154 | - const parsed = parseMarkdownRule(result); | |
| 155 | - expect(parsed.frontmatter.alwaysApply).toBe(false); | |
| 156 | - }); | |
| 157 | -}); |
deleted core/config/markdown/createMarkdownRule.ts +0 −75
| @@ -1,75 +0,0 @@ | ||
| 1 | -import * as YAML from "yaml"; | |
| 2 | -import { joinPathsToUri } from "../../util/uri"; | |
| 3 | -import { RuleFrontmatter } from "./parseMarkdownRule"; | |
| 4 | - | |
| 5 | -export const RULE_FILE_EXTENSION = "md"; | |
| 6 | - | |
| 7 | -/** | |
| 8 | - * Sanitizes a rule name for use in filenames (removes special chars, replaces spaces with dashes) | |
| 9 | - */ | |
| 10 | -export function sanitizeRuleName(name: string): string { | |
| 11 | - return name | |
| 12 | - .toLowerCase() | |
| 13 | - .replace(/[^a-z0-9\s-]/g, "") | |
| 14 | - .replace(/\s+/g, "-") | |
| 15 | - .replace(/^-+|-+$/g, ""); // Remove leading/trailing dashes | |
| 16 | -} | |
| 17 | - | |
| 18 | -/** | |
| 19 | - * Creates the file path for a rule in the workspace .continue/rules directory | |
| 20 | - */ | |
| 21 | -export function createRuleFilePath( | |
| 22 | - workspaceDir: string, | |
| 23 | - ruleName: string, | |
| 24 | -): string { | |
| 25 | - const safeRuleName = sanitizeRuleName(ruleName); | |
| 26 | - return joinPathsToUri( | |
| 27 | - workspaceDir, | |
| 28 | - ".continue", | |
| 29 | - "rules", | |
| 30 | - `${safeRuleName}.${RULE_FILE_EXTENSION}`, | |
| 31 | - ); | |
| 32 | -} | |
| 33 | - | |
| 34 | -/** | |
| 35 | - * Creates markdown content with YAML frontmatter in the format expected by parseMarkdownRule | |
| 36 | - */ | |
| 37 | -export function createMarkdownWithFrontmatter( | |
| 38 | - frontmatter: RuleFrontmatter, | |
| 39 | - markdown: string, | |
| 40 | -): string { | |
| 41 | - const frontmatterStr = YAML.stringify(frontmatter).trim(); | |
| 42 | - return `---\n${frontmatterStr}\n---\n\n${markdown}`; | |
| 43 | -} | |
| 44 | - | |
| 45 | -/** | |
| 46 | - * Creates a rule markdown file content from rule components | |
| 47 | - */ | |
| 48 | -export function createRuleMarkdown( | |
| 49 | - name: string, | |
| 50 | - ruleContent: string, | |
| 51 | - options: { | |
| 52 | - description?: string; | |
| 53 | - globs?: string | string[]; | |
| 54 | - alwaysApply?: boolean; | |
| 55 | - } = {}, | |
| 56 | -): string { | |
| 57 | - const frontmatter: RuleFrontmatter = {}; | |
| 58 | - | |
| 59 | - if (options.globs) { | |
| 60 | - frontmatter.globs = | |
| 61 | - typeof options.globs === "string" ? options.globs.trim() : options.globs; | |
| 62 | - } | |
| 63 | - | |
| 64 | - if (options.description) { | |
| 65 | - frontmatter.description = options.description.trim(); | |
| 66 | - } | |
| 67 | - | |
| 68 | - if (options.alwaysApply !== undefined) { | |
| 69 | - frontmatter.alwaysApply = options.alwaysApply; | |
| 70 | - } | |
| 71 | - | |
| 72 | - const markdownBody = `# ${name}\n\n${ruleContent}`; | |
| 73 | - | |
| 74 | - return createMarkdownWithFrontmatter(frontmatter, markdownBody); | |
| 75 | -} |
modified core/config/markdown/index.ts +0 −2
| @@ -1,3 +1,1 @@ | ||
| 1 | -export * from "./createMarkdownRule"; | |
| 2 | 1 | export * from "./loadMarkdownRules"; |
| 3 | -export * from "./parseMarkdownRule"; |
modified core/config/markdown/loadCodebaseRules.ts +6 −4
| @@ -1,9 +1,11 @@ | ||
| 1 | -import { ConfigValidationError } from "@continuedev/config-yaml"; | |
| 1 | +import { | |
| 2 | + ConfigValidationError, | |
| 3 | + markdownToRule, | |
| 4 | +} from "@continuedev/config-yaml"; | |
| 2 | 5 | import { IDE, RuleWithSource } from "../.."; |
| 3 | 6 | import { walkDirs } from "../../indexing/walkDir"; |
| 4 | 7 | import { RULES_MARKDOWN_FILENAME } from "../../llm/rules/constants"; |
| 5 | 8 | import { getUriPathBasename } from "../../util/uri"; |
| 6 | -import { convertMarkdownRuleToContinueRule } from "./parseMarkdownRule"; | |
| 7 | 9 | |
| 8 | 10 | /** |
| 9 | 11 | * Loads rules from rules.md files colocated in the codebase |
| @@ -29,9 +31,9 @@ | ||
| 29 | 31 | for (const filePath of rulesMdFiles) { |
| 30 | 32 | try { |
| 31 | 33 | const content = await ide.readFile(filePath); |
| 32 | - const rule = convertMarkdownRuleToContinueRule(filePath, content); | |
| 34 | + const rule = markdownToRule(content, { uriType: "file", filePath }); | |
| 33 | 35 | |
| 34 | - rules.push(rule); | |
| 36 | + rules.push({ ...rule, source: "rules-block" }); | |
| 35 | 37 | } catch (e) { |
| 36 | 38 | errors.push({ |
| 37 | 39 | fatal: false, |
modified core/config/markdown/loadCodebaseRules.vitest.ts +8 −8
| @@ -1,16 +1,16 @@ | ||
| 1 | +import { markdownToRule } from "@continuedev/config-yaml"; | |
| 1 | 2 | import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; |
| 2 | 3 | import { IDE } from "../.."; |
| 3 | 4 | import { walkDirs } from "../../indexing/walkDir"; |
| 4 | 5 | import { loadCodebaseRules } from "./loadCodebaseRules"; |
| 5 | -import { convertMarkdownRuleToContinueRule } from "./parseMarkdownRule"; | |
| 6 | 6 | |
| 7 | 7 | // Mock dependencies |
| 8 | 8 | vi.mock("../../indexing/walkDir", () => ({ |
| 9 | 9 | walkDirs: vi.fn(), |
| 10 | 10 | })); |
| 11 | 11 | |
| 12 | -vi.mock("./parseMarkdownRule", () => ({ | |
| 13 | - convertMarkdownRuleToContinueRule: vi.fn(), | |
| 12 | +vi.mock("@continuedev/config-yaml", () => ({ | |
| 13 | + markdownToRule: vi.fn(), | |
| 14 | 14 | })); |
| 15 | 15 | |
| 16 | 16 | describe("loadCodebaseRules", () => { |
| @@ -82,10 +82,10 @@ | ||
| 82 | 82 | return Promise.resolve(mockRuleContent[path] || ""); |
| 83 | 83 | }); |
| 84 | 84 | |
| 85 | - // Mock convertMarkdownRuleToContinueRule to return converted rules | |
| 86 | - (convertMarkdownRuleToContinueRule as any).mockImplementation( | |
| 87 | - (path: string, content: string) => { | |
| 88 | - return mockConvertedRules[path]; | |
| 85 | + // Mock markdownToRule to return converted rules | |
| 86 | + (markdownToRule as any).mockImplementation( | |
| 87 | + (content: string, options: any) => { | |
| 88 | + return mockConvertedRules[options.filePath]; | |
| 89 | 89 | }, |
| 90 | 90 | ); |
| 91 | 91 | }); |
| @@ -107,7 +107,7 @@ | ||
| 107 | 107 | expect(mockIde.readFile).toHaveBeenCalledWith(".continue/rules.md"); |
| 108 | 108 | |
| 109 | 109 | // Should convert all rules |
| 110 | - expect(convertMarkdownRuleToContinueRule).toHaveBeenCalledTimes(4); | |
| 110 | + expect(markdownToRule).toHaveBeenCalledTimes(4); | |
| 111 | 111 | |
| 112 | 112 | // Should return all rules |
| 113 | 113 | expect(rules).toHaveLength(4); |
modified core/config/markdown/loadMarkdownRules.ts +10 −5
| @@ -1,7 +1,9 @@ | ||
| 1 | -import { ConfigValidationError } from "@continuedev/config-yaml"; | |
| 1 | +import { | |
| 2 | + ConfigValidationError, | |
| 3 | + markdownToRule, | |
| 4 | +} from "@continuedev/config-yaml"; | |
| 2 | 5 | import { IDE, RuleWithSource } from "../.."; |
| 3 | 6 | import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants"; |
| 4 | -import { convertMarkdownRuleToContinueRule } from "./parseMarkdownRule"; | |
| 5 | 7 | |
| 6 | 8 | /** |
| 7 | 9 | * Loads rules from markdown files in the .continue/rules directory |
| @@ -17,7 +19,7 @@ | ||
| 17 | 19 | // Get all .md files from .continue/rules |
| 18 | 20 | const markdownFiles = await getAllDotContinueDefinitionFiles( |
| 19 | 21 | ide, |
| 20 | - { includeGlobal: true, includeWorkspace: true }, | |
| 22 | + { includeGlobal: true, includeWorkspace: true, fileExtType: "markdown" }, | |
| 21 | 23 | "rules", |
| 22 | 24 | ); |
| 23 | 25 | |
| @@ -27,8 +29,11 @@ | ||
| 27 | 29 | // Process each markdown file |
| 28 | 30 | for (const file of mdFiles) { |
| 29 | 31 | try { |
| 30 | - const rule = convertMarkdownRuleToContinueRule(file.path, file.content); | |
| 31 | - rules.push(rule); | |
| 32 | + const rule = markdownToRule(file.content, { | |
| 33 | + uriType: "file", | |
| 34 | + filePath: file.path, | |
| 35 | + }); | |
| 36 | + rules.push({ ...rule, source: "rules-block" }); | |
| 32 | 37 | } catch (e) { |
| 33 | 38 | errors.push({ |
| 34 | 39 | fatal: false, |
deleted core/config/markdown/parseMarkdownRule.test.ts +0 −192
| @@ -1,192 +0,0 @@ | ||
| 1 | -import { | |
| 2 | - convertMarkdownRuleToContinueRule, | |
| 3 | - parseMarkdownRule, | |
| 4 | -} from "./parseMarkdownRule"; | |
| 5 | - | |
| 6 | -describe("parseMarkdownRule", () => { | |
| 7 | - it("should correctly parse markdown with YAML frontmatter", () => { | |
| 8 | - const content = `--- | |
| 9 | -globs: "**/test/**/*.kt" | |
| 10 | ---- | |
| 11 | - | |
| 12 | -# Test Rule | |
| 13 | - | |
| 14 | -This is a test rule.`; | |
| 15 | - | |
| 16 | - const result = parseMarkdownRule(content); | |
| 17 | - expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" }); | |
| 18 | - expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule."); | |
| 19 | - }); | |
| 20 | - | |
| 21 | - it("should handle missing frontmatter", () => { | |
| 22 | - const content = `# Test Rule | |
| 23 | - | |
| 24 | -This is a test rule without frontmatter.`; | |
| 25 | - | |
| 26 | - const result = parseMarkdownRule(content); | |
| 27 | - expect(result.frontmatter).toEqual({}); | |
| 28 | - expect(result.markdown).toBe(content); | |
| 29 | - }); | |
| 30 | - | |
| 31 | - it("should handle empty frontmatter", () => { | |
| 32 | - const content = `--- | |
| 33 | ---- | |
| 34 | - | |
| 35 | -# Test Rule | |
| 36 | - | |
| 37 | -This is a test rule with empty frontmatter.`; | |
| 38 | - | |
| 39 | - const result = parseMarkdownRule(content); | |
| 40 | - | |
| 41 | - // Log exact strings for debugging | |
| 42 | - console.log("Actual:", JSON.stringify(result.markdown)); | |
| 43 | - console.log( | |
| 44 | - "Expected:", | |
| 45 | - JSON.stringify( | |
| 46 | - "# Test Rule\n\nThis is a test rule with empty frontmatter.", | |
| 47 | - ), | |
| 48 | - ); | |
| 49 | - | |
| 50 | - expect(result.frontmatter).toEqual({}); | |
| 51 | - expect(result.markdown).toBe( | |
| 52 | - "# Test Rule\n\nThis is a test rule with empty frontmatter.", | |
| 53 | - ); | |
| 54 | - }); | |
| 55 | - | |
| 56 | - it("should handle frontmatter with whitespace", () => { | |
| 57 | - const content = `--- | |
| 58 | -globs: "**/test/**/*.kt" | |
| 59 | ---- | |
| 60 | - | |
| 61 | -# Test Rule | |
| 62 | - | |
| 63 | -This is a test rule.`; | |
| 64 | - | |
| 65 | - const result = parseMarkdownRule(content); | |
| 66 | - expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" }); | |
| 67 | - expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule."); | |
| 68 | - }); | |
| 69 | - | |
| 70 | - it("should handle Windows line endings (CRLF)", () => { | |
| 71 | - // Using \r\n for CRLF line endings | |
| 72 | - const content = `---\r | |
| 73 | -globs: "**/test/**/*.kt"\r | |
| 74 | ----\r | |
| 75 | -\r | |
| 76 | -# Test Rule\r | |
| 77 | -\r | |
| 78 | -This is a test rule.`; | |
| 79 | - | |
| 80 | - const result = parseMarkdownRule(content); | |
| 81 | - expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" }); | |
| 82 | - // The result should be normalized to \n | |
| 83 | - expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule."); | |
| 84 | - }); | |
| 85 | - | |
| 86 | - it("should handle malformed frontmatter", () => { | |
| 87 | - const content = `--- | |
| 88 | -globs: - "**/test/**/*.kt" | |
| 89 | -invalid: yaml: content | |
| 90 | ---- | |
| 91 | - | |
| 92 | -# Test Rule | |
| 93 | - | |
| 94 | -This is a test rule.`; | |
| 95 | - | |
| 96 | - // Should treat as only markdown when frontmatter is malformed | |
| 97 | - const result = parseMarkdownRule(content); | |
| 98 | - expect(result.frontmatter).toEqual({}); | |
| 99 | - expect(result.markdown).toBe(content); | |
| 100 | - }); | |
| 101 | -}); | |
| 102 | - | |
| 103 | -describe("convertMarkdownRuleToContinueRule", () => { | |
| 104 | - it("should convert markdown with frontmatter to a rule", () => { | |
| 105 | - const content = `--- | |
| 106 | -globs: "**/test/**/*.kt" | |
| 107 | -name: Custom Name | |
| 108 | ---- | |
| 109 | - | |
| 110 | -# Test Rule | |
| 111 | - | |
| 112 | -This is a test rule.`; | |
| 113 | - | |
| 114 | - const result = convertMarkdownRuleToContinueRule( | |
| 115 | - "/path/to/rule.md", | |
| 116 | - content, | |
| 117 | - ); | |
| 118 | - expect(result.rule).toBe("# Test Rule\n\nThis is a test rule."); | |
| 119 | - expect(result.globs).toBe("**/test/**/*.kt"); | |
| 120 | - expect(result.name).toBe("Custom Name"); | |
| 121 | - expect(result.source).toBe("rules-block"); | |
| 122 | - expect(result.ruleFile).toBe("/path/to/rule.md"); | |
| 123 | - }); | |
| 124 | - | |
| 125 | - it("should use the first heading as name if not in frontmatter", () => { | |
| 126 | - const content = `--- | |
| 127 | -globs: "**/test/**/*.kt" | |
| 128 | ---- | |
| 129 | - | |
| 130 | -# Test Rule Title | |
| 131 | - | |
| 132 | -This is a test rule.`; | |
| 133 | - | |
| 134 | - const result = convertMarkdownRuleToContinueRule( | |
| 135 | - "/path/to/rule.md", | |
| 136 | - content, | |
| 137 | - ); | |
| 138 | - expect(result.name).toBe("Test Rule Title"); | |
| 139 | - }); | |
| 140 | - | |
| 141 | - it("should use filename as name if no heading or frontmatter name", () => { | |
| 142 | - const content = `--- | |
| 143 | -globs: "**/test/**/*.kt" | |
| 144 | ---- | |
| 145 | - | |
| 146 | -This is a test rule without a heading.`; | |
| 147 | - | |
| 148 | - const result = convertMarkdownRuleToContinueRule( | |
| 149 | - "/path/to/custom-rule.md", | |
| 150 | - content, | |
| 151 | - ); | |
| 152 | - expect(result.name).toBe("custom-rule"); | |
| 153 | - }); | |
| 154 | - | |
| 155 | - it("should include description from frontmatter", () => { | |
| 156 | - const content = `--- | |
| 157 | -globs: "**/test/**/*.kt" | |
| 158 | -name: Test Rule | |
| 159 | -description: This is a rule description from frontmatter | |
| 160 | ---- | |
| 161 | - | |
| 162 | -# Test Rule | |
| 163 | - | |
| 164 | -This is the content of the rule.`; | |
| 165 | - | |
| 166 | - const result = convertMarkdownRuleToContinueRule( | |
| 167 | - "/path/to/rule.md", | |
| 168 | - content, | |
| 169 | - ); | |
| 170 | - expect(result.description).toBe( | |
| 171 | - "This is a rule description from frontmatter", | |
| 172 | - ); | |
| 173 | - }); | |
| 174 | - | |
| 175 | - it("should include `alwaysApply` from frontmatter", () => { | |
| 176 | - const content = `--- | |
| 177 | -globs: "**/test/**/*.kt" | |
| 178 | -name: Test Rule | |
| 179 | -alwaysApply: false | |
| 180 | ---- | |
| 181 | - | |
| 182 | -# Test Rule | |
| 183 | - | |
| 184 | -This is a rule with alwaysApply explicitly set to false.`; | |
| 185 | - | |
| 186 | - const result = convertMarkdownRuleToContinueRule( | |
| 187 | - "/path/to/rule.md", | |
| 188 | - content, | |
| 189 | - ); | |
| 190 | - expect(result.alwaysApply).toBe(false); | |
| 191 | - }); | |
| 192 | -}); |
deleted core/config/markdown/parseMarkdownRule.ts +0 −77
| @@ -1,77 +0,0 @@ | ||
| 1 | -import { basename } from "path"; | |
| 2 | -import * as YAML from "yaml"; | |
| 3 | -import { RuleWithSource } from "../.."; | |
| 4 | - | |
| 5 | -export interface RuleFrontmatter { | |
| 6 | - globs?: RuleWithSource["globs"]; | |
| 7 | - name?: RuleWithSource["name"]; | |
| 8 | - description?: RuleWithSource["description"]; | |
| 9 | - alwaysApply?: RuleWithSource["alwaysApply"]; | |
| 10 | -} | |
| 11 | - | |
| 12 | -/** | |
| 13 | - * Parses markdown content with YAML frontmatter | |
| 14 | - */ | |
| 15 | -export function parseMarkdownRule(content: string): { | |
| 16 | - frontmatter: RuleFrontmatter; | |
| 17 | - markdown: string; | |
| 18 | -} { | |
| 19 | - // Normalize line endings to \n | |
| 20 | - const normalizedContent = content.replace(/\r\n/g, "\n"); | |
| 21 | - | |
| 22 | - // More reliable frontmatter detection | |
| 23 | - const parts = normalizedContent.split(/^---\s*$/m); | |
| 24 | - | |
| 25 | - // If we have at least 3 parts (before ---, frontmatter, after ---), we have frontmatter | |
| 26 | - if (parts.length >= 3) { | |
| 27 | - const frontmatterStr = parts[1]; | |
| 28 | - // Join the remaining parts back together (in case there are more --- in the markdown) | |
| 29 | - const markdownContent = parts.slice(2).join("---"); | |
| 30 | - | |
| 31 | - try { | |
| 32 | - // Parse YAML frontmatter | |
| 33 | - const frontmatter = YAML.parse(frontmatterStr) || {}; // Handle empty frontmatter | |
| 34 | - return { frontmatter, markdown: markdownContent.trim() }; | |
| 35 | - } catch (e) { | |
| 36 | - // Error parsing frontmatter, treat as markdown only | |
| 37 | - console.warn("Error parsing markdown frontmatter:", e); | |
| 38 | - return { frontmatter: {}, markdown: normalizedContent }; | |
| 39 | - } | |
| 40 | - } | |
| 41 | - | |
| 42 | - // No frontmatter found | |
| 43 | - return { frontmatter: {}, markdown: normalizedContent }; | |
| 44 | -} | |
| 45 | - | |
| 46 | -/** | |
| 47 | - * Converts a markdown file with YAML frontmatter to a RuleWithSource object | |
| 48 | - */ | |
| 49 | -export function convertMarkdownRuleToContinueRule( | |
| 50 | - path: string, | |
| 51 | - content: string, | |
| 52 | -): RuleWithSource { | |
| 53 | - const { frontmatter, markdown } = parseMarkdownRule(content); | |
| 54 | - | |
| 55 | - // Try to extract title from first heading if no name in frontmatter | |
| 56 | - let name = frontmatter.name; | |
| 57 | - if (!name) { | |
| 58 | - // Look for a heading in the markdown | |
| 59 | - const headingMatch = markdown.match(/^#\s+(.+)$/m); | |
| 60 | - if (headingMatch) { | |
| 61 | - name = headingMatch[1].trim(); | |
| 62 | - } else { | |
| 63 | - // Fall back to filename | |
| 64 | - name = basename(path).replace(/\.md$/, ""); | |
| 65 | - } | |
| 66 | - } | |
| 67 | - | |
| 68 | - return { | |
| 69 | - name, | |
| 70 | - rule: markdown, | |
| 71 | - globs: frontmatter.globs, | |
| 72 | - description: frontmatter.description, | |
| 73 | - alwaysApply: frontmatter.alwaysApply, | |
| 74 | - source: "rules-block", | |
| 75 | - ruleFile: path, | |
| 76 | - }; | |
| 77 | -} |
added core/config/markdown/utils.ts +21 −0
| @@ -0,0 +1,21 @@ | ||
| 1 | +import { | |
| 2 | + RULE_FILE_EXTENSION, | |
| 3 | + sanitizeRuleName, | |
| 4 | +} from "@continuedev/config-yaml"; | |
| 5 | +import { joinPathsToUri } from "../../util/uri"; | |
| 6 | + | |
| 7 | +/** | |
| 8 | + * Creates the file path for a rule in the workspace .continue/rules directory | |
| 9 | + */ | |
| 10 | +export function createRuleFilePath( | |
| 11 | + workspaceDir: string, | |
| 12 | + ruleName: string, | |
| 13 | +): string { | |
| 14 | + const safeRuleName = sanitizeRuleName(ruleName); | |
| 15 | + return joinPathsToUri( | |
| 16 | + workspaceDir, | |
| 17 | + ".continue", | |
| 18 | + "rules", | |
| 19 | + `${safeRuleName}.${RULE_FILE_EXTENSION}`, | |
| 20 | + ); | |
| 21 | +} |
added core/config/markdown/utils.vitest.ts +19 −0
| @@ -0,0 +1,19 @@ | ||
| 1 | +import { describe, expect, it } from "vitest"; | |
| 2 | +import { createRuleFilePath } from "./utils"; | |
| 3 | + | |
| 4 | +describe("createRuleFilePath", () => { | |
| 5 | + it("should create correct rule file path", () => { | |
| 6 | + const result = createRuleFilePath("/workspace", "My Test Rule"); | |
| 7 | + expect(result).toBe("/workspace/.continue/rules/my-test-rule.md"); | |
| 8 | + }); | |
| 9 | + | |
| 10 | + it("should handle special characters in rule name", () => { | |
| 11 | + const result = createRuleFilePath("/home/user", "Rule with @#$% chars"); | |
| 12 | + expect(result).toBe("/home/user/.continue/rules/rule-with-chars.md"); | |
| 13 | + }); | |
| 14 | + | |
| 15 | + it("should handle edge case rule names", () => { | |
| 16 | + const result = createRuleFilePath("/test", " Multiple Spaces "); | |
| 17 | + expect(result).toBe("/test/.continue/rules/multiple-spaces.md"); | |
| 18 | + }); | |
| 19 | +}); |
modified core/config/migrateSharedConfig.ts +1 −1
| @@ -211,6 +211,6 @@ | ||
| 211 | 211 | new GlobalContext().updateSharedConfig(shareConfigUpdates); |
| 212 | 212 | } |
| 213 | 213 | } catch (e) { |
| 214 | - throw new Error(`Migration: Failed to parse config.json: ${e}`); | |
| 214 | + console.error(`Migration: Failed to parse config.json: ${e}`); | |
| 215 | 215 | } |
| 216 | 216 | } |
modified core/config/workspace/workspaceBlocks.test.ts +1 −3
| @@ -1,12 +1,10 @@ | ||
| 1 | -import { BlockType } from "@continuedev/config-yaml"; | |
| 1 | +import { BlockType, RULE_FILE_EXTENSION } from "@continuedev/config-yaml"; | |
| 2 | 2 | import { describe, expect, test } from "@jest/globals"; |
| 3 | -import { RULE_FILE_EXTENSION } from "../markdown"; | |
| 4 | 3 | import { findAvailableFilename, getFileContent } from "./workspaceBlocks"; |
| 5 | 4 | |
| 6 | 5 | describe("getFileContent", () => { |
| 7 | 6 | test("returns markdown content for rules block type", () => { |
| 8 | 7 | const result = getFileContent("rules"); |
| 9 | - expect(result).toContain("# New Rule"); | |
| 10 | 8 | expect(result).toContain("Your rule content"); |
| 11 | 9 | expect(result).toContain("A description of your rule"); |
| 12 | 10 | }); |
modified core/config/workspace/workspaceBlocks.ts +6 −2
| @@ -1,8 +1,12 @@ | ||
| 1 | -import { BlockType, ConfigYaml } from "@continuedev/config-yaml"; | |
| 1 | +import { | |
| 2 | + BlockType, | |
| 3 | + ConfigYaml, | |
| 4 | + createRuleMarkdown, | |
| 5 | + RULE_FILE_EXTENSION, | |
| 6 | +} from "@continuedev/config-yaml"; | |
| 2 | 7 | import * as YAML from "yaml"; |
| 3 | 8 | import { IDE } from "../.."; |
| 4 | 9 | import { joinPathsToUri } from "../../util/uri"; |
| 5 | -import { RULE_FILE_EXTENSION, createRuleMarkdown } from "../markdown"; | |
| 6 | 10 | |
| 7 | 11 | const BLOCK_TYPE_CONFIG: Record< |
| 8 | 12 | BlockType, |
modified core/config/yaml/LocalPlatformClient.vitest.ts +0 −1
| @@ -123,7 +123,6 @@ | ||
| 123 | 123 | expect( |
| 124 | 124 | (resolvedFQSNs[0] as SecretResult & { value: unknown })?.value, |
| 125 | 125 | ).toBe(secretValue); |
| 126 | - console.log("debug1 resolved fqsn", resolvedFQSNs); | |
| 127 | 126 | }); |
| 128 | 127 | }); |
| 129 | 128 |
modified core/config/yaml/loadYaml.ts +6 −11
| @@ -97,7 +97,7 @@ | ||
| 97 | 97 | for (const blockType of BLOCK_TYPES) { |
| 98 | 98 | const localBlocks = await getAllDotContinueDefinitionFiles( |
| 99 | 99 | ide, |
| 100 | - { includeGlobal: true, includeWorkspace: true }, | |
| 100 | + { includeGlobal: true, includeWorkspace: true, fileExtType: "yaml" }, | |
| 101 | 101 | blockType, |
| 102 | 102 | ); |
| 103 | 103 | allLocalBlocks.push( |
| @@ -134,6 +134,7 @@ | ||
| 134 | 134 | rootPath, |
| 135 | 135 | }), |
| 136 | 136 | { |
| 137 | + renderSecrets: true, | |
| 137 | 138 | currentUserSlug: "", |
| 138 | 139 | onPremProxyUrl: null, |
| 139 | 140 | orgScopeId, |
| @@ -142,9 +143,7 @@ | ||
| 142 | 143 | controlPlaneClient, |
| 143 | 144 | ide, |
| 144 | 145 | ), |
| 145 | - renderSecrets: true, | |
| 146 | 146 | injectBlocks: allLocalBlocks, |
| 147 | - asConfigResult: true, | |
| 148 | 147 | }, |
| 149 | 148 | ); |
| 150 | 149 | config = unrollResult.config; |
| @@ -153,13 +152,8 @@ | ||
| 153 | 152 | } |
| 154 | 153 | } |
| 155 | 154 | |
| 156 | - if (config) { | |
| 157 | - isAssistantUnrolledNonNullable(config) | |
| 158 | - ? errors.push(...validateConfigYaml(config)) | |
| 159 | - : errors.push({ | |
| 160 | - fatal: true, | |
| 161 | - message: "Assistant includes blocks that don't exist", | |
| 162 | - }); | |
| 155 | + if (config && isAssistantUnrolledNonNullable(config)) { | |
| 156 | + errors.push(...validateConfigYaml(config)); | |
| 163 | 157 | } |
| 164 | 158 | |
| 165 | 159 | if (errors?.some((error) => error.fatal)) { |
| @@ -223,7 +217,8 @@ | ||
| 223 | 217 | config: continueConfig, |
| 224 | 218 | errors: [ |
| 225 | 219 | { |
| 226 | - message: "Found missing blocks in config.yaml", | |
| 220 | + message: | |
| 221 | + "Failed to load config due to missing blocks, see which blocks are missing below", | |
| 227 | 222 | fatal: true, |
| 228 | 223 | }, |
| 229 | 224 | ], |
modified core/core.ts +23 −21
| @@ -49,7 +49,7 @@ | ||
| 49 | 49 | |
| 50 | 50 | import { ConfigYaml } from "@continuedev/config-yaml"; |
| 51 | 51 | import { getDiffFn, GitDiffCache } from "./autocomplete/snippets/gitDiffCache"; |
| 52 | -import { isLocalAssistantFile } from "./config/loadLocalAssistants"; | |
| 52 | +import { isLocalDefinitionFile } from "./config/loadLocalAssistants"; | |
| 53 | 53 | import { |
| 54 | 54 | setupLocalConfig, |
| 55 | 55 | setupProviderConfig, |
| @@ -145,8 +145,8 @@ | ||
| 145 | 145 | this.messenger, |
| 146 | 146 | ); |
| 147 | 147 | |
| 148 | - MCPManagerSingleton.getInstance().onConnectionsRefreshed = async () => { | |
| 149 | - await this.configHandler.reloadConfig(); | |
| 148 | + MCPManagerSingleton.getInstance().onConnectionsRefreshed = () => { | |
| 149 | + void this.configHandler.reloadConfig(); | |
| 150 | 150 | }; |
| 151 | 151 | |
| 152 | 152 | this.codeBaseIndexer = new CodebaseIndexer( |
| @@ -156,24 +156,26 @@ | ||
| 156 | 156 | this.globalContext.get("indexingPaused"), |
| 157 | 157 | ); |
| 158 | 158 | |
| 159 | - this.configHandler.onConfigUpdate(async (result) => { | |
| 160 | - const serializedResult = await this.configHandler.getSerializedConfig(); | |
| 161 | - this.messenger.send("configUpdate", { | |
| 162 | - result: serializedResult, | |
| 163 | - profileId: | |
| 164 | - this.configHandler.currentProfile?.profileDescription.id || null, | |
| 165 | - organizations: this.configHandler.getSerializedOrgs(), | |
| 166 | - selectedOrgId: this.configHandler.currentOrg.id, | |
| 167 | - }); | |
| 168 | - | |
| 169 | - // update additional submenu context providers registered via VSCode API | |
| 170 | - const additionalProviders = | |
| 171 | - this.configHandler.getAdditionalSubmenuContextProviders(); | |
| 172 | - if (additionalProviders.length > 0) { | |
| 173 | - this.messenger.send("refreshSubmenuItems", { | |
| 174 | - providers: additionalProviders, | |
| 159 | + this.configHandler.onConfigUpdate((result) => { | |
| 160 | + void (async () => { | |
| 161 | + const serializedResult = await this.configHandler.getSerializedConfig(); | |
| 162 | + this.messenger.send("configUpdate", { | |
| 163 | + result: serializedResult, | |
| 164 | + profileId: | |
| 165 | + this.configHandler.currentProfile?.profileDescription.id || null, | |
| 166 | + organizations: this.configHandler.getSerializedOrgs(), | |
| 167 | + selectedOrgId: this.configHandler.currentOrg.id, | |
| 175 | 168 | }); |
| 176 | - } | |
| 169 | + | |
| 170 | + // update additional submenu context providers registered via VSCode API | |
| 171 | + const additionalProviders = | |
| 172 | + this.configHandler.getAdditionalSubmenuContextProviders(); | |
| 173 | + if (additionalProviders.length > 0) { | |
| 174 | + this.messenger.send("refreshSubmenuItems", { | |
| 175 | + providers: additionalProviders, | |
| 176 | + }); | |
| 177 | + } | |
| 178 | + })(); | |
| 177 | 179 | }); |
| 178 | 180 | |
| 179 | 181 | // Dev Data Logger |
| @@ -606,7 +608,7 @@ | ||
| 606 | 608 | // If it's a local assistant being created, we want to reload all assistants so it shows up in the list |
| 607 | 609 | let localAssistantCreated = false; |
| 608 | 610 | for (const uri of data.uris) { |
| 609 | - if (isLocalAssistantFile(uri)) { | |
| 611 | + if (isLocalDefinitionFile(uri)) { | |
| 610 | 612 | localAssistantCreated = true; |
| 611 | 613 | } |
| 612 | 614 | } |
modified core/indexing/LanceDbIndex.ts +4 −4
| @@ -97,8 +97,8 @@ | ||
| 97 | 97 | contents TEXT NOT NULL |
| 98 | 98 | )`); |
| 99 | 99 | |
| 100 | - await new Promise((resolve) => | |
| 101 | - migrate( | |
| 100 | + await new Promise((resolve) => { | |
| 101 | + void migrate( | |
| 102 | 102 | "lancedb_sqlite_artifact_id_column", |
| 103 | 103 | async () => { |
| 104 | 104 | try { |
| @@ -118,8 +118,8 @@ | ||
| 118 | 118 | } |
| 119 | 119 | }, |
| 120 | 120 | () => resolve(undefined), |
| 121 | - ), | |
| 122 | - ); | |
| 121 | + ); | |
| 122 | + }); | |
| 123 | 123 | } |
| 124 | 124 | |
| 125 | 125 | private async computeRows(items: PathAndCacheKey[]): Promise<LanceDbRow[]> { |
modified core/indexing/chunk/chunk.ts +17 −15
| @@ -50,21 +50,23 @@ | ||
| 50 | 50 | maxChunkSize, |
| 51 | 51 | )) { |
| 52 | 52 | chunkPromises.push( |
| 53 | - new Promise(async (resolve) => { | |
| 54 | - if ((await countTokensAsync(chunkWithoutId.content)) > maxChunkSize) { | |
| 55 | - // console.debug( | |
| 56 | - // `Chunk with more than ${maxChunkSize} tokens constructed: `, | |
| 57 | - // filepath, | |
| 58 | - // countTokens(chunkWithoutId.content), | |
| 59 | - // ); | |
| 60 | - return resolve(undefined); | |
| 61 | - } | |
| 62 | - resolve({ | |
| 63 | - ...chunkWithoutId, | |
| 64 | - digest, | |
| 65 | - index, | |
| 66 | - filepath, | |
| 67 | - }); | |
| 53 | + new Promise((resolve) => { | |
| 54 | + void (async () => { | |
| 55 | + if ((await countTokensAsync(chunkWithoutId.content)) > maxChunkSize) { | |
| 56 | + // console.debug( | |
| 57 | + // `Chunk with more than ${maxChunkSize} tokens constructed: `, | |
| 58 | + // filepath, | |
| 59 | + // countTokens(chunkWithoutId.content), | |
| 60 | + // ); | |
| 61 | + return resolve(undefined); | |
| 62 | + } | |
| 63 | + resolve({ | |
| 64 | + ...chunkWithoutId, | |
| 65 | + digest, | |
| 66 | + index, | |
| 67 | + filepath, | |
| 68 | + }); | |
| 69 | + })(); | |
| 68 | 70 | }), |
| 69 | 71 | ); |
| 70 | 72 | index++; |
modified core/indexing/docs/DocsService.ts +3 −1
| @@ -186,7 +186,9 @@ | ||
| 186 | 186 | private async init(configHandler: ConfigHandler) { |
| 187 | 187 | const result = await configHandler.loadConfig(); |
| 188 | 188 | await this.handleConfigUpdate(result); |
| 189 | - configHandler.onConfigUpdate(this.handleConfigUpdate.bind(this)); | |
| 189 | + configHandler.onConfigUpdate( | |
| 190 | + this.handleConfigUpdate.bind(this) as (arg: any) => void, | |
| 191 | + ); | |
| 190 | 192 | } |
| 191 | 193 | |
| 192 | 194 | readonly statuses: Map<string, IndexingStatus> = new Map(); |
modified core/indexing/docs/migrations.ts +4 −4
| @@ -6,8 +6,8 @@ | ||
| 6 | 6 | import DocsService, { SqliteDocsRow } from "./DocsService.js"; |
| 7 | 7 | |
| 8 | 8 | export async function runLanceMigrations(table: Table) { |
| 9 | - await new Promise((resolve) => | |
| 10 | - migrate( | |
| 9 | + await new Promise((resolve) => { | |
| 10 | + void migrate( | |
| 11 | 11 | "rename_baseurl_column_for_lance_docs", |
| 12 | 12 | async () => { |
| 13 | 13 | try { |
| @@ -21,8 +21,8 @@ | ||
| 21 | 21 | } |
| 22 | 22 | }, |
| 23 | 23 | () => resolve(undefined), |
| 24 | - ), | |
| 25 | - ); | |
| 24 | + ); | |
| 25 | + }); | |
| 26 | 26 | } |
| 27 | 27 | |
| 28 | 28 | export async function runSqliteMigrations(db: Database) { |
modified core/jest.config.js +1 −3
| @@ -29,7 +29,5 @@ | ||
| 29 | 29 | globalSetup: "<rootDir>/test/jest.global-setup.ts", |
| 30 | 30 | setupFilesAfterEnv: ["<rootDir>/test/jest.setup-after-env.js"], |
| 31 | 31 | maxWorkers: 1, // equivalent to CLI --runInBand |
| 32 | - modulePathIgnorePatterns: [ | |
| 33 | - "<rootDir>/config/yaml/LocalPlatformClient.test.ts", | |
| 34 | - ], | |
| 32 | + testMatch: ["**/*.test.ts"], | |
| 35 | 33 | }; |
modified core/llm/autodetect.ts +6 −0
| @@ -52,6 +52,7 @@ | ||
| 52 | 52 | "msty", |
| 53 | 53 | "anthropic", |
| 54 | 54 | "bedrock", |
| 55 | + "cohere", | |
| 55 | 56 | "sagemaker", |
| 56 | 57 | "continue-proxy", |
| 57 | 58 | "mistral", |
| @@ -65,6 +66,7 @@ | ||
| 65 | 66 | const PROVIDER_SUPPORTS_IMAGES: string[] = [ |
| 66 | 67 | "openai", |
| 67 | 68 | "ollama", |
| 69 | + "cohere", | |
| 68 | 70 | "gemini", |
| 69 | 71 | "msty", |
| 70 | 72 | "anthropic", |
| @@ -89,6 +91,8 @@ | ||
| 89 | 91 | "gpt-4o-mini", |
| 90 | 92 | "gpt-4-vision", |
| 91 | 93 | "claude-3", |
| 94 | + "c4ai-aya-vision-8b", | |
| 95 | + "c4ai-aya-vision-32b", | |
| 92 | 96 | "gemini-ultra", |
| 93 | 97 | "gemini-1.5-pro", |
| 94 | 98 | "gemini-1.5-flash", |
| @@ -140,6 +144,7 @@ | ||
| 140 | 144 | const PARALLEL_PROVIDERS: string[] = [ |
| 141 | 145 | "anthropic", |
| 142 | 146 | "bedrock", |
| 147 | + "cohere", | |
| 143 | 148 | "sagemaker", |
| 144 | 149 | "deepinfra", |
| 145 | 150 | "gemini", |
| @@ -176,6 +181,7 @@ | ||
| 176 | 181 | if ( |
| 177 | 182 | lower.includes("gpt") || |
| 178 | 183 | lower.includes("command") || |
| 184 | + lower.includes("aya") || | |
| 179 | 185 | lower.includes("chat-bison") || |
| 180 | 186 | lower.includes("pplx") || |
| 181 | 187 | lower.includes("gemini") || |
modified core/llm/index.ts +11 −3
| @@ -1068,9 +1068,17 @@ | ||
| 1068 | 1068 | documents: chunks.map((chunk) => chunk.content), |
| 1069 | 1069 | }); |
| 1070 | 1070 | |
| 1071 | - // Put them in the order they were given | |
| 1072 | - const sortedResults = results.data.sort((a, b) => a.index - b.index); | |
| 1073 | - return sortedResults.map((result) => result.relevance_score); | |
| 1071 | + // Standard OpenAI format | |
| 1072 | + if (results.data && Array.isArray(results.data)) { | |
| 1073 | + return results.data | |
| 1074 | + .sort((a, b) => a.index - b.index) | |
| 1075 | + .map((result) => result.relevance_score); | |
| 1076 | + } | |
| 1077 | + | |
| 1078 | + throw new Error( | |
| 1079 | + `Unexpected rerank response format from ${this.providerName}. ` + | |
| 1080 | + `Expected 'data' array but got: ${JSON.stringify(Object.keys(results))}`, | |
| 1081 | + ); | |
| 1074 | 1082 | } |
| 1075 | 1083 | |
| 1076 | 1084 | throw new Error( |
modified core/llm/llm.test.ts +7 −21
| @@ -161,12 +161,7 @@ | ||
| 161 | 161 | group: "Hello", |
| 162 | 162 | }, |
| 163 | 163 | ], |
| 164 | - toolChoice: { | |
| 165 | - type: "function", | |
| 166 | - function: { | |
| 167 | - name: "say_hello", | |
| 168 | - }, | |
| 169 | - }, | |
| 164 | + toolChoice: { type: "function", function: { name: "say_hello" } }, | |
| 170 | 165 | }, |
| 171 | 166 | )) { |
| 172 | 167 | const typedChunk = chunk as AssistantChatMessage; |
| @@ -211,10 +206,7 @@ | ||
| 211 | 206 | model: "claude-3-5-sonnet-latest", |
| 212 | 207 | apiKey: process.env.ANTHROPIC_API_KEY, |
| 213 | 208 | }), |
| 214 | - { | |
| 215 | - skip: false, | |
| 216 | - testToolCall: true, | |
| 217 | - }, | |
| 209 | + { skip: false, testToolCall: true }, | |
| 218 | 210 | ); |
| 219 | 211 | testLLM(new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "gpt-4o" }), { |
| 220 | 212 | skip: false, |
| @@ -240,12 +232,7 @@ | ||
| 240 | 232 | apiKey: process.env.MISTRAL_API_KEY, |
| 241 | 233 | model: "codestral-latest", |
| 242 | 234 | }), |
| 243 | - { | |
| 244 | - testFim: true, | |
| 245 | - skip: false, | |
| 246 | - testToolCall: true, | |
| 247 | - timeout: 60000, | |
| 248 | - }, | |
| 235 | + { testFim: true, skip: false, testToolCall: true, timeout: 60000 }, | |
| 249 | 236 | ); |
| 250 | 237 | testLLM( |
| 251 | 238 | new Azure({ |
| @@ -260,11 +247,10 @@ | ||
| 260 | 247 | ); |
| 261 | 248 | testLLM( |
| 262 | 249 | new Azure({ |
| 263 | - apiKey: process.env.AZURE_FOUNDRY_API_KEY, | |
| 264 | - model: "codestral-latest", | |
| 265 | - apiBase: | |
| 266 | - "https://codestral-2501-continue-testing.eastus.models.ai.azure.com", | |
| 267 | - apiType: "azure-foundry", | |
| 250 | + apiKey: process.env.AZURE_FOUNDRY_CODESTRAL_API_KEY, | |
| 251 | + model: "Codestral-2501", | |
| 252 | + apiBase: "https://continue-foundry-resource.services.ai.azure.com", | |
| 253 | + env: { apiType: "azure-foundry", apiVersion: "2024-05-01-preview" }, | |
| 268 | 254 | }), |
| 269 | 255 | { testFim: false, skip: false, timeout: 20000 }, |
| 270 | 256 | ); |
modified core/llm/llms/Cohere.ts +173 −20
| @@ -1,9 +1,10 @@ | ||
| 1 | -import { streamJSON } from "@continuedev/fetch"; | |
| 1 | +import { streamSse } from "@continuedev/fetch"; | |
| 2 | 2 | import { |
| 3 | 3 | ChatMessage, |
| 4 | 4 | Chunk, |
| 5 | 5 | CompletionOptions, |
| 6 | 6 | LLMOptions, |
| 7 | + MessageContent, | |
| 7 | 8 | } from "../../index.js"; |
| 8 | 9 | import { renderChatMessage, stripImages } from "../../util/messageContent.js"; |
| 9 | 10 | import { BaseLLM } from "../index.js"; |
| @@ -11,21 +12,89 @@ | ||
| 11 | 12 | class Cohere extends BaseLLM { |
| 12 | 13 | static providerName = "cohere"; |
| 13 | 14 | static defaultOptions: Partial<LLMOptions> = { |
| 14 | - apiBase: "https://api.cohere.ai/v1", | |
| 15 | + apiBase: "https://api.cohere.ai/v2", | |
| 15 | 16 | maxEmbeddingBatchSize: 96, |
| 16 | 17 | }; |
| 17 | 18 | static maxStopSequences = 5; |
| 18 | 19 | |
| 19 | 20 | private _convertMessages(msgs: ChatMessage[]): any[] { |
| 20 | 21 | const messages = []; |
| 22 | + let lastToolPlan: MessageContent | undefined; | |
| 21 | 23 | for (const m of msgs) { |
| 22 | - if (m.role === "system" || !m.content) { | |
| 24 | + if (!m.content) { | |
| 23 | 25 | continue; |
| 24 | 26 | } |
| 25 | - messages.push({ | |
| 26 | - role: m.role === "assistant" ? "chatbot" : m.role, | |
| 27 | - message: m.content, | |
| 28 | - }); | |
| 27 | + switch (m.role) { | |
| 28 | + case "user": | |
| 29 | + if (typeof m.content === "string") { | |
| 30 | + messages.push({ | |
| 31 | + role: m.role, | |
| 32 | + content: m.content, | |
| 33 | + }); | |
| 34 | + break; | |
| 35 | + } | |
| 36 | + | |
| 37 | + messages.push({ | |
| 38 | + role: m.role, | |
| 39 | + content: m.content.map((part) => { | |
| 40 | + if (part.type === "imageUrl") { | |
| 41 | + return { | |
| 42 | + type: "image_url", | |
| 43 | + image_url: { url: part.imageUrl.url }, | |
| 44 | + }; | |
| 45 | + } | |
| 46 | + return part; | |
| 47 | + }), | |
| 48 | + }); | |
| 49 | + break; | |
| 50 | + case "thinking": | |
| 51 | + lastToolPlan = m.content; | |
| 52 | + break; | |
| 53 | + case "assistant": | |
| 54 | + if (m.toolCalls) { | |
| 55 | + if (!lastToolPlan) { | |
| 56 | + throw new Error("No tool plan found"); | |
| 57 | + } | |
| 58 | + messages.push({ | |
| 59 | + role: m.role, | |
| 60 | + tool_calls: m.toolCalls.map((toolCall) => ({ | |
| 61 | + id: toolCall.id, | |
| 62 | + type: "function", | |
| 63 | + function: { | |
| 64 | + name: toolCall.function?.name, | |
| 65 | + arguments: toolCall.function?.arguments, | |
| 66 | + }, | |
| 67 | + })), | |
| 68 | + // Ideally the tool plan would be in this message, but it is | |
| 69 | + // split in another, usually the previous, this one's content is | |
| 70 | + // a space. | |
| 71 | + // tool_plan: m.content, | |
| 72 | + tool_plan: lastToolPlan, | |
| 73 | + }); | |
| 74 | + lastToolPlan = undefined; | |
| 75 | + break; | |
| 76 | + } | |
| 77 | + messages.push({ | |
| 78 | + role: m.role, | |
| 79 | + content: m.content, | |
| 80 | + }); | |
| 81 | + break; | |
| 82 | + case "system": | |
| 83 | + messages.push({ | |
| 84 | + role: m.role, | |
| 85 | + content: stripImages(m.content), | |
| 86 | + }); | |
| 87 | + break; | |
| 88 | + case "tool": | |
| 89 | + messages.push({ | |
| 90 | + role: m.role, | |
| 91 | + content: m.content, | |
| 92 | + tool_call_id: m.toolCallId, | |
| 93 | + }); | |
| 94 | + break; | |
| 95 | + default: | |
| 96 | + break; | |
| 97 | + } | |
| 29 | 98 | } |
| 30 | 99 | return messages; |
| 31 | 100 | } |
| @@ -41,7 +110,14 @@ | ||
| 41 | 110 | stop_sequences: options.stop?.slice(0, Cohere.maxStopSequences), |
| 42 | 111 | frequency_penalty: options.frequencyPenalty, |
| 43 | 112 | presence_penalty: options.presencePenalty, |
| 44 | - raw_prompting: options.raw, | |
| 113 | + tools: options.tools?.map((tool) => ({ | |
| 114 | + type: "function", | |
| 115 | + function: { | |
| 116 | + name: tool.function.name, | |
| 117 | + parameters: tool.function.parameters, | |
| 118 | + description: tool.function.description, | |
| 119 | + }, | |
| 120 | + })), | |
| 45 | 121 | }; |
| 46 | 122 | } |
| 47 | 123 | |
| @@ -67,19 +143,12 @@ | ||
| 67 | 143 | ...this.requestOptions?.headers, |
| 68 | 144 | }; |
| 69 | 145 | |
| 70 | - let preamble: string | undefined = undefined; | |
| 71 | - const systemMessage = messages.find((m) => m.role === "system")?.content; | |
| 72 | - if (systemMessage) { | |
| 73 | - preamble = stripImages(systemMessage); | |
| 74 | - } | |
| 75 | 146 | const resp = await this.fetch(new URL("chat", this.apiBase), { |
| 76 | 147 | method: "POST", |
| 77 | 148 | headers, |
| 78 | 149 | body: JSON.stringify({ |
| 79 | 150 | ...this._convertArgs(options), |
| 80 | - message: messages.pop()?.content, | |
| 81 | - chat_history: this._convertMessages(messages), | |
| 82 | - preamble, | |
| 151 | + messages: this._convertMessages(messages), | |
| 83 | 152 | }), |
| 84 | 153 | signal, |
| 85 | 154 | }); |
| @@ -90,13 +159,97 @@ | ||
| 90 | 159 | |
| 91 | 160 | if (options.stream === false) { |
| 92 | 161 | const data = await resp.json(); |
| 93 | - yield { role: "assistant", content: data.text }; | |
| 162 | + if (data.message.tool_calls) { | |
| 163 | + yield { | |
| 164 | + // Use the "thinking" role for `tool_plan`, since there is no such | |
| 165 | + // role in the Cohere API at the moment and it is a "a | |
| 166 | + // chain-of-thought style reflection". | |
| 167 | + role: "thinking", | |
| 168 | + content: data.message.tool_plan, | |
| 169 | + }; | |
| 170 | + yield { | |
| 171 | + role: "assistant", | |
| 172 | + content: "", | |
| 173 | + toolCalls: data.message.tool_calls.map((toolCall: any) => ({ | |
| 174 | + id: toolCall.id, | |
| 175 | + type: "function", | |
| 176 | + function: { | |
| 177 | + name: toolCall.function?.name, | |
| 178 | + arguments: toolCall.function?.arguments, | |
| 179 | + }, | |
| 180 | + })), | |
| 181 | + }; | |
| 182 | + return; | |
| 183 | + } | |
| 184 | + yield { role: "assistant", content: data.message.content[0].text }; | |
| 94 | 185 | return; |
| 95 | 186 | } |
| 96 | 187 | |
| 97 | - for await (const value of streamJSON(resp)) { | |
| 98 | - if (value.event_type === "text-generation") { | |
| 99 | - yield { role: "assistant", content: value.text }; | |
| 188 | + let lastToolUseId: string | undefined; | |
| 189 | + let lastToolUseName: string | undefined; | |
| 190 | + for await (const value of streamSse(resp)) { | |
| 191 | + // https://docs.cohere.com/v2/docs/streaming#stream-events | |
| 192 | + switch (value.type) { | |
| 193 | + // https://docs.cohere.com/v2/docs/streaming#content-delta | |
| 194 | + case "content-delta": | |
| 195 | + yield { | |
| 196 | + role: "assistant", | |
| 197 | + content: value.delta.message.content.text, | |
| 198 | + }; | |
| 199 | + break; | |
| 200 | + // https://docs.cohere.com/reference/chat-stream#request.body.messages.assistant.tool_plan | |
| 201 | + case "tool-plan-delta": | |
| 202 | + // Use the "thinking" role for `tool_plan`, since there is no such | |
| 203 | + // role in the Cohere API at the moment and it is a "a | |
| 204 | + // chain-of-thought style reflection". | |
| 205 | + yield { | |
| 206 | + role: "thinking", | |
| 207 | + content: value.delta.message.tool_plan, | |
| 208 | + }; | |
| 209 | + break; | |
| 210 | + case "tool-call-start": | |
| 211 | + lastToolUseId = value.delta.message.tool_calls.id; | |
| 212 | + lastToolUseName = value.delta.message.tool_calls.function.name; | |
| 213 | + yield { | |
| 214 | + role: "assistant", | |
| 215 | + content: "", | |
| 216 | + toolCalls: [ | |
| 217 | + { | |
| 218 | + id: lastToolUseId, | |
| 219 | + type: "function", | |
| 220 | + function: { | |
| 221 | + name: lastToolUseName, | |
| 222 | + arguments: value.delta.message.tool_calls.function.arguments, | |
| 223 | + }, | |
| 224 | + }, | |
| 225 | + ], | |
| 226 | + }; | |
| 227 | + break; | |
| 228 | + case "tool-call-delta": | |
| 229 | + if (!lastToolUseId || !lastToolUseName) { | |
| 230 | + throw new Error("No tool use found"); | |
| 231 | + } | |
| 232 | + yield { | |
| 233 | + role: "assistant", | |
| 234 | + content: "", | |
| 235 | + toolCalls: [ | |
| 236 | + { | |
| 237 | + id: lastToolUseId, | |
| 238 | + type: "function", | |
| 239 | + function: { | |
| 240 | + name: lastToolUseName, | |
| 241 | + arguments: value.delta.message.tool_calls.function.arguments, | |
| 242 | + }, | |
| 243 | + }, | |
| 244 | + ], | |
| 245 | + }; | |
| 246 | + break; | |
| 247 | + case "tool-call-end": | |
| 248 | + lastToolUseId = undefined; | |
| 249 | + lastToolUseName = undefined; | |
| 250 | + break; | |
| 251 | + default: | |
| 252 | + break; | |
| 100 | 253 | } |
| 101 | 254 | } |
| 102 | 255 | } |
modified core/llm/llms/Vllm.ts +41 −1
| @@ -1,7 +1,25 @@ | ||
| 1 | -import { LLMOptions } from "../../index.js"; | |
| 1 | +import { Chunk, LLMOptions } from "../../index.js"; | |
| 2 | 2 | |
| 3 | 3 | import OpenAI from "./OpenAI.js"; |
| 4 | 4 | |
| 5 | +// vLLM-specific rerank response types | |
| 6 | +interface VllmRerankItem { | |
| 7 | + index: number; | |
| 8 | + document: { | |
| 9 | + text: string; | |
| 10 | + }; | |
| 11 | + relevance_score: number; | |
| 12 | +} | |
| 13 | + | |
| 14 | +interface VllmRerankResponse { | |
| 15 | + id: string; | |
| 16 | + model: string; | |
| 17 | + usage: { | |
| 18 | + total_tokens: number; | |
| 19 | + }; | |
| 20 | + results: VllmRerankItem[]; | |
| 21 | +} | |
| 22 | + | |
| 5 | 23 | class Vllm extends OpenAI { |
| 6 | 24 | static providerName = "vllm"; |
| 7 | 25 | constructor(options: LLMOptions) { |
| @@ -16,6 +34,28 @@ | ||
| 16 | 34 | return false; |
| 17 | 35 | } |
| 18 | 36 | |
| 37 | + async rerank(query: string, chunks: Chunk[]): Promise<number[]> { | |
| 38 | + if (this.useOpenAIAdapterFor.includes("rerank") && this.openaiAdapter) { | |
| 39 | + const results = (await this.openaiAdapter.rerank({ | |
| 40 | + model: this.model, | |
| 41 | + query, | |
| 42 | + documents: chunks.map((chunk) => chunk.content), | |
| 43 | + })) as unknown as VllmRerankResponse; | |
| 44 | + | |
| 45 | + // vLLM uses 'results' array instead of 'data' | |
| 46 | + if (results.results && Array.isArray(results.results)) { | |
| 47 | + const sortedResults = results.results.sort((a, b) => a.index - b.index); | |
| 48 | + return sortedResults.map((result) => result.index); | |
| 49 | + } | |
| 50 | + | |
| 51 | + throw new Error( | |
| 52 | + `vLLM rerank response missing 'results' array. Got: ${JSON.stringify(Object.keys(results))}`, | |
| 53 | + ); | |
| 54 | + } | |
| 55 | + | |
| 56 | + throw new Error("vLLM rerank requires OpenAI adapter"); | |
| 57 | + } | |
| 58 | + | |
| 19 | 59 | private _setupCompletionOptions() { |
| 20 | 60 | this.fetch(this._getEndpoint("models"), { |
| 21 | 61 | method: "GET", |
modified core/llm/toolSupport.test.ts +14 −0
| @@ -109,6 +109,19 @@ | ||
| 109 | 109 | }); |
| 110 | 110 | }); |
| 111 | 111 | |
| 112 | + describe("cohere", () => { | |
| 113 | + const supportsFn = PROVIDER_TOOL_SUPPORT["cohere"]; | |
| 114 | + | |
| 115 | + it("should return true for Command models", () => { | |
| 116 | + expect(supportsFn("command-r")).toBe(true); | |
| 117 | + expect(supportsFn("command-a")).toBe(true); | |
| 118 | + }); | |
| 119 | + | |
| 120 | + it("should return false for other models", () => { | |
| 121 | + expect(supportsFn("c4ai-aya-expanse-32b")).toBe(false); | |
| 122 | + }); | |
| 123 | + }); | |
| 124 | + | |
| 112 | 125 | describe("gemini", () => { |
| 113 | 126 | const supportsFn = PROVIDER_TOOL_SUPPORT["gemini"]; |
| 114 | 127 | |
| @@ -221,6 +234,7 @@ | ||
| 221 | 234 | expect(supportsFn("qwen2")).toBe(true); |
| 222 | 235 | expect(supportsFn("mixtral-8x7b")).toBe(true); |
| 223 | 236 | expect(supportsFn("command-r")).toBe(true); |
| 237 | + expect(supportsFn("command-a")).toBe(true); | |
| 224 | 238 | expect(supportsFn("smollm2")).toBe(true); |
| 225 | 239 | expect(supportsFn("hermes3")).toBe(true); |
| 226 | 240 | expect(supportsFn("athene-v2")).toBe(true); |
modified core/llm/toolSupport.ts +5 −0
| @@ -71,6 +71,9 @@ | ||
| 71 | 71 | |
| 72 | 72 | return false; |
| 73 | 73 | }, |
| 74 | + cohere: (model) => { | |
| 75 | + return model.toLowerCase().startsWith("command"); | |
| 76 | + }, | |
| 74 | 77 | gemini: (model) => { |
| 75 | 78 | // All gemini models support function calling |
| 76 | 79 | return model.toLowerCase().includes("gemini"); |
| @@ -144,6 +147,7 @@ | ||
| 144 | 147 | "qwen3", |
| 145 | 148 | "mixtral", |
| 146 | 149 | "command-r", |
| 150 | + "command-a", | |
| 147 | 151 | "smollm2", |
| 148 | 152 | "hermes3", |
| 149 | 153 | "athene-v2", |
| @@ -226,6 +230,7 @@ | ||
| 226 | 230 | "qwen/qwen3", |
| 227 | 231 | "qwen/qwen-", |
| 228 | 232 | "cohere/command-r", |
| 233 | + "cohere/command-a", | |
| 229 | 234 | "ai21/jamba-1.6", |
| 230 | 235 | "mistralai/mistral", |
| 231 | 236 | "mistralai/ministral", |
added core/test/vitest.global-setup.ts +11 −0
| @@ -0,0 +1,11 @@ | ||
| 1 | +import fs from "fs"; | |
| 2 | +import path from "path"; | |
| 3 | + | |
| 4 | +// Sets up the GLOBAL directory for testing - equivalent to ~/.continue | |
| 5 | +// IMPORTANT: the CONTINUE_GLOBAL_DIR environment variable is used in utils/paths for getting all local paths | |
| 6 | +export default async function () { | |
| 7 | + process.env.CONTINUE_GLOBAL_DIR = path.join(__dirname, ".continue-test"); | |
| 8 | + if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR)) { | |
| 9 | + fs.rmdirSync(process.env.CONTINUE_GLOBAL_DIR, { recursive: true }); | |
| 10 | + } | |
| 11 | +} |
added core/test/vitest.setup.ts +16 −0
| @@ -0,0 +1,16 @@ | ||
| 1 | +import { TextDecoder, TextEncoder } from "util"; | |
| 2 | + | |
| 3 | +import fetch, { Request, Response } from "node-fetch"; | |
| 4 | +import { beforeAll } from "vitest"; | |
| 5 | + | |
| 6 | +beforeAll(() => { | |
| 7 | + // @ts-ignore | |
| 8 | + globalThis.fetch = fetch; | |
| 9 | + // @ts-ignore | |
| 10 | + globalThis.Request = Request; | |
| 11 | + // @ts-ignore | |
| 12 | + globalThis.Response = Response; | |
| 13 | + globalThis.TextEncoder = TextEncoder; | |
| 14 | + // @ts-ignore | |
| 15 | + globalThis.TextDecoder = TextDecoder; | |
| 16 | +}); |
modified core/tools/implementations/createRuleBlock.test.ts +1 −4
| @@ -1,5 +1,5 @@ | ||
| 1 | +import { parseMarkdownRule } from "@continuedev/config-yaml"; | |
| 1 | 2 | import { jest } from "@jest/globals"; |
| 2 | -import { parseMarkdownRule } from "../../config/markdown"; | |
| 3 | 3 | import { createRuleBlockImpl } from "./createRuleBlock"; |
| 4 | 4 | |
| 5 | 5 | const mockIde = { |
| @@ -40,7 +40,6 @@ | ||
| 40 | 40 | globs: "**/*.{ts,tsx}", |
| 41 | 41 | }); |
| 42 | 42 | |
| 43 | - expect(markdown).toContain("# TypeScript Rule"); | |
| 44 | 43 | expect(markdown).toContain("Use interfaces for object shapes"); |
| 45 | 44 | }); |
| 46 | 45 | |
| @@ -76,7 +75,6 @@ | ||
| 76 | 75 | description: "This is a detailed explanation of the rule", |
| 77 | 76 | }); |
| 78 | 77 | |
| 79 | - expect(markdown).toContain("# Description Test"); | |
| 80 | 78 | expect(markdown).toContain("This is the rule content"); |
| 81 | 79 | }); |
| 82 | 80 | |
| @@ -100,7 +98,6 @@ | ||
| 100 | 98 | globs: "**/*.js", |
| 101 | 99 | }); |
| 102 | 100 | |
| 103 | - expect(markdown).toContain("# Complete Rule"); | |
| 104 | 101 | expect(markdown).toContain("Follow this standard"); |
| 105 | 102 | }); |
| 106 | 103 |
modified core/tools/implementations/createRuleBlock.ts +2 −1
| @@ -1,6 +1,7 @@ | ||
| 1 | +import { createRuleMarkdown } from "@continuedev/config-yaml"; | |
| 1 | 2 | import { ToolImpl } from "."; |
| 2 | 3 | import { RuleWithSource } from "../.."; |
| 3 | -import { createRuleFilePath, createRuleMarkdown } from "../../config/markdown"; | |
| 4 | +import { createRuleFilePath } from "../../config/markdown/utils"; | |
| 4 | 5 | |
| 5 | 6 | export type CreateRuleBlockArgs = Pick< |
| 6 | 7 | Required<RuleWithSource>, |
modified core/tools/implementations/requestRule.ts +3 −7
| @@ -1,5 +1,4 @@ | ||
| 1 | 1 | import { ToolImpl } from "."; |
| 2 | -import { parseMarkdownRule } from "../../config/markdown/parseMarkdownRule"; | |
| 3 | 2 | |
| 4 | 3 | export const requestRuleImpl: ToolImpl = async (args, extras) => { |
| 5 | 4 | // Find the rule by name in the config |
| @@ -11,14 +10,11 @@ | ||
| 11 | 10 | ); |
| 12 | 11 | } |
| 13 | 12 | |
| 14 | - const fileContent = await extras.ide.readFile(rule.ruleFile); | |
| 15 | - const { markdown, frontmatter } = parseMarkdownRule(fileContent); | |
| 16 | - | |
| 17 | 13 | return [ |
| 18 | 14 | { |
| 19 | - name: frontmatter.name ?? "", | |
| 20 | - description: frontmatter.description ?? "", | |
| 21 | - content: markdown, | |
| 15 | + name: rule.name ?? "", | |
| 16 | + description: rule.description ?? "", | |
| 17 | + content: rule.rule, | |
| 22 | 18 | uri: { |
| 23 | 19 | type: "file", |
| 24 | 20 | value: rule.ruleFile, |
modified core/tools/implementations/runTerminalCommand.ts +63 −47
| @@ -10,6 +10,16 @@ | ||
| 10 | 10 | |
| 11 | 11 | const asyncExec = util.promisify(childProcess.exec); |
| 12 | 12 | |
| 13 | +// Add color-supporting environment variables | |
| 14 | +const getColorEnv = () => ({ | |
| 15 | + ...process.env, | |
| 16 | + FORCE_COLOR: "1", | |
| 17 | + COLORTERM: "truecolor", | |
| 18 | + TERM: "xterm-256color", | |
| 19 | + CLICOLOR: "1", | |
| 20 | + CLICOLOR_FORCE: "1", | |
| 21 | +}); | |
| 22 | + | |
| 13 | 23 | const ENABLED_FOR_REMOTES = [ |
| 14 | 24 | "", |
| 15 | 25 | "local", |
| @@ -56,10 +66,11 @@ | ||
| 56 | 66 | } |
| 57 | 67 | } |
| 58 | 68 | |
| 59 | - // Use spawn instead of exec to get streaming output | |
| 69 | + // Use spawn with color environment | |
| 60 | 70 | const childProc = childProcess.spawn(args.command, { |
| 61 | 71 | cwd, |
| 62 | 72 | shell: true, |
| 73 | + env: getColorEnv(), // Add enhanced environment for colors | |
| 63 | 74 | }); |
| 64 | 75 | |
| 65 | 76 | childProc.stdout?.on("data", (data) => { |
| @@ -130,26 +141,7 @@ | ||
| 130 | 141 | return; |
| 131 | 142 | } |
| 132 | 143 | |
| 133 | - if (!waitForCompletion) { | |
| 134 | - // Already resolved, just update the UI with final output | |
| 135 | - if (extras.onPartialOutput) { | |
| 136 | - const status = | |
| 137 | - code === 0 || !code | |
| 138 | - ? "\nBackground command completed" | |
| 139 | - : `\nBackground command failed with exit code ${code}`; | |
| 140 | - extras.onPartialOutput({ | |
| 141 | - toolCallId, | |
| 142 | - contextItems: [ | |
| 143 | - { | |
| 144 | - name: "Terminal", | |
| 145 | - description: "Terminal command output", | |
| 146 | - content: terminalOutput, | |
| 147 | - status: status, | |
| 148 | - }, | |
| 149 | - ], | |
| 150 | - }); | |
| 151 | - } | |
| 152 | - } else { | |
| 144 | + if (waitForCompletion) { | |
| 153 | 145 | // Normal completion, resolve now |
| 154 | 146 | if (code === 0) { |
| 155 | 147 | const status = "Command completed"; |
| @@ -172,6 +164,25 @@ | ||
| 172 | 164 | }, |
| 173 | 165 | ]); |
| 174 | 166 | } |
| 167 | + } else { | |
| 168 | + // Already resolved, just update the UI with final output | |
| 169 | + if (extras.onPartialOutput) { | |
| 170 | + const status = | |
| 171 | + code === 0 || !code | |
| 172 | + ? "\nBackground command completed" | |
| 173 | + : `\nBackground command failed with exit code ${code}`; | |
| 174 | + extras.onPartialOutput({ | |
| 175 | + toolCallId, | |
| 176 | + contextItems: [ | |
| 177 | + { | |
| 178 | + name: "Terminal", | |
| 179 | + description: "Terminal command output", | |
| 180 | + content: terminalOutput, | |
| 181 | + status: status, | |
| 182 | + }, | |
| 183 | + ], | |
| 184 | + }); | |
| 185 | + } | |
| 175 | 186 | } |
| 176 | 187 | }); |
| 177 | 188 | |
| @@ -197,14 +208,43 @@ | ||
| 197 | 208 | const workspaceDirs = await extras.ide.getWorkspaceDirs(); |
| 198 | 209 | const cwd = fileURLToPath(workspaceDirs[0]); |
| 199 | 210 | |
| 200 | - if (!waitForCompletion) { | |
| 211 | + if (waitForCompletion) { | |
| 212 | + // Standard execution, waiting for completion | |
| 213 | + try { | |
| 214 | + // Use color environment for exec as well | |
| 215 | + const output = await asyncExec(args.command, { | |
| 216 | + cwd, | |
| 217 | + env: getColorEnv(), | |
| 218 | + }); | |
| 219 | + const status = "Command completed"; | |
| 220 | + return [ | |
| 221 | + { | |
| 222 | + name: "Terminal", | |
| 223 | + description: "Terminal command output", | |
| 224 | + content: output.stdout ?? "", | |
| 225 | + status: status, | |
| 226 | + }, | |
| 227 | + ]; | |
| 228 | + } catch (error: any) { | |
| 229 | + const status = `Command failed with: ${error.message || error.toString()}`; | |
| 230 | + return [ | |
| 231 | + { | |
| 232 | + name: "Terminal", | |
| 233 | + description: "Terminal command output", | |
| 234 | + content: error.stderr ?? error.toString(), | |
| 235 | + status: status, | |
| 236 | + }, | |
| 237 | + ]; | |
| 238 | + } | |
| 239 | + } else { | |
| 201 | 240 | // For non-streaming but also not waiting for completion, use spawn |
| 202 | 241 | // but don't attach any listeners other than error |
| 203 | 242 | try { |
| 204 | - // Use spawn instead of exec but don't wait | |
| 243 | + // Use spawn with color environment | |
| 205 | 244 | const childProc = childProcess.spawn(args.command, { |
| 206 | 245 | cwd, |
| 207 | 246 | shell: true, |
| 247 | + env: getColorEnv(), // Add color environment | |
| 208 | 248 | // Detach the process so it's not tied to the parent |
| 209 | 249 | detached: true, |
| 210 | 250 | // Redirect to /dev/null equivalent (works cross-platform) |
| @@ -246,30 +286,6 @@ | ||
| 246 | 286 | }, |
| 247 | 287 | ]; |
| 248 | 288 | } |
| 249 | - } else { | |
| 250 | - // Standard execution, waiting for completion | |
| 251 | - try { | |
| 252 | - const output = await asyncExec(args.command, { cwd }); | |
| 253 | - const status = "Command completed"; | |
| 254 | - return [ | |
| 255 | - { | |
| 256 | - name: "Terminal", | |
| 257 | - description: "Terminal command output", | |
| 258 | - content: output.stdout ?? "", | |
| 259 | - status: status, | |
| 260 | - }, | |
| 261 | - ]; | |
| 262 | - } catch (error: any) { | |
| 263 | - const status = `Command failed with: ${error.message || error.toString()}`; | |
| 264 | - return [ | |
| 265 | - { | |
| 266 | - name: "Terminal", | |
| 267 | - description: "Terminal command output", | |
| 268 | - content: error.stderr ?? error.toString(), | |
| 269 | - status: status, | |
| 270 | - }, | |
| 271 | - ]; | |
| 272 | - } | |
| 273 | 289 | } |
| 274 | 290 | } |
| 275 | 291 | } |
modified core/util/shellPath.ts +3 −6
| @@ -1,10 +1,6 @@ | ||
| 1 | 1 | import { execSync } from "child_process"; |
| 2 | +import { homedir } from "os"; | |
| 2 | 3 | |
| 3 | -/** | |
| 4 | - * Gets the PATH env var from the user's login shell on non-Windows platforms. | |
| 5 | - * Windows is not implemented primarily because it is not needed at the moment. | |
| 6 | - * @returns The enhanced PATH from the user's shell, or the current PATH if it cannot be determined | |
| 7 | - */ | |
| 8 | 4 | export function getEnvPathFromUserShell(): string | undefined { |
| 9 | 5 | if (process.platform === "win32") { |
| 10 | 6 | console.warn(`${getEnvPathFromUserShell.name} not implemented for Windows`); |
| @@ -16,7 +12,8 @@ | ||
| 16 | 12 | } |
| 17 | 13 | |
| 18 | 14 | try { |
| 19 | - const command = `${process.env.SHELL} -l -c 'echo $PATH'`; | |
| 15 | + // Source common profile files | |
| 16 | + const command = `${process.env.SHELL} -l -c 'for f in ~/.zprofile ~/.zshrc ~/.bash_profile ~/.bashrc; do [ -f "$f" ] && source "$f" 2>/dev/null; done; echo $PATH'`; | |
| 20 | 17 | |
| 21 | 18 | const stdout = execSync(command, { |
| 22 | 19 | encoding: "utf8", |
modified core/util/treeSitter.ts +2 −2
| @@ -181,7 +181,7 @@ | ||
| 181 | 181 | } |
| 182 | 182 | |
| 183 | 183 | const sourcePath = path.join( |
| 184 | - __dirname, | |
| 184 | + process.env.NODE_ENV === "test" ? process.cwd() : __dirname, | |
| 185 | 185 | "..", |
| 186 | 186 | ...(process.env.NODE_ENV === "test" |
| 187 | 187 | ? ["extensions", "vscode", "tree-sitter"] |
| @@ -201,7 +201,7 @@ | ||
| 201 | 201 | fileExtension: string, |
| 202 | 202 | ): Promise<Language> { |
| 203 | 203 | const wasmPath = path.join( |
| 204 | - __dirname, | |
| 204 | + process.env.NODE_ENV === "test" ? process.cwd() : __dirname, | |
| 205 | 205 | ...(process.env.NODE_ENV === "test" |
| 206 | 206 | ? ["node_modules", "tree-sitter-wasms", "out"] |
| 207 | 207 | : ["tree-sitter-wasms"]), |
modified core/vitest.config.ts +7 −0
| @@ -2,6 +2,13 @@ | ||
| 2 | 2 | |
| 3 | 3 | export default defineConfig({ |
| 4 | 4 | test: { |
| 5 | + testTransformMode: { | |
| 6 | + web: ["/.[jt]s?$/"], | |
| 7 | + ssr: ["/.[jt]s?$/"], | |
| 8 | + }, | |
| 9 | + globalSetup: "./test/vitest.global-setup.ts", | |
| 10 | + setupFiles: "./test/vitest.setup.ts", | |
| 11 | + fileParallelism: false, | |
| 5 | 12 | include: ["**/*.vitest.ts"], |
| 6 | 13 | }, |
| 7 | 14 | }); |
modified docs/docs/customize/deep-dives/mcp.mdx +156 −26
| @@ -7,45 +7,175 @@ | ||
| 7 | 7 | import TabItem from "@theme/TabItem"; |
| 8 | 8 | import Tabs from "@theme/Tabs"; |
| 9 | 9 | |
| 10 | -## MCP | |
| 10 | +# MCP | |
| 11 | 11 | |
| 12 | -Currently custom tools can be configured using the [Model Context Protocol](https://modelcontextprotocol.io/introduction), a standard proposed by Anthropic to unify prompts, context, and tool use. | |
| 12 | +As AI systems get better, they're still held back by their training data and | |
| 13 | +can't access real-time information or specialized tools. The [Model Context | |
| 14 | +Protocol](https://modelcontextprotocol.io/introduction) (MCP) fixes this by | |
| 15 | +letting AI models connect with outside data sources, tools, and environments. | |
| 16 | +This allows smooth sharing of information and abilities between AI systems and | |
| 17 | +the wider digital world. This standard, created by Anthropic to bring together | |
| 18 | +prompts, context, and tool use, is key for building truly useful AI experiences | |
| 19 | +that can be set up with custom tools. | |
| 13 | 20 | |
| 14 | -MCP Servers can be added to hub Assistants using `mcpServers` blocks. You can explore available MCP server blocks [here](https://hub.continue.dev/explore/mcp). | |
| 21 | +## How it works | |
| 22 | + | |
| 23 | +Currently custom tools can be configured using the Model Context | |
| 24 | +Protocol standard to unify prompts, context, and tool use. | |
| 25 | + | |
| 26 | +MCP Servers can be added to hub Assistants using `mcpServers` blocks. You can | |
| 27 | +explore available MCP server blocks | |
| 28 | +[here](https://hub.continue.dev/explore/mcp). | |
| 15 | 29 | |
| 16 | 30 | :::info |
| 17 | 31 | MCP can only be used in the **agent** mode. |
| 18 | 32 | ::: |
| 19 | 33 | |
| 20 | -To set up your own MCP server, read the [MCP quickstart](https://modelcontextprotocol.io/quickstart) and then [create an `mcpServers` block](https://hub.continue.dev/new?type=block&blockType=mcpServers) or add the following to your [config file](./configuration.md): | |
| 34 | +## Quick Start | |
| 35 | + | |
| 36 | +Below is a quick example of setting up a new MCP server for use in your assistant: | |
| 37 | + | |
| 38 | +1. Create a folder called `.continue/mcpServers` at the top level of your workspace | |
| 39 | +2. Add a file called `playwright-mcp.yaml` to this folder. | |
| 40 | +3. Write the following contents to `playwright-mcp.yaml` and save. | |
| 41 | + | |
| 42 | +```yaml title=".continue/mcpServers/playwright-mcp.yaml" | |
| 43 | +name: Playwright mcpServer | |
| 44 | +version: 0.0.1 | |
| 45 | +schema: v1 | |
| 46 | +mcpServers: | |
| 47 | + - name: Browser search | |
| 48 | + command: npx | |
| 49 | + args: | |
| 50 | + - "@playwright/mcp@latest" | |
| 51 | +``` | |
| 52 | + | |
| 53 | +Now test your MCP server by prompting the following command: | |
| 54 | + | |
| 55 | +``` | |
| 56 | +Open the browser and navigate Hacker News. Save the top 10 headlines in a hn.txt file. | |
| 57 | +``` | |
| 58 | + | |
| 59 | +The result will be a generated file called `hn.txt` in the current working directory. | |
| 21 | 60 | |
| 22 | -<Tabs groupId="config-example"> | |
| 61 | + | |
| 62 | + | |
| 63 | +## Using MCP Servers | |
| 64 | + | |
| 65 | +To set up your own MCP server, read the [MCP | |
| 66 | +quickstart](https://modelcontextprotocol.io/quickstart) and then [create an | |
| 67 | +`mcpServers` | |
| 68 | +block](https://hub.continue.dev/new?type=block&blockType=mcpServers) or add a local MCP | |
| 69 | +server block to your [config file](./configuration.md): | |
| 70 | + | |
| 71 | +<Tabs groupId="config.yaml"> | |
| 23 | 72 | <TabItem value="yaml" label="YAML"> |
| 24 | 73 | ```yaml title="config.yaml" |
| 25 | 74 | mcpServers: |
| 26 | - - name: My MCP Server | |
| 27 | - command: uvx | |
| 75 | + - name: SQLite MCP | |
| 76 | + command: npx | |
| 28 | 77 | args: |
| 29 | - - mcp-server-sqlite | |
| 30 | - - --db-path | |
| 31 | - - /Users/NAME/test.db | |
| 32 | - ``` | |
| 33 | - </TabItem> | |
| 34 | - <TabItem value="json" label="JSON"> | |
| 35 | - ```json title="config.json" | |
| 36 | - { | |
| 37 | - "experimental": { | |
| 38 | - "modelContextProtocolServers": [ | |
| 39 | - { | |
| 40 | - "transport": { | |
| 41 | - "type": "stdio", | |
| 42 | - "command": "uvx", | |
| 43 | - "args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"] | |
| 44 | - } | |
| 78 | + - "-y" | |
| 79 | + - "mcp-sqlite" | |
| 80 | + - "/path/to/your/database.db" | |
| 81 | + | |
| 82 | +```` | |
| 83 | +</TabItem> | |
| 84 | +<TabItem value="json" label="JSON"> | |
| 85 | +```json title="config.json" | |
| 86 | +{ | |
| 87 | + "experimental": { | |
| 88 | + "modelContextProtocolServers": [ | |
| 89 | + { | |
| 90 | + "transport": { | |
| 91 | + "type": "stdio", | |
| 92 | + "command": "uvx", | |
| 93 | + "args": ["mcp-server-sqlite", "--db-path", "/path/to/your/database.db"] | |
| 45 | 94 | } |
| 46 | - ] | |
| 47 | - } | |
| 95 | + } | |
| 96 | + ] | |
| 48 | 97 | } |
| 49 | - ``` | |
| 98 | +} | |
| 99 | +```` | |
| 100 | + | |
| 50 | 101 | </TabItem> |
| 51 | 102 | </Tabs> |
| 103 | + | |
| 104 | +### Syntax | |
| 105 | + | |
| 106 | +MCP blocks follow the established syntax for blocks, with a few additional properties specific to MCP servers. | |
| 107 | + | |
| 108 | +- `name` (**required**): A display name for the MCP server. | |
| 109 | +- `command` (**required**): The command to run to start the MCP server. | |
| 110 | +- `type` (optional): The type of the MCP server: `sse`, `stdio`, `streamable-http` | |
| 111 | +- `args` (optional): Arguments to pass to the command. | |
| 112 | +- `env` (optional): Secrets to be injected into the command as environment variables. | |
| 113 | + | |
| 114 | +### Transport Types | |
| 115 | + | |
| 116 | +MCP now supports remote server connections through HTTP-based transports, expanding beyond the traditional local stdio transport method. This enables integration with cloud-hosted MCP servers and distributed architectures. | |
| 117 | + | |
| 118 | +#### Server-Sent Events (SSE) Transport | |
| 119 | + | |
| 120 | +For real-time streaming communication, use the SSE transport: | |
| 121 | + | |
| 122 | +```yaml | |
| 123 | +mcpServers: | |
| 124 | + - name: Name | |
| 125 | + type: sse | |
| 126 | + url: https://.... | |
| 127 | +``` | |
| 128 | + | |
| 129 | +#### Standard Input/Output (stdio) | |
| 130 | + | |
| 131 | +For local MCP servers that communicate via standard input and output: | |
| 132 | + | |
| 133 | +```yaml | |
| 134 | +mcpServers: | |
| 135 | + - name: Name | |
| 136 | + type: stdio | |
| 137 | + command: npx | |
| 138 | + args: | |
| 139 | + - "@modelcontextprotocol/server-sqlite" | |
| 140 | + - "/path/to/your/database.db" | |
| 141 | +``` | |
| 142 | + | |
| 143 | +#### Streamable HTTP Transport | |
| 144 | + | |
| 145 | +For standard HTTP-based communication with streaming capabilities: | |
| 146 | + | |
| 147 | +```yaml | |
| 148 | +mcpServers: | |
| 149 | + - name: Name | |
| 150 | + type: streamable-http | |
| 151 | + url: https://.... | |
| 152 | +``` | |
| 153 | + | |
| 154 | +These remote transport options allow you to connect to MCP servers hosted on remote infrastructure, enabling more flexible deployment architectures and shared server resources across multiple clients. | |
| 155 | + | |
| 156 | +For detailed information about transport mechanisms and their use cases, refer to the official MCP documentation on [transports](https://modelcontextprotocol.io/docs/concepts/transports#server-sent-events-sse). | |
| 157 | + | |
| 158 | +### Working with Secrets | |
| 159 | + | |
| 160 | +With some MCP servers you will need to use API keys or other secrets. You can leverage locally stored environments secrets | |
| 161 | +as well as access hosted secrets in the Continue Hub. To leverage Hub secrets, you can use the `inputs` property in your MCP env block instead of `secrets`. | |
| 162 | + | |
| 163 | +```yaml | |
| 164 | +mcpServers: | |
| 165 | + - name: Supabase MCP | |
| 166 | + command: npx | |
| 167 | + args: | |
| 168 | + - -y | |
| 169 | + - "@supabase/mcp-server-supabase@latest" | |
| 170 | + - --access-token | |
| 171 | + - ${{ secrets.SUPABASE_TOKEN }} | |
| 172 | + env: | |
| 173 | + SUPABASE_TOKEN: ${{ secrets.SUPABASE_TOKEN }} | |
| 174 | + - name: GitHub | |
| 175 | + command: npx | |
| 176 | + args: | |
| 177 | + - "-y" | |
| 178 | + - "@modelcontextprotocol/server-github" | |
| 179 | + env: | |
| 180 | + GITHUB_PERSONAL_ACCESS_TOKEN: ${{ secrets.GITHUB_PERSONAL_ACCESS_TOKEN }} | |
| 181 | +``` |
modified docs/docs/customize/model-providers/more/cohere.mdx +13 −13
| @@ -7,15 +7,15 @@ | ||
| 7 | 7 | |
| 8 | 8 | ## Chat model |
| 9 | 9 | |
| 10 | -We recommend configuring **Command-R Plus** as your chat model. | |
| 10 | +We recommend configuring **Command A** as your chat model. | |
| 11 | 11 | |
| 12 | 12 | <Tabs groupId="config-example"> |
| 13 | 13 | <TabItem value="yaml" label="YAML"> |
| 14 | 14 | ```yaml title="config.yaml" |
| 15 | 15 | models: |
| 16 | - - name: Cohere | |
| 16 | + - name: Command A 03-2025 | |
| 17 | 17 | provider: cohere |
| 18 | - model: command-r-plus | |
| 18 | + model: command-a-03-2025 | |
| 19 | 19 | apiKey: <YOUR_COHERE_API_KEY> |
| 20 | 20 | ``` |
| 21 | 21 | </TabItem> |
| @@ -24,9 +24,9 @@ | ||
| 24 | 24 | { |
| 25 | 25 | "models": [ |
| 26 | 26 | { |
| 27 | - "title": "Cohere", | |
| 27 | + "title": "Command A 03-2025", | |
| 28 | 28 | "provider": "cohere", |
| 29 | - "model": "command-r-plus", | |
| 29 | + "model": "command-a-03-2025", | |
| 30 | 30 | "apiKey": "<YOUR_COHERE_API_KEY>" |
| 31 | 31 | } |
| 32 | 32 | ] |
| @@ -43,15 +43,15 @@ | ||
| 43 | 43 | |
| 44 | 44 | ## Embeddings model |
| 45 | 45 | |
| 46 | -We recommend configuring **embed-english-v3.0** as your embeddings model. | |
| 46 | +We recommend configuring **embed-v4.0** as your embeddings model. | |
| 47 | 47 | |
| 48 | 48 | <Tabs groupId="config-example"> |
| 49 | 49 | <TabItem value="yaml" label="YAML"> |
| 50 | 50 | ```yaml title="config.yaml" |
| 51 | 51 | models: |
| 52 | - - name: Cohere Embed | |
| 52 | + - name: Cohere Embed v4.0 | |
| 53 | 53 | provider: cohere |
| 54 | - model: embed-english-v3.0 | |
| 54 | + model: embed-v4.0 | |
| 55 | 55 | apiKey: <YOUR_COHERE_API_KEY> |
| 56 | 56 | roles: |
| 57 | 57 | - embed |
| @@ -62,7 +62,7 @@ | ||
| 62 | 62 | { |
| 63 | 63 | "embeddingsProvider": { |
| 64 | 64 | "provider": "cohere", |
| 65 | - "model": "embed-english-v3.0", | |
| 65 | + "model": "embed-v4.0", | |
| 66 | 66 | "apiKey": "<YOUR_COHERE_API_KEY>" |
| 67 | 67 | } |
| 68 | 68 | } |
| @@ -72,15 +72,15 @@ | ||
| 72 | 72 | |
| 73 | 73 | ## Reranking model |
| 74 | 74 | |
| 75 | -We recommend configuring **rerank-english-v3.0** as your reranking model. | |
| 75 | +We recommend configuring **rerank-v3.5** as your reranking model. | |
| 76 | 76 | |
| 77 | 77 | <Tabs groupId="config-example"> |
| 78 | 78 | <TabItem value="yaml" label="YAML"> |
| 79 | 79 | ```yaml title="config.yaml" |
| 80 | 80 | models: |
| 81 | - - name: Cohere Reranker | |
| 81 | + - name: Cohere Rerank v3.5 | |
| 82 | 82 | provider: cohere |
| 83 | - model: rerank-english-v3.0 | |
| 83 | + model: rerank-v3.5 | |
| 84 | 84 | apiKey: <YOUR_COHERE_API_KEY> |
| 85 | 85 | roles: |
| 86 | 86 | - rerank |
| @@ -92,7 +92,7 @@ | ||
| 92 | 92 | "reranker": { |
| 93 | 93 | "name": "cohere", |
| 94 | 94 | "params": { |
| 95 | - "model": "rerank-english-v3.0", | |
| 95 | + "model": "rerank-v3.5", | |
| 96 | 96 | "apiKey": "<YOUR_COHERE_API_KEY>" |
| 97 | 97 | } |
| 98 | 98 | } |
modified docs/docs/customize/model-providers/more/vllm.mdx +2 −0
| @@ -100,6 +100,8 @@ | ||
| 100 | 100 | |
| 101 | 101 | ## Reranking model |
| 102 | 102 | |
| 103 | +Continue automatically handles vLLM's response format (which uses `results` instead of `data`). | |
| 104 | + | |
| 103 | 105 | [Click here](../../model-roles/reranking.mdx) to see a list of reranking model providers. |
| 104 | 106 | |
| 105 | 107 | The continue implementation uses [OpenAI](../top-level/openai.mdx) under the hood. [View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Vllm.ts) |
modified docs/docs/customize/model-providers/top-level/anthropic.mdx +21 −12
| @@ -12,15 +12,15 @@ | ||
| 12 | 12 | |
| 13 | 13 | ## Chat model |
| 14 | 14 | |
| 15 | -We recommend configuring **Claude 3.5 Sonnet** as your chat model. | |
| 15 | +We recommend configuring **Claude 4 Sonnet** as your chat model. | |
| 16 | 16 | |
| 17 | 17 | <Tabs groupId="config-example"> |
| 18 | 18 | <TabItem value="yaml" label="YAML"> |
| 19 | 19 | ```yaml title="config.yaml" |
| 20 | 20 | models: |
| 21 | - - name: Claude 3.5 Sonnet | |
| 21 | + - name: Claude 4 Sonnet | |
| 22 | 22 | provider: anthropic |
| 23 | - model: claude-3-5-sonnet-latest | |
| 23 | + model: claude-sonnet-4-20250514 | |
| 24 | 24 | apiKey: <YOUR_ANTHROPIC_API_KEY> |
| 25 | 25 | ``` |
| 26 | 26 | </TabItem> |
| @@ -29,9 +29,9 @@ | ||
| 29 | 29 | { |
| 30 | 30 | "models": [ |
| 31 | 31 | { |
| 32 | - "title": "Claude 3.5 Sonnet", | |
| 32 | + "title": "Claude 4 Sonnet", | |
| 33 | 33 | "provider": "anthropic", |
| 34 | - "model": "claude-3-5-sonnet-latest", | |
| 34 | + "model": "claude-sonnet-4-latest", | |
| 35 | 35 | "apiKey": "<YOUR_ANTHROPIC_API_KEY>" |
| 36 | 36 | } |
| 37 | 37 | ] |
| @@ -60,9 +60,16 @@ | ||
| 60 | 60 | |
| 61 | 61 | ## Prompt caching |
| 62 | 62 | |
| 63 | -Anthropic supports [prompt caching with Claude](https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching). | |
| 63 | +Anthropic supports [prompt caching with Claude](https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching), which allows Claude models to cache system messages and conversation history between requests to improve performance and reduce costs. | |
| 64 | 64 | |
| 65 | -To enable caching of the system message and the turn-by-turn conversation, update your your model configuration as following: | |
| 65 | +Prompt caching is generally available for: | |
| 66 | + | |
| 67 | +- Claude 4 Sonnet | |
| 68 | +- Claude 3.7 Sonnet | |
| 69 | +- Claude 3.5 Sonnet | |
| 70 | +- Claude 3.5 Haiku | |
| 71 | + | |
| 72 | +To enable caching of the system message and the turn-by-turn conversation, update your model configuration as follows: | |
| 66 | 73 | |
| 67 | 74 | <Tabs groupId="config-example"> |
| 68 | 75 | <TabItem value="yaml" label="YAML"> |
| @@ -70,13 +77,12 @@ | ||
| 70 | 77 | models: |
| 71 | 78 | - name: Anthropic |
| 72 | 79 | provider: anthropic |
| 73 | - model: claude-3-5-sonnet-latest | |
| 80 | + model: claude-sonnet-4-20250514 | |
| 74 | 81 | apiKey: <YOUR_ANTHROPIC_API_KEY> |
| 75 | 82 | roles: |
| 76 | 83 | - chat |
| 77 | - cacheBehavior: | |
| 78 | - cacheSystemMessage: true | |
| 79 | - cacheConversation: true | |
| 84 | + defaultCompletionOptions: | |
| 85 | + promptCaching: true | |
| 80 | 86 | ``` |
| 81 | 87 | </TabItem> |
| 82 | 88 | <TabItem value="json" label="JSON"> |
| @@ -90,7 +96,10 @@ | ||
| 90 | 96 | }, |
| 91 | 97 | "title": "Anthropic", |
| 92 | 98 | "provider": "anthropic", |
| 93 | - "model": "claude-3-5-sonnet-latest", | |
| 99 | + "model": "claude-sonnet-4-latest", | |
| 100 | + "defaultCompletionOptions": { | |
| 101 | + "promptCaching": true | |
| 102 | + }, | |
| 94 | 103 | "apiKey": "<YOUR_ANTHROPIC_API_KEY>" |
| 95 | 104 | } |
| 96 | 105 | ] |
modified docs/docs/customize/model-roles/apply.mdx +1 −0
| @@ -2,6 +2,7 @@ | ||
| 2 | 2 | title: Apply Role |
| 3 | 3 | description: Apply model role |
| 4 | 4 | keywords: [apply, model, role] |
| 5 | +sidebar_position: 4 | |
| 5 | 6 | --- |
| 6 | 7 | |
| 7 | 8 | When editing code, Chat and Edit model output often doesn't clearly align with existing code. A model with the `apply` role is used to generate a more precise diff to apply changes to a file. |
modified docs/docs/troubleshooting.mdx +6 −0
| @@ -162,6 +162,12 @@ | ||
| 162 | 162 | |
| 163 | 163 | For more details about this requirement, see the [LanceDB issue #2195](https://github.com/lancedb/lance/issues/2195). |
| 164 | 164 | |
| 165 | +### How do I reset the state of the extension? | |
| 166 | + | |
| 167 | +Continue stores it's data in the `~/.continue` directory (%USERPROFILE%\.continue` on Windows). | |
| 168 | + | |
| 169 | +If you'd like to perform a clean reset of the extension, including removing all configuration files, indices, etc, you can remove this directory, uninstall, and then reinstall. | |
| 170 | + | |
| 165 | 171 | ## Still having trouble? |
| 166 | 172 | |
| 167 | 173 | You can also join our Discord community [here](https://discord.gg/vapESyrFmJ) for additional support and discussions. Alternatively, you can create a GitHub issue [here](https://github.com/continuedev/continue/issues/new?assignees=&labels=bug&projects=&template=bug-report-%F0%9F%90%9B.md&title=), providing details of your problem, and we'll be able to help you out more quickly. |
modified docs/docusaurus.config.js +8 −0
| @@ -203,6 +203,14 @@ | ||
| 203 | 203 | }, |
| 204 | 204 | }), |
| 205 | 205 | plugins: [ |
| 206 | + [ | |
| 207 | + "posthog-docusaurus", | |
| 208 | + { | |
| 209 | + apiKey: process.env.POSTHOG_API_KEY || "DEV", | |
| 210 | + appUrl: "https://us.i.posthog.com", | |
| 211 | + enableInDevelopment: false, | |
| 212 | + }, | |
| 213 | + ], | |
| 206 | 214 | [ |
| 207 | 215 | "@docusaurus/plugin-client-redirects", |
| 208 | 216 | { |
modified docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/cohere.md +7 −7
| @@ -4,15 +4,15 @@ | ||
| 4 | 4 | |
| 5 | 5 | ## 聊天模型 |
| 6 | 6 | |
| 7 | -我们推荐配置 **Command-R Plus** 作为你的聊天模型。 | |
| 7 | +我们推荐配置 **Command-A** 作为你的聊天模型。 | |
| 8 | 8 | |
| 9 | 9 | ```json title="config.json" |
| 10 | 10 | { |
| 11 | 11 | "models": [ |
| 12 | 12 | { |
| 13 | - "title": "Cohere", | |
| 13 | + "title": "Command A 03-2025", | |
| 14 | 14 | "provider": "cohere", |
| 15 | - "model": "command-r-plus", | |
| 15 | + "model": "command-a-03-2025", | |
| 16 | 16 | "apiKey": "YOUR_API_KEY" |
| 17 | 17 | } |
| 18 | 18 | ] |
| @@ -27,13 +27,13 @@ | ||
| 27 | 27 | |
| 28 | 28 | ## 嵌入模型 |
| 29 | 29 | |
| 30 | -我们推荐配置 **embed-english-v3.0** 作为你的嵌入模型。 | |
| 30 | +我们推荐配置 **embed-v4.0** 作为你的嵌入模型。 | |
| 31 | 31 | |
| 32 | 32 | ```json title="config.json" |
| 33 | 33 | { |
| 34 | 34 | "embeddingsProvider": { |
| 35 | 35 | "provider": "cohere", |
| 36 | - "model": "embed-english-v3.0", | |
| 36 | + "model": "embed-v4.0", | |
| 37 | 37 | "apiKey": "<COHERE_API_KEY>" |
| 38 | 38 | } |
| 39 | 39 | } |
| @@ -41,14 +41,14 @@ | ||
| 41 | 41 | |
| 42 | 42 | ## 重排序模型 |
| 43 | 43 | |
| 44 | -我们推荐配置 **rerank-english-v3.0** 作为你的重排序模型。 | |
| 44 | +我们推荐配置 **rerank-v3.5** 作为你的重排序模型。 | |
| 45 | 45 | |
| 46 | 46 | ```json title="config.json" |
| 47 | 47 | { |
| 48 | 48 | "embeddingsProvider": { |
| 49 | 49 | "provider": "cohere", |
| 50 | 50 | "params": { |
| 51 | - "model": "rerank-english-v3.0", | |
| 51 | + "model": "rerank-v3.5", | |
| 52 | 52 | "apiKey": "<COHERE_API_KEY>" |
| 53 | 53 | } |
| 54 | 54 | } |
modified docs/package-lock.json +0 −0
Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.
modified docs/package.json +1 −0
| @@ -22,6 +22,7 @@ | ||
| 22 | 22 | "@docusaurus/preset-classic": "^3.7.0", |
| 23 | 23 | "@mdx-js/react": "^3.0.0", |
| 24 | 24 | "clsx": "^2.1.0", |
| 25 | + "posthog-docusaurus": "^2.0.4", | |
| 25 | 26 | "prism-react-renderer": "^2.3.1", |
| 26 | 27 | "react": "^18.2.0", |
| 27 | 28 | "react-dom": "^18.2.0" |
added docs/static/img/mcp-playwright.png +0 −0
Binary content is not shown. View the file.
modified extensions/intellij/gradle.properties +1 −1
| @@ -3,7 +3,7 @@ | ||
| 3 | 3 | pluginName=continue-intellij-extension |
| 4 | 4 | pluginRepositoryUrl=https://github.com/continuedev/continue |
| 5 | 5 | # SemVer format -> https://semver.org |
| 6 | -pluginVersion=1.0.22 | |
| 6 | +pluginVersion=1.0.24 | |
| 7 | 7 | # Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html |
| 8 | 8 | pluginSinceBuild=223 |
| 9 | 9 | # IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension |
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt +5 −1
| @@ -169,7 +169,11 @@ | ||
| 169 | 169 | ide: IDE, |
| 170 | 170 | params: ApplyToFileParams |
| 171 | 171 | ) { |
| 172 | - val editorUtils = EditorUtils.getOrOpenEditor(project, params.filepath) | |
| 172 | + val editorUtils = if (EditorUtils.editorFileExist(params.filepath)) | |
| 173 | + EditorUtils.getOrOpenEditor(project, params.filepath) | |
| 174 | + else | |
| 175 | + EditorUtils.getEditorByCreateFile(project, params.filepath) | |
| 176 | + | |
| 173 | 177 | val diffStreamService = project.getService(DiffStreamService::class.java) |
| 174 | 178 | |
| 175 | 179 | val handler = ApplyToFileHandler( |
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/EditorUtils.kt +36 −0
| @@ -2,6 +2,7 @@ | ||
| 2 | 2 | |
| 3 | 3 | import com.github.continuedev.continueintellijextension.utils.toUriOrNull |
| 4 | 4 | import com.intellij.openapi.application.ApplicationManager |
| 5 | +import com.intellij.openapi.application.runWriteAction | |
| 5 | 6 | import com.intellij.openapi.command.WriteCommandAction |
| 6 | 7 | import com.intellij.openapi.editor.Editor |
| 7 | 8 | import com.intellij.openapi.editor.SelectionModel |
| @@ -14,6 +15,8 @@ | ||
| 14 | 15 | import com.intellij.openapi.vfs.VirtualFileManager |
| 15 | 16 | import com.intellij.ui.JBColor |
| 16 | 17 | import com.intellij.openapi.editor.ScrollType |
| 18 | +import com.intellij.openapi.vfs.LocalFileSystem | |
| 19 | +import java.io.File | |
| 17 | 20 | |
| 18 | 21 | /** |
| 19 | 22 | * Utility class for working with Editor instances. |
| @@ -166,5 +169,38 @@ | ||
| 166 | 169 | val editor = FileEditorManager.getInstance(project).selectedTextEditor ?: return null |
| 167 | 170 | return EditorUtils(editor) |
| 168 | 171 | } |
| 172 | + | |
| 173 | + /** | |
| 174 | + * Gets editor for the filepath is existed | |
| 175 | + */ | |
| 176 | + fun editorFileExist(filepath: String?): Boolean { | |
| 177 | + return !filepath.isNullOrEmpty() && VirtualFileManager.getInstance().findFileByUrl(filepath) != null | |
| 178 | + } | |
| 179 | + | |
| 180 | + /** | |
| 181 | + * Gets editor for the no exist filepath and returns an EditorUtils instance | |
| 182 | + */ | |
| 183 | + fun getEditorByCreateFile(project: Project, filepath: String?): EditorUtils? { | |
| 184 | + if (!filepath.isNullOrEmpty()) { | |
| 185 | + // file not exists and create | |
| 186 | + val ioFile = File(filepath.replace("file:///", "")) | |
| 187 | + if (!ioFile.exists()) { | |
| 188 | + ioFile.parentFile?.mkdirs() | |
| 189 | + ioFile.createNewFile() | |
| 190 | + } | |
| 191 | + // IntelliJ refresh VirtualFile | |
| 192 | + val virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(ioFile) | |
| 193 | + if (virtualFile != null) { | |
| 194 | + ApplicationManager.getApplication().invokeAndWait { | |
| 195 | + runWriteAction { | |
| 196 | + FileEditorManager.getInstance(project).openFile(virtualFile, true) | |
| 197 | + } | |
| 198 | + } | |
| 199 | + } | |
| 200 | + } | |
| 201 | + | |
| 202 | + val editor = FileEditorManager.getInstance(project).selectedTextEditor ?: return null | |
| 203 | + return EditorUtils(editor) | |
| 204 | + } | |
| 169 | 205 | } |
| 170 | 206 | } |
modified extensions/vscode/.eslintrc.json +2 −1
| @@ -6,6 +6,7 @@ | ||
| 6 | 6 | "extends": ["../../.eslintrc.shared.json"], |
| 7 | 7 | "rules": { |
| 8 | 8 | "@typescript-eslint/naming-convention": "off", |
| 9 | - "@typescript-eslint/no-floating-promises": "warn" | |
| 9 | + "@typescript-eslint/no-floating-promises": "warn", | |
| 10 | + "@typescript-eslint/no-misused-promises": "warn" | |
| 10 | 11 | } |
| 11 | 12 | } |
modified extensions/vscode/config_schema.json +15 −1
| @@ -868,7 +868,21 @@ | ||
| 868 | 868 | "then": { |
| 869 | 869 | "properties": { |
| 870 | 870 | "model": { |
| 871 | - "enum": ["command-r", "command-r-plus"] | |
| 871 | + "enum": [ | |
| 872 | + "c4ai-aya-expanse-8b", | |
| 873 | + "c4ai-aya-expanse-32b", | |
| 874 | + "c4ai-aya-vision-8b", | |
| 875 | + "c4ai-aya-vision-32b", | |
| 876 | + "command-r", | |
| 877 | + "command-r-plus", | |
| 878 | + "command-r-03-2024", | |
| 879 | + "command-r-plus-04-2024", | |
| 880 | + "command-r-08-2024", | |
| 881 | + "command-r-plus-08-2024", | |
| 882 | + "command-r7b-12-2024", | |
| 883 | + "command-r7b-arabic-02-2025", | |
| 884 | + "command-a-03-2025" | |
| 885 | + ] | |
| 872 | 886 | } |
| 873 | 887 | } |
| 874 | 888 | } |
modified extensions/vscode/package-lock.json +0 −0
Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.
modified extensions/vscode/package.json +8 −1
| @@ -2,7 +2,7 @@ | ||
| 2 | 2 | "name": "continue", |
| 3 | 3 | "icon": "media/icon.png", |
| 4 | 4 | "author": "Continue Dev, Inc", |
| 5 | - "version": "1.1.47", | |
| 5 | + "version": "1.1.49", | |
| 6 | 6 | "repository": { |
| 7 | 7 | "type": "git", |
| 8 | 8 | "url": "https://github.com/continuedev/continue" |
| @@ -624,6 +624,7 @@ | ||
| 624 | 624 | "lint:fix": "eslint . --ext ts --fix", |
| 625 | 625 | "build-test": "npm run esbuild && node esbuild.test.mjs", |
| 626 | 626 | "test": "npm run build-test && node ./out/runTestOnVSCodeHost.js", |
| 627 | + "vitest": "vitest run", | |
| 627 | 628 | "quick-test": "npm run build-test && node ./out/runTestOnVSCodeHost.js", |
| 628 | 629 | "write-build-timestamp": "node scripts/write-build-timestamp.js", |
| 629 | 630 | "prepackage": "node scripts/prepackage.js", |
| @@ -732,8 +733,14 @@ | ||
| 732 | 733 | "uuid": "^9.0.1", |
| 733 | 734 | "uuidv4": "^6.2.13", |
| 734 | 735 | "vectordb": "^0.4.20", |
| 736 | + "vitest": "^3.1.4", | |
| 735 | 737 | "vscode-languageclient": "^8.0.2", |
| 736 | 738 | "ws": "^8.13.0", |
| 737 | 739 | "yarn": "^1.22.21" |
| 740 | + }, | |
| 741 | + "overrides": { | |
| 742 | + "vitest": { | |
| 743 | + "@types/node": "^16.18.119" | |
| 744 | + } | |
| 738 | 745 | } |
| 739 | 746 | } |
modified extensions/vscode/src/stubs/WorkOsAuthProvider.ts +71 −37
| @@ -76,8 +76,10 @@ | ||
| 76 | 76 | string, |
| 77 | 77 | { promise: Promise<string>; cancel: EventEmitter<void> } |
| 78 | 78 | >(); |
| 79 | + private _refreshInterval: NodeJS.Timeout | null = null; | |
| 79 | 80 | |
| 80 | 81 | private static EXPIRATION_TIME_MS = 1000 * 60 * 15; // 15 minutes |
| 82 | + private static REFRESH_INTERVAL_MS = 1000 * 60 * 10; // 10 minutes | |
| 81 | 83 | |
| 82 | 84 | private secretStorage: SecretStorage; |
| 83 | 85 | |
| @@ -96,6 +98,14 @@ | ||
| 96 | 98 | ); |
| 97 | 99 | |
| 98 | 100 | this.secretStorage = new SecretStorage(context); |
| 101 | + | |
| 102 | + // Immediately refresh any existing sessions | |
| 103 | + this.refreshSessions(); | |
| 104 | + | |
| 105 | + // Set up a regular interval to refresh tokens | |
| 106 | + this._refreshInterval = setInterval(() => { | |
| 107 | + this.refreshSessions(); | |
| 108 | + }, WorkOsAuthProvider.REFRESH_INTERVAL_MS); | |
| 99 | 109 | } |
| 100 | 110 | |
| 101 | 111 | private decodeJwt(jwt: string): Record<string, any> | null { |
| @@ -110,16 +120,6 @@ | ||
| 110 | 120 | } |
| 111 | 121 | } |
| 112 | 122 | |
| 113 | - private getExpirationTimeMs(jwt: string): number { | |
| 114 | - const decodedToken = this.decodeJwt(jwt); | |
| 115 | - if (!decodedToken) { | |
| 116 | - return WorkOsAuthProvider.EXPIRATION_TIME_MS; | |
| 117 | - } | |
| 118 | - return decodedToken.exp && decodedToken.iat | |
| 119 | - ? (decodedToken.exp - decodedToken.iat) * 1000 | |
| 120 | - : WorkOsAuthProvider.EXPIRATION_TIME_MS; | |
| 121 | - } | |
| 122 | - | |
| 123 | 123 | private jwtIsExpiredOrInvalid(jwt: string): boolean { |
| 124 | 124 | const decodedToken = this.decodeJwt(jwt); |
| 125 | 125 | if (!decodedToken) { |
| @@ -128,13 +128,14 @@ | ||
| 128 | 128 | return decodedToken.exp * 1000 < Date.now(); |
| 129 | 129 | } |
| 130 | 130 | |
| 131 | - private async debugAccessTokenValidity(jwt: string, refreshToken: string) { | |
| 132 | - const expiredOrInvalid = this.jwtIsExpiredOrInvalid(jwt); | |
| 133 | - if (expiredOrInvalid) { | |
| 134 | - console.debug("Invalid JWT"); | |
| 135 | - } else { | |
| 136 | - console.debug("Valid JWT"); | |
| 131 | + private getExpirationTimeMs(jwt: string): number { | |
| 132 | + const decodedToken = this.decodeJwt(jwt); | |
| 133 | + if (!decodedToken) { | |
| 134 | + return WorkOsAuthProvider.EXPIRATION_TIME_MS; | |
| 137 | 135 | } |
| 136 | + return decodedToken.exp && decodedToken.iat | |
| 137 | + ? (decodedToken.exp - decodedToken.iat) * 1000 | |
| 138 | + : WorkOsAuthProvider.EXPIRATION_TIME_MS; | |
| 138 | 139 | } |
| 139 | 140 | |
| 140 | 141 | private async storeSessions(value: ContinueAuthenticationSession[]) { |
| @@ -197,7 +198,12 @@ | ||
| 197 | 198 | const finalSessions = []; |
| 198 | 199 | for (const session of sessions) { |
| 199 | 200 | try { |
| 200 | - const newSession = await this._refreshSession(session.refreshToken); | |
| 201 | + // For expired tokens, don't use retries - if refresh fails, we drop the session | |
| 202 | + const refreshMethod = this.jwtIsExpiredOrInvalid(session.accessToken) | |
| 203 | + ? this._refreshSession.bind(this) // Direct refresh for expired tokens | |
| 204 | + : this._refreshSessionWithRetry.bind(this); // Retry for valid tokens | |
| 205 | + | |
| 206 | + const newSession = await refreshMethod(session.refreshToken); | |
| 201 | 207 | finalSessions.push({ |
| 202 | 208 | ...session, |
| 203 | 209 | accessToken: newSession.accessToken, |
| @@ -205,36 +211,65 @@ | ||
| 205 | 211 | expiresInMs: newSession.expiresInMs, |
| 206 | 212 | }); |
| 207 | 213 | } catch (e: any) { |
| 208 | - // If the refresh token doesn't work, we just drop the session | |
| 214 | + // If refresh fails (after retries for valid tokens), drop the session | |
| 209 | 215 | console.debug(`Error refreshing session token: ${e.message}`); |
| 210 | - await this.debugAccessTokenValidity( | |
| 211 | - session.accessToken, | |
| 212 | - session.refreshToken, | |
| 213 | - ); | |
| 214 | 216 | this._sessionChangeEmitter.fire({ |
| 215 | 217 | added: [], |
| 216 | 218 | removed: [session], |
| 217 | 219 | changed: [], |
| 218 | 220 | }); |
| 219 | - // We don't need to refresh the sessions again, since we'll get a new one when we need it | |
| 220 | - // setTimeout(() => this._refreshSessions(), 60 * 1000); | |
| 221 | - // return; | |
| 222 | 221 | } |
| 223 | 222 | } |
| 223 | + | |
| 224 | 224 | await this.storeSessions(finalSessions); |
| 225 | 225 | this._sessionChangeEmitter.fire({ |
| 226 | 226 | added: [], |
| 227 | 227 | removed: [], |
| 228 | 228 | changed: finalSessions, |
| 229 | 229 | }); |
| 230 | + } | |
| 230 | 231 | |
| 231 | - if (finalSessions[0]?.expiresInMs) { | |
| 232 | - setTimeout( | |
| 233 | - async () => { | |
| 234 | - await this._refreshSessions(); | |
| 235 | - }, | |
| 236 | - (finalSessions[0].expiresInMs * 2) / 3, | |
| 237 | - ); | |
| 232 | + private async _refreshSessionWithRetry( | |
| 233 | + refreshToken: string, | |
| 234 | + attempt = 1, | |
| 235 | + maxAttempts = 3, | |
| 236 | + baseDelay = 1000, | |
| 237 | + ): Promise<{ | |
| 238 | + accessToken: string; | |
| 239 | + refreshToken: string; | |
| 240 | + expiresInMs: number; | |
| 241 | + }> { | |
| 242 | + try { | |
| 243 | + return await this._refreshSession(refreshToken); | |
| 244 | + } catch (error: any) { | |
| 245 | + // Don't retry for auth errors (401 Unauthorized) or if we've reached max attempts | |
| 246 | + if ( | |
| 247 | + error.message?.includes("401") || | |
| 248 | + error.message?.includes("Invalid refresh token") || | |
| 249 | + error.message?.includes("Unauthorized") || | |
| 250 | + attempt >= maxAttempts | |
| 251 | + ) { | |
| 252 | + throw error; | |
| 253 | + } | |
| 254 | + | |
| 255 | + // For network errors or transient server issues, retry with backoff | |
| 256 | + // Calculate exponential backoff delay with jitter | |
| 257 | + const delay = | |
| 258 | + baseDelay * Math.pow(2, attempt - 1) * (0.5 + Math.random() * 0.5); | |
| 259 | + | |
| 260 | + // Schedule retry after delay | |
| 261 | + return new Promise((resolve, reject) => { | |
| 262 | + setTimeout(() => { | |
| 263 | + this._refreshSessionWithRetry( | |
| 264 | + refreshToken, | |
| 265 | + attempt + 1, | |
| 266 | + maxAttempts, | |
| 267 | + baseDelay, | |
| 268 | + ) | |
| 269 | + .then(resolve) | |
| 270 | + .catch(reject); | |
| 271 | + }, delay); | |
| 272 | + }); | |
| 238 | 273 | } |
| 239 | 274 | } |
| 240 | 275 | |
| @@ -323,11 +358,6 @@ | ||
| 323 | 358 | changed: [], |
| 324 | 359 | }); |
| 325 | 360 | |
| 326 | - setTimeout( | |
| 327 | - () => this._refreshSessions(), | |
| 328 | - (this.getExpirationTimeMs(session.accessToken) * 2) / 3, | |
| 329 | - ); | |
| 330 | - | |
| 331 | 361 | return session; |
| 332 | 362 | } catch (e) { |
| 333 | 363 | window.showErrorMessage(`Sign in failed: ${e}`); |
| @@ -360,6 +390,10 @@ | ||
| 360 | 390 | * Dispose the registered services |
| 361 | 391 | */ |
| 362 | 392 | public async dispose() { |
| 393 | + if (this._refreshInterval) { | |
| 394 | + clearInterval(this._refreshInterval); | |
| 395 | + this._refreshInterval = null; | |
| 396 | + } | |
| 363 | 397 | this._disposable.dispose(); |
| 364 | 398 | } |
| 365 | 399 |
added extensions/vscode/src/stubs/WorkOsAuthProvider.vitest.ts +805 −0
| @@ -0,0 +1,805 @@ | ||
| 1 | +// @ts-nocheck | |
| 2 | +import fetch from "node-fetch"; | |
| 3 | +import { afterEach, beforeEach, expect, it, vi } from "vitest"; | |
| 4 | +import { EventEmitter } from "vscode"; | |
| 5 | + | |
| 6 | +// Don't import WorkOsAuthProvider directly here | |
| 7 | + | |
| 8 | +// Mock the modules we need | |
| 9 | +vi.mock("vscode", () => ({ | |
| 10 | + authentication: { | |
| 11 | + registerAuthenticationProvider: vi.fn(), | |
| 12 | + }, | |
| 13 | + window: { | |
| 14 | + registerUriHandler: vi.fn(), | |
| 15 | + }, | |
| 16 | + EventEmitter: vi.fn(() => ({ | |
| 17 | + event: { dispose: vi.fn() }, | |
| 18 | + fire: vi.fn(), | |
| 19 | + })), | |
| 20 | + Disposable: { | |
| 21 | + from: vi.fn(() => ({ dispose: vi.fn() })), | |
| 22 | + }, | |
| 23 | + env: { | |
| 24 | + uriScheme: "vscode", | |
| 25 | + }, | |
| 26 | +})); | |
| 27 | + | |
| 28 | +// Properly mock node-fetch | |
| 29 | +vi.mock("node-fetch", () => { | |
| 30 | + return { | |
| 31 | + __esModule: true, | |
| 32 | + default: vi.fn(), | |
| 33 | + }; | |
| 34 | +}); | |
| 35 | + | |
| 36 | +vi.mock("core/control-plane/env", () => ({ | |
| 37 | + getControlPlaneEnvSync: vi.fn(() => ({ | |
| 38 | + AUTH_TYPE: "workos", | |
| 39 | + APP_URL: "https://continue.dev", | |
| 40 | + CONTROL_PLANE_URL: "https://api.continue.dev", | |
| 41 | + WORKOS_CLIENT_ID: "client_123", | |
| 42 | + })), | |
| 43 | +})); | |
| 44 | + | |
| 45 | +vi.mock("crypto", () => ({ | |
| 46 | + createHash: vi.fn(() => ({ | |
| 47 | + update: vi.fn(() => ({ | |
| 48 | + digest: vi.fn(() => Buffer.from("test-hash")), | |
| 49 | + })), | |
| 50 | + })), | |
| 51 | +})); | |
| 52 | + | |
| 53 | +// Create a simple SecretStorage mock that we can control | |
| 54 | +const mockSecretStorageGet = vi.fn(); | |
| 55 | +const mockSecretStorageStore = vi.fn(); | |
| 56 | + | |
| 57 | +// Mock SecretStorage class | |
| 58 | +vi.mock("./SecretStorage", () => { | |
| 59 | + return { | |
| 60 | + SecretStorage: vi.fn().mockImplementation(() => ({ | |
| 61 | + store: mockSecretStorageStore, | |
| 62 | + get: mockSecretStorageGet, | |
| 63 | + })), | |
| 64 | + }; | |
| 65 | +}); | |
| 66 | + | |
| 67 | +// Helper to create valid and expired JWTs | |
| 68 | +function createJwt({ expired }: { expired: boolean }): string { | |
| 69 | + const now = Math.floor(Date.now() / 1000); | |
| 70 | + const header = { alg: "HS256", typ: "JWT" }; | |
| 71 | + const payload = { | |
| 72 | + sub: "user123", | |
| 73 | + iat: now, | |
| 74 | + exp: expired ? now - 3600 : now + 3600, // Expired 1 hour ago or valid for 1 hour | |
| 75 | + }; | |
| 76 | + | |
| 77 | + const base64Header = Buffer.from(JSON.stringify(header)) | |
| 78 | + .toString("base64") | |
| 79 | + .replace(/=/g, ""); | |
| 80 | + const base64Payload = Buffer.from(JSON.stringify(payload)) | |
| 81 | + .toString("base64") | |
| 82 | + .replace(/=/g, ""); | |
| 83 | + const signature = "dummysignature"; | |
| 84 | + | |
| 85 | + return `${base64Header}.${base64Payload}.${signature}`; | |
| 86 | +} | |
| 87 | + | |
| 88 | +beforeEach(() => { | |
| 89 | + // Set up fake timers before each test | |
| 90 | + vi.useFakeTimers(); | |
| 91 | +}); | |
| 92 | + | |
| 93 | +afterEach(() => { | |
| 94 | + vi.clearAllMocks(); | |
| 95 | + vi.clearAllTimers(); | |
| 96 | + vi.useRealTimers(); // Restore real timers after each test | |
| 97 | +}); | |
| 98 | + | |
| 99 | +it("should refresh tokens on initialization when sessions exist", async () => { | |
| 100 | + // Mock setInterval to prevent the refresh interval | |
| 101 | + const originalSetInterval = global.setInterval; | |
| 102 | + global.setInterval = vi.fn().mockReturnValue(123 as any); | |
| 103 | + | |
| 104 | + // Setup existing sessions with a valid token | |
| 105 | + const validToken = createJwt({ expired: false }); | |
| 106 | + const mockSession = { | |
| 107 | + id: "test-id", | |
| 108 | + accessToken: validToken, | |
| 109 | + refreshToken: "refresh-token", | |
| 110 | + expiresInMs: 3600000, // 1 hour | |
| 111 | + account: { label: "Test User", id: "user@example.com" }, | |
| 112 | + scopes: [], | |
| 113 | + loginNeeded: false, | |
| 114 | + }; | |
| 115 | + | |
| 116 | + // Setup fetch mock | |
| 117 | + const fetchMock = fetch as any; | |
| 118 | + fetchMock.mockClear(); | |
| 119 | + | |
| 120 | + // Setup successful token refresh | |
| 121 | + fetchMock.mockResolvedValueOnce({ | |
| 122 | + ok: true, | |
| 123 | + json: async () => ({ | |
| 124 | + accessToken: createJwt({ expired: false }), | |
| 125 | + refreshToken: "new-refresh-token", | |
| 126 | + }), | |
| 127 | + text: async () => "", | |
| 128 | + }); | |
| 129 | + | |
| 130 | + // Create a mock UriHandler | |
| 131 | + const mockUriHandler = { | |
| 132 | + event: new EventEmitter(), | |
| 133 | + handleCallback: vi.fn(), | |
| 134 | + }; | |
| 135 | + | |
| 136 | + // Create a mock ExtensionContext | |
| 137 | + const mockContext = { | |
| 138 | + secrets: { | |
| 139 | + store: vi.fn(), | |
| 140 | + get: vi.fn(), | |
| 141 | + }, | |
| 142 | + subscriptions: [], | |
| 143 | + }; | |
| 144 | + | |
| 145 | + // Set up our SecretStorage mock to return the session | |
| 146 | + mockSecretStorageGet.mockResolvedValue(JSON.stringify([mockSession])); | |
| 147 | + | |
| 148 | + // Import WorkOsAuthProvider after setting up all mocks | |
| 149 | + const { WorkOsAuthProvider } = await import("./WorkOsAuthProvider"); | |
| 150 | + | |
| 151 | + // Create provider instance - this will automatically call refreshSessions | |
| 152 | + const provider = new WorkOsAuthProvider(mockContext, mockUriHandler); | |
| 153 | + | |
| 154 | + // Wait for all promises to resolve, including any nested promise chains | |
| 155 | + await new Promise(process.nextTick); | |
| 156 | + | |
| 157 | + // Verify that the token refresh endpoint was called | |
| 158 | + expect(fetchMock).toHaveBeenCalledWith( | |
| 159 | + expect.any(URL), | |
| 160 | + expect.objectContaining({ | |
| 161 | + method: "POST", | |
| 162 | + body: expect.stringContaining("refresh-token"), | |
| 163 | + }), | |
| 164 | + ); | |
| 165 | + | |
| 166 | + // Restore setInterval | |
| 167 | + global.setInterval = originalSetInterval; | |
| 168 | + | |
| 169 | + // Clean up | |
| 170 | + if (provider._refreshInterval) { | |
| 171 | + clearInterval(provider._refreshInterval); | |
| 172 | + provider._refreshInterval = null; | |
| 173 | + } | |
| 174 | +}); | |
| 175 | + | |
| 176 | +it("should not remove sessions during transient network errors", async () => { | |
| 177 | + // Setup existing sessions with a valid token | |
| 178 | + const validToken = createJwt({ expired: false }); | |
| 179 | + const mockSession = { | |
| 180 | + id: "test-id", | |
| 181 | + accessToken: validToken, | |
| 182 | + refreshToken: "refresh-token", | |
| 183 | + expiresInMs: 300000, // 5 minutes | |
| 184 | + account: { label: "Test User", id: "user@example.com" }, | |
| 185 | + scopes: [], | |
| 186 | + loginNeeded: false, | |
| 187 | + }; | |
| 188 | + | |
| 189 | + // Setup fetch mock | |
| 190 | + const fetchMock = fetch as any; | |
| 191 | + fetchMock.mockClear(); | |
| 192 | + | |
| 193 | + // First refresh attempt fails with network error | |
| 194 | + fetchMock.mockRejectedValueOnce(new Error("Network error")); | |
| 195 | + | |
| 196 | + // Second refresh attempt should succeed | |
| 197 | + fetchMock.mockResolvedValueOnce({ | |
| 198 | + ok: true, | |
| 199 | + json: async () => ({ | |
| 200 | + accessToken: createJwt({ expired: false }), | |
| 201 | + refreshToken: "new-refresh-token", | |
| 202 | + }), | |
| 203 | + text: async () => "", | |
| 204 | + }); | |
| 205 | + | |
| 206 | + // Create a mock UriHandler | |
| 207 | + const mockUriHandler = { | |
| 208 | + event: new EventEmitter(), | |
| 209 | + handleCallback: vi.fn(), | |
| 210 | + }; | |
| 211 | + | |
| 212 | + // Create a mock ExtensionContext | |
| 213 | + const mockContext = { | |
| 214 | + secrets: { | |
| 215 | + store: vi.fn(), | |
| 216 | + get: vi.fn(), | |
| 217 | + }, | |
| 218 | + subscriptions: [], | |
| 219 | + }; | |
| 220 | + | |
| 221 | + // Set up our SecretStorage mock to return the session | |
| 222 | + mockSecretStorageGet.mockResolvedValue(JSON.stringify([mockSession])); | |
| 223 | + | |
| 224 | + // Import WorkOsAuthProvider after setting up all mocks | |
| 225 | + const { WorkOsAuthProvider } = await import("./WorkOsAuthProvider"); | |
| 226 | + | |
| 227 | + // Allow setInterval to work normally with fake timers | |
| 228 | + // We're not mocking it anymore, instead we'll control when it fires | |
| 229 | + | |
| 230 | + // Create provider instance - this will automatically call refreshSessions with the network error | |
| 231 | + const provider = new WorkOsAuthProvider(mockContext, mockUriHandler); | |
| 232 | + | |
| 233 | + // Run microtasks to process promises from the initial refresh call | |
| 234 | + await Promise.resolve(); | |
| 235 | + | |
| 236 | + // Check that sessions were not cleared after network error | |
| 237 | + expect(mockSecretStorageStore).not.toHaveBeenCalledWith( | |
| 238 | + expect.anything(), | |
| 239 | + expect.stringMatching(/\[\]/), | |
| 240 | + ); | |
| 241 | + | |
| 242 | + // Reset the fetch mock call count to verify the next call | |
| 243 | + fetchMock.mockClear(); | |
| 244 | + | |
| 245 | + // Advance timers to the next refresh interval to simulate the timer firing | |
| 246 | + vi.advanceTimersByTime(WorkOsAuthProvider.REFRESH_INTERVAL_MS); | |
| 247 | + | |
| 248 | + // Run microtasks to process promises from the interval-triggered refresh | |
| 249 | + await Promise.resolve(); | |
| 250 | + | |
| 251 | + // Verify the second attempt was made via the interval | |
| 252 | + expect(fetchMock).toHaveBeenCalledTimes(1); | |
| 253 | + expect(fetchMock).toHaveBeenCalledWith( | |
| 254 | + expect.any(URL), | |
| 255 | + expect.objectContaining({ | |
| 256 | + method: "POST", | |
| 257 | + headers: expect.objectContaining({ | |
| 258 | + "Content-Type": "application/json", | |
| 259 | + }), | |
| 260 | + body: expect.stringContaining("refresh-token"), | |
| 261 | + }), | |
| 262 | + ); | |
| 263 | + | |
| 264 | + // Clean up | |
| 265 | + if (provider._refreshInterval) { | |
| 266 | + clearInterval(provider._refreshInterval); | |
| 267 | + provider._refreshInterval = null; | |
| 268 | + } | |
| 269 | +}); | |
| 270 | + | |
| 271 | +it("should refresh tokens at regular intervals rather than based on expiration", async () => { | |
| 272 | + // Setup existing sessions with a valid token | |
| 273 | + const validToken = createJwt({ expired: false }); | |
| 274 | + const mockSession = { | |
| 275 | + id: "test-id", | |
| 276 | + accessToken: validToken, | |
| 277 | + refreshToken: "refresh-token", | |
| 278 | + expiresInMs: 3600000, // 1 hour | |
| 279 | + account: { label: "Test User", id: "user@example.com" }, | |
| 280 | + scopes: [], | |
| 281 | + loginNeeded: false, | |
| 282 | + }; | |
| 283 | + | |
| 284 | + // Setup fetch mock | |
| 285 | + const fetchMock = fetch as any; | |
| 286 | + fetchMock.mockClear(); | |
| 287 | + | |
| 288 | + // Setup successful token refresh responses for multiple calls | |
| 289 | + fetchMock.mockResolvedValue({ | |
| 290 | + ok: true, | |
| 291 | + json: async () => ({ | |
| 292 | + accessToken: createJwt({ expired: false }), | |
| 293 | + refreshToken: "new-refresh-token", | |
| 294 | + }), | |
| 295 | + text: async () => "", | |
| 296 | + }); | |
| 297 | + | |
| 298 | + // Create a mock UriHandler | |
| 299 | + const mockUriHandler = { | |
| 300 | + event: new EventEmitter(), | |
| 301 | + handleCallback: vi.fn(), | |
| 302 | + }; | |
| 303 | + | |
| 304 | + // Create a mock ExtensionContext | |
| 305 | + const mockContext = { | |
| 306 | + secrets: { | |
| 307 | + store: vi.fn(), | |
| 308 | + get: vi.fn(), | |
| 309 | + }, | |
| 310 | + subscriptions: [], | |
| 311 | + }; | |
| 312 | + | |
| 313 | + // Set up our SecretStorage mock to return the session | |
| 314 | + mockSecretStorageGet.mockResolvedValue(JSON.stringify([mockSession])); | |
| 315 | + | |
| 316 | + // Import WorkOsAuthProvider after setting up all mocks | |
| 317 | + const { WorkOsAuthProvider } = await import("./WorkOsAuthProvider"); | |
| 318 | + | |
| 319 | + // Capture the original setInterval to restore it later | |
| 320 | + const originalSetInterval = global.setInterval; | |
| 321 | + | |
| 322 | + // Create our own implementation of setInterval that we can control better | |
| 323 | + let intervalCallback: Function; | |
| 324 | + global.setInterval = vi.fn((callback, ms) => { | |
| 325 | + intervalCallback = callback; | |
| 326 | + return 123 as any; // Return a dummy interval ID | |
| 327 | + }); | |
| 328 | + | |
| 329 | + // Create provider instance - this will automatically call refreshSessions | |
| 330 | + const provider = new WorkOsAuthProvider(mockContext, mockUriHandler); | |
| 331 | + | |
| 332 | + // Wait for all promises to resolve, including any nested promise chains | |
| 333 | + await new Promise(process.nextTick); | |
| 334 | + | |
| 335 | + // First refresh should happen immediately on initialization | |
| 336 | + expect(fetchMock).toHaveBeenCalledTimes(1); | |
| 337 | + fetchMock.mockClear(); | |
| 338 | + | |
| 339 | + // Verify that setInterval was called to set up regular refreshes | |
| 340 | + expect(global.setInterval).toHaveBeenCalled(); | |
| 341 | + | |
| 342 | + // Get the interval time from the call to setInterval | |
| 343 | + const intervalTime = (global.setInterval as any).mock.calls[0][1]; | |
| 344 | + | |
| 345 | + // Should be a reasonable interval (less than the expiration time) | |
| 346 | + expect(intervalTime).toBeLessThan(mockSession.expiresInMs); | |
| 347 | + | |
| 348 | + // Now manually trigger the interval callback - First interval | |
| 349 | + intervalCallback(); | |
| 350 | + | |
| 351 | + // Wait for all promises to resolve | |
| 352 | + await new Promise(process.nextTick); | |
| 353 | + | |
| 354 | + // Verify that refresh was called again when the interval callback fired | |
| 355 | + expect(fetchMock).toHaveBeenCalledTimes(1); | |
| 356 | + | |
| 357 | + // Check that we're making refresh calls to the right endpoint with the right data | |
| 358 | + expect(fetchMock).toHaveBeenCalledWith( | |
| 359 | + expect.objectContaining({ pathname: "/auth/refresh" }), | |
| 360 | + expect.objectContaining({ | |
| 361 | + method: "POST", | |
| 362 | + headers: expect.objectContaining({ | |
| 363 | + "Content-Type": "application/json", | |
| 364 | + }), | |
| 365 | + body: expect.stringContaining("refresh-token"), | |
| 366 | + }), | |
| 367 | + ); | |
| 368 | + | |
| 369 | + // Clear mock calls for the second interval test | |
| 370 | + fetchMock.mockClear(); | |
| 371 | + | |
| 372 | + // Trigger the callback again - Second interval | |
| 373 | + intervalCallback(); | |
| 374 | + | |
| 375 | + // Wait for all promises to resolve | |
| 376 | + await new Promise(process.nextTick); | |
| 377 | + | |
| 378 | + // Verify the refresh was called a second time | |
| 379 | + expect(fetchMock).toHaveBeenCalledTimes(1); | |
| 380 | + | |
| 381 | + // Verify the second call has the same correct parameters | |
| 382 | + expect(fetchMock).toHaveBeenCalledWith( | |
| 383 | + expect.objectContaining({ pathname: "/auth/refresh" }), | |
| 384 | + expect.objectContaining({ | |
| 385 | + method: "POST", | |
| 386 | + headers: expect.objectContaining({ | |
| 387 | + "Content-Type": "application/json", | |
| 388 | + }), | |
| 389 | + body: expect.stringContaining("refresh-token"), | |
| 390 | + }), | |
| 391 | + ); | |
| 392 | + | |
| 393 | + // Restore the original setInterval | |
| 394 | + global.setInterval = originalSetInterval; | |
| 395 | + | |
| 396 | + // Clean up | |
| 397 | + if (provider._refreshInterval) { | |
| 398 | + clearInterval(provider._refreshInterval); | |
| 399 | + provider._refreshInterval = null; | |
| 400 | + } | |
| 401 | +}); | |
| 402 | + | |
| 403 | +it("should remove session if token refresh fails with authentication error", async () => { | |
| 404 | + // Setup existing sessions with a valid token | |
| 405 | + const validToken = createJwt({ expired: false }); | |
| 406 | + const mockSession = { | |
| 407 | + id: "test-id", | |
| 408 | + accessToken: validToken, | |
| 409 | + refreshToken: "invalid-refresh-token", | |
| 410 | + expiresInMs: 300000, // 5 minutes | |
| 411 | + account: { label: "Test User", id: "user@example.com" }, | |
| 412 | + scopes: [], | |
| 413 | + loginNeeded: false, | |
| 414 | + }; | |
| 415 | + | |
| 416 | + // Setup fetch mock | |
| 417 | + const fetchMock = fetch as any; | |
| 418 | + fetchMock.mockClear(); | |
| 419 | + | |
| 420 | + // Setup refresh to fail with 401 unauthorized | |
| 421 | + fetchMock.mockResolvedValueOnce({ | |
| 422 | + ok: false, | |
| 423 | + status: 401, | |
| 424 | + text: async () => "Invalid refresh token", | |
| 425 | + }); | |
| 426 | + | |
| 427 | + // Create a mock UriHandler | |
| 428 | + const mockUriHandler = { | |
| 429 | + event: new EventEmitter(), | |
| 430 | + handleCallback: vi.fn(), | |
| 431 | + }; | |
| 432 | + | |
| 433 | + // Create a mock ExtensionContext | |
| 434 | + const mockContext = { | |
| 435 | + secrets: { | |
| 436 | + store: vi.fn(), | |
| 437 | + get: vi.fn(), | |
| 438 | + }, | |
| 439 | + subscriptions: [], | |
| 440 | + }; | |
| 441 | + | |
| 442 | + // Mock setInterval to prevent continuous refreshes | |
| 443 | + const originalSetInterval = global.setInterval; | |
| 444 | + global.setInterval = vi.fn().mockReturnValue(123 as any); | |
| 445 | + | |
| 446 | + // Set up our SecretStorage mock to return the session | |
| 447 | + mockSecretStorageGet.mockResolvedValue(JSON.stringify([mockSession])); | |
| 448 | + mockSecretStorageStore.mockClear(); | |
| 449 | + | |
| 450 | + // Import WorkOsAuthProvider after setting up all mocks | |
| 451 | + const { WorkOsAuthProvider } = await import("./WorkOsAuthProvider"); | |
| 452 | + | |
| 453 | + // Create provider instance - this will automatically call refreshSessions | |
| 454 | + const provider = new WorkOsAuthProvider(mockContext, mockUriHandler); | |
| 455 | + | |
| 456 | + // Wait for all promises to resolve, including any nested promise chains | |
| 457 | + await new Promise(process.nextTick); | |
| 458 | + | |
| 459 | + // Verify that the token refresh endpoint was called | |
| 460 | + expect(fetchMock).toHaveBeenCalledWith( | |
| 461 | + expect.any(URL), | |
| 462 | + expect.objectContaining({ | |
| 463 | + method: "POST", | |
| 464 | + body: expect.stringContaining("invalid-refresh-token"), | |
| 465 | + }), | |
| 466 | + ); | |
| 467 | + | |
| 468 | + // Verify sessions were removed due to auth error | |
| 469 | + expect(mockSecretStorageStore).toHaveBeenCalledWith( | |
| 470 | + "workos.sessions", // Use the hard-coded key that matches our mock | |
| 471 | + expect.stringMatching(/\[\]/), | |
| 472 | + ); | |
| 473 | + | |
| 474 | + // Restore setInterval | |
| 475 | + global.setInterval = originalSetInterval; | |
| 476 | + | |
| 477 | + // Clean up | |
| 478 | + if (provider._refreshInterval) { | |
| 479 | + clearInterval(provider._refreshInterval); | |
| 480 | + provider._refreshInterval = null; | |
| 481 | + } | |
| 482 | +}); | |
| 483 | + | |
| 484 | +it("should remove session if token refresh returns Unauthorized error message", async () => { | |
| 485 | + // Setup existing sessions with a valid token | |
| 486 | + const validToken = createJwt({ expired: false }); | |
| 487 | + const mockSession = { | |
| 488 | + id: "test-id", | |
| 489 | + accessToken: validToken, | |
| 490 | + refreshToken: "invalid-refresh-token", | |
| 491 | + expiresInMs: 300000, // 5 minutes | |
| 492 | + account: { label: "Test User", id: "user@example.com" }, | |
| 493 | + scopes: [], | |
| 494 | + loginNeeded: false, | |
| 495 | + }; | |
| 496 | + | |
| 497 | + // Setup fetch mock | |
| 498 | + const fetchMock = fetch as any; | |
| 499 | + fetchMock.mockClear(); | |
| 500 | + | |
| 501 | + // Setup refresh to return an error containing "Unauthorized" in the message | |
| 502 | + // Status code doesn't matter here, what matters is the error message text | |
| 503 | + fetchMock.mockResolvedValueOnce({ | |
| 504 | + ok: false, | |
| 505 | + status: 403, // Could be any error code | |
| 506 | + text: async () => "Unauthorized", | |
| 507 | + }); | |
| 508 | + | |
| 509 | + // Create a mock UriHandler | |
| 510 | + const mockUriHandler = { | |
| 511 | + event: new EventEmitter(), | |
| 512 | + handleCallback: vi.fn(), | |
| 513 | + }; | |
| 514 | + | |
| 515 | + // Create a mock ExtensionContext | |
| 516 | + const mockContext = { | |
| 517 | + secrets: { | |
| 518 | + store: vi.fn(), | |
| 519 | + get: vi.fn(), | |
| 520 | + }, | |
| 521 | + subscriptions: [], | |
| 522 | + }; | |
| 523 | + | |
| 524 | + // Mock setInterval to prevent continuous refreshes | |
| 525 | + const originalSetInterval = global.setInterval; | |
| 526 | + global.setInterval = vi.fn().mockReturnValue(123 as any); | |
| 527 | + | |
| 528 | + // Set up our SecretStorage mock to return the session | |
| 529 | + mockSecretStorageGet.mockResolvedValue(JSON.stringify([mockSession])); | |
| 530 | + mockSecretStorageStore.mockClear(); | |
| 531 | + | |
| 532 | + // Import WorkOsAuthProvider after setting up all mocks | |
| 533 | + const { WorkOsAuthProvider } = await import("./WorkOsAuthProvider"); | |
| 534 | + | |
| 535 | + // Create provider instance - this will automatically call refreshSessions | |
| 536 | + const provider = new WorkOsAuthProvider(mockContext, mockUriHandler); | |
| 537 | + | |
| 538 | + // Wait for all promises to resolve, including any nested promise chains | |
| 539 | + await new Promise(process.nextTick); | |
| 540 | + | |
| 541 | + // Verify that the token refresh endpoint was called | |
| 542 | + expect(fetchMock).toHaveBeenCalledWith( | |
| 543 | + expect.any(URL), | |
| 544 | + expect.objectContaining({ | |
| 545 | + method: "POST", | |
| 546 | + body: expect.stringContaining("invalid-refresh-token"), | |
| 547 | + }), | |
| 548 | + ); | |
| 549 | + | |
| 550 | + // Verify sessions were removed due to Unauthorized error message | |
| 551 | + expect(mockSecretStorageStore).toHaveBeenCalledWith( | |
| 552 | + "workos.sessions", // Use the hard-coded key that matches our mock | |
| 553 | + expect.stringMatching(/\[\]/), | |
| 554 | + ); | |
| 555 | + | |
| 556 | + // Restore setInterval | |
| 557 | + global.setInterval = originalSetInterval; | |
| 558 | + | |
| 559 | + // Clean up | |
| 560 | + if (provider._refreshInterval) { | |
| 561 | + clearInterval(provider._refreshInterval); | |
| 562 | + provider._refreshInterval = null; | |
| 563 | + } | |
| 564 | +}); | |
| 565 | + | |
| 566 | +it("should preserve valid tokens during network errors by retrying", async () => { | |
| 567 | + // Mock Date.now to return a fixed timestamp for token validation | |
| 568 | + const originalDateNow = Date.now; | |
| 569 | + const currentTimestamp = Date.now(); | |
| 570 | + Date.now = vi.fn(() => currentTimestamp); | |
| 571 | + | |
| 572 | + // Setup with a valid token | |
| 573 | + const validToken = createJwt({ expired: false }); | |
| 574 | + const validSession = { | |
| 575 | + id: "valid-id", | |
| 576 | + accessToken: validToken, | |
| 577 | + refreshToken: "valid-refresh-token", | |
| 578 | + expiresInMs: 3600000, | |
| 579 | + account: { label: "Valid User", id: "valid@example.com" }, | |
| 580 | + scopes: [], | |
| 581 | + loginNeeded: false, | |
| 582 | + }; | |
| 583 | + | |
| 584 | + // Setup fetch mock | |
| 585 | + const fetchMock = fetch as any; | |
| 586 | + fetchMock.mockClear(); | |
| 587 | + | |
| 588 | + // Create mock objects | |
| 589 | + const mockUriHandler = { event: new EventEmitter(), handleCallback: vi.fn() }; | |
| 590 | + const mockContext = { | |
| 591 | + secrets: { store: vi.fn(), get: vi.fn() }, | |
| 592 | + subscriptions: [], | |
| 593 | + }; | |
| 594 | + | |
| 595 | + // Mock setInterval and setTimeout | |
| 596 | + const originalSetInterval = global.setInterval; | |
| 597 | + global.setInterval = vi.fn().mockReturnValue(123 as any); | |
| 598 | + | |
| 599 | + const originalSetTimeout = global.setTimeout; | |
| 600 | + global.setTimeout = vi.fn((callback) => { | |
| 601 | + callback(); | |
| 602 | + return 123 as any; | |
| 603 | + }); | |
| 604 | + | |
| 605 | + // Network error followed by success | |
| 606 | + fetchMock.mockRejectedValueOnce(new Error("Network error")); | |
| 607 | + fetchMock.mockResolvedValueOnce({ | |
| 608 | + ok: true, | |
| 609 | + json: async () => ({ | |
| 610 | + accessToken: createJwt({ expired: false }), | |
| 611 | + refreshToken: "new-refresh-token", | |
| 612 | + }), | |
| 613 | + text: async () => "", | |
| 614 | + }); | |
| 615 | + | |
| 616 | + // Setup storage | |
| 617 | + mockSecretStorageGet.mockResolvedValue(JSON.stringify([validSession])); | |
| 618 | + mockSecretStorageStore.mockClear(); | |
| 619 | + | |
| 620 | + // Import and create provider | |
| 621 | + const { WorkOsAuthProvider } = await import("./WorkOsAuthProvider"); | |
| 622 | + const provider = new WorkOsAuthProvider(mockContext, mockUriHandler); | |
| 623 | + | |
| 624 | + // Wait for promises to resolve | |
| 625 | + await new Promise(process.nextTick); | |
| 626 | + | |
| 627 | + // Check that a non-empty session array was stored (session was preserved) | |
| 628 | + const storeCall = mockSecretStorageStore.mock.calls[0]; | |
| 629 | + expect(storeCall[0]).toBe("workos.sessions"); | |
| 630 | + expect(JSON.parse(storeCall[1])).toHaveLength(1); // Should contain one session | |
| 631 | + | |
| 632 | + // Restore originals | |
| 633 | + global.setTimeout = originalSetTimeout; | |
| 634 | + global.setInterval = originalSetInterval; | |
| 635 | + Date.now = originalDateNow; | |
| 636 | + | |
| 637 | + // Clean up provider | |
| 638 | + if (provider._refreshInterval) { | |
| 639 | + clearInterval(provider._refreshInterval); | |
| 640 | + provider._refreshInterval = null; | |
| 641 | + } | |
| 642 | +}); | |
| 643 | + | |
| 644 | +it("should remove expired tokens when refresh fails", async () => { | |
| 645 | + // Mock Date.now to return a time that makes tokens appear expired | |
| 646 | + const originalDateNow = Date.now; | |
| 647 | + const futureTime = Date.now() + 7200000; // 2 hours in the future | |
| 648 | + Date.now = vi.fn(() => futureTime); | |
| 649 | + | |
| 650 | + // Setup with an expired token | |
| 651 | + const expiredToken = createJwt({ expired: true }); | |
| 652 | + const expiredSession = { | |
| 653 | + id: "expired-id", | |
| 654 | + accessToken: expiredToken, | |
| 655 | + refreshToken: "expired-refresh-token", | |
| 656 | + expiresInMs: 3600000, | |
| 657 | + account: { label: "Expired User", id: "expired@example.com" }, | |
| 658 | + scopes: [], | |
| 659 | + loginNeeded: false, | |
| 660 | + }; | |
| 661 | + | |
| 662 | + // Setup fetch mock | |
| 663 | + const fetchMock = fetch as any; | |
| 664 | + fetchMock.mockClear(); | |
| 665 | + | |
| 666 | + // Create mock objects | |
| 667 | + const mockUriHandler = { event: new EventEmitter(), handleCallback: vi.fn() }; | |
| 668 | + const mockContext = { | |
| 669 | + secrets: { store: vi.fn(), get: vi.fn() }, | |
| 670 | + subscriptions: [], | |
| 671 | + }; | |
| 672 | + | |
| 673 | + // Mock setInterval | |
| 674 | + const originalSetInterval = global.setInterval; | |
| 675 | + global.setInterval = vi.fn().mockReturnValue(123 as any); | |
| 676 | + | |
| 677 | + // Refresh will fail with network error | |
| 678 | + fetchMock.mockRejectedValueOnce(new Error("Network error")); | |
| 679 | + | |
| 680 | + // Setup storage | |
| 681 | + mockSecretStorageGet.mockResolvedValue(JSON.stringify([expiredSession])); | |
| 682 | + mockSecretStorageStore.mockClear(); | |
| 683 | + | |
| 684 | + // Import and create provider | |
| 685 | + const { WorkOsAuthProvider } = await import("./WorkOsAuthProvider"); | |
| 686 | + const provider = new WorkOsAuthProvider(mockContext, mockUriHandler); | |
| 687 | + | |
| 688 | + // Wait for promises to resolve | |
| 689 | + await new Promise(process.nextTick); | |
| 690 | + | |
| 691 | + // Check that an empty session array was stored (session was removed) | |
| 692 | + const storeCall = mockSecretStorageStore.mock.calls[0]; | |
| 693 | + expect(storeCall[0]).toBe("workos.sessions"); | |
| 694 | + expect(JSON.parse(storeCall[1])).toHaveLength(0); // Should be empty | |
| 695 | + | |
| 696 | + // Restore originals | |
| 697 | + global.setInterval = originalSetInterval; | |
| 698 | + Date.now = originalDateNow; | |
| 699 | + | |
| 700 | + // Clean up provider | |
| 701 | + if (provider._refreshInterval) { | |
| 702 | + clearInterval(provider._refreshInterval); | |
| 703 | + provider._refreshInterval = null; | |
| 704 | + } | |
| 705 | +}); | |
| 706 | + | |
| 707 | +it("should implement exponential backoff for failed refresh attempts", async () => { | |
| 708 | + // Setup existing sessions with a valid token | |
| 709 | + const validToken = createJwt({ expired: false }); | |
| 710 | + const mockSession = { | |
| 711 | + id: "test-id", | |
| 712 | + accessToken: validToken, | |
| 713 | + refreshToken: "refresh-token", | |
| 714 | + expiresInMs: 300000, // 5 minutes | |
| 715 | + account: { label: "Test User", id: "user@example.com" }, | |
| 716 | + scopes: [], | |
| 717 | + loginNeeded: false, | |
| 718 | + }; | |
| 719 | + | |
| 720 | + // Setup fetch mock | |
| 721 | + const fetchMock = fetch as any; | |
| 722 | + fetchMock.mockClear(); | |
| 723 | + | |
| 724 | + // Setup repeated network errors followed by success | |
| 725 | + fetchMock.mockRejectedValueOnce(new Error("Network error 1")); | |
| 726 | + fetchMock.mockRejectedValueOnce(new Error("Network error 2")); | |
| 727 | + fetchMock.mockResolvedValueOnce({ | |
| 728 | + ok: true, | |
| 729 | + json: async () => ({ | |
| 730 | + accessToken: createJwt({ expired: false }), | |
| 731 | + refreshToken: "new-refresh-token", | |
| 732 | + }), | |
| 733 | + text: async () => "", | |
| 734 | + }); | |
| 735 | + | |
| 736 | + // Create a mock UriHandler | |
| 737 | + const mockUriHandler = { | |
| 738 | + event: new EventEmitter(), | |
| 739 | + handleCallback: vi.fn(), | |
| 740 | + }; | |
| 741 | + | |
| 742 | + // Create a mock ExtensionContext | |
| 743 | + const mockContext = { | |
| 744 | + secrets: { | |
| 745 | + store: vi.fn(), | |
| 746 | + get: vi.fn(), | |
| 747 | + }, | |
| 748 | + subscriptions: [], | |
| 749 | + }; | |
| 750 | + | |
| 751 | + // Mock setInterval to prevent continuous refreshes | |
| 752 | + const originalSetInterval = global.setInterval; | |
| 753 | + global.setInterval = vi.fn().mockReturnValue(123 as any); | |
| 754 | + | |
| 755 | + // Track setTimeout calls | |
| 756 | + const setTimeoutSpy = vi.spyOn(global, "setTimeout"); | |
| 757 | + | |
| 758 | + // Set up our SecretStorage mock to return the session | |
| 759 | + mockSecretStorageGet.mockResolvedValue(JSON.stringify([mockSession])); | |
| 760 | + | |
| 761 | + // Import WorkOsAuthProvider after setting up all mocks | |
| 762 | + const { WorkOsAuthProvider } = await import("./WorkOsAuthProvider"); | |
| 763 | + | |
| 764 | + // Create provider instance - this will automatically call refreshSessions | |
| 765 | + const provider = new WorkOsAuthProvider(mockContext, mockUriHandler); | |
| 766 | + | |
| 767 | + // Wait for all promises to resolve for the initial refresh attempt | |
| 768 | + await new Promise(process.nextTick); | |
| 769 | + | |
| 770 | + // Verify the first fetch attempt was made | |
| 771 | + expect(fetchMock).toHaveBeenCalledTimes(1); | |
| 772 | + | |
| 773 | + // Trigger first retry | |
| 774 | + vi.advanceTimersByTime(1000); // Initial backoff | |
| 775 | + await new Promise(process.nextTick); | |
| 776 | + | |
| 777 | + // Verify the second fetch attempt was made | |
| 778 | + expect(fetchMock).toHaveBeenCalledTimes(2); | |
| 779 | + | |
| 780 | + // Trigger second retry | |
| 781 | + vi.advanceTimersByTime(2000); // Double the backoff | |
| 782 | + await new Promise(process.nextTick); | |
| 783 | + | |
| 784 | + // Verify the third fetch attempt was made | |
| 785 | + expect(fetchMock).toHaveBeenCalledTimes(3); | |
| 786 | + | |
| 787 | + // Verify setTimeout was called with increasing delays | |
| 788 | + expect(setTimeoutSpy).toHaveBeenCalledTimes(2); | |
| 789 | + | |
| 790 | + // Check that the backoff periods increased | |
| 791 | + const firstDelay = setTimeoutSpy.mock.calls[0][1]; | |
| 792 | + const secondDelay = setTimeoutSpy.mock.calls[1][1]; | |
| 793 | + | |
| 794 | + // Check that backoff increased | |
| 795 | + expect(secondDelay).toBeGreaterThan(firstDelay); | |
| 796 | + | |
| 797 | + // Restore setInterval | |
| 798 | + global.setInterval = originalSetInterval; | |
| 799 | + | |
| 800 | + // Clean up | |
| 801 | + if (provider._refreshInterval) { | |
| 802 | + clearInterval(provider._refreshInterval); | |
| 803 | + provider._refreshInterval = null; | |
| 804 | + } | |
| 805 | +}); |
added extensions/vscode/vitest.config.ts +8 −0
| @@ -0,0 +1,8 @@ | ||
| 1 | +import { defineConfig } from "vitest/config"; | |
| 2 | + | |
| 3 | +export default defineConfig({ | |
| 4 | + test: { | |
| 5 | + include: ["**/*.vitest.ts"], | |
| 6 | + environment: "node", | |
| 7 | + }, | |
| 8 | +}); |
modified gui/package-lock.json +0 −0
Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.
modified gui/package.json +2 −0
| @@ -34,10 +34,12 @@ | ||
| 34 | 34 | "@tiptap/starter-kit": "^2.1.13", |
| 35 | 35 | "@tiptap/suggestion": "^2.1.13", |
| 36 | 36 | "@types/uuid": "^10.0.0", |
| 37 | + "anser": "^2.3.2", | |
| 37 | 38 | "clsx": "^2.1.1", |
| 38 | 39 | "core": "file:../core", |
| 39 | 40 | "dompurify": "^3.0.6", |
| 40 | 41 | "downshift": "^7.6.0", |
| 42 | + "escape-carriage": "^1.3.1", | |
| 41 | 43 | "lodash": "^4.17.21", |
| 42 | 44 | "lowlight": "^3.3.0", |
| 43 | 45 | "minisearch": "^7.0.2", |
added gui/src/components/ansiTerminal/Ansi.tsx +279 −0
| @@ -0,0 +1,279 @@ | ||
| 1 | +import Anser, { AnserJsonEntry } from "anser"; | |
| 2 | +import { escapeCarriageReturn } from "escape-carriage"; | |
| 3 | +import * as React from "react"; | |
| 4 | +import styled from "styled-components"; | |
| 5 | +import { | |
| 6 | + defaultBorderRadius, | |
| 7 | + vscBackground, | |
| 8 | + vscEditorBackground, | |
| 9 | + vscForeground, | |
| 10 | +} from "../../components"; | |
| 11 | +import { getFontSize } from "../../util"; | |
| 12 | + | |
| 13 | +const AnsiSpan = styled.span<{ | |
| 14 | + bg?: string; | |
| 15 | + fg?: string; | |
| 16 | + decoration?: string; | |
| 17 | +}>` | |
| 18 | + ${({ bg }) => bg && `background-color: rgb(${bg});`} | |
| 19 | + ${({ fg }) => fg && `color: rgb(${fg});`} | |
| 20 | + ${({ decoration }) => { | |
| 21 | + switch (decoration) { | |
| 22 | + case "bold": | |
| 23 | + return "font-weight: bold;"; | |
| 24 | + case "dim": | |
| 25 | + return "opacity: 0.5;"; | |
| 26 | + case "italic": | |
| 27 | + return "font-style: italic;"; | |
| 28 | + case "hidden": | |
| 29 | + return "visibility: hidden;"; | |
| 30 | + case "strikethrough": | |
| 31 | + return "text-decoration: line-through;"; | |
| 32 | + case "underline": | |
| 33 | + return "text-decoration: underline;"; | |
| 34 | + case "blink": | |
| 35 | + return "text-decoration: blink;"; | |
| 36 | + default: | |
| 37 | + return ""; | |
| 38 | + } | |
| 39 | + }} | |
| 40 | +`; | |
| 41 | + | |
| 42 | +const AnsiLink = styled.a` | |
| 43 | + color: var(--vscode-textLink-foreground, #3794ff); | |
| 44 | + text-decoration: none; | |
| 45 | + &:hover { | |
| 46 | + text-decoration: underline; | |
| 47 | + } | |
| 48 | +`; | |
| 49 | + | |
| 50 | +// Using the same styled component structure as StyledMarkdown | |
| 51 | +const StyledAnsi = styled.div<{ | |
| 52 | + fontSize?: number; | |
| 53 | + whiteSpace: string; | |
| 54 | + bgColor: string; | |
| 55 | +}>` | |
| 56 | + pre { | |
| 57 | + white-space: ${(props) => props.whiteSpace}; | |
| 58 | + background-color: ${vscEditorBackground}; | |
| 59 | + border-radius: ${defaultBorderRadius}; | |
| 60 | + border: 1px solid | |
| 61 | + var(--vscode-editorWidget-border, rgba(127, 127, 127, 0.3)); | |
| 62 | + max-width: calc(100vw - 24px); | |
| 63 | + overflow-x: scroll; | |
| 64 | + overflow-y: hidden; | |
| 65 | + padding: 8px; | |
| 66 | + } | |
| 67 | + | |
| 68 | + code { | |
| 69 | + span.line:empty { | |
| 70 | + display: none; | |
| 71 | + } | |
| 72 | + word-wrap: break-word; | |
| 73 | + border-radius: ${defaultBorderRadius}; | |
| 74 | + background-color: ${vscEditorBackground}; | |
| 75 | + font-size: ${getFontSize() - 2}px; | |
| 76 | + font-family: var(--vscode-editor-font-family); | |
| 77 | + } | |
| 78 | + | |
| 79 | + code:not(pre > code) { | |
| 80 | + font-family: var(--vscode-editor-font-family); | |
| 81 | + color: var(--vscode-input-placeholderForeground); | |
| 82 | + } | |
| 83 | + | |
| 84 | + background-color: ${(props) => props.bgColor}; | |
| 85 | + font-family: | |
| 86 | + var(--vscode-font-family), | |
| 87 | + system-ui, | |
| 88 | + -apple-system, | |
| 89 | + BlinkMacSystemFont, | |
| 90 | + "Segoe UI", | |
| 91 | + Roboto, | |
| 92 | + Oxygen, | |
| 93 | + Ubuntu, | |
| 94 | + Cantarell, | |
| 95 | + "Open Sans", | |
| 96 | + "Helvetica Neue", | |
| 97 | + sans-serif; | |
| 98 | + font-size: ${(props) => props.fontSize || getFontSize()}px; | |
| 99 | + padding-left: 8px; | |
| 100 | + padding-right: 8px; | |
| 101 | + color: ${vscForeground}; | |
| 102 | + line-height: 1.5; | |
| 103 | + | |
| 104 | + > *:last-child { | |
| 105 | + margin-bottom: 0; | |
| 106 | + } | |
| 107 | +`; | |
| 108 | + | |
| 109 | +/** | |
| 110 | + * Converts ANSI strings into JSON output. | |
| 111 | + * @name ansiToJSON | |
| 112 | + * @function | |
| 113 | + * @param {String} input The input string. | |
| 114 | + * @param {boolean} use_classes If `true`, HTML classes will be appended | |
| 115 | + * to the HTML output. | |
| 116 | + * @return {Array} The parsed input. | |
| 117 | + */ | |
| 118 | +function ansiToJSON( | |
| 119 | + input: string, | |
| 120 | + use_classes: boolean = false, | |
| 121 | +): AnserJsonEntry[] { | |
| 122 | + input = escapeCarriageReturn(fixBackspace(input)); | |
| 123 | + return Anser.ansiToJson(input, { | |
| 124 | + json: true, | |
| 125 | + remove_empty: true, | |
| 126 | + use_classes, | |
| 127 | + }); | |
| 128 | +} | |
| 129 | + | |
| 130 | +/** | |
| 131 | + * Create a class string. | |
| 132 | + * @name createClass | |
| 133 | + * @function | |
| 134 | + * @param {AnserJsonEntry} bundle | |
| 135 | + * @return {String} class name(s) | |
| 136 | + */ | |
| 137 | +function createClass(bundle: AnserJsonEntry): string | null { | |
| 138 | + let classNames: string = ""; | |
| 139 | + | |
| 140 | + if (bundle.bg) { | |
| 141 | + classNames += `${bundle.bg}-bg `; | |
| 142 | + } | |
| 143 | + if (bundle.fg) { | |
| 144 | + classNames += `${bundle.fg}-fg `; | |
| 145 | + } | |
| 146 | + if (bundle.decoration) { | |
| 147 | + classNames += `ansi-${bundle.decoration} `; | |
| 148 | + } | |
| 149 | + | |
| 150 | + if (classNames === "") { | |
| 151 | + return null; | |
| 152 | + } | |
| 153 | + | |
| 154 | + classNames = classNames.substring(0, classNames.length - 1); | |
| 155 | + return classNames; | |
| 156 | +} | |
| 157 | + | |
| 158 | +/** | |
| 159 | + * Converts an Anser bundle into a React Node. | |
| 160 | + * @param linkify whether links should be converting into clickable anchor tags. | |
| 161 | + * @param useClasses should render the span with a class instead of style. | |
| 162 | + * @param bundle Anser output. | |
| 163 | + * @param key | |
| 164 | + */ | |
| 165 | + | |
| 166 | +function convertBundleIntoReact( | |
| 167 | + linkify: boolean, | |
| 168 | + useClasses: boolean, | |
| 169 | + bundle: AnserJsonEntry, | |
| 170 | + key: number, | |
| 171 | +): JSX.Element { | |
| 172 | + const className = useClasses ? createClass(bundle) : null; | |
| 173 | + // Convert bundle.decoration to string or undefined (not null) to match the prop type | |
| 174 | + const decorationProp = bundle.decoration | |
| 175 | + ? String(bundle.decoration) | |
| 176 | + : undefined; | |
| 177 | + | |
| 178 | + if (!linkify) { | |
| 179 | + return ( | |
| 180 | + <AnsiSpan | |
| 181 | + key={key} | |
| 182 | + className={className || undefined} | |
| 183 | + bg={useClasses ? undefined : bundle.bg} | |
| 184 | + fg={useClasses ? undefined : bundle.fg} | |
| 185 | + decoration={decorationProp} | |
| 186 | + > | |
| 187 | + {bundle.content} | |
| 188 | + </AnsiSpan> | |
| 189 | + ); | |
| 190 | + } | |
| 191 | + | |
| 192 | + const content: React.ReactNode[] = []; | |
| 193 | + const linkRegex = | |
| 194 | + /(\s|^)(https?:\/\/(?:www\.|(?!www))[^\s.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})/g; | |
| 195 | + | |
| 196 | + let index = 0; | |
| 197 | + let match: RegExpExecArray | null; | |
| 198 | + while ((match = linkRegex.exec(bundle.content)) !== null) { | |
| 199 | + const [, pre, url] = match; | |
| 200 | + | |
| 201 | + const startIndex = match.index + pre.length; | |
| 202 | + if (startIndex > index) { | |
| 203 | + content.push(bundle.content.substring(index, startIndex)); | |
| 204 | + } | |
| 205 | + | |
| 206 | + // Make sure the href we generate from the link is fully qualified. We assume http | |
| 207 | + // if it starts with a www because many sites don't support https | |
| 208 | + const href = url.startsWith("www.") ? `http://${url}` : url; | |
| 209 | + | |
| 210 | + content.push( | |
| 211 | + <AnsiLink key={index} href={href} target="_blank"> | |
| 212 | + {url} | |
| 213 | + </AnsiLink>, | |
| 214 | + ); | |
| 215 | + | |
| 216 | + index = linkRegex.lastIndex; | |
| 217 | + } | |
| 218 | + | |
| 219 | + if (index < bundle.content.length) { | |
| 220 | + content.push(bundle.content.substring(index)); | |
| 221 | + } | |
| 222 | + | |
| 223 | + return ( | |
| 224 | + <AnsiSpan | |
| 225 | + key={key} | |
| 226 | + className={className || undefined} | |
| 227 | + bg={useClasses ? undefined : bundle.bg} | |
| 228 | + fg={useClasses ? undefined : bundle.fg} | |
| 229 | + decoration={decorationProp} | |
| 230 | + > | |
| 231 | + {content} | |
| 232 | + </AnsiSpan> | |
| 233 | + ); | |
| 234 | +} | |
| 235 | + | |
| 236 | +declare interface Props { | |
| 237 | + children?: string; | |
| 238 | + linkify?: boolean; | |
| 239 | + className?: string; | |
| 240 | + useClasses?: boolean; | |
| 241 | +} | |
| 242 | + | |
| 243 | +export default function Ansi(props: Props): JSX.Element { | |
| 244 | + const { className, useClasses, children, linkify } = props; | |
| 245 | + | |
| 246 | + // Create the ANSI content | |
| 247 | + const ansiContent = ansiToJSON(children ?? "", useClasses ?? false).map( | |
| 248 | + (bundle, i) => | |
| 249 | + convertBundleIntoReact(linkify ?? false, useClasses ?? false, bundle, i), | |
| 250 | + ); | |
| 251 | + | |
| 252 | + return ( | |
| 253 | + <StyledAnsi | |
| 254 | + contentEditable="false" | |
| 255 | + fontSize={getFontSize()} | |
| 256 | + whiteSpace="pre-wrap" | |
| 257 | + bgColor={vscBackground} | |
| 258 | + > | |
| 259 | + <pre> | |
| 260 | + <code className={className}>{ansiContent}</code> | |
| 261 | + </pre> | |
| 262 | + </StyledAnsi> | |
| 263 | + ); | |
| 264 | +} | |
| 265 | + | |
| 266 | +// This is copied from the Jupyter Classic source code | |
| 267 | +// notebook/static/base/js/utils.js to handle \b in a way | |
| 268 | +// that is **compatible with Jupyter classic**. One can | |
| 269 | +// argue that this behavior is questionable: | |
| 270 | +// https://stackoverflow.com/questions/55440152/multiple-b-doesnt-work-as-expected-in-jupyter# | |
| 271 | +function fixBackspace(txt: string) { | |
| 272 | + let tmp = txt; | |
| 273 | + do { | |
| 274 | + txt = tmp; | |
| 275 | + // Cancel out anything-but-newline followed by backspace | |
| 276 | + tmp = txt.replace(/[^\n]\x08/gm, ""); | |
| 277 | + } while (tmp.length < txt.length); | |
| 278 | + return txt; | |
| 279 | +} |
modified gui/src/pages/AddNewModel/configs/models.ts +133 −7
| @@ -913,12 +913,68 @@ | ||
| 913 | 913 | providerOptions: ["gemini"], |
| 914 | 914 | isOpenSource: false, |
| 915 | 915 | }, |
| 916 | - commandR: { | |
| 917 | - title: "Command R", | |
| 916 | + c4aiAyaExpanse8B: { | |
| 917 | + title: "C4AI Aya Expanse 8B", | |
| 918 | + description: | |
| 919 | + "Aya Expanse is a massively multilingual large language model excelling in enterprise-scale tasks.", | |
| 920 | + params: { | |
| 921 | + model: "c4ai-aya-expanse-8b", | |
| 922 | + contextLength: 8_000, | |
| 923 | + title: "C4AI Aya Expanse 8B", | |
| 924 | + apiKey: "", | |
| 925 | + }, | |
| 926 | + providerOptions: ["cohere"], | |
| 927 | + icon: "cohere.png", | |
| 928 | + isOpenSource: false, | |
| 929 | + }, | |
| 930 | + c4aiAyaExpanse32B: { | |
| 931 | + title: "C4AI Aya Expanse 32B", | |
| 932 | + description: | |
| 933 | + "Aya Expanse is a massively multilingual large language model excelling in enterprise-scale tasks.", | |
| 934 | + params: { | |
| 935 | + model: "c4ai-aya-expanse-32b", | |
| 936 | + contextLength: 128_000, | |
| 937 | + title: "C4AI Aya Expanse 32B", | |
| 938 | + apiKey: "", | |
| 939 | + }, | |
| 940 | + providerOptions: ["cohere"], | |
| 941 | + icon: "cohere.png", | |
| 942 | + isOpenSource: false, | |
| 943 | + }, | |
| 944 | + c4aiAyaVision8B: { | |
| 945 | + title: "C4AI Aya Vision 8B", | |
| 946 | + description: | |
| 947 | + "Aya Vision is a state-of-the-art multimodal and massively multilingual large language model excelling at critical benchmarks for language, text, and image capabilities.", | |
| 948 | + params: { | |
| 949 | + model: "c4ai-aya-vision-8b", | |
| 950 | + contextLength: 16_000, | |
| 951 | + title: "C4AI Aya Vision 8B", | |
| 952 | + apiKey: "", | |
| 953 | + }, | |
| 954 | + providerOptions: ["cohere"], | |
| 955 | + icon: "cohere.png", | |
| 956 | + isOpenSource: false, | |
| 957 | + }, | |
| 958 | + c4aiAyaVision32B: { | |
| 959 | + title: "C4AI Aya Vision 32B", | |
| 960 | + description: | |
| 961 | + "Aya Vision is a state-of-the-art multimodal and massively multilingual large language model excelling at critical benchmarks for language, text, and image capabilities.", | |
| 962 | + params: { | |
| 963 | + model: "c4ai-aya-vision-32b", | |
| 964 | + contextLength: 16_000, | |
| 965 | + title: "C4AI Aya Vision 32B", | |
| 966 | + apiKey: "", | |
| 967 | + }, | |
| 968 | + providerOptions: ["cohere"], | |
| 969 | + icon: "cohere.png", | |
| 970 | + isOpenSource: false, | |
| 971 | + }, | |
| 972 | + commandR032024: { | |
| 973 | + title: "Command R 03-2024", | |
| 918 | 974 | description: |
| 919 | 975 | "Command R is a scalable generative model targeting RAG and Tool Use to enable production-scale AI for enterprise.", |
| 920 | 976 | params: { |
| 921 | - model: "command-r", | |
| 977 | + model: "command-r-03-2024", | |
| 922 | 978 | contextLength: 128_000, |
| 923 | 979 | title: "Command R", |
| 924 | 980 | apiKey: "", |
| @@ -927,12 +983,12 @@ | ||
| 927 | 983 | icon: "cohere.png", |
| 928 | 984 | isOpenSource: false, |
| 929 | 985 | }, |
| 930 | - commandRPlus: { | |
| 931 | - title: "Command R+", | |
| 986 | + commandRPlus042024: { | |
| 987 | + title: "Command R+ 04-2024", | |
| 932 | 988 | description: |
| 933 | - "Command R+ is a state-of-the-art RAG-optimized model designed to tackle enterprise-grade workloads", | |
| 989 | + "Command R+ is a state-of-the-art RAG-optimized model designed to tackle enterprise-grade workloads.", | |
| 934 | 990 | params: { |
| 935 | - model: "command-r-plus", | |
| 991 | + model: "command-r-plus-04-2024", | |
| 936 | 992 | contextLength: 128_000, |
| 937 | 993 | title: "Command R+", |
| 938 | 994 | apiKey: "", |
| @@ -941,6 +997,76 @@ | ||
| 941 | 997 | icon: "cohere.png", |
| 942 | 998 | isOpenSource: false, |
| 943 | 999 | }, |
| 1000 | + commandR082024: { | |
| 1001 | + title: "Command R 08-2024", | |
| 1002 | + description: | |
| 1003 | + "Command R is a scalable generative model targeting RAG and Tool Use to enable production-scale AI for enterprise.", | |
| 1004 | + params: { | |
| 1005 | + model: "command-r-08-2024", | |
| 1006 | + contextLength: 128_000, | |
| 1007 | + title: "Command R 08-2024", | |
| 1008 | + apiKey: "", | |
| 1009 | + }, | |
| 1010 | + providerOptions: ["cohere"], | |
| 1011 | + icon: "cohere.png", | |
| 1012 | + isOpenSource: false, | |
| 1013 | + }, | |
| 1014 | + commandRPlus082024: { | |
| 1015 | + title: "Command R+ 08-2024", | |
| 1016 | + description: | |
| 1017 | + "Command R+ is a state-of-the-art RAG-optimized model designed to tackle enterprise-grade workloads.", | |
| 1018 | + params: { | |
| 1019 | + model: "command-r-plus-08-2024", | |
| 1020 | + contextLength: 128_000, | |
| 1021 | + title: "Command R+ 08-2024", | |
| 1022 | + apiKey: "", | |
| 1023 | + }, | |
| 1024 | + providerOptions: ["cohere"], | |
| 1025 | + icon: "cohere.png", | |
| 1026 | + isOpenSource: false, | |
| 1027 | + }, | |
| 1028 | + commandR7B122024: { | |
| 1029 | + title: "Command R7B 12-2024", | |
| 1030 | + description: | |
| 1031 | + "The smallest model in our R series delivers top-tier speed, efficiency, and quality to build powerful AI applications on commodity GPUs and edge devices.", | |
| 1032 | + params: { | |
| 1033 | + model: "command-r7b-12-2024", | |
| 1034 | + contextLength: 128_000, | |
| 1035 | + title: "Command R7B 12-2024", | |
| 1036 | + apiKey: "", | |
| 1037 | + }, | |
| 1038 | + providerOptions: ["cohere"], | |
| 1039 | + icon: "cohere.png", | |
| 1040 | + isOpenSource: false, | |
| 1041 | + }, | |
| 1042 | + commandR7BArabic022025: { | |
| 1043 | + title: "Command R7B Arabic 02-2025", | |
| 1044 | + description: | |
| 1045 | + "Our state-of-the-art lightweight multilingual AI model has been optimized for advanced Arabic language capabilities to support enterprises in the MENA region.", | |
| 1046 | + params: { | |
| 1047 | + model: "command-r7b-arabic-02-2025", | |
| 1048 | + contextLength: 128_000, | |
| 1049 | + title: "Command R7B Arabic 02-2025", | |
| 1050 | + apiKey: "", | |
| 1051 | + }, | |
| 1052 | + providerOptions: ["cohere"], | |
| 1053 | + icon: "cohere.png", | |
| 1054 | + isOpenSource: false, | |
| 1055 | + }, | |
| 1056 | + commandA032025: { | |
| 1057 | + title: "Command A 03-2025", | |
| 1058 | + description: | |
| 1059 | + "Command A is Cohere’s most performant model to date, excelling at real world enterprise tasks including tool use, retrieval augmented generation (RAG), agents, and multilingual use cases.", | |
| 1060 | + params: { | |
| 1061 | + model: "command-a-03-2025", | |
| 1062 | + contextLength: 256_000, | |
| 1063 | + title: "Command A 03-2025", | |
| 1064 | + apiKey: "", | |
| 1065 | + }, | |
| 1066 | + providerOptions: ["cohere"], | |
| 1067 | + icon: "cohere.png", | |
| 1068 | + isOpenSource: false, | |
| 1069 | + }, | |
| 944 | 1070 | gpt4turbo: { |
| 945 | 1071 | title: "GPT-4 Turbo", |
| 946 | 1072 | description: |
modified gui/src/pages/AddNewModel/configs/providers.ts +13 −1
| @@ -349,7 +349,19 @@ | ||
| 349 | 349 | }, |
| 350 | 350 | ...completionParamsInputsConfigs, |
| 351 | 351 | ], |
| 352 | - packages: [models.commandR, models.commandRPlus], | |
| 352 | + packages: [ | |
| 353 | + models.commandA032025, | |
| 354 | + models.commandR7BArabic022025, | |
| 355 | + models.commandR7B122024, | |
| 356 | + models.commandRPlus082024, | |
| 357 | + models.commandR082024, | |
| 358 | + models.commandRPlus042024, | |
| 359 | + models.commandR032024, | |
| 360 | + models.c4aiAyaVision32B, | |
| 361 | + models.c4aiAyaVision8B, | |
| 362 | + models.c4aiAyaExpanse32B, | |
| 363 | + models.c4aiAyaExpanse8B, | |
| 364 | + ], | |
| 353 | 365 | apiKeyUrl: "https://docs.cohere.com/v2/docs/rate-limits", |
| 354 | 366 | }, |
| 355 | 367 | groq: { |
modified gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx +43 −21
| @@ -1,11 +1,10 @@ | ||
| 1 | -import { AnyAction, ThunkDispatch } from "@reduxjs/toolkit"; | |
| 2 | 1 | import { ToolCallState } from "core"; |
| 3 | -import { Fragment } from "react"; | |
| 4 | -import { useDispatch } from "react-redux"; | |
| 5 | 2 | import styled from "styled-components"; |
| 3 | +import { vscForeground } from "../../../components"; | |
| 4 | +import Ansi from "../../../components/ansiTerminal/Ansi"; | |
| 6 | 5 | import StyledMarkdownPreview from "../../../components/StyledMarkdownPreview"; |
| 7 | -import { moveTerminalProcessToBackground } from "../../../redux/thunks/moveTerminalProcessToBackground"; | |
| 8 | 6 | import { useAppDispatch } from "../../../redux/hooks"; |
| 7 | +import { moveTerminalProcessToBackground } from "../../../redux/thunks/moveTerminalProcessToBackground"; | |
| 9 | 8 | |
| 10 | 9 | interface RunTerminalCommandToolCallProps { |
| 11 | 10 | command: string; |
| @@ -15,13 +14,12 @@ | ||
| 15 | 14 | |
| 16 | 15 | const CommandStatus = styled.div` |
| 17 | 16 | font-size: 12px; |
| 18 | - color: #666; | |
| 17 | + color: var(--vscode-descriptionForeground, ${vscForeground}88); | |
| 19 | 18 | margin-top: 8px; |
| 20 | - padding-left: 8px; | |
| 21 | - padding-right: 8px; | |
| 22 | - padding-bottom: 8px; | |
| 23 | 19 | display: flex; |
| 24 | 20 | align-items: center; |
| 21 | + padding-left: 8px; | |
| 22 | + padding-right: 8px; | |
| 25 | 23 | `; |
| 26 | 24 | |
| 27 | 25 | const StatusIcon = styled.span<{ |
| @@ -33,21 +31,32 @@ | ||
| 33 | 31 | margin-right: 8px; |
| 34 | 32 | background-color: ${(props) => |
| 35 | 33 | props.status === "running" |
| 36 | - ? "#4caf50" | |
| 34 | + ? "var(--vscode-testing-runAction, #4caf50)" | |
| 37 | 35 | : props.status === "completed" |
| 38 | - ? "#4caf50" | |
| 36 | + ? "var(--vscode-testing-iconPassed, #4caf50)" | |
| 39 | 37 | : props.status === "background" |
| 40 | - ? "#2196f3" | |
| 41 | - : "#f44336"}; | |
| 38 | + ? "var(--vscode-statusBarItem-prominentBackground, #2196f3)" | |
| 39 | + : "var(--vscode-testing-iconFailed, #f44336)"}; | |
| 42 | 40 | ${(props) => |
| 43 | 41 | props.status === "running" ? "animation: pulse 1.5s infinite;" : ""} |
| 44 | 42 | `; |
| 45 | 43 | |
| 46 | -// Removed unused styled components | |
| 44 | +// Waiting message styled for consistency | |
| 45 | +const WaitingMessage = styled.div` | |
| 46 | + padding: 8px; | |
| 47 | + padding-left: 16px; | |
| 48 | + padding-right: 16px; | |
| 49 | + margin-top: 8px; | |
| 50 | +`; | |
| 51 | + | |
| 52 | +// For consistency with the rest of the styled components | |
| 53 | +const AnsiWrapper = styled.div` | |
| 54 | + margin-top: 8px; | |
| 55 | +`; | |
| 47 | 56 | |
| 48 | 57 | const BackgroundLink = styled.a` |
| 49 | 58 | font-size: 12px; |
| 50 | - color: #0077cc; | |
| 59 | + color: var(--vscode-textLink-foreground, #3794ff); | |
| 51 | 60 | margin-left: 12px; |
| 52 | 61 | cursor: pointer; |
| 53 | 62 | text-decoration: none; |
| @@ -57,6 +66,11 @@ | ||
| 57 | 66 | } |
| 58 | 67 | `; |
| 59 | 68 | |
| 69 | +// Just spacing between terminal components and the next toolcall | |
| 70 | +const TerminalContainer = styled.div` | |
| 71 | + margin-bottom: 16px; | |
| 72 | +`; | |
| 73 | + | |
| 60 | 74 | export function RunTerminalCommand(props: RunTerminalCommandToolCallProps) { |
| 61 | 75 | const dispatch = useAppDispatch(); |
| 62 | 76 | |
| @@ -82,16 +96,24 @@ | ||
| 82 | 96 | } |
| 83 | 97 | |
| 84 | 98 | return ( |
| 85 | - <Fragment> | |
| 99 | + <TerminalContainer> | |
| 100 | + {/* Command */} | |
| 86 | 101 | <StyledMarkdownPreview |
| 87 | 102 | isRenderingInStepContainer |
| 88 | - source={`\`\`\`bash .sh\n$ ${props.command ?? ""}${ | |
| 89 | - hasOutput || isRunning | |
| 90 | - ? `\n${terminalContent || "Waiting for output..."}` | |
| 91 | - : "" | |
| 92 | - }\n\`\`\``} | |
| 103 | + source={`\`\`\`bash .sh\n$ ${props.command ?? ""}\n\`\`\``} | |
| 93 | 104 | /> |
| 94 | 105 | |
| 106 | + {/* Terminal output with ANSI support */} | |
| 107 | + {isRunning && !hasOutput && ( | |
| 108 | + <WaitingMessage>Waiting for output...</WaitingMessage> | |
| 109 | + )} | |
| 110 | + {hasOutput && ( | |
| 111 | + <AnsiWrapper> | |
| 112 | + <Ansi>{terminalContent}</Ansi> | |
| 113 | + </AnsiWrapper> | |
| 114 | + )} | |
| 115 | + | |
| 116 | + {/* Status information */} | |
| 95 | 117 | {(statusMessage || isRunning) && ( |
| 96 | 118 | <CommandStatus> |
| 97 | 119 | <StatusIcon status={statusType} /> |
| @@ -112,6 +134,6 @@ | ||
| 112 | 134 | )} |
| 113 | 135 | </CommandStatus> |
| 114 | 136 | )} |
| 115 | - </Fragment> | |
| 137 | + </TerminalContainer> | |
| 116 | 138 | ); |
| 117 | 139 | } |
modified packages/config-yaml/package-lock.json +2 −2
| @@ -1,12 +1,12 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "name": "@continuedev/config-yaml", |
| 3 | - "version": "1.0.88", | |
| 3 | + "version": "1.0.93", | |
| 4 | 4 | "lockfileVersion": 3, |
| 5 | 5 | "requires": true, |
| 6 | 6 | "packages": { |
| 7 | 7 | "": { |
| 8 | 8 | "name": "@continuedev/config-yaml", |
| 9 | - "version": "1.0.88", | |
| 9 | + "version": "1.0.93", | |
| 10 | 10 | "license": "Apache-2.0", |
| 11 | 11 | "dependencies": { |
| 12 | 12 | "@continuedev/config-types": "^1.0.14", |
modified packages/config-yaml/package.json +8 −1
| @@ -1,10 +1,17 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "name": "@continuedev/config-yaml", |
| 3 | - "version": "1.0.88", | |
| 3 | + "version": "1.0.94", | |
| 4 | 4 | "description": "", |
| 5 | 5 | "main": "dist/index.js", |
| 6 | 6 | "types": "dist/index.d.ts", |
| 7 | 7 | "type": "module", |
| 8 | + "exports": { | |
| 9 | + ".": { | |
| 10 | + "browser": "./dist/browser.js", | |
| 11 | + "node": "./dist/index.js", | |
| 12 | + "default": "./dist/index.js" | |
| 13 | + } | |
| 14 | + }, | |
| 8 | 15 | "bin": { |
| 9 | 16 | "@continuedev/config-yaml": "./dist/cli.js" |
| 10 | 17 | }, |
modified packages/config-yaml/src/__tests__/index.test.ts +16 −12
| @@ -119,7 +119,7 @@ | ||
| 119 | 119 | }, |
| 120 | 120 | ); |
| 121 | 121 | |
| 122 | - expect(unrolledConfig.rules?.[0]).toBeNull(); | |
| 122 | + expect(unrolledConfig.config?.rules?.[0]).toBeNull(); | |
| 123 | 123 | }); |
| 124 | 124 | |
| 125 | 125 | it("should correctly unroll assistant", async () => { |
| @@ -142,19 +142,21 @@ | ||
| 142 | 142 | }, |
| 143 | 143 | ); |
| 144 | 144 | |
| 145 | + const config = unrolledConfig.config; | |
| 146 | + | |
| 145 | 147 | // Test that packages were correctly unrolled and params replaced |
| 146 | - expect(unrolledConfig.models?.length).toBe(4); | |
| 148 | + expect(config?.models?.length).toBe(4); | |
| 147 | 149 | |
| 148 | - const openAiModel = unrolledConfig.models?.[0]!; | |
| 150 | + const openAiModel = config?.models?.[0]!; | |
| 149 | 151 | expect(openAiModel.apiKey).toBe("sk-123"); |
| 150 | 152 | |
| 151 | - const geminiModel = unrolledConfig.models?.[1]!; | |
| 153 | + const geminiModel = config?.models?.[1]!; | |
| 152 | 154 | expect(geminiModel.provider).toBe("continue-proxy"); |
| 153 | 155 | expect(geminiModel.apiKey).toBeUndefined(); |
| 154 | 156 | const geminiSecretLocation = "organization:test-org/GEMINI_API_KEY"; |
| 155 | 157 | expect((geminiModel as any).apiKeyLocation).toBe(geminiSecretLocation); |
| 156 | 158 | |
| 157 | - const anthropicModel = unrolledConfig.models?.[2]!; | |
| 159 | + const anthropicModel = config?.models?.[2]!; | |
| 158 | 160 | expect(anthropicModel.provider).toBe("continue-proxy"); |
| 159 | 161 | expect(anthropicModel.apiKey).toBeUndefined(); |
| 160 | 162 | const anthropicSecretLocation = |
| @@ -163,15 +165,15 @@ | ||
| 163 | 165 | anthropicSecretLocation, |
| 164 | 166 | ); |
| 165 | 167 | |
| 166 | - const proxyOllamaModel = unrolledConfig.models?.[3]!; | |
| 168 | + const proxyOllamaModel = config?.models?.[3]!; | |
| 167 | 169 | expect(proxyOllamaModel.provider).toBe("ollama"); |
| 168 | 170 | expect(proxyOllamaModel.defaultCompletionOptions?.stream).toBe(false); |
| 169 | 171 | |
| 170 | - expect(unrolledConfig.rules?.length).toBe(2); | |
| 171 | - expect(unrolledConfig.docs?.[0]?.startUrl).toBe( | |
| 172 | + expect(config?.rules?.length).toBe(2); | |
| 173 | + expect(config?.docs?.[0]?.startUrl).toBe( | |
| 172 | 174 | "https://docs.python.org/release/3.13.1", |
| 173 | 175 | ); |
| 174 | - expect(unrolledConfig.docs?.[0]?.rootUrl).toBe( | |
| 176 | + expect(config?.docs?.[0]?.rootUrl).toBe( | |
| 175 | 177 | "https://docs.python.org/release/3.13.1", |
| 176 | 178 | ); |
| 177 | 179 | |
| @@ -242,16 +244,18 @@ | ||
| 242 | 244 | }, |
| 243 | 245 | ); |
| 244 | 246 | |
| 247 | + const config = unrolledConfig.config; | |
| 248 | + | |
| 245 | 249 | // The original rules array should have two items |
| 246 | - expect(unrolledConfig.rules?.length).toBe(3); // Now 3 with the injected block | |
| 250 | + expect(config?.rules?.length).toBe(3); // Now 3 with the injected block | |
| 247 | 251 | |
| 248 | 252 | // Check the original doc is still there |
| 249 | - expect(unrolledConfig.docs?.[0]?.startUrl).toBe( | |
| 253 | + expect(config?.docs?.[0]?.startUrl).toBe( | |
| 250 | 254 | "https://docs.python.org/release/3.13.1", |
| 251 | 255 | ); |
| 252 | 256 | |
| 253 | 257 | // Check the injected doc block was added |
| 254 | - expect(unrolledConfig.rules?.[2]).toBe("Be kind"); | |
| 258 | + expect(config?.rules?.[2]).toBe("Be kind"); | |
| 255 | 259 | }); |
| 256 | 260 | |
| 257 | 261 | it.skip("should prioritize org over user / package secrets", () => {}); |
added packages/config-yaml/src/browser.ts +18 −0
| @@ -0,0 +1,18 @@ | ||
| 1 | +// Browser-compatible exports (excludes RegistryClient which uses Node.js APIs) | |
| 2 | +export * from "./converter.js"; | |
| 3 | +export * from "./interfaces/index.js"; | |
| 4 | +export * from "./interfaces/SecretResult.js"; | |
| 5 | +export * from "./interfaces/slugs.js"; | |
| 6 | +export * from "./load/clientRender.js"; | |
| 7 | +export * from "./load/getBlockType.js"; | |
| 8 | +export * from "./load/merge.js"; | |
| 9 | +export * from "./load/proxySecretResolution.js"; | |
| 10 | +export * from "./load/typeGuards.js"; | |
| 11 | +export * from "./load/unroll.js"; | |
| 12 | +export * from "./markdown/index.js"; | |
| 13 | +export * from "./modelName.js"; | |
| 14 | +// Note: registryClient.js is excluded because it uses Node.js fs/path APIs | |
| 15 | +export * from "./schemas/data/index.js"; | |
| 16 | +export * from "./schemas/index.js"; | |
| 17 | +export * from "./schemas/models.js"; | |
| 18 | +export * from "./validation.js"; |
modified packages/config-yaml/src/index.ts +1 −15
| @@ -1,16 +1,2 @@ | ||
| 1 | -export * from "./converter.js"; | |
| 2 | -export * from "./interfaces/index.js"; | |
| 3 | -export * from "./interfaces/SecretResult.js"; | |
| 4 | -export * from "./interfaces/slugs.js"; | |
| 5 | -export * from "./load/clientRender.js"; | |
| 6 | -export * from "./load/getBlockType.js"; | |
| 7 | -export * from "./load/merge.js"; | |
| 8 | -export * from "./load/proxySecretResolution.js"; | |
| 9 | -export * from "./load/typeGuards.js"; | |
| 10 | -export * from "./load/unroll.js"; | |
| 11 | -export * from "./modelName.js"; | |
| 1 | +export * from "./browser.js"; | |
| 12 | 2 | export * from "./registryClient.js"; |
| 13 | -export * from "./schemas/data/index.js"; | |
| 14 | -export * from "./schemas/index.js"; | |
| 15 | -export * from "./schemas/models.js"; | |
| 16 | -export * from "./validation.js"; |
modified packages/config-yaml/src/interfaces/slugs.ts +9 −0
| @@ -25,6 +25,15 @@ | ||
| 25 | 25 | |
| 26 | 26 | export type PackageIdentifier = FullSlugIdentifier | FileIdentifier; |
| 27 | 27 | |
| 28 | +export function packageIdentifierToDisplayName(id: PackageIdentifier): string { | |
| 29 | + switch (id.uriType) { | |
| 30 | + case "file": | |
| 31 | + return id.filePath; | |
| 32 | + case "slug": | |
| 33 | + return id.fullSlug.packageSlug; | |
| 34 | + } | |
| 35 | +} | |
| 36 | + | |
| 28 | 37 | export function encodePackageIdentifier(identifier: PackageIdentifier): string { |
| 29 | 38 | switch (identifier.uriType) { |
| 30 | 39 | case "slug": |
modified packages/config-yaml/src/load/unroll.ts +88 −57
| @@ -9,6 +9,7 @@ | ||
| 9 | 9 | FQSN, |
| 10 | 10 | PackageIdentifier, |
| 11 | 11 | } from "../interfaces/slugs.js"; |
| 12 | +import { markdownToRule } from "../markdown/index.js"; | |
| 12 | 13 | import { |
| 13 | 14 | AssistantUnrolled, |
| 14 | 15 | assistantUnrolledSchema, |
| @@ -195,7 +196,6 @@ | ||
| 195 | 196 | export interface BaseUnrollAssistantOptions { |
| 196 | 197 | renderSecrets: boolean; |
| 197 | 198 | injectBlocks?: PackageIdentifier[]; |
| 198 | - asConfigResult?: true; | |
| 199 | 199 | } |
| 200 | 200 | |
| 201 | 201 | export interface DoNotRenderSecretsUnrollAssistantOptions |
| @@ -217,24 +217,11 @@ | ||
| 217 | 217 | | DoNotRenderSecretsUnrollAssistantOptions |
| 218 | 218 | | RenderSecretsUnrollAssistantOptions; |
| 219 | 219 | |
| 220 | -// Overload to satisfy existing consumers of unrollAssistant. | |
| 221 | -export async function unrollAssistant( | |
| 222 | - id: PackageIdentifier, | |
| 223 | - registry: Registry, | |
| 224 | - options: UnrollAssistantOptions & { asConfigResult: true }, | |
| 225 | -): Promise<ConfigResult<AssistantUnrolled>>; | |
| 226 | - | |
| 227 | -export async function unrollAssistant( | |
| 228 | - id: PackageIdentifier, | |
| 229 | - registry: Registry, | |
| 230 | - options: UnrollAssistantOptions, | |
| 231 | -): Promise<AssistantUnrolled>; | |
| 232 | - | |
| 233 | 220 | export async function unrollAssistant( |
| 234 | 221 | id: PackageIdentifier, |
| 235 | 222 | registry: Registry, |
| 236 | 223 | options: UnrollAssistantOptions, |
| 237 | -): Promise<AssistantUnrolled | ConfigResult<AssistantUnrolled>> { | |
| 224 | +): Promise<ConfigResult<AssistantUnrolled>> { | |
| 238 | 225 | // Request the content from the registry |
| 239 | 226 | const rawContent = await registry.getContent(id); |
| 240 | 227 | |
| @@ -265,24 +252,19 @@ | ||
| 265 | 252 | rawYaml: string, |
| 266 | 253 | registry: Registry, |
| 267 | 254 | options: UnrollAssistantOptions, |
| 268 | -): Promise<AssistantUnrolled | ConfigResult<AssistantUnrolled>> { | |
| 255 | +): Promise<ConfigResult<AssistantUnrolled>> { | |
| 269 | 256 | // Parse string to Zod-validated YAML |
| 270 | - let parsedYaml = parseConfigYaml(rawYaml); | |
| 257 | + let parsedYaml = parseMarkdownRuleOrConfigYaml(rawYaml, id); | |
| 271 | 258 | |
| 272 | 259 | // Unroll blocks and convert their secrets to FQSNs |
| 273 | - const unrolledAssistant = await unrollBlocks( | |
| 274 | - parsedYaml, | |
| 275 | - registry, | |
| 276 | - options.injectBlocks, | |
| 277 | - options.asConfigResult ?? false, | |
| 278 | - ); | |
| 260 | + const { | |
| 261 | + config: unrolledAssistant, | |
| 262 | + configLoadInterrupted, | |
| 263 | + errors, | |
| 264 | + } = await unrollBlocks(parsedYaml, registry, options.injectBlocks); | |
| 279 | 265 | |
| 280 | 266 | // Back to a string so we can fill in template variables |
| 281 | - const rawUnrolledYaml = options.asConfigResult | |
| 282 | - ? YAML.stringify( | |
| 283 | - (unrolledAssistant as ConfigResult<AssistantUnrolled>).config, | |
| 284 | - ) | |
| 285 | - : YAML.stringify(unrolledAssistant); | |
| 267 | + const rawUnrolledYaml = YAML.stringify(unrolledAssistant); | |
| 286 | 268 | |
| 287 | 269 | // Convert all of the template variables to FQSNs |
| 288 | 270 | // Secrets from the block will have the assistant slug prepended to the FQSN |
| @@ -291,7 +273,11 @@ | ||
| 291 | 273 | }); |
| 292 | 274 | |
| 293 | 275 | if (!options.renderSecrets) { |
| 294 | - return parseAssistantUnrolled(templatedYaml); | |
| 276 | + return { | |
| 277 | + config: parseAssistantUnrolled(templatedYaml), | |
| 278 | + errors: [], | |
| 279 | + configLoadInterrupted: false, | |
| 280 | + }; | |
| 295 | 281 | } |
| 296 | 282 | |
| 297 | 283 | // Render secret values/locations for client |
| @@ -312,25 +298,18 @@ | ||
| 312 | 298 | options.onPremProxyUrl, |
| 313 | 299 | ); |
| 314 | 300 | |
| 315 | - if (options.asConfigResult) { | |
| 316 | - return { | |
| 317 | - config: finalConfig, | |
| 318 | - errors: (unrolledAssistant as ConfigResult<AssistantUnrolled>).errors, | |
| 319 | - configLoadInterrupted: ( | |
| 320 | - unrolledAssistant as ConfigResult<AssistantUnrolled> | |
| 321 | - ).configLoadInterrupted, | |
| 322 | - }; | |
| 323 | - } | |
| 324 | - | |
| 325 | - return finalConfig; | |
| 301 | + return { | |
| 302 | + config: finalConfig, | |
| 303 | + errors, | |
| 304 | + configLoadInterrupted, | |
| 305 | + }; | |
| 326 | 306 | } |
| 327 | 307 | |
| 328 | 308 | export async function unrollBlocks( |
| 329 | 309 | assistant: ConfigYaml, |
| 330 | 310 | registry: Registry, |
| 331 | 311 | injectBlocks: PackageIdentifier[] | undefined, |
| 332 | - asConfigError: boolean, | |
| 333 | -): Promise<AssistantUnrolled | ConfigResult<AssistantUnrolled>> { | |
| 312 | +): Promise<ConfigResult<AssistantUnrolled>> { | |
| 334 | 313 | const errors: ConfigValidationError[] = []; |
| 335 | 314 | |
| 336 | 315 | const unrolledAssistant: AssistantUnrolled = { |
| @@ -432,7 +411,10 @@ | ||
| 432 | 411 | for (const injectBlock of injectBlocks ?? []) { |
| 433 | 412 | try { |
| 434 | 413 | const blockConfigYaml = await registry.getContent(injectBlock); |
| 435 | - const parsedBlock = parseConfigYaml(blockConfigYaml); | |
| 414 | + const parsedBlock = parseMarkdownRuleOrConfigYaml( | |
| 415 | + blockConfigYaml, | |
| 416 | + injectBlock, | |
| 417 | + ); | |
| 436 | 418 | const blockType = getBlockType(parsedBlock); |
| 437 | 419 | const resolvedBlock = await resolveBlock( |
| 438 | 420 | injectBlock, |
| @@ -466,20 +448,16 @@ | ||
| 466 | 448 | } |
| 467 | 449 | } |
| 468 | 450 | |
| 469 | - if (asConfigError) { | |
| 470 | - const configResult: ConfigResult<AssistantUnrolled> = { | |
| 471 | - config: undefined, | |
| 472 | - errors: undefined, | |
| 473 | - configLoadInterrupted: false, | |
| 474 | - }; | |
| 475 | - configResult.config = unrolledAssistant; | |
| 476 | - if (errors.length > 0) { | |
| 477 | - configResult.errors = errors; | |
| 478 | - } | |
| 479 | - return configResult; | |
| 451 | + const configResult: ConfigResult<AssistantUnrolled> = { | |
| 452 | + config: undefined, | |
| 453 | + errors: undefined, | |
| 454 | + configLoadInterrupted: false, | |
| 455 | + }; | |
| 456 | + configResult.config = unrolledAssistant; | |
| 457 | + if (errors.length > 0) { | |
| 458 | + configResult.errors = errors; | |
| 480 | 459 | } |
| 481 | - | |
| 482 | - return unrolledAssistant; | |
| 460 | + return configResult; | |
| 483 | 461 | } |
| 484 | 462 | |
| 485 | 463 | export async function resolveBlock( |
| @@ -503,7 +481,60 @@ | ||
| 503 | 481 | secrets: extractFQSNMap(rawYaml, [id]), |
| 504 | 482 | }); |
| 505 | 483 | |
| 506 | - const parsedYaml = parseBlock(templatedYaml); | |
| 484 | + return parseMarkdownRuleOrAssistantUnrolled(templatedYaml, id); | |
| 485 | +} | |
| 486 | + | |
| 487 | +function parseMarkdownRuleOrAssistantUnrolled( | |
| 488 | + content: string, | |
| 489 | + id: PackageIdentifier, | |
| 490 | +): AssistantUnrolled { | |
| 491 | + // Try to parse as YAML first, then as markdown rule if that fails | |
| 492 | + let parsedYaml: AssistantUnrolled; | |
| 493 | + try { | |
| 494 | + parsedYaml = parseBlock(content); | |
| 495 | + } catch (yamlError) { | |
| 496 | + // If YAML parsing fails, try parsing as markdown rule | |
| 497 | + try { | |
| 498 | + const rule = markdownToRule(content, id); | |
| 499 | + // Convert the rule object to the expected format | |
| 500 | + parsedYaml = { | |
| 501 | + name: rule.name, | |
| 502 | + version: "1.0.0", | |
| 503 | + rules: [rule], | |
| 504 | + }; | |
| 505 | + } catch (markdownError) { | |
| 506 | + // If both fail, throw the original YAML error | |
| 507 | + throw yamlError; | |
| 508 | + } | |
| 509 | + } | |
| 510 | + | |
| 511 | + return parsedYaml; | |
| 512 | +} | |
| 513 | + | |
| 514 | +function parseMarkdownRuleOrConfigYaml( | |
| 515 | + content: string, | |
| 516 | + id: PackageIdentifier, | |
| 517 | +): ConfigYaml { | |
| 518 | + // Try to parse as YAML first, then as markdown rule if that fails | |
| 519 | + let parsedYaml: ConfigYaml; | |
| 520 | + try { | |
| 521 | + parsedYaml = parseConfigYaml(content); | |
| 522 | + } catch (yamlError) { | |
| 523 | + // If YAML parsing fails, try parsing as markdown rule | |
| 524 | + try { | |
| 525 | + const rule = markdownToRule(content, id); | |
| 526 | + // Convert the rule object to the expected format | |
| 527 | + parsedYaml = { | |
| 528 | + name: rule.name, | |
| 529 | + version: "1.0.0", | |
| 530 | + rules: [rule], | |
| 531 | + }; | |
| 532 | + } catch (markdownError) { | |
| 533 | + // If both fail, throw the original YAML error | |
| 534 | + throw yamlError; | |
| 535 | + } | |
| 536 | + } | |
| 537 | + | |
| 507 | 538 | return parsedYaml; |
| 508 | 539 | } |
| 509 | 540 |
added packages/config-yaml/src/markdown/createMarkdownRule.test.ts +149 −0
| @@ -0,0 +1,149 @@ | ||
| 1 | +import { PackageIdentifier } from "../browser.js"; | |
| 2 | +import { | |
| 3 | + createMarkdownWithFrontmatter, | |
| 4 | + createRuleMarkdown, | |
| 5 | + sanitizeRuleName, | |
| 6 | +} from "./createMarkdownRule.js"; | |
| 7 | +import { markdownToRule } from "./markdownToRule.js"; | |
| 8 | + | |
| 9 | +// Mock package identifier for testing | |
| 10 | +const mockPackageId: PackageIdentifier = { | |
| 11 | + uriType: "file", | |
| 12 | + filePath: "/path/to/file", | |
| 13 | +}; | |
| 14 | + | |
| 15 | +describe("sanitizeRuleName", () => { | |
| 16 | + it("should sanitize rule names for filenames", () => { | |
| 17 | + expect(sanitizeRuleName("My Test Rule")).toBe("my-test-rule"); | |
| 18 | + expect(sanitizeRuleName("Rule with @#$% chars")).toBe("rule-with-chars"); | |
| 19 | + expect(sanitizeRuleName("Multiple spaces")).toBe("multiple-spaces"); | |
| 20 | + expect(sanitizeRuleName("UPPERCASE-rule")).toBe("uppercase-rule"); | |
| 21 | + expect(sanitizeRuleName("already-sanitized")).toBe("already-sanitized"); | |
| 22 | + }); | |
| 23 | + | |
| 24 | + it("should handle empty and edge case inputs", () => { | |
| 25 | + expect(sanitizeRuleName("")).toBe(""); | |
| 26 | + expect(sanitizeRuleName(" ")).toBe(""); | |
| 27 | + expect(sanitizeRuleName("123")).toBe("123"); | |
| 28 | + expect(sanitizeRuleName("rule-with-numbers-123")).toBe( | |
| 29 | + "rule-with-numbers-123", | |
| 30 | + ); | |
| 31 | + }); | |
| 32 | +}); | |
| 33 | + | |
| 34 | +describe("createMarkdownWithFrontmatter", () => { | |
| 35 | + it("should create properly formatted markdown with frontmatter", () => { | |
| 36 | + const frontmatter = { | |
| 37 | + name: "Test Rule", | |
| 38 | + description: "A test rule", | |
| 39 | + globs: "*.ts", | |
| 40 | + }; | |
| 41 | + const markdown = "# Test Rule\n\nThis is a test rule."; | |
| 42 | + | |
| 43 | + const result = createMarkdownWithFrontmatter(frontmatter, markdown); | |
| 44 | + | |
| 45 | + // The exact quote style doesn't matter as long as it parses correctly | |
| 46 | + expect(result).toContain("name: Test Rule"); | |
| 47 | + expect(result).toContain("description: A test rule"); | |
| 48 | + expect(result).toContain("globs:"); | |
| 49 | + expect(result).toContain("*.ts"); | |
| 50 | + expect(result).toContain("---\n\n# Test Rule\n\nThis is a test rule."); | |
| 51 | + }); | |
| 52 | + | |
| 53 | + it("should handle empty frontmatter", () => { | |
| 54 | + const frontmatter = {}; | |
| 55 | + const markdown = "# Simple Rule\n\nJust markdown content."; | |
| 56 | + | |
| 57 | + const result = createMarkdownWithFrontmatter(frontmatter, markdown); | |
| 58 | + | |
| 59 | + const expected = `--- | |
| 60 | +{} | |
| 61 | +--- | |
| 62 | + | |
| 63 | +# Simple Rule | |
| 64 | + | |
| 65 | +Just markdown content.`; | |
| 66 | + | |
| 67 | + expect(result).toBe(expected); | |
| 68 | + }); | |
| 69 | + | |
| 70 | + it("should create content that can be parsed back correctly", () => { | |
| 71 | + const originalFrontmatter = { | |
| 72 | + name: "Roundtrip Test", | |
| 73 | + description: "Testing roundtrip parsing", | |
| 74 | + globs: ["*.js", "*.ts"], | |
| 75 | + alwaysApply: true, | |
| 76 | + }; | |
| 77 | + const originalMarkdown = | |
| 78 | + "# Roundtrip Test\n\nThis should parse back correctly."; | |
| 79 | + | |
| 80 | + const created = createMarkdownWithFrontmatter( | |
| 81 | + originalFrontmatter, | |
| 82 | + originalMarkdown, | |
| 83 | + ); | |
| 84 | + const parsed = markdownToRule(created, mockPackageId); | |
| 85 | + | |
| 86 | + expect(parsed.name).toBe(originalFrontmatter.name); | |
| 87 | + expect(parsed.description).toBe(originalFrontmatter.description); | |
| 88 | + expect(parsed.globs).toEqual(originalFrontmatter.globs); | |
| 89 | + expect(parsed.alwaysApply).toBe(originalFrontmatter.alwaysApply); | |
| 90 | + expect(parsed.rule).toBe(originalMarkdown); | |
| 91 | + }); | |
| 92 | +}); | |
| 93 | + | |
| 94 | +describe("createRuleMarkdown", () => { | |
| 95 | + it("should create rule markdown with all options", () => { | |
| 96 | + const result = createRuleMarkdown("Test Rule", "This is the rule content", { | |
| 97 | + description: "Test description", | |
| 98 | + globs: ["*.ts", "*.js"], | |
| 99 | + alwaysApply: true, | |
| 100 | + }); | |
| 101 | + | |
| 102 | + const parsed = markdownToRule(result, mockPackageId); | |
| 103 | + | |
| 104 | + expect(parsed.description).toBe("Test description"); | |
| 105 | + expect(parsed.globs).toEqual(["*.ts", "*.js"]); | |
| 106 | + expect(parsed.alwaysApply).toBe(true); | |
| 107 | + expect(parsed.rule).toBe("This is the rule content"); | |
| 108 | + }); | |
| 109 | + | |
| 110 | + it("should create rule markdown with minimal options", () => { | |
| 111 | + const result = createRuleMarkdown("Simple Rule", "Simple content"); | |
| 112 | + | |
| 113 | + const parsed = markdownToRule(result, mockPackageId); | |
| 114 | + | |
| 115 | + expect(parsed.description).toBeUndefined(); | |
| 116 | + expect(parsed.globs).toBeUndefined(); | |
| 117 | + expect(parsed.alwaysApply).toBeUndefined(); | |
| 118 | + expect(parsed.rule).toBe("Simple content"); | |
| 119 | + }); | |
| 120 | + | |
| 121 | + it("should handle string globs", () => { | |
| 122 | + const result = createRuleMarkdown("String Glob Rule", "Content", { | |
| 123 | + globs: "*.py", | |
| 124 | + }); | |
| 125 | + | |
| 126 | + const parsed = markdownToRule(result, mockPackageId); | |
| 127 | + expect(parsed.globs).toBe("*.py"); | |
| 128 | + }); | |
| 129 | + | |
| 130 | + it("should trim description and globs", () => { | |
| 131 | + const result = createRuleMarkdown("Trim Test", "Content", { | |
| 132 | + description: " spaced description ", | |
| 133 | + globs: " *.ts ", | |
| 134 | + }); | |
| 135 | + | |
| 136 | + const parsed = markdownToRule(result, mockPackageId); | |
| 137 | + expect(parsed.description).toBe("spaced description"); | |
| 138 | + expect(parsed.globs).toBe("*.ts"); | |
| 139 | + }); | |
| 140 | + | |
| 141 | + it("should handle alwaysApply false explicitly", () => { | |
| 142 | + const result = createRuleMarkdown("Always Apply False", "Content", { | |
| 143 | + alwaysApply: false, | |
| 144 | + }); | |
| 145 | + | |
| 146 | + const parsed = markdownToRule(result, mockPackageId); | |
| 147 | + expect(parsed.alwaysApply).toBe(false); | |
| 148 | + }); | |
| 149 | +}); |
added packages/config-yaml/src/markdown/createMarkdownRule.ts +56 −0
| @@ -0,0 +1,56 @@ | ||
| 1 | +import * as YAML from "yaml"; | |
| 2 | +import { RuleFrontmatter } from "./markdownToRule.js"; | |
| 3 | + | |
| 4 | +export const RULE_FILE_EXTENSION = "md"; | |
| 5 | + | |
| 6 | +/** | |
| 7 | + * Sanitizes a rule name for use in filenames (removes special chars, replaces spaces with dashes) | |
| 8 | + */ | |
| 9 | +export function sanitizeRuleName(name: string): string { | |
| 10 | + return name | |
| 11 | + .toLowerCase() | |
| 12 | + .replace(/[^a-z0-9\s-]/g, "") | |
| 13 | + .replace(/\s+/g, "-") | |
| 14 | + .replace(/^-+|-+$/g, ""); // Remove leading/trailing dashes | |
| 15 | +} | |
| 16 | + | |
| 17 | +/** | |
| 18 | + * Creates markdown content with YAML frontmatter in the format expected by parseMarkdownRule | |
| 19 | + */ | |
| 20 | +export function createMarkdownWithFrontmatter( | |
| 21 | + frontmatter: RuleFrontmatter, | |
| 22 | + markdown: string, | |
| 23 | +): string { | |
| 24 | + const frontmatterStr = YAML.stringify(frontmatter).trim(); | |
| 25 | + return `---\n${frontmatterStr}\n---\n\n${markdown}`; | |
| 26 | +} | |
| 27 | + | |
| 28 | +/** | |
| 29 | + * Creates a rule markdown file content from rule components | |
| 30 | + */ | |
| 31 | +export function createRuleMarkdown( | |
| 32 | + name: string, | |
| 33 | + ruleContent: string, | |
| 34 | + options: { | |
| 35 | + description?: string; | |
| 36 | + globs?: string | string[]; | |
| 37 | + alwaysApply?: boolean; | |
| 38 | + } = {}, | |
| 39 | +): string { | |
| 40 | + const frontmatter: RuleFrontmatter = {}; | |
| 41 | + | |
| 42 | + if (options.globs) { | |
| 43 | + frontmatter.globs = | |
| 44 | + typeof options.globs === "string" ? options.globs.trim() : options.globs; | |
| 45 | + } | |
| 46 | + | |
| 47 | + if (options.description) { | |
| 48 | + frontmatter.description = options.description.trim(); | |
| 49 | + } | |
| 50 | + | |
| 51 | + if (options.alwaysApply !== undefined) { | |
| 52 | + frontmatter.alwaysApply = options.alwaysApply; | |
| 53 | + } | |
| 54 | + | |
| 55 | + return createMarkdownWithFrontmatter(frontmatter, ruleContent); | |
| 56 | +} |
added packages/config-yaml/src/markdown/index.ts +2 −0
| @@ -0,0 +1,2 @@ | ||
| 1 | +export * from "./createMarkdownRule.js"; | |
| 2 | +export * from "./markdownToRule.js"; |
added packages/config-yaml/src/markdown/markdownToRule.test.ts +173 −0
| @@ -0,0 +1,173 @@ | ||
| 1 | +import { PackageIdentifier } from "../browser.js"; | |
| 2 | +import { markdownToRule } from "./markdownToRule.js"; | |
| 3 | + | |
| 4 | +describe("markdownToRule", () => { | |
| 5 | + // Use a mock PackageIdentifier for testing | |
| 6 | + const mockId: PackageIdentifier = { | |
| 7 | + uriType: "file", | |
| 8 | + filePath: "/path/to/file", | |
| 9 | + }; | |
| 10 | + | |
| 11 | + it("should convert markdown with frontmatter to a rule", () => { | |
| 12 | + const content = `--- | |
| 13 | +globs: "**/test/**/*.kt" | |
| 14 | +name: Custom Name | |
| 15 | +--- | |
| 16 | + | |
| 17 | +# Test Rule | |
| 18 | + | |
| 19 | +This is a test rule.`; | |
| 20 | + | |
| 21 | + const result = markdownToRule(content, mockId); | |
| 22 | + expect(result.rule).toBe("# Test Rule\n\nThis is a test rule."); | |
| 23 | + expect(result.globs).toBe("**/test/**/*.kt"); | |
| 24 | + expect(result.name).toBe("Custom Name"); | |
| 25 | + }); | |
| 26 | + | |
| 27 | + it("should correctly parse markdown with YAML frontmatter", () => { | |
| 28 | + const content = `--- | |
| 29 | +globs: "**/test/**/*.kt" | |
| 30 | +--- | |
| 31 | + | |
| 32 | +# Test Rule | |
| 33 | + | |
| 34 | +This is a test rule.`; | |
| 35 | + | |
| 36 | + const result = markdownToRule(content, mockId); | |
| 37 | + expect(result.globs).toBe("**/test/**/*.kt"); | |
| 38 | + expect(result.rule).toBe("# Test Rule\n\nThis is a test rule."); | |
| 39 | + expect(result.name).toBe("/path/to/file"); // Should use packageIdentifierToDisplayName result | |
| 40 | + }); | |
| 41 | + | |
| 42 | + it("should handle missing frontmatter", () => { | |
| 43 | + const content = `# Test Rule | |
| 44 | + | |
| 45 | +This is a test rule without frontmatter.`; | |
| 46 | + | |
| 47 | + const result = markdownToRule(content, mockId); | |
| 48 | + expect(result.globs).toBeUndefined(); | |
| 49 | + expect(result.rule).toBe(content); | |
| 50 | + expect(result.name).toBe("/path/to/file"); // Should use packageIdentifierToDisplayName result | |
| 51 | + }); | |
| 52 | + | |
| 53 | + it("should handle empty frontmatter", () => { | |
| 54 | + const content = `--- | |
| 55 | +--- | |
| 56 | + | |
| 57 | +# Test Rule | |
| 58 | + | |
| 59 | +This is a test rule with empty frontmatter.`; | |
| 60 | + | |
| 61 | + const result = markdownToRule(content, mockId); | |
| 62 | + expect(result.globs).toBeUndefined(); | |
| 63 | + expect(result.rule).toBe( | |
| 64 | + "# Test Rule\n\nThis is a test rule with empty frontmatter.", | |
| 65 | + ); | |
| 66 | + expect(result.name).toBe("/path/to/file"); // Should use packageIdentifierToDisplayName result | |
| 67 | + }); | |
| 68 | + | |
| 69 | + it("should handle frontmatter with whitespace", () => { | |
| 70 | + const content = `--- | |
| 71 | +globs: "**/test/**/*.kt" | |
| 72 | +--- | |
| 73 | + | |
| 74 | +# Test Rule | |
| 75 | + | |
| 76 | +This is a test rule.`; | |
| 77 | + | |
| 78 | + const result = markdownToRule(content, mockId); | |
| 79 | + expect(result.globs).toBe("**/test/**/*.kt"); | |
| 80 | + expect(result.rule).toBe("# Test Rule\n\nThis is a test rule."); | |
| 81 | + expect(result.name).toBe("/path/to/file"); // Should use packageIdentifierToDisplayName result | |
| 82 | + }); | |
| 83 | + | |
| 84 | + it("should handle Windows line endings (CRLF)", () => { | |
| 85 | + // Using \r\n for CRLF line endings | |
| 86 | + const content = `---\r | |
| 87 | +globs: "**/test/**/*.kt"\r | |
| 88 | +---\r | |
| 89 | +\r | |
| 90 | +# Test Rule\r | |
| 91 | +\r | |
| 92 | +This is a test rule.`; | |
| 93 | + | |
| 94 | + const result = markdownToRule(content, mockId); | |
| 95 | + expect(result.globs).toBe("**/test/**/*.kt"); | |
| 96 | + // The result should be normalized to \n | |
| 97 | + expect(result.rule).toBe("# Test Rule\n\nThis is a test rule."); | |
| 98 | + expect(result.name).toBe("/path/to/file"); // Should use packageIdentifierToDisplayName result | |
| 99 | + }); | |
| 100 | + | |
| 101 | + it("should handle malformed frontmatter", () => { | |
| 102 | + const content = `--- | |
| 103 | +globs: - "**/test/**/*.kt" | |
| 104 | +invalid: yaml: content | |
| 105 | +--- | |
| 106 | + | |
| 107 | +# Test Rule | |
| 108 | + | |
| 109 | +This is a test rule.`; | |
| 110 | + | |
| 111 | + // Should treat as only markdown when frontmatter is malformed | |
| 112 | + const result = markdownToRule(content, mockId); | |
| 113 | + expect(result.globs).toBeUndefined(); | |
| 114 | + expect(result.rule).toBe(content); | |
| 115 | + expect(result.name).toBe("/path/to/file"); // Should use packageIdentifierToDisplayName result | |
| 116 | + }); | |
| 117 | + | |
| 118 | + it("should use packageIdentifierToDisplayName if no heading or frontmatter name", () => { | |
| 119 | + const content = `--- | |
| 120 | +globs: "**/test/**/*.kt" | |
| 121 | +--- | |
| 122 | + | |
| 123 | +# Test Rule Title | |
| 124 | + | |
| 125 | +This is a test rule.`; | |
| 126 | + | |
| 127 | + const result = markdownToRule(content, mockId); | |
| 128 | + expect(result.name).toBe("/path/to/file"); // Should use packageIdentifierToDisplayName result | |
| 129 | + }); | |
| 130 | + | |
| 131 | + it("should use packageIdentifierToDisplayName if no heading or frontmatter name (no heading)", () => { | |
| 132 | + const content = `--- | |
| 133 | +globs: "**/test/**/*.kt" | |
| 134 | +--- | |
| 135 | + | |
| 136 | +This is a test rule without a heading.`; | |
| 137 | + | |
| 138 | + const result = markdownToRule(content, mockId); | |
| 139 | + expect(result.name).toBe("/path/to/file"); // Should use packageIdentifierToDisplayName result | |
| 140 | + }); | |
| 141 | + | |
| 142 | + it("should include description from frontmatter", () => { | |
| 143 | + const content = `--- | |
| 144 | +globs: "**/test/**/*.kt" | |
| 145 | +name: Test Rule | |
| 146 | +description: This is a rule description from frontmatter | |
| 147 | +--- | |
| 148 | + | |
| 149 | +# Test Rule | |
| 150 | + | |
| 151 | +This is the content of the rule.`; | |
| 152 | + | |
| 153 | + const result = markdownToRule(content, mockId); | |
| 154 | + expect(result.description).toBe( | |
| 155 | + "This is a rule description from frontmatter", | |
| 156 | + ); | |
| 157 | + }); | |
| 158 | + | |
| 159 | + it("should include alwaysApply from frontmatter", () => { | |
| 160 | + const content = `--- | |
| 161 | +globs: "**/test/**/*.kt" | |
| 162 | +name: Test Rule | |
| 163 | +alwaysApply: false | |
| 164 | +--- | |
| 165 | + | |
| 166 | +# Test Rule | |
| 167 | + | |
| 168 | +This is a rule with alwaysApply explicitly set to false.`; | |
| 169 | + | |
| 170 | + const result = markdownToRule(content, mockId); | |
| 171 | + expect(result.alwaysApply).toBe(false); | |
| 172 | + }); | |
| 173 | +}); |
added packages/config-yaml/src/markdown/markdownToRule.ts +62 −0
| @@ -0,0 +1,62 @@ | ||
| 1 | +import * as YAML from "yaml"; | |
| 2 | +import { | |
| 3 | + PackageIdentifier, | |
| 4 | + packageIdentifierToDisplayName, | |
| 5 | +} from "../browser.js"; | |
| 6 | +import { RuleObject } from "../schemas/index.js"; | |
| 7 | + | |
| 8 | +export interface RuleFrontmatter { | |
| 9 | + globs?: RuleObject["globs"]; | |
| 10 | + name?: RuleObject["name"]; | |
| 11 | + description?: RuleObject["description"]; | |
| 12 | + alwaysApply?: RuleObject["alwaysApply"]; | |
| 13 | +} | |
| 14 | + | |
| 15 | +/** | |
| 16 | + * Parses markdown content with YAML frontmatter | |
| 17 | + */ | |
| 18 | +export function parseMarkdownRule(content: string): { | |
| 19 | + frontmatter: RuleFrontmatter; | |
| 20 | + markdown: string; | |
| 21 | +} { | |
| 22 | + // Normalize line endings to \n | |
| 23 | + const normalizedContent = content.replace(/\r\n/g, "\n"); | |
| 24 | + | |
| 25 | + // More reliable frontmatter detection | |
| 26 | + const parts = normalizedContent.split(/^---\s*$/m); | |
| 27 | + | |
| 28 | + // If we have at least 3 parts (before ---, frontmatter, after ---), we have frontmatter | |
| 29 | + if (parts.length >= 3) { | |
| 30 | + const frontmatterStr = parts[1]; | |
| 31 | + // Join the remaining parts back together (in case there are more --- in the markdown) | |
| 32 | + const markdownContent = parts.slice(2).join("---"); | |
| 33 | + | |
| 34 | + try { | |
| 35 | + // Parse YAML frontmatter | |
| 36 | + const frontmatter = YAML.parse(frontmatterStr) || {}; // Handle empty frontmatter | |
| 37 | + return { frontmatter, markdown: markdownContent.trim() }; | |
| 38 | + } catch (e) { | |
| 39 | + // Error parsing frontmatter, treat as markdown only | |
| 40 | + console.warn("Error parsing markdown frontmatter:", e); | |
| 41 | + return { frontmatter: {}, markdown: normalizedContent }; | |
| 42 | + } | |
| 43 | + } | |
| 44 | + | |
| 45 | + // No frontmatter found | |
| 46 | + return { frontmatter: {}, markdown: normalizedContent }; | |
| 47 | +} | |
| 48 | + | |
| 49 | +export function markdownToRule( | |
| 50 | + rule: string, | |
| 51 | + id: PackageIdentifier, | |
| 52 | +): RuleObject { | |
| 53 | + const { frontmatter, markdown } = parseMarkdownRule(rule); | |
| 54 | + | |
| 55 | + return { | |
| 56 | + name: frontmatter.name ?? packageIdentifierToDisplayName(id), | |
| 57 | + rule: markdown, | |
| 58 | + globs: frontmatter.globs, | |
| 59 | + description: frontmatter.description, | |
| 60 | + alwaysApply: frontmatter.alwaysApply, | |
| 61 | + }; | |
| 62 | +} |
modified packages/config-yaml/src/schemas/index.ts +16 −0
| @@ -39,6 +39,7 @@ | ||
| 39 | 39 | }); |
| 40 | 40 | |
| 41 | 41 | export type DocsConfig = z.infer<typeof docSchema>; |
| 42 | + | |
| 42 | 43 | const ruleObjectSchema = z.object({ |
| 43 | 44 | name: z.string(), |
| 44 | 45 | rule: z.string(), |
| @@ -48,8 +49,23 @@ | ||
| 48 | 49 | }); |
| 49 | 50 | const ruleSchema = z.union([z.string(), ruleObjectSchema]); |
| 50 | 51 | |
| 52 | +/** | |
| 53 | + * A schema for rules.json files | |
| 54 | + */ | |
| 55 | +export const rulesJsonSchema = z.object({ | |
| 56 | + name: z.string(), | |
| 57 | + version: z.string(), | |
| 58 | + author: z.string().optional(), | |
| 59 | + license: z.string().optional(), | |
| 60 | + rules: z.record(z.string(), z.string()).optional(), | |
| 61 | +}); | |
| 62 | + | |
| 51 | 63 | export type Rule = z.infer<typeof ruleSchema>; |
| 52 | 64 | export type RuleObject = z.infer<typeof ruleObjectSchema>; |
| 65 | +/** | |
| 66 | + * A schema for rules.json files | |
| 67 | + */ | |
| 68 | +export type RulesJson = z.infer<typeof rulesJsonSchema>; | |
| 53 | 69 | |
| 54 | 70 | const defaultUsesSchema = z.string(); |
| 55 | 71 |
modified packages/continue-sdk/package-lock.json +0 −0
Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.
modified packages/llm-info/src/providers/cohere.ts +150 −12
| @@ -3,29 +3,167 @@ | ||
| 3 | 3 | export const Cohere: ModelProvider = { |
| 4 | 4 | models: [ |
| 5 | 5 | { |
| 6 | - model: "command-r-plus", | |
| 7 | - displayName: "Command R+", | |
| 6 | + model: "command-a-03-2025", | |
| 7 | + displayName: "Command A 03-2025", | |
| 8 | + contextLength: 256000, | |
| 9 | + maxCompletionTokens: 8192, | |
| 10 | + description: | |
| 11 | + "Command A is Cohere’s most performant model to date, excelling at real world enterprise tasks including tool use, retrieval augmented generation (RAG), agents, and multilingual use cases.", | |
| 12 | + recommendedFor: ["chat"], | |
| 13 | + }, | |
| 14 | + { | |
| 15 | + model: "command-r7b-arabic-12-2024", | |
| 16 | + displayName: "Command R7B Arabic 02-2025", | |
| 17 | + contextLength: 128000, | |
| 18 | + maxCompletionTokens: 4096, | |
| 19 | + description: | |
| 20 | + "Our state-of-the-art lightweight multilingual AI model has been optimized for advanced Arabic language capabilities to support enterprises in the MENA region.", | |
| 21 | + recommendedFor: ["chat"], | |
| 22 | + }, | |
| 23 | + { | |
| 24 | + model: "command-r7b-12-2024", | |
| 25 | + displayName: "Command R7B 12-2024", | |
| 26 | + contextLength: 128000, | |
| 27 | + maxCompletionTokens: 4096, | |
| 28 | + description: | |
| 29 | + "The smallest model in our R series delivers top-tier speed, efficiency, and quality to build powerful AI applications on commodity GPUs and edge devices.", | |
| 30 | + recommendedFor: ["chat"], | |
| 31 | + }, | |
| 32 | + { | |
| 33 | + model: "command-r-plus-08-2024", | |
| 34 | + displayName: "Command R+ 08-2024", | |
| 35 | + contextLength: 128000, | |
| 36 | + maxCompletionTokens: 4096, | |
| 37 | + description: | |
| 38 | + "Command R is a scalable generative model targeting RAG and Tool Use to enable production-scale AI for enterprise.", | |
| 39 | + recommendedFor: ["chat"], | |
| 40 | + }, | |
| 41 | + { | |
| 42 | + model: "command-r-08-2024", | |
| 43 | + displayName: "Command R 08-2024", | |
| 44 | + contextLength: 128000, | |
| 45 | + maxCompletionTokens: 4096, | |
| 46 | + description: | |
| 47 | + "Command R+ is a state-of-the-art RAG-optimized model designed to tackle enterprise-grade workloads.", | |
| 48 | + recommendedFor: ["chat"], | |
| 49 | + }, | |
| 50 | + { | |
| 51 | + model: "command-r-plus-04-2024", | |
| 52 | + displayName: "Command R+ 04-2024", | |
| 53 | + contextLength: 128000, | |
| 54 | + maxCompletionTokens: 4096, | |
| 55 | + description: | |
| 56 | + "Command R is a scalable generative model targeting RAG and Tool Use to enable production-scale AI for enterprise.", | |
| 57 | + recommendedFor: ["chat"], | |
| 58 | + }, | |
| 59 | + { | |
| 60 | + model: "command-r-03-2024", | |
| 61 | + displayName: "Command R 03-2024", | |
| 62 | + contextLength: 128000, | |
| 63 | + maxCompletionTokens: 4096, | |
| 64 | + description: | |
| 65 | + "Command R+ is a state-of-the-art RAG-optimized model designed to tackle enterprise-grade workloads.", | |
| 66 | + recommendedFor: ["chat"], | |
| 67 | + }, | |
| 68 | + { | |
| 69 | + model: "c4ai-aya-vision-32b", | |
| 70 | + displayName: "C4AI Aya Vision 32B", | |
| 71 | + contextLength: 16000, | |
| 72 | + maxCompletionTokens: 4096, | |
| 73 | + description: | |
| 74 | + "Aya Vision is a state-of-the-art multimodal and massively multilingual large language model excelling at critical benchmarks for language, text, and image capabilities.", | |
| 75 | + recommendedFor: ["chat"], | |
| 76 | + }, | |
| 77 | + { | |
| 78 | + model: "c4ai-aya-vision-8b", | |
| 79 | + displayName: "C4AI Aya Vision 8B", | |
| 80 | + contextLength: 16000, | |
| 81 | + maxCompletionTokens: 4096, | |
| 82 | + description: | |
| 83 | + "Aya Vision is a state-of-the-art multimodal and massively multilingual large language model excelling at critical benchmarks for language, text, and image capabilities.", | |
| 84 | + recommendedFor: ["chat"], | |
| 85 | + }, | |
| 86 | + { | |
| 87 | + model: "c4ai-aya-expanse-32b", | |
| 88 | + displayName: "C4AI Aya Expanse 32B", | |
| 8 | 89 | contextLength: 128000, |
| 9 | - maxCompletionTokens: 4000, | |
| 10 | - // recommendedFor: ["chat"], | |
| 90 | + maxCompletionTokens: 4096, | |
| 91 | + description: | |
| 92 | + "Aya Expanse is a massively multilingual large language model excelling in enterprise-scale tasks.", | |
| 93 | + recommendedFor: ["chat"], | |
| 11 | 94 | }, |
| 12 | 95 | { |
| 13 | - model: "command-r", | |
| 14 | - displayName: "Command R", | |
| 96 | + model: "c4ai-aya-expanse-8b", | |
| 97 | + displayName: "C4AI Aya Expanse 8B", | |
| 98 | + contextLength: 8000, | |
| 99 | + maxCompletionTokens: 4096, | |
| 100 | + description: | |
| 101 | + "Aya Expanse is a massively multilingual large language model excelling in enterprise-scale tasks.", | |
| 102 | + recommendedFor: ["chat"], | |
| 103 | + }, | |
| 104 | + { | |
| 105 | + model: "embed-v4.0", | |
| 106 | + displayName: "Embed v4.0", | |
| 107 | + description: | |
| 108 | + "A model that allows for text and images to be classified or turned into embeddings.", | |
| 109 | + recommendedFor: ["embed"], | |
| 15 | 110 | contextLength: 128000, |
| 16 | - maxCompletionTokens: 4000, | |
| 17 | 111 | }, |
| 18 | 112 | { |
| 19 | 113 | model: "embed-english-v3.0", |
| 20 | - displayName: "Embed English 3.0", | |
| 21 | - // recommendedFor: ["embed"], | |
| 114 | + displayName: "Embed English v3.0", | |
| 115 | + description: | |
| 116 | + "A model that allows for text to be classified or turned into embeddings. English only.", | |
| 117 | + recommendedFor: ["embed"], | |
| 118 | + contextLength: 512, | |
| 119 | + }, | |
| 120 | + { | |
| 121 | + model: "embed-english-light-v3.0", | |
| 122 | + displayName: "Embed English Light v3.0", | |
| 123 | + description: | |
| 124 | + "A smaller, faster version of embed-english-v3.0. Almost as capable, but a lot faster. English only.", | |
| 125 | + recommendedFor: ["embed"], | |
| 22 | 126 | contextLength: 512, |
| 23 | 127 | }, |
| 128 | + { | |
| 129 | + model: "embed-multilingual-v3.0", | |
| 130 | + displayName: "Embed Multilingual v3.0", | |
| 131 | + description: | |
| 132 | + "Provides multilingual classification and embedding support.", | |
| 133 | + recommendedFor: ["embed"], | |
| 134 | + contextLength: 512, | |
| 135 | + }, | |
| 136 | + { | |
| 137 | + model: "embed-multilingual-light-v3.0", | |
| 138 | + displayName: "Embed Multilingual Light v3.0", | |
| 139 | + description: | |
| 140 | + "A smaller, faster version of embed-multilingual-v3.0. Almost as capable, but a lot faster.", | |
| 141 | + recommendedFor: ["embed"], | |
| 142 | + contextLength: 512, | |
| 143 | + }, | |
| 144 | + { | |
| 145 | + model: "rerank-v3.5", | |
| 146 | + displayName: "Rerank v3.5", | |
| 147 | + description: | |
| 148 | + "A model for documents and semi-structured data (JSON). State-of-the-art performance in English and non-English languages.", | |
| 149 | + recommendedFor: ["rerank"], | |
| 150 | + contextLength: 4096, | |
| 151 | + }, | |
| 24 | 152 | { |
| 25 | 153 | model: "rerank-english-v3.0", |
| 26 | - displayName: "Rerank English 3.0", | |
| 27 | - // recommendedFor: ["rerank"], | |
| 28 | - contextLength: 4000, | |
| 154 | + displayName: "Rerank English v3.0", | |
| 155 | + description: | |
| 156 | + "A model that allows for re-ranking English Language documents and semi-structured data (JSON).", | |
| 157 | + recommendedFor: ["rerank"], | |
| 158 | + contextLength: 4096, | |
| 159 | + }, | |
| 160 | + { | |
| 161 | + model: "rerank-multilingual-v3.0", | |
| 162 | + displayName: "Rerank Multilingual v3.0", | |
| 163 | + description: | |
| 164 | + "A model for documents and semi-structure data (JSON) that are not in English.", | |
| 165 | + recommendedFor: ["rerank"], | |
| 166 | + contextLength: 4096, | |
| 29 | 167 | }, |
| 30 | 168 | ], |
| 31 | 169 | id: "cohere", |
modified packages/openai-adapters/src/test/main.test.ts +2 −2
| @@ -85,7 +85,7 @@ | ||
| 85 | 85 | }, |
| 86 | 86 | // { |
| 87 | 87 | // provider: "cohere", |
| 88 | - // model: "embed-english-v3.0", | |
| 88 | + // model: "embed-v4.0", | |
| 89 | 89 | // apiKey: process.env.COHERE_API_KEY!, |
| 90 | 90 | // roles: ["embed"], |
| 91 | 91 | // }, |
| @@ -103,7 +103,7 @@ | ||
| 103 | 103 | }, |
| 104 | 104 | // { |
| 105 | 105 | // provider: "cohere", |
| 106 | - // model: "rerank-english-v3.0", | |
| 106 | + // model: "rerank-v3.5", | |
| 107 | 107 | // apiKey: process.env.COHERE_API_KEY!, |
| 108 | 108 | // roles: ["rerank"], |
| 109 | 109 | // }, |