| 1 | import { JSONContent } from "@tiptap/core"; |
| 2 | import { InputModifiers } from "core"; |
| 3 | import { describe, expect, it, vi } from "vitest"; |
| 4 | import { createMockStore } from "../../util/test/mockStore"; |
| 5 | import { streamResponseThunk } from "./streamResponse"; |
| 6 | |
| 7 | // Mock external dependencies only - let selectors run naturally |
| 8 | // Removed: modelSupportsNativeTools - let it run naturally |
| 9 | |
| 10 | // Removed: addSystemMessageToolsToSystemMessage - let it run naturally |
| 11 | |
| 12 | // Mock system message construction to keep test readable |
| 13 | vi.mock("../util/getBaseSystemMessage", () => ({ |
| 14 | getBaseSystemMessage: vi.fn(), |
| 15 | })); |
| 16 | |
| 17 | import { getBaseSystemMessage } from "../util/getBaseSystemMessage"; |
| 18 | |
| 19 | // Removed: shouldAutoEnableSystemMessageTools - let it run naturally |
| 20 | |
| 21 | // Additional mocks for streamResponseThunk |
| 22 | vi.mock("posthog-js", () => ({ |
| 23 | default: { |
| 24 | capture: vi.fn(), |
| 25 | }, |
| 26 | })); |
| 27 | |
| 28 | vi.mock("uuid", () => ({ |
| 29 | v4: vi.fn(() => "mock-uuid-123"), |
| 30 | })); |
| 31 | |
| 32 | vi.mock( |
| 33 | "../../components/mainInput/TipTapEditor/utils/resolveEditorContent", |
| 34 | () => ({ |
| 35 | resolveEditorContent: vi.fn(), |
| 36 | }), |
| 37 | ); |
| 38 | |
| 39 | import { ModelDescription } from "core"; |
| 40 | import posthog from "posthog-js"; |
| 41 | import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils/resolveEditorContent"; |
| 42 | |
| 43 | const mockGetBaseSystemMessage = vi.mocked(getBaseSystemMessage); |
| 44 | |
| 45 | const mockPosthog = vi.mocked(posthog); |
| 46 | const mockResolveEditorContent = vi.mocked(resolveEditorContent); |
| 47 | |
| 48 | const mockClaudeModel: ModelDescription = { |
| 49 | title: "Claude 3.5 Sonnet", |
| 50 | model: "claude-3-5-sonnet-20241022", |
| 51 | provider: "anthropic", |
| 52 | underlyingProviderName: "anthropic", |
| 53 | completionOptions: { reasoningBudgetTokens: 2048 }, |
| 54 | }; |
| 55 | |
| 56 | // Mock editor state (what user types in the input) |
| 57 | const mockEditorState: JSONContent = { |
| 58 | type: "doc", |
| 59 | content: [ |
| 60 | { |
| 61 | type: "paragraph", |
| 62 | content: [{ type: "text", text: "Hello, please help me with this code" }], |
| 63 | }, |
| 64 | ], |
| 65 | }; |
| 66 | |
| 67 | // Mock input modifiers (codebase context, etc.) |
| 68 | const mockModifiers: InputModifiers = { |
| 69 | useCodebase: true, |
| 70 | noContext: false, |
| 71 | }; |
| 72 | |
| 73 | function setupTest() { |
| 74 | vi.clearAllMocks(); |
| 75 | |
| 76 | // Default mock implementations for external functions |
| 77 | |
| 78 | // Default mock for resolveEditorContent (can be overridden in individual tests) |
| 79 | mockResolveEditorContent.mockResolvedValue({ |
| 80 | selectedContextItems: [], |
| 81 | selectedCode: [], |
| 82 | content: "Hello, please help me with this code", |
| 83 | legacyCommandWithInput: undefined, |
| 84 | }); |
| 85 | |
| 86 | // Mock getBaseSystemMessage to return simple system message for readable tests |
| 87 | mockGetBaseSystemMessage.mockReturnValue("You are a helpful assistant."); |
| 88 | |
| 89 | // Create store with realistic state that selectors can work with |
| 90 | const mockStore = createMockStore({ |
| 91 | session: { |
| 92 | history: [ |
| 93 | { |
| 94 | message: { id: "1", role: "user", content: "Hello" }, |
| 95 | contextItems: [], |
| 96 | }, |
| 97 | ], |
| 98 | hasReasoningEnabled: false, |
| 99 | isStreaming: true, |
| 100 | id: "session-123", |
| 101 | mode: "chat", |
| 102 | streamAborter: new AbortController(), |
| 103 | contextPercentage: 0, |
| 104 | isPruned: false, |
| 105 | isInEdit: false, |
| 106 | title: "", |
| 107 | lastSessionId: undefined, |
| 108 | isSessionMetadataLoading: false, |
| 109 | allSessionMetadata: [], |
| 110 | symbols: {}, |
| 111 | codeBlockApplyStates: { |
| 112 | states: [], |
| 113 | curIndex: 0, |
| 114 | }, |
| 115 | newestToolbarPreviewForInput: {}, |
| 116 | compactionLoading: {}, |
| 117 | inlineErrorMessage: undefined, |
| 118 | }, |
| 119 | config: { |
| 120 | config: { |
| 121 | tools: [], |
| 122 | rules: [], |
| 123 | tabAutocompleteModel: undefined, |
| 124 | selectedModelByRole: { |
| 125 | chat: mockClaudeModel, |
| 126 | apply: null, |
| 127 | edit: null, |
| 128 | summarize: null, |
| 129 | autocomplete: null, |
| 130 | rerank: null, |
| 131 | embed: null, |
| 132 | }, |
| 133 | experimental: { |
| 134 | onlyUseSystemMessageTools: false, |
| 135 | }, |
| 136 | } as any, |
| 137 | lastSelectedModelByRole: { |
| 138 | chat: mockClaudeModel.title, |
| 139 | }, |
| 140 | } as any, |
| 141 | ui: { |
| 142 | toolSettings: {}, |
| 143 | ruleSettings: {}, |
| 144 | showDialog: false, |
| 145 | dialogMessage: undefined, |
| 146 | } as any, |
| 147 | }); |
| 148 | |
| 149 | const mockIdeMessenger = mockStore.mockIdeMessenger; |
| 150 | |
| 151 | return { mockStore, mockIdeMessenger }; |
| 152 | } |
| 153 | |
| 154 | describe("streamResponseThunk - tool calls", () => { |
| 155 | it("should execute streaming flow with tool call execution", async () => { |
| 156 | const { mockStore, mockIdeMessenger } = setupTest(); |
| 157 | |
| 158 | // Set up auto-approved tool setting for our test tool |
| 159 | const mockStoreWithToolSettings = createMockStore({ |
| 160 | session: { |
| 161 | history: [ |
| 162 | { |
| 163 | message: { |
| 164 | id: "1", |
| 165 | role: "user", |
| 166 | content: "Please search the codebase", |
| 167 | }, |
| 168 | contextItems: [], |
| 169 | }, |
| 170 | ], |
| 171 | hasReasoningEnabled: false, |
| 172 | isStreaming: true, |
| 173 | id: "session-123", |
| 174 | mode: "chat", |
| 175 | streamAborter: new AbortController(), |
| 176 | contextPercentage: 0, |
| 177 | isPruned: false, |
| 178 | isInEdit: false, |
| 179 | title: "", |
| 180 | lastSessionId: undefined, |
| 181 | isSessionMetadataLoading: false, |
| 182 | allSessionMetadata: [], |
| 183 | symbols: {}, |
| 184 | codeBlockApplyStates: { |
| 185 | states: [], |
| 186 | curIndex: 0, |
| 187 | }, |
| 188 | newestToolbarPreviewForInput: {}, |
| 189 | compactionLoading: {}, |
| 190 | inlineErrorMessage: undefined, |
| 191 | }, |
| 192 | config: { |
| 193 | config: { |
| 194 | tools: [], |
| 195 | rules: [], |
| 196 | tabAutocompleteModel: undefined, |
| 197 | selectedModelByRole: { |
| 198 | chat: mockClaudeModel, |
| 199 | apply: null, |
| 200 | edit: null, |
| 201 | summarize: null, |
| 202 | autocomplete: null, |
| 203 | rerank: null, |
| 204 | embed: null, |
| 205 | }, |
| 206 | experimental: { |
| 207 | onlyUseSystemMessageTools: false, |
| 208 | }, |
| 209 | } as any, |
| 210 | lastSelectedModelByRole: { |
| 211 | chat: mockClaudeModel.title, |
| 212 | }, |
| 213 | } as any, |
| 214 | ui: { |
| 215 | toolSettings: { |
| 216 | search_codebase: "allowedWithoutPermission", // Auto-approve this tool |
| 217 | }, |
| 218 | ruleSettings: {}, |
| 219 | showDialog: false, |
| 220 | dialogMessage: undefined, |
| 221 | } as any, |
| 222 | }); |
| 223 | |
| 224 | const mockIdeMessengerWithTool = mockStoreWithToolSettings.mockIdeMessenger; |
| 225 | |
| 226 | // Setup successful compilation and tool responses |
| 227 | mockIdeMessengerWithTool.request.mockImplementation( |
| 228 | (endpoint: string, data: any) => { |
| 229 | if (endpoint === "llm/compileChat") { |
| 230 | return Promise.resolve({ |
| 231 | status: "success", |
| 232 | content: { |
| 233 | compiledChatMessages: [ |
| 234 | { role: "user", content: "Please search the codebase" }, |
| 235 | ], |
| 236 | didPrune: false, |
| 237 | contextPercentage: 0.9, |
| 238 | }, |
| 239 | }); |
| 240 | } else if (endpoint === "tools/evaluatePolicy") { |
| 241 | // Mock dynamic policy evaluation - return auto-approve for this test |
| 242 | return Promise.resolve({ |
| 243 | status: "success", |
| 244 | content: { policy: "allowedWithoutPermission" }, |
| 245 | }); |
| 246 | } else if (endpoint === "tools/call") { |
| 247 | // Mock server-side tool call response |
| 248 | return Promise.resolve({ |
| 249 | status: "success", |
| 250 | content: { |
| 251 | contextItems: [ |
| 252 | { |
| 253 | name: "Search Results", |
| 254 | description: "Found 3 matches", |
| 255 | content: "Result 1\nResult 2\nResult 3", |
| 256 | icon: "search", |
| 257 | hidden: false, |
| 258 | }, |
| 259 | ], |
| 260 | errorMessage: undefined, |
| 261 | }, |
| 262 | }); |
| 263 | } else if (endpoint === "history/save") { |
| 264 | // Mock session save |
| 265 | return Promise.resolve({ status: "success" }); |
| 266 | } else if (endpoint === "history/list") { |
| 267 | return Promise.resolve({ status: "success", content: [] }); |
| 268 | } |
| 269 | // Let other endpoints pass through or return success |
| 270 | return Promise.resolve({ status: "success", content: {} }); |
| 271 | }, |
| 272 | ); |
| 273 | |
| 274 | // Setup streaming generator with tool call |
| 275 | async function* mockStreamGeneratorWithTool() { |
| 276 | yield [ |
| 277 | { role: "assistant", content: "I'll search the codebase for you." }, |
| 278 | ]; |
| 279 | yield [ |
| 280 | { |
| 281 | role: "assistant", |
| 282 | content: "", |
| 283 | toolCalls: [ |
| 284 | { |
| 285 | id: "tool-call-1", |
| 286 | type: "function", |
| 287 | function: { |
| 288 | name: "search_codebase", |
| 289 | arguments: JSON.stringify({ query: "test function" }), |
| 290 | }, |
| 291 | }, |
| 292 | ], |
| 293 | }, |
| 294 | ]; |
| 295 | return { |
| 296 | prompt: "Please search the codebase", |
| 297 | completion: "I'll search the codebase for you.", |
| 298 | modelProvider: "anthropic", |
| 299 | }; |
| 300 | } |
| 301 | |
| 302 | // Mock different streaming responses for multiple calls |
| 303 | let streamCallCount = 0; |
| 304 | mockIdeMessengerWithTool.llmStreamChat.mockImplementation(() => { |
| 305 | streamCallCount++; |
| 306 | if (streamCallCount === 1) { |
| 307 | // First call - main streaming with tool call |
| 308 | return mockStreamGeneratorWithTool(); |
| 309 | } else { |
| 310 | // Subsequent calls from streamResponseAfterToolCall - return minimal response |
| 311 | async function* simpleGenerator() { |
| 312 | yield [{ role: "assistant", content: "Search completed." }]; |
| 313 | return { |
| 314 | prompt: "continuing after tool", |
| 315 | completion: "Search completed.", |
| 316 | modelProvider: "anthropic", |
| 317 | }; |
| 318 | } |
| 319 | return simpleGenerator(); |
| 320 | } |
| 321 | }); |
| 322 | |
| 323 | // Track isStreaming state changes to detect UI flashing during auto-approved tool execution |
| 324 | const streamingStateChanges: boolean[] = []; |
| 325 | let lastStreamingState = |
| 326 | mockStoreWithToolSettings.getState().session.isStreaming; |
| 327 | // Record the initial state |
| 328 | streamingStateChanges.push(lastStreamingState); |
| 329 | |
| 330 | // Subscribe to store changes to catch ALL state updates |
| 331 | const unsubscribe = mockStoreWithToolSettings.subscribe(() => { |
| 332 | const currentState = |
| 333 | mockStoreWithToolSettings.getState().session.isStreaming; |
| 334 | if (currentState !== lastStreamingState) { |
| 335 | console.log( |
| 336 | `Store subscription: isStreaming changed from ${lastStreamingState} to ${currentState}`, |
| 337 | ); |
| 338 | streamingStateChanges.push(currentState); |
| 339 | lastStreamingState = currentState; |
| 340 | } |
| 341 | }); |
| 342 | |
| 343 | // Execute thunk |
| 344 | const result = await mockStoreWithToolSettings.dispatch( |
| 345 | streamResponseThunk({ |
| 346 | editorState: mockEditorState, |
| 347 | modifiers: mockModifiers, |
| 348 | }) as any, |
| 349 | ); |
| 350 | |
| 351 | // Debug: check what happened |
| 352 | const debugState = mockStoreWithToolSettings.getState(); |
| 353 | const finalStreamingState = debugState.session.isStreaming; |
| 354 | const toolCallStates = debugState.session.history.flatMap( |
| 355 | (item) => item.toolCallStates || [], |
| 356 | ); |
| 357 | |
| 358 | console.log("Initial streaming state:", lastStreamingState); |
| 359 | console.log("Final streaming state:", finalStreamingState); |
| 360 | console.log( |
| 361 | "Tool call states:", |
| 362 | toolCallStates.map((t) => ({ |
| 363 | id: t.toolCallId, |
| 364 | status: t.status, |
| 365 | toolName: t.toolCall.function.name, |
| 366 | })), |
| 367 | ); |
| 368 | console.log("Tool settings:", debugState.ui.toolSettings); |
| 369 | console.log( |
| 370 | "Auto-approved tool streaming state changes:", |
| 371 | streamingStateChanges, |
| 372 | ); |
| 373 | |
| 374 | // Unsubscribe from store updates |
| 375 | unsubscribe(); |
| 376 | |
| 377 | // Verify no UI flashing during auto-approved tool execution |
| 378 | // DESIRED: Should stay true throughout tool execution, only becoming false at the very end |
| 379 | // We expect [true, false] - streaming starts true, stays true during tool execution, then false when all done |
| 380 | expect(streamingStateChanges).toEqual([true, false]); |
| 381 | |
| 382 | // Verify key actions are dispatched (tool calls trigger a complex cascade, so we verify key actions exist) |
| 383 | const dispatchedActions = (mockStoreWithToolSettings as any).getActions(); |
| 384 | |
| 385 | // Verify exact action sequence |
| 386 | const actionTypes = dispatchedActions.map((action: any) => action.type); |
| 387 | expect(actionTypes).toEqual([ |
| 388 | "chat/streamResponse/pending", |
| 389 | "chat/streamWrapper/pending", |
| 390 | "session/submitEditorAndInitAtIndex", |
| 391 | "session/resetNextCodeBlockToApplyIndex", |
| 392 | "symbols/updateFromContextItems/pending", |
| 393 | "session/updateHistoryItemAtIndex", |
| 394 | "chat/streamNormalInput/pending", |
| 395 | "session/setAppliedRulesAtIndex", |
| 396 | "session/setActive", |
| 397 | "session/setInlineErrorMessage", |
| 398 | "session/setIsPruned", |
| 399 | "session/setContextPercentage", |
| 400 | "symbols/updateFromContextItems/fulfilled", |
| 401 | "session/streamUpdate", |
| 402 | "session/streamUpdate", |
| 403 | "session/addPromptCompletionPair", |
| 404 | "session/setToolGenerated", |
| 405 | "chat/callTool/pending", |
| 406 | "session/setToolCallCalling", |
| 407 | "session/updateToolCallOutput", |
| 408 | "session/acceptToolCall", |
| 409 | "chat/streamAfterToolCall/pending", |
| 410 | "chat/streamWrapper/pending", |
| 411 | "session/resetNextCodeBlockToApplyIndex", |
| 412 | "session/streamUpdate", |
| 413 | "chat/streamNormalInput/pending", |
| 414 | "session/setAppliedRulesAtIndex", |
| 415 | "session/setActive", |
| 416 | "session/setInlineErrorMessage", |
| 417 | "session/setIsPruned", |
| 418 | "session/setContextPercentage", |
| 419 | "session/streamUpdate", |
| 420 | "session/addPromptCompletionPair", |
| 421 | "session/setInactive", |
| 422 | "chat/streamNormalInput/fulfilled", |
| 423 | "session/saveCurrent/pending", |
| 424 | "session/update/pending", |
| 425 | "session/updateSessionMetadata", |
| 426 | "session/refreshMetadata/pending", |
| 427 | "session/setIsSessionMetadataLoading", |
| 428 | "session/setAllSessionMetadata", |
| 429 | "session/refreshMetadata/fulfilled", |
| 430 | "session/update/fulfilled", |
| 431 | "session/saveCurrent/fulfilled", |
| 432 | "chat/streamWrapper/fulfilled", |
| 433 | "chat/streamAfterToolCall/fulfilled", |
| 434 | "chat/callTool/fulfilled", |
| 435 | "chat/streamNormalInput/fulfilled", |
| 436 | "session/saveCurrent/pending", |
| 437 | "session/update/pending", |
| 438 | "session/updateSessionMetadata", |
| 439 | "session/refreshMetadata/pending", |
| 440 | "session/setIsSessionMetadataLoading", |
| 441 | "session/setAllSessionMetadata", |
| 442 | "session/refreshMetadata/fulfilled", |
| 443 | "session/update/fulfilled", |
| 444 | "session/saveCurrent/fulfilled", |
| 445 | "chat/streamWrapper/fulfilled", |
| 446 | "chat/streamResponse/fulfilled", |
| 447 | ]); |
| 448 | |
| 449 | // Verify key payload data for important actions |
| 450 | const setContextPercentageAction = dispatchedActions.find( |
| 451 | (a: any) => a.type === "session/setContextPercentage", |
| 452 | ); |
| 453 | expect(setContextPercentageAction.payload).toBe(0.9); |
| 454 | |
| 455 | const streamUpdates = dispatchedActions.filter( |
| 456 | (a: any) => a.type === "session/streamUpdate", |
| 457 | ); |
| 458 | expect(streamUpdates[0].payload).toEqual([ |
| 459 | { role: "assistant", content: "I'll search the codebase for you." }, |
| 460 | ]); |
| 461 | expect(streamUpdates[1].payload).toEqual([ |
| 462 | { |
| 463 | role: "assistant", |
| 464 | content: "", |
| 465 | toolCalls: [ |
| 466 | { |
| 467 | id: "tool-call-1", |
| 468 | type: "function", |
| 469 | function: { |
| 470 | name: "search_codebase", |
| 471 | arguments: JSON.stringify({ query: "test function" }), |
| 472 | }, |
| 473 | }, |
| 474 | ], |
| 475 | }, |
| 476 | ]); |
| 477 | |
| 478 | const completionPairs = dispatchedActions.filter( |
| 479 | (a: any) => a.type === "session/addPromptCompletionPair", |
| 480 | ); |
| 481 | expect(completionPairs[0].payload).toEqual([ |
| 482 | { |
| 483 | completion: "I'll search the codebase for you.", |
| 484 | modelProvider: "anthropic", |
| 485 | prompt: "Please search the codebase", |
| 486 | }, |
| 487 | ]); |
| 488 | |
| 489 | const toolCallActions = dispatchedActions.filter( |
| 490 | (a: any) => a.type === "session/setToolCallCalling", |
| 491 | ); |
| 492 | expect(toolCallActions[0].payload).toEqual({ toolCallId: "tool-call-1" }); |
| 493 | |
| 494 | const toolOutputActions = dispatchedActions.filter( |
| 495 | (a: any) => a.type === "session/updateToolCallOutput", |
| 496 | ); |
| 497 | expect(toolOutputActions[0].payload).toEqual({ |
| 498 | toolCallId: "tool-call-1", |
| 499 | contextItems: [ |
| 500 | { |
| 501 | name: "Search Results", |
| 502 | description: "Found 3 matches", |
| 503 | content: "Result 1\nResult 2\nResult 3", |
| 504 | icon: "search", |
| 505 | hidden: false, |
| 506 | }, |
| 507 | ], |
| 508 | }); |
| 509 | |
| 510 | // Verify IDE messenger calls |
| 511 | expect(mockIdeMessengerWithTool.request).toHaveBeenCalledWith( |
| 512 | "llm/compileChat", |
| 513 | { |
| 514 | messages: [ |
| 515 | { |
| 516 | role: "system", |
| 517 | content: "You are a helpful assistant.", |
| 518 | }, |
| 519 | { |
| 520 | role: "user", |
| 521 | content: [ |
| 522 | { |
| 523 | type: "text", |
| 524 | text: "Please search the codebase", |
| 525 | }, |
| 526 | ], |
| 527 | }, |
| 528 | { |
| 529 | role: "user", |
| 530 | content: [ |
| 531 | { |
| 532 | type: "text", |
| 533 | text: "Hello, please help me with this code", |
| 534 | }, |
| 535 | ], |
| 536 | }, |
| 537 | ], |
| 538 | options: { |
| 539 | reasoning: false, |
| 540 | }, |
| 541 | }, |
| 542 | ); |
| 543 | |
| 544 | expect(mockIdeMessengerWithTool.request).toHaveBeenCalledWith( |
| 545 | "tools/call", |
| 546 | { |
| 547 | toolCall: { |
| 548 | id: "tool-call-1", |
| 549 | type: "function", |
| 550 | function: { |
| 551 | name: "search_codebase", |
| 552 | arguments: JSON.stringify({ query: "test function" }), |
| 553 | }, |
| 554 | }, |
| 555 | }, |
| 556 | ); |
| 557 | |
| 558 | // Verify that multiple compilation calls were made (due to tool call continuation) |
| 559 | const compileCallsCount = |
| 560 | mockIdeMessengerWithTool.request.mock.calls.filter( |
| 561 | (call: any) => call[0] === "llm/compileChat", |
| 562 | ).length; |
| 563 | expect(compileCallsCount).toBeGreaterThanOrEqual(1); |
| 564 | |
| 565 | expect(result.type).toBe("chat/streamResponse/fulfilled"); |
| 566 | |
| 567 | // Verify telemetry events for auto-approved tool execution |
| 568 | // Use partial matching to allow additional fields (e.g. model) in payload |
| 569 | expect(mockPosthog.capture).toHaveBeenCalledWith( |
| 570 | "tool_call_decision", |
| 571 | expect.objectContaining({ |
| 572 | decision: "auto_accept", |
| 573 | toolName: "search_codebase", |
| 574 | toolCallId: "tool-call-1", |
| 575 | }), |
| 576 | ); |
| 577 | |
| 578 | expect(mockPosthog.capture).toHaveBeenCalledWith( |
| 579 | "tool_call_outcome", |
| 580 | expect.objectContaining({ |
| 581 | succeeded: true, |
| 582 | toolName: "search_codebase", |
| 583 | errorReason: undefined, |
| 584 | duration_ms: expect.any(Number), |
| 585 | }), |
| 586 | ); |
| 587 | |
| 588 | // Verify final state after tool call execution |
| 589 | const finalState = mockStoreWithToolSettings.getState(); |
| 590 | |
| 591 | // Check that the tool was executed (status should be 'done' if auto-approved and executed) |
| 592 | const toolCallState = finalState.session.history.find( |
| 593 | (item) => item.toolCallStates && item.toolCallStates.length > 0, |
| 594 | )?.toolCallStates?.[0]; |
| 595 | |
| 596 | // With proper mocking, the tool should be auto-executed |
| 597 | expect(toolCallState?.status).toBe("done"); |
| 598 | expect(toolCallState?.output).toBeDefined(); |
| 599 | |
| 600 | expect(finalState).toEqual({ |
| 601 | session: { |
| 602 | history: [ |
| 603 | { |
| 604 | contextItems: [], |
| 605 | message: { |
| 606 | id: "1", |
| 607 | role: "user", |
| 608 | content: "Please search the codebase", |
| 609 | }, |
| 610 | }, |
| 611 | { |
| 612 | appliedRules: [], |
| 613 | contextItems: [], |
| 614 | editorState: mockEditorState, |
| 615 | message: { |
| 616 | id: expect.any(String), |
| 617 | role: "user", |
| 618 | content: "Hello, please help me with this code", |
| 619 | }, |
| 620 | }, |
| 621 | { |
| 622 | contextItems: [], |
| 623 | message: { |
| 624 | content: "I'll search the codebase for you.", |
| 625 | id: expect.any(String), |
| 626 | role: "assistant", |
| 627 | toolCalls: [ |
| 628 | { |
| 629 | id: "tool-call-1", |
| 630 | type: "function", |
| 631 | function: { |
| 632 | name: "search_codebase", |
| 633 | arguments: JSON.stringify({ query: "test function" }), |
| 634 | }, |
| 635 | }, |
| 636 | ], |
| 637 | }, |
| 638 | promptLogs: [ |
| 639 | { |
| 640 | completion: "I'll search the codebase for you.", |
| 641 | modelProvider: "anthropic", |
| 642 | prompt: "Please search the codebase", |
| 643 | }, |
| 644 | ], |
| 645 | toolCallStates: [ |
| 646 | { |
| 647 | toolCallId: "tool-call-1", |
| 648 | toolCall: { |
| 649 | id: "tool-call-1", |
| 650 | type: "function", |
| 651 | function: { |
| 652 | name: "search_codebase", |
| 653 | arguments: JSON.stringify({ query: "test function" }), |
| 654 | }, |
| 655 | }, |
| 656 | parsedArgs: { query: "test function" }, |
| 657 | status: "done", |
| 658 | output: [ |
| 659 | { |
| 660 | name: "Search Results", |
| 661 | description: "Found 3 matches", |
| 662 | content: "Result 1\nResult 2\nResult 3", |
| 663 | icon: "search", |
| 664 | hidden: false, |
| 665 | }, |
| 666 | ], |
| 667 | }, |
| 668 | ], |
| 669 | }, |
| 670 | { |
| 671 | contextItems: [], |
| 672 | message: { |
| 673 | content: "Result 1\nResult 2\nResult 3", |
| 674 | id: expect.any(String), |
| 675 | role: "tool", |
| 676 | toolCallId: "tool-call-1", |
| 677 | }, |
| 678 | }, |
| 679 | { |
| 680 | contextItems: [], |
| 681 | isGatheringContext: false, |
| 682 | message: { |
| 683 | content: "Search completed.", |
| 684 | id: "mock-uuid-123", |
| 685 | role: "assistant", |
| 686 | }, |
| 687 | promptLogs: [ |
| 688 | { |
| 689 | completion: "Search completed.", |
| 690 | modelProvider: "anthropic", |
| 691 | prompt: "continuing after tool", |
| 692 | }, |
| 693 | ], |
| 694 | }, |
| 695 | ], |
| 696 | hasReasoningEnabled: false, |
| 697 | isStreaming: false, |
| 698 | id: "session-123", |
| 699 | mode: "chat", |
| 700 | streamAborter: expect.any(AbortController), |
| 701 | contextPercentage: 0.9, |
| 702 | isPruned: false, |
| 703 | isInEdit: false, |
| 704 | title: "New Session", |
| 705 | lastSessionId: undefined, |
| 706 | isSessionMetadataLoading: false, |
| 707 | allSessionMetadata: [], |
| 708 | symbols: {}, |
| 709 | codeBlockApplyStates: { |
| 710 | states: [], |
| 711 | curIndex: 0, |
| 712 | }, |
| 713 | newestToolbarPreviewForInput: {}, |
| 714 | compactionLoading: {}, |
| 715 | inlineErrorMessage: undefined, |
| 716 | }, |
| 717 | config: { |
| 718 | config: { |
| 719 | tools: [], |
| 720 | rules: [], |
| 721 | tabAutocompleteModel: undefined, |
| 722 | selectedModelByRole: { |
| 723 | chat: mockClaudeModel, |
| 724 | apply: null, |
| 725 | edit: null, |
| 726 | summarize: null, |
| 727 | autocomplete: null, |
| 728 | rerank: null, |
| 729 | embed: null, |
| 730 | }, |
| 731 | experimental: { |
| 732 | onlyUseSystemMessageTools: false, |
| 733 | }, |
| 734 | }, |
| 735 | lastSelectedModelByRole: { |
| 736 | chat: mockClaudeModel.title, |
| 737 | }, |
| 738 | loading: false, |
| 739 | configError: undefined, |
| 740 | }, |
| 741 | ui: { |
| 742 | toolSettings: { |
| 743 | search_codebase: "allowedWithoutPermission", |
| 744 | }, |
| 745 | ruleSettings: {}, |
| 746 | showDialog: false, |
| 747 | dialogMessage: undefined, |
| 748 | }, |
| 749 | editModeState: { |
| 750 | isInEdit: false, |
| 751 | returnToMode: "chat", |
| 752 | }, |
| 753 | indexing: { |
| 754 | indexing: { |
| 755 | statuses: {}, |
| 756 | hiddenChatPeekTypes: { |
| 757 | docs: false, |
| 758 | }, |
| 759 | }, |
| 760 | }, |
| 761 | tabs: { |
| 762 | tabsItems: [], |
| 763 | }, |
| 764 | profiles: { |
| 765 | organizations: [], |
| 766 | selectedProfileId: null, |
| 767 | selectedOrganizationId: null, |
| 768 | preferencesByProfileId: {}, |
| 769 | }, |
| 770 | }); |
| 771 | }); |
| 772 | |
| 773 | it("should handle tool call rejection error", async () => { |
| 774 | const { mockStore, mockIdeMessenger } = setupTest(); |
| 775 | |
| 776 | // Create store with tool settings that will reject the tool call |
| 777 | const mockStoreWithToolReject = createMockStore({ |
| 778 | session: { |
| 779 | history: [ |
| 780 | { |
| 781 | message: { |
| 782 | id: "1", |
| 783 | role: "user", |
| 784 | content: "Please edit this file", |
| 785 | }, |
| 786 | contextItems: [], |
| 787 | }, |
| 788 | ], |
| 789 | hasReasoningEnabled: false, |
| 790 | isStreaming: true, |
| 791 | id: "session-123", |
| 792 | mode: "chat", |
| 793 | streamAborter: new AbortController(), |
| 794 | contextPercentage: 0, |
| 795 | isPruned: false, |
| 796 | isInEdit: false, |
| 797 | title: "", |
| 798 | lastSessionId: undefined, |
| 799 | isSessionMetadataLoading: false, |
| 800 | allSessionMetadata: [], |
| 801 | symbols: {}, |
| 802 | codeBlockApplyStates: { |
| 803 | states: [], |
| 804 | curIndex: 0, |
| 805 | }, |
| 806 | newestToolbarPreviewForInput: {}, |
| 807 | compactionLoading: {}, |
| 808 | inlineErrorMessage: undefined, |
| 809 | }, |
| 810 | config: { |
| 811 | config: { |
| 812 | tools: [], |
| 813 | rules: [], |
| 814 | tabAutocompleteModel: undefined, |
| 815 | selectedModelByRole: { |
| 816 | chat: mockClaudeModel, |
| 817 | apply: null, |
| 818 | edit: null, |
| 819 | summarize: null, |
| 820 | autocomplete: null, |
| 821 | rerank: null, |
| 822 | embed: null, |
| 823 | }, |
| 824 | experimental: { |
| 825 | onlyUseSystemMessageTools: false, |
| 826 | }, |
| 827 | } as any, |
| 828 | lastSelectedModelByRole: { |
| 829 | chat: mockClaudeModel.title, |
| 830 | }, |
| 831 | } as any, |
| 832 | ui: { |
| 833 | toolSettings: { |
| 834 | edit_existing_file: "disabled", // Tool is disabled/rejected |
| 835 | }, |
| 836 | ruleSettings: {}, |
| 837 | showDialog: false, |
| 838 | dialogMessage: undefined, |
| 839 | } as any, |
| 840 | }); |
| 841 | |
| 842 | const mockIdeMessengerReject = mockStoreWithToolReject.mockIdeMessenger; |
| 843 | |
| 844 | // Setup successful compilation |
| 845 | mockIdeMessengerReject.request.mockResolvedValue({ |
| 846 | status: "success", |
| 847 | content: { |
| 848 | compiledChatMessages: [ |
| 849 | { role: "user", content: "Please edit this file" }, |
| 850 | ], |
| 851 | didPrune: false, |
| 852 | contextPercentage: 0.7, |
| 853 | }, |
| 854 | }); |
| 855 | |
| 856 | // Setup streaming generator with tool call that will be rejected |
| 857 | async function* mockStreamGeneratorWithRejectedTool() { |
| 858 | yield [{ role: "assistant", content: "I'll edit the file for you." }]; |
| 859 | yield [ |
| 860 | { |
| 861 | role: "assistant", |
| 862 | content: "", |
| 863 | toolCalls: [ |
| 864 | { |
| 865 | id: "tool-reject-1", |
| 866 | type: "function", |
| 867 | function: { |
| 868 | name: "edit_existing_file", |
| 869 | arguments: JSON.stringify({ |
| 870 | filepath: "test.js", |
| 871 | changes: "const x = 1;", |
| 872 | }), |
| 873 | }, |
| 874 | }, |
| 875 | ], |
| 876 | }, |
| 877 | ]; |
| 878 | return { |
| 879 | prompt: "Please edit this file", |
| 880 | completion: "I'll edit the file for you.", |
| 881 | modelProvider: "anthropic", |
| 882 | }; |
| 883 | } |
| 884 | |
| 885 | mockIdeMessengerReject.llmStreamChat.mockReturnValue( |
| 886 | mockStreamGeneratorWithRejectedTool(), |
| 887 | ); |
| 888 | |
| 889 | // Execute thunk |
| 890 | const result = await mockStoreWithToolReject.dispatch( |
| 891 | streamResponseThunk({ |
| 892 | editorState: mockEditorState, |
| 893 | modifiers: mockModifiers, |
| 894 | }) as any, |
| 895 | ); |
| 896 | |
| 897 | // Verify thunk completed successfully (tool rejection is handled gracefully) |
| 898 | expect(result.type).toBe("chat/streamResponse/fulfilled"); |
| 899 | |
| 900 | // Verify exact action sequence includes tool generation but rejection handling |
| 901 | const dispatchedActions = (mockStoreWithToolReject as any).getActions(); |
| 902 | expect(dispatchedActions).toEqual([ |
| 903 | { |
| 904 | type: "chat/streamResponse/pending", |
| 905 | meta: { |
| 906 | arg: { |
| 907 | editorState: mockEditorState, |
| 908 | modifiers: mockModifiers, |
| 909 | }, |
| 910 | requestId: expect.any(String), |
| 911 | requestStatus: "pending", |
| 912 | }, |
| 913 | payload: undefined, |
| 914 | }, |
| 915 | { |
| 916 | type: "chat/streamWrapper/pending", |
| 917 | meta: { |
| 918 | arg: expect.any(Function), |
| 919 | requestId: expect.any(String), |
| 920 | requestStatus: "pending", |
| 921 | }, |
| 922 | payload: undefined, |
| 923 | }, |
| 924 | { |
| 925 | type: "session/submitEditorAndInitAtIndex", |
| 926 | payload: { |
| 927 | editorState: mockEditorState, |
| 928 | index: 1, |
| 929 | }, |
| 930 | }, |
| 931 | { |
| 932 | type: "session/resetNextCodeBlockToApplyIndex", |
| 933 | payload: undefined, |
| 934 | }, |
| 935 | { |
| 936 | type: "symbols/updateFromContextItems/pending", |
| 937 | meta: { |
| 938 | arg: [], |
| 939 | requestId: expect.any(String), |
| 940 | requestStatus: "pending", |
| 941 | }, |
| 942 | payload: undefined, |
| 943 | }, |
| 944 | { |
| 945 | type: "session/updateHistoryItemAtIndex", |
| 946 | payload: { |
| 947 | index: 1, |
| 948 | updates: { |
| 949 | contextItems: [], |
| 950 | message: { |
| 951 | content: "Hello, please help me with this code", |
| 952 | id: "mock-uuid-123", |
| 953 | role: "user", |
| 954 | }, |
| 955 | }, |
| 956 | }, |
| 957 | }, |
| 958 | { |
| 959 | type: "chat/streamNormalInput/pending", |
| 960 | meta: { |
| 961 | arg: { |
| 962 | legacySlashCommandData: undefined, |
| 963 | }, |
| 964 | requestId: expect.any(String), |
| 965 | requestStatus: "pending", |
| 966 | }, |
| 967 | payload: undefined, |
| 968 | }, |
| 969 | { |
| 970 | type: "session/setAppliedRulesAtIndex", |
| 971 | payload: { |
| 972 | appliedRules: [], |
| 973 | index: 1, |
| 974 | }, |
| 975 | }, |
| 976 | { |
| 977 | type: "session/setActive", |
| 978 | payload: undefined, |
| 979 | }, |
| 980 | { |
| 981 | type: "session/setInlineErrorMessage", |
| 982 | payload: undefined, |
| 983 | }, |
| 984 | { |
| 985 | type: "session/setIsPruned", |
| 986 | payload: false, |
| 987 | }, |
| 988 | { |
| 989 | type: "session/setContextPercentage", |
| 990 | payload: 0.7, |
| 991 | }, |
| 992 | { |
| 993 | type: "symbols/updateFromContextItems/fulfilled", |
| 994 | meta: { |
| 995 | arg: [], |
| 996 | requestId: expect.any(String), |
| 997 | requestStatus: "fulfilled", |
| 998 | }, |
| 999 | payload: undefined, |
| 1000 | }, |
| 1001 | { |
| 1002 | type: "session/streamUpdate", |
| 1003 | payload: [ |
| 1004 | { |
| 1005 | role: "assistant", |
| 1006 | content: "I'll edit the file for you.", |
| 1007 | }, |
| 1008 | ], |
| 1009 | }, |
| 1010 | { |
| 1011 | type: "session/streamUpdate", |
| 1012 | payload: [ |
| 1013 | { |
| 1014 | role: "assistant", |
| 1015 | content: "", |
| 1016 | toolCalls: [ |
| 1017 | { |
| 1018 | id: "tool-reject-1", |
| 1019 | type: "function", |
| 1020 | function: { |
| 1021 | name: "edit_existing_file", |
| 1022 | arguments: '{"filepath":"test.js","changes":"const x = 1;"}', |
| 1023 | }, |
| 1024 | }, |
| 1025 | ], |
| 1026 | }, |
| 1027 | ], |
| 1028 | }, |
| 1029 | { |
| 1030 | type: "session/addPromptCompletionPair", |
| 1031 | payload: [ |
| 1032 | { |
| 1033 | completion: "I'll edit the file for you.", |
| 1034 | modelProvider: "anthropic", |
| 1035 | prompt: "Please edit this file", |
| 1036 | }, |
| 1037 | ], |
| 1038 | }, |
| 1039 | { |
| 1040 | type: "session/errorToolCall", |
| 1041 | payload: { |
| 1042 | toolCallId: "tool-reject-1", |
| 1043 | }, |
| 1044 | }, |
| 1045 | { |
| 1046 | type: "session/updateToolCallOutput", |
| 1047 | payload: { |
| 1048 | toolCallId: "tool-reject-1", |
| 1049 | contextItems: [ |
| 1050 | { |
| 1051 | icon: "problems", |
| 1052 | name: "Security Policy Violation", |
| 1053 | description: "Command Disabled", |
| 1054 | content: `This command has been disabled by security policy:\n\nedit_existing_file\n\nThis command cannot be executed as it may pose a security risk.`, |
| 1055 | hidden: false, |
| 1056 | }, |
| 1057 | ], |
| 1058 | }, |
| 1059 | }, |
| 1060 | { |
| 1061 | type: "session/setInactive", |
| 1062 | payload: undefined, |
| 1063 | }, |
| 1064 | { |
| 1065 | type: "chat/streamNormalInput/fulfilled", |
| 1066 | meta: { |
| 1067 | arg: { |
| 1068 | legacySlashCommandData: undefined, |
| 1069 | }, |
| 1070 | requestId: expect.any(String), |
| 1071 | requestStatus: "fulfilled", |
| 1072 | }, |
| 1073 | payload: undefined, |
| 1074 | }, |
| 1075 | { |
| 1076 | type: "session/saveCurrent/pending", |
| 1077 | meta: { |
| 1078 | arg: { |
| 1079 | generateTitle: true, |
| 1080 | openNewSession: false, |
| 1081 | }, |
| 1082 | requestId: expect.any(String), |
| 1083 | requestStatus: "pending", |
| 1084 | }, |
| 1085 | payload: undefined, |
| 1086 | }, |
| 1087 | { |
| 1088 | type: "session/update/pending", |
| 1089 | meta: { |
| 1090 | arg: expect.objectContaining({ |
| 1091 | history: expect.any(Array), |
| 1092 | sessionId: "session-123", |
| 1093 | title: "New Session", |
| 1094 | workspaceDirectory: "", |
| 1095 | }), |
| 1096 | requestId: expect.any(String), |
| 1097 | requestStatus: "pending", |
| 1098 | }, |
| 1099 | payload: undefined, |
| 1100 | }, |
| 1101 | { |
| 1102 | type: "session/updateSessionMetadata", |
| 1103 | payload: { |
| 1104 | sessionId: "session-123", |
| 1105 | title: "New Session", |
| 1106 | }, |
| 1107 | }, |
| 1108 | { |
| 1109 | type: "session/refreshMetadata/pending", |
| 1110 | meta: { |
| 1111 | arg: {}, |
| 1112 | requestId: expect.any(String), |
| 1113 | requestStatus: "pending", |
| 1114 | }, |
| 1115 | payload: undefined, |
| 1116 | }, |
| 1117 | { |
| 1118 | type: "session/setIsSessionMetadataLoading", |
| 1119 | payload: false, |
| 1120 | }, |
| 1121 | { |
| 1122 | type: "session/setAllSessionMetadata", |
| 1123 | payload: { |
| 1124 | compiledChatMessages: [ |
| 1125 | { |
| 1126 | content: "Please edit this file", |
| 1127 | role: "user", |
| 1128 | }, |
| 1129 | ], |
| 1130 | contextPercentage: 0.7, |
| 1131 | didPrune: false, |
| 1132 | }, |
| 1133 | }, |
| 1134 | { |
| 1135 | type: "session/refreshMetadata/fulfilled", |
| 1136 | meta: { |
| 1137 | arg: {}, |
| 1138 | requestId: expect.any(String), |
| 1139 | requestStatus: "fulfilled", |
| 1140 | }, |
| 1141 | payload: { |
| 1142 | compiledChatMessages: [ |
| 1143 | { |
| 1144 | content: "Please edit this file", |
| 1145 | role: "user", |
| 1146 | }, |
| 1147 | ], |
| 1148 | contextPercentage: 0.7, |
| 1149 | didPrune: false, |
| 1150 | }, |
| 1151 | }, |
| 1152 | { |
| 1153 | type: "session/update/fulfilled", |
| 1154 | meta: { |
| 1155 | arg: expect.objectContaining({ |
| 1156 | history: expect.any(Array), |
| 1157 | sessionId: "session-123", |
| 1158 | title: "New Session", |
| 1159 | workspaceDirectory: "", |
| 1160 | }), |
| 1161 | requestId: expect.any(String), |
| 1162 | requestStatus: "fulfilled", |
| 1163 | }, |
| 1164 | payload: undefined, |
| 1165 | }, |
| 1166 | { |
| 1167 | type: "session/saveCurrent/fulfilled", |
| 1168 | meta: { |
| 1169 | arg: { |
| 1170 | generateTitle: true, |
| 1171 | openNewSession: false, |
| 1172 | }, |
| 1173 | requestId: expect.any(String), |
| 1174 | requestStatus: "fulfilled", |
| 1175 | }, |
| 1176 | payload: undefined, |
| 1177 | }, |
| 1178 | { |
| 1179 | type: "chat/streamWrapper/fulfilled", |
| 1180 | meta: { |
| 1181 | arg: expect.any(Function), |
| 1182 | requestId: expect.any(String), |
| 1183 | requestStatus: "fulfilled", |
| 1184 | }, |
| 1185 | payload: undefined, |
| 1186 | }, |
| 1187 | { |
| 1188 | type: "chat/streamResponse/fulfilled", |
| 1189 | meta: { |
| 1190 | arg: { |
| 1191 | editorState: mockEditorState, |
| 1192 | modifiers: mockModifiers, |
| 1193 | }, |
| 1194 | requestId: expect.any(String), |
| 1195 | requestStatus: "fulfilled", |
| 1196 | }, |
| 1197 | payload: undefined, |
| 1198 | }, |
| 1199 | ]); |
| 1200 | |
| 1201 | // Verify IDE messenger calls - compilation should succeed, streaming should happen |
| 1202 | expect(mockIdeMessengerReject.request).toHaveBeenCalledWith( |
| 1203 | "llm/compileChat", |
| 1204 | { |
| 1205 | messages: [ |
| 1206 | { |
| 1207 | role: "system", |
| 1208 | content: "You are a helpful assistant.", |
| 1209 | }, |
| 1210 | { |
| 1211 | role: "user", |
| 1212 | content: [ |
| 1213 | { |
| 1214 | type: "text", |
| 1215 | text: "Please edit this file", |
| 1216 | }, |
| 1217 | ], |
| 1218 | }, |
| 1219 | { |
| 1220 | role: "user", |
| 1221 | content: [ |
| 1222 | { |
| 1223 | type: "text", |
| 1224 | text: "Hello, please help me with this code", |
| 1225 | }, |
| 1226 | ], |
| 1227 | }, |
| 1228 | ], |
| 1229 | options: { |
| 1230 | reasoning: false, |
| 1231 | }, |
| 1232 | }, |
| 1233 | ); |
| 1234 | |
| 1235 | expect(mockIdeMessengerReject.llmStreamChat).toHaveBeenCalledWith( |
| 1236 | { |
| 1237 | completionOptions: { |
| 1238 | reasoning: false, |
| 1239 | }, |
| 1240 | legacySlashCommandData: undefined, |
| 1241 | messageOptions: { precompiled: true }, |
| 1242 | messages: [ |
| 1243 | { |
| 1244 | role: "user", |
| 1245 | content: "Please edit this file", |
| 1246 | }, |
| 1247 | ], |
| 1248 | title: "Claude 3.5 Sonnet", |
| 1249 | }, |
| 1250 | expect.any(AbortSignal), |
| 1251 | ); |
| 1252 | |
| 1253 | // Should NOT call tools/call since tool is disabled/rejected |
| 1254 | expect(mockIdeMessengerReject.request).not.toHaveBeenCalledWith( |
| 1255 | "tools/call", |
| 1256 | expect.anything(), |
| 1257 | ); |
| 1258 | |
| 1259 | // Verify session save was called |
| 1260 | expect(mockIdeMessengerReject.request).toHaveBeenCalledWith( |
| 1261 | "history/save", |
| 1262 | expect.anything(), |
| 1263 | ); |
| 1264 | |
| 1265 | // Verify final state contains the tool call but it's not executed |
| 1266 | const finalState = mockStoreWithToolReject.getState(); |
| 1267 | expect(finalState).toEqual({ |
| 1268 | session: { |
| 1269 | history: [ |
| 1270 | { |
| 1271 | contextItems: [], |
| 1272 | message: { |
| 1273 | id: "1", |
| 1274 | role: "user", |
| 1275 | content: "Please edit this file", |
| 1276 | }, |
| 1277 | }, |
| 1278 | { |
| 1279 | appliedRules: [], |
| 1280 | contextItems: [], |
| 1281 | editorState: mockEditorState, |
| 1282 | message: { |
| 1283 | content: "Hello, please help me with this code", |
| 1284 | id: expect.any(String), |
| 1285 | role: "user", |
| 1286 | }, |
| 1287 | }, |
| 1288 | { |
| 1289 | contextItems: [], |
| 1290 | isGatheringContext: false, |
| 1291 | message: { |
| 1292 | content: "I'll edit the file for you.", |
| 1293 | id: "mock-uuid-123", |
| 1294 | role: "assistant", |
| 1295 | toolCalls: [ |
| 1296 | { |
| 1297 | id: "tool-reject-1", |
| 1298 | type: "function", |
| 1299 | function: { |
| 1300 | name: "edit_existing_file", |
| 1301 | arguments: JSON.stringify({ |
| 1302 | filepath: "test.js", |
| 1303 | changes: "const x = 1;", |
| 1304 | }), |
| 1305 | }, |
| 1306 | }, |
| 1307 | ], |
| 1308 | }, |
| 1309 | promptLogs: [ |
| 1310 | { |
| 1311 | completion: "I'll edit the file for you.", |
| 1312 | modelProvider: "anthropic", |
| 1313 | prompt: "Please edit this file", |
| 1314 | }, |
| 1315 | ], |
| 1316 | toolCallStates: [ |
| 1317 | { |
| 1318 | toolCallId: "tool-reject-1", |
| 1319 | toolCall: { |
| 1320 | id: "tool-reject-1", |
| 1321 | type: "function", |
| 1322 | function: { |
| 1323 | name: "edit_existing_file", |
| 1324 | arguments: JSON.stringify({ |
| 1325 | filepath: "test.js", |
| 1326 | changes: "const x = 1;", |
| 1327 | }), |
| 1328 | }, |
| 1329 | }, |
| 1330 | parsedArgs: { |
| 1331 | filepath: "test.js", |
| 1332 | changes: "const x = 1;", |
| 1333 | }, |
| 1334 | status: "errored", // Tool call is marked as errored due to being disabled |
| 1335 | output: [ |
| 1336 | { |
| 1337 | icon: "problems", |
| 1338 | name: "Security Policy Violation", |
| 1339 | description: "Command Disabled", |
| 1340 | content: `This command has been disabled by security policy:\n\nedit_existing_file\n\nThis command cannot be executed as it may pose a security risk.`, |
| 1341 | hidden: false, |
| 1342 | }, |
| 1343 | ], |
| 1344 | }, |
| 1345 | ], |
| 1346 | }, |
| 1347 | ], |
| 1348 | hasReasoningEnabled: false, |
| 1349 | isStreaming: false, |
| 1350 | id: "session-123", |
| 1351 | mode: "chat", |
| 1352 | streamAborter: expect.any(AbortController), |
| 1353 | contextPercentage: 0.7, |
| 1354 | isPruned: false, |
| 1355 | isInEdit: false, |
| 1356 | title: "New Session", |
| 1357 | lastSessionId: undefined, |
| 1358 | isSessionMetadataLoading: false, |
| 1359 | allSessionMetadata: { |
| 1360 | compiledChatMessages: [ |
| 1361 | { |
| 1362 | content: "Please edit this file", |
| 1363 | role: "user", |
| 1364 | }, |
| 1365 | ], |
| 1366 | contextPercentage: 0.7, |
| 1367 | didPrune: false, |
| 1368 | }, |
| 1369 | symbols: {}, |
| 1370 | codeBlockApplyStates: { |
| 1371 | states: [], |
| 1372 | curIndex: 0, |
| 1373 | }, |
| 1374 | newestToolbarPreviewForInput: {}, |
| 1375 | compactionLoading: {}, |
| 1376 | inlineErrorMessage: undefined, |
| 1377 | }, |
| 1378 | config: { |
| 1379 | config: { |
| 1380 | tools: [], |
| 1381 | rules: [], |
| 1382 | tabAutocompleteModel: undefined, |
| 1383 | selectedModelByRole: { |
| 1384 | chat: mockClaudeModel, |
| 1385 | apply: null, |
| 1386 | edit: null, |
| 1387 | summarize: null, |
| 1388 | autocomplete: null, |
| 1389 | rerank: null, |
| 1390 | embed: null, |
| 1391 | }, |
| 1392 | experimental: { |
| 1393 | onlyUseSystemMessageTools: false, |
| 1394 | }, |
| 1395 | }, |
| 1396 | lastSelectedModelByRole: { |
| 1397 | chat: mockClaudeModel.title, |
| 1398 | }, |
| 1399 | loading: false, |
| 1400 | configError: undefined, |
| 1401 | }, |
| 1402 | ui: { |
| 1403 | toolSettings: { |
| 1404 | edit_existing_file: "disabled", |
| 1405 | }, |
| 1406 | ruleSettings: {}, |
| 1407 | showDialog: false, |
| 1408 | dialogMessage: undefined, |
| 1409 | }, |
| 1410 | editModeState: { |
| 1411 | isInEdit: false, |
| 1412 | returnToMode: "chat", |
| 1413 | }, |
| 1414 | indexing: { |
| 1415 | indexing: { |
| 1416 | statuses: {}, |
| 1417 | hiddenChatPeekTypes: { |
| 1418 | docs: false, |
| 1419 | }, |
| 1420 | }, |
| 1421 | }, |
| 1422 | tabs: { |
| 1423 | tabsItems: [], |
| 1424 | }, |
| 1425 | profiles: { |
| 1426 | organizations: [], |
| 1427 | selectedProfileId: null, |
| 1428 | selectedOrganizationId: null, |
| 1429 | preferencesByProfileId: {}, |
| 1430 | }, |
| 1431 | }); |
| 1432 | }); |
| 1433 | |
| 1434 | it("should handle tool call requiring manual approval", async () => { |
| 1435 | const { mockStore, mockIdeMessenger } = setupTest(); |
| 1436 | |
| 1437 | // Create store with tool settings that require manual approval (ask first) |
| 1438 | const mockStoreWithManualApproval = createMockStore({ |
| 1439 | session: { |
| 1440 | history: [ |
| 1441 | { |
| 1442 | message: { |
| 1443 | id: "1", |
| 1444 | role: "user", |
| 1445 | content: "Please search the codebase", |
| 1446 | }, |
| 1447 | contextItems: [], |
| 1448 | }, |
| 1449 | ], |
| 1450 | hasReasoningEnabled: false, |
| 1451 | isStreaming: true, |
| 1452 | id: "session-123", |
| 1453 | mode: "chat", |
| 1454 | streamAborter: new AbortController(), |
| 1455 | contextPercentage: 0, |
| 1456 | isPruned: false, |
| 1457 | isInEdit: false, |
| 1458 | title: "", |
| 1459 | lastSessionId: undefined, |
| 1460 | isSessionMetadataLoading: false, |
| 1461 | allSessionMetadata: [], |
| 1462 | symbols: {}, |
| 1463 | codeBlockApplyStates: { |
| 1464 | states: [], |
| 1465 | curIndex: 0, |
| 1466 | }, |
| 1467 | newestToolbarPreviewForInput: {}, |
| 1468 | compactionLoading: {}, |
| 1469 | inlineErrorMessage: undefined, |
| 1470 | }, |
| 1471 | config: { |
| 1472 | config: { |
| 1473 | tools: [], |
| 1474 | rules: [], |
| 1475 | tabAutocompleteModel: undefined, |
| 1476 | selectedModelByRole: { |
| 1477 | chat: mockClaudeModel, |
| 1478 | apply: null, |
| 1479 | edit: null, |
| 1480 | summarize: null, |
| 1481 | autocomplete: null, |
| 1482 | rerank: null, |
| 1483 | embed: null, |
| 1484 | }, |
| 1485 | experimental: { |
| 1486 | onlyUseSystemMessageTools: false, |
| 1487 | }, |
| 1488 | } as any, |
| 1489 | lastSelectedModelByRole: { |
| 1490 | chat: mockClaudeModel.title, |
| 1491 | }, |
| 1492 | } as any, |
| 1493 | ui: { |
| 1494 | toolSettings: { |
| 1495 | search_codebase: "askFirst", // Requires manual approval |
| 1496 | }, |
| 1497 | ruleSettings: {}, |
| 1498 | showDialog: false, |
| 1499 | dialogMessage: undefined, |
| 1500 | } as any, |
| 1501 | }); |
| 1502 | |
| 1503 | const mockIdeMessengerManual = mockStoreWithManualApproval.mockIdeMessenger; |
| 1504 | |
| 1505 | // Setup successful compilation |
| 1506 | mockIdeMessengerManual.request.mockResolvedValue({ |
| 1507 | status: "success", |
| 1508 | content: { |
| 1509 | compiledChatMessages: [ |
| 1510 | { role: "user", content: "Please search the codebase" }, |
| 1511 | ], |
| 1512 | didPrune: false, |
| 1513 | contextPercentage: 0.9, |
| 1514 | }, |
| 1515 | }); |
| 1516 | |
| 1517 | // Setup streaming generator with tool call requiring approval |
| 1518 | async function* mockStreamGeneratorWithApprovalTool() { |
| 1519 | yield [ |
| 1520 | { role: "assistant", content: "I'll search the codebase for you." }, |
| 1521 | ]; |
| 1522 | yield [ |
| 1523 | { |
| 1524 | role: "assistant", |
| 1525 | content: "", |
| 1526 | toolCalls: [ |
| 1527 | { |
| 1528 | id: "tool-approval-1", |
| 1529 | type: "function", |
| 1530 | function: { |
| 1531 | name: "search_codebase", |
| 1532 | arguments: JSON.stringify({ query: "test function" }), |
| 1533 | }, |
| 1534 | }, |
| 1535 | ], |
| 1536 | }, |
| 1537 | ]; |
| 1538 | return { |
| 1539 | prompt: "Please search the codebase", |
| 1540 | completion: "I'll search the codebase for you.", |
| 1541 | modelProvider: "anthropic", |
| 1542 | }; |
| 1543 | } |
| 1544 | |
| 1545 | mockIdeMessengerManual.llmStreamChat.mockReturnValue( |
| 1546 | mockStreamGeneratorWithApprovalTool(), |
| 1547 | ); |
| 1548 | |
| 1549 | // Track isStreaming state changes to ensure it doesn't become false after tool generation |
| 1550 | const streamingStates: boolean[] = []; |
| 1551 | const originalDispatch = mockStoreWithManualApproval.dispatch; |
| 1552 | mockStoreWithManualApproval.dispatch = ((action: any) => { |
| 1553 | const result = originalDispatch(action); |
| 1554 | // Capture isStreaming state after each action |
| 1555 | const currentState = |
| 1556 | mockStoreWithManualApproval.getState().session.isStreaming; |
| 1557 | streamingStates.push(currentState); |
| 1558 | return result; |
| 1559 | }) as any; |
| 1560 | |
| 1561 | // Execute thunk |
| 1562 | const result = await mockStoreWithManualApproval.dispatch( |
| 1563 | streamResponseThunk({ |
| 1564 | editorState: mockEditorState, |
| 1565 | modifiers: mockModifiers, |
| 1566 | }) as any, |
| 1567 | ); |
| 1568 | |
| 1569 | // Verify thunk completed successfully (tool waits for approval) |
| 1570 | expect(result.type).toBe("chat/streamResponse/fulfilled"); |
| 1571 | |
| 1572 | // Since tool requires approval, isStreaming should become false after completion |
| 1573 | // but should stay true throughout the initial streaming phase |
| 1574 | const finalStreamingState = |
| 1575 | mockStoreWithManualApproval.getState().session.isStreaming; |
| 1576 | expect(finalStreamingState).toBe(false); // Final state should be false since we're waiting for approval |
| 1577 | |
| 1578 | // Verify exact action sequence includes tool generation but NO execution |
| 1579 | const dispatchedActions = (mockStoreWithManualApproval as any).getActions(); |
| 1580 | expect(dispatchedActions).toEqual([ |
| 1581 | { |
| 1582 | type: "chat/streamResponse/pending", |
| 1583 | meta: { |
| 1584 | arg: { |
| 1585 | editorState: mockEditorState, |
| 1586 | modifiers: mockModifiers, |
| 1587 | }, |
| 1588 | requestId: expect.any(String), |
| 1589 | requestStatus: "pending", |
| 1590 | }, |
| 1591 | payload: undefined, |
| 1592 | }, |
| 1593 | { |
| 1594 | type: "chat/streamWrapper/pending", |
| 1595 | meta: { |
| 1596 | arg: expect.any(Function), |
| 1597 | requestId: expect.any(String), |
| 1598 | requestStatus: "pending", |
| 1599 | }, |
| 1600 | payload: undefined, |
| 1601 | }, |
| 1602 | { |
| 1603 | type: "session/submitEditorAndInitAtIndex", |
| 1604 | payload: { |
| 1605 | editorState: mockEditorState, |
| 1606 | index: 1, |
| 1607 | }, |
| 1608 | }, |
| 1609 | { |
| 1610 | type: "session/resetNextCodeBlockToApplyIndex", |
| 1611 | payload: undefined, |
| 1612 | }, |
| 1613 | { |
| 1614 | type: "symbols/updateFromContextItems/pending", |
| 1615 | meta: { |
| 1616 | arg: [], |
| 1617 | requestId: expect.any(String), |
| 1618 | requestStatus: "pending", |
| 1619 | }, |
| 1620 | payload: undefined, |
| 1621 | }, |
| 1622 | { |
| 1623 | type: "session/updateHistoryItemAtIndex", |
| 1624 | payload: { |
| 1625 | index: 1, |
| 1626 | updates: { |
| 1627 | contextItems: [], |
| 1628 | message: { |
| 1629 | content: "Hello, please help me with this code", |
| 1630 | id: "mock-uuid-123", |
| 1631 | role: "user", |
| 1632 | }, |
| 1633 | }, |
| 1634 | }, |
| 1635 | }, |
| 1636 | { |
| 1637 | type: "chat/streamNormalInput/pending", |
| 1638 | meta: { |
| 1639 | arg: { |
| 1640 | legacySlashCommandData: undefined, |
| 1641 | }, |
| 1642 | requestId: expect.any(String), |
| 1643 | requestStatus: "pending", |
| 1644 | }, |
| 1645 | payload: undefined, |
| 1646 | }, |
| 1647 | { |
| 1648 | type: "session/setAppliedRulesAtIndex", |
| 1649 | payload: { |
| 1650 | appliedRules: [], |
| 1651 | index: 1, |
| 1652 | }, |
| 1653 | }, |
| 1654 | { |
| 1655 | type: "session/setActive", |
| 1656 | payload: undefined, |
| 1657 | }, |
| 1658 | { |
| 1659 | type: "session/setInlineErrorMessage", |
| 1660 | payload: undefined, |
| 1661 | }, |
| 1662 | { |
| 1663 | type: "session/setIsPruned", |
| 1664 | payload: false, |
| 1665 | }, |
| 1666 | { |
| 1667 | type: "session/setContextPercentage", |
| 1668 | payload: 0.9, |
| 1669 | }, |
| 1670 | { |
| 1671 | type: "symbols/updateFromContextItems/fulfilled", |
| 1672 | meta: { |
| 1673 | arg: [], |
| 1674 | requestId: expect.any(String), |
| 1675 | requestStatus: "fulfilled", |
| 1676 | }, |
| 1677 | payload: undefined, |
| 1678 | }, |
| 1679 | { |
| 1680 | type: "session/streamUpdate", |
| 1681 | payload: [ |
| 1682 | { |
| 1683 | role: "assistant", |
| 1684 | content: "I'll search the codebase for you.", |
| 1685 | }, |
| 1686 | ], |
| 1687 | }, |
| 1688 | { |
| 1689 | type: "session/streamUpdate", |
| 1690 | payload: [ |
| 1691 | { |
| 1692 | role: "assistant", |
| 1693 | content: "", |
| 1694 | toolCalls: [ |
| 1695 | { |
| 1696 | id: "tool-approval-1", |
| 1697 | type: "function", |
| 1698 | function: { |
| 1699 | name: "search_codebase", |
| 1700 | arguments: JSON.stringify({ query: "test function" }), |
| 1701 | }, |
| 1702 | }, |
| 1703 | ], |
| 1704 | }, |
| 1705 | ], |
| 1706 | }, |
| 1707 | { |
| 1708 | type: "session/addPromptCompletionPair", |
| 1709 | payload: [ |
| 1710 | { |
| 1711 | completion: "I'll search the codebase for you.", |
| 1712 | modelProvider: "anthropic", |
| 1713 | prompt: "Please search the codebase", |
| 1714 | }, |
| 1715 | ], |
| 1716 | }, |
| 1717 | { |
| 1718 | type: "session/setToolGenerated", |
| 1719 | payload: { |
| 1720 | toolCallId: "tool-approval-1", |
| 1721 | tools: [], |
| 1722 | }, |
| 1723 | }, |
| 1724 | { |
| 1725 | type: "session/setInactive", |
| 1726 | payload: undefined, |
| 1727 | }, |
| 1728 | { |
| 1729 | type: "chat/streamNormalInput/fulfilled", |
| 1730 | meta: { |
| 1731 | arg: { |
| 1732 | legacySlashCommandData: undefined, |
| 1733 | }, |
| 1734 | requestId: expect.any(String), |
| 1735 | requestStatus: "fulfilled", |
| 1736 | }, |
| 1737 | payload: undefined, |
| 1738 | }, |
| 1739 | { |
| 1740 | type: "session/saveCurrent/pending", |
| 1741 | meta: { |
| 1742 | arg: { |
| 1743 | generateTitle: true, |
| 1744 | openNewSession: false, |
| 1745 | }, |
| 1746 | requestId: expect.any(String), |
| 1747 | requestStatus: "pending", |
| 1748 | }, |
| 1749 | payload: undefined, |
| 1750 | }, |
| 1751 | { |
| 1752 | type: "session/update/pending", |
| 1753 | meta: { |
| 1754 | arg: expect.objectContaining({ |
| 1755 | history: expect.any(Array), |
| 1756 | sessionId: "session-123", |
| 1757 | title: "New Session", |
| 1758 | workspaceDirectory: "", |
| 1759 | }), |
| 1760 | requestId: expect.any(String), |
| 1761 | requestStatus: "pending", |
| 1762 | }, |
| 1763 | payload: undefined, |
| 1764 | }, |
| 1765 | { |
| 1766 | type: "session/updateSessionMetadata", |
| 1767 | payload: { |
| 1768 | sessionId: "session-123", |
| 1769 | title: "New Session", |
| 1770 | }, |
| 1771 | }, |
| 1772 | { |
| 1773 | type: "session/refreshMetadata/pending", |
| 1774 | meta: { |
| 1775 | arg: {}, |
| 1776 | requestId: expect.any(String), |
| 1777 | requestStatus: "pending", |
| 1778 | }, |
| 1779 | payload: undefined, |
| 1780 | }, |
| 1781 | { |
| 1782 | type: "session/setIsSessionMetadataLoading", |
| 1783 | payload: false, |
| 1784 | }, |
| 1785 | { |
| 1786 | type: "session/setAllSessionMetadata", |
| 1787 | payload: { |
| 1788 | compiledChatMessages: [ |
| 1789 | { |
| 1790 | content: "Please search the codebase", |
| 1791 | role: "user", |
| 1792 | }, |
| 1793 | ], |
| 1794 | contextPercentage: 0.9, |
| 1795 | didPrune: false, |
| 1796 | }, |
| 1797 | }, |
| 1798 | { |
| 1799 | type: "session/refreshMetadata/fulfilled", |
| 1800 | meta: { |
| 1801 | arg: {}, |
| 1802 | requestId: expect.any(String), |
| 1803 | requestStatus: "fulfilled", |
| 1804 | }, |
| 1805 | payload: { |
| 1806 | compiledChatMessages: [ |
| 1807 | { |
| 1808 | content: "Please search the codebase", |
| 1809 | role: "user", |
| 1810 | }, |
| 1811 | ], |
| 1812 | contextPercentage: 0.9, |
| 1813 | didPrune: false, |
| 1814 | }, |
| 1815 | }, |
| 1816 | { |
| 1817 | type: "session/update/fulfilled", |
| 1818 | meta: { |
| 1819 | arg: expect.objectContaining({ |
| 1820 | history: expect.any(Array), |
| 1821 | sessionId: "session-123", |
| 1822 | title: "New Session", |
| 1823 | workspaceDirectory: "", |
| 1824 | }), |
| 1825 | requestId: expect.any(String), |
| 1826 | requestStatus: "fulfilled", |
| 1827 | }, |
| 1828 | payload: undefined, |
| 1829 | }, |
| 1830 | { |
| 1831 | type: "session/saveCurrent/fulfilled", |
| 1832 | meta: { |
| 1833 | arg: { |
| 1834 | generateTitle: true, |
| 1835 | openNewSession: false, |
| 1836 | }, |
| 1837 | requestId: expect.any(String), |
| 1838 | requestStatus: "fulfilled", |
| 1839 | }, |
| 1840 | payload: undefined, |
| 1841 | }, |
| 1842 | { |
| 1843 | type: "chat/streamWrapper/fulfilled", |
| 1844 | meta: { |
| 1845 | arg: expect.any(Function), |
| 1846 | requestId: expect.any(String), |
| 1847 | requestStatus: "fulfilled", |
| 1848 | }, |
| 1849 | payload: undefined, |
| 1850 | }, |
| 1851 | { |
| 1852 | type: "chat/streamResponse/fulfilled", |
| 1853 | meta: { |
| 1854 | arg: { |
| 1855 | editorState: mockEditorState, |
| 1856 | modifiers: mockModifiers, |
| 1857 | }, |
| 1858 | requestId: expect.any(String), |
| 1859 | requestStatus: "fulfilled", |
| 1860 | }, |
| 1861 | payload: undefined, |
| 1862 | }, |
| 1863 | ]); |
| 1864 | |
| 1865 | // Verify IDE messenger calls - compilation should happen, streaming should happen |
| 1866 | expect(mockIdeMessengerManual.request).toHaveBeenCalledWith( |
| 1867 | "llm/compileChat", |
| 1868 | { |
| 1869 | messages: [ |
| 1870 | { |
| 1871 | role: "system", |
| 1872 | content: "You are a helpful assistant.", |
| 1873 | }, |
| 1874 | { |
| 1875 | role: "user", |
| 1876 | content: [ |
| 1877 | { |
| 1878 | type: "text", |
| 1879 | text: "Please search the codebase", |
| 1880 | }, |
| 1881 | ], |
| 1882 | }, |
| 1883 | { |
| 1884 | role: "user", |
| 1885 | content: [ |
| 1886 | { |
| 1887 | type: "text", |
| 1888 | text: "Hello, please help me with this code", |
| 1889 | }, |
| 1890 | ], |
| 1891 | }, |
| 1892 | ], |
| 1893 | options: { |
| 1894 | reasoning: false, |
| 1895 | }, |
| 1896 | }, |
| 1897 | ); |
| 1898 | |
| 1899 | expect(mockIdeMessengerManual.llmStreamChat).toHaveBeenCalledWith( |
| 1900 | { |
| 1901 | completionOptions: { |
| 1902 | reasoning: false, |
| 1903 | }, |
| 1904 | legacySlashCommandData: undefined, |
| 1905 | messageOptions: { precompiled: true }, |
| 1906 | messages: [ |
| 1907 | { |
| 1908 | role: "user", |
| 1909 | content: "Please search the codebase", |
| 1910 | }, |
| 1911 | ], |
| 1912 | title: "Claude 3.5 Sonnet", |
| 1913 | }, |
| 1914 | expect.any(AbortSignal), |
| 1915 | ); |
| 1916 | |
| 1917 | // Should NOT call tools/call since tool requires approval |
| 1918 | expect(mockIdeMessengerManual.request).not.toHaveBeenCalledWith( |
| 1919 | "tools/call", |
| 1920 | expect.anything(), |
| 1921 | ); |
| 1922 | |
| 1923 | // Verify session save was called |
| 1924 | expect(mockIdeMessengerManual.request).toHaveBeenCalledWith( |
| 1925 | "history/save", |
| 1926 | expect.anything(), |
| 1927 | ); |
| 1928 | |
| 1929 | // Verify final state contains the tool call in "generated" state (waiting for approval) |
| 1930 | const finalState = mockStoreWithManualApproval.getState(); |
| 1931 | expect(finalState).toEqual({ |
| 1932 | session: { |
| 1933 | history: [ |
| 1934 | { |
| 1935 | contextItems: [], |
| 1936 | message: { |
| 1937 | id: "1", |
| 1938 | role: "user", |
| 1939 | content: "Please search the codebase", |
| 1940 | }, |
| 1941 | }, |
| 1942 | { |
| 1943 | appliedRules: [], |
| 1944 | contextItems: [], |
| 1945 | editorState: mockEditorState, |
| 1946 | message: { |
| 1947 | content: "Hello, please help me with this code", |
| 1948 | id: expect.any(String), |
| 1949 | role: "user", |
| 1950 | }, |
| 1951 | }, |
| 1952 | { |
| 1953 | contextItems: [], |
| 1954 | isGatheringContext: false, |
| 1955 | message: { |
| 1956 | content: "I'll search the codebase for you.", |
| 1957 | id: "mock-uuid-123", |
| 1958 | role: "assistant", |
| 1959 | toolCalls: [ |
| 1960 | { |
| 1961 | id: "tool-approval-1", |
| 1962 | type: "function", |
| 1963 | function: { |
| 1964 | name: "search_codebase", |
| 1965 | arguments: JSON.stringify({ query: "test function" }), |
| 1966 | }, |
| 1967 | }, |
| 1968 | ], |
| 1969 | }, |
| 1970 | promptLogs: [ |
| 1971 | { |
| 1972 | completion: "I'll search the codebase for you.", |
| 1973 | modelProvider: "anthropic", |
| 1974 | prompt: "Please search the codebase", |
| 1975 | }, |
| 1976 | ], |
| 1977 | toolCallStates: [ |
| 1978 | { |
| 1979 | toolCallId: "tool-approval-1", |
| 1980 | toolCall: { |
| 1981 | id: "tool-approval-1", |
| 1982 | type: "function", |
| 1983 | function: { |
| 1984 | name: "search_codebase", |
| 1985 | arguments: JSON.stringify({ query: "test function" }), |
| 1986 | }, |
| 1987 | }, |
| 1988 | parsedArgs: { query: "test function" }, |
| 1989 | status: "generated", // Waiting for user approval |
| 1990 | }, |
| 1991 | ], |
| 1992 | }, |
| 1993 | ], |
| 1994 | hasReasoningEnabled: false, |
| 1995 | isStreaming: false, |
| 1996 | id: "session-123", |
| 1997 | mode: "chat", |
| 1998 | streamAborter: expect.any(AbortController), |
| 1999 | contextPercentage: 0.9, |
| 2000 | isPruned: false, |
| 2001 | isInEdit: false, |
| 2002 | title: "New Session", |
| 2003 | lastSessionId: undefined, |
| 2004 | isSessionMetadataLoading: false, |
| 2005 | allSessionMetadata: { |
| 2006 | compiledChatMessages: [ |
| 2007 | { |
| 2008 | content: "Please search the codebase", |
| 2009 | role: "user", |
| 2010 | }, |
| 2011 | ], |
| 2012 | contextPercentage: 0.9, |
| 2013 | didPrune: false, |
| 2014 | }, |
| 2015 | symbols: {}, |
| 2016 | codeBlockApplyStates: { |
| 2017 | states: [], |
| 2018 | curIndex: 0, |
| 2019 | }, |
| 2020 | newestToolbarPreviewForInput: {}, |
| 2021 | compactionLoading: {}, |
| 2022 | inlineErrorMessage: undefined, |
| 2023 | }, |
| 2024 | config: { |
| 2025 | config: { |
| 2026 | tools: [], |
| 2027 | rules: [], |
| 2028 | tabAutocompleteModel: undefined, |
| 2029 | selectedModelByRole: { |
| 2030 | chat: mockClaudeModel, |
| 2031 | apply: null, |
| 2032 | edit: null, |
| 2033 | summarize: null, |
| 2034 | autocomplete: null, |
| 2035 | rerank: null, |
| 2036 | embed: null, |
| 2037 | }, |
| 2038 | experimental: { |
| 2039 | onlyUseSystemMessageTools: false, |
| 2040 | }, |
| 2041 | }, |
| 2042 | lastSelectedModelByRole: { |
| 2043 | chat: mockClaudeModel.title, |
| 2044 | }, |
| 2045 | loading: false, |
| 2046 | configError: undefined, |
| 2047 | }, |
| 2048 | ui: { |
| 2049 | toolSettings: { |
| 2050 | search_codebase: "askFirst", |
| 2051 | }, |
| 2052 | ruleSettings: {}, |
| 2053 | showDialog: false, |
| 2054 | dialogMessage: undefined, |
| 2055 | }, |
| 2056 | editModeState: { |
| 2057 | isInEdit: false, |
| 2058 | returnToMode: "chat", |
| 2059 | }, |
| 2060 | indexing: { |
| 2061 | indexing: { |
| 2062 | statuses: {}, |
| 2063 | hiddenChatPeekTypes: { |
| 2064 | docs: false, |
| 2065 | }, |
| 2066 | }, |
| 2067 | }, |
| 2068 | tabs: { |
| 2069 | tabsItems: [], |
| 2070 | }, |
| 2071 | profiles: { |
| 2072 | organizations: [], |
| 2073 | selectedProfileId: null, |
| 2074 | selectedOrganizationId: null, |
| 2075 | preferencesByProfileId: {}, |
| 2076 | }, |
| 2077 | }); |
| 2078 | }); |
| 2079 | |
| 2080 | it("should handle complete user approval and tool execution flow", async () => { |
| 2081 | const { mockStore, mockIdeMessenger } = setupTest(); |
| 2082 | |
| 2083 | // Create store with tool settings that require manual approval |
| 2084 | const mockStoreWithApproval = createMockStore({ |
| 2085 | session: { |
| 2086 | history: [ |
| 2087 | { |
| 2088 | message: { |
| 2089 | id: "1", |
| 2090 | role: "user", |
| 2091 | content: "Please search the codebase for test functions", |
| 2092 | }, |
| 2093 | contextItems: [], |
| 2094 | }, |
| 2095 | ], |
| 2096 | hasReasoningEnabled: false, |
| 2097 | isStreaming: true, |
| 2098 | id: "session-123", |
| 2099 | mode: "chat", |
| 2100 | streamAborter: new AbortController(), |
| 2101 | contextPercentage: 0, |
| 2102 | isPruned: false, |
| 2103 | isInEdit: false, |
| 2104 | title: "", |
| 2105 | lastSessionId: undefined, |
| 2106 | isSessionMetadataLoading: false, |
| 2107 | allSessionMetadata: [], |
| 2108 | symbols: {}, |
| 2109 | codeBlockApplyStates: { |
| 2110 | states: [], |
| 2111 | curIndex: 0, |
| 2112 | }, |
| 2113 | newestToolbarPreviewForInput: {}, |
| 2114 | compactionLoading: {}, |
| 2115 | inlineErrorMessage: undefined, |
| 2116 | }, |
| 2117 | config: { |
| 2118 | config: { |
| 2119 | tools: [], |
| 2120 | rules: [], |
| 2121 | tabAutocompleteModel: undefined, |
| 2122 | selectedModelByRole: { |
| 2123 | chat: mockClaudeModel, |
| 2124 | apply: null, |
| 2125 | edit: null, |
| 2126 | summarize: null, |
| 2127 | autocomplete: null, |
| 2128 | rerank: null, |
| 2129 | embed: null, |
| 2130 | }, |
| 2131 | experimental: { |
| 2132 | onlyUseSystemMessageTools: false, |
| 2133 | }, |
| 2134 | } as any, |
| 2135 | lastSelectedModelByRole: { |
| 2136 | chat: mockClaudeModel.title, |
| 2137 | }, |
| 2138 | } as any, |
| 2139 | ui: { |
| 2140 | toolSettings: { |
| 2141 | search_codebase: "askFirst", // Requires manual approval |
| 2142 | }, |
| 2143 | ruleSettings: {}, |
| 2144 | showDialog: false, |
| 2145 | dialogMessage: undefined, |
| 2146 | } as any, |
| 2147 | }); |
| 2148 | |
| 2149 | const mockIdeMessengerApproval = mockStoreWithApproval.mockIdeMessenger; |
| 2150 | |
| 2151 | // Setup successful compilation |
| 2152 | mockIdeMessengerApproval.request.mockImplementation( |
| 2153 | (endpoint: string, data: any) => { |
| 2154 | if (endpoint === "llm/compileChat") { |
| 2155 | return Promise.resolve({ |
| 2156 | status: "success", |
| 2157 | content: { |
| 2158 | compiledChatMessages: [ |
| 2159 | { |
| 2160 | role: "user", |
| 2161 | content: "Please search the codebase for test functions", |
| 2162 | }, |
| 2163 | ], |
| 2164 | didPrune: false, |
| 2165 | contextPercentage: 0.85, |
| 2166 | }, |
| 2167 | }); |
| 2168 | } else if (endpoint === "tools/call") { |
| 2169 | // Mock server-side tool call response for search_codebase |
| 2170 | return Promise.resolve({ |
| 2171 | status: "success", |
| 2172 | content: { |
| 2173 | contextItems: [ |
| 2174 | { |
| 2175 | name: "Search Results", |
| 2176 | description: "Found test functions", |
| 2177 | content: |
| 2178 | "function testUserLogin() {...}\\nfunction testDataValidation() {...}", |
| 2179 | icon: "search", |
| 2180 | hidden: false, |
| 2181 | }, |
| 2182 | ], |
| 2183 | errorMessage: undefined, |
| 2184 | }, |
| 2185 | }); |
| 2186 | } else if (endpoint === "history/save") { |
| 2187 | return Promise.resolve({ status: "success" }); |
| 2188 | } else if (endpoint === "history/list") { |
| 2189 | return Promise.resolve({ status: "success", content: [] }); |
| 2190 | } |
| 2191 | return Promise.resolve({ status: "success", content: {} }); |
| 2192 | }, |
| 2193 | ); |
| 2194 | |
| 2195 | // Setup streaming generator with tool call |
| 2196 | async function* mockStreamGeneratorWithApprovalFlow() { |
| 2197 | yield [ |
| 2198 | { |
| 2199 | role: "assistant", |
| 2200 | content: "I'll search for test functions in the codebase.", |
| 2201 | }, |
| 2202 | ]; |
| 2203 | yield [ |
| 2204 | { |
| 2205 | role: "assistant", |
| 2206 | content: "", |
| 2207 | toolCalls: [ |
| 2208 | { |
| 2209 | id: "tool-approval-flow-1", |
| 2210 | type: "function", |
| 2211 | function: { |
| 2212 | name: "search_codebase", |
| 2213 | arguments: JSON.stringify({ query: "test function" }), |
| 2214 | }, |
| 2215 | }, |
| 2216 | ], |
| 2217 | }, |
| 2218 | ]; |
| 2219 | return { |
| 2220 | prompt: "Please search the codebase for test functions", |
| 2221 | completion: "I'll search for test functions in the codebase.", |
| 2222 | modelProvider: "anthropic", |
| 2223 | }; |
| 2224 | } |
| 2225 | |
| 2226 | // Mock subsequent streaming calls (after tool execution) |
| 2227 | let streamCallCount = 0; |
| 2228 | mockIdeMessengerApproval.llmStreamChat.mockImplementation(() => { |
| 2229 | streamCallCount++; |
| 2230 | if (streamCallCount === 1) { |
| 2231 | // First call - initial streaming with tool call |
| 2232 | return mockStreamGeneratorWithApprovalFlow(); |
| 2233 | } else { |
| 2234 | // Subsequent calls from streamResponseAfterToolCall |
| 2235 | async function* followupGenerator() { |
| 2236 | yield [ |
| 2237 | { |
| 2238 | role: "assistant", |
| 2239 | content: |
| 2240 | "I found several test functions in your codebase. Here are the main ones I discovered...", |
| 2241 | }, |
| 2242 | ]; |
| 2243 | return { |
| 2244 | prompt: "continuing after tool execution", |
| 2245 | completion: |
| 2246 | "I found several test functions in your codebase. Here are the main ones I discovered...", |
| 2247 | modelProvider: "anthropic", |
| 2248 | }; |
| 2249 | } |
| 2250 | return followupGenerator(); |
| 2251 | } |
| 2252 | }); |
| 2253 | |
| 2254 | // Track isStreaming state changes throughout the entire test |
| 2255 | const streamingStateChanges: boolean[] = []; |
| 2256 | let lastStreamingState = |
| 2257 | mockStoreWithApproval.getState().session.isStreaming; |
| 2258 | const originalDispatch = mockStoreWithApproval.dispatch; |
| 2259 | mockStoreWithApproval.dispatch = ((action: any) => { |
| 2260 | const result = originalDispatch(action); |
| 2261 | const currentStreamingState = |
| 2262 | mockStoreWithApproval.getState().session.isStreaming; |
| 2263 | // Only record when the state actually changes |
| 2264 | if (currentStreamingState !== lastStreamingState) { |
| 2265 | streamingStateChanges.push(currentStreamingState); |
| 2266 | lastStreamingState = currentStreamingState; |
| 2267 | } |
| 2268 | return result; |
| 2269 | }) as any; |
| 2270 | |
| 2271 | // Execute initial thunk - this should generate the tool call but not execute it |
| 2272 | const initialResult = await mockStoreWithApproval.dispatch( |
| 2273 | streamResponseThunk({ |
| 2274 | editorState: mockEditorState, |
| 2275 | modifiers: mockModifiers, |
| 2276 | }) as any, |
| 2277 | ); |
| 2278 | |
| 2279 | // Verify initial streaming completed successfully |
| 2280 | expect(initialResult.type).toBe("chat/streamResponse/fulfilled"); |
| 2281 | |
| 2282 | // Verify exact initial action sequence by comparing action types |
| 2283 | const initialActions = (mockStoreWithApproval as any).getActions(); |
| 2284 | |
| 2285 | expect(initialActions).toEqual([ |
| 2286 | { |
| 2287 | type: "chat/streamResponse/pending", |
| 2288 | meta: { |
| 2289 | arg: { |
| 2290 | editorState: mockEditorState, |
| 2291 | modifiers: mockModifiers, |
| 2292 | }, |
| 2293 | requestId: expect.any(String), |
| 2294 | requestStatus: "pending", |
| 2295 | }, |
| 2296 | payload: undefined, |
| 2297 | }, |
| 2298 | { |
| 2299 | type: "chat/streamWrapper/pending", |
| 2300 | meta: { |
| 2301 | arg: expect.any(Function), |
| 2302 | requestId: expect.any(String), |
| 2303 | requestStatus: "pending", |
| 2304 | }, |
| 2305 | payload: undefined, |
| 2306 | }, |
| 2307 | { |
| 2308 | type: "session/submitEditorAndInitAtIndex", |
| 2309 | payload: { |
| 2310 | editorState: mockEditorState, |
| 2311 | index: 1, |
| 2312 | }, |
| 2313 | }, |
| 2314 | { |
| 2315 | type: "session/resetNextCodeBlockToApplyIndex", |
| 2316 | payload: undefined, |
| 2317 | }, |
| 2318 | { |
| 2319 | type: "symbols/updateFromContextItems/pending", |
| 2320 | meta: { |
| 2321 | arg: [], |
| 2322 | requestId: expect.any(String), |
| 2323 | requestStatus: "pending", |
| 2324 | }, |
| 2325 | payload: undefined, |
| 2326 | }, |
| 2327 | { |
| 2328 | type: "session/updateHistoryItemAtIndex", |
| 2329 | payload: { |
| 2330 | index: 1, |
| 2331 | updates: { |
| 2332 | contextItems: [], |
| 2333 | message: { |
| 2334 | content: "Hello, please help me with this code", |
| 2335 | id: "mock-uuid-123", |
| 2336 | role: "user", |
| 2337 | }, |
| 2338 | }, |
| 2339 | }, |
| 2340 | }, |
| 2341 | { |
| 2342 | type: "chat/streamNormalInput/pending", |
| 2343 | meta: { |
| 2344 | arg: { |
| 2345 | legacySlashCommandData: undefined, |
| 2346 | }, |
| 2347 | requestId: expect.any(String), |
| 2348 | requestStatus: "pending", |
| 2349 | }, |
| 2350 | payload: undefined, |
| 2351 | }, |
| 2352 | { |
| 2353 | type: "session/setAppliedRulesAtIndex", |
| 2354 | payload: { |
| 2355 | appliedRules: [], |
| 2356 | index: 1, |
| 2357 | }, |
| 2358 | }, |
| 2359 | { |
| 2360 | type: "session/setActive", |
| 2361 | payload: undefined, |
| 2362 | }, |
| 2363 | { |
| 2364 | type: "session/setInlineErrorMessage", |
| 2365 | payload: undefined, |
| 2366 | }, |
| 2367 | { |
| 2368 | type: "session/setIsPruned", |
| 2369 | payload: false, |
| 2370 | }, |
| 2371 | { |
| 2372 | type: "session/setContextPercentage", |
| 2373 | payload: 0.85, |
| 2374 | }, |
| 2375 | { |
| 2376 | type: "symbols/updateFromContextItems/fulfilled", |
| 2377 | meta: { |
| 2378 | arg: [], |
| 2379 | requestId: expect.any(String), |
| 2380 | requestStatus: "fulfilled", |
| 2381 | }, |
| 2382 | payload: undefined, |
| 2383 | }, |
| 2384 | { |
| 2385 | type: "session/streamUpdate", |
| 2386 | payload: [ |
| 2387 | { |
| 2388 | role: "assistant", |
| 2389 | content: "I'll search for test functions in the codebase.", |
| 2390 | }, |
| 2391 | ], |
| 2392 | }, |
| 2393 | { |
| 2394 | type: "session/streamUpdate", |
| 2395 | payload: [ |
| 2396 | { |
| 2397 | role: "assistant", |
| 2398 | content: "", |
| 2399 | toolCalls: [ |
| 2400 | { |
| 2401 | id: "tool-approval-flow-1", |
| 2402 | type: "function", |
| 2403 | function: { |
| 2404 | name: "search_codebase", |
| 2405 | arguments: JSON.stringify({ query: "test function" }), |
| 2406 | }, |
| 2407 | }, |
| 2408 | ], |
| 2409 | }, |
| 2410 | ], |
| 2411 | }, |
| 2412 | { |
| 2413 | type: "session/addPromptCompletionPair", |
| 2414 | payload: [ |
| 2415 | { |
| 2416 | completion: "I'll search for test functions in the codebase.", |
| 2417 | modelProvider: "anthropic", |
| 2418 | prompt: "Please search the codebase for test functions", |
| 2419 | }, |
| 2420 | ], |
| 2421 | }, |
| 2422 | { |
| 2423 | type: "session/setToolGenerated", |
| 2424 | payload: { |
| 2425 | toolCallId: "tool-approval-flow-1", |
| 2426 | tools: [], |
| 2427 | }, |
| 2428 | }, |
| 2429 | { |
| 2430 | type: "session/setInactive", |
| 2431 | payload: undefined, |
| 2432 | }, |
| 2433 | { |
| 2434 | type: "chat/streamNormalInput/fulfilled", |
| 2435 | meta: { |
| 2436 | arg: { |
| 2437 | legacySlashCommandData: undefined, |
| 2438 | }, |
| 2439 | requestId: expect.any(String), |
| 2440 | requestStatus: "fulfilled", |
| 2441 | }, |
| 2442 | payload: undefined, |
| 2443 | }, |
| 2444 | { |
| 2445 | type: "session/saveCurrent/pending", |
| 2446 | meta: { |
| 2447 | arg: { |
| 2448 | generateTitle: true, |
| 2449 | openNewSession: false, |
| 2450 | }, |
| 2451 | requestId: expect.any(String), |
| 2452 | requestStatus: "pending", |
| 2453 | }, |
| 2454 | payload: undefined, |
| 2455 | }, |
| 2456 | { |
| 2457 | type: "session/update/pending", |
| 2458 | meta: { |
| 2459 | arg: expect.objectContaining({ |
| 2460 | history: expect.any(Array), |
| 2461 | sessionId: "session-123", |
| 2462 | title: "New Session", |
| 2463 | workspaceDirectory: "", |
| 2464 | }), |
| 2465 | requestId: expect.any(String), |
| 2466 | requestStatus: "pending", |
| 2467 | }, |
| 2468 | payload: undefined, |
| 2469 | }, |
| 2470 | { |
| 2471 | type: "session/updateSessionMetadata", |
| 2472 | payload: { |
| 2473 | sessionId: "session-123", |
| 2474 | title: "New Session", |
| 2475 | }, |
| 2476 | }, |
| 2477 | { |
| 2478 | type: "session/refreshMetadata/pending", |
| 2479 | meta: { |
| 2480 | arg: {}, |
| 2481 | requestId: expect.any(String), |
| 2482 | requestStatus: "pending", |
| 2483 | }, |
| 2484 | payload: undefined, |
| 2485 | }, |
| 2486 | { |
| 2487 | type: "session/setIsSessionMetadataLoading", |
| 2488 | payload: false, |
| 2489 | }, |
| 2490 | { |
| 2491 | type: "session/setAllSessionMetadata", |
| 2492 | payload: [], |
| 2493 | }, |
| 2494 | { |
| 2495 | type: "session/refreshMetadata/fulfilled", |
| 2496 | meta: { |
| 2497 | arg: {}, |
| 2498 | requestId: expect.any(String), |
| 2499 | requestStatus: "fulfilled", |
| 2500 | }, |
| 2501 | payload: [], |
| 2502 | }, |
| 2503 | { |
| 2504 | type: "session/update/fulfilled", |
| 2505 | meta: { |
| 2506 | arg: expect.objectContaining({ |
| 2507 | history: expect.any(Array), |
| 2508 | sessionId: "session-123", |
| 2509 | title: "New Session", |
| 2510 | workspaceDirectory: "", |
| 2511 | }), |
| 2512 | requestId: expect.any(String), |
| 2513 | requestStatus: "fulfilled", |
| 2514 | }, |
| 2515 | payload: undefined, |
| 2516 | }, |
| 2517 | { |
| 2518 | type: "session/saveCurrent/fulfilled", |
| 2519 | meta: { |
| 2520 | arg: { |
| 2521 | generateTitle: true, |
| 2522 | openNewSession: false, |
| 2523 | }, |
| 2524 | requestId: expect.any(String), |
| 2525 | requestStatus: "fulfilled", |
| 2526 | }, |
| 2527 | payload: undefined, |
| 2528 | }, |
| 2529 | { |
| 2530 | type: "chat/streamWrapper/fulfilled", |
| 2531 | meta: { |
| 2532 | arg: expect.any(Function), |
| 2533 | requestId: expect.any(String), |
| 2534 | requestStatus: "fulfilled", |
| 2535 | }, |
| 2536 | payload: undefined, |
| 2537 | }, |
| 2538 | { |
| 2539 | type: "chat/streamResponse/fulfilled", |
| 2540 | meta: { |
| 2541 | arg: { |
| 2542 | editorState: mockEditorState, |
| 2543 | modifiers: mockModifiers, |
| 2544 | }, |
| 2545 | requestId: expect.any(String), |
| 2546 | requestStatus: "fulfilled", |
| 2547 | }, |
| 2548 | payload: undefined, |
| 2549 | }, |
| 2550 | ]); |
| 2551 | |
| 2552 | // Clear the actions array to track only the approval flow |
| 2553 | (mockStoreWithApproval as any).clearActions(); |
| 2554 | |
| 2555 | // Import the callToolById thunk to simulate user approval |
| 2556 | const { callToolById } = await import("./callToolById"); |
| 2557 | |
| 2558 | // Simulate user clicking "Accept" on the tool call |
| 2559 | const approvalResult = await mockStoreWithApproval.dispatch( |
| 2560 | callToolById({ toolCallId: "tool-approval-flow-1" }) as any, |
| 2561 | ); |
| 2562 | |
| 2563 | // Verify tool execution completed successfully |
| 2564 | expect(approvalResult.type).toBe("chat/callTool/fulfilled"); |
| 2565 | |
| 2566 | // Verify exact approval flow actions |
| 2567 | const approvalActions = (mockStoreWithApproval as any).getActions(); |
| 2568 | expect(approvalActions).toEqual([ |
| 2569 | { |
| 2570 | type: "chat/callTool/pending", |
| 2571 | meta: { |
| 2572 | arg: { toolCallId: "tool-approval-flow-1" }, |
| 2573 | requestId: expect.any(String), |
| 2574 | requestStatus: "pending", |
| 2575 | }, |
| 2576 | payload: undefined, |
| 2577 | }, |
| 2578 | { |
| 2579 | type: "session/setToolCallCalling", |
| 2580 | payload: { toolCallId: "tool-approval-flow-1" }, |
| 2581 | }, |
| 2582 | { |
| 2583 | type: "session/updateToolCallOutput", |
| 2584 | payload: { |
| 2585 | toolCallId: "tool-approval-flow-1", |
| 2586 | contextItems: [ |
| 2587 | { |
| 2588 | name: "Search Results", |
| 2589 | description: "Found test functions", |
| 2590 | content: |
| 2591 | "function testUserLogin() {...}\\nfunction testDataValidation() {...}", |
| 2592 | icon: "search", |
| 2593 | hidden: false, |
| 2594 | }, |
| 2595 | ], |
| 2596 | }, |
| 2597 | }, |
| 2598 | { |
| 2599 | type: "session/acceptToolCall", |
| 2600 | payload: { toolCallId: "tool-approval-flow-1" }, |
| 2601 | }, |
| 2602 | { |
| 2603 | type: "chat/streamAfterToolCall/pending", |
| 2604 | meta: { |
| 2605 | arg: { |
| 2606 | toolCallId: "tool-approval-flow-1", |
| 2607 | }, |
| 2608 | requestId: expect.any(String), |
| 2609 | requestStatus: "pending", |
| 2610 | }, |
| 2611 | payload: undefined, |
| 2612 | }, |
| 2613 | { |
| 2614 | type: "chat/streamWrapper/pending", |
| 2615 | meta: { |
| 2616 | arg: expect.any(Function), |
| 2617 | requestId: expect.any(String), |
| 2618 | requestStatus: "pending", |
| 2619 | }, |
| 2620 | payload: undefined, |
| 2621 | }, |
| 2622 | { |
| 2623 | type: "session/resetNextCodeBlockToApplyIndex", |
| 2624 | payload: undefined, |
| 2625 | }, |
| 2626 | { |
| 2627 | type: "session/streamUpdate", |
| 2628 | payload: [ |
| 2629 | { |
| 2630 | content: |
| 2631 | "function testUserLogin() {...}\\nfunction testDataValidation() {...}", |
| 2632 | role: "tool", |
| 2633 | toolCallId: "tool-approval-flow-1", |
| 2634 | }, |
| 2635 | ], |
| 2636 | }, |
| 2637 | { |
| 2638 | type: "chat/streamNormalInput/pending", |
| 2639 | meta: { |
| 2640 | arg: {}, |
| 2641 | requestId: expect.any(String), |
| 2642 | requestStatus: "pending", |
| 2643 | }, |
| 2644 | payload: undefined, |
| 2645 | }, |
| 2646 | { |
| 2647 | type: "session/setAppliedRulesAtIndex", |
| 2648 | payload: { |
| 2649 | appliedRules: [], |
| 2650 | index: 1, |
| 2651 | }, |
| 2652 | }, |
| 2653 | { |
| 2654 | type: "session/setActive", |
| 2655 | payload: undefined, |
| 2656 | }, |
| 2657 | { |
| 2658 | type: "session/setInlineErrorMessage", |
| 2659 | payload: undefined, |
| 2660 | }, |
| 2661 | { |
| 2662 | type: "session/setIsPruned", |
| 2663 | payload: false, |
| 2664 | }, |
| 2665 | { |
| 2666 | type: "session/setContextPercentage", |
| 2667 | payload: 0.85, |
| 2668 | }, |
| 2669 | { |
| 2670 | type: "session/streamUpdate", |
| 2671 | payload: [ |
| 2672 | { |
| 2673 | role: "assistant", |
| 2674 | content: |
| 2675 | "I found several test functions in your codebase. Here are the main ones I discovered...", |
| 2676 | }, |
| 2677 | ], |
| 2678 | }, |
| 2679 | { |
| 2680 | type: "session/addPromptCompletionPair", |
| 2681 | payload: [ |
| 2682 | { |
| 2683 | completion: |
| 2684 | "I found several test functions in your codebase. Here are the main ones I discovered...", |
| 2685 | modelProvider: "anthropic", |
| 2686 | prompt: "continuing after tool execution", |
| 2687 | }, |
| 2688 | ], |
| 2689 | }, |
| 2690 | { |
| 2691 | type: "session/setInactive", |
| 2692 | payload: undefined, |
| 2693 | }, |
| 2694 | { |
| 2695 | type: "chat/streamNormalInput/fulfilled", |
| 2696 | meta: { |
| 2697 | arg: {}, |
| 2698 | requestId: expect.any(String), |
| 2699 | requestStatus: "fulfilled", |
| 2700 | }, |
| 2701 | payload: undefined, |
| 2702 | }, |
| 2703 | { |
| 2704 | type: "session/saveCurrent/pending", |
| 2705 | meta: { |
| 2706 | arg: { |
| 2707 | generateTitle: true, |
| 2708 | openNewSession: false, |
| 2709 | }, |
| 2710 | requestId: expect.any(String), |
| 2711 | requestStatus: "pending", |
| 2712 | }, |
| 2713 | payload: undefined, |
| 2714 | }, |
| 2715 | { |
| 2716 | type: "session/update/pending", |
| 2717 | meta: { |
| 2718 | arg: expect.objectContaining({ |
| 2719 | history: expect.any(Array), |
| 2720 | sessionId: "session-123", |
| 2721 | title: "New Session", |
| 2722 | workspaceDirectory: "", |
| 2723 | }), |
| 2724 | requestId: expect.any(String), |
| 2725 | requestStatus: "pending", |
| 2726 | }, |
| 2727 | payload: undefined, |
| 2728 | }, |
| 2729 | { |
| 2730 | type: "session/updateSessionMetadata", |
| 2731 | payload: { |
| 2732 | sessionId: "session-123", |
| 2733 | title: "New Session", |
| 2734 | }, |
| 2735 | }, |
| 2736 | { |
| 2737 | type: "session/refreshMetadata/pending", |
| 2738 | meta: { |
| 2739 | arg: {}, |
| 2740 | requestId: expect.any(String), |
| 2741 | requestStatus: "pending", |
| 2742 | }, |
| 2743 | payload: undefined, |
| 2744 | }, |
| 2745 | { |
| 2746 | type: "session/setIsSessionMetadataLoading", |
| 2747 | payload: false, |
| 2748 | }, |
| 2749 | { |
| 2750 | type: "session/setAllSessionMetadata", |
| 2751 | payload: [], |
| 2752 | }, |
| 2753 | { |
| 2754 | type: "session/refreshMetadata/fulfilled", |
| 2755 | meta: { |
| 2756 | arg: {}, |
| 2757 | requestId: expect.any(String), |
| 2758 | requestStatus: "fulfilled", |
| 2759 | }, |
| 2760 | payload: [], |
| 2761 | }, |
| 2762 | { |
| 2763 | type: "session/update/fulfilled", |
| 2764 | meta: { |
| 2765 | arg: expect.objectContaining({ |
| 2766 | history: expect.any(Array), |
| 2767 | sessionId: "session-123", |
| 2768 | title: "New Session", |
| 2769 | workspaceDirectory: "", |
| 2770 | }), |
| 2771 | requestId: expect.any(String), |
| 2772 | requestStatus: "fulfilled", |
| 2773 | }, |
| 2774 | payload: undefined, |
| 2775 | }, |
| 2776 | { |
| 2777 | type: "session/saveCurrent/fulfilled", |
| 2778 | meta: { |
| 2779 | arg: { |
| 2780 | generateTitle: true, |
| 2781 | openNewSession: false, |
| 2782 | }, |
| 2783 | requestId: expect.any(String), |
| 2784 | requestStatus: "fulfilled", |
| 2785 | }, |
| 2786 | payload: undefined, |
| 2787 | }, |
| 2788 | { |
| 2789 | type: "chat/streamWrapper/fulfilled", |
| 2790 | meta: { |
| 2791 | arg: expect.any(Function), |
| 2792 | requestId: expect.any(String), |
| 2793 | requestStatus: "fulfilled", |
| 2794 | }, |
| 2795 | payload: undefined, |
| 2796 | }, |
| 2797 | { |
| 2798 | type: "chat/streamAfterToolCall/fulfilled", |
| 2799 | meta: { |
| 2800 | arg: { |
| 2801 | toolCallId: "tool-approval-flow-1", |
| 2802 | }, |
| 2803 | requestId: expect.any(String), |
| 2804 | requestStatus: "fulfilled", |
| 2805 | }, |
| 2806 | payload: undefined, |
| 2807 | }, |
| 2808 | { |
| 2809 | type: "chat/callTool/fulfilled", |
| 2810 | meta: { |
| 2811 | arg: { toolCallId: "tool-approval-flow-1" }, |
| 2812 | requestId: expect.any(String), |
| 2813 | requestStatus: "fulfilled", |
| 2814 | }, |
| 2815 | payload: undefined, |
| 2816 | }, |
| 2817 | ]); |
| 2818 | |
| 2819 | // Verify telemetry events for manual approval flow |
| 2820 | // Use partial matching to allow additional fields (e.g. model) in payload |
| 2821 | expect(mockPosthog.capture).toHaveBeenCalledWith( |
| 2822 | "tool_call_decision", |
| 2823 | expect.objectContaining({ |
| 2824 | decision: "accept", |
| 2825 | toolName: "search_codebase", |
| 2826 | toolCallId: "tool-approval-flow-1", |
| 2827 | }), |
| 2828 | ); |
| 2829 | |
| 2830 | expect(mockPosthog.capture).toHaveBeenCalledWith( |
| 2831 | "tool_call_outcome", |
| 2832 | expect.objectContaining({ |
| 2833 | succeeded: true, |
| 2834 | toolName: "search_codebase", |
| 2835 | errorReason: undefined, |
| 2836 | duration_ms: expect.any(Number), |
| 2837 | }), |
| 2838 | ); |
| 2839 | |
| 2840 | // Verify IDE messenger calls for tool execution |
| 2841 | expect(mockIdeMessengerApproval.request).toHaveBeenCalledWith( |
| 2842 | "tools/call", |
| 2843 | { |
| 2844 | toolCall: { |
| 2845 | id: "tool-approval-flow-1", |
| 2846 | type: "function", |
| 2847 | function: { |
| 2848 | name: "search_codebase", |
| 2849 | arguments: JSON.stringify({ query: "test function" }), |
| 2850 | }, |
| 2851 | }, |
| 2852 | }, |
| 2853 | ); |
| 2854 | |
| 2855 | // Verify second streaming call was made for continuation |
| 2856 | expect(streamCallCount).toBe(2); |
| 2857 | |
| 2858 | // Verify final state shows completed tool call and follow-up response |
| 2859 | const finalState = mockStoreWithApproval.getState(); |
| 2860 | expect(finalState).toEqual({ |
| 2861 | session: { |
| 2862 | history: [ |
| 2863 | { |
| 2864 | contextItems: [], |
| 2865 | message: { |
| 2866 | id: "1", |
| 2867 | role: "user", |
| 2868 | content: "Please search the codebase for test functions", |
| 2869 | }, |
| 2870 | }, |
| 2871 | { |
| 2872 | appliedRules: [], |
| 2873 | contextItems: [], |
| 2874 | editorState: mockEditorState, |
| 2875 | message: { |
| 2876 | content: "Hello, please help me with this code", |
| 2877 | id: expect.any(String), |
| 2878 | role: "user", |
| 2879 | }, |
| 2880 | }, |
| 2881 | { |
| 2882 | contextItems: [], |
| 2883 | isGatheringContext: false, |
| 2884 | message: { |
| 2885 | content: "I'll search for test functions in the codebase.", |
| 2886 | id: expect.any(String), |
| 2887 | role: "assistant", |
| 2888 | toolCalls: [ |
| 2889 | { |
| 2890 | id: "tool-approval-flow-1", |
| 2891 | type: "function", |
| 2892 | function: { |
| 2893 | name: "search_codebase", |
| 2894 | arguments: JSON.stringify({ query: "test function" }), |
| 2895 | }, |
| 2896 | }, |
| 2897 | ], |
| 2898 | }, |
| 2899 | promptLogs: [ |
| 2900 | { |
| 2901 | completion: "I'll search for test functions in the codebase.", |
| 2902 | modelProvider: "anthropic", |
| 2903 | prompt: "Please search the codebase for test functions", |
| 2904 | }, |
| 2905 | ], |
| 2906 | toolCallStates: [ |
| 2907 | { |
| 2908 | toolCallId: "tool-approval-flow-1", |
| 2909 | toolCall: { |
| 2910 | id: "tool-approval-flow-1", |
| 2911 | type: "function", |
| 2912 | function: { |
| 2913 | name: "search_codebase", |
| 2914 | arguments: JSON.stringify({ query: "test function" }), |
| 2915 | }, |
| 2916 | }, |
| 2917 | parsedArgs: { query: "test function" }, |
| 2918 | status: "done", // Tool call completed successfully |
| 2919 | output: [ |
| 2920 | { |
| 2921 | name: "Search Results", |
| 2922 | description: "Found test functions", |
| 2923 | content: |
| 2924 | "function testUserLogin() {...}\\nfunction testDataValidation() {...}", |
| 2925 | icon: "search", |
| 2926 | hidden: false, |
| 2927 | }, |
| 2928 | ], |
| 2929 | }, |
| 2930 | ], |
| 2931 | }, |
| 2932 | { |
| 2933 | contextItems: [], |
| 2934 | message: { |
| 2935 | content: |
| 2936 | "function testUserLogin() {...}\\nfunction testDataValidation() {...}", |
| 2937 | id: expect.any(String), |
| 2938 | role: "tool", |
| 2939 | toolCallId: "tool-approval-flow-1", |
| 2940 | }, |
| 2941 | }, |
| 2942 | { |
| 2943 | contextItems: [], |
| 2944 | isGatheringContext: false, |
| 2945 | message: { |
| 2946 | content: |
| 2947 | "I found several test functions in your codebase. Here are the main ones I discovered...", |
| 2948 | id: "mock-uuid-123", |
| 2949 | role: "assistant", |
| 2950 | }, |
| 2951 | promptLogs: [ |
| 2952 | { |
| 2953 | completion: |
| 2954 | "I found several test functions in your codebase. Here are the main ones I discovered...", |
| 2955 | modelProvider: "anthropic", |
| 2956 | prompt: "continuing after tool execution", |
| 2957 | }, |
| 2958 | ], |
| 2959 | }, |
| 2960 | ], |
| 2961 | hasReasoningEnabled: false, |
| 2962 | isStreaming: false, // Inactive after complete flow |
| 2963 | id: "session-123", |
| 2964 | mode: "chat", |
| 2965 | streamAborter: expect.any(AbortController), |
| 2966 | contextPercentage: 0.85, |
| 2967 | isPruned: false, |
| 2968 | isInEdit: false, |
| 2969 | title: "New Session", |
| 2970 | lastSessionId: undefined, |
| 2971 | isSessionMetadataLoading: false, |
| 2972 | allSessionMetadata: [], |
| 2973 | symbols: {}, |
| 2974 | codeBlockApplyStates: { |
| 2975 | states: [], |
| 2976 | curIndex: 0, |
| 2977 | }, |
| 2978 | newestToolbarPreviewForInput: {}, |
| 2979 | compactionLoading: {}, |
| 2980 | inlineErrorMessage: undefined, |
| 2981 | }, |
| 2982 | config: { |
| 2983 | config: { |
| 2984 | tools: [], |
| 2985 | rules: [], |
| 2986 | tabAutocompleteModel: undefined, |
| 2987 | selectedModelByRole: { |
| 2988 | chat: mockClaudeModel, |
| 2989 | apply: null, |
| 2990 | edit: null, |
| 2991 | summarize: null, |
| 2992 | autocomplete: null, |
| 2993 | rerank: null, |
| 2994 | embed: null, |
| 2995 | }, |
| 2996 | experimental: { |
| 2997 | onlyUseSystemMessageTools: false, |
| 2998 | }, |
| 2999 | }, |
| 3000 | lastSelectedModelByRole: { |
| 3001 | chat: mockClaudeModel.title, |
| 3002 | }, |
| 3003 | loading: false, |
| 3004 | configError: undefined, |
| 3005 | }, |
| 3006 | ui: { |
| 3007 | toolSettings: { |
| 3008 | search_codebase: "askFirst", |
| 3009 | }, |
| 3010 | ruleSettings: {}, |
| 3011 | showDialog: false, |
| 3012 | dialogMessage: undefined, |
| 3013 | }, |
| 3014 | editModeState: { |
| 3015 | isInEdit: false, |
| 3016 | returnToMode: "chat", |
| 3017 | }, |
| 3018 | indexing: { |
| 3019 | indexing: { |
| 3020 | statuses: {}, |
| 3021 | hiddenChatPeekTypes: { |
| 3022 | docs: false, |
| 3023 | }, |
| 3024 | }, |
| 3025 | }, |
| 3026 | tabs: { |
| 3027 | tabsItems: [], |
| 3028 | }, |
| 3029 | profiles: { |
| 3030 | organizations: [], |
| 3031 | selectedProfileId: null, |
| 3032 | selectedOrganizationId: null, |
| 3033 | preferencesByProfileId: {}, |
| 3034 | }, |
| 3035 | }); |
| 3036 | }); |
| 3037 | |
| 3038 | describe("dynamic policy evaluation", () => { |
| 3039 | it("should call tools/evaluatePolicy with correct parameters", async () => { |
| 3040 | const mockStore = createMockStore({ |
| 3041 | session: { |
| 3042 | history: [ |
| 3043 | { |
| 3044 | message: { id: "1", role: "user", content: "Run echo hello" }, |
| 3045 | contextItems: [], |
| 3046 | }, |
| 3047 | ], |
| 3048 | hasReasoningEnabled: false, |
| 3049 | isStreaming: true, |
| 3050 | id: "session-123", |
| 3051 | mode: "chat", |
| 3052 | streamAborter: new AbortController(), |
| 3053 | contextPercentage: 0, |
| 3054 | isPruned: false, |
| 3055 | isInEdit: false, |
| 3056 | title: "", |
| 3057 | lastSessionId: undefined, |
| 3058 | isSessionMetadataLoading: false, |
| 3059 | allSessionMetadata: [], |
| 3060 | symbols: {}, |
| 3061 | codeBlockApplyStates: { |
| 3062 | states: [], |
| 3063 | curIndex: 0, |
| 3064 | }, |
| 3065 | newestToolbarPreviewForInput: {}, |
| 3066 | compactionLoading: {}, |
| 3067 | inlineErrorMessage: undefined, |
| 3068 | }, |
| 3069 | config: { |
| 3070 | config: { |
| 3071 | tools: [], |
| 3072 | rules: [], |
| 3073 | tabAutocompleteModel: undefined, |
| 3074 | selectedModelByRole: { |
| 3075 | chat: mockClaudeModel, |
| 3076 | apply: null, |
| 3077 | edit: null, |
| 3078 | summarize: null, |
| 3079 | autocomplete: null, |
| 3080 | rerank: null, |
| 3081 | embed: null, |
| 3082 | }, |
| 3083 | experimental: { |
| 3084 | onlyUseSystemMessageTools: false, |
| 3085 | }, |
| 3086 | } as any, |
| 3087 | lastSelectedModelByRole: { |
| 3088 | chat: mockClaudeModel.title, |
| 3089 | }, |
| 3090 | } as any, |
| 3091 | ui: { |
| 3092 | toolSettings: { |
| 3093 | run_terminal_command: "allowedWithoutPermission", |
| 3094 | }, |
| 3095 | ruleSettings: {}, |
| 3096 | showDialog: false, |
| 3097 | dialogMessage: undefined, |
| 3098 | } as any, |
| 3099 | } as any); |
| 3100 | |
| 3101 | const mockIdeMessenger = mockStore.mockIdeMessenger; |
| 3102 | |
| 3103 | // Simple mock - just return a different policy for testing |
| 3104 | mockIdeMessenger.request.mockImplementation( |
| 3105 | (endpoint: string, data: any) => { |
| 3106 | if (endpoint === "tools/evaluatePolicy") { |
| 3107 | // For this test, simulate that echo commands require permission |
| 3108 | if (data.args.command?.toLowerCase().startsWith("echo")) { |
| 3109 | return Promise.resolve({ |
| 3110 | status: "success", |
| 3111 | content: { policy: "allowedWithPermission" }, |
| 3112 | }); |
| 3113 | } |
| 3114 | return Promise.resolve({ |
| 3115 | status: "success", |
| 3116 | content: { policy: data.basePolicy }, |
| 3117 | }); |
| 3118 | } else if (endpoint === "llm/compileChat") { |
| 3119 | return Promise.resolve({ |
| 3120 | status: "success", |
| 3121 | content: { |
| 3122 | compiledChatMessages: [ |
| 3123 | { role: "user", content: "Run echo hello" }, |
| 3124 | ], |
| 3125 | didPrune: false, |
| 3126 | contextPercentage: 0.5, |
| 3127 | }, |
| 3128 | }); |
| 3129 | } else if (endpoint === "history/save") { |
| 3130 | return Promise.resolve({ status: "success" }); |
| 3131 | } else if (endpoint === "history/list") { |
| 3132 | return Promise.resolve({ status: "success", content: [] }); |
| 3133 | } |
| 3134 | return Promise.resolve({ status: "success", content: {} }); |
| 3135 | }, |
| 3136 | ); |
| 3137 | |
| 3138 | // Setup streaming with echo command (should require permission despite auto-approve base) |
| 3139 | async function* mockStreamWithEcho() { |
| 3140 | yield [{ role: "assistant", content: "I'll run the echo command." }]; |
| 3141 | yield [ |
| 3142 | { |
| 3143 | role: "assistant", |
| 3144 | content: "", |
| 3145 | toolCalls: [ |
| 3146 | { |
| 3147 | id: "tool-echo-1", |
| 3148 | type: "function", |
| 3149 | function: { |
| 3150 | name: "run_terminal_command", |
| 3151 | arguments: JSON.stringify({ command: "echo hello" }), |
| 3152 | }, |
| 3153 | }, |
| 3154 | ], |
| 3155 | }, |
| 3156 | ]; |
| 3157 | return { |
| 3158 | prompt: "Run echo hello", |
| 3159 | completion: "I'll run the echo command.", |
| 3160 | modelProvider: "anthropic", |
| 3161 | }; |
| 3162 | } |
| 3163 | |
| 3164 | mockIdeMessenger.llmStreamChat.mockReturnValue(mockStreamWithEcho()); |
| 3165 | |
| 3166 | // Execute thunk |
| 3167 | await mockStore.dispatch( |
| 3168 | streamResponseThunk({ |
| 3169 | editorState: mockEditorState, |
| 3170 | modifiers: mockModifiers, |
| 3171 | }) as any, |
| 3172 | ); |
| 3173 | |
| 3174 | // Just verify the call was made with correct params |
| 3175 | expect(mockIdeMessenger.request).toHaveBeenCalledWith( |
| 3176 | "tools/evaluatePolicy", |
| 3177 | expect.objectContaining({ |
| 3178 | toolName: "run_terminal_command", |
| 3179 | basePolicy: "allowedWithoutPermission", |
| 3180 | args: { command: "echo hello" }, |
| 3181 | }), |
| 3182 | ); |
| 3183 | |
| 3184 | // Verify tool wasn't auto-executed (policy changed to require permission) |
| 3185 | expect(mockIdeMessenger.request).not.toHaveBeenCalledWith( |
| 3186 | "tools/call", |
| 3187 | expect.any(Object), |
| 3188 | ); |
| 3189 | }); |
| 3190 | |
| 3191 | it("should respect disabled policy", async () => { |
| 3192 | const mockStore = createMockStore({ |
| 3193 | session: { |
| 3194 | history: [ |
| 3195 | { |
| 3196 | message: { id: "1", role: "user", content: "Run ls" }, |
| 3197 | contextItems: [], |
| 3198 | }, |
| 3199 | ], |
| 3200 | hasReasoningEnabled: false, |
| 3201 | isStreaming: true, |
| 3202 | id: "session-123", |
| 3203 | mode: "chat", |
| 3204 | streamAborter: new AbortController(), |
| 3205 | contextPercentage: 0, |
| 3206 | isPruned: false, |
| 3207 | isInEdit: false, |
| 3208 | title: "", |
| 3209 | lastSessionId: undefined, |
| 3210 | isSessionMetadataLoading: false, |
| 3211 | allSessionMetadata: [], |
| 3212 | symbols: {}, |
| 3213 | codeBlockApplyStates: { |
| 3214 | states: [], |
| 3215 | curIndex: 0, |
| 3216 | }, |
| 3217 | newestToolbarPreviewForInput: {}, |
| 3218 | compactionLoading: {}, |
| 3219 | inlineErrorMessage: undefined, |
| 3220 | }, |
| 3221 | config: { |
| 3222 | config: { |
| 3223 | tools: [], |
| 3224 | rules: [], |
| 3225 | tabAutocompleteModel: undefined, |
| 3226 | selectedModelByRole: { |
| 3227 | chat: mockClaudeModel, |
| 3228 | apply: null, |
| 3229 | edit: null, |
| 3230 | summarize: null, |
| 3231 | autocomplete: null, |
| 3232 | rerank: null, |
| 3233 | embed: null, |
| 3234 | }, |
| 3235 | experimental: { |
| 3236 | onlyUseSystemMessageTools: false, |
| 3237 | }, |
| 3238 | } as any, |
| 3239 | lastSelectedModelByRole: { |
| 3240 | chat: mockClaudeModel.title, |
| 3241 | }, |
| 3242 | } as any, |
| 3243 | ui: { |
| 3244 | toolSettings: { |
| 3245 | run_terminal_command: "disabled", // Tool is disabled |
| 3246 | }, |
| 3247 | ruleSettings: {}, |
| 3248 | showDialog: false, |
| 3249 | dialogMessage: undefined, |
| 3250 | } as any, |
| 3251 | } as any); |
| 3252 | |
| 3253 | const mockIdeMessenger = mockStore.mockIdeMessenger; |
| 3254 | |
| 3255 | // Simple mock - just return disabled policy |
| 3256 | mockIdeMessenger.request.mockImplementation( |
| 3257 | (endpoint: string, data: any) => { |
| 3258 | if (endpoint === "tools/evaluatePolicy") { |
| 3259 | // Backend should respect disabled state |
| 3260 | return Promise.resolve({ |
| 3261 | status: "success", |
| 3262 | content: { policy: "disabled" }, |
| 3263 | }); |
| 3264 | } else if (endpoint === "llm/compileChat") { |
| 3265 | return Promise.resolve({ |
| 3266 | status: "success", |
| 3267 | content: { |
| 3268 | compiledChatMessages: [{ role: "user", content: "Run ls" }], |
| 3269 | didPrune: false, |
| 3270 | contextPercentage: 0.5, |
| 3271 | }, |
| 3272 | }); |
| 3273 | } else if (endpoint === "history/save") { |
| 3274 | return Promise.resolve({ status: "success" }); |
| 3275 | } else if (endpoint === "history/list") { |
| 3276 | return Promise.resolve({ status: "success", content: [] }); |
| 3277 | } |
| 3278 | return Promise.resolve({ status: "success", content: {} }); |
| 3279 | }, |
| 3280 | ); |
| 3281 | |
| 3282 | // Setup streaming with regular command |
| 3283 | async function* mockStreamWithLs() { |
| 3284 | yield [{ role: "assistant", content: "I'll list the files." }]; |
| 3285 | yield [ |
| 3286 | { |
| 3287 | role: "assistant", |
| 3288 | content: "", |
| 3289 | toolCalls: [ |
| 3290 | { |
| 3291 | id: "tool-ls-1", |
| 3292 | type: "function", |
| 3293 | function: { |
| 3294 | name: "run_terminal_command", |
| 3295 | arguments: JSON.stringify({ command: "ls" }), |
| 3296 | }, |
| 3297 | }, |
| 3298 | ], |
| 3299 | }, |
| 3300 | ]; |
| 3301 | return { |
| 3302 | prompt: "Run ls", |
| 3303 | completion: "I'll list the files.", |
| 3304 | modelProvider: "anthropic", |
| 3305 | }; |
| 3306 | } |
| 3307 | |
| 3308 | mockIdeMessenger.llmStreamChat.mockReturnValue(mockStreamWithLs()); |
| 3309 | |
| 3310 | // Execute thunk |
| 3311 | await mockStore.dispatch( |
| 3312 | streamResponseThunk({ |
| 3313 | editorState: mockEditorState, |
| 3314 | modifiers: mockModifiers, |
| 3315 | }) as any, |
| 3316 | ); |
| 3317 | |
| 3318 | // Verify tools/evaluatePolicy was called |
| 3319 | expect(mockIdeMessenger.request).toHaveBeenCalledWith( |
| 3320 | "tools/evaluatePolicy", |
| 3321 | expect.objectContaining({ |
| 3322 | toolName: "run_terminal_command", |
| 3323 | basePolicy: "disabled", |
| 3324 | args: { command: "ls" }, |
| 3325 | }), |
| 3326 | ); |
| 3327 | |
| 3328 | // Tool should NOT be executed since it's disabled |
| 3329 | expect(mockIdeMessenger.request).not.toHaveBeenCalledWith( |
| 3330 | "tools/call", |
| 3331 | expect.any(Object), |
| 3332 | ); |
| 3333 | }); |
| 3334 | |
| 3335 | it("should handle evaluation errors gracefully", async () => { |
| 3336 | const mockStore = createMockStore({ |
| 3337 | session: { |
| 3338 | history: [ |
| 3339 | { |
| 3340 | message: { id: "1", role: "user", content: "Do something" }, |
| 3341 | contextItems: [], |
| 3342 | }, |
| 3343 | ], |
| 3344 | hasReasoningEnabled: false, |
| 3345 | isStreaming: true, |
| 3346 | id: "session-123", |
| 3347 | mode: "chat", |
| 3348 | streamAborter: new AbortController(), |
| 3349 | contextPercentage: 0, |
| 3350 | isPruned: false, |
| 3351 | isInEdit: false, |
| 3352 | title: "", |
| 3353 | lastSessionId: undefined, |
| 3354 | isSessionMetadataLoading: false, |
| 3355 | allSessionMetadata: [], |
| 3356 | symbols: {}, |
| 3357 | codeBlockApplyStates: { |
| 3358 | states: [], |
| 3359 | curIndex: 0, |
| 3360 | }, |
| 3361 | newestToolbarPreviewForInput: {}, |
| 3362 | compactionLoading: {}, |
| 3363 | inlineErrorMessage: undefined, |
| 3364 | }, |
| 3365 | config: { |
| 3366 | config: { |
| 3367 | tools: [], |
| 3368 | rules: [], |
| 3369 | tabAutocompleteModel: undefined, |
| 3370 | selectedModelByRole: { |
| 3371 | chat: mockClaudeModel, |
| 3372 | apply: null, |
| 3373 | edit: null, |
| 3374 | summarize: null, |
| 3375 | autocomplete: null, |
| 3376 | rerank: null, |
| 3377 | embed: null, |
| 3378 | }, |
| 3379 | experimental: { |
| 3380 | onlyUseSystemMessageTools: false, |
| 3381 | }, |
| 3382 | } as any, |
| 3383 | lastSelectedModelByRole: { |
| 3384 | chat: mockClaudeModel.title, |
| 3385 | }, |
| 3386 | } as any, |
| 3387 | ui: { |
| 3388 | toolSettings: { |
| 3389 | some_tool: "allowedWithoutPermission", |
| 3390 | }, |
| 3391 | ruleSettings: {}, |
| 3392 | showDialog: false, |
| 3393 | dialogMessage: undefined, |
| 3394 | } as any, |
| 3395 | } as any); |
| 3396 | |
| 3397 | const mockIdeMessenger = mockStore.mockIdeMessenger; |
| 3398 | |
| 3399 | // Mock evaluation failure |
| 3400 | mockIdeMessenger.request.mockImplementation((endpoint: string) => { |
| 3401 | if (endpoint === "tools/evaluatePolicy") { |
| 3402 | // Simulate evaluation error |
| 3403 | return Promise.resolve({ |
| 3404 | status: "error", |
| 3405 | error: "Failed to evaluate policy", |
| 3406 | }); |
| 3407 | } else if (endpoint === "llm/compileChat") { |
| 3408 | return Promise.resolve({ |
| 3409 | status: "success", |
| 3410 | content: { |
| 3411 | compiledChatMessages: [{ role: "user", content: "Do something" }], |
| 3412 | didPrune: false, |
| 3413 | contextPercentage: 0.5, |
| 3414 | }, |
| 3415 | }); |
| 3416 | } else if (endpoint === "history/save") { |
| 3417 | return Promise.resolve({ status: "success" }); |
| 3418 | } else if (endpoint === "history/list") { |
| 3419 | return Promise.resolve({ status: "success", content: [] }); |
| 3420 | } |
| 3421 | return Promise.resolve({ status: "success", content: {} }); |
| 3422 | }); |
| 3423 | |
| 3424 | // Setup streaming with tool call |
| 3425 | async function* mockStreamWithTool() { |
| 3426 | yield [{ role: "assistant", content: "I'll help you." }]; |
| 3427 | yield [ |
| 3428 | { |
| 3429 | role: "assistant", |
| 3430 | content: "", |
| 3431 | toolCalls: [ |
| 3432 | { |
| 3433 | id: "tool-1", |
| 3434 | type: "function", |
| 3435 | function: { |
| 3436 | name: "some_tool", |
| 3437 | arguments: JSON.stringify({ arg: "value" }), |
| 3438 | }, |
| 3439 | }, |
| 3440 | ], |
| 3441 | }, |
| 3442 | ]; |
| 3443 | return { |
| 3444 | prompt: "Do something", |
| 3445 | completion: "I'll help you.", |
| 3446 | modelProvider: "anthropic", |
| 3447 | }; |
| 3448 | } |
| 3449 | |
| 3450 | mockIdeMessenger.llmStreamChat.mockReturnValue(mockStreamWithTool()); |
| 3451 | |
| 3452 | // Execute thunk - should handle error gracefully |
| 3453 | const result = await mockStore.dispatch( |
| 3454 | streamResponseThunk({ |
| 3455 | editorState: mockEditorState, |
| 3456 | modifiers: mockModifiers, |
| 3457 | }) as any, |
| 3458 | ); |
| 3459 | |
| 3460 | // Should complete successfully despite evaluation error |
| 3461 | expect(result.type).toBe("chat/streamResponse/fulfilled"); |
| 3462 | |
| 3463 | // Tool should be treated as disabled due to evaluation error |
| 3464 | expect(mockIdeMessenger.request).not.toHaveBeenCalledWith( |
| 3465 | "tools/call", |
| 3466 | expect.any(Object), |
| 3467 | ); |
| 3468 | }); |
| 3469 | |
| 3470 | it("should properly handle disabled commands and show error status", async () => { |
| 3471 | const { mockStore, mockIdeMessenger } = setupTest(); |
| 3472 | |
| 3473 | // Setup store with runTerminalCommand tool |
| 3474 | const mockStoreWithTerminalTool = createMockStore({ |
| 3475 | ...mockStore.getState(), |
| 3476 | config: { |
| 3477 | ...mockStore.getState().config, |
| 3478 | config: { |
| 3479 | ...mockStore.getState().config.config, |
| 3480 | tools: [ |
| 3481 | { |
| 3482 | type: "function", |
| 3483 | displayTitle: "Run Terminal Command", |
| 3484 | function: { |
| 3485 | name: "runTerminalCommand", |
| 3486 | description: "Execute a terminal command", |
| 3487 | parameters: { |
| 3488 | type: "object", |
| 3489 | properties: { |
| 3490 | command: { |
| 3491 | type: "string", |
| 3492 | description: "The command to execute", |
| 3493 | }, |
| 3494 | }, |
| 3495 | required: ["command"], |
| 3496 | }, |
| 3497 | }, |
| 3498 | defaultToolPolicy: "allowedWithPermission", |
| 3499 | readonly: false, |
| 3500 | group: "code", |
| 3501 | }, |
| 3502 | ], |
| 3503 | }, |
| 3504 | }, |
| 3505 | ui: { |
| 3506 | ...mockStore.getState().ui, |
| 3507 | toolSettings: { |
| 3508 | runTerminalCommand: "allowedWithPermission", |
| 3509 | }, |
| 3510 | }, |
| 3511 | }); |
| 3512 | |
| 3513 | const mockTerminalIdeMessenger = |
| 3514 | mockStoreWithTerminalTool.mockIdeMessenger; |
| 3515 | |
| 3516 | // Setup compilation and policy evaluation responses |
| 3517 | mockTerminalIdeMessenger.request.mockImplementation( |
| 3518 | (endpoint: string, data: any) => { |
| 3519 | if (endpoint === "llm/compileChat") { |
| 3520 | return Promise.resolve({ |
| 3521 | status: "success", |
| 3522 | content: { |
| 3523 | compiledChatMessages: [ |
| 3524 | { role: "user", content: "Run eval command" }, |
| 3525 | ], |
| 3526 | didPrune: false, |
| 3527 | contextPercentage: 0.9, |
| 3528 | }, |
| 3529 | }); |
| 3530 | } else if (endpoint === "tools/evaluatePolicy") { |
| 3531 | // Return disabled for eval command |
| 3532 | const args = data.args || {}; |
| 3533 | if (args.command && args.command.includes("eval")) { |
| 3534 | return Promise.resolve({ |
| 3535 | status: "success", |
| 3536 | content: { policy: "disabled" }, |
| 3537 | }); |
| 3538 | } |
| 3539 | return Promise.resolve({ |
| 3540 | status: "success", |
| 3541 | content: { policy: "allowedWithPermission" }, |
| 3542 | }); |
| 3543 | } else if (endpoint === "history/save") { |
| 3544 | return Promise.resolve({ status: "success" }); |
| 3545 | } else if (endpoint === "history/list") { |
| 3546 | return Promise.resolve({ status: "success", content: [] }); |
| 3547 | } |
| 3548 | return Promise.resolve({ status: "success", content: {} }); |
| 3549 | }, |
| 3550 | ); |
| 3551 | |
| 3552 | // Setup streaming with eval command tool call |
| 3553 | async function* mockStreamWithEvalCommand() { |
| 3554 | yield [ |
| 3555 | { role: "assistant", content: "I'll run the eval command for you." }, |
| 3556 | ]; |
| 3557 | yield [ |
| 3558 | { |
| 3559 | role: "assistant", |
| 3560 | content: "", |
| 3561 | toolCalls: [ |
| 3562 | { |
| 3563 | id: "tool-call-eval", |
| 3564 | type: "function", |
| 3565 | function: { |
| 3566 | name: "runTerminalCommand", |
| 3567 | arguments: JSON.stringify({ command: 'eval "echo hello"' }), |
| 3568 | }, |
| 3569 | }, |
| 3570 | ], |
| 3571 | }, |
| 3572 | ]; |
| 3573 | return { |
| 3574 | prompt: "Run eval command", |
| 3575 | completion: "I'll run the eval command for you.", |
| 3576 | modelProvider: "anthropic", |
| 3577 | }; |
| 3578 | } |
| 3579 | |
| 3580 | mockTerminalIdeMessenger.llmStreamChat.mockReturnValue( |
| 3581 | mockStreamWithEvalCommand(), |
| 3582 | ); |
| 3583 | |
| 3584 | // Execute thunk |
| 3585 | await mockStoreWithTerminalTool.dispatch( |
| 3586 | streamResponseThunk({ |
| 3587 | editorState: mockEditorState, |
| 3588 | modifiers: mockModifiers, |
| 3589 | }) as any, |
| 3590 | ); |
| 3591 | |
| 3592 | // Get final state |
| 3593 | const finalState = mockStoreWithTerminalTool.getState(); |
| 3594 | const toolCallStates = finalState.session.history.flatMap( |
| 3595 | (item) => item.toolCallStates || [], |
| 3596 | ); |
| 3597 | |
| 3598 | // Find the eval command tool call |
| 3599 | const evalToolCall = toolCallStates.find( |
| 3600 | (t) => t.toolCallId === "tool-call-eval", |
| 3601 | ); |
| 3602 | |
| 3603 | expect(evalToolCall).toBeDefined(); |
| 3604 | |
| 3605 | // The tool call should have an errored status (not "generated") |
| 3606 | expect(evalToolCall?.status).toBe("errored"); |
| 3607 | |
| 3608 | // The tool call should have an error message explaining it's disabled |
| 3609 | // Errors are stored as ContextItems with the error in the content |
| 3610 | const errorOutput = evalToolCall?.output?.[0]; |
| 3611 | expect(errorOutput?.content).toContain("disabled"); |
| 3612 | |
| 3613 | // Verify the command was NOT executed (no tool/call request) |
| 3614 | const toolCallRequests = |
| 3615 | mockTerminalIdeMessenger.request.mock.calls.filter( |
| 3616 | (call) => call[0] === "tools/call", |
| 3617 | ); |
| 3618 | expect(toolCallRequests).toHaveLength(0); |
| 3619 | }); |
| 3620 | }); |
| 3621 | }); |