Merge pull request #6421 from continuedev/pe/rule-dialog
feat: generate rule dialog
This commit is contained in:
commit
f92253c3f3
26 changed files with 986 additions and 63 deletions
|
|
@ -1,6 +0,0 @@
|
|||
---
|
||||
name: Never use useEffect
|
||||
regex: "useEffect"
|
||||
---
|
||||
|
||||
TELL THE USER IN ALL CAPS THAT YOU REFUSE TO TAKE ANY FURTHER ACTION UNTIL THE `useEffect` IS REMOVED FROM THE CODE. IT IS A BAD PRACTICE AND SHOULD NEVER BE NECESSARY. YOU CAN SUGGEST A FIX TO REMOVE THE `useEffect` AND REPLACE IT WITH SOMETHING ELSE, BUT YOU SHOULD REFUSE TO DO ANY OTHER TASKS BEFORE THAT IS DONE.
|
||||
|
|
@ -77,4 +77,5 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
|
|||
updateApplyState: [ApplyState, void];
|
||||
exitEditMode: [undefined, void];
|
||||
focusEdit: [undefined, void];
|
||||
generateRule: [undefined, void];
|
||||
};
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ export const createRuleBlock: Tool = {
|
|||
function: {
|
||||
name: BuiltInToolNames.CreateRuleBlock,
|
||||
description:
|
||||
'Creates a "rule" that can be referenced in future conversations. This should be used whenever you want to establish code standards / preferences that should be applied consistently, or when you want to avoid making a mistake again. To modify existing rules, use the edit tool instead.',
|
||||
'Creates a "rule" that can be referenced in future conversations. This should be used whenever you want to establish code standards / preferences that should be applied consistently, or when you want to avoid making a mistake again. To modify existing rules, use the edit tool instead.\n\nRule Types:\n- Always: Include only "rule" (always included in model context)\n- Auto Attached: Include "rule", "globs", and/or "regex" (included when files match patterns)\n- Agent Requested: Include "rule" and "description" (AI decides when to apply based on description)\n- Manual: Include only "rule" (only included when explicitly mentioned using @ruleName)',
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["name", "rule", "description"],
|
||||
|
|
@ -30,7 +30,8 @@ export const createRuleBlock: Tool = {
|
|||
},
|
||||
description: {
|
||||
type: "string",
|
||||
description: "Short description of the rule",
|
||||
description:
|
||||
"Description of when this rule should be applied. Required for Agent Requested rules (AI decides when to apply). Optional for other types.",
|
||||
},
|
||||
globs: {
|
||||
type: "string",
|
||||
|
|
@ -42,6 +43,11 @@ export const createRuleBlock: Tool = {
|
|||
description:
|
||||
"Optional regex patterns to match against file content. Rule applies only to files whose content matches the pattern (e.g. 'useEffect' for React hooks or '\\bclass\\b' for class definitions)",
|
||||
},
|
||||
alwaysApply: {
|
||||
type: "boolean",
|
||||
description:
|
||||
"Whether this rule should always be applied. Set to false for Agent Requested and Manual rules. Omit or set to true for Always and Auto Attached rules.",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
|
|
|||
|
|
@ -36,6 +36,7 @@ test("createRuleBlockImpl should create a rule with glob pattern", async () => {
|
|||
const { frontmatter, markdown } = parseMarkdownRule(fileContent);
|
||||
|
||||
expect(frontmatter).toEqual({
|
||||
alwaysApply: true,
|
||||
description: "Always use interfaces",
|
||||
globs: "**/*.{ts,tsx}",
|
||||
});
|
||||
|
|
@ -72,6 +73,7 @@ test("createRuleBlockImpl should create a rule with description pattern", async
|
|||
const { frontmatter, markdown } = parseMarkdownRule(fileContent);
|
||||
|
||||
expect(frontmatter).toEqual({
|
||||
alwaysApply: true,
|
||||
description: "This is a detailed explanation of the rule",
|
||||
});
|
||||
|
||||
|
|
@ -94,6 +96,7 @@ test("createRuleBlockImpl should include both globs and description in frontmatt
|
|||
const { frontmatter, markdown } = parseMarkdownRule(fileContent);
|
||||
|
||||
expect(frontmatter).toEqual({
|
||||
alwaysApply: false,
|
||||
description: "This rule enforces our team standards",
|
||||
globs: "**/*.js",
|
||||
});
|
||||
|
|
@ -116,6 +119,7 @@ test("createRuleBlockImpl should create a rule with alwaysApply set to false", a
|
|||
const { frontmatter } = parseMarkdownRule(fileContent);
|
||||
|
||||
expect(frontmatter).toEqual({
|
||||
alwaysApply: false,
|
||||
description: "Optional rule",
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -5,29 +5,18 @@ import { createRuleFilePath } from "../../config/markdown/utils";
|
|||
|
||||
export type CreateRuleBlockArgs = Pick<
|
||||
Required<RuleWithSource>,
|
||||
"rule" | "description" | "alwaysApply" | "name"
|
||||
"rule" | "name"
|
||||
> &
|
||||
Pick<RuleWithSource, "globs" | "regex">;
|
||||
Pick<RuleWithSource, "globs" | "regex" | "description" | "alwaysApply">;
|
||||
|
||||
export const createRuleBlockImpl: ToolImpl = async (
|
||||
args: CreateRuleBlockArgs,
|
||||
{ name, rule, ...otherArgs }: CreateRuleBlockArgs,
|
||||
extras,
|
||||
) => {
|
||||
// Create options object with the fields that createRuleMarkdown expects
|
||||
const options: any = {
|
||||
description: args.description,
|
||||
globs: args.globs,
|
||||
};
|
||||
|
||||
// Add regex if provided
|
||||
if (args.regex) {
|
||||
options.regex = args.regex;
|
||||
}
|
||||
|
||||
const fileContent = createRuleMarkdown(args.name, args.rule, options);
|
||||
const fileContent = createRuleMarkdown(name, rule, otherArgs);
|
||||
|
||||
const [localContinueDir] = await extras.ide.getWorkspaceDirs();
|
||||
const ruleFilePath = createRuleFilePath(localContinueDir, args.name);
|
||||
const ruleFilePath = createRuleFilePath(localContinueDir, name);
|
||||
|
||||
await extras.ide.writeFile(ruleFilePath, fileContent);
|
||||
await extras.ide.openFile(ruleFilePath);
|
||||
|
|
@ -35,7 +24,7 @@ export const createRuleBlockImpl: ToolImpl = async (
|
|||
return [
|
||||
{
|
||||
name: "New Rule Block",
|
||||
description: args.description || "",
|
||||
description: otherArgs.description || "",
|
||||
uri: {
|
||||
type: "file",
|
||||
value: ruleFilePath,
|
||||
|
|
|
|||
|
|
@ -349,6 +349,12 @@
|
|||
"command": "continue.forceNextEdit",
|
||||
"category": "Continue",
|
||||
"title": "Continue: Force Next Edit"
|
||||
},
|
||||
{
|
||||
"command": "continue.generateRule",
|
||||
"category": "Continue",
|
||||
"title": "Generate Rule",
|
||||
"group": "Continue"
|
||||
}
|
||||
],
|
||||
"keybindings": [
|
||||
|
|
@ -478,6 +484,9 @@
|
|||
},
|
||||
{
|
||||
"command": "continue.enterEnterpriseLicenseKey"
|
||||
},
|
||||
{
|
||||
"command": "continue.generateRule"
|
||||
}
|
||||
],
|
||||
"editor/context": [
|
||||
|
|
|
|||
|
|
@ -341,6 +341,11 @@ const getCommandsMap: (
|
|||
editDecorationManager.clear();
|
||||
void sidebar.webviewProtocol?.request("exitEditMode", undefined);
|
||||
},
|
||||
"continue.generateRule": async () => {
|
||||
captureCommandTelemetry("generateRule");
|
||||
focusGUI();
|
||||
void sidebar.webviewProtocol?.request("generateRule", undefined);
|
||||
},
|
||||
"continue.writeCommentsForCode": async () => {
|
||||
captureCommandTelemetry("writeCommentsForCode");
|
||||
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ export interface FeedbackButtonsProps {
|
|||
item: ChatHistoryItem;
|
||||
}
|
||||
|
||||
export default function FeedbackButtons({ item }: FeedbackButtonsProps) {
|
||||
export function FeedbackButtons({ item }: FeedbackButtonsProps) {
|
||||
const [feedback, setFeedback] = useState<boolean | undefined>(undefined);
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const sessionId = useAppSelector((store) => store.session.id);
|
||||
|
|
@ -41,7 +41,7 @@ export default function FeedbackButtons({ item }: FeedbackButtonsProps) {
|
|||
onClick={() => sendFeedback(true)}
|
||||
>
|
||||
<HandThumbUpIcon
|
||||
className={`mx-0.5 h-3.5 w-3.5 ${feedback === true ? "text-green-400" : "text-gray-500"}`}
|
||||
className={`mx-0.5 h-3.5 w-3.5 ${feedback === true ? "text-success" : "text-description-muted"}`}
|
||||
/>
|
||||
</HeaderButtonWithToolTip>
|
||||
<HeaderButtonWithToolTip
|
||||
|
|
@ -50,7 +50,7 @@ export default function FeedbackButtons({ item }: FeedbackButtonsProps) {
|
|||
onClick={() => sendFeedback(false)}
|
||||
>
|
||||
<HandThumbDownIcon
|
||||
className={`h-3.5 w-3.5 ${feedback === false ? "text-red-400" : "text-gray-500"}`}
|
||||
className={`h-3.5 w-3.5 ${feedback === false ? "text-error" : "text-description-muted"}`}
|
||||
/>
|
||||
</HeaderButtonWithToolTip>
|
||||
</>
|
||||
|
|
|
|||
300
gui/src/components/GenerateRuleDialog/GenerationScreen.tsx
Normal file
300
gui/src/components/GenerateRuleDialog/GenerationScreen.tsx
Normal file
|
|
@ -0,0 +1,300 @@
|
|||
import {
|
||||
createRuleMarkdown,
|
||||
getRuleType,
|
||||
RuleType,
|
||||
RuleTypeDescriptions,
|
||||
} from "@continuedev/config-yaml";
|
||||
import { InformationCircleIcon } from "@heroicons/react/24/outline";
|
||||
import { createRuleFilePath } from "core/config/markdown/utils";
|
||||
import { CreateRuleBlockArgs } from "core/tools/implementations/createRuleBlock";
|
||||
import { useContext, useEffect, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { IdeMessengerContext } from "../../context/IdeMessenger";
|
||||
import Spinner from "../gui/Spinner";
|
||||
import { ToolTip } from "../gui/Tooltip";
|
||||
import { Button } from "../ui";
|
||||
import { useRuleGeneration } from "./useRuleGeneration";
|
||||
|
||||
interface GenerationScreenProps {
|
||||
inputPrompt: string;
|
||||
onBack: () => void;
|
||||
onSuccess: () => void;
|
||||
isManualMode?: boolean;
|
||||
}
|
||||
|
||||
export function GenerationScreen({
|
||||
inputPrompt,
|
||||
onBack,
|
||||
onSuccess,
|
||||
isManualMode = false,
|
||||
}: GenerationScreenProps) {
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
|
||||
const { register, watch, setValue, reset } = useForm<CreateRuleBlockArgs>({
|
||||
defaultValues: {
|
||||
name: "",
|
||||
description: "",
|
||||
globs: "",
|
||||
alwaysApply: undefined,
|
||||
rule: "",
|
||||
},
|
||||
});
|
||||
|
||||
const formData = watch();
|
||||
|
||||
// Track rule type separately from form data
|
||||
const [selectedRuleType, setSelectedRuleType] = useState<RuleType>(
|
||||
RuleType.Always,
|
||||
);
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
|
||||
// Use the generation hook with the input prompt
|
||||
const { generateRule, isGenerating, error } = useRuleGeneration(
|
||||
inputPrompt,
|
||||
(args) => {
|
||||
// Streaming causes a lot of jank, so wait until done generating
|
||||
if (!isGenerating) {
|
||||
reset(args);
|
||||
handleRuleTypeChange(getRuleType(args));
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// Start generation once when component mounts (only if not in manual mode)
|
||||
useEffect(() => {
|
||||
if (!isManualMode) {
|
||||
void generateRule();
|
||||
}
|
||||
}, [isManualMode]);
|
||||
|
||||
const handleRuleTypeChange = (newRuleType: RuleType) => {
|
||||
setSelectedRuleType(newRuleType);
|
||||
|
||||
// Update alwaysApply based on rule type
|
||||
const alwaysApply = newRuleType === RuleType.Always;
|
||||
setValue("alwaysApply", alwaysApply);
|
||||
|
||||
// Don't clear optional fields - preserve their state
|
||||
// Users can manually clear them if needed
|
||||
};
|
||||
|
||||
const handleContinue = async () => {
|
||||
// Clear any previous errors
|
||||
setFormError(null);
|
||||
|
||||
if (!formData.name) {
|
||||
setFormError("Rule name is required");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!formData.rule) {
|
||||
setFormError("Rule content is required");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const options: any = {
|
||||
alwaysApply: formData.alwaysApply,
|
||||
};
|
||||
|
||||
if (formData.description) {
|
||||
options.description = formData.description;
|
||||
}
|
||||
|
||||
if (formData.globs) {
|
||||
options.globs = formData.globs;
|
||||
}
|
||||
|
||||
const fileContent = createRuleMarkdown(
|
||||
formData.name,
|
||||
formData.rule,
|
||||
options,
|
||||
);
|
||||
|
||||
const workspaceDirs = await ideMessenger.request(
|
||||
"getWorkspaceDirs",
|
||||
undefined,
|
||||
);
|
||||
|
||||
if (workspaceDirs.status !== "success") {
|
||||
setFormError("Failed to get workspace directory");
|
||||
return;
|
||||
}
|
||||
|
||||
const localContinueDir = workspaceDirs.content[0];
|
||||
const ruleFilePath = createRuleFilePath(localContinueDir, formData.name);
|
||||
|
||||
await ideMessenger.request("writeFile", {
|
||||
path: ruleFilePath,
|
||||
contents: fileContent,
|
||||
});
|
||||
ideMessenger.post("openFile", { path: ruleFilePath });
|
||||
|
||||
onSuccess();
|
||||
} catch (err) {
|
||||
const errorMessage =
|
||||
err instanceof Error ? err.message : "Unknown error occurred";
|
||||
setFormError(`Failed to create rule file: ${errorMessage}`);
|
||||
}
|
||||
};
|
||||
|
||||
const showNameSpinner = isGenerating && !formData.name && !isManualMode;
|
||||
const tooltipId = "rule-type-tooltip";
|
||||
|
||||
return (
|
||||
<div className="px-2 pb-2 pt-4 sm:px-4">
|
||||
<div>
|
||||
<div className="text-center">
|
||||
<h2 className="mb-0">Your rule</h2>
|
||||
<p className="text-description m-0 mt-2 p-0">
|
||||
Review and edit your generated rule below
|
||||
</p>
|
||||
</div>
|
||||
<div className="mt-5">
|
||||
<div className="flex flex-col gap-4">
|
||||
{/* Rule metadata form */}
|
||||
<div className="space-y-4">
|
||||
{/* Rule Name - Always visible */}
|
||||
<div className="space-y-1">
|
||||
<label className="text-foreground text-sm font-medium">
|
||||
Rule Name
|
||||
</label>
|
||||
<div className="relative">
|
||||
<input
|
||||
type="text"
|
||||
className="border-input-border bg-input text-input-foreground placeholder:text-input-placeholder focus:border-border-focus box-border w-full rounded-md border px-3 py-2 text-xs focus:outline-none"
|
||||
placeholder={showNameSpinner ? "" : "Enter rule name..."}
|
||||
disabled={isGenerating && !isManualMode}
|
||||
{...register("name")}
|
||||
/>
|
||||
{showNameSpinner && (
|
||||
<div className="absolute left-3 top-1/2 -translate-y-1/2">
|
||||
<Spinner />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Rule Type Selector - Always visible */}
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<label className="text-foreground text-sm font-medium">
|
||||
Rule Type
|
||||
</label>
|
||||
<InformationCircleIcon
|
||||
data-tooltip-id={tooltipId}
|
||||
data-tooltip-content={
|
||||
RuleTypeDescriptions[selectedRuleType]
|
||||
}
|
||||
className="h-4 w-4 text-gray-500"
|
||||
/>
|
||||
<ToolTip id={tooltipId} style={{ zIndex: 100001 }} />
|
||||
</div>
|
||||
<div className="relative">
|
||||
<select
|
||||
className="border-input-border bg-input text-input-foreground focus:border-border-focus w-full rounded-md border px-3 py-2 text-xs focus:outline-none"
|
||||
value={isGenerating ? "" : selectedRuleType}
|
||||
onChange={(e) =>
|
||||
handleRuleTypeChange(e.target.value as RuleType)
|
||||
}
|
||||
disabled={isGenerating && !isManualMode}
|
||||
>
|
||||
{isGenerating && !isManualMode ? (
|
||||
<option value=""></option>
|
||||
) : (
|
||||
<>
|
||||
<option value={RuleType.Always}>Always</option>
|
||||
<option value={RuleType.AutoAttached}>
|
||||
Auto Attached
|
||||
</option>
|
||||
<option value={RuleType.AgentRequested}>
|
||||
Agent Requested
|
||||
</option>
|
||||
<option value={RuleType.Manual}>Manual</option>
|
||||
</>
|
||||
)}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Description (for Agent Requested only) */}
|
||||
<div
|
||||
className={`space-y-1 ${selectedRuleType === RuleType.AgentRequested ? "" : "hidden"}`}
|
||||
>
|
||||
<label className="text-foreground text-sm font-medium">
|
||||
Description
|
||||
</label>
|
||||
<textarea
|
||||
className="border-input-border bg-input text-input-foreground placeholder:text-input-placeholder focus:border-border-focus box-border w-full resize-none rounded-md border px-3 py-2 text-xs focus:outline-none"
|
||||
rows={3}
|
||||
placeholder="Description of the task this rule is helpful for..."
|
||||
{...register("description")}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* File Pattern (for Auto Attached only) */}
|
||||
<div
|
||||
className={`space-y-1 ${selectedRuleType === RuleType.AutoAttached ? "" : "hidden"}`}
|
||||
>
|
||||
<label className="text-foreground text-sm font-medium">
|
||||
File pattern matches
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
className="border-input-border bg-input text-input-foreground placeholder:text-input-placeholder focus:border-border-focus box-border w-full rounded-md border px-3 py-2 font-mono text-xs focus:outline-none"
|
||||
placeholder="*.tsx, **/*.{ts,tsx}, tests/**/*.ts ..."
|
||||
{...register("globs")}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Rule Content */}
|
||||
<div className="relative">
|
||||
<label className="text-foreground text-sm font-medium">
|
||||
Rule Content
|
||||
</label>
|
||||
<textarea
|
||||
className="border-input-border bg-input text-input-foreground placeholder:text-input-placeholder focus:border-border-focus mt-1 box-border w-full resize-none rounded border p-2 text-xs focus:outline-none"
|
||||
rows={10}
|
||||
disabled={isGenerating && !isManualMode}
|
||||
placeholder="Your rule content..."
|
||||
{...register("rule")}
|
||||
/>
|
||||
</div>
|
||||
{error && <p className="text-sm text-red-500">{error}</p>}
|
||||
|
||||
<div className="my-4 flex flex-col items-center gap-2">
|
||||
<div className="flex flex-row justify-center gap-3">
|
||||
<Button
|
||||
type="button"
|
||||
className="min-w-16"
|
||||
onClick={onBack}
|
||||
variant="outline"
|
||||
disabled={isGenerating && !isManualMode}
|
||||
>
|
||||
Back
|
||||
</Button>
|
||||
<Button
|
||||
className="min-w-16"
|
||||
onClick={handleContinue}
|
||||
disabled={
|
||||
(isGenerating && !isManualMode) ||
|
||||
(!formData.rule && !error) ||
|
||||
!formData.name
|
||||
}
|
||||
>
|
||||
Continue
|
||||
</Button>
|
||||
</div>
|
||||
{formError && (
|
||||
<span className="text-error text-center text-xs">
|
||||
Error creating rule: {formError}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
93
gui/src/components/GenerateRuleDialog/InputScreen.tsx
Normal file
93
gui/src/components/GenerateRuleDialog/InputScreen.tsx
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
import React from "react";
|
||||
import { Button } from "../ui";
|
||||
import { RuleTemplateChip } from "./RuleTemplateChip";
|
||||
import { RuleTemplate, ruleTemplates } from "./ruleTemplates";
|
||||
|
||||
interface InputScreenProps {
|
||||
inputPrompt: string;
|
||||
onInputChange: (prompt: string) => void;
|
||||
onGenerate: (prompt: string) => void;
|
||||
onCancel: () => void;
|
||||
onManualWrite: () => void;
|
||||
}
|
||||
|
||||
export function InputScreen({
|
||||
inputPrompt,
|
||||
onInputChange,
|
||||
onGenerate,
|
||||
onCancel,
|
||||
onManualWrite,
|
||||
}: InputScreenProps) {
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (!inputPrompt.trim()) {
|
||||
return;
|
||||
}
|
||||
|
||||
onGenerate(inputPrompt);
|
||||
};
|
||||
|
||||
const handleRuleTemplateClick = (template: RuleTemplate) => {
|
||||
onInputChange(template.template);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="px-2 pb-2 pt-4 sm:px-4">
|
||||
<div>
|
||||
<div className="text-center">
|
||||
<h2 className="mb-0">Generate Rule</h2>
|
||||
<p className="text-description m-0 mt-2 p-0">
|
||||
This will generate a new rule using the content of your chat history
|
||||
</p>
|
||||
</div>
|
||||
<div className="mt-5">
|
||||
<form onSubmit={handleSubmit} className="flex flex-col gap-1">
|
||||
<div className="mb-2 flex flex-wrap items-center justify-center gap-x-3">
|
||||
{ruleTemplates.map((template, index) => (
|
||||
<RuleTemplateChip
|
||||
key={index}
|
||||
icon={template.icon}
|
||||
text={template.title}
|
||||
onClick={() => handleRuleTemplateClick(template)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
<textarea
|
||||
className="border-input-border bg-input text-input-foreground placeholder:text-input-placeholder focus:border-border-focus box-border w-full resize-none rounded border p-2 text-xs focus:outline-none"
|
||||
placeholder="Describe your rule..."
|
||||
rows={5}
|
||||
value={inputPrompt}
|
||||
onChange={(e) => onInputChange(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="my-4 flex flex-col items-center gap-2">
|
||||
<div className="flex flex-row justify-center gap-3">
|
||||
<Button
|
||||
type="button"
|
||||
className="min-w-16"
|
||||
onClick={onCancel}
|
||||
variant="outline"
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button className="min-w-16" disabled={!inputPrompt.trim()}>
|
||||
Generate
|
||||
</Button>
|
||||
</div>
|
||||
<span
|
||||
className="text-description cursor-pointer text-xs underline"
|
||||
onClick={onManualWrite}
|
||||
>
|
||||
Or, write a rule from scratch
|
||||
</span>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
26
gui/src/components/GenerateRuleDialog/RuleTemplateChip.tsx
Normal file
26
gui/src/components/GenerateRuleDialog/RuleTemplateChip.tsx
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
import React from "react";
|
||||
import { Button } from "../ui";
|
||||
|
||||
interface RuleTemplateChipProps {
|
||||
icon: React.ComponentType<{ className?: string }>;
|
||||
text: string;
|
||||
onClick: () => void;
|
||||
}
|
||||
|
||||
export function RuleTemplateChip({
|
||||
icon: Icon,
|
||||
text,
|
||||
onClick,
|
||||
}: RuleTemplateChipProps) {
|
||||
return (
|
||||
<Button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
className="flex items-center gap-2"
|
||||
variant="secondary"
|
||||
>
|
||||
<Icon className="h-3 w-3" />
|
||||
<span className="text-xs">{text}</span>
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
62
gui/src/components/GenerateRuleDialog/index.tsx
Normal file
62
gui/src/components/GenerateRuleDialog/index.tsx
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
import { useState } from "react";
|
||||
import { useDispatch } from "react-redux";
|
||||
import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice";
|
||||
import { GenerationScreen } from "./GenerationScreen";
|
||||
import { InputScreen } from "./InputScreen";
|
||||
|
||||
type Screen = "input" | "generation";
|
||||
|
||||
export function GenerateRuleDialog() {
|
||||
const dispatch = useDispatch();
|
||||
const [screen, setScreen] = useState<Screen>("input");
|
||||
const [inputPrompt, setInputPrompt] = useState("");
|
||||
const [isManualMode, setIsManualMode] = useState(false);
|
||||
|
||||
const closeDialog = () => {
|
||||
setScreen("input");
|
||||
setInputPrompt("");
|
||||
setIsManualMode(false);
|
||||
dispatch(setDialogMessage(undefined));
|
||||
dispatch(setShowDialog(false));
|
||||
};
|
||||
|
||||
const handleGenerate = (prompt: string) => {
|
||||
setInputPrompt(prompt);
|
||||
setIsManualMode(false);
|
||||
setScreen("generation");
|
||||
};
|
||||
|
||||
const handleManualWrite = () => {
|
||||
setIsManualMode(true);
|
||||
setScreen("generation");
|
||||
};
|
||||
|
||||
const handleBack = () => {
|
||||
setScreen("input");
|
||||
};
|
||||
|
||||
const handleSuccess = () => {
|
||||
closeDialog();
|
||||
};
|
||||
|
||||
if (screen === "input") {
|
||||
return (
|
||||
<InputScreen
|
||||
inputPrompt={inputPrompt}
|
||||
onInputChange={setInputPrompt}
|
||||
onGenerate={handleGenerate}
|
||||
onCancel={closeDialog}
|
||||
onManualWrite={handleManualWrite}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<GenerationScreen
|
||||
inputPrompt={inputPrompt}
|
||||
onBack={handleBack}
|
||||
onSuccess={handleSuccess}
|
||||
isManualMode={isManualMode}
|
||||
/>
|
||||
);
|
||||
}
|
||||
36
gui/src/components/GenerateRuleDialog/ruleTemplates.ts
Normal file
36
gui/src/components/GenerateRuleDialog/ruleTemplates.ts
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
import {
|
||||
AtSymbolIcon,
|
||||
CodeBracketIcon,
|
||||
GlobeAltIcon,
|
||||
SparklesIcon,
|
||||
} from "@heroicons/react/24/outline";
|
||||
|
||||
export interface RuleTemplate {
|
||||
icon: React.ComponentType<{ className?: string }>;
|
||||
title: string;
|
||||
template: string;
|
||||
}
|
||||
|
||||
export const ruleTemplates: RuleTemplate[] = [
|
||||
{
|
||||
icon: GlobeAltIcon,
|
||||
title: "Always Applied",
|
||||
template: "Create an always applied rule where for all files...",
|
||||
},
|
||||
{
|
||||
icon: CodeBracketIcon,
|
||||
title: "Auto attached",
|
||||
template:
|
||||
"Create an auto-attached rule where for all {FILE_EXTENSIONS} files...",
|
||||
},
|
||||
{
|
||||
icon: SparklesIcon,
|
||||
title: "Agent Requested",
|
||||
template: "Create an agent requested rule where...",
|
||||
},
|
||||
{
|
||||
icon: AtSymbolIcon,
|
||||
title: "Manual",
|
||||
template: "Create a manually requested rule where...",
|
||||
},
|
||||
];
|
||||
139
gui/src/components/GenerateRuleDialog/useRuleGeneration.ts
Normal file
139
gui/src/components/GenerateRuleDialog/useRuleGeneration.ts
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
import { ToolCallDelta } from "core";
|
||||
import { createRuleBlock } from "core/tools/definitions/createRuleBlock";
|
||||
import { CreateRuleBlockArgs } from "core/tools/implementations/createRuleBlock";
|
||||
import { useCallback, useContext, useState } from "react";
|
||||
import { IdeMessengerContext } from "../../context/IdeMessenger";
|
||||
import { useAppSelector } from "../../redux/hooks";
|
||||
import { selectSelectedChatModel } from "../../redux/slices/configSlice";
|
||||
import { constructMessages } from "../../redux/util/constructMessages";
|
||||
import { addToolCallDeltaToState } from "../../util/toolCallState";
|
||||
|
||||
const RULE_GENERATION_SYSTEM_MESSAGE = `You are an expert at creating effective rules for AI coding assistants. Create concise, actionable rules that follow these guidelines:
|
||||
|
||||
FOCUS:
|
||||
- Keep rules focused on a single, specific concern
|
||||
- Be specific and actionable - avoid vague guidance
|
||||
- Write in imperative language ("Use X", "Always do Y", "Avoid Z")
|
||||
|
||||
EXAMPLES FROM CHAT HISTORY:
|
||||
- Use concrete examples from the chat history when possible
|
||||
- If they say "don't do X", find instances where "X" was done incorrectly
|
||||
- Include before/after code examples using this format:
|
||||
|
||||
**Example**
|
||||
\`\`\`typescript
|
||||
// Bad: Don't do this
|
||||
const badExample = "from chat history";
|
||||
|
||||
// Good: Do this instead
|
||||
const goodExample = "corrected version";
|
||||
\`\`\`
|
||||
|
||||
Be concise but comprehensive. The chat history contains real examples of what to do or avoid.`;
|
||||
|
||||
export interface UseRuleGenerationReturn {
|
||||
generateRule: () => Promise<void>;
|
||||
isGenerating: boolean;
|
||||
error: string | null;
|
||||
reset: () => void;
|
||||
}
|
||||
|
||||
export function useRuleGeneration(
|
||||
inputPrompt: string,
|
||||
onGenerate?: (args: CreateRuleBlockArgs) => void,
|
||||
): UseRuleGenerationReturn {
|
||||
const [isGenerating, setIsGenerating] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const currentHistory = useAppSelector((state) => state.session.history);
|
||||
const selectedChatModel = useAppSelector(selectSelectedChatModel);
|
||||
|
||||
const generateRule = useCallback(async () => {
|
||||
if (!selectedChatModel) {
|
||||
setError("No chat model selected");
|
||||
return;
|
||||
}
|
||||
|
||||
setIsGenerating(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
// Convert current history to ChatHistoryItem format
|
||||
|
||||
// Add our rule generation prompt with instruction to use the tool
|
||||
const history = [
|
||||
{
|
||||
message: {
|
||||
role: "system" as const,
|
||||
content: RULE_GENERATION_SYSTEM_MESSAGE,
|
||||
},
|
||||
contextItems: [],
|
||||
},
|
||||
...currentHistory,
|
||||
{
|
||||
message: {
|
||||
role: "user" as const,
|
||||
content: `The user has requested that we write a new rule. You MUST USE the create_rule_block tool to generate a well-structured rule. Do not say anything else, only call this tool. Here is their request: ${inputPrompt}`,
|
||||
},
|
||||
contextItems: [],
|
||||
},
|
||||
];
|
||||
|
||||
const { messages } = constructMessages(history, undefined, [], {});
|
||||
|
||||
// Create abort controller for this request
|
||||
const abortController = new AbortController();
|
||||
|
||||
// Stream the response with createRuleBlock tool
|
||||
const gen = ideMessenger.llmStreamChat(
|
||||
{
|
||||
messages,
|
||||
completionOptions: {
|
||||
tools: [createRuleBlock],
|
||||
},
|
||||
title: selectedChatModel.title,
|
||||
},
|
||||
abortController.signal,
|
||||
);
|
||||
|
||||
let toolCallState: any = undefined;
|
||||
|
||||
// Process each chunk
|
||||
for await (const chunks of gen) {
|
||||
for (const chunk of chunks) {
|
||||
// Handle tool calls - this is what we care about
|
||||
if (chunk.role === "assistant" && chunk.toolCalls?.length) {
|
||||
const toolCallDelta: ToolCallDelta = chunk.toolCalls[0];
|
||||
toolCallState = addToolCallDeltaToState(
|
||||
toolCallDelta,
|
||||
toolCallState,
|
||||
);
|
||||
|
||||
// Call the callback if provided with the parsed args
|
||||
if (toolCallState?.parsedArgs) {
|
||||
onGenerate?.(toolCallState.parsedArgs);
|
||||
}
|
||||
}
|
||||
// Ignore regular assistant content - we only care about the tool call
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "An error occurred");
|
||||
} finally {
|
||||
setIsGenerating(false);
|
||||
}
|
||||
}, [ideMessenger, currentHistory, selectedChatModel, inputPrompt]);
|
||||
|
||||
const reset = useCallback(() => {
|
||||
setError(null);
|
||||
setIsGenerating(false);
|
||||
}, []);
|
||||
|
||||
return {
|
||||
generateRule,
|
||||
isGenerating,
|
||||
error,
|
||||
reset,
|
||||
};
|
||||
}
|
||||
|
|
@ -18,6 +18,7 @@ import { ROUTES } from "../util/navigation";
|
|||
import { FatalErrorIndicator } from "./config/FatalErrorNotice";
|
||||
import TextDialog from "./dialogs";
|
||||
import Footer from "./Footer";
|
||||
import { GenerateRuleDialog } from "./GenerateRuleDialog";
|
||||
import { LumpProvider } from "./mainInput/Lump/LumpContext";
|
||||
import { useMainEditor } from "./mainInput/TipTapEditor";
|
||||
import {
|
||||
|
|
@ -195,6 +196,15 @@ const Layout = () => {
|
|||
[],
|
||||
);
|
||||
|
||||
useWebviewListener(
|
||||
"generateRule",
|
||||
async () => {
|
||||
dispatch(setShowDialog(true));
|
||||
dispatch(setDialogMessage(<GenerateRuleDialog />));
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (event: any) => {
|
||||
if (isMetaEquivalentKeyPressed(event) && event.code === "KeyC") {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,18 @@
|
|||
import { BarsArrowDownIcon, TrashIcon } from "@heroicons/react/24/outline";
|
||||
import {
|
||||
BarsArrowDownIcon,
|
||||
PlusIcon,
|
||||
TrashIcon,
|
||||
} from "@heroicons/react/24/outline";
|
||||
import { ChatHistoryItem } from "core";
|
||||
import { modelSupportsTools } from "core/llm/autodetect";
|
||||
import { renderChatMessage } from "core/util/messageContent";
|
||||
import FeedbackButtons from "../FeedbackButtons";
|
||||
import { useMemo } from "react";
|
||||
import { useDispatch } from "react-redux";
|
||||
import { useAppSelector } from "../../redux/hooks";
|
||||
import { selectSelectedChatModel } from "../../redux/slices/configSlice";
|
||||
import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice";
|
||||
import { FeedbackButtons } from "../FeedbackButtons";
|
||||
import { GenerateRuleDialog } from "../GenerateRuleDialog";
|
||||
import { CopyIconButton } from "../gui/CopyIconButton";
|
||||
import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip";
|
||||
|
||||
|
|
@ -11,6 +22,7 @@ export interface ResponseActionsProps {
|
|||
index: number;
|
||||
onDelete: () => void;
|
||||
item: ChatHistoryItem;
|
||||
isLast: boolean;
|
||||
}
|
||||
|
||||
export default function ResponseActions({
|
||||
|
|
@ -19,16 +31,43 @@ export default function ResponseActions({
|
|||
item,
|
||||
isTruncated,
|
||||
onDelete,
|
||||
isLast,
|
||||
}: ResponseActionsProps) {
|
||||
const dispatch = useDispatch();
|
||||
const selectedModel = useAppSelector(selectSelectedChatModel);
|
||||
const ruleGenerationSupported = useMemo(() => {
|
||||
return selectedModel && modelSupportsTools(selectedModel);
|
||||
}, [selectedModel]);
|
||||
|
||||
const onGenerateRule = () => {
|
||||
dispatch(setShowDialog(true));
|
||||
dispatch(setDialogMessage(<GenerateRuleDialog />));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="mx-2 flex cursor-default items-center justify-end space-x-1 bg-transparent pb-0 text-xs text-gray-400">
|
||||
<div className="text-description-muted mx-2 flex cursor-default items-center justify-end space-x-1 bg-transparent pb-0 text-xs">
|
||||
{isLast && ruleGenerationSupported && (
|
||||
<div
|
||||
className="mr-1 border-y-0 border-l-0 border-r border-solid pr-2"
|
||||
onClick={onGenerateRule}
|
||||
>
|
||||
<span className="flex cursor-pointer items-center hover:brightness-125">
|
||||
<PlusIcon className="mr-1 h-3 w-3" />
|
||||
<span className="xs:block hidden whitespace-nowrap">
|
||||
Generate rule
|
||||
</span>
|
||||
<span className="xs:hidden block whitespace-nowrap">Rule</span>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isTruncated && (
|
||||
<HeaderButtonWithToolTip
|
||||
tabIndex={-1}
|
||||
text="Continue generation"
|
||||
onClick={onContinueGeneration}
|
||||
>
|
||||
<BarsArrowDownIcon className="h-3.5 w-3.5 text-gray-500" />
|
||||
<BarsArrowDownIcon className="h-3.5 w-3.5" />
|
||||
</HeaderButtonWithToolTip>
|
||||
)}
|
||||
|
||||
|
|
@ -38,14 +77,14 @@ export default function ResponseActions({
|
|||
tabIndex={-1}
|
||||
onClick={onDelete}
|
||||
>
|
||||
<TrashIcon className="h-3.5 w-3.5 text-gray-500" />
|
||||
<TrashIcon className="text-description-muted h-3.5 w-3.5" />
|
||||
</HeaderButtonWithToolTip>
|
||||
|
||||
<CopyIconButton
|
||||
tabIndex={-1}
|
||||
text={renderChatMessage(item.message)}
|
||||
clipboardIconClassName="h-3.5 w-3.5 text-gray-500"
|
||||
checkIconClassName="h-3.5 w-3.5 text-green-400"
|
||||
clipboardIconClassName="h-3.5 w-3.5 text-description-muted"
|
||||
checkIconClassName="h-3.5 w-3.5 text-success"
|
||||
/>
|
||||
|
||||
<FeedbackButtons item={item} />
|
||||
|
|
|
|||
|
|
@ -112,6 +112,7 @@ export default function StepContainer(props: StepContainerProps) {
|
|||
onContinueGeneration={onContinueGeneration}
|
||||
index={props.index}
|
||||
item={props.item}
|
||||
isLast={props.isLast}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { XMarkIcon } from "@heroicons/react/24/outline";
|
||||
import React, { isValidElement, useEffect } from "react";
|
||||
import React, { isValidElement } from "react";
|
||||
import ReactMarkdown from "react-markdown";
|
||||
import styled from "styled-components";
|
||||
import {
|
||||
|
|
@ -8,7 +8,6 @@ import {
|
|||
vscBackground,
|
||||
vscForeground,
|
||||
} from "..";
|
||||
import { varWithFallback } from "../../styles/theme";
|
||||
|
||||
interface TextDialogProps {
|
||||
showDialog: boolean;
|
||||
|
|
@ -21,7 +20,8 @@ const ScreenCover = styled.div`
|
|||
position: fixed;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: ${varWithFallback("background")}aa;
|
||||
background-color: rgba(0, 0, 0, 0.35);
|
||||
backdrop-filter: blur(0.5px);
|
||||
z-index: 100000;
|
||||
flex-direction: column;
|
||||
`;
|
||||
|
|
@ -41,25 +41,23 @@ const DialogContainer = styled.div`
|
|||
`;
|
||||
|
||||
const TextDialog = (props: TextDialogProps) => {
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") {
|
||||
props.onClose();
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener("keydown", handleKeyDown);
|
||||
return () => {
|
||||
document.removeEventListener("keydown", handleKeyDown);
|
||||
};
|
||||
}, [props]);
|
||||
const handleKeyDown = (event: React.KeyboardEvent) => {
|
||||
if (event.key === "Escape") {
|
||||
props.onClose();
|
||||
}
|
||||
};
|
||||
|
||||
if (!isValidElement(props.message) && typeof props.message !== "string") {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<ScreenCover onClick={props.onClose} hidden={!props.showDialog}>
|
||||
<ScreenCover
|
||||
onClick={props.onClose}
|
||||
hidden={!props.showDialog}
|
||||
onKeyDown={handleKeyDown}
|
||||
tabIndex={-1}
|
||||
>
|
||||
<DialogContainer
|
||||
className="xs:w-[90%] no-scrollbar max-h-[95%] w-[92%] max-w-[600px] overflow-auto sm:w-[88%] md:w-[80%]"
|
||||
onClick={(e) => {
|
||||
|
|
|
|||
|
|
@ -1,13 +1,13 @@
|
|||
import { CSSProperties } from "react";
|
||||
import ReactDOM from "react-dom";
|
||||
import { ITooltip, Tooltip } from "react-tooltip";
|
||||
import { vscBackground, vscForeground, vscInputBorder } from "..";
|
||||
import { vscBackground, vscForeground } from "..";
|
||||
import { fontSize } from "../../util";
|
||||
|
||||
const TooltipStyles: CSSProperties = {
|
||||
fontSize: fontSize(-2),
|
||||
backgroundColor: vscBackground,
|
||||
outline: `0.5px solid ${vscInputBorder}`,
|
||||
outline: `0.5px solid ${vscForeground}`,
|
||||
color: vscForeground,
|
||||
padding: "4px 8px",
|
||||
zIndex: 1000,
|
||||
|
|
@ -26,7 +26,13 @@ export function ToolTip(props: ITooltip) {
|
|||
return (
|
||||
tooltipPortalDiv &&
|
||||
ReactDOM.createPortal(
|
||||
<Tooltip {...props} style={combinedStyles} opacity={1} delayShow={200} />,
|
||||
<Tooltip
|
||||
{...props}
|
||||
noArrow
|
||||
style={combinedStyles}
|
||||
opacity={1}
|
||||
delayShow={200}
|
||||
/>,
|
||||
tooltipPortalDiv,
|
||||
)
|
||||
);
|
||||
|
|
|
|||
|
|
@ -131,7 +131,7 @@ export function ContextItemsPeekItem({
|
|||
{contextItem.name}
|
||||
</span>
|
||||
<div
|
||||
className={`group flex flex-row items-center gap-1.5 pr-1.5 text-xs text-gray-400 ${isUrl ? "hover:underline" : ""}`}
|
||||
className={`text-description-muted group flex flex-row items-center gap-1.5 pr-1.5 text-xs ${isUrl ? "hover:underline" : ""}`}
|
||||
onClick={
|
||||
isUrl
|
||||
? (e) => {
|
||||
|
|
@ -151,7 +151,7 @@ export function ContextItemsPeekItem({
|
|||
: contextItem.description}
|
||||
</span>
|
||||
{isUrl && (
|
||||
<ArrowTopRightOnSquareIcon className="h-3 w-3 flex-shrink-0 text-gray-400 opacity-80 group-hover:opacity-100" />
|
||||
<ArrowTopRightOnSquareIcon className="text-description-muted h-3 w-3 flex-shrink-0 opacity-80 group-hover:opacity-100" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
|
@ -196,7 +196,9 @@ export function ContextItemsPeek({
|
|||
<ContextItemsPeekItem key={idx} contextItem={contextItem} />
|
||||
))
|
||||
) : (
|
||||
<div className="pl-2 text-xs italic text-gray-400">No results</div>
|
||||
<div className="text-description-muted pl-2 text-xs italic">
|
||||
No results
|
||||
</div>
|
||||
)}
|
||||
</ToggleDiv>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -62,9 +62,9 @@ export function RulesPeekItem({ rule }: RulesPeekItemProps) {
|
|||
>
|
||||
<div className="flex w-full items-center">
|
||||
{isGlobal ? (
|
||||
<GlobeAltIcon className="mr-2 h-4 w-4 flex-shrink-0 text-gray-400" />
|
||||
<GlobeAltIcon className="text-description-muted mr-2 h-4 w-4 flex-shrink-0" />
|
||||
) : (
|
||||
<DocumentTextIcon className="mr-2 h-4 w-4 flex-shrink-0 text-gray-400" />
|
||||
<DocumentTextIcon className="text-description-muted mr-2 h-4 w-4 flex-shrink-0" />
|
||||
)}
|
||||
|
||||
<div className="flex min-w-0 flex-1 gap-2 text-xs">
|
||||
|
|
@ -87,7 +87,7 @@ export function RulesPeekItem({ rule }: RulesPeekItemProps) {
|
|||
>
|
||||
{displayedRule}
|
||||
{isRuleLong && (
|
||||
<span className="ml-1 text-gray-400 opacity-0 transition-opacity group-hover:opacity-100">
|
||||
<span className="text-description-muted ml-1 opacity-0 transition-opacity group-hover:opacity-100">
|
||||
{expanded ? "(collapse)" : "(expand)"}
|
||||
</span>
|
||||
)}
|
||||
|
|
|
|||
|
|
@ -154,7 +154,7 @@ function ThinkingBlockPeek({
|
|||
}}
|
||||
>
|
||||
{redactedThinking ? (
|
||||
<div className="pl-4 text-xs text-gray-400">
|
||||
<div className="text-description-muted pl-4 text-xs">
|
||||
Thinking content redacted due to safety reasons.
|
||||
</div>
|
||||
) : (
|
||||
|
|
|
|||
|
|
@ -13,9 +13,9 @@ const buttonVariants = {
|
|||
primary:
|
||||
"px-3 py-1.5 border-none text-background bg-foreground hover:enabled:brightness-125",
|
||||
secondary:
|
||||
"px-3 py-1.5 border border-input-border text-foreground bg-input hover:enabled:bg-background hover:enabled:opacity-90",
|
||||
"px-3 py-1.5 border-none text-foreground bg-input hover:enabled:bg-gray-500/20",
|
||||
outline:
|
||||
"px-3 py-1.5 border-[0.5px] border-foreground text-foreground bg-transparent hover:enabled:bg-foreground/10",
|
||||
"px-3 py-1.5 border border-foreground text-foreground bg-transparent hover:enabled:bg-input",
|
||||
ghost:
|
||||
"px-2 py-1.5 border-none text-foreground bg-gray-500/40 hover:enabled:brightness-125",
|
||||
};
|
||||
|
|
|
|||
147
packages/config-yaml/src/markdown/getRuleType.test.ts
Normal file
147
packages/config-yaml/src/markdown/getRuleType.test.ts
Normal file
|
|
@ -0,0 +1,147 @@
|
|||
import { getRuleType, RuleType } from "./getRuleType.js";
|
||||
|
||||
describe("getRuleType", () => {
|
||||
describe("Always type", () => {
|
||||
it("should return Always for rule with no special properties", () => {
|
||||
const rule = { rule: "Some rule content" };
|
||||
expect(getRuleType(rule)).toBe(RuleType.Always);
|
||||
});
|
||||
|
||||
it("should return Always when alwaysApply is true", () => {
|
||||
const rule = { rule: "Some rule content", alwaysApply: true };
|
||||
expect(getRuleType(rule)).toBe(RuleType.Always);
|
||||
});
|
||||
|
||||
it("should return Always when alwaysApply is undefined", () => {
|
||||
const rule = { rule: "Some rule content", alwaysApply: undefined };
|
||||
expect(getRuleType(rule)).toBe(RuleType.Always);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Auto Attached type", () => {
|
||||
it("should return AutoAttached when globs is provided", () => {
|
||||
const rule = { rule: "Some rule content", globs: ["*.ts"] };
|
||||
expect(getRuleType(rule)).toBe(RuleType.AutoAttached);
|
||||
});
|
||||
|
||||
it("should return AutoAttached when regex is provided", () => {
|
||||
const rule = { rule: "Some rule content", regex: "useEffect" };
|
||||
expect(getRuleType(rule)).toBe(RuleType.AutoAttached);
|
||||
});
|
||||
|
||||
it("should return AutoAttached when both globs and regex are provided", () => {
|
||||
const rule = {
|
||||
rule: "Some rule content",
|
||||
globs: ["*.tsx"],
|
||||
regex: "useState",
|
||||
};
|
||||
expect(getRuleType(rule)).toBe(RuleType.AutoAttached);
|
||||
});
|
||||
|
||||
it("should prioritize AutoAttached over other types when globs/regex present", () => {
|
||||
const rule = {
|
||||
rule: "Some rule content",
|
||||
globs: ["*.ts"],
|
||||
description: "Some description",
|
||||
alwaysApply: false,
|
||||
};
|
||||
expect(getRuleType(rule)).toBe(RuleType.AutoAttached);
|
||||
});
|
||||
|
||||
it("should handle string globs", () => {
|
||||
const rule = { rule: "Some rule content", globs: "*.js" };
|
||||
expect(getRuleType(rule)).toBe(RuleType.AutoAttached);
|
||||
});
|
||||
|
||||
it("should handle array regex", () => {
|
||||
const rule = {
|
||||
rule: "Some rule content",
|
||||
regex: ["pattern1", "pattern2"],
|
||||
};
|
||||
expect(getRuleType(rule)).toBe(RuleType.AutoAttached);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Agent Requested type", () => {
|
||||
it("should return AgentRequested when description provided and alwaysApply is false", () => {
|
||||
const rule = {
|
||||
rule: "Some rule content",
|
||||
description: "Helpful for testing",
|
||||
alwaysApply: false,
|
||||
};
|
||||
expect(getRuleType(rule)).toBe(RuleType.AgentRequested);
|
||||
});
|
||||
|
||||
it("should not return AgentRequested when description provided but alwaysApply is true", () => {
|
||||
const rule = {
|
||||
rule: "Some rule content",
|
||||
description: "Helpful for testing",
|
||||
alwaysApply: true,
|
||||
};
|
||||
expect(getRuleType(rule)).toBe(RuleType.Always);
|
||||
});
|
||||
|
||||
it("should not return AgentRequested when description provided but alwaysApply is undefined", () => {
|
||||
const rule = {
|
||||
rule: "Some rule content",
|
||||
description: "Helpful for testing",
|
||||
};
|
||||
expect(getRuleType(rule)).toBe(RuleType.Always);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Manual type", () => {
|
||||
it("should return Manual when alwaysApply is false and no description", () => {
|
||||
const rule = {
|
||||
rule: "Some rule content",
|
||||
alwaysApply: false,
|
||||
};
|
||||
expect(getRuleType(rule)).toBe(RuleType.Manual);
|
||||
});
|
||||
|
||||
it("should not return Manual when description is provided", () => {
|
||||
const rule = {
|
||||
rule: "Some rule content",
|
||||
alwaysApply: false,
|
||||
description: "Some description",
|
||||
};
|
||||
expect(getRuleType(rule)).toBe(RuleType.AgentRequested);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Edge cases", () => {
|
||||
it("should handle empty rule object", () => {
|
||||
const rule = {};
|
||||
expect(getRuleType(rule)).toBe(RuleType.Always);
|
||||
});
|
||||
|
||||
it("should handle rule with empty string globs", () => {
|
||||
const rule = { rule: "Some rule content", globs: "" };
|
||||
expect(getRuleType(rule)).toBe(RuleType.Always);
|
||||
});
|
||||
|
||||
it("should handle rule with empty array globs", () => {
|
||||
const rule = { rule: "Some rule content", globs: [] };
|
||||
expect(getRuleType(rule)).toBe(RuleType.Always);
|
||||
});
|
||||
|
||||
it("should handle rule with empty string regex", () => {
|
||||
const rule = { rule: "Some rule content", regex: "" };
|
||||
expect(getRuleType(rule)).toBe(RuleType.Always);
|
||||
});
|
||||
|
||||
it("should handle rule with empty array regex", () => {
|
||||
const rule = { rule: "Some rule content", regex: [] };
|
||||
expect(getRuleType(rule)).toBe(RuleType.Always);
|
||||
});
|
||||
|
||||
it("should handle rule with empty string description", () => {
|
||||
const rule = {
|
||||
rule: "Some rule content",
|
||||
description: "",
|
||||
alwaysApply: false,
|
||||
};
|
||||
expect(getRuleType(rule)).toBe(RuleType.Manual);
|
||||
});
|
||||
});
|
||||
});
|
||||
55
packages/config-yaml/src/markdown/getRuleType.ts
Normal file
55
packages/config-yaml/src/markdown/getRuleType.ts
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
import { RuleObject } from "../schemas/index.js";
|
||||
|
||||
export enum RuleType {
|
||||
Always = "Always",
|
||||
AutoAttached = "Auto Attached",
|
||||
AgentRequested = "Agent Requested",
|
||||
Manual = "Manual",
|
||||
}
|
||||
|
||||
export const RuleTypeDescriptions: Record<RuleType, string> = {
|
||||
[RuleType.Always]: "Always included in model context",
|
||||
[RuleType.AutoAttached]:
|
||||
"Included when files matching a glob pattern are referenced",
|
||||
[RuleType.AgentRequested]:
|
||||
"Available to AI, which decides whether to include it. Must provide a description",
|
||||
[RuleType.Manual]: "Only included when explicitly mentioned using @ruleName",
|
||||
};
|
||||
|
||||
/**
|
||||
* Determines the rule type based on the rule properties
|
||||
*/
|
||||
export function getRuleType(rule: Partial<RuleObject>): RuleType {
|
||||
// Check if globs/regex have meaningful values (not empty arrays/strings)
|
||||
const hasGlobs =
|
||||
rule.globs &&
|
||||
(Array.isArray(rule.globs)
|
||||
? rule.globs.length > 0
|
||||
: rule.globs.trim().length > 0);
|
||||
const hasRegex =
|
||||
rule.regex &&
|
||||
(Array.isArray(rule.regex)
|
||||
? rule.regex.length > 0
|
||||
: rule.regex.trim().length > 0);
|
||||
|
||||
// Auto Attached: has globs and/or regex patterns
|
||||
if (hasGlobs || hasRegex) {
|
||||
return RuleType.AutoAttached;
|
||||
}
|
||||
|
||||
// Check if description has meaningful value
|
||||
const hasDescription = rule.description && rule.description.trim().length > 0;
|
||||
|
||||
// Agent Requested: has description and alwaysApply is false
|
||||
if (hasDescription && rule.alwaysApply === false) {
|
||||
return RuleType.AgentRequested;
|
||||
}
|
||||
|
||||
// Manual: alwaysApply is false but no description
|
||||
if (rule.alwaysApply === false && !hasDescription) {
|
||||
return RuleType.Manual;
|
||||
}
|
||||
|
||||
// Always: default case (alwaysApply true/undefined, no globs/regex)
|
||||
return RuleType.Always;
|
||||
}
|
||||
|
|
@ -1,2 +1,3 @@
|
|||
export * from "./createMarkdownRule.js";
|
||||
export * from "./getRuleType.js";
|
||||
export * from "./markdownToRule.js";
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue