| 1 | import { render } from "ink-testing-library"; |
| 2 | import React from "react"; |
| 3 | import { vi } from "vitest"; |
| 4 | |
| 5 | import { ToolPermissionSelector } from "../components/ToolPermissionSelector.js"; |
| 6 | |
| 7 | describe("TUIChat - Stream Stopping on Tool Rejection", () => { |
| 8 | beforeEach(() => { |
| 9 | vi.useFakeTimers(); |
| 10 | }); |
| 11 | |
| 12 | afterEach(() => { |
| 13 | vi.clearAllTimers(); |
| 14 | vi.useRealTimers(); |
| 15 | }); |
| 16 | |
| 17 | it("verifies tool permission rejection flow", async () => { |
| 18 | const handleResponse = vi.fn(); |
| 19 | |
| 20 | const { stdin } = render( |
| 21 | <ToolPermissionSelector |
| 22 | toolName="Edit" |
| 23 | toolArgs={{ |
| 24 | file_path: "/test.txt", |
| 25 | old_string: "old content", |
| 26 | new_string: "new content", |
| 27 | }} |
| 28 | requestId="test-request-123" |
| 29 | onResponse={handleResponse} |
| 30 | />, |
| 31 | ); |
| 32 | |
| 33 | await vi.advanceTimersByTimeAsync(50); |
| 34 | |
| 35 | // Simulate user rejecting the tool call (press escape) |
| 36 | stdin.write("\x1b"); // ESC key |
| 37 | |
| 38 | await vi.advanceTimersByTimeAsync(50); |
| 39 | |
| 40 | // Verify that the tool was rejected with stop stream |
| 41 | expect(handleResponse).toHaveBeenCalledWith( |
| 42 | "test-request-123", |
| 43 | false, // approved = false |
| 44 | false, // createPolicy = false |
| 45 | true, // stopStream = true |
| 46 | ); |
| 47 | }); |
| 48 | |
| 49 | it("verifies rejection with 'n' key triggers proper response", async () => { |
| 50 | const handleResponse = vi.fn(); |
| 51 | |
| 52 | const { stdin } = render( |
| 53 | <ToolPermissionSelector |
| 54 | toolName="Write" |
| 55 | toolArgs={{ |
| 56 | file_path: "/dangerous-file.sh", |
| 57 | content: "rm -rf /", |
| 58 | }} |
| 59 | requestId="dangerous-request" |
| 60 | onResponse={handleResponse} |
| 61 | />, |
| 62 | ); |
| 63 | |
| 64 | await vi.advanceTimersByTimeAsync(50); |
| 65 | |
| 66 | // Press 'n' to reject |
| 67 | stdin.write("n"); |
| 68 | |
| 69 | await vi.advanceTimersByTimeAsync(50); |
| 70 | |
| 71 | // Verify rejection with stop stream |
| 72 | expect(handleResponse).toHaveBeenCalledWith( |
| 73 | "dangerous-request", |
| 74 | false, // rejected |
| 75 | false, // createPolicy = false |
| 76 | true, // stopStream = true |
| 77 | ); |
| 78 | }); |
| 79 | |
| 80 | it("tests that rejection response leads to stream stopping behavior", () => { |
| 81 | // This test validates the key behavior - when onResponse is called with approved=false, |
| 82 | // it should lead to the streamChatResponse function stopping and returning early |
| 83 | |
| 84 | const mockStreamingFunction = vi.fn().mockImplementation((approved) => { |
| 85 | if (!approved) { |
| 86 | // Simulate early return when tool is rejected |
| 87 | return "Partial content before rejection"; |
| 88 | } |
| 89 | // If approved, would continue with full processing |
| 90 | return "Full content with tool results"; |
| 91 | }); |
| 92 | |
| 93 | // Test rejection path |
| 94 | const rejectedResult = mockStreamingFunction(false); |
| 95 | expect(rejectedResult).toBe("Partial content before rejection"); |
| 96 | |
| 97 | // Test approval path for comparison |
| 98 | const approvedResult = mockStreamingFunction(true); |
| 99 | expect(approvedResult).toBe("Full content with tool results"); |
| 100 | |
| 101 | // The key insight: when tools are rejected, processing stops early |
| 102 | expect(rejectedResult).not.toBe(approvedResult); |
| 103 | }); |
| 104 | |
| 105 | it("validates permission manager handles rejection correctly", async () => { |
| 106 | // Import the permission manager to test its behavior |
| 107 | const { toolPermissionManager } = await import( |
| 108 | "../../permissions/permissionManager.js" |
| 109 | ); |
| 110 | |
| 111 | const mockResolve = vi.fn(); |
| 112 | |
| 113 | // Simulate a pending request |
| 114 | const requestId = "test-request-456"; |
| 115 | (toolPermissionManager as any).pendingRequests.set(requestId, { |
| 116 | toolCall: { name: "Edit", arguments: {} }, |
| 117 | resolve: mockResolve, |
| 118 | }); |
| 119 | |
| 120 | // Reject the request (this is what happens when user presses escape/n) |
| 121 | const result = toolPermissionManager.rejectRequest(requestId); |
| 122 | |
| 123 | // Verify the request was properly rejected |
| 124 | expect(result).toBe(true); |
| 125 | expect(mockResolve).toHaveBeenCalledWith({ approved: false }); |
| 126 | |
| 127 | // Verify the request was removed from pending requests |
| 128 | expect((toolPermissionManager as any).pendingRequests.has(requestId)).toBe( |
| 129 | false, |
| 130 | ); |
| 131 | }); |
| 132 | |
| 133 | it("handles multiple tool calls correctly when first is rejected", () => { |
| 134 | // Test the bug fix: when multiple tool calls are present and the first is rejected, |
| 135 | // remaining tool calls should be marked as cancelled to maintain chat history consistency |
| 136 | |
| 137 | const mockMultipleToolCalls = [ |
| 138 | { id: "call_1", name: "Edit", arguments: {} }, |
| 139 | { id: "call_2", name: "Write", arguments: {} }, |
| 140 | { id: "call_3", name: "Read", arguments: {} }, |
| 141 | ]; |
| 142 | |
| 143 | const mockCallbacks = { |
| 144 | onToolResult: vi.fn(), |
| 145 | }; |
| 146 | |
| 147 | // Simulate the rejection handling logic |
| 148 | const deniedMessage = "Permission denied by user"; |
| 149 | const rejectedToolCall = mockMultipleToolCalls[0]; |
| 150 | |
| 151 | // First tool call gets denied |
| 152 | mockCallbacks.onToolResult(deniedMessage, rejectedToolCall.name, "errored"); |
| 153 | |
| 154 | // Remaining tool calls should be cancelled |
| 155 | for (let i = 1; i < mockMultipleToolCalls.length; i++) { |
| 156 | const remainingToolCall = mockMultipleToolCalls[i]; |
| 157 | const cancelledMessage = "Cancelled due to previous tool rejection"; |
| 158 | mockCallbacks.onToolResult( |
| 159 | cancelledMessage, |
| 160 | remainingToolCall.name, |
| 161 | "canceled", |
| 162 | ); |
| 163 | } |
| 164 | |
| 165 | // Verify all tool calls got results |
| 166 | expect(mockCallbacks.onToolResult).toHaveBeenCalledTimes(3); |
| 167 | expect(mockCallbacks.onToolResult).toHaveBeenNthCalledWith( |
| 168 | 1, |
| 169 | "Permission denied by user", |
| 170 | "Edit", |
| 171 | "errored", |
| 172 | ); |
| 173 | expect(mockCallbacks.onToolResult).toHaveBeenNthCalledWith( |
| 174 | 2, |
| 175 | "Cancelled due to previous tool rejection", |
| 176 | "Write", |
| 177 | "canceled", |
| 178 | ); |
| 179 | expect(mockCallbacks.onToolResult).toHaveBeenNthCalledWith( |
| 180 | 3, |
| 181 | "Cancelled due to previous tool rejection", |
| 182 | "Read", |
| 183 | "canceled", |
| 184 | ); |
| 185 | }); |
| 186 | |
| 187 | it("ensures proper response content in headless mode", () => { |
| 188 | // Test the bug fix: ensure finalResponse fallback works properly in headless mode |
| 189 | |
| 190 | const mockStreamingBehavior = ( |
| 191 | isHeadless: boolean, |
| 192 | finalResponse: string, |
| 193 | content: string, |
| 194 | fullResponse: string, |
| 195 | ) => { |
| 196 | // Simulate the fixed return logic |
| 197 | const responseToReturn = isHeadless |
| 198 | ? finalResponse || content |
| 199 | : fullResponse; |
| 200 | return responseToReturn; |
| 201 | }; |
| 202 | |
| 203 | // Test headless mode with initialized finalResponse |
| 204 | expect( |
| 205 | mockStreamingBehavior( |
| 206 | true, |
| 207 | "final content", |
| 208 | "current content", |
| 209 | "full content", |
| 210 | ), |
| 211 | ).toBe("final content"); |
| 212 | |
| 213 | // Test headless mode with uninitialized finalResponse (empty string) |
| 214 | expect( |
| 215 | mockStreamingBehavior(true, "", "current content", "full content"), |
| 216 | ).toBe("current content"); |
| 217 | |
| 218 | // Test non-headless mode |
| 219 | expect( |
| 220 | mockStreamingBehavior( |
| 221 | false, |
| 222 | "final content", |
| 223 | "current content", |
| 224 | "full content", |
| 225 | ), |
| 226 | ).toBe("full content"); |
| 227 | }); |
| 228 | }); |