Merge pull request #6176 from continuedev/tomasz/on-off-rules

Manually triggering rules on and off
This commit is contained in:
Tomasz Stefaniak 2025-06-20 12:41:40 -07:00 • committed by GitHub
commit e34d43fcd8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
9 changed files with 259 additions and 46 deletions

View file

@ -11,6 +11,7 @@ import { findLast } from "../util/findLast";
import { normalizeToMessageParts } from "../util/messageContent";
import { isUserOrToolMsg } from "./messages";
import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules";
import { RulePolicies } from "./rules/types";
export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL =
"https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts";
@ -108,6 +109,7 @@ export function constructMessages(
history: ChatHistoryItem[],
baseChatOrAgentSystemMessage: string | undefined,
rules: RuleWithSource[],
rulePolicies?: RulePolicies,
): ChatMessage[] {
const filteredHistory = history.filter(
(item) => item.message.role !== "system",
@ -164,6 +166,7 @@ export function constructMessages(
rules,
userMessage: lastUserMsg,
contextItems: lastUserContextItems,
rulePolicies,
});
if (systemMessage.trim()) {

View file

@ -6,6 +6,7 @@ import {
UserChatMessage,
} from "../..";
import { getApplicableRules } from "./getSystemMessageWithRules";
import { RulePolicies } from "./types";
describe("Rule application with alwaysApply", () => {
// Create an always-apply rule
@ -136,4 +137,38 @@ describe("Rule application with alwaysApply", () => {
expect(applicableRules).toHaveLength(1);
expect(applicableRules.map((r) => r.name)).toContain("Always Apply Rule");
});
it("should respect 'off' rulePolicies over alwaysApply when there are no file paths", () => {
// Rule with alwaysApply: true
const globalRule: RuleWithSource = {
name: "Global Rule",
rule: "This rule has alwaysApply: true but is blocked by rulePolicies",
alwaysApply: true,
source: "rules-block",
ruleFile: "src/some/path.md",
};
// Message with no code blocks or file references
const simpleMessage: UserChatMessage = {
role: "user",
content: "Can you help me with something?",
};
// Create a rule policy that blocks the rule
const rulePolicies: RulePolicies = {
"Global Rule": "off",
};
// The rule should NOT be applied due to the "off" policy,
// even though it has alwaysApply: true and there are no file paths
const applicableRules = getApplicableRules(
simpleMessage,
[globalRule],
[],
rulePolicies,
);
expect(applicableRules).toHaveLength(0);
expect(applicableRules.map((r) => r.name)).not.toContain("Global Rule");
});
});

View file

@ -8,6 +8,7 @@ import {
import { renderChatMessage } from "../../util/messageContent";
import { getCleanUriPath } from "../../util/uri";
import { extractPathsFromCodeBlocks } from "../utils/extractPathsFromCodeBlocks";
import { RulePolicies } from "./types";
/**
* Checks if a path matches any of the provided globs
@ -120,13 +121,21 @@ const isGlobalRule = (rule: RuleWithSource): boolean => {
export const shouldApplyRule = (
rule: RuleWithSource,
filePaths: string[],
rulePolicies: RulePolicies = {},
): boolean => {
const policy = rulePolicies[rule.name || ""];
// Never apply if policy is "off"
if (policy === "off") {
return false;
}
// If it's a global rule, always apply it regardless of file paths
if (isGlobalRule(rule)) {
return true;
}
// If there are no file paths to check:
// If there are no file paths to check and we've made it here:
// - We've already handled global rules above
// - Don't apply other rules since we have no files to match against
if (filePaths.length === 0) {
@ -196,11 +205,9 @@ export const getApplicableRules = (
userMessage: UserChatMessage | ToolResultChatMessage | undefined,
rules: RuleWithSource[],
contextItems: ContextItemWithId[],
rulePolicies: RulePolicies = {},
): RuleWithSource[] => {
// First, extract any global rules that should always apply
const globalRules = rules.filter((rule) => isGlobalRule(rule));
// Get file paths from message and context for regular rule matching
// Get file paths from message and context for rule matching
const filePathsFromMessage = userMessage
? extractPathsFromCodeBlocks(renderChatMessage(userMessage))
: [];
@ -213,41 +220,34 @@ export const getApplicableRules = (
// Combine file paths from both sources
const allFilePaths = [...filePathsFromMessage, ...filePathsFromContextItems];
// If we have no file paths, just return the global rules
if (allFilePaths.length === 0) {
return globalRules;
}
// Apply shouldApplyRule to all rules - this will handle global rules, rule policies,
// and path matching in a consistent way
const applicableRules = rules.filter((rule) =>
shouldApplyRule(rule, allFilePaths, rulePolicies),
);
// Get rules that match file paths
const matchingRules = rules
.filter((rule) => !isGlobalRule(rule)) // Skip global rules as we've already handled them
.filter((rule) => shouldApplyRule(rule, allFilePaths));
// Combine global rules with matching rules, ensuring no duplicates
return [...globalRules, ...matchingRules];
return applicableRules;
};
/**
* Creates a system message string with applicable rules appended
*
* @param baseSystemMessage - The base system message to start with
* @param userMessage - The user message to check for file paths
* @param rules - The list of rules to filter
* @param contextItems - Context items to check for file paths
* @returns System message with applicable rules appended
*/
export const getSystemMessageWithRules = ({
baseSystemMessage,
userMessage,
rules,
contextItems,
rulePolicies = {},
}: {
baseSystemMessage?: string;
userMessage: UserChatMessage | ToolResultChatMessage | undefined;
rules: RuleWithSource[];
contextItems: ContextItemWithId[];
rulePolicies?: RulePolicies;
}) => {
const applicableRules = getApplicableRules(userMessage, rules, contextItems);
const applicableRules = getApplicableRules(
userMessage,
rules,
contextItems,
rulePolicies,
);
let systemMessage = baseSystemMessage ?? "";
for (const rule of applicableRules) {

View file

@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import { RuleWithSource } from "../..";
import { shouldApplyRule } from "./getSystemMessageWithRules";
import { RulePolicies } from "./types";
describe("Rule colocation glob matching", () => {
// This test file demonstrates the expected behavior after our fix
@ -132,3 +133,114 @@ describe("Rule colocation glob matching", () => {
);
});
});
describe("Rule policies", () => {
const componentRule: RuleWithSource = {
name: "Components Rule",
rule: "Use functional components with hooks",
source: "rules-block",
ruleFile: "src/components/rules.md",
};
const testFiles = ["src/components/Button.tsx"];
const nonMatchingFiles = ["src/utils/helpers.ts"];
it("should never apply rules with 'off' policy regardless of file paths", () => {
const rulePolicies: RulePolicies = {
"Components Rule": "off",
};
// Should not apply even to matching files
expect(shouldApplyRule(componentRule, testFiles, rulePolicies)).toBe(false);
// Rule with alwaysApply: true should still be overridden by 'off' policy
const alwaysApplyRule: RuleWithSource = {
name: "Always Apply Rule",
rule: "This rule would normally always apply",
alwaysApply: true,
source: "rules-block",
ruleFile: "src/components/rules.md",
};
const offPolicies: RulePolicies = {
"Always Apply Rule": "off",
};
expect(shouldApplyRule(alwaysApplyRule, testFiles, offPolicies)).toBe(
false,
);
});
it("should apply 'on' policy rules based on normal matching logic", () => {
const rulePolicies: RulePolicies = {
"Components Rule": "on",
};
// Should apply to matching files
expect(shouldApplyRule(componentRule, testFiles, rulePolicies)).toBe(true);
// Should not apply to non-matching files
expect(shouldApplyRule(componentRule, nonMatchingFiles, rulePolicies)).toBe(
false,
);
});
it("should use default behavior when no policy is specified", () => {
// Empty policies object should use default behavior
const rulePolicies: RulePolicies = {};
// Should apply to matching files
expect(shouldApplyRule(componentRule, testFiles, rulePolicies)).toBe(true);
// Should not apply to non-matching files
expect(shouldApplyRule(componentRule, nonMatchingFiles, rulePolicies)).toBe(
false,
);
});
it("should handle policy interaction with global rules", () => {
// Root level rule which would normally apply globally
const rootRule: RuleWithSource = {
name: "Root Rule",
rule: "Follow project standards",
source: "rules-block",
ruleFile: ".continue/rules.md",
};
// Off policy should override even global rules
const offPolicies: RulePolicies = {
"Root Rule": "off",
};
expect(shouldApplyRule(rootRule, testFiles, offPolicies)).toBe(false);
// On policy should maintain global rule behavior
const onPolicies: RulePolicies = {
"Root Rule": "on",
};
expect(shouldApplyRule(rootRule, testFiles, onPolicies)).toBe(true);
});
it("should prioritize 'off' policy over alwaysApply and directory restrictions", () => {
// Create rule with multiple matching criteria
const complexRule: RuleWithSource = {
name: "Complex Rule",
rule: "This rule has complex matching logic",
alwaysApply: true,
globs: "**/*.ts",
source: "rules-block",
ruleFile: "src/utils/rules.md",
};
// Off policy should win over everything
const offPolicies: RulePolicies = {
"Complex Rule": "off",
};
// Even with matching files and alwaysApply: true, off policy wins
expect(
shouldApplyRule(complexRule, ["src/utils/test.ts"], offPolicies),
).toBe(false);
});
});

2
core/llm/rules/types.ts Normal file
View file

@ -0,0 +1,2 @@
export type RulePolicy = "on" | "off";
export type RulePolicies = { [ruleName: string]: RulePolicy };

View file

@ -16,10 +16,13 @@ import { useAuth } from "../../../../context/Auth";
import { IdeMessengerContext } from "../../../../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../../../../redux/hooks";
import {
DEFAULT_RULE_SETTING,
setDialogMessage,
setShowDialog,
toggleRuleSetting,
} from "../../../../redux/slices/uiSlice";
import HeaderButtonWithToolTip from "../../../gui/HeaderButtonWithToolTip";
import Switch from "../../../gui/Switch";
import { useFontSize } from "../../../ui/font";
import { ExploreBlocksButton } from "./ExploreBlocksButton";
@ -31,6 +34,13 @@ const RuleCard: React.FC<RuleCardProps> = ({ rule }) => {
const dispatch = useAppDispatch();
const ideMessenger = useContext(IdeMessengerContext);
const mode = useAppSelector((store) => store.session.mode);
const policy = useAppSelector((state) =>
rule.name
? state.ui.ruleSettings[rule.name] || DEFAULT_RULE_SETTING
: undefined,
);
const isDisabled = policy === "off";
const handleOpen = async () => {
if (rule.slug) {
@ -53,6 +63,12 @@ const RuleCard: React.FC<RuleCardProps> = ({ rule }) => {
}
};
const handleTogglePolicy = () => {
if (rule.name) {
dispatch(toggleRuleSetting(rule.name));
}
};
const title = useMemo(() => {
if (rule.name) {
return rule.name;
@ -90,31 +106,45 @@ const RuleCard: React.FC<RuleCardProps> = ({ rule }) => {
const smallFont = useFontSize(-2);
const tinyFont = useFontSize(-3);
return (
<div className="border-border flex flex-col rounded-sm px-2 py-1.5 transition-colors">
<div
className={`border-border flex flex-col rounded-sm px-2 py-1.5 transition-colors ${isDisabled ? "opacity-50" : ""}`}
>
<div className="flex flex-col">
<div className="flex flex-row justify-between gap-1">
<span
className="text-vsc-foreground line-clamp-2"
className={`line-clamp-2 ${isDisabled ? "text-gray-400" : "text-vsc-foreground"}`}
style={{
fontSize: smallFont,
}}
>
{title}
</span>
<div className="flex flex-row items-start gap-1">
<HeaderButtonWithToolTip onClick={onClickExpand} text="Expand">
<ArrowsPointingOutIcon className="h-3 w-3 text-gray-400" />
</HeaderButtonWithToolTip>{" "}
{rule.source === "default-chat" ||
rule.source === "default-agent" ? (
<HeaderButtonWithToolTip onClick={handleOpen} text="View">
<EyeIcon className="h-3 w-3 text-gray-400" />
</HeaderButtonWithToolTip>
) : (
<HeaderButtonWithToolTip onClick={handleOpen} text="Edit">
<PencilIcon className="h-3 w-3 text-gray-400" />
</HeaderButtonWithToolTip>
<div className="flex flex-row items-center gap-2">
{rule.name && policy && (
<div className="flex cursor-pointer flex-row items-center justify-end gap-1 px-2 py-0.5">
<Switch
isToggled={policy === "on"}
onToggle={() => handleTogglePolicy()}
size={10}
text=""
/>
</div>
)}
<div className="flex flex-row items-start gap-1">
<HeaderButtonWithToolTip onClick={onClickExpand} text="Expand">
<ArrowsPointingOutIcon className="h-3 w-3 text-gray-400" />
</HeaderButtonWithToolTip>{" "}
{rule.source === "default-chat" ||
rule.source === "default-agent" ? (
<HeaderButtonWithToolTip onClick={handleOpen} text="View">
<EyeIcon className="h-3 w-3 text-gray-400" />
</HeaderButtonWithToolTip>
) : (
<HeaderButtonWithToolTip onClick={handleOpen} text="Edit">
<PencilIcon className="h-3 w-3 text-gray-400" />
</HeaderButtonWithToolTip>
)}
</div>
</div>
</div>
@ -122,7 +152,7 @@ const RuleCard: React.FC<RuleCardProps> = ({ rule }) => {
style={{
fontSize: tinyFont,
}}
className="mt-1 line-clamp-3 text-gray-400"
className={`mt-1 line-clamp-3 ${isDisabled ? "text-gray-500" : "text-gray-400"}`}
>
{rule.rule}
</span>
@ -134,7 +164,9 @@ const RuleCard: React.FC<RuleCardProps> = ({ rule }) => {
className="mt-1.5 flex flex-col gap-1"
>
<span className="italic">Applies to files</span>
<code className="line-clamp-1 px-1 py-0.5 text-gray-400">
<code
className={`line-clamp-1 px-1 py-0.5 ${isDisabled ? "text-gray-500" : "text-gray-400"}`}
>
{rule.globs}
</code>
</div>
@ -146,7 +178,6 @@ const RuleCard: React.FC<RuleCardProps> = ({ rule }) => {
export function RulesSection() {
const { selectedProfile } = useAuth();
const config = useAppSelector((store) => store.config.config);
const mode = useAppSelector((store) => store.session.mode);
const sortedRules: RuleWithSource[] = useMemo(() => {

View file

@ -1,5 +1,5 @@
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { Tool } from "core";
import { RuleWithSource, Tool } from "core";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "core/tools/builtIn";
import {
defaultOnboardingCardState,
@ -12,9 +12,12 @@ export type ToolPolicy =
| "allowedWithoutPermission"
| "disabled";
export type RulePolicy = "on" | "off";
export type ToolGroupPolicy = "include" | "exclude";
export type ToolPolicies = { [toolName: string]: ToolPolicy };
export type RulePolicies = { [ruleName: string]: RulePolicy };
export type ToolGroupPolicies = { [toolGroupName: string]: ToolGroupPolicy };
type UIState = {
@ -27,10 +30,12 @@ type UIState = {
shouldAddFileForEditing: boolean;
toolSettings: ToolPolicies;
toolGroupSettings: ToolGroupPolicies;
ruleSettings: RulePolicies;
ttsActive: boolean;
};
export const DEFAULT_TOOL_SETTING: ToolPolicy = "allowedWithPermission";
export const DEFAULT_RULE_SETTING: RulePolicy = "on";
export const uiSlice = createSlice({
name: "ui",
@ -62,6 +67,7 @@ export const uiSlice = createSlice({
toolGroupSettings: {
[BUILT_IN_GROUP_NAME]: "include",
},
ruleSettings: {},
} as UIState,
reducers: {
setOnboardingCard: (
@ -126,6 +132,25 @@ export const uiSlice = createSlice({
state.toolGroupSettings[action.payload] = "include";
}
},
// Rules
addRule: (state, action: PayloadAction<RuleWithSource>) => {
state.ruleSettings[action.payload.name!] = DEFAULT_RULE_SETTING;
},
toggleRuleSetting: (state, action: PayloadAction<string>) => {
const setting = state.ruleSettings[action.payload];
switch (setting) {
case "on":
state.ruleSettings[action.payload] = "off";
break;
case "off":
state.ruleSettings[action.payload] = "on";
break;
default:
state.ruleSettings[action.payload] = DEFAULT_RULE_SETTING;
break;
}
},
setTTSActive: (state, { payload }: PayloadAction<boolean>) => {
state.ttsActive = payload;
},
@ -142,6 +167,8 @@ export const {
toggleToolSetting,
toggleToolGroupSetting,
addTool,
addRule,
toggleRuleSetting,
setTTSActive,
} = uiSlice.actions;

View file

@ -58,7 +58,7 @@ const saveSubsetFilters = [
"codeToEdit",
]),
createFilter("config", ["defaultModelTitle"]),
createFilter("ui", ["toolSettings", "toolGroupSettings"]),
createFilter("ui", ["toolSettings", "toolGroupSettings", "ruleSettings"]),
createFilter("indexing", []),
createFilter("tabs", ["tabs"]),
createFilter("profiles", [

View file

@ -92,6 +92,7 @@ export const streamResponseThunk = createAsyncThunk<
// Determine which rules apply to this message
const userMsg = updatedHistory[inputIndex].message;
const rules = getState().config.config.rules;
const rulePolicies = getState().ui.ruleSettings;
// Calculate applicable rules once
// We need to check the message type to match what getApplicableRules expects
@ -101,6 +102,7 @@ export const streamResponseThunk = createAsyncThunk<
: undefined,
rules,
selectedContextItems,
rulePolicies,
);
// Store in history for UI display
@ -122,6 +124,7 @@ export const streamResponseThunk = createAsyncThunk<
[...updatedHistory],
baseChatOrAgentSystemMessage,
applicableRules,
rulePolicies,
);
posthog.capture("step run", {