Changesets · Branches · Tags · Compare
| Changeset | bc28bda66fd73c6d9a43fab42383c807baa64f6da3d47ca9159deba8af138120 |
|---|---|
| Author | Nate <sestinj@gmail.com> · 2025-07-02 13:27 -07:00 |
| Committer | Nate <sestinj@gmail.com> · 2025-07-02 13:27 -07:00 |
| Parents | c4896f3cb05d, 83d435465f76 |
64 files changed
modified .github/workflows/jetbrains-release.yaml +2 −14
| @@ -167,20 +167,8 @@ | ||
| 167 | 167 | path: gui/node_modules |
| 168 | 168 | key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }} |
| 169 | 169 | |
| 170 | - - uses: actions/cache@v4 | |
| 171 | - id: config-yaml-cache | |
| 172 | - with: | |
| 173 | - path: packages/config-yaml/node_modules | |
| 174 | - key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} | |
| 175 | - | |
| 176 | - - name: Build and check config-yaml | |
| 177 | - run: | | |
| 178 | - cd ../../packages/config-yaml | |
| 179 | - npm i | |
| 180 | - npx tsc --noEmit | |
| 181 | - # Tests are currently failing, commenting out for now | |
| 182 | - # npm test | |
| 183 | - npm run build | |
| 170 | + - name: Build packages (Unix) | |
| 171 | + run: ./scripts/build-packages.sh | |
| 184 | 172 | |
| 185 | 173 | # npm install core |
| 186 | 174 | - name: Install core node_modules |
modified core/config/util.ts +1 −1
| @@ -10,7 +10,7 @@ | ||
| 10 | 10 | JSONModelDescription, |
| 11 | 11 | PromptTemplate, |
| 12 | 12 | } from "../"; |
| 13 | -import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../llm/constructMessages"; | |
| 13 | +import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../llm/defaultSystemMessages"; | |
| 14 | 14 | import { GlobalContext } from "../util/GlobalContext"; |
| 15 | 15 | import { editConfigFile } from "../util/paths"; |
| 16 | 16 |
modified core/context/providers/index.ts +9 −1
| @@ -1,5 +1,6 @@ | ||
| 1 | 1 | import { BaseContextProvider } from "../"; |
| 2 | 2 | import { ContextProviderName } from "../../"; |
| 3 | +import { Telemetry } from "../../util/posthog"; | |
| 3 | 4 | |
| 4 | 5 | import ClipboardContextProvider from "./ClipboardContextProvider"; |
| 5 | 6 | import CodebaseContextProvider from "./CodebaseContextProvider"; |
| @@ -75,5 +76,12 @@ | ||
| 75 | 76 | export function contextProviderClassFromName( |
| 76 | 77 | name: ContextProviderName, |
| 77 | 78 | ): typeof BaseContextProvider | undefined { |
| 78 | - return Providers.find((cls) => cls.description.title === name); | |
| 79 | + const provider = Providers.find((cls) => cls.description.title === name); | |
| 80 | + | |
| 81 | + void Telemetry.capture("context_provider_load", { | |
| 82 | + providerName: name, | |
| 83 | + found: !!provider, // also capture those which user expected to be present | |
| 84 | + }); | |
| 85 | + | |
| 86 | + return provider; | |
| 79 | 87 | } |
modified core/core.ts +7 −1
| @@ -872,7 +872,7 @@ | ||
| 872 | 872 | this.messenger.send("toolCallPartialOutput", params); |
| 873 | 873 | }; |
| 874 | 874 | |
| 875 | - return await callTool(tool, toolCall, { | |
| 875 | + const result = await callTool(tool, toolCall, { | |
| 876 | 876 | config, |
| 877 | 877 | ide: this.ide, |
| 878 | 878 | llm: config.selectedModelByRole.chat, |
| @@ -883,6 +883,8 @@ | ||
| 883 | 883 | onPartialOutput, |
| 884 | 884 | codeBaseIndexer: this.codeBaseIndexer, |
| 885 | 885 | }); |
| 886 | + | |
| 887 | + return result; | |
| 886 | 888 | } |
| 887 | 889 | |
| 888 | 890 | private async isItemTooBig(item: ContextItemWithId) { |
| @@ -1105,6 +1107,10 @@ | ||
| 1105 | 1107 | itemId: uuidv4(), |
| 1106 | 1108 | }; |
| 1107 | 1109 | |
| 1110 | + void Telemetry.capture("context_provider_get_context_items", { | |
| 1111 | + name: provider.description.title, | |
| 1112 | + }); | |
| 1113 | + | |
| 1108 | 1114 | const items = await provider.getContextItems(query, { |
| 1109 | 1115 | config, |
| 1110 | 1116 | llm, |
modified core/edit/streamDiffLines.ts +2 −2
| @@ -112,7 +112,7 @@ | ||
| 112 | 112 | // If any rules are present this will result in using chat instead of legacy completion |
| 113 | 113 | const systemMessage = rulesToInclude |
| 114 | 114 | ? getSystemMessageWithRules({ |
| 115 | - rules: rulesToInclude, | |
| 115 | + availableRules: rulesToInclude, | |
| 116 | 116 | userMessage: |
| 117 | 117 | typeof prompt === "string" |
| 118 | 118 | ? ({ |
| @@ -125,7 +125,7 @@ | ||
| 125 | 125 | ) as UserChatMessage | ToolResultChatMessage | undefined), |
| 126 | 126 | baseSystemMessage: undefined, |
| 127 | 127 | contextItems: [], |
| 128 | - }) | |
| 128 | + }).systemMessage | |
| 129 | 129 | : undefined; |
| 130 | 130 | |
| 131 | 131 | if (systemMessage) { |
deleted core/llm/constructMessages.ts +0 −187
| @@ -1,187 +0,0 @@ | ||
| 1 | -import { | |
| 2 | - ChatHistoryItem, | |
| 3 | - ChatMessage, | |
| 4 | - ContextItemWithId, | |
| 5 | - RuleWithSource, | |
| 6 | - TextMessagePart, | |
| 7 | - ToolResultChatMessage, | |
| 8 | - UserChatMessage, | |
| 9 | -} from "../"; | |
| 10 | -import { findLast } from "../util/findLast"; | |
| 11 | -import { normalizeToMessageParts } from "../util/messageContent"; | |
| 12 | -import { isUserOrToolMsg } from "./messages"; | |
| 13 | -import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules"; | |
| 14 | -import { RulePolicies } from "./rules/types"; | |
| 15 | - | |
| 16 | -export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL = | |
| 17 | - "https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts"; | |
| 18 | - | |
| 19 | -export const DEFAULT_AGENT_SYSTEM_MESSAGE_URL = | |
| 20 | - "https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts"; | |
| 21 | - | |
| 22 | -export const CODEBLOCK_FORMATTING_INSTRUCTIONS = `\ | |
| 23 | - Always include the language and file name in the info string when you write code blocks. | |
| 24 | - If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py' | |
| 25 | -`; | |
| 26 | - | |
| 27 | -export const EDIT_CODE_INSTRUCTIONS = `\ | |
| 28 | - When addressing code modification requests, present a concise code snippet that | |
| 29 | - emphasizes only the necessary changes and uses abbreviated placeholders for | |
| 30 | - unmodified sections. For example: | |
| 31 | - | |
| 32 | - \`\`\`language /path/to/file | |
| 33 | - // ... existing code ... | |
| 34 | - | |
| 35 | - {{ modified code here }} | |
| 36 | - | |
| 37 | - // ... existing code ... | |
| 38 | - | |
| 39 | - {{ another modification }} | |
| 40 | - | |
| 41 | - // ... rest of code ... | |
| 42 | - \`\`\` | |
| 43 | - | |
| 44 | - In existing files, you should always restate the function or class that the snippet belongs to: | |
| 45 | - | |
| 46 | - \`\`\`language /path/to/file | |
| 47 | - // ... existing code ... | |
| 48 | - | |
| 49 | - function exampleFunction() { | |
| 50 | - // ... existing code ... | |
| 51 | - | |
| 52 | - {{ modified code here }} | |
| 53 | - | |
| 54 | - // ... rest of function ... | |
| 55 | - } | |
| 56 | - | |
| 57 | - // ... rest of code ... | |
| 58 | - \`\`\` | |
| 59 | - | |
| 60 | - Since users have access to their complete file, they prefer reading only the | |
| 61 | - relevant modifications. It's perfectly acceptable to omit unmodified portions | |
| 62 | - at the beginning, middle, or end of files using these "lazy" comments. Only | |
| 63 | - provide the complete file when explicitly requested. Include a concise explanation | |
| 64 | - of changes unless the user specifically asks for code only. | |
| 65 | -`; | |
| 66 | - | |
| 67 | -export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\ | |
| 68 | -<important_rules> | |
| 69 | - You are in chat mode. | |
| 70 | - | |
| 71 | - If the user asks to make changes to files offer that they can use the Apply Button on the code block, or switch to Agent Mode to make the suggested updates automatically. | |
| 72 | - If needed consisely explain to the user they can switch to agent mode using the Mode Selector dropdown and provide no other details. | |
| 73 | - | |
| 74 | -${CODEBLOCK_FORMATTING_INSTRUCTIONS} | |
| 75 | -${EDIT_CODE_INSTRUCTIONS} | |
| 76 | -</important_rules>`; | |
| 77 | - | |
| 78 | -export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\ | |
| 79 | -<important_rules> | |
| 80 | - You are in agent mode. | |
| 81 | - | |
| 82 | -${CODEBLOCK_FORMATTING_INSTRUCTIONS} | |
| 83 | -</important_rules>`; | |
| 84 | - | |
| 85 | -/** | |
| 86 | - * Helper function to get the context items for a user message | |
| 87 | - */ | |
| 88 | -function getUserContextItems( | |
| 89 | - userMsg: UserChatMessage | ToolResultChatMessage | undefined, | |
| 90 | - history: ChatHistoryItem[], | |
| 91 | -): ContextItemWithId[] { | |
| 92 | - if (!userMsg) return []; | |
| 93 | - | |
| 94 | - // Find the history item that contains the userMsg | |
| 95 | - const historyItem = history.find((item) => { | |
| 96 | - // Check if the message ID matches | |
| 97 | - if ("id" in userMsg && "id" in item.message) { | |
| 98 | - return (item.message as any).id === (userMsg as any).id; | |
| 99 | - } | |
| 100 | - // Fallback to content comparison | |
| 101 | - return ( | |
| 102 | - item.message.content === userMsg.content && | |
| 103 | - item.message.role === userMsg.role | |
| 104 | - ); | |
| 105 | - }); | |
| 106 | - | |
| 107 | - return historyItem?.contextItems || []; | |
| 108 | -} | |
| 109 | - | |
| 110 | -export function constructMessages( | |
| 111 | - messageMode: string, | |
| 112 | - history: ChatHistoryItem[], | |
| 113 | - baseChatOrAgentSystemMessage: string | undefined, | |
| 114 | - rules: RuleWithSource[], | |
| 115 | - rulePolicies?: RulePolicies, | |
| 116 | -): ChatMessage[] { | |
| 117 | - const filteredHistory = history.filter( | |
| 118 | - (item) => item.message.role !== "system", | |
| 119 | - ); | |
| 120 | - const msgs: ChatMessage[] = []; | |
| 121 | - | |
| 122 | - for (let i = 0; i < filteredHistory.length; i++) { | |
| 123 | - const historyItem = filteredHistory[i]; | |
| 124 | - | |
| 125 | - if (messageMode === "chat") { | |
| 126 | - const toolMessage: ToolResultChatMessage = | |
| 127 | - historyItem.message as ToolResultChatMessage; | |
| 128 | - if (historyItem.toolCallState?.toolCallId || toolMessage.toolCallId) { | |
| 129 | - // remove all tool calls from the history | |
| 130 | - continue; | |
| 131 | - } | |
| 132 | - } | |
| 133 | - | |
| 134 | - if (historyItem.message.role === "user") { | |
| 135 | - // Gather context items for user messages | |
| 136 | - let content = normalizeToMessageParts(historyItem.message); | |
| 137 | - | |
| 138 | - const ctxItems = historyItem.contextItems | |
| 139 | - .map((ctxItem) => { | |
| 140 | - return { | |
| 141 | - type: "text", | |
| 142 | - text: `${ctxItem.content}\n`, | |
| 143 | - } as TextMessagePart; | |
| 144 | - }) | |
| 145 | - .filter((part) => !!part.text.trim()); | |
| 146 | - | |
| 147 | - content = [...ctxItems, ...content]; | |
| 148 | - msgs.push({ | |
| 149 | - ...historyItem.message, | |
| 150 | - content, | |
| 151 | - }); | |
| 152 | - } else { | |
| 153 | - msgs.push(historyItem.message); | |
| 154 | - } | |
| 155 | - } | |
| 156 | - | |
| 157 | - const lastUserMsg = findLast(msgs, isUserOrToolMsg) as | |
| 158 | - | UserChatMessage | |
| 159 | - | ToolResultChatMessage | |
| 160 | - | undefined; | |
| 161 | - | |
| 162 | - // Get context items for the last user message | |
| 163 | - const lastUserContextItems = getUserContextItems( | |
| 164 | - lastUserMsg, | |
| 165 | - filteredHistory, | |
| 166 | - ); | |
| 167 | - const systemMessage = getSystemMessageWithRules({ | |
| 168 | - baseSystemMessage: baseChatOrAgentSystemMessage, | |
| 169 | - rules, | |
| 170 | - userMessage: lastUserMsg, | |
| 171 | - contextItems: lastUserContextItems, | |
| 172 | - rulePolicies, | |
| 173 | - }); | |
| 174 | - | |
| 175 | - if (systemMessage.trim()) { | |
| 176 | - msgs.unshift({ | |
| 177 | - role: "system", | |
| 178 | - content: systemMessage, | |
| 179 | - }); | |
| 180 | - } | |
| 181 | - | |
| 182 | - // Remove the "id" from all of the messages | |
| 183 | - return msgs.map((msg) => { | |
| 184 | - const { id, ...rest } = msg as any; | |
| 185 | - return rest; | |
| 186 | - }); | |
| 187 | -} |
added core/llm/defaultSystemMessages.ts +68 −0
| @@ -0,0 +1,68 @@ | ||
| 1 | +export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL = | |
| 2 | + "https://github.com/continuedev/continue/blob/main/core/llm/defaultSystemMessages.ts"; | |
| 3 | + | |
| 4 | +export const DEFAULT_AGENT_SYSTEM_MESSAGE_URL = | |
| 5 | + "https://github.com/continuedev/continue/blob/main/core/llm/defaultSystemMessages.ts"; | |
| 6 | + | |
| 7 | +export const CODEBLOCK_FORMATTING_INSTRUCTIONS = `\ | |
| 8 | + Always include the language and file name in the info string when you write code blocks. | |
| 9 | + If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py' | |
| 10 | +`; | |
| 11 | + | |
| 12 | +export const EDIT_CODE_INSTRUCTIONS = `\ | |
| 13 | + When addressing code modification requests, present a concise code snippet that | |
| 14 | + emphasizes only the necessary changes and uses abbreviated placeholders for | |
| 15 | + unmodified sections. For example: | |
| 16 | + | |
| 17 | + \`\`\`language /path/to/file | |
| 18 | + // ... existing code ... | |
| 19 | + | |
| 20 | + {{ modified code here }} | |
| 21 | + | |
| 22 | + // ... existing code ... | |
| 23 | + | |
| 24 | + {{ another modification }} | |
| 25 | + | |
| 26 | + // ... rest of code ... | |
| 27 | + \`\`\` | |
| 28 | + | |
| 29 | + In existing files, you should always restate the function or class that the snippet belongs to: | |
| 30 | + | |
| 31 | + \`\`\`language /path/to/file | |
| 32 | + // ... existing code ... | |
| 33 | + | |
| 34 | + function exampleFunction() { | |
| 35 | + // ... existing code ... | |
| 36 | + | |
| 37 | + {{ modified code here }} | |
| 38 | + | |
| 39 | + // ... rest of function ... | |
| 40 | + } | |
| 41 | + | |
| 42 | + // ... rest of code ... | |
| 43 | + \`\`\` | |
| 44 | + | |
| 45 | + Since users have access to their complete file, they prefer reading only the | |
| 46 | + relevant modifications. It's perfectly acceptable to omit unmodified portions | |
| 47 | + at the beginning, middle, or end of files using these "lazy" comments. Only | |
| 48 | + provide the complete file when explicitly requested. Include a concise explanation | |
| 49 | + of changes unless the user specifically asks for code only. | |
| 50 | +`; | |
| 51 | + | |
| 52 | +export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\ | |
| 53 | +<important_rules> | |
| 54 | + You are in chat mode. | |
| 55 | + | |
| 56 | + If the user asks to make changes to files offer that they can use the Apply Button on the code block, or switch to Agent Mode to make the suggested updates automatically. | |
| 57 | + If needed consisely explain to the user they can switch to agent mode using the Mode Selector dropdown and provide no other details. | |
| 58 | + | |
| 59 | +${CODEBLOCK_FORMATTING_INSTRUCTIONS} | |
| 60 | +${EDIT_CODE_INSTRUCTIONS} | |
| 61 | +</important_rules>`; | |
| 62 | + | |
| 63 | +export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\ | |
| 64 | +<important_rules> | |
| 65 | + You are in agent mode. | |
| 66 | + | |
| 67 | +${CODEBLOCK_FORMATTING_INSTRUCTIONS} | |
| 68 | +</important_rules>`; |
modified core/llm/llms/Bedrock.test.ts +248 −80
| @@ -1,12 +1,10 @@ | ||
| 1 | -import { BedrockRuntimeClient } from "@aws-sdk/client-bedrock-runtime"; | |
| 2 | -import { fromNodeProviderChain } from "@aws-sdk/credential-providers"; | |
| 3 | -import Bedrock from "./Bedrock.js"; | |
| 4 | 1 | import { |
| 5 | 2 | ChatMessage, |
| 6 | 3 | Chunk, |
| 7 | 4 | CompletionOptions, |
| 8 | 5 | UserChatMessage, |
| 9 | 6 | } from "../../index.js"; |
| 7 | +import Bedrock from "./Bedrock.js"; | |
| 10 | 8 | |
| 11 | 9 | // Mock AWS SDK |
| 12 | 10 | jest.mock("@aws-sdk/client-bedrock-runtime", () => ({ |
| @@ -317,96 +315,266 @@ | ||
| 317 | 315 | }); |
| 318 | 316 | }); |
| 319 | 317 | |
| 320 | - it("should convert text messages correctly", () => { | |
| 321 | - const message: ChatMessage = { | |
| 322 | - role: "user", | |
| 323 | - content: "Hello", | |
| 324 | - } as UserChatMessage; | |
| 325 | - const converted = bedrock["_convertMessage"](message); | |
| 326 | - expect(converted).toEqual({ | |
| 327 | - role: "user", | |
| 328 | - content: [{ text: "Hello" }], | |
| 329 | - }); | |
| 318 | + it("should convert simple user and assistant messages correctly", () => { | |
| 319 | + const messages: ChatMessage[] = [ | |
| 320 | + { role: "user", content: "Hello" } as UserChatMessage, | |
| 321 | + { role: "assistant", content: "Hi there" }, | |
| 322 | + ]; | |
| 323 | + | |
| 324 | + const availableTools = new Set<string>(); | |
| 325 | + const converted = bedrock["_convertMessages"](messages, availableTools); | |
| 326 | + | |
| 327 | + expect(converted).toEqual([ | |
| 328 | + { role: "user", content: [{ text: "Hello" }] }, | |
| 329 | + { role: "assistant", content: [{ text: "Hi there" }] }, | |
| 330 | + ]); | |
| 330 | 331 | }); |
| 331 | 332 | |
| 332 | - it("should convert tool responses correctly", () => { | |
| 333 | - const message: ChatMessage = { | |
| 334 | - role: "tool", | |
| 335 | - content: "Tool result", | |
| 336 | - toolCallId: "tool-1", | |
| 337 | - }; | |
| 338 | - const converted = bedrock["_convertMessage"](message); | |
| 339 | - expect(converted).toEqual({ | |
| 340 | - role: "user", | |
| 341 | - content: [ | |
| 342 | - { | |
| 343 | - toolResult: { | |
| 344 | - toolUseId: "tool-1", | |
| 345 | - content: [{ text: "Tool result" }], | |
| 333 | + it("should handle tool responses correctly", () => { | |
| 334 | + const messages: ChatMessage[] = [ | |
| 335 | + { role: "user", content: "Use a tool" } as UserChatMessage, | |
| 336 | + { | |
| 337 | + role: "assistant", | |
| 338 | + content: "", | |
| 339 | + toolCalls: [ | |
| 340 | + { | |
| 341 | + id: "tool-1", | |
| 342 | + type: "function", | |
| 343 | + function: { | |
| 344 | + name: "test_tool", | |
| 345 | + arguments: '{"arg":"value"}', | |
| 346 | + }, | |
| 346 | 347 | }, |
| 347 | - }, | |
| 348 | - ], | |
| 349 | - }); | |
| 348 | + ], | |
| 349 | + }, | |
| 350 | + { | |
| 351 | + role: "tool", | |
| 352 | + content: "Tool result", | |
| 353 | + toolCallId: "tool-1", | |
| 354 | + }, | |
| 355 | + ]; | |
| 356 | + | |
| 357 | + const availableTools = new Set(["test_tool"]); | |
| 358 | + const converted = bedrock["_convertMessages"](messages, availableTools); | |
| 359 | + | |
| 360 | + expect(converted).toEqual([ | |
| 361 | + { role: "user", content: [{ text: "Use a tool" }] }, | |
| 362 | + { | |
| 363 | + role: "assistant", | |
| 364 | + content: [ | |
| 365 | + { | |
| 366 | + toolUse: { | |
| 367 | + toolUseId: "tool-1", | |
| 368 | + name: "test_tool", | |
| 369 | + input: { arg: "value" }, | |
| 370 | + }, | |
| 371 | + }, | |
| 372 | + ], | |
| 373 | + }, | |
| 374 | + { | |
| 375 | + role: "user", | |
| 376 | + content: [ | |
| 377 | + { | |
| 378 | + toolResult: { | |
| 379 | + toolUseId: "tool-1", | |
| 380 | + content: [{ text: "Tool result" }], | |
| 381 | + }, | |
| 382 | + }, | |
| 383 | + ], | |
| 384 | + }, | |
| 385 | + ]); | |
| 350 | 386 | }); |
| 351 | 387 | |
| 352 | - it("should convert tool calls correctly", () => { | |
| 353 | - const message: ChatMessage = { | |
| 354 | - role: "assistant", | |
| 355 | - content: "", | |
| 356 | - toolCalls: [ | |
| 357 | - { | |
| 358 | - id: "tool-1", | |
| 359 | - type: "function" as const, | |
| 360 | - function: { | |
| 361 | - name: "test_tool", | |
| 362 | - arguments: '{"arg":"value"}', | |
| 388 | + it("should handle tool calls with unavailable tools as text", () => { | |
| 389 | + const messages: ChatMessage[] = [ | |
| 390 | + { role: "user", content: "Use a tool" } as UserChatMessage, | |
| 391 | + { | |
| 392 | + role: "assistant", | |
| 393 | + content: "", | |
| 394 | + toolCalls: [ | |
| 395 | + { | |
| 396 | + id: "tool-1", | |
| 397 | + type: "function", | |
| 398 | + function: { | |
| 399 | + name: "unavailable_tool", | |
| 400 | + arguments: '{"arg":"value"}', | |
| 401 | + }, | |
| 363 | 402 | }, |
| 364 | - }, | |
| 365 | - ], | |
| 366 | - }; | |
| 367 | - const converted = bedrock["_convertMessage"](message); | |
| 368 | - expect(converted).toEqual({ | |
| 369 | - role: "assistant", | |
| 370 | - content: [ | |
| 371 | - { | |
| 372 | - toolUse: { | |
| 373 | - toolUseId: "tool-1", | |
| 374 | - name: "test_tool", | |
| 375 | - input: { arg: "value" }, | |
| 403 | + ], | |
| 404 | + }, | |
| 405 | + ]; | |
| 406 | + | |
| 407 | + // Empty set means no tools are available | |
| 408 | + const availableTools = new Set<string>(); | |
| 409 | + const converted = bedrock["_convertMessages"](messages, availableTools); | |
| 410 | + | |
| 411 | + expect(converted).toEqual([ | |
| 412 | + { role: "user", content: [{ text: "Use a tool" }] }, | |
| 413 | + { | |
| 414 | + role: "assistant", | |
| 415 | + content: [ | |
| 416 | + { | |
| 417 | + text: expect.stringContaining("Assistant tool call:"), | |
| 376 | 418 | }, |
| 377 | - }, | |
| 378 | - ], | |
| 379 | - }); | |
| 419 | + ], | |
| 420 | + }, | |
| 421 | + ]); | |
| 380 | 422 | }); |
| 381 | 423 | |
| 382 | - it("should handle multimodal content correctly", () => { | |
| 383 | - const message: ChatMessage = { | |
| 384 | - role: "user", | |
| 385 | - content: [ | |
| 386 | - { type: "text", text: "Look at this image:" }, | |
| 387 | - { | |
| 388 | - type: "imageUrl", | |
| 389 | - imageUrl: { | |
| 390 | - url: "data:image/jpeg;base64,/9j/4AAQSkZJRg==", | |
| 424 | + it("should handle thinking messages correctly", () => { | |
| 425 | + const messages: ChatMessage[] = [ | |
| 426 | + { role: "user", content: "Think about this" } as UserChatMessage, | |
| 427 | + { role: "thinking", content: "I am thinking about the solution" }, | |
| 428 | + { role: "assistant", content: "Here's my answer" }, | |
| 429 | + ]; | |
| 430 | + | |
| 431 | + const availableTools = new Set<string>(); | |
| 432 | + const converted = bedrock["_convertMessages"](messages, availableTools); | |
| 433 | + | |
| 434 | + expect(converted).toEqual([ | |
| 435 | + { role: "user", content: [{ text: "Think about this" }] }, | |
| 436 | + { | |
| 437 | + role: "assistant", | |
| 438 | + content: [ | |
| 439 | + { | |
| 440 | + reasoningContent: { | |
| 441 | + reasoningText: { | |
| 442 | + text: "I am thinking about the solution", | |
| 443 | + signature: undefined, | |
| 444 | + }, | |
| 445 | + }, | |
| 391 | 446 | }, |
| 392 | - }, | |
| 393 | - ], | |
| 394 | - } as UserChatMessage; | |
| 395 | - const converted = bedrock["_convertMessage"](message); | |
| 396 | - expect(converted).toEqual({ | |
| 397 | - role: "user", | |
| 398 | - content: [ | |
| 399 | - { text: "Look at this image:" }, | |
| 400 | - { | |
| 401 | - image: { | |
| 402 | - format: "jpeg", | |
| 403 | - source: { | |
| 404 | - bytes: Buffer.from("/9j/4AAQSkZJRg==", "base64"), | |
| 447 | + { text: "Here's my answer" }, | |
| 448 | + ], | |
| 449 | + }, | |
| 450 | + ]); | |
| 451 | + }); | |
| 452 | + | |
| 453 | + it("should handle redacted thinking messages", () => { | |
| 454 | + const messages: ChatMessage[] = [ | |
| 455 | + { role: "user", content: "Think about this" } as UserChatMessage, | |
| 456 | + { | |
| 457 | + role: "thinking", | |
| 458 | + content: "", | |
| 459 | + redactedThinking: "redacted-content-bytes", | |
| 460 | + }, | |
| 461 | + { role: "assistant", content: "Here's my answer" }, | |
| 462 | + ]; | |
| 463 | + | |
| 464 | + const availableTools = new Set<string>(); | |
| 465 | + const converted = bedrock["_convertMessages"](messages, availableTools); | |
| 466 | + | |
| 467 | + expect(converted).toEqual([ | |
| 468 | + { role: "user", content: [{ text: "Think about this" }] }, | |
| 469 | + { | |
| 470 | + role: "assistant", | |
| 471 | + content: [ | |
| 472 | + { | |
| 473 | + reasoningContent: { | |
| 474 | + redactedContent: expect.any(Uint8Array), | |
| 405 | 475 | }, |
| 406 | 476 | }, |
| 407 | - }, | |
| 408 | - ], | |
| 477 | + { text: "Here's my answer" }, | |
| 478 | + ], | |
| 479 | + }, | |
| 480 | + ]); | |
| 481 | + | |
| 482 | + // Check that the Uint8Array contains the expected bytes | |
| 483 | + const redactedContent = | |
| 484 | + converted[1].content?.[0].reasoningContent?.redactedContent; | |
| 485 | + expect(redactedContent).toBeInstanceOf(Uint8Array); | |
| 486 | + expect(Buffer.from(redactedContent!).toString()).toBe( | |
| 487 | + "redacted-content-bytes", | |
| 488 | + ); | |
| 489 | + }); | |
| 490 | + | |
| 491 | + it("should convert multimodal content correctly", () => { | |
| 492 | + const messages: ChatMessage[] = [ | |
| 493 | + { | |
| 494 | + role: "user", | |
| 495 | + content: [ | |
| 496 | + { type: "text", text: "Look at this image:" }, | |
| 497 | + { | |
| 498 | + type: "imageUrl", | |
| 499 | + imageUrl: { | |
| 500 | + url: "data:image/jpeg;base64,/9j/4AAQSkZJRg==", | |
| 501 | + }, | |
| 502 | + }, | |
| 503 | + ], | |
| 504 | + } as UserChatMessage, | |
| 505 | + ]; | |
| 506 | + | |
| 507 | + const availableTools = new Set<string>(); | |
| 508 | + const converted = bedrock["_convertMessages"](messages, availableTools); | |
| 509 | + | |
| 510 | + expect(converted).toEqual([ | |
| 511 | + { | |
| 512 | + role: "user", | |
| 513 | + content: [ | |
| 514 | + { text: "Look at this image:" }, | |
| 515 | + { | |
| 516 | + image: { | |
| 517 | + format: "jpeg", | |
| 518 | + source: { | |
| 519 | + bytes: expect.any(Uint8Array), | |
| 520 | + }, | |
| 521 | + }, | |
| 522 | + }, | |
| 523 | + ], | |
| 524 | + }, | |
| 525 | + ]); | |
| 526 | + | |
| 527 | + // Check that the image bytes were processed correctly | |
| 528 | + const imageBytes = converted[0].content?.[1].image?.source?.bytes; | |
| 529 | + expect(imageBytes).toBeInstanceOf(Uint8Array); | |
| 530 | + expect(Buffer.from(imageBytes!).toString("base64")).toBe( | |
| 531 | + "/9j/4AAQSkZJRg==", | |
| 532 | + ); | |
| 533 | + }); | |
| 534 | + | |
| 535 | + it("should add cache points for prompt caching when needed", () => { | |
| 536 | + // Create a test instance with caching behavior enabled | |
| 537 | + const bedrockWithCaching = new TestBedrock({ | |
| 538 | + apiKey: "test-key", | |
| 539 | + model: "anthropic.claude-3-sonnet-20240229-v1:0", | |
| 540 | + region: "us-east-1", | |
| 409 | 541 | }); |
| 542 | + | |
| 543 | + // Set caching behavior | |
| 544 | + bedrockWithCaching.cacheBehavior = { | |
| 545 | + cacheConversation: true, | |
| 546 | + cacheSystemMessage: true, | |
| 547 | + }; | |
| 548 | + | |
| 549 | + const messages: ChatMessage[] = [ | |
| 550 | + { role: "system", content: "You are a helpful assistant" }, | |
| 551 | + { role: "user", content: "First message" } as UserChatMessage, | |
| 552 | + { role: "assistant", content: "First response" }, | |
| 553 | + { role: "user", content: "Second message" } as UserChatMessage, | |
| 554 | + ]; | |
| 555 | + | |
| 556 | + const availableTools = new Set<string>(); | |
| 557 | + const converted = bedrockWithCaching["_convertMessages"]( | |
| 558 | + messages, | |
| 559 | + availableTools, | |
| 560 | + ); | |
| 561 | + | |
| 562 | + // The last two user messages should have cache points | |
| 563 | + // But we're not testing the system message here since it's handled separately | |
| 564 | + expect(converted.length).toBe(3); | |
| 565 | + expect(converted[0].role).toBe("user"); | |
| 566 | + expect(converted[0].content?.some((block) => block.cachePoint)).toBe( | |
| 567 | + true, | |
| 568 | + ); | |
| 569 | + expect(converted[1].role).toBe("assistant"); | |
| 570 | + expect(converted[2].role).toBe("user"); | |
| 571 | + expect(converted[2].content?.some((block) => block.cachePoint)).toBe( | |
| 572 | + true, | |
| 573 | + ); | |
| 574 | + | |
| 575 | + // Verify that text content includes a cache ID suffix | |
| 576 | + const userMessageText = converted[0].content?.[0].text; | |
| 577 | + expect(userMessageText).toMatch(/First message.+/); | |
| 410 | 578 | }); |
| 411 | 579 | }); |
| 412 | 580 | }); |
modified core/llm/llms/Bedrock.ts +236 −159
| @@ -1,8 +1,10 @@ | ||
| 1 | 1 | import { |
| 2 | 2 | BedrockRuntimeClient, |
| 3 | 3 | ContentBlock, |
| 4 | + ConversationRole, | |
| 4 | 5 | ConverseStreamCommand, |
| 5 | 6 | ConverseStreamCommandOutput, |
| 7 | + ImageFormat, | |
| 6 | 8 | InvokeModelCommand, |
| 7 | 9 | Message, |
| 8 | 10 | ToolConfiguration, |
| @@ -14,6 +16,7 @@ | ||
| 14 | 16 | Chunk, |
| 15 | 17 | CompletionOptions, |
| 16 | 18 | LLMOptions, |
| 19 | + MessageContent, | |
| 17 | 20 | } from "../../index.js"; |
| 18 | 21 | import { safeParseToolCallArgs } from "../../tools/parseArgs.js"; |
| 19 | 22 | import { renderChatMessage, stripImages } from "../../util/messageContent.js"; |
| @@ -289,8 +292,8 @@ | ||
| 289 | 292 | const systemMessage = stripImages( |
| 290 | 293 | messages.find((m) => m.role === "system")?.content ?? "", |
| 291 | 294 | ); |
| 292 | - const convertedMessages = this._convertMessages(messages); | |
| 293 | 295 | |
| 296 | + // Prompt and system message caching settings | |
| 294 | 297 | const shouldCacheSystemMessage = |
| 295 | 298 | (!!systemMessage && this.cacheBehavior?.cacheSystemMessage) || |
| 296 | 299 | this.completionOptions.promptCaching; |
| @@ -298,9 +301,7 @@ | ||
| 298 | 301 | shouldCacheSystemMessage || |
| 299 | 302 | this.cacheBehavior?.cacheConversation || |
| 300 | 303 | this.completionOptions.promptCaching; |
| 301 | - const shouldCacheToolsConfig = this.completionOptions.promptCaching; | |
| 302 | 304 | |
| 303 | - // Add header for prompt caching | |
| 304 | 305 | if (enablePromptCaching) { |
| 305 | 306 | this.requestOptions.headers = { |
| 306 | 307 | ...this.requestOptions.headers, |
| @@ -308,30 +309,37 @@ | ||
| 308 | 309 | }; |
| 309 | 310 | } |
| 310 | 311 | |
| 312 | + // First get tools | |
| 311 | 313 | const supportsTools = |
| 312 | 314 | (this.capabilities?.tools || |
| 313 | 315 | PROVIDER_TOOL_SUPPORT.bedrock?.(options.model)) ?? |
| 314 | 316 | false; |
| 315 | 317 | |
| 316 | - let toolConfig = | |
| 317 | - supportsTools && options.tools | |
| 318 | - ? ({ | |
| 319 | - tools: options.tools.map((tool) => ({ | |
| 320 | - toolSpec: { | |
| 321 | - name: tool.function.name, | |
| 322 | - description: tool.function.description, | |
| 323 | - inputSchema: { | |
| 324 | - json: tool.function.parameters, | |
| 325 | - }, | |
| 326 | - }, | |
| 327 | - })), | |
| 328 | - } as ToolConfiguration) | |
| 329 | - : undefined; | |
| 330 | - | |
| 331 | - if (toolConfig?.tools && shouldCacheToolsConfig) { | |
| 332 | - toolConfig.tools.push({ cachePoint: { type: "default" } }); | |
| 318 | + let toolConfig: undefined | ToolConfiguration = undefined; | |
| 319 | + const availableTools = new Set<string>(); | |
| 320 | + if (supportsTools && options.tools && options.tools.length > 0) { | |
| 321 | + toolConfig = { | |
| 322 | + tools: options.tools.map((tool) => ({ | |
| 323 | + toolSpec: { | |
| 324 | + name: tool.function.name, | |
| 325 | + description: tool.function.description, | |
| 326 | + inputSchema: { | |
| 327 | + json: tool.function.parameters, | |
| 328 | + }, | |
| 329 | + }, | |
| 330 | + })), | |
| 331 | + } as ToolConfiguration; | |
| 332 | + const shouldCacheToolsConfig = this.completionOptions.promptCaching; | |
| 333 | + if (shouldCacheToolsConfig) { | |
| 334 | + toolConfig.tools!.push({ cachePoint: { type: "default" } }); | |
| 335 | + } | |
| 336 | + options.tools.forEach((tool) => { | |
| 337 | + availableTools.add(tool.function.name); | |
| 338 | + }); | |
| 333 | 339 | } |
| 334 | 340 | |
| 341 | + const convertedMessages = this._convertMessages(messages, availableTools); | |
| 342 | + | |
| 335 | 343 | return { |
| 336 | 344 | modelId: options.model, |
| 337 | 345 | system: systemMessage |
| @@ -368,167 +376,236 @@ | ||
| 368 | 376 | }; |
| 369 | 377 | } |
| 370 | 378 | |
| 371 | - private _convertMessage( | |
| 372 | - message: ChatMessage, | |
| 373 | - addCaching: boolean = false, | |
| 374 | - ): Message | null { | |
| 375 | - // Handle system messages explicitly | |
| 376 | - if (message.role === "system") { | |
| 377 | - return null; | |
| 378 | - } | |
| 379 | + /* | |
| 380 | + Converts the messages to the format expected by the Bedrock API. | |
| 381 | + | |
| 382 | + */ | |
| 383 | + private _convertMessages( | |
| 384 | + messages: ChatMessage[], | |
| 385 | + availableTools: Set<string>, | |
| 386 | + ): Message[] { | |
| 387 | + let currentRole: "user" | "assistant" = "user"; | |
| 388 | + let currentBlocks: ContentBlock[] = []; | |
| 389 | + | |
| 390 | + const converted: Message[] = []; | |
| 391 | + const pushCurrentMessage = () => { | |
| 392 | + if (currentBlocks.length === 0 && converted.length > 1) { | |
| 393 | + throw new Error( | |
| 394 | + `Bedrock: no content in ${currentRole} message before conversational turn change`, | |
| 395 | + ); | |
| 396 | + } | |
| 397 | + if (currentBlocks.length > 0) { | |
| 398 | + converted.push({ | |
| 399 | + role: currentRole, | |
| 400 | + content: currentBlocks, | |
| 401 | + }); | |
| 402 | + } | |
| 403 | + currentBlocks = []; | |
| 404 | + }; | |
| 379 | 405 | |
| 380 | - const cachePoint = addCaching | |
| 381 | - ? { cachePoint: { type: "default" } } | |
| 382 | - : undefined; | |
| 383 | - | |
| 384 | - // Tool response handling | |
| 385 | - if (message.role === "tool") { | |
| 386 | - return { | |
| 387 | - role: "user", | |
| 388 | - content: [ | |
| 389 | - { | |
| 390 | - toolResult: { | |
| 391 | - toolUseId: message.toolCallId, | |
| 392 | - content: [ | |
| 393 | - { | |
| 394 | - text: message.content || "", | |
| 406 | + const nonSystemMessages = messages.filter((m) => m.role !== "system"); | |
| 407 | + const hasAddedToolCallIds = new Set<string>(); | |
| 408 | + | |
| 409 | + for (let idx = 0; idx < nonSystemMessages.length; idx++) { | |
| 410 | + const message = nonSystemMessages[idx]; | |
| 411 | + | |
| 412 | + if (message.role === "user" || message.role === "tool") { | |
| 413 | + // Detect conversational turn change | |
| 414 | + if (currentRole !== ConversationRole.USER) { | |
| 415 | + pushCurrentMessage(); | |
| 416 | + currentRole = ConversationRole.USER; | |
| 417 | + } | |
| 418 | + | |
| 419 | + // USER messages: | |
| 420 | + // Non-empty user message content is converted to "text" and "image" blocks | |
| 421 | + // If ANY user message part is cached, we add a single cache point block when we push the message | |
| 422 | + if (message.role === "user") { | |
| 423 | + const trimmedContent = | |
| 424 | + typeof message.content === "string" | |
| 425 | + ? message.content.trim() | |
| 426 | + : message.content; | |
| 427 | + if (trimmedContent) { | |
| 428 | + currentBlocks.push( | |
| 429 | + ...this._convertMessageContentToBlocks(trimmedContent), | |
| 430 | + ); | |
| 431 | + } | |
| 432 | + } | |
| 433 | + // TOOL messages: | |
| 434 | + // Tool messages are represented by "toolResult" blocks | |
| 435 | + // toolResult blocks must follow valid toolUse blocks (which also verifies that the tool name is present in toolConfig) | |
| 436 | + // If it doesn't, we convert it to a text block | |
| 437 | + else if (message.role === "tool") { | |
| 438 | + const trimmedContent = message.content.trim() || "No tool output"; | |
| 439 | + if (hasAddedToolCallIds.has(message.toolCallId)) { | |
| 440 | + currentBlocks.push({ | |
| 441 | + toolResult: { | |
| 442 | + toolUseId: message.toolCallId, | |
| 443 | + content: [ | |
| 444 | + { | |
| 445 | + text: trimmedContent, | |
| 446 | + }, | |
| 447 | + ], | |
| 448 | + }, | |
| 449 | + }); | |
| 450 | + } else { | |
| 451 | + currentBlocks.push({ | |
| 452 | + text: `Tool call output for Tool Call ID ${message.toolCallId}:\n\n${trimmedContent}`, | |
| 453 | + }); | |
| 454 | + } | |
| 455 | + } | |
| 456 | + } else if (message.role === "assistant" || message.role === "thinking") { | |
| 457 | + // Detect conversational turn change | |
| 458 | + if (currentRole !== ConversationRole.ASSISTANT) { | |
| 459 | + pushCurrentMessage(); | |
| 460 | + currentRole = ConversationRole.ASSISTANT; | |
| 461 | + } | |
| 462 | + | |
| 463 | + // ASSISTANT messages: | |
| 464 | + // Non-empty assistant message content is converted to "text" and "image" blocks | |
| 465 | + if (message.role === "assistant") { | |
| 466 | + const trimmedContent = | |
| 467 | + typeof message.content === "string" | |
| 468 | + ? message.content.trim() | |
| 469 | + : message.content; | |
| 470 | + if (trimmedContent) { | |
| 471 | + currentBlocks.push( | |
| 472 | + ...this._convertMessageContentToBlocks(trimmedContent), | |
| 473 | + ); | |
| 474 | + } | |
| 475 | + // TOOL CALLS: | |
| 476 | + // Tool calls are represented by "toolUse" blocks | |
| 477 | + // Each tool call must have an id and a function name | |
| 478 | + // The function name must match one of the available tools | |
| 479 | + // Otherwise, we will convert it to a text block (e.g. Chat mode will pass no tools) | |
| 480 | + if (message.toolCalls) { | |
| 481 | + for (const toolCall of message.toolCalls) { | |
| 482 | + if (toolCall.id && toolCall.function?.name) { | |
| 483 | + if (availableTools.has(toolCall.function.name)) { | |
| 484 | + currentBlocks.push({ | |
| 485 | + toolUse: { | |
| 486 | + toolUseId: toolCall.id, | |
| 487 | + name: toolCall.function.name, | |
| 488 | + input: safeParseToolCallArgs(toolCall), | |
| 489 | + }, | |
| 490 | + }); | |
| 491 | + hasAddedToolCallIds.add(toolCall.id); | |
| 492 | + } else { | |
| 493 | + const toolCallText = `Assistant tool call:\nTool name: ${toolCall.function.name}\nTool Call ID: ${toolCall.id}\nArguments: ${toolCall.function?.arguments ?? "{}"}`; | |
| 494 | + currentBlocks.push({ | |
| 495 | + text: toolCallText, | |
| 496 | + }); | |
| 497 | + } | |
| 498 | + } else { | |
| 499 | + console.warn( | |
| 500 | + `Bedrock: tool call missing id or name, skipping tool call: ${JSON.stringify(toolCall)}`, | |
| 501 | + ); | |
| 502 | + continue; | |
| 503 | + } | |
| 504 | + } | |
| 505 | + } | |
| 506 | + } else if (message.role === "thinking") { | |
| 507 | + // THINKING: | |
| 508 | + // Thinking messages are represented by "reasoningContent" blocks which can have redacted content or reasoning content | |
| 509 | + if (message.redactedThinking) { | |
| 510 | + const block: ContentBlock.ReasoningContentMember = { | |
| 511 | + reasoningContent: { | |
| 512 | + redactedContent: new Uint8Array( | |
| 513 | + Buffer.from(message.redactedThinking), | |
| 514 | + ), | |
| 515 | + }, | |
| 516 | + }; | |
| 517 | + currentBlocks.push(block); | |
| 518 | + } else { | |
| 519 | + const block: ContentBlock.ReasoningContentMember = { | |
| 520 | + reasoningContent: { | |
| 521 | + reasoningText: { | |
| 522 | + text: (message.content as string) || "", | |
| 523 | + signature: message.signature, | |
| 395 | 524 | }, |
| 396 | - ], | |
| 397 | - }, | |
| 398 | - }, | |
| 399 | - ], | |
| 400 | - }; | |
| 525 | + }, | |
| 526 | + }; | |
| 527 | + currentBlocks.push(block); | |
| 528 | + } | |
| 529 | + } | |
| 530 | + } | |
| 401 | 531 | } |
| 402 | - | |
| 403 | - // Tool calls handling | |
| 404 | - if (message.role === "assistant" && message.toolCalls) { | |
| 405 | - return { | |
| 406 | - role: "assistant", | |
| 407 | - content: message.toolCalls.map((toolCall) => ({ | |
| 408 | - toolUse: { | |
| 409 | - toolUseId: toolCall.id, | |
| 410 | - name: toolCall.function?.name, | |
| 411 | - input: safeParseToolCallArgs(toolCall), | |
| 412 | - }, | |
| 413 | - })), | |
| 414 | - }; | |
| 532 | + if (currentBlocks.length > 0) { | |
| 533 | + pushCurrentMessage(); | |
| 415 | 534 | } |
| 416 | 535 | |
| 417 | - if (message.role === "thinking") { | |
| 418 | - if (message.redactedThinking) { | |
| 419 | - const content: ContentBlock.ReasoningContentMember = { | |
| 420 | - reasoningContent: { | |
| 421 | - redactedContent: new Uint8Array( | |
| 422 | - Buffer.from(message.redactedThinking), | |
| 423 | - ), | |
| 424 | - }, | |
| 425 | - }; | |
| 426 | - return { | |
| 427 | - role: "assistant", | |
| 428 | - content: [content], | |
| 429 | - }; | |
| 430 | - } else { | |
| 431 | - const content: ContentBlock.ReasoningContentMember = { | |
| 432 | - reasoningContent: { | |
| 433 | - reasoningText: { | |
| 434 | - text: (message.content as string) || "", | |
| 435 | - signature: message.signature, | |
| 436 | - }, | |
| 437 | - }, | |
| 438 | - }; | |
| 439 | - return { | |
| 440 | - role: "assistant", | |
| 441 | - content: [content], | |
| 442 | - }; | |
| 443 | - } | |
| 536 | + // If caching is enabled, we add cache_control parameter to the last two user messages | |
| 537 | + // The second-to-last because it retrieves potentially already cached contents, | |
| 538 | + // The last one because we want it cached for later retrieval. | |
| 539 | + // See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html | |
| 540 | + if (this.cacheBehavior?.cacheConversation) { | |
| 541 | + this._addCachingToLastTwoUserMessages(converted); | |
| 444 | 542 | } |
| 445 | 543 | |
| 446 | - // Standard text message | |
| 447 | - if (typeof message.content === "string") { | |
| 448 | - if (addCaching) { | |
| 449 | - message.content += getSecureID(); | |
| 544 | + return converted; | |
| 545 | + } | |
| 546 | + | |
| 547 | + private _addCachingToLastTwoUserMessages(converted: Message[]) { | |
| 548 | + let numCached = 0; | |
| 549 | + for (let i = converted.length - 1; i >= 0; i--) { | |
| 550 | + const message = converted[i]; | |
| 551 | + if (message.role === "user") { | |
| 552 | + message.content?.forEach((block) => { | |
| 553 | + if (block.text) { | |
| 554 | + block.text += getSecureID(); | |
| 555 | + } | |
| 556 | + }); | |
| 557 | + message.content?.push({ cachePoint: { type: "default" } }); | |
| 558 | + numCached++; | |
| 450 | 559 | } |
| 451 | - const content: any[] = [{ text: message.content }]; | |
| 452 | - if (addCaching) { | |
| 453 | - content.push({ cachePoint: { type: "default" } }); | |
| 560 | + if (numCached === 2) { | |
| 561 | + break; | |
| 454 | 562 | } |
| 455 | - return { | |
| 456 | - role: message.role, | |
| 457 | - content, | |
| 458 | - }; | |
| 459 | 563 | } |
| 564 | + } | |
| 460 | 565 | |
| 461 | - // Improved multimodal content handling | |
| 462 | - if (Array.isArray(message.content)) { | |
| 463 | - const content: any[] = []; | |
| 464 | - | |
| 465 | - // Process all parts first | |
| 466 | - message.content.forEach((part) => { | |
| 566 | + // Converts Continue message content (string/parts) to Bedrock ContentBlock format. | |
| 567 | + // Unsupported/problematic image formats are skipped with a warning. | |
| 568 | + private _convertMessageContentToBlocks( | |
| 569 | + content: MessageContent, | |
| 570 | + ): ContentBlock[] { | |
| 571 | + const blocks: ContentBlock[] = []; | |
| 572 | + if (typeof content === "string") { | |
| 573 | + blocks.push({ text: content }); | |
| 574 | + } else { | |
| 575 | + for (const part of content) { | |
| 467 | 576 | if (part.type === "text") { |
| 468 | - if (addCaching) { | |
| 469 | - part.text += getSecureID(); | |
| 470 | - } | |
| 471 | - content.push({ text: part.text }); | |
| 577 | + blocks.push({ text: part.text }); | |
| 472 | 578 | } else if (part.type === "imageUrl" && part.imageUrl) { |
| 473 | 579 | try { |
| 474 | 580 | const [mimeType, base64Data] = part.imageUrl.url.split(","); |
| 475 | 581 | const format = mimeType.split("/")[1]?.split(";")[0] || "jpeg"; |
| 476 | - content.push({ | |
| 477 | - image: { | |
| 478 | - format, | |
| 479 | - source: { | |
| 480 | - bytes: Buffer.from(base64Data, "base64"), | |
| 582 | + if ( | |
| 583 | + format === ImageFormat.JPEG || | |
| 584 | + format === ImageFormat.PNG || | |
| 585 | + format === ImageFormat.WEBP || | |
| 586 | + format === ImageFormat.GIF | |
| 587 | + ) { | |
| 588 | + blocks.push({ | |
| 589 | + image: { | |
| 590 | + format, | |
| 591 | + source: { | |
| 592 | + bytes: Uint8Array.from(Buffer.from(base64Data, "base64")), | |
| 593 | + }, | |
| 481 | 594 | }, |
| 482 | - }, | |
| 483 | - }); | |
| 595 | + }); | |
| 596 | + } else { | |
| 597 | + console.warn( | |
| 598 | + `Bedrock: skipping unsupported image part format: ${format}`, | |
| 599 | + part, | |
| 600 | + ); | |
| 601 | + } | |
| 484 | 602 | } catch (error) { |
| 485 | - console.warn(`Failed to process image: ${error}`); | |
| 603 | + console.warn("Bedrock: failed to process image part", error, part); | |
| 486 | 604 | } |
| 487 | 605 | } |
| 488 | - }); | |
| 489 | - | |
| 490 | - // Add cache point as a separate block at the end if needed | |
| 491 | - if (addCaching && content.length > 0) { | |
| 492 | - content.push({ cachePoint: { type: "default" } }); | |
| 493 | 606 | } |
| 494 | - | |
| 495 | - return { | |
| 496 | - role: message.role, | |
| 497 | - content, | |
| 498 | - } as Message; | |
| 499 | 607 | } |
| 500 | - return null; | |
| 501 | - } | |
| 502 | - | |
| 503 | - private _convertMessages(messages: ChatMessage[]): any[] { | |
| 504 | - const filteredmessages = messages.filter( | |
| 505 | - (m) => m.role !== "system" && !!m.content, | |
| 506 | - ); | |
| 507 | - const lastTwoUserMsgIndices = filteredmessages | |
| 508 | - .map((msg, index) => (msg.role === "user" ? index : -1)) | |
| 509 | - .filter((index) => index !== -1) | |
| 510 | - .slice(-2); | |
| 511 | - | |
| 512 | - const converted = filteredmessages | |
| 513 | - .map((message, filteredMsgIdx) => { | |
| 514 | - // Add cache_control parameter to the last two user messages | |
| 515 | - // The second-to-last because it retrieves potentially already cached contents, | |
| 516 | - // The last one because we want it cached for later retrieval. | |
| 517 | - // See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html | |
| 518 | - const addCaching = | |
| 519 | - this.cacheBehavior?.cacheConversation && | |
| 520 | - lastTwoUserMsgIndices.includes(filteredMsgIdx); | |
| 521 | - | |
| 522 | - try { | |
| 523 | - return this._convertMessage(message, addCaching); | |
| 524 | - } catch (error) { | |
| 525 | - console.error(`Failed to convert message: ${error}`); | |
| 526 | - return null; | |
| 527 | - } | |
| 528 | - }) | |
| 529 | - .filter(Boolean); | |
| 530 | - | |
| 531 | - return converted; | |
| 608 | + return blocks; | |
| 532 | 609 | } |
| 533 | 610 | |
| 534 | 611 | private async _getCredentials() { |
modified core/llm/llms/index.ts +1 −1
| @@ -8,7 +8,7 @@ | ||
| 8 | 8 | LLMOptions, |
| 9 | 9 | } from "../.."; |
| 10 | 10 | import { renderTemplatedString } from "../../util/handlebars/renderTemplatedString"; |
| 11 | -import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../constructMessages"; | |
| 11 | +import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../defaultSystemMessages"; | |
| 12 | 12 | import { BaseLLM } from "../index"; |
| 13 | 13 | import Anthropic from "./Anthropic"; |
| 14 | 14 | import Asksage from "./Asksage"; |
modified core/llm/rules/getSystemMessageWithRules.ts +17 −8
| @@ -327,27 +327,36 @@ | ||
| 327 | 327 | export const getSystemMessageWithRules = ({ |
| 328 | 328 | baseSystemMessage, |
| 329 | 329 | userMessage, |
| 330 | - rules, | |
| 330 | + availableRules, | |
| 331 | 331 | contextItems, |
| 332 | 332 | rulePolicies = {}, |
| 333 | 333 | }: { |
| 334 | 334 | baseSystemMessage?: string; |
| 335 | 335 | userMessage: UserChatMessage | ToolResultChatMessage | undefined; |
| 336 | - rules: RuleWithSource[]; | |
| 336 | + availableRules: RuleWithSource[]; | |
| 337 | 337 | contextItems: ContextItemWithId[]; |
| 338 | 338 | rulePolicies?: RulePolicies; |
| 339 | -}) => { | |
| 340 | - const applicableRules = getApplicableRules( | |
| 339 | +}): { | |
| 340 | + systemMessage: string; | |
| 341 | + appliedRules: RuleWithSource[]; | |
| 342 | +} => { | |
| 343 | + const appliedRules = getApplicableRules( | |
| 341 | 344 | userMessage, |
| 342 | - rules, | |
| 345 | + availableRules, | |
| 343 | 346 | contextItems, |
| 344 | 347 | rulePolicies, |
| 345 | 348 | ); |
| 346 | 349 | let systemMessage = baseSystemMessage ?? ""; |
| 347 | 350 | |
| 348 | - for (const rule of applicableRules) { | |
| 349 | - systemMessage += `\n\n${rule.rule}`; | |
| 351 | + for (const rule of appliedRules) { | |
| 352 | + if (systemMessage) { | |
| 353 | + systemMessage += "\n\n"; | |
| 354 | + } | |
| 355 | + systemMessage += rule.rule; | |
| 350 | 356 | } |
| 351 | 357 | |
| 352 | - return systemMessage; | |
| 358 | + return { | |
| 359 | + systemMessage, | |
| 360 | + appliedRules, | |
| 361 | + }; | |
| 353 | 362 | }; |
modified core/llm/toolSupport.ts +3 −1
| @@ -181,7 +181,9 @@ | ||
| 181 | 181 | return false; |
| 182 | 182 | }, |
| 183 | 183 | deepseek: (model) => { |
| 184 | - if (model !== "deepseek-reasoner") { | |
| 184 | + // https://api-docs.deepseek.com/quick_start/pricing | |
| 185 | + // https://api-docs.deepseek.com/guides/function_calling | |
| 186 | + if (model === "deepseek-reasoner" || model === "deepseek-chat") { | |
| 185 | 187 | return true; |
| 186 | 188 | } |
| 187 | 189 |
modified core/promptFiles/getPromptFiles.ts +87 −1
| @@ -1,9 +1,86 @@ | ||
| 1 | -import { DEFAULT_PROMPTS_FOLDER_V1, DEFAULT_PROMPTS_FOLDER_V2 } from "."; | |
| 1 | +import { DEFAULT_PROMPTS_FOLDER_V1 } from "."; | |
| 2 | 2 | import { IDE } from ".."; |
| 3 | 3 | import { walkDir } from "../indexing/walkDir"; |
| 4 | 4 | import { readAllGlobalPromptFiles } from "../util/paths"; |
| 5 | 5 | import { joinPathsToUri } from "../util/uri"; |
| 6 | 6 | |
| 7 | +// The hardcoded init prompt content | |
| 8 | +const INIT_PROMPT_CONTENT = `name: Init | |
| 9 | +description: Initialize Codebase | |
| 10 | +--- | |
| 11 | +You are an expert development assistant. Your task is to create a comprehensive CONTINUE.md project guide for the user's codebase to help them and their team better understand and work with the project. | |
| 12 | + | |
| 13 | +## Step 1: Check Required Tools | |
| 14 | +First, verify that you have access to the necessary tools: | |
| 15 | +- builtin_file_glob_search: To discover project files | |
| 16 | +- builtin_read_file: To analyze file contents | |
| 17 | +- builtin_ls: To explore directory structure | |
| 18 | +- builtin_create_new_file: To generate the CONTINUE.md file | |
| 19 | + | |
| 20 | +If any of these tools are unavailable, inform the user that they need to activate them and enable "Agent Mode" in Continue before proceeding. | |
| 21 | + | |
| 22 | +## Step 2: Project Analysis | |
| 23 | +Analyze the project structure and key files to understand: | |
| 24 | +- The programming languages and frameworks used | |
| 25 | +- The overall architecture and organization | |
| 26 | +- Key components and their responsibilities | |
| 27 | +- Important configuration files | |
| 28 | +- Build/deployment system | |
| 29 | + | |
| 30 | +## Step 3: Generate CONTINUE.md | |
| 31 | +Create a comprehensive CONTINUE.md file in the .continue/rules/ directory with the following sections: | |
| 32 | + | |
| 33 | +1. **Project Overview** | |
| 34 | + - Brief description of the project's purpose | |
| 35 | + - Key technologies used | |
| 36 | + - High-level architecture | |
| 37 | + | |
| 38 | +2. **Getting Started** | |
| 39 | + - Prerequisites (required software, dependencies) | |
| 40 | + - Installation instructions | |
| 41 | + - Basic usage examples | |
| 42 | + - Running tests | |
| 43 | + | |
| 44 | +3. **Project Structure** | |
| 45 | + - Overview of main directories and their purpose | |
| 46 | + - Key files and their roles | |
| 47 | + - Important configuration files | |
| 48 | + | |
| 49 | +4. **Development Workflow** | |
| 50 | + - Coding standards or conventions | |
| 51 | + - Testing approach | |
| 52 | + - Build and deployment process | |
| 53 | + - Contribution guidelines | |
| 54 | + | |
| 55 | +5. **Key Concepts** | |
| 56 | + - Domain-specific terminology | |
| 57 | + - Core abstractions | |
| 58 | + - Design patterns used | |
| 59 | + | |
| 60 | +6. **Common Tasks** | |
| 61 | + - Step-by-step guides for frequent development tasks | |
| 62 | + - Examples of common operations | |
| 63 | + | |
| 64 | +7. **Troubleshooting** | |
| 65 | + - Common issues and their solutions | |
| 66 | + - Debugging tips | |
| 67 | + | |
| 68 | +8. **References** | |
| 69 | + - Links to relevant documentation | |
| 70 | + - Important resources | |
| 71 | + | |
| 72 | +Make sure your analysis is thorough but concise. Focus on information that would be most helpful to developers working on the project. If certain information isn't available from the codebase, make reasonable assumptions but mark these sections as needing verification. | |
| 73 | + | |
| 74 | +## Step 4: Finalize | |
| 75 | +After creating the .continue/rules/CONTINUE.md file, provide a summary of what you've created and remind the user to: | |
| 76 | +1. Review and edit the file as needed | |
| 77 | +2. Commit it to their repository to share with their team | |
| 78 | +3. Explain that Continue will automatically load this file into context when working with the project | |
| 79 | + | |
| 80 | +Also inform the user that they can create additional rules.md files in subdirectories for more specific documentation related to those components.`; | |
| 81 | + | |
| 82 | +export const DEFAULT_PROMPTS_FOLDER_V2 = ".continue/prompts"; | |
| 83 | + | |
| 7 | 84 | export async function getPromptFilesFromDir( |
| 8 | 85 | ide: IDE, |
| 9 | 86 | dir: string, |
| @@ -57,8 +134,17 @@ | ||
| 57 | 134 | // Also read from ~/.continue/.prompts |
| 58 | 135 | promptFiles.push(...readAllGlobalPromptFiles()); |
| 59 | 136 | |
| 137 | + // Add hardcoded init prompt | |
| 138 | + promptFiles.push({ | |
| 139 | + path: "builtin:/init.prompt", | |
| 140 | + content: INIT_PROMPT_CONTENT, | |
| 141 | + }); | |
| 142 | + | |
| 60 | 143 | return await Promise.all( |
| 61 | 144 | promptFiles.map(async (file) => { |
| 145 | + if (file.path.startsWith("builtin:")) { | |
| 146 | + return file; | |
| 147 | + } | |
| 62 | 148 | const content = await ide.readFile(file.path); |
| 63 | 149 | return { path: file.path, content }; |
| 64 | 150 | }), |
modified core/tools/builtIn.ts +17 −17
| @@ -1,23 +1,23 @@ | ||
| 1 | 1 | export enum BuiltInToolNames { |
| 2 | - ReadFile = "builtin_read_file", | |
| 3 | - EditExistingFile = "builtin_edit_existing_file", | |
| 4 | - SearchAndReplaceInFile = "builtin_search_and_replace_in_file", | |
| 5 | - ReadCurrentlyOpenFile = "builtin_read_currently_open_file", | |
| 6 | - CreateNewFile = "builtin_create_new_file", | |
| 7 | - RunTerminalCommand = "builtin_run_terminal_command", | |
| 8 | - GrepSearch = "builtin_grep_search", | |
| 9 | - FileGlobSearch = "builtin_file_glob_search", | |
| 10 | - SearchWeb = "builtin_search_web", | |
| 11 | - ViewDiff = "builtin_view_diff", | |
| 12 | - LSTool = "builtin_ls", | |
| 13 | - CreateRuleBlock = "builtin_create_rule_block", | |
| 14 | - RequestRule = "builtin_request_rule", | |
| 15 | - FetchUrlContent = "builtin_fetch_url_content", | |
| 16 | - CodebaseTool = "builtin_codebase", | |
| 2 | + ReadFile = "read_file", | |
| 3 | + EditExistingFile = "edit_existing_file", | |
| 4 | + SearchAndReplaceInFile = "search_and_replace_in_file", | |
| 5 | + ReadCurrentlyOpenFile = "read_currently_open_file", | |
| 6 | + CreateNewFile = "create_new_file", | |
| 7 | + RunTerminalCommand = "run_terminal_command", | |
| 8 | + GrepSearch = "grep_search", | |
| 9 | + FileGlobSearch = "file_glob_search", | |
| 10 | + SearchWeb = "search_web", | |
| 11 | + ViewDiff = "view_diff", | |
| 12 | + LSTool = "ls", | |
| 13 | + CreateRuleBlock = "create_rule_block", | |
| 14 | + RequestRule = "request_rule", | |
| 15 | + FetchUrlContent = "fetch_url_content", | |
| 16 | + CodebaseTool = "codebase", | |
| 17 | 17 | |
| 18 | 18 | // excluded from allTools for now |
| 19 | - ViewRepoMap = "builtin_view_repo_map", | |
| 20 | - ViewSubdirectory = "builtin_view_subdirectory", | |
| 19 | + ViewRepoMap = "view_repo_map", | |
| 20 | + ViewSubdirectory = "view_subdirectory", | |
| 21 | 21 | } |
| 22 | 22 | |
| 23 | 23 | export const BUILT_IN_GROUP_NAME = "Built-In"; |
modified core/tools/callTool.ts +23 −0
| @@ -1,5 +1,6 @@ | ||
| 1 | 1 | import { ContextItem, Tool, ToolCall, ToolExtras } from ".."; |
| 2 | 2 | import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton"; |
| 3 | +import { DataLogger } from "../data/log"; | |
| 3 | 4 | import { canParseUrl } from "../util/url"; |
| 4 | 5 | import { BuiltInToolNames } from "./builtIn"; |
| 5 | 6 | |
| @@ -172,6 +173,26 @@ | ||
| 172 | 173 | } |
| 173 | 174 | } |
| 174 | 175 | |
| 176 | +function logToolUsage( | |
| 177 | + toolCall: ToolCall, | |
| 178 | + args: Record<string, any>, | |
| 179 | + contextItems: ContextItem[], | |
| 180 | + success: boolean, | |
| 181 | +) { | |
| 182 | + console.log(toolCall.function.arguments); | |
| 183 | + void DataLogger.getInstance().logDevData({ | |
| 184 | + name: "toolUsage", | |
| 185 | + data: { | |
| 186 | + toolCallId: toolCall.id, | |
| 187 | + functionName: toolCall.function.name, | |
| 188 | + functionArgs: toolCall.function.arguments, | |
| 189 | + toolCallArgs: args, | |
| 190 | + output: contextItems, | |
| 191 | + succeeded: success, | |
| 192 | + }, | |
| 193 | + }); | |
| 194 | +} | |
| 195 | + | |
| 175 | 196 | // Handles calls for core/non-client tools |
| 176 | 197 | // Returns an error context item if the tool call fails |
| 177 | 198 | // Note: Edit tool is handled on client |
| @@ -193,6 +214,7 @@ | ||
| 193 | 214 | item.icon = tool.faviconUrl; |
| 194 | 215 | }); |
| 195 | 216 | } |
| 217 | + logToolUsage(toolCall, args, contextItems, true); | |
| 196 | 218 | return { |
| 197 | 219 | contextItems, |
| 198 | 220 | errorMessage: undefined, |
| @@ -202,6 +224,7 @@ | ||
| 202 | 224 | if (e instanceof Error) { |
| 203 | 225 | errorMessage = e.message; |
| 204 | 226 | } |
| 227 | + logToolUsage(toolCall, {}, [], false); | |
| 205 | 228 | return { |
| 206 | 229 | contextItems: [], |
| 207 | 230 | errorMessage, |
modified core/tools/definitions/editFile.ts +1 −1
| @@ -1,5 +1,5 @@ | ||
| 1 | 1 | import { Tool } from "../.."; |
| 2 | -import { EDIT_CODE_INSTRUCTIONS } from "../../llm/constructMessages"; | |
| 2 | +import { EDIT_CODE_INSTRUCTIONS } from "../../llm/defaultSystemMessages"; | |
| 3 | 3 | import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; |
| 4 | 4 | |
| 5 | 5 | export interface EditToolArgs { |
modified core/util/findLast.ts +3 −3
| @@ -1,6 +1,6 @@ | ||
| 1 | -export function findLastIndex( | |
| 2 | - arr: any[], | |
| 3 | - criterion: (item: any) => boolean, | |
| 1 | +export function findLastIndex<T = any>( | |
| 2 | + arr: T[], | |
| 3 | + criterion: (item: T) => boolean, | |
| 4 | 4 | ): number { |
| 5 | 5 | let lastIndex = -1; |
| 6 | 6 |
modified docs/docs/agent/how-it-works.md +9 −11
| @@ -28,14 +28,12 @@ | ||
| 28 | 28 | |
| 29 | 29 | Continue includes several built-in tools which provide the model access to IDE functionality: |
| 30 | 30 | |
| 31 | -- **Read file** (`builtin_read_file`): read the contents of a file within the project | |
| 32 | -- **Read currently open file** (`builtin_read_currently_open_file`): read the contents of the currently open file | |
| 33 | -- **Create new file** (`builtin_create_new_file`): Create a new file within the project, with path and contents specified by the model | |
| 34 | -- **Exact search** (`builtin_exact_search`): perform a `ripgrep` search within the project | |
| 35 | -- **Glob search** (`builtin_file_glob_search`): perform a glob search on files in the project. Currently limits to 100 output and warns the Agent if limit reached. | |
| 36 | -- **Run terminal command** (`builtin_run_terminal_command`): run a terminal command from the workspace root | |
| 37 | -- **Search web** (`builtin_search_web`): Perform a web search to get top results | |
| 38 | -- **View diff** (`builtin_view_diff`): View the current working git diff | |
| 39 | -- **View repo map** (`builtin_view_repo_map`): request a copy of the repository map—same as the [Repo Map Context Provider](../customize/context-providers.mdx#repository-map) | |
| 40 | -- **View subdirectory** (`builtin_view_subdirectory`): request a copy of a repo map for a specific directory within the project | |
| 41 | -- **Create Rule Block** (`builtin_create_rule_block`): creates a new rule block in `.continue/rules` based on the contents of the conversation | |
| 31 | +- **Read file** (`read_file`): read the contents of a file within the project | |
| 32 | +- **Read currently open file** (`read_currently_open_file`): read the contents of the currently open file | |
| 33 | +- **Create new file** (`create_new_file`): Create a new file within the project, with path and contents specified by the model | |
| 34 | +- **Exact search** (`exact_search`): perform a `ripgrep` search within the project | |
| 35 | +- **Glob search** (`file_glob_search`): perform a glob search on files in the project. Currently limits to 100 output and warns the Agent if limit reached. | |
| 36 | +- **Run terminal command** (`run_terminal_command`): run a terminal command from the workspace root | |
| 37 | +- **Search web** (`search_web`): Perform a web search to get top results | |
| 38 | +- **View diff** (`view_diff`): View the current working git diff | |
| 39 | +- **Create Rule Block** (`create_rule_block`): creates a new rule block in `.continue/rules` based on the contents of the conversation |
modified docs/docs/customize/deep-dives/rules.mdx +1 −1
| @@ -48,7 +48,7 @@ | ||
| 48 | 48 |  |
| 49 | 49 | |
| 50 | 50 | :::info Automatically create local rule blocks |
| 51 | -When in Agent mode, you can prompt the agent to create a rule for you using the `builtin_create_rule_block` tool if enabled. | |
| 51 | +When in Agent mode, you can prompt the agent to create a rule for you using the `create_rule_block` tool if enabled. | |
| 52 | 52 | |
| 53 | 53 | For example, you can say "Create a rule for this", and a rule will be created for you in `.continue/rules` based on your conversation. |
| 54 | 54 | ::: |
modified extensions/intellij/build.gradle.kts +2 −5
| @@ -192,11 +192,8 @@ | ||
| 192 | 192 | } |
| 193 | 193 | |
| 194 | 194 | runIde { |
| 195 | - // Open the `manual-testing-sandbox` directory and the specific file on start | |
| 196 | - args = listOf( | |
| 197 | - "${rootProject.projectDir.parentFile.parentFile}/manual-testing-sandbox", | |
| 198 | - "${rootProject.projectDir.parentFile.parentFile}/manual-testing-sandbox/test.kt" | |
| 199 | - ).map { file(it).absolutePath } | |
| 195 | + val dir = "${rootProject.projectDir.parentFile.parentFile.absolutePath}/manual-testing-sandbox" | |
| 196 | + args = listOf(dir, "$dir/test.kt") | |
| 200 | 197 | } |
| 201 | 198 | |
| 202 | 199 | test { |
added extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/Icons.kt +10 −0
| @@ -0,0 +1,10 @@ | ||
| 1 | +package com.github.continuedev.continueintellijextension | |
| 2 | + | |
| 3 | +import com.intellij.openapi.util.IconLoader | |
| 4 | + | |
| 5 | +object Icons { | |
| 6 | + @JvmField | |
| 7 | + val Continue = IconLoader.getIcon("/icons/continue.svg", javaClass) | |
| 8 | + @JvmField | |
| 9 | + val Close = IconLoader.getIcon("/icons/close.svg", javaClass) | |
| 10 | +} | |
| No newline at the end of the file |
deleted extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/MyBundle.kt +0 −26
| @@ -1,26 +0,0 @@ | ||
| 1 | -package com.github.continuedev.continueintellijextension | |
| 2 | - | |
| 3 | -import com.intellij.DynamicBundle | |
| 4 | -import org.jetbrains.annotations.NonNls | |
| 5 | -import org.jetbrains.annotations.PropertyKey | |
| 6 | - | |
| 7 | -@NonNls | |
| 8 | -private const val BUNDLE = "messages.MyBundle" | |
| 9 | - | |
| 10 | -object MyBundle : DynamicBundle(BUNDLE) { | |
| 11 | - | |
| 12 | - @JvmStatic | |
| 13 | - fun message( | |
| 14 | - @PropertyKey(resourceBundle = BUNDLE) key: String, | |
| 15 | - vararg params: Any | |
| 16 | - ) = | |
| 17 | - getMessage(key, *params) | |
| 18 | - | |
| 19 | - @Suppress("unused") | |
| 20 | - @JvmStatic | |
| 21 | - fun messagePointer( | |
| 22 | - @PropertyKey(resourceBundle = BUNDLE) key: String, | |
| 23 | - vararg params: Any | |
| 24 | - ) = | |
| 25 | - getLazyMessage(key, *params) | |
| 26 | -} |
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteSpinnerWidgetFactory.kt +2 −1
| @@ -1,5 +1,6 @@ | ||
| 1 | 1 | package com.github.continuedev.continueintellijextension.autocomplete |
| 2 | 2 | |
| 3 | +import com.github.continuedev.continueintellijextension.Icons | |
| 3 | 4 | import com.github.continuedev.continueintellijextension.activities.ContinuePluginDisposable |
| 4 | 5 | import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings |
| 5 | 6 | import com.intellij.openapi.Disposable |
| @@ -50,7 +51,7 @@ | ||
| 50 | 51 | } |
| 51 | 52 | |
| 52 | 53 | override fun getIcon(): Icon = if (isLoading) animatedIcon else |
| 53 | - IconLoader.getIcon("/icons/continue.svg", javaClass) | |
| 54 | + Icons.Continue | |
| 54 | 55 | |
| 55 | 56 | fun setLoading(loading: Boolean) { |
| 56 | 57 | isLoading = loading |
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt +3 −1
| @@ -43,7 +43,9 @@ | ||
| 43 | 43 | val message = |
| 44 | 44 | gson.toJson(mapOf("messageId" to id, "messageType" to messageType, "data" to data)) |
| 45 | 45 | responseListeners[id] = onResponse |
| 46 | - write(message) | |
| 46 | + coroutineScope.launch(Dispatchers.IO) { | |
| 47 | + write(message) | |
| 48 | + } | |
| 47 | 49 | } |
| 48 | 50 | |
| 49 | 51 | private fun handleMessage(json: String) { |
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +20 −17
| @@ -18,6 +18,7 @@ | ||
| 18 | 18 | import com.intellij.notification.NotificationType |
| 19 | 19 | import com.intellij.openapi.application.ApplicationInfo |
| 20 | 20 | import com.intellij.openapi.application.ApplicationManager |
| 21 | +import com.intellij.openapi.application.EDT | |
| 21 | 22 | import com.intellij.openapi.components.service |
| 22 | 23 | import com.intellij.openapi.editor.impl.DocumentMarkupModel |
| 23 | 24 | import com.intellij.openapi.extensions.PluginId |
| @@ -294,23 +295,26 @@ | ||
| 294 | 295 | continuePluginService.diffManager?.showDiff(filepath, newContents, stepIndex) |
| 295 | 296 | } |
| 296 | 297 | |
| 297 | - override suspend fun getOpenFiles(): List<String> { | |
| 298 | - val fileEditorManager = FileEditorManager.getInstance(project) | |
| 299 | - return fileEditorManager.openFiles.mapNotNull { it.toUriOrNull() }.toList() | |
| 300 | - } | |
| 298 | + override suspend fun getOpenFiles(): List<String> = | |
| 299 | + withContext(Dispatchers.EDT) { | |
| 300 | + FileEditorManager.getInstance(project).openFiles | |
| 301 | + .mapNotNull { it.toUriOrNull() } | |
| 302 | + .toList() | |
| 303 | + } | |
| 301 | 304 | |
| 302 | - override suspend fun getCurrentFile(): Map<String, Any>? { | |
| 303 | - val fileEditorManager = FileEditorManager.getInstance(project) | |
| 304 | - val editor = fileEditorManager.selectedTextEditor | |
| 305 | - val virtualFile = editor?.document?.let { FileDocumentManager.getInstance().getFile(it) } | |
| 306 | - return virtualFile?.toUriOrNull()?.let { | |
| 307 | - mapOf( | |
| 308 | - "path" to it, | |
| 309 | - "contents" to editor.document.text, | |
| 310 | - "isUntitled" to false | |
| 311 | - ) | |
| 305 | + override suspend fun getCurrentFile(): Map<String, Any>? = | |
| 306 | + withContext(Dispatchers.EDT) { | |
| 307 | + val fileEditorManager = FileEditorManager.getInstance(project) | |
| 308 | + val document = fileEditorManager.selectedTextEditor?.document | |
| 309 | + val virtualFile = document?.let { FileDocumentManager.getInstance().getFile(it) } | |
| 310 | + virtualFile?.toUriOrNull()?.let { | |
| 311 | + mapOf( | |
| 312 | + "path" to it, | |
| 313 | + "contents" to document.text, | |
| 314 | + "isUntitled" to false | |
| 315 | + ) | |
| 316 | + } | |
| 312 | 317 | } |
| 313 | - } | |
| 314 | 318 | |
| 315 | 319 | override suspend fun getPinnedFiles(): List<String> { |
| 316 | 320 | // Returning open files for now as per existing code |
| @@ -525,10 +529,9 @@ | ||
| 525 | 529 | } |
| 526 | 530 | |
| 527 | 531 | val deferred = CompletableDeferred<String?>() |
| 528 | - val icon = IconLoader.getIcon("/icons/continue.svg", javaClass) | |
| 529 | 532 | |
| 530 | 533 | val notification = NotificationGroupManager.getInstance().getNotificationGroup("Continue") |
| 531 | - .createNotification(message, notificationType).setIcon(icon) | |
| 534 | + .createNotification(message, notificationType).setIcon(Icons.Continue) | |
| 532 | 535 | |
| 533 | 536 | val buttonTexts = otherParams.filterIsInstance<String>().toTypedArray() |
| 534 | 537 | buttonTexts.forEach { buttonText -> |
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditPanel.kt +2 −2
| @@ -1,5 +1,6 @@ | ||
| 1 | 1 | package com.github.continuedev.continueintellijextension.editor |
| 2 | 2 | |
| 3 | +import com.github.continuedev.continueintellijextension.Icons | |
| 3 | 4 | import com.github.continuedev.continueintellijextension.`continue`.GetTheme |
| 4 | 5 | import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings |
| 5 | 6 | import com.github.continuedev.continueintellijextension.services.ContinuePluginService |
| @@ -357,8 +358,7 @@ | ||
| 357 | 358 | } |
| 358 | 359 | |
| 359 | 360 | private fun createCloseButton(): JComponent { |
| 360 | - val closeIcon = IconLoader.getIcon("/icons/close.svg", javaClass) | |
| 361 | - return JLabel(closeIcon).apply { | |
| 361 | + return JLabel(Icons.Close).apply { | |
| 362 | 362 | background = Color(0, 0, 0, 0) |
| 363 | 363 | border = JBUI.Borders.empty(2, 6, 2, 0) |
| 364 | 364 | toolTipText = "`esc` to cancel" |
deleted extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/VirtualFileListener.kt +0 −0
modified extensions/intellij/src/main/resources/META-INF/plugin.xml +1 −6
| @@ -19,7 +19,7 @@ | ||
| 19 | 19 | <extensions defaultExtensionNs="com.intellij"> |
| 20 | 20 | <editorFactoryListener |
| 21 | 21 | implementation="com.github.continuedev.continueintellijextension.autocomplete.AutocompleteEditorListener"/> |
| 22 | - <toolWindow id="Continue" anchor="right" icon="/tool-window-icon.svg" | |
| 22 | + <toolWindow id="Continue" anchor="right" icon="com.github.continuedev.continueintellijextension.Icons.Continue" | |
| 23 | 23 | factoryClass="com.github.continuedev.continueintellijextension.toolWindow.ContinuePluginToolWindowFactory"/> |
| 24 | 24 | <projectService id="ContinuePluginService" |
| 25 | 25 | serviceImplementation="com.github.continuedev.continueintellijextension.services.ContinuePluginService"/> |
| @@ -37,11 +37,6 @@ | ||
| 37 | 37 | <actionPromoter order="last" |
| 38 | 38 | implementation="com.github.continuedev.continueintellijextension.actions.ContinueActionPromote"/> |
| 39 | 39 | <errorHandler implementation="com.github.continuedev.continueintellijextension.error.ContinueErrorSubmitter"/> |
| 40 | - </extensions> | |
| 41 | - | |
| 42 | - <resource-bundle>messages.MyBundle</resource-bundle> | |
| 43 | - | |
| 44 | - <extensions defaultExtensionNs="com.intellij"> | |
| 45 | 40 | <postStartupActivity |
| 46 | 41 | implementation="com.github.continuedev.continueintellijextension.activities.ContinuePluginStartupActivity"/> |
| 47 | 42 | <applicationConfigurable |
added extensions/intellij/src/main/resources/icons/continue_dark.svg +4 −0
| @@ -0,0 +1,4 @@ | ||
| 1 | +<svg width="13" height="13" viewBox="0 0 13 13" fill="none" xmlns="http://www.w3.org/2000/svg"> | |
| 2 | + <path d="M10.4742 1.6668L9.77141 2.88516L11.5477 5.95951C11.5607 5.98283 11.5685 6.01135 11.5685 6.03728C11.5685 6.0632 11.5607 6.09172 11.5477 6.11505L9.77141 9.19199L10.4742 10.4104L13 6.03728L10.4742 1.66421V1.6668ZM9.4991 2.72702L10.2019 1.50867H8.79634L8.09357 2.72702H9.5017H9.4991ZM8.09097 3.0433L9.73249 5.88173H11.138L9.4991 3.0433H8.09097ZM9.4991 9.03645L11.138 6.19542H9.73249L8.09097 9.03645H9.4991ZM8.09097 9.35273L8.79374 10.5659H10.1993L9.4965 9.35273H8.08837H8.09097ZM3.32716 10.8666C3.29864 10.8666 3.27271 10.8588 3.24939 10.8458C3.22599 10.8329 3.20527 10.8122 3.19227 10.7889L1.41332 7.71183H0.00777705L2.53362 12.0824H7.58267L6.87991 10.8666H3.32976H3.32716ZM7.15222 10.7085L7.85498 11.9242L8.55775 10.7059L7.85498 9.48755L7.15222 10.7059V10.7085ZM7.58267 9.33201H4.30484L3.60207 10.5503H6.87991L7.58267 9.33201ZM4.02992 9.17647L2.38841 6.33536L1.68562 7.55376L3.32716 10.3948L4.02992 9.17647ZM0.00518489 7.39562H1.41073L2.1135 6.17729H0.71055L0.00518489 7.39562ZM3.18454 1.29611C3.19746 1.27278 3.21826 1.25205 3.24159 1.23908C3.26491 1.22612 3.29344 1.21834 3.31936 1.21834H6.87471L7.57747 0H2.52582L0 4.37305H1.40555L3.17934 1.29871L3.18454 1.29611ZM2.1135 5.90506L1.41073 4.68673H0.00518489L0.707957 5.90506H2.1135ZM3.32196 1.69013L1.68303 4.52859L2.38581 5.74699L4.02472 2.90848L3.32196 1.69013ZM6.87731 1.532H3.59427L4.29704 2.75034H7.58007L6.87731 1.532ZM7.85498 2.5922L8.55515 1.37647L7.85498 0.158126L7.15222 1.37388L7.85498 2.5922Z" | |
| 3 | + fill="#CED0D6"/> | |
| 4 | +</svg> |
deleted extensions/intellij/src/main/resources/messages/MyBundle.properties +0 −3
| @@ -1,3 +0,0 @@ | ||
| 1 | -projectService=Project service: {0} | |
| 2 | -randomLabel=The random number is: {0} | |
| 3 | -shuffle=Shuffle |
deleted extensions/intellij/src/main/resources/tool-window-icon.svg +0 −3
| @@ -1,3 +0,0 @@ | ||
| 1 | -<svg width="13" height="13" viewBox="0 0 13 13" fill="none" xmlns="http://www.w3.org/2000/svg"> | |
| 2 | -<path d="M10.4742 1.6668L9.77141 2.88516L11.5477 5.95951C11.5607 5.98283 11.5685 6.01135 11.5685 6.03728C11.5685 6.0632 11.5607 6.09172 11.5477 6.11505L9.77141 9.19199L10.4742 10.4104L13 6.03728L10.4742 1.66421V1.6668ZM9.4991 2.72702L10.2019 1.50867H8.79634L8.09357 2.72702H9.5017H9.4991ZM8.09097 3.0433L9.73249 5.88173H11.138L9.4991 3.0433H8.09097ZM9.4991 9.03645L11.138 6.19542H9.73249L8.09097 9.03645H9.4991ZM8.09097 9.35273L8.79374 10.5659H10.1993L9.4965 9.35273H8.08837H8.09097ZM3.32716 10.8666C3.29864 10.8666 3.27271 10.8588 3.24939 10.8458C3.22599 10.8329 3.20527 10.8122 3.19227 10.7889L1.41332 7.71183H0.00777705L2.53362 12.0824H7.58267L6.87991 10.8666H3.32976H3.32716ZM7.15222 10.7085L7.85498 11.9242L8.55775 10.7059L7.85498 9.48755L7.15222 10.7059V10.7085ZM7.58267 9.33201H4.30484L3.60207 10.5503H6.87991L7.58267 9.33201ZM4.02992 9.17647L2.38841 6.33536L1.68562 7.55376L3.32716 10.3948L4.02992 9.17647ZM0.00518489 7.39562H1.41073L2.1135 6.17729H0.71055L0.00518489 7.39562ZM3.18454 1.29611C3.19746 1.27278 3.21826 1.25205 3.24159 1.23908C3.26491 1.22612 3.29344 1.21834 3.31936 1.21834H6.87471L7.57747 0H2.52582L0 4.37305H1.40555L3.17934 1.29871L3.18454 1.29611ZM2.1135 5.90506L1.41073 4.68673H0.00518489L0.707957 5.90506H2.1135ZM3.32196 1.69013L1.68303 4.52859L2.38581 5.74699L4.02472 2.90848L3.32196 1.69013ZM6.87731 1.532H3.59427L4.29704 2.75034H7.58007L6.87731 1.532ZM7.85498 2.5922L8.55515 1.37647L7.85498 0.158126L7.15222 1.37388L7.85498 2.5922Z" fill="#6C707E"/> | |
| 3 | -</svg> |
deleted extensions/intellij/src/main/resources/tool-window-icon_dark.svg +0 −3
| @@ -1,3 +0,0 @@ | ||
| 1 | -<svg width="13" height="13" viewBox="0 0 13 13" fill="none" xmlns="http://www.w3.org/2000/svg"> | |
| 2 | -<path d="M10.4742 1.6668L9.77141 2.88516L11.5477 5.95951C11.5607 5.98283 11.5685 6.01135 11.5685 6.03728C11.5685 6.0632 11.5607 6.09172 11.5477 6.11505L9.77141 9.19199L10.4742 10.4104L13 6.03728L10.4742 1.66421V1.6668ZM9.4991 2.72702L10.2019 1.50867H8.79634L8.09357 2.72702H9.5017H9.4991ZM8.09097 3.0433L9.73249 5.88173H11.138L9.4991 3.0433H8.09097ZM9.4991 9.03645L11.138 6.19542H9.73249L8.09097 9.03645H9.4991ZM8.09097 9.35273L8.79374 10.5659H10.1993L9.4965 9.35273H8.08837H8.09097ZM3.32716 10.8666C3.29864 10.8666 3.27271 10.8588 3.24939 10.8458C3.22599 10.8329 3.20527 10.8122 3.19227 10.7889L1.41332 7.71183H0.00777705L2.53362 12.0824H7.58267L6.87991 10.8666H3.32976H3.32716ZM7.15222 10.7085L7.85498 11.9242L8.55775 10.7059L7.85498 9.48755L7.15222 10.7059V10.7085ZM7.58267 9.33201H4.30484L3.60207 10.5503H6.87991L7.58267 9.33201ZM4.02992 9.17647L2.38841 6.33536L1.68562 7.55376L3.32716 10.3948L4.02992 9.17647ZM0.00518489 7.39562H1.41073L2.1135 6.17729H0.71055L0.00518489 7.39562ZM3.18454 1.29611C3.19746 1.27278 3.21826 1.25205 3.24159 1.23908C3.26491 1.22612 3.29344 1.21834 3.31936 1.21834H6.87471L7.57747 0H2.52582L0 4.37305H1.40555L3.17934 1.29871L3.18454 1.29611ZM2.1135 5.90506L1.41073 4.68673H0.00518489L0.707957 5.90506H2.1135ZM3.32196 1.69013L1.68303 4.52859L2.38581 5.74699L4.02472 2.90848L3.32196 1.69013ZM6.87731 1.532H3.59427L4.29704 2.75034H7.58007L6.87731 1.532ZM7.85498 2.5922L8.55515 1.37647L7.85498 0.158126L7.15222 1.37388L7.85498 2.5922Z" fill="#CED0D6"/> | |
| 3 | -</svg> |
modified extensions/vscode/e2e/test-continue-yaml/config.yaml +1 −1
| @@ -37,7 +37,7 @@ | ||
| 37 | 37 | - id: test_id |
| 38 | 38 | type: function |
| 39 | 39 | function: |
| 40 | - name: builtin_view_diff | |
| 40 | + name: view_diff | |
| 41 | 41 | - REPEAT_LAST_MSG |
| 42 | 42 | roles: |
| 43 | 43 | - chat |
modified extensions/vscode/e2e/test-continue/config.json +1 −1
| @@ -36,7 +36,7 @@ | ||
| 36 | 36 | "id": "test_id", |
| 37 | 37 | "type": "function", |
| 38 | 38 | "function": { |
| 39 | - "name": "builtin_view_diff" | |
| 39 | + "name": "view_diff" | |
| 40 | 40 | } |
| 41 | 41 | } |
| 42 | 42 | ] |
modified extensions/vscode/e2e/tests/GUI.test.ts +2 −2
| @@ -304,7 +304,7 @@ | ||
| 304 | 304 | }).timeout(DEFAULT_TIMEOUT.MD * 100); |
| 305 | 305 | |
| 306 | 306 | it("should call tool after approval", async () => { |
| 307 | - await GUIActions.toggleToolPolicy(view, "builtin_view_diff", 2); | |
| 307 | + await GUIActions.toggleToolPolicy(view, "view_diff", 2); | |
| 308 | 308 | |
| 309 | 309 | const [messageInput] = await GUISelectors.getMessageInputFields(view); |
| 310 | 310 | await messageInput.sendKeys("Hello"); |
| @@ -325,7 +325,7 @@ | ||
| 325 | 325 | }).timeout(DEFAULT_TIMEOUT.XL); |
| 326 | 326 | |
| 327 | 327 | it("should cancel tool", async () => { |
| 328 | - await GUIActions.toggleToolPolicy(view, "builtin_view_diff", 2); | |
| 328 | + await GUIActions.toggleToolPolicy(view, "view_diff", 2); | |
| 329 | 329 | |
| 330 | 330 | const [messageInput] = await GUISelectors.getMessageInputFields(view); |
| 331 | 331 | await messageInput.sendKeys("Hello"); |
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 +1 −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.53", | |
| 5 | + "version": "1.1.54", | |
| 6 | 6 | "repository": { |
| 7 | 7 | "type": "git", |
| 8 | 8 | "url": "https://github.com/continuedev/continue" |
modified gui/src/components/AcceptRejectDiffButtons.tsx +17 −1
| @@ -2,6 +2,9 @@ | ||
| 2 | 2 | import { ApplyState } from "core"; |
| 3 | 3 | import { useContext } from "react"; |
| 4 | 4 | import { IdeMessengerContext } from "../context/IdeMessenger"; |
| 5 | +import { useAppDispatch, useAppSelector } from "../redux/hooks"; | |
| 6 | +import { selectCurrentToolCallApplyState } from "../redux/selectors/selectCurrentToolCall"; | |
| 7 | +import { cancelToolCall } from "../redux/slices/sessionSlice"; | |
| 5 | 8 | import { getMetaKeyLabel } from "../util"; |
| 6 | 9 | import { ToolTip } from "./gui/Tooltip"; |
| 7 | 10 | |
| @@ -20,8 +23,21 @@ | ||
| 20 | 23 | (state) => state.status === "done", |
| 21 | 24 | ); |
| 22 | 25 | const ideMessenger = useContext(IdeMessengerContext); |
| 23 | - | |
| 26 | + const currentToolCallApplyState = useAppSelector( | |
| 27 | + selectCurrentToolCallApplyState, | |
| 28 | + ); | |
| 29 | + const dispatch = useAppDispatch(); | |
| 24 | 30 | async function handleAcceptOrReject(status: AcceptOrRejectOutcome) { |
| 31 | + if ( | |
| 32 | + status === "rejectDiff" && | |
| 33 | + currentToolCallApplyState?.status === "done" | |
| 34 | + ) { | |
| 35 | + dispatch( | |
| 36 | + cancelToolCall({ | |
| 37 | + toolCallId: currentToolCallApplyState.toolCallId!, | |
| 38 | + }), | |
| 39 | + ); | |
| 40 | + } | |
| 25 | 41 | for (const { filepath = "", streamId } of pendingApplyStates) { |
| 26 | 42 | ideMessenger.post(status, { |
| 27 | 43 | filepath, |
modified gui/src/components/mainInput/InputToolbar.tsx +4 −14
| @@ -9,10 +9,6 @@ | ||
| 9 | 9 | import { IdeMessengerContext } from "../../context/IdeMessenger"; |
| 10 | 10 | import { useAppDispatch, useAppSelector } from "../../redux/hooks"; |
| 11 | 11 | import { selectUseActiveFile } from "../../redux/selectors"; |
| 12 | -import { | |
| 13 | - selectCurrentToolCall, | |
| 14 | - selectCurrentToolCallApplyState, | |
| 15 | -} from "../../redux/selectors/selectCurrentToolCall"; | |
| 16 | 12 | import { selectSelectedChatModel } from "../../redux/slices/configSlice"; |
| 17 | 13 | import { setHasReasoningEnabled } from "../../redux/slices/sessionSlice"; |
| 18 | 14 | import { exitEdit } from "../../redux/thunks/edit"; |
| @@ -53,20 +49,12 @@ | ||
| 53 | 49 | const useActiveFile = useAppSelector(selectUseActiveFile); |
| 54 | 50 | const isInEdit = useAppSelector((store) => store.session.isInEdit); |
| 55 | 51 | const codeToEdit = useAppSelector((store) => store.editModeState.codeToEdit); |
| 56 | - const toolCallState = useAppSelector(selectCurrentToolCall); | |
| 57 | - const currentToolCallApplyState = useAppSelector( | |
| 58 | - selectCurrentToolCallApplyState, | |
| 59 | - ); | |
| 60 | 52 | const hasReasoningEnabled = useAppSelector( |
| 61 | 53 | (store) => store.session.hasReasoningEnabled, |
| 62 | 54 | ); |
| 63 | 55 | |
| 64 | 56 | const isEnterDisabled = |
| 65 | - props.disabled || | |
| 66 | - (isInEdit && codeToEdit.length === 0) || | |
| 67 | - toolCallState?.status === "generated" || | |
| 68 | - (currentToolCallApplyState && | |
| 69 | - currentToolCallApplyState.status !== "closed"); | |
| 57 | + props.disabled || (isInEdit && codeToEdit.length === 0); | |
| 70 | 58 | |
| 71 | 59 | const toolsSupported = defaultModel && modelSupportsTools(defaultModel); |
| 72 | 60 | |
| @@ -167,7 +155,9 @@ | ||
| 167 | 155 | /> |
| 168 | 156 | |
| 169 | 157 | <ToolTip id="model-reasoning-tooltip" place="top"> |
| 170 | - Use Model Reasoning | |
| 158 | + {hasReasoningEnabled | |
| 159 | + ? "Disable model reasoning" | |
| 160 | + : "Enable model reasoning"} | |
| 171 | 161 | </ToolTip> |
| 172 | 162 | </HoverItem> |
| 173 | 163 | )} |
modified gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx +6 −2
| @@ -2,8 +2,8 @@ | ||
| 2 | 2 | import { useSelector } from "react-redux"; |
| 3 | 3 | import { useAppDispatch, useAppSelector } from "../../../../redux/hooks"; |
| 4 | 4 | import { selectCurrentToolCall } from "../../../../redux/selectors/selectCurrentToolCall"; |
| 5 | +import { cancelToolCall } from "../../../../redux/slices/sessionSlice"; | |
| 5 | 6 | import { callCurrentTool } from "../../../../redux/thunks/callCurrentTool"; |
| 6 | -import { cancelCurrentToolCall } from "../../../../redux/thunks/cancelCurrentToolCall"; | |
| 7 | 7 | import { isJetBrains } from "../../../../util"; |
| 8 | 8 | import { BlockSettingsTopToolbar } from "./BlockSettingsTopToolbar"; |
| 9 | 9 | import { EditOutcomeToolbar } from "./EditOutcomeToolbar"; |
| @@ -50,7 +50,11 @@ | ||
| 50 | 50 | } else if ((jetbrains ? altKey : metaKey) && event.key === "Backspace") { |
| 51 | 51 | event.preventDefault(); |
| 52 | 52 | event.stopPropagation(); |
| 53 | - void dispatch(cancelCurrentToolCall()); | |
| 53 | + void dispatch( | |
| 54 | + cancelToolCall({ | |
| 55 | + toolCallId: toolCallState.toolCallId, | |
| 56 | + }), | |
| 57 | + ); | |
| 54 | 58 | } |
| 55 | 59 | }; |
| 56 | 60 |
modified gui/src/components/mainInput/Lump/LumpToolbar/PendingToolCallToolbar.tsx +15 −3
| @@ -1,7 +1,8 @@ | ||
| 1 | 1 | import styled from "styled-components"; |
| 2 | -import { useAppDispatch } from "../../../../redux/hooks"; | |
| 2 | +import { useAppDispatch, useAppSelector } from "../../../../redux/hooks"; | |
| 3 | +import { selectCurrentToolCall } from "../../../../redux/selectors/selectCurrentToolCall"; | |
| 4 | +import { cancelToolCall } from "../../../../redux/slices/sessionSlice"; | |
| 3 | 5 | import { callCurrentTool } from "../../../../redux/thunks/callCurrentTool"; |
| 4 | -import { cancelCurrentToolCall } from "../../../../redux/thunks/cancelCurrentToolCall"; | |
| 5 | 6 | import { |
| 6 | 7 | getAltKeyLabel, |
| 7 | 8 | getFontSize, |
| @@ -27,6 +28,7 @@ | ||
| 27 | 28 | export function PendingToolCallToolbar() { |
| 28 | 29 | const dispatch = useAppDispatch(); |
| 29 | 30 | const jetbrains = isJetBrains(); |
| 31 | + const currentToolCall = useAppSelector(selectCurrentToolCall); | |
| 30 | 32 | |
| 31 | 33 | return ( |
| 32 | 34 | <Container> |
| @@ -37,7 +39,17 @@ | ||
| 37 | 39 | <div className="flex gap-2 pb-0.5"> |
| 38 | 40 | <StopButton |
| 39 | 41 | className="text-description" |
| 40 | - onClick={() => dispatch(cancelCurrentToolCall())} | |
| 42 | + onClick={ | |
| 43 | + currentToolCall | |
| 44 | + ? () => { | |
| 45 | + dispatch( | |
| 46 | + cancelToolCall({ | |
| 47 | + toolCallId: currentToolCall.toolCallId, | |
| 48 | + }), | |
| 49 | + ); | |
| 50 | + } | |
| 51 | + : undefined | |
| 52 | + } | |
| 41 | 53 | data-testid="reject-tool-call-button" |
| 42 | 54 | > |
| 43 | 55 | {/* JetBrains overrides cmd+backspace, so we have to use another shortcut */} |
modified gui/src/components/mainInput/Lump/sections/RulesSection.tsx +1 −1
| @@ -10,7 +10,7 @@ | ||
| 10 | 10 | DEFAULT_AGENT_SYSTEM_MESSAGE_URL, |
| 11 | 11 | DEFAULT_CHAT_SYSTEM_MESSAGE, |
| 12 | 12 | DEFAULT_CHAT_SYSTEM_MESSAGE_URL, |
| 13 | -} from "core/llm/constructMessages"; | |
| 13 | +} from "core/llm/defaultSystemMessages"; | |
| 14 | 14 | import { useContext, useMemo } from "react"; |
| 15 | 15 | import { useAuth } from "../../../../context/Auth"; |
| 16 | 16 | import { IdeMessengerContext } from "../../../../context/IdeMessenger"; |
modified gui/src/components/mainInput/TipTapEditor/utils/processEditorContent.ts +1 −0
| @@ -37,6 +37,7 @@ | ||
| 37 | 37 | contextRequests.push({ |
| 38 | 38 | provider: |
| 39 | 39 | attrs.itemType === "contextProvider" ? attrs.id : attrs.itemType!, |
| 40 | + query: attrs.query, | |
| 40 | 41 | }); |
| 41 | 42 | return child.attrs?.renderInlineAs ?? child.attrs?.label; |
| 42 | 43 |
modified gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx +26 −31
| @@ -123,40 +123,35 @@ | ||
| 123 | 123 | return ( |
| 124 | 124 | <div |
| 125 | 125 | onClick={() => openContextItem(contextItem, ideMessenger)} |
| 126 | - className="group mr-2 flex cursor-pointer items-center overflow-hidden text-ellipsis whitespace-nowrap rounded px-1.5 py-1 text-xs hover:bg-white/10" | |
| 126 | + className="mr-2 flex cursor-pointer flex-row items-center gap-1.5 whitespace-nowrap rounded px-1.5 py-1 text-xs hover:bg-white/10" | |
| 127 | 127 | data-testid="context-items-peek-item" |
| 128 | 128 | > |
| 129 | - <div className="flex w-full items-center"> | |
| 130 | - {getContextItemIcon()} | |
| 131 | - <div className="flex min-w-0 flex-1 gap-2 text-xs"> | |
| 132 | - <div | |
| 133 | - className={`max-w-[50%] flex-shrink-0 truncate ${isUrl ? "hover:underline" : ""}`} | |
| 134 | - > | |
| 135 | - {contextItem.name} | |
| 136 | - </div> | |
| 137 | - <div | |
| 138 | - className={`min-w-0 flex-1 overflow-hidden truncate whitespace-nowrap text-xs text-gray-400 ${isUrl ? "hover:underline" : ""}`} | |
| 139 | - onClick={ | |
| 140 | - isUrl | |
| 141 | - ? (e) => { | |
| 142 | - if (contextItem.uri?.value) { | |
| 143 | - e.stopPropagation(); | |
| 144 | - ideMessenger.post("openUrl", contextItem.uri.value); | |
| 145 | - } else { | |
| 146 | - console.error("Couldn't open url", contextItem.uri); | |
| 147 | - } | |
| 148 | - } | |
| 149 | - : undefined | |
| 150 | - } | |
| 151 | - > | |
| 152 | - {contextItem.uri?.type === "file" | |
| 153 | - ? getUriPathBasename(contextItem.description) | |
| 154 | - : contextItem.description} | |
| 155 | - </div> | |
| 156 | - </div> | |
| 157 | - | |
| 129 | + {getContextItemIcon()} | |
| 130 | + <span className={`line-clamp-1 max-w-[130px] flex-shrink-0`}> | |
| 131 | + {contextItem.name} | |
| 132 | + </span> | |
| 133 | + <div | |
| 134 | + className={`group flex flex-row items-center gap-1.5 pr-1.5 text-xs text-gray-400 ${isUrl ? "hover:underline" : ""}`} | |
| 135 | + onClick={ | |
| 136 | + isUrl | |
| 137 | + ? (e) => { | |
| 138 | + if (contextItem.uri?.value) { | |
| 139 | + e.stopPropagation(); | |
| 140 | + ideMessenger.post("openUrl", contextItem.uri.value); | |
| 141 | + } else { | |
| 142 | + console.error("Couldn't open url", contextItem.uri); | |
| 143 | + } | |
| 144 | + } | |
| 145 | + : undefined | |
| 146 | + } | |
| 147 | + > | |
| 148 | + <span className={`line-clamp-1 flex-1 break-all`}> | |
| 149 | + {contextItem.uri?.type === "file" | |
| 150 | + ? getUriPathBasename(contextItem.description) | |
| 151 | + : contextItem.description} | |
| 152 | + </span> | |
| 158 | 153 | {isUrl && ( |
| 159 | - <ArrowTopRightOnSquareIcon className="mx-2 h-4 w-4 flex-shrink-0 text-gray-400 opacity-0 group-hover:opacity-100" /> | |
| 154 | + <ArrowTopRightOnSquareIcon className="h-3 w-3 flex-shrink-0 text-gray-400 opacity-80 group-hover:opacity-100" /> | |
| 160 | 155 | )} |
| 161 | 156 | </div> |
| 162 | 157 | </div> |
modified gui/src/hooks/ParallelListeners.tsx +10 −6
| @@ -38,6 +38,7 @@ | ||
| 38 | 38 | } from "../styles/theme"; |
| 39 | 39 | import { isJetBrains } from "../util"; |
| 40 | 40 | import { setLocalStorage } from "../util/localStorage"; |
| 41 | +import { migrateLocalStorage } from "../util/migrateLocalStorage"; | |
| 41 | 42 | import { useWebviewListener } from "./useWebviewListener"; |
| 42 | 43 | |
| 43 | 44 | function ParallelListeners() { |
| @@ -268,7 +269,6 @@ | ||
| 268 | 269 | currentToolCallApplyState.streamId === state.streamId |
| 269 | 270 | ) { |
| 270 | 271 | if (state.status === "done" && autoAcceptEditToolDiffs) { |
| 271 | - console.log("AUTO ACCEPTED"); | |
| 272 | 272 | ideMessenger.post("acceptDiff", { |
| 273 | 273 | streamId: state.streamId, |
| 274 | 274 | filepath: state.filepath, |
| @@ -281,6 +281,11 @@ | ||
| 281 | 281 | toolCallId: currentToolCallApplyState.toolCallId!, |
| 282 | 282 | }), |
| 283 | 283 | ); |
| 284 | + void dispatch( | |
| 285 | + streamResponseAfterToolCall({ | |
| 286 | + toolCallId: currentToolCallApplyState.toolCallId!, | |
| 287 | + }), | |
| 288 | + ); | |
| 284 | 289 | } |
| 285 | 290 | // const output: ContextItem = { |
| 286 | 291 | // name: "Edit tool output", |
| @@ -288,11 +293,6 @@ | ||
| 288 | 293 | // description: "", |
| 289 | 294 | // }; |
| 290 | 295 | // dispatch(setToolCallOutput([])); |
| 291 | - void dispatch( | |
| 292 | - streamResponseAfterToolCall({ | |
| 293 | - toolCallId: currentToolCallApplyState.toolCallId!, | |
| 294 | - }), | |
| 295 | - ); | |
| 296 | 296 | } |
| 297 | 297 | } |
| 298 | 298 | } |
| @@ -311,6 +311,10 @@ | ||
| 311 | 311 | } |
| 312 | 312 | }, [isInEdit, history]); |
| 313 | 313 | |
| 314 | + useEffect(() => { | |
| 315 | + migrateLocalStorage(dispatch); | |
| 316 | + }, []); | |
| 317 | + | |
| 314 | 318 | return <></>; |
| 315 | 319 | } |
| 316 | 320 |
modified gui/src/pages/gui/ToolCallDiv/index.tsx +3 −3
| @@ -46,9 +46,9 @@ | ||
| 46 | 46 | [BuiltInToolNames.ViewRepoMap]: MapIcon, |
| 47 | 47 | [BuiltInToolNames.ViewSubdirectory]: FolderOpenIcon, |
| 48 | 48 | [BuiltInToolNames.CreateRuleBlock]: PencilIcon, |
| 49 | - // EditExistingFile = "builtin_edit_existing_file", | |
| 50 | - // CreateNewFile = "builtin_create_new_file", | |
| 51 | - // RunTerminalCommand = "builtin_run_terminal_command", | |
| 49 | + // EditExistingFile | |
| 50 | + // CreateNewFile | |
| 51 | + // RunTerminalCommand | |
| 52 | 52 | }; |
| 53 | 53 | |
| 54 | 54 | function getStatusIcon(state: ToolStatus) { |
added gui/src/pages/gui/ToolCallDiv/toolCallStateToContextItem.ts +27 −0
| @@ -0,0 +1,27 @@ | ||
| 1 | +import { ContextItem, ContextItemWithId, ToolCallState } from "core"; | |
| 2 | + | |
| 3 | +export function toolCallStateToContextItems( | |
| 4 | + toolCallState: ToolCallState | undefined, | |
| 5 | +): ContextItemWithId[] { | |
| 6 | + if (!toolCallState) { | |
| 7 | + return []; | |
| 8 | + } | |
| 9 | + return ( | |
| 10 | + toolCallState.output?.map((ctxItem) => | |
| 11 | + toolCallCtxItemToCtxItemWithId(ctxItem, toolCallState.toolCallId), | |
| 12 | + ) ?? [] | |
| 13 | + ); | |
| 14 | +} | |
| 15 | + | |
| 16 | +export function toolCallCtxItemToCtxItemWithId( | |
| 17 | + ctxItem: ContextItem, | |
| 18 | + toolCallId: string, | |
| 19 | +): ContextItemWithId { | |
| 20 | + return { | |
| 21 | + ...ctxItem, | |
| 22 | + id: { | |
| 23 | + providerTitle: "toolCall", | |
| 24 | + itemId: toolCallId, | |
| 25 | + }, | |
| 26 | + }; | |
| 27 | +} |
modified gui/src/redux/slices/sessionSlice.ts +49 −12
| @@ -20,13 +20,20 @@ | ||
| 20 | 20 | SessionMetadata, |
| 21 | 21 | } from "core"; |
| 22 | 22 | import { NEW_SESSION_TITLE } from "core/util/constants"; |
| 23 | -import { renderChatMessage } from "core/util/messageContent"; | |
| 23 | +import { | |
| 24 | + renderChatMessage, | |
| 25 | + renderContextItems, | |
| 26 | +} from "core/util/messageContent"; | |
| 24 | 27 | import { findUriInDirs, getUriPathBasename } from "core/util/uri"; |
| 28 | +import { findLastIndex } from "lodash"; | |
| 25 | 29 | import { v4 as uuidv4 } from "uuid"; |
| 30 | +import { toolCallCtxItemToCtxItemWithId } from "../../pages/gui/ToolCallDiv/toolCallStateToContextItem"; | |
| 26 | 31 | import { addToolCallDeltaToState } from "../../util/toolCallState"; |
| 27 | 32 | import { RootState } from "../store"; |
| 28 | 33 | import { streamResponseThunk } from "../thunks/streamResponse"; |
| 29 | -import { findCurrentToolCall, findToolCall } from "../util"; | |
| 34 | +import { findCurrentToolCall, findToolCall, findToolOutput } from "../util"; | |
| 35 | + | |
| 36 | +const getIdeMessenger = () => (window as any).ideMessenger; | |
| 30 | 37 | |
| 31 | 38 | // We need this to handle reorderings (e.g. a mid-array deletion) of the messages array. |
| 32 | 39 | // The proper fix is adding a UUID to all chat messages, but this is the temp workaround. |
| @@ -105,19 +112,39 @@ | ||
| 105 | 112 | curMessage.isGatheringContext = payload; |
| 106 | 113 | } |
| 107 | 114 | }, |
| 108 | - clearLastEmptyResponse: (state) => { | |
| 115 | + clearDanglingMessages: (state) => { | |
| 116 | + // This is used during cancellation | |
| 117 | + // After the last user or tool message, we can have thinking and or valid assitant message (content or generated tool calls) OR nothing. | |
| 118 | + // The only thing allowed after the last assistant message that has either content or generated tool calls | |
| 119 | + // is a user or tool message | |
| 109 | 120 | if (state.history.length < 2) { |
| 110 | 121 | return; |
| 111 | 122 | } |
| 112 | - const lastMessage = state.history[state.history.length - 1]; | |
| 123 | + const lastUserOrToolIdx = findLastIndex( | |
| 124 | + state.history, | |
| 125 | + (item) => item.message.role === "tool" || item.message.role === "user", | |
| 126 | + ); | |
| 127 | + | |
| 128 | + let validAssistantMessageIdx = -1; | |
| 129 | + for (let i = state.history.length - 1; i > lastUserOrToolIdx; i--) { | |
| 130 | + const message = state.history[i]; | |
| 131 | + if ( | |
| 132 | + message.message.content || | |
| 133 | + message.toolCallState?.status !== "generating" | |
| 134 | + ) { | |
| 135 | + validAssistantMessageIdx = i; | |
| 136 | + // Cancel any tool calls that are dangling and generated | |
| 137 | + if (message.toolCallState?.status === "generated") { | |
| 138 | + message.toolCallState.status = "canceled"; | |
| 139 | + } | |
| 140 | + break; | |
| 141 | + } | |
| 142 | + } | |
| 113 | 143 | |
| 114 | - // Only clear in the case of an empty message | |
| 115 | - if (!lastMessage.message.content.length) { | |
| 116 | - state.mainEditorContentTrigger = | |
| 117 | - state.history[state.history.length - 2].editorState; | |
| 118 | - state.history = state.history.slice(0, -2); | |
| 119 | - // TODO is this logic correct for tool use conversations? | |
| 120 | - // Maybe slice at last index of "user" role message? | |
| 144 | + if (validAssistantMessageIdx === -1) { | |
| 145 | + state.history = state.history.slice(0, lastUserOrToolIdx + 1); | |
| 146 | + } else { | |
| 147 | + state.history = state.history.slice(0, validAssistantMessageIdx + 1); | |
| 121 | 148 | } |
| 122 | 149 | }, |
| 123 | 150 | // Trigger value picked up by editor with isMainInput to set its content |
| @@ -525,6 +552,7 @@ | ||
| 525 | 552 | contextItems: ContextItem[]; |
| 526 | 553 | }>, |
| 527 | 554 | ) => { |
| 555 | + // Update tool call state and corresponding tool output message | |
| 528 | 556 | const toolCallState = findToolCall( |
| 529 | 557 | state.history, |
| 530 | 558 | action.payload.toolCallId, |
| @@ -532,6 +560,15 @@ | ||
| 532 | 560 | if (toolCallState) { |
| 533 | 561 | toolCallState.output = action.payload.contextItems; |
| 534 | 562 | } |
| 563 | + const toolItem = findToolOutput(state.history, action.payload.toolCallId); | |
| 564 | + if (toolItem) { | |
| 565 | + toolItem.message.content = renderContextItems( | |
| 566 | + action.payload.contextItems, | |
| 567 | + ); | |
| 568 | + toolItem.contextItems = action.payload.contextItems.map((item) => | |
| 569 | + toolCallCtxItemToCtxItemWithId(item, action.payload.toolCallId), | |
| 570 | + ); | |
| 571 | + } | |
| 535 | 572 | }, |
| 536 | 573 | cancelToolCall: ( |
| 537 | 574 | state, |
| @@ -677,7 +714,7 @@ | ||
| 677 | 714 | setActive, |
| 678 | 715 | submitEditorAndInitAtIndex, |
| 679 | 716 | updateHistoryItemAtIndex, |
| 680 | - clearLastEmptyResponse, | |
| 717 | + clearDanglingMessages, | |
| 681 | 718 | setMainEditorContentTrigger, |
| 682 | 719 | deleteMessage, |
| 683 | 720 | setIsGatheringContext, |
modified gui/src/redux/slices/uiSlice.ts +14 −0
| @@ -106,6 +106,18 @@ | ||
| 106 | 106 | state.toolSettings[action.payload.function.name] = |
| 107 | 107 | "allowedWithPermission"; |
| 108 | 108 | }, |
| 109 | + setToolPolicy: ( | |
| 110 | + state, | |
| 111 | + action: PayloadAction<{ | |
| 112 | + toolName: string; | |
| 113 | + policy: ToolPolicy; | |
| 114 | + }>, | |
| 115 | + ) => { | |
| 116 | + state.toolSettings[action.payload.toolName] = action.payload.policy; | |
| 117 | + }, | |
| 118 | + clearToolPolicy: (state, action: PayloadAction<string>) => { | |
| 119 | + delete state.toolSettings[action.payload]; | |
| 120 | + }, | |
| 109 | 121 | toggleToolSetting: (state, action: PayloadAction<string>) => { |
| 110 | 122 | const setting = state.toolSettings[action.payload]; |
| 111 | 123 | |
| @@ -166,6 +178,8 @@ | ||
| 166 | 178 | setIsExploreDialogOpen, |
| 167 | 179 | setHasDismissedExploreDialog, |
| 168 | 180 | toggleToolSetting, |
| 181 | + setToolPolicy, | |
| 182 | + clearToolPolicy, | |
| 169 | 183 | toggleToolGroupSetting, |
| 170 | 184 | addTool, |
| 171 | 185 | addRule, |
modified gui/src/redux/thunks/callCurrentTool.ts +5 −0
| @@ -12,6 +12,7 @@ | ||
| 12 | 12 | updateToolCallOutput, |
| 13 | 13 | } from "../slices/sessionSlice"; |
| 14 | 14 | import { ThunkApiType } from "../store"; |
| 15 | +import { logToolUsage } from "../util"; | |
| 15 | 16 | import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; |
| 16 | 17 | |
| 17 | 18 | export const callCurrentTool = createAsyncThunk<void, undefined, ThunkApiType>( |
| @@ -100,6 +101,8 @@ | ||
| 100 | 101 | ], |
| 101 | 102 | }), |
| 102 | 103 | ); |
| 104 | + | |
| 105 | + logToolUsage(toolCallState, false, extra.ideMessenger, output); | |
| 103 | 106 | } else if (output?.length) { |
| 104 | 107 | dispatch( |
| 105 | 108 | updateToolCallOutput({ |
| @@ -107,6 +110,8 @@ | ||
| 107 | 110 | contextItems: output, |
| 108 | 111 | }), |
| 109 | 112 | ); |
| 113 | + | |
| 114 | + logToolUsage(toolCallState, true, extra.ideMessenger, output); | |
| 110 | 115 | } |
| 111 | 116 | |
| 112 | 117 | // Because we don't have access to use hooks, we check `allowAnonymousTelemetry` |
deleted gui/src/redux/thunks/cancelCurrentToolCall.ts +0 −50
| @@ -1,50 +0,0 @@ | ||
| 1 | -import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; | |
| 2 | -import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; | |
| 3 | -import { cancelToolCall, updateToolCallOutput } from "../slices/sessionSlice"; | |
| 4 | -import { ThunkApiType } from "../store"; | |
| 5 | -import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; | |
| 6 | - | |
| 7 | -export const cancelCurrentToolCall = createAsyncThunk< | |
| 8 | - void, | |
| 9 | - undefined, | |
| 10 | - ThunkApiType | |
| 11 | ->("chat/cancelTool", async (_, { dispatch, extra, getState }) => { | |
| 12 | - const state = getState(); | |
| 13 | - const toolCallState = selectCurrentToolCall(state); | |
| 14 | - | |
| 15 | - if (!toolCallState) { | |
| 16 | - return; | |
| 17 | - } | |
| 18 | - | |
| 19 | - if (toolCallState.status !== "generated") { | |
| 20 | - return; | |
| 21 | - } | |
| 22 | - | |
| 23 | - const { toolCallId } = toolCallState; | |
| 24 | - dispatch( | |
| 25 | - cancelToolCall({ | |
| 26 | - toolCallId, | |
| 27 | - }), | |
| 28 | - ); | |
| 29 | - | |
| 30 | - dispatch( | |
| 31 | - updateToolCallOutput({ | |
| 32 | - toolCallId, | |
| 33 | - contextItems: [ | |
| 34 | - { | |
| 35 | - name: "Tool Cancelled", | |
| 36 | - description: "Tool Cancelled", | |
| 37 | - content: | |
| 38 | - "The tool call was cancelled by the user. Please try something else or request further instructions.", | |
| 39 | - hidden: true, | |
| 40 | - }, | |
| 41 | - ], | |
| 42 | - }), | |
| 43 | - ); | |
| 44 | - const output = await dispatch( | |
| 45 | - streamResponseAfterToolCall({ | |
| 46 | - toolCallId, | |
| 47 | - }), | |
| 48 | - ); | |
| 49 | - unwrapResult(output); | |
| 50 | -}); |
modified gui/src/redux/thunks/cancelStream.ts +3 −5
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | import { createAsyncThunk } from "@reduxjs/toolkit"; |
| 2 | 2 | import { |
| 3 | 3 | abortStream, |
| 4 | - clearLastEmptyResponse, | |
| 4 | + clearDanglingMessages, | |
| 5 | 5 | setInactive, |
| 6 | 6 | } from "../slices/sessionSlice"; |
| 7 | 7 | import { ThunkApiType } from "../store"; |
| @@ -12,9 +12,7 @@ | ||
| 12 | 12 | dispatch(setInactive()); |
| 13 | 13 | dispatch(abortStream()); |
| 14 | 14 | |
| 15 | - // In the case tool calls were being generated, | |
| 16 | - // Replace them with | |
| 17 | - // If the assistant message is empty, then remove it and the user message, placing the user input in the main text box | |
| 18 | - dispatch(clearLastEmptyResponse()); | |
| 15 | + // Clear any dangling incomplete tool calls, thinking messages, etc. | |
| 16 | + dispatch(clearDanglingMessages()); | |
| 19 | 17 | }, |
| 20 | 18 | ); |
modified gui/src/redux/thunks/streamNormalInput.ts +41 −13
| @@ -1,5 +1,5 @@ | ||
| 1 | 1 | import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; |
| 2 | -import { ChatMessage, LLMFullCompletionOptions } from "core"; | |
| 2 | +import { LLMFullCompletionOptions } from "core"; | |
| 3 | 3 | import { modelSupportsTools } from "core/llm/autodetect"; |
| 4 | 4 | import { ToCoreProtocol } from "core/protocol"; |
| 5 | 5 | import { selectActiveTools } from "../selectors/selectActiveTools"; |
| @@ -9,38 +9,40 @@ | ||
| 9 | 9 | abortStream, |
| 10 | 10 | addPromptCompletionPair, |
| 11 | 11 | setActive, |
| 12 | + setAppliedRulesAtIndex, | |
| 12 | 13 | setInactive, |
| 13 | 14 | setToolGenerated, |
| 14 | 15 | streamUpdate, |
| 15 | 16 | } from "../slices/sessionSlice"; |
| 16 | 17 | import { ThunkApiType } from "../store"; |
| 18 | +import { | |
| 19 | + constructMessages, | |
| 20 | + getBaseSystemMessage, | |
| 21 | +} from "../util/constructMessages"; | |
| 17 | 22 | import { callCurrentTool } from "./callCurrentTool"; |
| 18 | 23 | |
| 19 | 24 | export const streamNormalInput = createAsyncThunk< |
| 20 | 25 | void, |
| 21 | 26 | { |
| 22 | - messages: ChatMessage[]; | |
| 23 | 27 | legacySlashCommandData?: ToCoreProtocol["llm/streamChat"][0]["legacySlashCommandData"]; |
| 24 | 28 | }, |
| 25 | 29 | ThunkApiType |
| 26 | 30 | >( |
| 27 | 31 | "chat/streamNormalInput", |
| 28 | - async ( | |
| 29 | - { messages, legacySlashCommandData }, | |
| 30 | - { dispatch, extra, getState }, | |
| 31 | - ) => { | |
| 32 | - // Gather state | |
| 32 | + async ({ legacySlashCommandData }, { dispatch, extra, getState }) => { | |
| 33 | 33 | const state = getState(); |
| 34 | 34 | const selectedChatModel = selectSelectedChatModel(state); |
| 35 | 35 | |
| 36 | - const streamAborter = state.session.streamAborter; | |
| 37 | 36 | if (!selectedChatModel) { |
| 38 | - throw new Error("Default model not defined"); | |
| 37 | + throw new Error("No chat model selected"); | |
| 39 | 38 | } |
| 40 | 39 | |
| 41 | - let completionOptions: LLMFullCompletionOptions = {}; | |
| 40 | + // Get tools | |
| 42 | 41 | const activeTools = selectActiveTools(state); |
| 43 | 42 | const toolsSupported = modelSupportsTools(selectedChatModel); |
| 43 | + | |
| 44 | + // Construct completion options | |
| 45 | + let completionOptions: LLMFullCompletionOptions = {}; | |
| 44 | 46 | if (toolsSupported && activeTools.length > 0) { |
| 45 | 47 | completionOptions = { |
| 46 | 48 | tools: activeTools, |
| @@ -55,20 +57,46 @@ | ||
| 55 | 57 | }; |
| 56 | 58 | } |
| 57 | 59 | |
| 60 | + // Construct messages (excluding system message) | |
| 61 | + const baseSystemMessage = getBaseSystemMessage( | |
| 62 | + state.session.mode, | |
| 63 | + selectedChatModel, | |
| 64 | + ); | |
| 65 | + | |
| 66 | + const withoutMessageIds = state.session.history.map((item) => { | |
| 67 | + const { id, ...messageWithoutId } = item.message; | |
| 68 | + return { ...item, message: messageWithoutId }; | |
| 69 | + }); | |
| 70 | + const { messages, appliedRules, appliedRuleIndex } = constructMessages( | |
| 71 | + withoutMessageIds, | |
| 72 | + baseSystemMessage, | |
| 73 | + state.config.config.rules, | |
| 74 | + state.ui.ruleSettings, | |
| 75 | + ); | |
| 76 | + | |
| 77 | + // TODO parallel tool calls will cause issues with this | |
| 78 | + // because there will be multiple tool messages, so which one should have applied rules? | |
| 79 | + dispatch( | |
| 80 | + setAppliedRulesAtIndex({ | |
| 81 | + index: appliedRuleIndex, | |
| 82 | + appliedRules: appliedRules, | |
| 83 | + }), | |
| 84 | + ); | |
| 85 | + | |
| 58 | 86 | dispatch(setActive()); |
| 59 | 87 | |
| 60 | - // Send request | |
| 88 | + // Send request and stream response | |
| 89 | + const streamAborter = state.session.streamAborter; | |
| 61 | 90 | const gen = extra.ideMessenger.llmStreamChat( |
| 62 | 91 | { |
| 63 | 92 | completionOptions, |
| 64 | 93 | title: selectedChatModel.title, |
| 65 | - messages, | |
| 94 | + messages: messages, | |
| 66 | 95 | legacySlashCommandData, |
| 67 | 96 | }, |
| 68 | 97 | streamAborter.signal, |
| 69 | 98 | ); |
| 70 | 99 | |
| 71 | - // Stream response | |
| 72 | 100 | let next = await gen.next(); |
| 73 | 101 | while (!next.done) { |
| 74 | 102 | if (!getState().session.isStreaming) { |
modified gui/src/redux/thunks/streamResponse.ts +2 −48
| @@ -1,15 +1,11 @@ | ||
| 1 | 1 | import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; |
| 2 | 2 | import { JSONContent } from "@tiptap/core"; |
| 3 | -import { InputModifiers, ToolResultChatMessage, UserChatMessage } from "core"; | |
| 4 | -import { constructMessages } from "core/llm/constructMessages"; | |
| 5 | -import { getApplicableRules } from "core/llm/rules/getSystemMessageWithRules"; | |
| 3 | +import { InputModifiers } from "core"; | |
| 6 | 4 | import posthog from "posthog-js"; |
| 7 | 5 | import { v4 as uuidv4 } from "uuid"; |
| 8 | 6 | import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils/resolveEditorContent"; |
| 9 | -import { getBaseSystemMessage } from "../../util"; | |
| 10 | 7 | import { selectSelectedChatModel } from "../slices/configSlice"; |
| 11 | 8 | import { |
| 12 | - setAppliedRulesAtIndex, | |
| 13 | 9 | submitEditorAndInitAtIndex, |
| 14 | 10 | updateHistoryItemAtIndex, |
| 15 | 11 | } from "../slices/sessionSlice"; |
| @@ -77,7 +73,7 @@ | ||
| 77 | 73 | .map((item) => item.uri!.value), |
| 78 | 74 | ...selectedCode.map((rif) => rif.filepath), |
| 79 | 75 | ]; |
| 80 | - dispatch(updateFileSymbolsFromFiles(filesForSymbols)); | |
| 76 | + void dispatch(updateFileSymbolsFromFiles(filesForSymbols)); | |
| 81 | 77 | |
| 82 | 78 | dispatch( |
| 83 | 79 | updateHistoryItemAtIndex({ |
| @@ -93,47 +89,6 @@ | ||
| 93 | 89 | }), |
| 94 | 90 | ); |
| 95 | 91 | |
| 96 | - // Get updated history after the update | |
| 97 | - const updatedHistory = getState().session.history; | |
| 98 | - | |
| 99 | - // Determine which rules apply to this message | |
| 100 | - const userMsg = updatedHistory[inputIndex].message; | |
| 101 | - const rules = getState().config.config.rules; | |
| 102 | - const rulePolicies = getState().ui.ruleSettings; | |
| 103 | - | |
| 104 | - // Calculate applicable rules once | |
| 105 | - // We need to check the message type to match what getApplicableRules expects | |
| 106 | - const applicableRules = getApplicableRules( | |
| 107 | - userMsg.role === "user" || userMsg.role === "tool" | |
| 108 | - ? (userMsg as UserChatMessage | ToolResultChatMessage) | |
| 109 | - : undefined, | |
| 110 | - rules, | |
| 111 | - selectedContextItems, | |
| 112 | - rulePolicies, | |
| 113 | - ); | |
| 114 | - | |
| 115 | - // Store in history for UI display | |
| 116 | - dispatch( | |
| 117 | - setAppliedRulesAtIndex({ | |
| 118 | - index: inputIndex, | |
| 119 | - appliedRules: applicableRules, | |
| 120 | - }), | |
| 121 | - ); | |
| 122 | - | |
| 123 | - const messageMode = getState().session.mode; | |
| 124 | - const baseChatOrAgentSystemMessage = getBaseSystemMessage( | |
| 125 | - selectedChatModel, | |
| 126 | - messageMode, | |
| 127 | - ); | |
| 128 | - | |
| 129 | - const messages = constructMessages( | |
| 130 | - messageMode, | |
| 131 | - [...updatedHistory], | |
| 132 | - baseChatOrAgentSystemMessage, | |
| 133 | - applicableRules, | |
| 134 | - rulePolicies, | |
| 135 | - ); | |
| 136 | - | |
| 137 | 92 | posthog.capture("step run", { |
| 138 | 93 | step_name: "User Input", |
| 139 | 94 | params: {}, |
| @@ -150,7 +105,6 @@ | ||
| 150 | 105 | unwrapResult( |
| 151 | 106 | await dispatch( |
| 152 | 107 | streamNormalInput({ |
| 153 | - messages, | |
| 154 | 108 | legacySlashCommandData: legacyCommandWithInput |
| 155 | 109 | ? { |
| 156 | 110 | command: legacyCommandWithInput.command, |
modified gui/src/redux/thunks/streamResponseAfterToolCall.ts +3 −39
| @@ -1,10 +1,7 @@ | ||
| 1 | 1 | import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; |
| 2 | 2 | import { ChatMessage } from "core"; |
| 3 | -import { constructMessages } from "core/llm/constructMessages"; | |
| 4 | 3 | import { renderContextItems } from "core/util/messageContent"; |
| 5 | -import { getBaseSystemMessage } from "../../util"; | |
| 6 | -import { selectSelectedChatModel } from "../slices/configSlice"; | |
| 7 | -import { addContextItemsAtIndex, streamUpdate } from "../slices/sessionSlice"; | |
| 4 | +import { streamUpdate } from "../slices/sessionSlice"; | |
| 8 | 5 | import { ThunkApiType } from "../store"; |
| 9 | 6 | import { findToolCall } from "../util"; |
| 10 | 7 | import { resetStateForNewMessage } from "./resetStateForNewMessage"; |
| @@ -21,15 +18,8 @@ | ||
| 21 | 18 | await dispatch( |
| 22 | 19 | streamThunkWrapper(async () => { |
| 23 | 20 | const state = getState(); |
| 24 | - const initialHistory = state.session.history; | |
| 25 | - const selectedChatModel = selectSelectedChatModel(state); | |
| 26 | - | |
| 27 | - if (!selectedChatModel) { | |
| 28 | - throw new Error("No model selected"); | |
| 29 | - } | |
| 30 | 21 | |
| 31 | 22 | const toolCallState = findToolCall(state.session.history, toolCallId); |
| 32 | - | |
| 33 | 23 | if (!toolCallState) { |
| 34 | 24 | return; // in cases where edit tool is cancelled mid apply, this will be triggered |
| 35 | 25 | } |
| @@ -40,41 +30,15 @@ | ||
| 40 | 30 | |
| 41 | 31 | await new Promise((resolve) => setTimeout(resolve, 0)); |
| 42 | 32 | |
| 33 | + // TODO parallel tool calls - dispatch one tool message per tool call | |
| 43 | 34 | const newMessage: ChatMessage = { |
| 44 | 35 | role: "tool", |
| 45 | 36 | content: renderContextItems(toolOutput), |
| 46 | 37 | toolCallId, |
| 47 | 38 | }; |
| 48 | 39 | dispatch(streamUpdate([newMessage])); |
| 49 | - dispatch( | |
| 50 | - addContextItemsAtIndex({ | |
| 51 | - index: initialHistory.length, | |
| 52 | - contextItems: toolOutput.map((contextItem) => ({ | |
| 53 | - ...contextItem, | |
| 54 | - id: { | |
| 55 | - providerTitle: "toolCall", | |
| 56 | - itemId: toolCallId, | |
| 57 | - }, | |
| 58 | - })), | |
| 59 | - }), | |
| 60 | - ); | |
| 61 | - | |
| 62 | - const updatedHistory = getState().session.history; | |
| 63 | - const messageMode = getState().session.mode; | |
| 64 | - | |
| 65 | - const baseChatOrAgentSystemMessage = getBaseSystemMessage( | |
| 66 | - selectedChatModel, | |
| 67 | - messageMode, | |
| 68 | - ); | |
| 69 | - | |
| 70 | - const messages = constructMessages( | |
| 71 | - messageMode, | |
| 72 | - [...updatedHistory], | |
| 73 | - baseChatOrAgentSystemMessage, | |
| 74 | - state.config.config.rules, | |
| 75 | - ); | |
| 76 | 40 | |
| 77 | - unwrapResult(await dispatch(streamNormalInput({ messages }))); | |
| 41 | + unwrapResult(await dispatch(streamNormalInput({}))); | |
| 78 | 42 | }), |
| 79 | 43 | ); |
| 80 | 44 | }, |
modified gui/src/redux/thunks/streamThunkWrapper.tsx +1 −1
| @@ -22,7 +22,7 @@ | ||
| 22 | 22 | ); |
| 23 | 23 | } |
| 24 | 24 | } catch (e) { |
| 25 | - dispatch(cancelStream()); | |
| 25 | + await dispatch(cancelStream()); | |
| 26 | 26 | dispatch(setDialogMessage(<StreamErrorDialog error={e} />)); |
| 27 | 27 | dispatch(setShowDialog(true)); |
| 28 | 28 | } |
added gui/src/redux/util/constructMessages.test.ts +734 −0
| @@ -0,0 +1,734 @@ | ||
| 1 | +import { | |
| 2 | + AssistantChatMessage, | |
| 3 | + ChatHistoryItem, | |
| 4 | + ChatMessage, | |
| 5 | + ContextItemWithId, | |
| 6 | + ModelDescription, | |
| 7 | + RuleWithSource, | |
| 8 | + ThinkingChatMessage, | |
| 9 | + ToolResultChatMessage, | |
| 10 | + UserChatMessage, | |
| 11 | +} from "core"; | |
| 12 | +import { | |
| 13 | + DEFAULT_AGENT_SYSTEM_MESSAGE, | |
| 14 | + DEFAULT_CHAT_SYSTEM_MESSAGE, | |
| 15 | +} from "core/llm/defaultSystemMessages"; | |
| 16 | +import { renderChatMessage } from "core/util/messageContent"; | |
| 17 | +import { beforeEach, describe, expect, test, vi } from "vitest"; | |
| 18 | +import { | |
| 19 | + CANCELLED_TOOL_CALL_MESSAGE, | |
| 20 | + constructMessages, | |
| 21 | + getBaseSystemMessage, | |
| 22 | + NO_TOOL_CALL_OUTPUT_MESSAGE, | |
| 23 | +} from "./constructMessages"; | |
| 24 | + | |
| 25 | +// For these tests we will mock the rules to simulate different scenarios | |
| 26 | +const CONTEXT_RULE: RuleWithSource = { | |
| 27 | + source: "rules-block", | |
| 28 | + rule: "CONTEXT_RULE", | |
| 29 | + description: "CONTEXT_TRIGGER", | |
| 30 | +}; | |
| 31 | +const LAST_MESSAGE_RULE: RuleWithSource = { | |
| 32 | + source: "rules-block", | |
| 33 | + rule: "LAST_MESSAGE_RULE", | |
| 34 | + description: "LAST_MESSAGE_TRIGGER", | |
| 35 | +}; | |
| 36 | +const NORMAL_RULE: RuleWithSource = { | |
| 37 | + source: "rules-block", | |
| 38 | + rule: "Always apply rule", | |
| 39 | +}; | |
| 40 | + | |
| 41 | +vi.mock("core/llm/rules/getSystemMessageWithRules", async (importOriginal) => { | |
| 42 | + const original = (await importOriginal()) as any; | |
| 43 | + return { | |
| 44 | + ...original, | |
| 45 | + getSystemMessageWithRules: ({ | |
| 46 | + baseSystemMessage, | |
| 47 | + availableRules, | |
| 48 | + userMessage, | |
| 49 | + contextItems, | |
| 50 | + rulePolicies, | |
| 51 | + }: { | |
| 52 | + baseSystemMessage: string; | |
| 53 | + availableRules: RuleWithSource[]; | |
| 54 | + userMessage?: UserChatMessage | ToolResultChatMessage; | |
| 55 | + contextItems: ContextItemWithId[]; | |
| 56 | + rulePolicies?: Record<string, any>; | |
| 57 | + }) => { | |
| 58 | + // Filter rules based on our mock logic | |
| 59 | + const appliedRules = availableRules.filter((rule) => { | |
| 60 | + if (rule.rule === LAST_MESSAGE_RULE.rule) { | |
| 61 | + if (userMessage) { | |
| 62 | + return renderChatMessage(userMessage).includes( | |
| 63 | + LAST_MESSAGE_RULE.description!, | |
| 64 | + ); | |
| 65 | + } else { | |
| 66 | + return false; | |
| 67 | + } | |
| 68 | + } | |
| 69 | + if (rule.rule === CONTEXT_RULE.rule) { | |
| 70 | + return contextItems.some((item) => | |
| 71 | + item.content.includes(CONTEXT_RULE.description!), | |
| 72 | + ); | |
| 73 | + } | |
| 74 | + return true; | |
| 75 | + }); | |
| 76 | + | |
| 77 | + // Build the system message with applied rules | |
| 78 | + let systemMessage = baseSystemMessage || ""; | |
| 79 | + if (appliedRules.length > 0) { | |
| 80 | + systemMessage += "\n\nRules to follow:\n"; | |
| 81 | + for (const rule of appliedRules) { | |
| 82 | + systemMessage += `- ${rule.rule}\n`; | |
| 83 | + } | |
| 84 | + } | |
| 85 | + | |
| 86 | + return { systemMessage, appliedRules }; | |
| 87 | + }, | |
| 88 | + }; | |
| 89 | +}); | |
| 90 | + | |
| 91 | +test("getBaseSystemMessage should return the correct system message based on mode", () => { | |
| 92 | + const mockModel = { | |
| 93 | + baseAgentSystemMessage: "Custom Agent System Message", | |
| 94 | + baseChatSystemMessage: "Custom Chat System Message", | |
| 95 | + } as ModelDescription; | |
| 96 | + | |
| 97 | + // Test agent mode with custom message | |
| 98 | + expect(getBaseSystemMessage("agent", mockModel)).toBe( | |
| 99 | + "Custom Agent System Message", | |
| 100 | + ); | |
| 101 | + | |
| 102 | + // Test chat mode with custom message | |
| 103 | + expect(getBaseSystemMessage("chat", mockModel)).toBe( | |
| 104 | + "Custom Chat System Message", | |
| 105 | + ); | |
| 106 | + | |
| 107 | + // Test agent mode with default message | |
| 108 | + expect(getBaseSystemMessage("agent", {} as ModelDescription)).toBe( | |
| 109 | + DEFAULT_AGENT_SYSTEM_MESSAGE, | |
| 110 | + ); | |
| 111 | + | |
| 112 | + // Test chat mode with default message | |
| 113 | + expect(getBaseSystemMessage("chat", {} as ModelDescription)).toBe( | |
| 114 | + DEFAULT_CHAT_SYSTEM_MESSAGE, | |
| 115 | + ); | |
| 116 | +}); | |
| 117 | + | |
| 118 | +describe("constructMessages", () => { | |
| 119 | + // Setup mock data | |
| 120 | + let mockHistory: ChatHistoryItem[]; | |
| 121 | + const mockRules: RuleWithSource[] = [ | |
| 122 | + CONTEXT_RULE, | |
| 123 | + LAST_MESSAGE_RULE, | |
| 124 | + NORMAL_RULE, | |
| 125 | + ]; | |
| 126 | + | |
| 127 | + const createContextItem = ( | |
| 128 | + id: string, | |
| 129 | + content: string, | |
| 130 | + ): ContextItemWithId => ({ | |
| 131 | + id: { | |
| 132 | + providerTitle: "test-provider", | |
| 133 | + itemId: id, | |
| 134 | + }, | |
| 135 | + content, | |
| 136 | + name: `Context Item ${id}`, | |
| 137 | + description: `Description for ${id}`, | |
| 138 | + }); | |
| 139 | + | |
| 140 | + beforeEach(() => { | |
| 141 | + // Reset mock history before each test | |
| 142 | + mockHistory = []; | |
| 143 | + }); | |
| 144 | + | |
| 145 | + test("should ignore empty, tool, and system messages that go in", () => { | |
| 146 | + // Setup history with various message types including ones to be ignored | |
| 147 | + mockHistory = [ | |
| 148 | + { | |
| 149 | + message: { | |
| 150 | + role: "system", | |
| 151 | + content: "I should be ignored", | |
| 152 | + } as ChatMessage, | |
| 153 | + contextItems: [], | |
| 154 | + }, | |
| 155 | + { | |
| 156 | + message: { | |
| 157 | + role: "tool", | |
| 158 | + content: "I should be ignored", | |
| 159 | + toolCallId: "123", | |
| 160 | + } as ToolResultChatMessage, | |
| 161 | + contextItems: [], | |
| 162 | + }, | |
| 163 | + { | |
| 164 | + message: { role: "user", content: "" } as ChatMessage, // Empty message | |
| 165 | + contextItems: [], | |
| 166 | + }, | |
| 167 | + { | |
| 168 | + message: { role: "user", content: "Valid user message" } as ChatMessage, | |
| 169 | + contextItems: [], | |
| 170 | + }, | |
| 171 | + ]; | |
| 172 | + | |
| 173 | + const { messages } = constructMessages( | |
| 174 | + mockHistory, | |
| 175 | + "Base System Message", | |
| 176 | + mockRules, | |
| 177 | + {}, | |
| 178 | + ); | |
| 179 | + | |
| 180 | + // Should only contain a system message (added by the function) and the valid user message | |
| 181 | + expect(messages.length).toBe(2); | |
| 182 | + expect(messages[0].role).toBe("system"); | |
| 183 | + expect(messages[1].role).toBe("user"); | |
| 184 | + expect(messages[1].content).toEqual([ | |
| 185 | + { type: "text", text: "Valid user message" }, | |
| 186 | + ]); | |
| 187 | + expect(messages.some((msg) => msg.content === "I should be ignored")).toBe( | |
| 188 | + false, | |
| 189 | + ); | |
| 190 | + }); | |
| 191 | + | |
| 192 | + test("should convert user messages to message parts arrays with context items", () => { | |
| 193 | + const contextItems = [ | |
| 194 | + createContextItem("1", "Context content 1"), | |
| 195 | + createContextItem("2", "Context content 2"), | |
| 196 | + ]; | |
| 197 | + | |
| 198 | + mockHistory = [ | |
| 199 | + { | |
| 200 | + message: { | |
| 201 | + role: "user", | |
| 202 | + content: "User message with context", | |
| 203 | + } as ChatMessage, | |
| 204 | + contextItems, | |
| 205 | + }, | |
| 206 | + ]; | |
| 207 | + | |
| 208 | + const { messages } = constructMessages( | |
| 209 | + mockHistory, | |
| 210 | + "Base System Message", | |
| 211 | + mockRules, | |
| 212 | + {}, | |
| 213 | + ); | |
| 214 | + | |
| 215 | + // Check that user message was converted to parts array with context items first | |
| 216 | + expect(messages.length).toBe(2); // System message + user message | |
| 217 | + expect(messages[1].role).toBe("user"); | |
| 218 | + | |
| 219 | + // Check content structure | |
| 220 | + const content = messages[1].content as any[]; | |
| 221 | + expect(content.length).toBe(3); // 2 context items + original message | |
| 222 | + expect(content[0].text).toContain("Context content 1"); | |
| 223 | + expect(content[1].text).toContain("Context content 2"); | |
| 224 | + expect(content[2].text).toBe("User message with context"); | |
| 225 | + }); | |
| 226 | + | |
| 227 | + test("should inject thinking messages with no changes", () => { | |
| 228 | + const thinkingMessage: ThinkingChatMessage = { | |
| 229 | + role: "thinking", | |
| 230 | + content: "Thinking process...", | |
| 231 | + }; | |
| 232 | + | |
| 233 | + mockHistory = [ | |
| 234 | + { | |
| 235 | + message: thinkingMessage, | |
| 236 | + contextItems: [], | |
| 237 | + }, | |
| 238 | + ]; | |
| 239 | + | |
| 240 | + const { messages } = constructMessages( | |
| 241 | + mockHistory, | |
| 242 | + "Base System Message", | |
| 243 | + mockRules, | |
| 244 | + {}, | |
| 245 | + ); | |
| 246 | + | |
| 247 | + // Should have system message + thinking message | |
| 248 | + expect(messages.length).toBe(2); | |
| 249 | + expect(messages[1].role).toBe("thinking"); | |
| 250 | + expect(messages[1].content).toBe("Thinking process..."); | |
| 251 | + }); | |
| 252 | + | |
| 253 | + test("should inject assistant messages with no changes", () => { | |
| 254 | + const assistantMessage: AssistantChatMessage = { | |
| 255 | + role: "assistant", | |
| 256 | + content: "Assistant response", | |
| 257 | + }; | |
| 258 | + | |
| 259 | + mockHistory = [ | |
| 260 | + { | |
| 261 | + message: assistantMessage, | |
| 262 | + contextItems: [], | |
| 263 | + }, | |
| 264 | + ]; | |
| 265 | + | |
| 266 | + const { messages } = constructMessages( | |
| 267 | + mockHistory, | |
| 268 | + "Base System Message", | |
| 269 | + mockRules, | |
| 270 | + {}, | |
| 271 | + ); | |
| 272 | + | |
| 273 | + // Should have system message + assistant message | |
| 274 | + expect(messages.length).toBe(2); | |
| 275 | + expect(messages[1].role).toBe("assistant"); | |
| 276 | + expect(messages[1].content).toBe("Assistant response"); | |
| 277 | + }); | |
| 278 | + | |
| 279 | + test("should follow assistant messages with tool calls by tool messages containing the tool output", () => { | |
| 280 | + const assistantWithToolCall: AssistantChatMessage = { | |
| 281 | + role: "assistant", | |
| 282 | + content: "I will search for that", | |
| 283 | + toolCalls: [ | |
| 284 | + { | |
| 285 | + id: "tool-call-1", | |
| 286 | + type: "function", | |
| 287 | + function: { | |
| 288 | + name: "search", | |
| 289 | + arguments: '{"query": "test"}', | |
| 290 | + }, | |
| 291 | + }, | |
| 292 | + ], | |
| 293 | + }; | |
| 294 | + | |
| 295 | + // With tool output | |
| 296 | + mockHistory = [ | |
| 297 | + { | |
| 298 | + message: { | |
| 299 | + role: "user", | |
| 300 | + content: "Can you search for something?", | |
| 301 | + } as UserChatMessage, | |
| 302 | + contextItems: [], | |
| 303 | + }, | |
| 304 | + { | |
| 305 | + message: assistantWithToolCall, | |
| 306 | + contextItems: [], | |
| 307 | + toolCallState: { | |
| 308 | + toolCallId: "tool-call-1", | |
| 309 | + toolCall: { | |
| 310 | + id: "tool-call-1", | |
| 311 | + type: "function", | |
| 312 | + function: { | |
| 313 | + name: "search", | |
| 314 | + arguments: '{"query": "test"}', | |
| 315 | + }, | |
| 316 | + }, | |
| 317 | + status: "done", | |
| 318 | + parsedArgs: { query: "test" }, | |
| 319 | + output: [createContextItem("search-result", "Search result content")], | |
| 320 | + }, | |
| 321 | + }, | |
| 322 | + ]; | |
| 323 | + | |
| 324 | + const { messages } = constructMessages( | |
| 325 | + mockHistory, | |
| 326 | + "Base System Message", | |
| 327 | + mockRules, | |
| 328 | + {}, | |
| 329 | + ); | |
| 330 | + | |
| 331 | + // Should have: system + user + assistant + tool messages | |
| 332 | + expect(messages.length).toBe(4); | |
| 333 | + expect(messages[2].role).toBe("assistant"); | |
| 334 | + expect(messages[3].role).toBe("tool"); | |
| 335 | + const toolMessage = messages[3] as ToolResultChatMessage; | |
| 336 | + expect(toolMessage.toolCallId).toBe("tool-call-1"); | |
| 337 | + expect(toolMessage.content).toContain("Search result content"); | |
| 338 | + }); | |
| 339 | + | |
| 340 | + test("should show cancelled message for cancelled tool calls", () => { | |
| 341 | + const assistantWithToolCall: AssistantChatMessage = { | |
| 342 | + role: "assistant", | |
| 343 | + content: "I will search for that", | |
| 344 | + toolCalls: [ | |
| 345 | + { | |
| 346 | + id: "tool-call-1", | |
| 347 | + type: "function", | |
| 348 | + function: { | |
| 349 | + name: "search", | |
| 350 | + arguments: '{"query": "test"}', | |
| 351 | + }, | |
| 352 | + }, | |
| 353 | + ], | |
| 354 | + }; | |
| 355 | + | |
| 356 | + // With cancelled tool call | |
| 357 | + mockHistory = [ | |
| 358 | + { | |
| 359 | + message: assistantWithToolCall, | |
| 360 | + contextItems: [], | |
| 361 | + toolCallState: { | |
| 362 | + toolCallId: "tool-call-1", | |
| 363 | + toolCall: { | |
| 364 | + id: "tool-call-1", | |
| 365 | + type: "function", | |
| 366 | + function: { | |
| 367 | + name: "search", | |
| 368 | + arguments: '{"query": "test"}', | |
| 369 | + }, | |
| 370 | + }, | |
| 371 | + status: "canceled", | |
| 372 | + parsedArgs: { query: "test" }, | |
| 373 | + }, | |
| 374 | + }, | |
| 375 | + ]; | |
| 376 | + | |
| 377 | + const { messages } = constructMessages( | |
| 378 | + mockHistory, | |
| 379 | + "Base System Message", | |
| 380 | + mockRules, | |
| 381 | + {}, | |
| 382 | + ); | |
| 383 | + | |
| 384 | + // Should have system + assistant + tool message with cancelled message | |
| 385 | + expect(messages.length).toBe(3); | |
| 386 | + expect(messages[2].role).toBe("tool"); | |
| 387 | + const toolMessage = messages[2] as ToolResultChatMessage; | |
| 388 | + expect(toolMessage.toolCallId).toBe("tool-call-1"); | |
| 389 | + expect(toolMessage.content).toBe(CANCELLED_TOOL_CALL_MESSAGE); | |
| 390 | + }); | |
| 391 | + | |
| 392 | + test('should show "No tool output" for tool calls without output', () => { | |
| 393 | + const assistantWithToolCall: AssistantChatMessage = { | |
| 394 | + role: "assistant", | |
| 395 | + content: "I will search for that", | |
| 396 | + toolCalls: [ | |
| 397 | + { | |
| 398 | + id: "tool-call-1", | |
| 399 | + type: "function", | |
| 400 | + function: { | |
| 401 | + name: "search", | |
| 402 | + arguments: '{"query": "test"}', | |
| 403 | + }, | |
| 404 | + }, | |
| 405 | + ], | |
| 406 | + }; | |
| 407 | + | |
| 408 | + // With tool call but no output | |
| 409 | + mockHistory = [ | |
| 410 | + { | |
| 411 | + message: assistantWithToolCall, | |
| 412 | + contextItems: [], | |
| 413 | + toolCallState: { | |
| 414 | + toolCallId: "tool-call-1", | |
| 415 | + toolCall: { | |
| 416 | + id: "tool-call-1", | |
| 417 | + type: "function", | |
| 418 | + function: { | |
| 419 | + name: "search", | |
| 420 | + arguments: '{"query": "test"}', | |
| 421 | + }, | |
| 422 | + }, | |
| 423 | + status: "generating", // Not done yet | |
| 424 | + parsedArgs: { query: "test" }, | |
| 425 | + }, | |
| 426 | + }, | |
| 427 | + ]; | |
| 428 | + | |
| 429 | + const { messages } = constructMessages( | |
| 430 | + mockHistory, | |
| 431 | + "Base System Message", | |
| 432 | + mockRules, | |
| 433 | + {}, | |
| 434 | + ); | |
| 435 | + | |
| 436 | + // Should have system + assistant + tool message with "No tool output" | |
| 437 | + expect(messages.length).toBe(3); | |
| 438 | + expect(messages[2].role).toBe("tool"); | |
| 439 | + expect(messages[2].content).toBe(NO_TOOL_CALL_OUTPUT_MESSAGE); | |
| 440 | + }); | |
| 441 | + | |
| 442 | + test("should start with system message using base message if provided", () => { | |
| 443 | + mockHistory = [ | |
| 444 | + { | |
| 445 | + message: { role: "user", content: "Hello" } as UserChatMessage, | |
| 446 | + contextItems: [], | |
| 447 | + }, | |
| 448 | + ]; | |
| 449 | + | |
| 450 | + const { messages } = constructMessages( | |
| 451 | + mockHistory, | |
| 452 | + "Custom Base System Message", | |
| 453 | + mockRules, | |
| 454 | + {}, | |
| 455 | + ); | |
| 456 | + | |
| 457 | + expect(messages[0].role).toBe("system"); | |
| 458 | + expect(messages[0].content).toContain("Custom Base System Message"); | |
| 459 | + }); | |
| 460 | + | |
| 461 | + test("should handle multiple tool calls in a single assistant message", () => { | |
| 462 | + const assistantWithMultipleToolCalls: AssistantChatMessage = { | |
| 463 | + role: "assistant", | |
| 464 | + content: "I will search and check the weather", | |
| 465 | + toolCalls: [ | |
| 466 | + { | |
| 467 | + id: "tool-call-1", | |
| 468 | + type: "function", | |
| 469 | + function: { | |
| 470 | + name: "search", | |
| 471 | + arguments: '{"query": "test"}', | |
| 472 | + }, | |
| 473 | + }, | |
| 474 | + { | |
| 475 | + id: "tool-call-2", | |
| 476 | + type: "function", | |
| 477 | + function: { | |
| 478 | + name: "weather", | |
| 479 | + arguments: '{"location": "New York"}', | |
| 480 | + }, | |
| 481 | + }, | |
| 482 | + ], | |
| 483 | + }; | |
| 484 | + | |
| 485 | + // Only the first tool call has output | |
| 486 | + mockHistory = [ | |
| 487 | + { | |
| 488 | + message: assistantWithMultipleToolCalls, | |
| 489 | + contextItems: [], | |
| 490 | + toolCallState: { | |
| 491 | + toolCallId: "tool-call-1", | |
| 492 | + toolCall: { | |
| 493 | + id: "tool-call-1", | |
| 494 | + type: "function", | |
| 495 | + function: { | |
| 496 | + name: "search", | |
| 497 | + arguments: '{"query": "test"}', | |
| 498 | + }, | |
| 499 | + }, | |
| 500 | + status: "done", | |
| 501 | + parsedArgs: { query: "test" }, | |
| 502 | + output: [createContextItem("search-result", "Search result content")], | |
| 503 | + }, | |
| 504 | + }, | |
| 505 | + ]; | |
| 506 | + | |
| 507 | + const { messages } = constructMessages( | |
| 508 | + mockHistory, | |
| 509 | + "Base System Message", | |
| 510 | + mockRules, | |
| 511 | + {}, | |
| 512 | + ); | |
| 513 | + | |
| 514 | + // Should have: system + assistant + 2 tool messages | |
| 515 | + expect(messages.length).toBe(4); | |
| 516 | + expect(messages[1].role).toBe("assistant"); | |
| 517 | + | |
| 518 | + // First tool message should have output | |
| 519 | + expect(messages[2].role).toBe("tool"); | |
| 520 | + expect(messages[3].role).toBe("tool"); | |
| 521 | + | |
| 522 | + const toolMessage1 = messages[2] as ToolResultChatMessage; | |
| 523 | + const toolMessage2 = messages[3] as ToolResultChatMessage; | |
| 524 | + expect(toolMessage1.toolCallId).toBe("tool-call-1"); | |
| 525 | + expect(toolMessage1.content).toContain("Search result content"); | |
| 526 | + | |
| 527 | + // Second tool message should have "No tool output" | |
| 528 | + expect(toolMessage2.toolCallId).toBe("tool-call-2"); | |
| 529 | + expect(toolMessage2.content).toBe(NO_TOOL_CALL_OUTPUT_MESSAGE); | |
| 530 | + }); | |
| 531 | + | |
| 532 | + test("should handle messages with array content", () => { | |
| 533 | + // User message with array content (including an image) | |
| 534 | + const userMessageWithArray: UserChatMessage = { | |
| 535 | + role: "user", | |
| 536 | + content: [ | |
| 537 | + { type: "text", text: "Here is some text" }, | |
| 538 | + { | |
| 539 | + type: "imageUrl", | |
| 540 | + imageUrl: { url: "https://example.com/image.jpg" }, | |
| 541 | + }, | |
| 542 | + ], | |
| 543 | + }; | |
| 544 | + | |
| 545 | + mockHistory = [ | |
| 546 | + { | |
| 547 | + message: userMessageWithArray, | |
| 548 | + contextItems: [createContextItem("ctx", "Context text")], | |
| 549 | + }, | |
| 550 | + ]; | |
| 551 | + | |
| 552 | + const { messages, appliedRules } = constructMessages( | |
| 553 | + mockHistory, | |
| 554 | + "Base System Message", | |
| 555 | + mockRules, | |
| 556 | + {}, | |
| 557 | + ); | |
| 558 | + | |
| 559 | + // Check the user message content structure | |
| 560 | + expect(messages.length).toBe(2); | |
| 561 | + expect(messages[1].role).toBe("user"); | |
| 562 | + | |
| 563 | + const content = messages[1].content as any[]; | |
| 564 | + // Should have context item + original 2 parts | |
| 565 | + expect(content.length).toBe(3); | |
| 566 | + expect(content[0].type).toBe("text"); | |
| 567 | + expect(content[0].text).toContain("Context text"); | |
| 568 | + expect(content[1].type).toBe("text"); | |
| 569 | + expect(content[1].text).toBe("Here is some text"); | |
| 570 | + expect(content[2].type).toBe("imageUrl"); | |
| 571 | + expect(content[2].imageUrl.url).toBe("https://example.com/image.jpg"); | |
| 572 | + | |
| 573 | + // This also verifies that rules are NOT applied if the triggers are not present | |
| 574 | + expect(appliedRules).toHaveLength(1); | |
| 575 | + expect(appliedRules).toContainEqual(NORMAL_RULE); | |
| 576 | + }); | |
| 577 | + | |
| 578 | + test("system message should include rules triggered by context items from the last user message forward", () => { | |
| 579 | + // Create context item that should trigger the CONTEXT_RULE | |
| 580 | + const triggeringContextItem = createContextItem( | |
| 581 | + "trigger", | |
| 582 | + `Some content with ${CONTEXT_RULE.description} in it`, | |
| 583 | + ); | |
| 584 | + | |
| 585 | + mockHistory = [ | |
| 586 | + // First user message with non-triggering context | |
| 587 | + { | |
| 588 | + message: { role: "user", content: "First message" } as UserChatMessage, | |
| 589 | + contextItems: [createContextItem("normal", "Normal context")], | |
| 590 | + }, | |
| 591 | + // Assistant response | |
| 592 | + { | |
| 593 | + message: { | |
| 594 | + role: "assistant", | |
| 595 | + content: "Assistant response", | |
| 596 | + } as AssistantChatMessage, | |
| 597 | + contextItems: [], | |
| 598 | + }, | |
| 599 | + // Last user message with triggering context | |
| 600 | + { | |
| 601 | + message: { role: "user", content: "Last message" } as UserChatMessage, | |
| 602 | + contextItems: [triggeringContextItem], | |
| 603 | + }, | |
| 604 | + ]; | |
| 605 | + | |
| 606 | + const { messages, appliedRules } = constructMessages( | |
| 607 | + mockHistory, | |
| 608 | + "Base System Message", | |
| 609 | + mockRules, | |
| 610 | + {}, | |
| 611 | + ); | |
| 612 | + | |
| 613 | + // Verify context rule was applied in the system message | |
| 614 | + expect(appliedRules).toHaveLength(2); | |
| 615 | + expect(appliedRules).toContainEqual(NORMAL_RULE); | |
| 616 | + expect(appliedRules).toContainEqual(CONTEXT_RULE); | |
| 617 | + expect(messages[0].role).toBe("system"); | |
| 618 | + expect(messages[0].content).toContain("Base System Message"); | |
| 619 | + expect(messages[0].content).toContain(CONTEXT_RULE.rule); | |
| 620 | + }); | |
| 621 | + | |
| 622 | + test("system message should include rules triggered by tool output after the last user message", () => { | |
| 623 | + // Create a history with a user message, assistant with tool call, and tool output containing triggering content | |
| 624 | + const assistantWithToolCall: AssistantChatMessage = { | |
| 625 | + role: "assistant", | |
| 626 | + content: "I will search for that", | |
| 627 | + toolCalls: [ | |
| 628 | + { | |
| 629 | + id: "tool-call-1", | |
| 630 | + type: "function", | |
| 631 | + function: { | |
| 632 | + name: "search", | |
| 633 | + arguments: '{"query": "test"}', | |
| 634 | + }, | |
| 635 | + }, | |
| 636 | + ], | |
| 637 | + }; | |
| 638 | + | |
| 639 | + // Tool output containing the trigger for CONTEXT_RULE | |
| 640 | + const triggeringToolOutput = createContextItem( | |
| 641 | + "search-result", | |
| 642 | + `Search result with ${CONTEXT_RULE.description} trigger`, | |
| 643 | + ); | |
| 644 | + | |
| 645 | + mockHistory = [ | |
| 646 | + { | |
| 647 | + message: { | |
| 648 | + role: "user", | |
| 649 | + content: "Can you search for something?", | |
| 650 | + } as UserChatMessage, | |
| 651 | + contextItems: [], | |
| 652 | + }, | |
| 653 | + { | |
| 654 | + message: assistantWithToolCall, | |
| 655 | + contextItems: [], | |
| 656 | + toolCallState: { | |
| 657 | + toolCallId: "tool-call-1", | |
| 658 | + toolCall: { | |
| 659 | + id: "tool-call-1", | |
| 660 | + type: "function", | |
| 661 | + function: { | |
| 662 | + name: "search", | |
| 663 | + arguments: '{"query": "test"}', | |
| 664 | + }, | |
| 665 | + }, | |
| 666 | + status: "done", | |
| 667 | + parsedArgs: { query: "test" }, | |
| 668 | + output: [triggeringToolOutput], | |
| 669 | + }, | |
| 670 | + }, | |
| 671 | + ]; | |
| 672 | + | |
| 673 | + const { messages, appliedRules } = constructMessages( | |
| 674 | + mockHistory, | |
| 675 | + "Base System Message", | |
| 676 | + mockRules, | |
| 677 | + {}, | |
| 678 | + ); | |
| 679 | + | |
| 680 | + // Verify context rule was applied in the system message due to the tool output | |
| 681 | + expect(appliedRules).toHaveLength(2); | |
| 682 | + expect(appliedRules).toContainEqual(NORMAL_RULE); | |
| 683 | + expect(appliedRules).toContainEqual(CONTEXT_RULE); | |
| 684 | + expect(messages[0].role).toBe("system"); | |
| 685 | + expect(messages[0].content).toContain("Base System Message"); | |
| 686 | + expect(messages[0].content).toContain(CONTEXT_RULE.rule); | |
| 687 | + }); | |
| 688 | + | |
| 689 | + test("system message should only apply rules triggered by the last user message", () => { | |
| 690 | + // First user message with trigger for LAST_MESSAGE_RULE | |
| 691 | + const firstUserMessage = { | |
| 692 | + role: "user", | |
| 693 | + content: `This contains ${LAST_MESSAGE_RULE.description}`, | |
| 694 | + } as UserChatMessage; | |
| 695 | + | |
| 696 | + // Last user message without any triggers | |
| 697 | + const lastUserMessage = { | |
| 698 | + role: "user", | |
| 699 | + content: "This is a normal message", | |
| 700 | + } as UserChatMessage; | |
| 701 | + | |
| 702 | + mockHistory = [ | |
| 703 | + { | |
| 704 | + message: firstUserMessage, | |
| 705 | + contextItems: [], | |
| 706 | + }, | |
| 707 | + { | |
| 708 | + message: { | |
| 709 | + role: "assistant", | |
| 710 | + content: "First response", | |
| 711 | + } as AssistantChatMessage, | |
| 712 | + contextItems: [], | |
| 713 | + }, | |
| 714 | + { | |
| 715 | + message: lastUserMessage, | |
| 716 | + contextItems: [], | |
| 717 | + }, | |
| 718 | + ]; | |
| 719 | + | |
| 720 | + const { messages, appliedRules } = constructMessages( | |
| 721 | + mockHistory, | |
| 722 | + "Base System Message", | |
| 723 | + mockRules, | |
| 724 | + {}, | |
| 725 | + ); | |
| 726 | + | |
| 727 | + // LAST_MESSAGE_RULE should not be applied since the trigger is not in the last message | |
| 728 | + expect(appliedRules).toHaveLength(1); | |
| 729 | + expect(appliedRules).toContainEqual(NORMAL_RULE); // Normal rule should always apply | |
| 730 | + expect(messages[0].role).toBe("system"); | |
| 731 | + expect(messages[0].content).toContain("Base System Message"); | |
| 732 | + expect(messages[0].content).not.toContain(LAST_MESSAGE_RULE.rule); | |
| 733 | + }); | |
| 734 | +}); |
added gui/src/redux/util/constructMessages.ts +173 −0
| @@ -0,0 +1,173 @@ | ||
| 1 | +import { | |
| 2 | + ChatHistoryItem, | |
| 3 | + ChatMessage, | |
| 4 | + ContextItemWithId, | |
| 5 | + ModelDescription, | |
| 6 | + RuleWithSource, | |
| 7 | + TextMessagePart, | |
| 8 | + ToolResultChatMessage, | |
| 9 | + UserChatMessage, | |
| 10 | +} from "core"; | |
| 11 | +import { | |
| 12 | + DEFAULT_AGENT_SYSTEM_MESSAGE, | |
| 13 | + DEFAULT_CHAT_SYSTEM_MESSAGE, | |
| 14 | +} from "core/llm/defaultSystemMessages"; | |
| 15 | +import { chatMessageIsEmpty } from "core/llm/messages"; | |
| 16 | +import { getSystemMessageWithRules } from "core/llm/rules/getSystemMessageWithRules"; | |
| 17 | +import { RulePolicies } from "core/llm/rules/types"; | |
| 18 | +import { findLast, findLastIndex } from "core/util/findLast"; | |
| 19 | +import { | |
| 20 | + normalizeToMessageParts, | |
| 21 | + renderContextItems, | |
| 22 | +} from "core/util/messageContent"; | |
| 23 | +import { toolCallStateToContextItems } from "../../pages/gui/ToolCallDiv/toolCallStateToContextItem"; | |
| 24 | + | |
| 25 | +export const NO_TOOL_CALL_OUTPUT_MESSAGE = "No tool output"; | |
| 26 | +export const CANCELLED_TOOL_CALL_MESSAGE = "The user cancelled this tool call."; | |
| 27 | + | |
| 28 | +interface MessageWithContextItems { | |
| 29 | + ctxItems: ContextItemWithId[]; | |
| 30 | + message: ChatMessage; | |
| 31 | +} | |
| 32 | +export function constructMessages( | |
| 33 | + history: ChatHistoryItem[], | |
| 34 | + baseSystemMessage: string | undefined, | |
| 35 | + availableRules: RuleWithSource[], | |
| 36 | + rulePolicies: RulePolicies, | |
| 37 | +): { | |
| 38 | + messages: ChatMessage[]; | |
| 39 | + appliedRules: RuleWithSource[]; | |
| 40 | + appliedRuleIndex: number; | |
| 41 | +} { | |
| 42 | + const historyCopy = [...history]; | |
| 43 | + | |
| 44 | + const msgs: MessageWithContextItems[] = []; | |
| 45 | + let appliedRuleIndex = -1; | |
| 46 | + let index = -1; | |
| 47 | + for (const item of historyCopy) { | |
| 48 | + index++; | |
| 49 | + if ( | |
| 50 | + item.message.role === "system" || | |
| 51 | + item.message.role === "tool" || | |
| 52 | + chatMessageIsEmpty(item.message) | |
| 53 | + ) { | |
| 54 | + // Tool messages will be re-inserted | |
| 55 | + continue; | |
| 56 | + } | |
| 57 | + | |
| 58 | + if (item.message.role === "user") { | |
| 59 | + appliedRuleIndex = index; | |
| 60 | + // Gather context items for user messages | |
| 61 | + let content = normalizeToMessageParts(item.message); | |
| 62 | + | |
| 63 | + const ctxItemParts = item.contextItems | |
| 64 | + .map((ctxItem) => { | |
| 65 | + return { | |
| 66 | + type: "text", | |
| 67 | + text: `${ctxItem.content}\n`, | |
| 68 | + } as TextMessagePart; | |
| 69 | + }) | |
| 70 | + .filter((part) => !!part.text.trim()); | |
| 71 | + | |
| 72 | + content = [...ctxItemParts, ...content]; | |
| 73 | + msgs.push({ | |
| 74 | + ctxItems: item.contextItems, | |
| 75 | + message: { | |
| 76 | + ...item.message, | |
| 77 | + content, | |
| 78 | + }, | |
| 79 | + }); | |
| 80 | + } else if (item.message.role === "thinking") { | |
| 81 | + msgs.push({ | |
| 82 | + ctxItems: item.contextItems, | |
| 83 | + message: item.message, | |
| 84 | + }); | |
| 85 | + } else if (item.message.role === "assistant") { | |
| 86 | + msgs.push({ | |
| 87 | + ctxItems: item.contextItems, | |
| 88 | + message: item.message, | |
| 89 | + }); | |
| 90 | + | |
| 91 | + // Add a tool message for each tool call | |
| 92 | + if (item.message.toolCalls?.length) { | |
| 93 | + // If the assistant message has tool calls, we need to insert tool messages | |
| 94 | + for (const toolCall of item.message.toolCalls) { | |
| 95 | + let content: string = NO_TOOL_CALL_OUTPUT_MESSAGE; | |
| 96 | + // TODO parallel tool calls: toolCallState only supports one tool call per message for now | |
| 97 | + if (item.toolCallState?.status === "canceled") { | |
| 98 | + content = CANCELLED_TOOL_CALL_MESSAGE; | |
| 99 | + } else if ( | |
| 100 | + item.toolCallState?.toolCallId === toolCall.id && | |
| 101 | + item.toolCallState?.output | |
| 102 | + ) { | |
| 103 | + content = renderContextItems(item.toolCallState.output); | |
| 104 | + } | |
| 105 | + msgs.push({ | |
| 106 | + ctxItems: toolCallStateToContextItems(item.toolCallState), | |
| 107 | + message: { | |
| 108 | + role: "tool", | |
| 109 | + content, | |
| 110 | + toolCallId: toolCall.id!, | |
| 111 | + }, | |
| 112 | + }); | |
| 113 | + } | |
| 114 | + } | |
| 115 | + } | |
| 116 | + } | |
| 117 | + | |
| 118 | + // Some rules only apply to the last user or tool message | |
| 119 | + const lastUserOrToolMsg = findLast( | |
| 120 | + msgs, | |
| 121 | + (item) => item.message.role === "user" || item.message.role === "tool", | |
| 122 | + )?.message as UserChatMessage | ToolResultChatMessage; | |
| 123 | + | |
| 124 | + // Some rules apply to all context items since the last user message, inclusiv | |
| 125 | + const lastUserMsgIndex = findLastIndex( | |
| 126 | + msgs, | |
| 127 | + (item) => item.message.role === "user", | |
| 128 | + ); | |
| 129 | + const itemsBackToLastUserMessage = msgs | |
| 130 | + .slice(lastUserMsgIndex, msgs.length) | |
| 131 | + .filter( | |
| 132 | + (item) => item.message.role === "tool" || item.message.role === "user", | |
| 133 | + ); | |
| 134 | + const rulesContextItems = itemsBackToLastUserMessage | |
| 135 | + .map((item) => item.ctxItems) | |
| 136 | + .flat(); | |
| 137 | + | |
| 138 | + const { systemMessage, appliedRules } = getSystemMessageWithRules({ | |
| 139 | + baseSystemMessage, | |
| 140 | + availableRules, | |
| 141 | + userMessage: lastUserOrToolMsg, | |
| 142 | + contextItems: rulesContextItems, | |
| 143 | + rulePolicies, | |
| 144 | + }); | |
| 145 | + | |
| 146 | + if (systemMessage.trim()) { | |
| 147 | + msgs.unshift({ | |
| 148 | + ctxItems: [], | |
| 149 | + message: { | |
| 150 | + role: "system", | |
| 151 | + content: systemMessage, | |
| 152 | + }, | |
| 153 | + }); | |
| 154 | + } | |
| 155 | + | |
| 156 | + const messages = msgs.map((m) => m.message); | |
| 157 | + return { | |
| 158 | + messages, | |
| 159 | + appliedRules, | |
| 160 | + appliedRuleIndex, | |
| 161 | + }; | |
| 162 | +} | |
| 163 | + | |
| 164 | +export function getBaseSystemMessage( | |
| 165 | + messageMode: string, | |
| 166 | + model: ModelDescription, | |
| 167 | +): string { | |
| 168 | + if (messageMode === "agent") { | |
| 169 | + return model.baseAgentSystemMessage ?? DEFAULT_AGENT_SYSTEM_MESSAGE; | |
| 170 | + } else { | |
| 171 | + return model.baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE; | |
| 172 | + } | |
| 173 | +} |
modified gui/src/redux/util/index.ts +34 −1
| @@ -1,4 +1,7 @@ | ||
| 1 | -import { ToolCallState } from "core"; | |
| 1 | +import { ContextItem, ToolCallState } from "core"; | |
| 2 | +import { safeParseToolCallArgs } from "core/tools/parseArgs"; | |
| 3 | +import { IIdeMessenger } from "../../context/IdeMessenger"; | |
| 4 | +import { ChatHistoryItemWithMessageId } from "../slices/sessionSlice"; | |
| 2 | 5 | import { RootState } from "../store"; |
| 3 | 6 | |
| 4 | 7 | export function findCurrentToolCall( |
| @@ -7,6 +10,7 @@ | ||
| 7 | 10 | return chatHistory[chatHistory.length - 1]?.toolCallState; |
| 8 | 11 | } |
| 9 | 12 | |
| 13 | +// TODO parallel tool calls - find tool call must search within arrays | |
| 10 | 14 | export function findToolCall( |
| 11 | 15 | chatHistory: RootState["session"]["history"], |
| 12 | 16 | toolCallId: string, |
| @@ -15,3 +19,32 @@ | ||
| 15 | 19 | (item) => item.toolCallState?.toolCallId === toolCallId, |
| 16 | 20 | )?.toolCallState; |
| 17 | 21 | } |
| 22 | + | |
| 23 | +export function findToolOutput( | |
| 24 | + chatHistory: RootState["session"]["history"], | |
| 25 | + toolCallId: string, | |
| 26 | +): ChatHistoryItemWithMessageId | undefined { | |
| 27 | + return chatHistory.find( | |
| 28 | + (item) => | |
| 29 | + item.message.role === "tool" && item.message.toolCallId === toolCallId, | |
| 30 | + ); | |
| 31 | +} | |
| 32 | + | |
| 33 | +export function logToolUsage( | |
| 34 | + toolCallState: ToolCallState, | |
| 35 | + success: boolean, | |
| 36 | + messenger: IIdeMessenger, | |
| 37 | + finalOutput?: ContextItem[], | |
| 38 | +) { | |
| 39 | + messenger.post("devdata/log", { | |
| 40 | + name: "toolUsage", | |
| 41 | + data: { | |
| 42 | + toolCallId: toolCallState.toolCallId, | |
| 43 | + functionName: toolCallState.toolCall?.function?.name, | |
| 44 | + functionArgs: toolCallState.toolCall?.function?.arguments, | |
| 45 | + toolCallArgs: safeParseToolCallArgs(toolCallState.toolCall), | |
| 46 | + output: finalOutput || toolCallState.output || [], | |
| 47 | + succeeded: success, | |
| 48 | + }, | |
| 49 | + }); | |
| 50 | +} |
modified gui/src/util/index.ts +0 −52
| @@ -1,10 +1,4 @@ | ||
| 1 | -import { MessageModes, ModelDescription } from "core"; | |
| 2 | 1 | import { ProfileDescription } from "core/config/ProfileLifecycleManager"; |
| 3 | -import { | |
| 4 | - DEFAULT_AGENT_SYSTEM_MESSAGE, | |
| 5 | - DEFAULT_CHAT_SYSTEM_MESSAGE, | |
| 6 | -} from "core/llm/constructMessages"; | |
| 7 | -import _ from "lodash"; | |
| 8 | 2 | import { KeyboardEvent as ReactKeyboardEvent } from "react"; |
| 9 | 3 | import { getLocalStorage } from "./localStorage"; |
| 10 | 4 | |
| @@ -88,52 +82,6 @@ | ||
| 88 | 82 | return false; |
| 89 | 83 | } |
| 90 | 84 | |
| 91 | -/** | |
| 92 | - * Updates the values of an object's properties based on the specified paths. | |
| 93 | - * | |
| 94 | - * This function creates a deep clone of the provided object and updates its properties | |
| 95 | - * based on the given path-to-value mappings. If a value in the mapping is a function, | |
| 96 | - * it will be used to determine the new value for the property. Otherwise, the value itself | |
| 97 | - * will be set for the property. | |
| 98 | - * | |
| 99 | - * @param {Object} old - The original object to be cloned and updated. | |
| 100 | - * @param {Object} pathToValue - An object where the keys represent the paths to the properties | |
| 101 | - * to be updated and the values represent the new values or functions | |
| 102 | - * to determine the new values. | |
| 103 | - * @returns {Object} A new object with the updated values. | |
| 104 | - */ | |
| 105 | -export function updatedObj(old: any, pathToValue: { [key: string]: any }) { | |
| 106 | - const newObject = _.cloneDeep(old); | |
| 107 | - | |
| 108 | - for (const key in pathToValue) { | |
| 109 | - if (typeof pathToValue[key] === "function") { | |
| 110 | - _.updateWith(newObject, key, pathToValue[key]); | |
| 111 | - } else { | |
| 112 | - _.updateWith(newObject, key, (__) => pathToValue[key]); | |
| 113 | - } | |
| 114 | - } | |
| 115 | - | |
| 116 | - return newObject; | |
| 117 | -} | |
| 118 | - | |
| 119 | 85 | export function isLocalProfile(profile: ProfileDescription): boolean { |
| 120 | 86 | return profile.profileType === "local"; |
| 121 | 87 | } |
| 122 | - | |
| 123 | -/** | |
| 124 | - * Get the base system message for the agent or chat mode from the model description. | |
| 125 | - */ | |
| 126 | -export function getBaseSystemMessage( | |
| 127 | - modelDetails: ModelDescription | null, | |
| 128 | - mode: MessageModes, | |
| 129 | -) { | |
| 130 | - let baseChatOrAgentSystemMessage: string | undefined; | |
| 131 | - if (mode === "agent") { | |
| 132 | - baseChatOrAgentSystemMessage = | |
| 133 | - modelDetails?.baseAgentSystemMessage ?? DEFAULT_AGENT_SYSTEM_MESSAGE; | |
| 134 | - } else { | |
| 135 | - baseChatOrAgentSystemMessage = | |
| 136 | - modelDetails?.baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE; | |
| 137 | - } | |
| 138 | - return baseChatOrAgentSystemMessage; | |
| 139 | -} |
added gui/src/util/migrateLocalStorage.ts +74 −0
| @@ -0,0 +1,74 @@ | ||
| 1 | +import { BuiltInToolNames } from "core/tools/builtIn"; | |
| 2 | +import { | |
| 3 | + clearToolPolicy, | |
| 4 | + setToolPolicy, | |
| 5 | + ToolPolicy, | |
| 6 | +} from "../redux/slices/uiSlice"; | |
| 7 | +import { AppDispatch } from "../redux/store"; | |
| 8 | + | |
| 9 | +const validPolicyValues: ToolPolicy[] = [ | |
| 10 | + "allowedWithPermission", | |
| 11 | + "allowedWithoutPermission", | |
| 12 | + "disabled", | |
| 13 | +]; | |
| 14 | +function migrateToolPolicies(dispatch: AppDispatch) { | |
| 15 | + const toFromMap: Record<string, string[]> = { | |
| 16 | + [BuiltInToolNames.ReadFile]: ["builtin_read_file"], | |
| 17 | + [BuiltInToolNames.EditExistingFile]: ["builtin_edit_existing_file"], | |
| 18 | + [BuiltInToolNames.SearchAndReplaceInFile]: [ | |
| 19 | + "builtin_search_and_replace_in_file", | |
| 20 | + ], | |
| 21 | + [BuiltInToolNames.ReadCurrentlyOpenFile]: [ | |
| 22 | + "builtin_read_currently_open_file", | |
| 23 | + ], | |
| 24 | + [BuiltInToolNames.CreateNewFile]: ["builtin_create_new_file"], | |
| 25 | + [BuiltInToolNames.RunTerminalCommand]: ["builtin_run_terminal_command"], | |
| 26 | + [BuiltInToolNames.GrepSearch]: ["builtin_grep_search"], | |
| 27 | + [BuiltInToolNames.FileGlobSearch]: ["builtin_file_glob_search"], | |
| 28 | + [BuiltInToolNames.SearchWeb]: ["builtin_search_web"], | |
| 29 | + [BuiltInToolNames.ViewDiff]: ["builtin_view_diff"], | |
| 30 | + [BuiltInToolNames.LSTool]: ["builtin_ls"], | |
| 31 | + [BuiltInToolNames.CreateRuleBlock]: ["builtin_create_rule_block"], | |
| 32 | + [BuiltInToolNames.RequestRule]: ["builtin_request_rule"], | |
| 33 | + [BuiltInToolNames.FetchUrlContent]: ["builtin_fetch_url_content"], | |
| 34 | + [BuiltInToolNames.CodebaseTool]: ["builtin_codebase"], | |
| 35 | + [BuiltInToolNames.ViewRepoMap]: ["builtin_view_repo_map"], | |
| 36 | + [BuiltInToolNames.ViewSubdirectory]: ["builtin_view_subdirectory"], | |
| 37 | + }; | |
| 38 | + const persistedRedux = localStorage.getItem("persist:root"); | |
| 39 | + if (persistedRedux) { | |
| 40 | + const uiState = JSON.parse(persistedRedux)?.ui; | |
| 41 | + if (uiState) { | |
| 42 | + const parsedSettings = JSON.parse(uiState)?.toolSettings; | |
| 43 | + if (parsedSettings) { | |
| 44 | + let migratedToolSettings = 0; | |
| 45 | + Object.entries(toFromMap).forEach(([newToolName, oldToolNames]) => { | |
| 46 | + for (const tool of oldToolNames) { | |
| 47 | + if ( | |
| 48 | + tool in parsedSettings && | |
| 49 | + validPolicyValues.includes(parsedSettings[tool]) | |
| 50 | + ) { | |
| 51 | + dispatch( | |
| 52 | + setToolPolicy({ | |
| 53 | + toolName: newToolName, | |
| 54 | + policy: parsedSettings[tool], | |
| 55 | + }), | |
| 56 | + ); | |
| 57 | + dispatch(clearToolPolicy(tool)); | |
| 58 | + migratedToolSettings++; | |
| 59 | + } | |
| 60 | + } | |
| 61 | + }); | |
| 62 | + if (migratedToolSettings > 0) { | |
| 63 | + console.log( | |
| 64 | + `Migrated ${migratedToolSettings} tool policies successfully.`, | |
| 65 | + ); | |
| 66 | + } | |
| 67 | + } | |
| 68 | + } | |
| 69 | + } | |
| 70 | +} | |
| 71 | + | |
| 72 | +export function migrateLocalStorage(dispatch: AppDispatch) { | |
| 73 | + migrateToolPolicies(dispatch); | |
| 74 | +} |
modified packages/config-yaml/src/schemas/data/index.ts +10 −0
| @@ -28,6 +28,7 @@ | ||
| 28 | 28 | editInteractionEventSchema_0_2_0, |
| 29 | 29 | editInteractionEventSchema_0_2_0_noCode, |
| 30 | 30 | } from "./editInteraction/v0.2.0.js"; |
| 31 | +import { editOutcomeEventAllSchema } from "./editOutcome/index.js"; | |
| 31 | 32 | import { |
| 32 | 33 | editOutcomeEventSchema_0_2_0, |
| 33 | 34 | editOutcomeEventSchema_0_2_0_noCode, |
| @@ -51,6 +52,11 @@ | ||
| 51 | 52 | tokensGeneratedEventSchema_0_2_0, |
| 52 | 53 | tokensGeneratedEventSchema_0_2_0_noCode, |
| 53 | 54 | } from "./tokensGenerated/v0.2.0.js"; |
| 55 | +import { toolUsageEventAllSchema } from "./toolUsage/index.js"; | |
| 56 | +import { | |
| 57 | + toolUsageEventSchema_0_2_0, | |
| 58 | + toolUsageEventSchema_0_2_0_noCode, | |
| 59 | +} from "./toolUsage/v0.2.0.js"; | |
| 54 | 60 | |
| 55 | 61 | const semverRegex = |
| 56 | 62 | /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9A-Za-z-][0-9A-Za-z-]*))*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/; |
| @@ -81,7 +87,9 @@ | ||
| 81 | 87 | tokensGenerated: tokensGeneratedEventAllSchema, |
| 82 | 88 | chatInteraction: chatInteractionEventAllSchema, |
| 83 | 89 | editInteraction: editInteractionEventAllSchema, |
| 90 | + editOutcome: editOutcomeEventAllSchema, | |
| 84 | 91 | nextEdit: nextEditEventAllSchema, |
| 92 | + toolUsage: toolUsageEventAllSchema, | |
| 85 | 93 | }); |
| 86 | 94 | |
| 87 | 95 | // Version and level specific schemas are organized here |
| @@ -109,6 +117,7 @@ | ||
| 109 | 117 | editInteraction: editInteractionEventSchema_0_2_0, |
| 110 | 118 | editOutcome: editOutcomeEventSchema_0_2_0, |
| 111 | 119 | nextEdit: nextEditEventSchema_0_2_0, |
| 120 | + toolUsage: toolUsageEventSchema_0_2_0, | |
| 112 | 121 | }, |
| 113 | 122 | noCode: { |
| 114 | 123 | autocomplete: autocompleteEventSchema_0_2_0_noCode, |
| @@ -118,6 +127,7 @@ | ||
| 118 | 127 | editInteraction: editInteractionEventSchema_0_2_0_noCode, |
| 119 | 128 | editOutcome: editOutcomeEventSchema_0_2_0_noCode, |
| 120 | 129 | nextEdit: nextEditEventSchema_0_2_0_noCode, |
| 130 | + toolUsage: toolUsageEventSchema_0_2_0_noCode, | |
| 121 | 131 | }, |
| 122 | 132 | }, |
| 123 | 133 | }; |
added packages/config-yaml/src/schemas/data/toolUsage/index.ts +11 −0
| @@ -0,0 +1,11 @@ | ||
| 1 | +import { z } from "zod"; | |
| 2 | +import { baseDevDataAllSchema } from "../base.js"; | |
| 3 | + | |
| 4 | +export const toolUsageEventAllSchema = baseDevDataAllSchema.extend({ | |
| 5 | + toolCallId: z.string(), | |
| 6 | + functionName: z.string(), | |
| 7 | + functionArgs: z.string(), | |
| 8 | + toolCallArgs: z.any(), | |
| 9 | + succeeded: z.boolean(), | |
| 10 | + output: z.array(z.any()).optional(), | |
| 11 | +}); |
added packages/config-yaml/src/schemas/data/toolUsage/v0.2.0.ts +26 −0
| @@ -0,0 +1,26 @@ | ||
| 1 | +import { toolUsageEventAllSchema } from "./index.js"; | |
| 2 | + | |
| 3 | +export const toolUsageEventSchema_0_2_0 = toolUsageEventAllSchema.pick({ | |
| 4 | + // base | |
| 5 | + timestamp: true, | |
| 6 | + userId: true, | |
| 7 | + userAgent: true, | |
| 8 | + selectedProfileId: true, | |
| 9 | + eventName: true, | |
| 10 | + schema: true, | |
| 11 | + | |
| 12 | + // tool-usage-specific | |
| 13 | + toolCallId: true, | |
| 14 | + functionName: true, | |
| 15 | + functionArgs: true, | |
| 16 | + toolCallArgs: true, | |
| 17 | + succeeded: true, | |
| 18 | + output: true, | |
| 19 | +}); | |
| 20 | + | |
| 21 | +export const toolUsageEventSchema_0_2_0_noCode = | |
| 22 | + toolUsageEventSchema_0_2_0.omit({ | |
| 23 | + functionArgs: true, | |
| 24 | + toolCallArgs: true, | |
| 25 | + output: true, | |
| 26 | + }); |