Merge pull request #212 from continuedev/nate/tell-cn-what-to-do

Add stopStream parameter to tool permission rejection with stream cancellation
This commit is contained in:
Nate Sesti 2025-08-14 11:25:10 -07:00 • committed by GitHub
commit 2cc71c8064
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 427 additions and 24 deletions

View file

@ -343,4 +343,56 @@ describe("ToolPermissionService", () => {
]);
});
});
describe("reloadPermissions", () => {
test("should reload permissions from files in normal mode", async () => {
const mockPolicies = [
{ tool: "Edit", permission: "allow" as const },
{ tool: "Write", permission: "ask" as const },
];
// Mock the precedence resolver to return fresh policies
vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue(mockPolicies);
const service = new ToolPermissionService();
service.initializeSync({ mode: "normal" });
// Verify initial state
expect(service.getPermissions().policies).toEqual(mockPolicies);
// Simulate new policies being added to the file
const newMockPolicies = [
...mockPolicies,
{ tool: "Read", permission: "allow" as const },
];
vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue(newMockPolicies);
// Reload permissions
await service.reloadPermissions();
// Verify policies were reloaded
expect(service.getPermissions().policies).toEqual(newMockPolicies);
expect(precedenceResolver.resolvePermissionPrecedence).toHaveBeenCalledWith({
personalSettings: true,
useDefaults: true,
});
});
test("should skip reload in non-normal modes", async () => {
const service = new ToolPermissionService();
service.initializeSync({ mode: "plan" });
const initialPolicies = service.getPermissions().policies;
// Clear the mock call count
vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockClear();
// Try to reload
await service.reloadPermissions();
// Verify no reload happened
expect(service.getPermissions().policies).toEqual(initialPolicies);
expect(precedenceResolver.resolvePermissionPrecedence).not.toHaveBeenCalled();
});
});
});

View file

@ -258,6 +258,55 @@ export class ToolPermissionService extends BaseService<ToolPermissionServiceStat
return this.currentState.isHeadless;
}
/**
* Reload permissions from configuration files
* Useful after policy changes to update the in-memory permissions
*/
async reloadPermissions(): Promise<void> {
// Only reload if we're in normal mode - other modes have absolute overrides
if (this.currentState.currentMode !== "normal") {
logger.debug("Skipping permission reload in non-normal mode");
return;
}
logger.debug("Reloading permissions from configuration files");
// Reload permissions from files
const freshPolicies = resolvePermissionPrecedence({
personalSettings: true, // Enable loading from ~/.continue/permissions.yaml
useDefaults: true,
});
// Generate mode-specific policies (should be empty for normal mode)
const modePolicies = this.generateModePolicies();
// Combine mode policies with freshly loaded user policies
const allPolicies = [...modePolicies, ...freshPolicies];
this.setState({
permissions: { policies: allPolicies },
modePolicyCount: modePolicies.length,
});
logger.debug(
`Reloaded permissions: ${freshPolicies.length} user policies, ${modePolicies.length} mode policies`,
);
// Update the service container with the new state
// Import here to avoid circular dependencies
try {
const { serviceContainer } = await import("./ServiceContainer.js");
const { SERVICE_NAMES } = await import("./types.js");
serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, this.getState());
logger.debug("Updated service container with reloaded permissions");
} catch (error) {
logger.error(
"Failed to update service container after permission reload",
{ error },
);
}
}
/**
* Override isReady to always return true since we initialize synchronously
*/

View file

@ -262,6 +262,7 @@ interface ScreenContentProps {
requestId: string,
approved: boolean,
createPolicy?: boolean,
stopStream?: boolean,
) => void;
handleUserMessage: (message: string) => void;
isWaitingForResponse: boolean;

View file

@ -0,0 +1,165 @@
import { vi, beforeEach, describe, it, expect } from "vitest";
// Mock the services
const mockToolPermissionService = {
reloadPermissions: vi.fn(),
getState: vi.fn(),
getCurrentMode: vi.fn(() => "normal"),
};
const mockServices = {
mode: {
getToolPermissionService: vi.fn(() => mockToolPermissionService),
},
};
vi.mock("../../services/index.js", () => ({
services: mockServices,
}));
// Mock the permission system
vi.mock("../../permissions/policyWriter.js", () => ({
generatePolicyRule: vi.fn(),
addPolicyToYaml: vi.fn(),
}));
describe("Permission Policy Reload Workflow", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("should call reloadPermissions after creating a policy", async () => {
// Mock the policy writer
const { generatePolicyRule, addPolicyToYaml } = await import("../../permissions/policyWriter.js");
vi.mocked(generatePolicyRule).mockReturnValue("tool: Edit\npermission: allow");
vi.mocked(addPolicyToYaml).mockResolvedValue(undefined);
// Test the workflow that should happen in useChat.handleToolPermissionResponse
const mockActiveRequest = {
toolName: "Edit",
toolArgs: { file_path: "test.txt" },
};
const approved = true;
const createPolicy = true;
// Simulate the policy creation flow from useChat
if (approved && createPolicy && mockActiveRequest) {
try {
const { generatePolicyRule, addPolicyToYaml } = await import(
"../../permissions/policyWriter.js"
);
const { services } = await import("../../services/index.js");
const policyRule = generatePolicyRule(
mockActiveRequest.toolName,
mockActiveRequest.toolArgs,
);
await addPolicyToYaml(policyRule);
// This is the key part we're testing - reload should be called
await services.mode.getToolPermissionService().reloadPermissions();
} catch (error) {
// Handle errors gracefully
}
}
// Verify the complete workflow executed
expect(generatePolicyRule).toHaveBeenCalledWith("Edit", { file_path: "test.txt" });
expect(addPolicyToYaml).toHaveBeenCalledWith("tool: Edit\npermission: allow");
expect(mockToolPermissionService.reloadPermissions).toHaveBeenCalled();
});
it("should handle permission reload failure gracefully", async () => {
// Mock the policy writer
const { generatePolicyRule, addPolicyToYaml } = await import("../../permissions/policyWriter.js");
vi.mocked(generatePolicyRule).mockReturnValue("tool: Write\npermission: allow");
vi.mocked(addPolicyToYaml).mockResolvedValue(undefined);
// Mock reloadPermissions to fail
mockToolPermissionService.reloadPermissions.mockRejectedValue(new Error("Reload failed"));
const mockActiveRequest = {
toolName: "Write",
toolArgs: { file_path: "test.txt" },
};
const approved = true;
const createPolicy = true;
// Test that error handling works correctly - this should not throw
let errorCaught = false;
try {
const { generatePolicyRule, addPolicyToYaml } = await import(
"../../permissions/policyWriter.js"
);
const { services } = await import("../../services/index.js");
const policyRule = generatePolicyRule(
mockActiveRequest.toolName,
mockActiveRequest.toolArgs,
);
await addPolicyToYaml(policyRule);
// This should fail but not break the flow
await services.mode.getToolPermissionService().reloadPermissions();
} catch (error) {
// Error should be caught and handled gracefully
errorCaught = true;
expect((error as Error).message).toBe("Reload failed");
}
// Verify that despite the reload failure, the policy was still created
expect(addPolicyToYaml).toHaveBeenCalled();
expect(mockToolPermissionService.reloadPermissions).toHaveBeenCalled();
expect(errorCaught).toBe(true);
});
it("verifies the expected improvement: policy takes effect immediately", async () => {
// This test documents what the user should experience
const { generatePolicyRule, addPolicyToYaml } = await import("../../permissions/policyWriter.js");
vi.mocked(generatePolicyRule).mockReturnValue("tool: Edit\npermission: allow");
vi.mocked(addPolicyToYaml).mockResolvedValue(undefined);
// Mock successful reload
mockToolPermissionService.reloadPermissions.mockResolvedValue(undefined);
const mockActiveRequest = {
toolName: "Edit",
toolArgs: { file_path: "test.txt" },
};
// BEFORE: User has to approve tool permission
// Simulate user choosing "Continue + don't ask again"
const approved = true;
const createPolicy = true;
// The workflow should complete successfully
if (approved && createPolicy && mockActiveRequest) {
const { generatePolicyRule, addPolicyToYaml } = await import(
"../../permissions/policyWriter.js"
);
const { services } = await import("../../services/index.js");
const policyRule = generatePolicyRule(
mockActiveRequest.toolName,
mockActiveRequest.toolArgs,
);
await addPolicyToYaml(policyRule);
await services.mode.getToolPermissionService().reloadPermissions();
}
// AFTER: Policy is now active without restart
// Next time user tries to edit a file, it should be automatically allowed
expect(mockToolPermissionService.reloadPermissions).toHaveBeenCalled();
// This represents the improvement: the new policy takes effect immediately
// without requiring the user to restart the Continue CLI
});
});

View file

@ -37,11 +37,12 @@ describe("TUIChat - Stream Stopping on Tool Rejection", () => {
await vi.advanceTimersByTimeAsync(50);
// Verify that the tool was rejected
// Verify that the tool was rejected with stop stream
expect(handleResponse).toHaveBeenCalledWith(
"test-request-123",
false, // approved = false
false // createPolicy = false
false, // createPolicy = false
true // stopStream = true
);
});
@ -67,11 +68,12 @@ describe("TUIChat - Stream Stopping on Tool Rejection", () => {
await vi.advanceTimersByTimeAsync(50);
// Verify rejection
// Verify rejection with stop stream
expect(handleResponse).toHaveBeenCalledWith(
"dangerous-request",
false, // rejected
false
false, // createPolicy = false
true // stopStream = true
);
});

View file

@ -38,10 +38,12 @@ describe("TUIChat - Tool Permission Tests", () => {
expect(frame).toContain("Would you like to continue?");
expect(frame).toContain("Continue");
expect(frame).toContain("Continue + don't ask again");
expect(frame).toContain("Cancel");
expect(frame).toContain("No, and tell Continue what to do differently");
expect(frame).toContain("(tab)");
expect(frame).toContain("(shift+tab)");
expect(frame).toContain("(esc)");
// Verify old Cancel option is not shown
expect(frame).not.toContain("Cancel");
});
it("handles keyboard shortcuts for permission approval and rejection", async () => {
@ -69,6 +71,7 @@ describe("TUIChat - Tool Permission Tests", () => {
expect(handleResponse).toHaveBeenCalledWith(
"test-request-123",
true,
false,
false
);
});
@ -97,7 +100,8 @@ describe("TUIChat - Tool Permission Tests", () => {
expect(handleResponse).toHaveBeenCalledWith(
"test-request-456",
false,
false
false,
true
);
});
@ -125,7 +129,8 @@ describe("TUIChat - Tool Permission Tests", () => {
expect(handleResponse).toHaveBeenCalledWith(
"test-request-789",
false,
false
false,
true
);
});
@ -156,6 +161,7 @@ describe("TUIChat - Tool Permission Tests", () => {
expect(handleResponse).toHaveBeenCalledWith(
"test-request-123",
true,
undefined,
undefined
);
});
@ -185,7 +191,103 @@ describe("TUIChat - Tool Permission Tests", () => {
expect(handleResponse).toHaveBeenCalledWith(
"test-request-policy",
true,
true
true,
false
);
});
it("shows the new 'No, and tell Continue what to do differently' option in the UI", async () => {
const handleResponse = vi.fn();
const { lastFrame } = render(
<ToolPermissionSelector
toolName="Edit"
toolArgs={{
file_path: "/path/to/test.txt",
old_string: "old content",
new_string: "new content",
}}
requestId="test-request-stop"
onResponse={handleResponse}
/>
);
await vi.advanceTimersByTimeAsync(50);
// Verify the new option exists in the rendered output
const frame = lastFrame();
expect(frame).toContain("No, and tell Continue what to do differently");
// Verify all 3 options are present
expect(frame).toContain("Continue");
expect(frame).toContain("Continue + don't ask again");
expect(frame).toContain("No, and tell Continue what to do differently");
// Verify old Cancel option is not shown
expect(frame).not.toContain("Cancel");
});
it("triggers stop stream when escape key is pressed", async () => {
// This test ensures the actual ToolPermissionSelector component correctly handles the escape key
const handleResponse = vi.fn();
const { stdin } = render(
<ToolPermissionSelector
toolName="Edit"
toolArgs={{
file_path: "/path/to/test.txt",
old_string: "old content",
new_string: "new content",
}}
requestId="test-request-escape"
onResponse={handleResponse}
/>
);
await vi.advanceTimersByTimeAsync(50);
// Press escape key to trigger the "No, and tell Continue what to do differently" option
stdin.write("\x1b"); // ESC key
await vi.advanceTimersByTimeAsync(50);
// Verify the escape key triggers the stopStream behavior
expect(handleResponse).toHaveBeenCalledWith(
"test-request-escape",
false, // approved = false (rejection)
false, // createPolicy = false
true // stopStream = true (this is the new behavior)
);
});
it("triggers stop stream when 'n' key is pressed", async () => {
// This test ensures the 'n' key also triggers the new stop stream behavior
const handleResponse = vi.fn();
const { stdin } = render(
<ToolPermissionSelector
toolName="Write"
toolArgs={{
file_path: "/path/to/new-file.txt",
content: "New content",
}}
requestId="test-request-n-key"
onResponse={handleResponse}
/>
);
await vi.advanceTimersByTimeAsync(50);
// Press 'n' key to trigger the "No, and tell Continue what to do differently" option
stdin.write("n");
await vi.advanceTimersByTimeAsync(50);
// Verify the 'n' key triggers the stopStream behavior
expect(handleResponse).toHaveBeenCalledWith(
"test-request-n-key",
false, // approved = false (rejection)
false, // createPolicy = false
true // stopStream = true (this is the new behavior)
);
});

View file

@ -12,6 +12,7 @@ interface PermissionOption {
color: string;
approved: boolean;
createPolicy?: boolean;
stopStream?: boolean;
}
interface ToolPermissionSelectorProps {
@ -23,6 +24,7 @@ interface ToolPermissionSelectorProps {
requestId: string,
approved: boolean,
createPolicy?: boolean,
stopStream?: boolean,
) => void;
}
@ -35,7 +37,13 @@ const PERMISSION_OPTIONS: PermissionOption[] = [
approved: true,
createPolicy: true,
},
{ id: "deny", name: "Cancel", color: "red", approved: false },
{
id: "deny_stop",
name: "No, and tell Continue what to do differently",
color: "yellow",
approved: false,
stopStream: true,
},
];
export const ToolPermissionSelector: React.FC<ToolPermissionSelectorProps> = ({
@ -54,25 +62,26 @@ export const ToolPermissionSelector: React.FC<ToolPermissionSelectorProps> = ({
requestId,
selectedOption.approved,
selectedOption.createPolicy,
selectedOption.stopStream,
);
return;
}
// Tab to continue (approve)
if (key.tab && !key.shift) {
onResponse(requestId, true, false);
onResponse(requestId, true, false, false);
return;
}
// Shift+Tab to continue with policy creation
if (key.tab && key.shift) {
onResponse(requestId, true, true);
onResponse(requestId, true, true, false);
return;
}
// Escape to reject (deny)
// Escape to reject with stop stream
if (key.escape) {
onResponse(requestId, false, false);
onResponse(requestId, false, false, true);
return;
}
@ -86,9 +95,9 @@ export const ToolPermissionSelector: React.FC<ToolPermissionSelectorProps> = ({
// Also support y/n for quick responses
if (input === "y" || input === "Y") {
onResponse(requestId, true, false);
onResponse(requestId, true, false, false);
} else if (input === "n" || input === "N") {
onResponse(requestId, false, false);
onResponse(requestId, false, false, true);
}
});
@ -121,7 +130,7 @@ export const ToolPermissionSelector: React.FC<ToolPermissionSelectorProps> = ({
let shortcut = "";
if (option.id === "approve") shortcut = "(tab)";
else if (option.id === "approve_policy") shortcut = "(shift+tab)";
else if (option.id === "deny") shortcut = "(esc)";
else if (option.id === "deny_stop") shortcut = "(esc)";
return (
<Box key={option.id} marginTop={index === 0 ? 1 : 0}>

View file

@ -4,6 +4,7 @@ import { useEffect, useState } from "react";
import { findCompactionIndex } from "../../compaction.js";
import { toolPermissionManager } from "../../permissions/permissionManager.js";
import { services } from "../../services/index.js";
import { loadSession, saveSession } from "../../session.js";
import { handleSlashCommands } from "../../slashCommands.js";
import { telemetryService } from "../../telemetry/telemetryService.js";
@ -12,13 +13,13 @@ import { logger } from "../../util/logger.js";
import { DisplayMessage } from "../types.js";
import {
formatMessageWithFiles,
handleAutoCompaction,
handleCompactCommand,
handleSpecialCommands,
initChatHistory,
processSlashCommandResult,
trackUserMessage,
handleAutoCompaction,
formatMessageWithFiles,
handleSpecialCommands,
} from "./useChat.helpers.js";
import {
handleRemoteMessage,
@ -29,9 +30,9 @@ import {
executeStreaming,
} from "./useChat.stream.helpers.js";
import {
UseChatProps,
AttachedFile,
ActivePermissionRequest,
AttachedFile,
UseChatProps,
} from "./useChat.types.js";
export function useChat({
@ -367,6 +368,7 @@ export function useChat({
requestId: string,
approved: boolean,
createPolicy?: boolean,
stopStream?: boolean,
) => {
// Capture the current permission request before clearing it
const currentRequest = activePermissionRequest;
@ -387,11 +389,15 @@ export function useChat({
);
await addPolicyToYaml(policyRule);
logger.debug(`Policy created: ${policyRule}`);
// Reload permissions to pick up the new policy without requiring restart
await services.mode.getToolPermissionService().reloadPermissions();
} catch (error) {
logger.error("Failed to create policy", { error });
// Continue with the approval even if policy creation fails
logger.error("Failed to create policy or reload permissions", {
error,
});
// Continue with the approval even if policy creation/reload fails
}
}
@ -402,6 +408,23 @@ export function useChat({
toolPermissionManager.approveRequest(requestId);
} else {
toolPermissionManager.rejectRequest(requestId);
// If this is a "stop stream" rejection, abort the current request
if (stopStream && abortController && isWaitingForResponse) {
abortController.abort();
setMessages((prev) => [
...prev,
{
role: "system",
content:
"[Tool canceled - please tell Continue what to do differently]",
messageType: "system" as const,
},
]);
setIsWaitingForResponse(false);
setResponseStartTime(null);
setInputMode(true);
}
}
};