Merge pull request #7500 from continuedev/tips

feat: tips for cli
This commit is contained in:
Nate Sesti 2025-09-01 22:36:55 -07:00 • committed by GitHub
commit e37b9b0bce
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 321 additions and 213 deletions

View file

@ -1,195 +1,84 @@
import { AssistantUnrolled } from "@continuedev/config-yaml";
import { Text } from "ink";
import { render } from "ink-testing-library";
import React from "react";
import { describe, expect, it, vi } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { IntroMessage } from "./IntroMessage.js";
// Mock the MCPService
vi.mock("../services/MCPService.js", () => ({
MCPService: vi.fn().mockImplementation(() => ({
getState: () => ({ prompts: [] }),
})),
// Mock the TipsDisplay module
vi.mock("./TipsDisplay.js", () => ({
TipsDisplay: () => React.createElement(Text, null, "Mocked TipsDisplay"),
shouldShowTip: vi.fn(),
}));
// Mock other dependencies
vi.mock("../asciiArt.js", () => ({
getDisplayableAsciiArt: () => "MOCK ASCII ART",
}));
// Mock the model capability check
vi.mock("../utils/modelCapability.js", () => ({
isModelCapable: vi.fn().mockReturnValue(true),
isModelCapable: () => true,
}));
describe("IntroMessage", () => {
const mockMcpService = {
getState: () => ({ prompts: [] }),
} as any;
const mockModel = {
provider: "anthropic",
name: "claude-3-sonnet",
model: "claude-3-sonnet",
} as any;
it("should not duplicate rules from command line", () => {
// Config with rules that were already injected from command line
// Hub rules are stored as RuleObject with name and rule fields
const config: AssistantUnrolled = {
name: "Test Assistant",
rules: [
{ name: "nate/spanish", rule: "Always respond in Spanish." },
"Always be helpful",
],
} as any;
const { lastFrame } = render(
<IntroMessage
config={config}
model={mockModel}
mcpService={mockMcpService}
/>,
);
const output = lastFrame();
// Count occurrences of "nate/spanish" in the output
const matches = output?.match(/nate\/spanish/g) || [];
// Should appear exactly once, not twice
expect(matches.length).toBe(1);
// Verify the slug is shown, not the content
expect(output).toContain("nate/spanish");
expect(output).not.toContain("Always respond in Spanish");
// Verify plain string rule is shown as-is
expect(output).toContain("Always be helpful");
beforeEach(() => {
vi.clearAllMocks();
});
it("should display rules from config correctly", () => {
const config: AssistantUnrolled = {
name: "Test Assistant",
rules: ["Rule 1", { name: "Rule 2" }, "Rule 3"],
} as any;
const { lastFrame } = render(
<IntroMessage
config={config}
model={mockModel}
mcpService={mockMcpService}
/>,
);
const output = lastFrame();
expect(output).toContain("Rules:");
expect(output).toContain("Rule 1");
expect(output).toContain("Rule 2");
expect(output).toContain("Rule 3");
afterEach(() => {
vi.restoreAllMocks();
});
it("should not show Rules section when no rules exist", () => {
const config: AssistantUnrolled = {
name: "Test Assistant",
} as any;
it("renders ASCII art and basic structure", () => {
const { lastFrame } = render(<IntroMessage />);
const { lastFrame } = render(
<IntroMessage
config={config}
model={mockModel}
mcpService={mockMcpService}
/>,
);
const output = lastFrame();
expect(output).not.toContain("Rules:");
expect(lastFrame()).toContain("MOCK ASCII ART");
});
it("should handle rule objects with missing name property", () => {
const config: AssistantUnrolled = {
name: "Test Assistant",
rules: [
"String rule",
{ someOtherProp: "value" }, // Missing 'name' property
],
} as any;
it("shows tips when shouldShowTip returns true", async () => {
const { shouldShowTip } = await import("./TipsDisplay.js");
vi.mocked(shouldShowTip).mockReturnValue(true);
const { lastFrame } = render(
<IntroMessage
config={config}
model={mockModel}
mcpService={mockMcpService}
/>,
);
const { lastFrame } = render(<IntroMessage />);
const output = lastFrame();
expect(output).toContain("String rule");
expect(output).toContain("Unknown"); // Should show "Unknown" for objects without name
expect(lastFrame()).toContain("Mocked TipsDisplay");
});
it("should display hub rule slugs, not their content", () => {
const config: AssistantUnrolled = {
name: "Test Assistant",
rules: [
{
name: "org/complex-rule",
rule: `---
alwaysApply: true
---
it("does not show tips when shouldShowTip returns false", async () => {
const { shouldShowTip } = await import("./TipsDisplay.js");
vi.mocked(shouldShowTip).mockReturnValue(false);
This is a very long rule content that should not be displayed.
It contains multiple lines and complex formatting.
The UI should only show the slug 'org/complex-rule'.`,
},
{ name: "another/rule", rule: "Short content" },
],
} as any;
const { lastFrame } = render(<IntroMessage />);
const { lastFrame } = render(
<IntroMessage
config={config}
model={mockModel}
mcpService={mockMcpService}
/>,
);
const output = lastFrame();
// Should show slugs only
expect(output).toContain("org/complex-rule");
expect(output).toContain("another/rule");
// Should NOT show the rule content
expect(output).not.toContain("This is a very long rule");
expect(output).not.toContain("alwaysApply");
expect(output).not.toContain("Short content");
expect(lastFrame()).not.toContain("Mocked TipsDisplay");
});
it("should handle partial loading gracefully", () => {
// Test with no config, no model, no mcpService
const { lastFrame: frame1 } = render(<IntroMessage />);
let output = frame1();
expect(output).toContain("Loading...");
it("renders agent name when config is provided", () => {
const config = { name: "Test Agent", version: "1.0.0", rules: [] };
// Test with only model missing
const config: AssistantUnrolled = {
name: "Test Assistant",
rules: ["Rule 1"],
} as any;
const { lastFrame } = render(<IntroMessage config={config} />);
const { lastFrame: frame2 } = render(
<IntroMessage config={config} mcpService={mockMcpService} />,
);
output = frame2();
expect(output).toContain("Test Assistant");
expect(output).toContain("Loading...");
expect(output).toContain("Rule 1");
expect(lastFrame()).toContain("Agent:");
expect(lastFrame()).toContain("Test Agent");
});
// Test with only config missing
const { lastFrame: frame3 } = render(
<IntroMessage model={mockModel} mcpService={mockMcpService} />,
);
output = frame3();
expect(output).toContain("claude-3-sonnet");
expect(output).not.toContain("Rules:");
it("renders model information when model is provided", () => {
const model = {
name: "provider/model-name",
provider: "test-provider",
model: "test-model",
};
const { lastFrame } = render(<IntroMessage model={model} />);
expect(lastFrame()).toContain("Model:");
expect(lastFrame()).toContain("model-name");
});
it("shows loading state when model is not provided", () => {
const { lastFrame } = render(<IntroMessage />);
expect(lastFrame()).toContain("Model:");
expect(lastFrame()).toContain("Loading...");
});
});

View file

@ -7,6 +7,7 @@ import { MCPService } from "../services/MCPService.js";
import { isModelCapable } from "../utils/modelCapability.js";
import { ModelCapabilityWarning } from "./ModelCapabilityWarning.js";
import { TipsDisplay, shouldShowTip } from "./TipsDisplay.js";
interface IntroMessageProps {
config?: AssistantUnrolled;
@ -14,6 +15,13 @@ interface IntroMessageProps {
mcpService?: MCPService;
}
// Helper function to extract rule names
const extractRuleNames = (rules: any[] = []): string[] => {
return rules.map((rule: any) =>
typeof rule === "string" ? rule : rule?.name || "Unknown",
);
};
const IntroMessage: React.FC<IntroMessageProps> = ({
config,
model,
@ -22,15 +30,12 @@ const IntroMessage: React.FC<IntroMessageProps> = ({
// Get MCP prompts directly (not memoized since they can change after first render)
const mcpPrompts = mcpService?.getState().prompts ?? [];
// Determine if we should show a tip (1 in 5 chance) - computed once on mount
const showTip = useMemo(() => shouldShowTip(), []);
// Memoize expensive operations to avoid running on every resize
const { allRules, modelCapable } = useMemo(() => {
// Show all rules from config (command-line rules are already merged into config)
const configRules =
config?.rules?.map((rule: any) =>
typeof rule === "string" ? rule : rule?.name || "Unknown",
) || [];
const allRules = configRules;
const allRules = extractRuleNames(config?.rules);
// Check if model is capable - now checking both name and model properties
const modelCapable = model
@ -40,12 +45,59 @@ const IntroMessage: React.FC<IntroMessageProps> = ({
return { allRules, modelCapable };
}, [config?.rules, model?.provider, model?.name, model?.model]);
// Render helper components
const renderMcpPrompts = () =>
mcpPrompts.length > 0 ? (
<>
{mcpPrompts.map((prompt, index) => (
<Text key={`mcp-${index}`}>
- <Text color="white">/{prompt.name}</Text>:{" "}
<Text color="gray">{prompt.description}</Text>
</Text>
))}
<Text> </Text>
</>
) : null;
const renderRules = () =>
allRules.length > 0 ? (
<>
<Text bold color="blue">
Rules:
</Text>
{allRules.map((rule, index) => (
<Text key={index}>
- <Text color="white">{rule}</Text>
</Text>
))}
<Text> </Text>
</>
) : null;
const renderMcpServers = () =>
(config?.mcpServers?.length ?? 0) > 0 ? (
<>
<Text bold color="blue">
MCP Servers:
</Text>
{config?.mcpServers?.map((server: any, index: number) => (
<Text key={index}>
- <Text color="white">{server?.name}</Text>
</Text>
))}
<Text> </Text>
</>
) : null;
return (
<Box flexDirection="column" paddingX={1} paddingY={1}>
{/* ASCII Art */}
<Text>{getDisplayableAsciiArt()}</Text>
<Text> </Text>
{/* Tips Display - shown randomly 1 in 5 times */}
{showTip && <TipsDisplay />}
{/* Agent name */}
{config && (
<Text color="blue">
@ -77,48 +129,9 @@ const IntroMessage: React.FC<IntroMessageProps> = ({
</>
)}
{/* MCP prompts */}
{mcpPrompts.length > 0 && (
<>
{mcpPrompts.map((prompt, index) => (
<Text key={`mcp-${index}`}>
- <Text color="white">/{prompt.name}</Text>:{" "}
<Text color="gray">{prompt.description}</Text>
</Text>
))}
<Text> </Text>
</>
)}
{/* Rules */}
{allRules.length > 0 && (
<>
<Text bold color="blue">
Rules:
</Text>
{allRules.map((rule, index) => (
<Text key={index}>
- <Text color="white">{rule}</Text>
</Text>
))}
<Text> </Text>
</>
)}
{/* MCP Servers */}
{(config?.mcpServers?.length ?? 0) > 0 && (
<>
<Text bold color="blue">
MCP Servers:
</Text>
{config?.mcpServers?.map((server: any, index: number) => (
<Text key={index}>
- <Text color="white">{server?.name}</Text>
</Text>
))}
<Text> </Text>
</>
)}
{renderMcpPrompts()}
{renderRules()}
{renderMcpServers()}
</Box>
);
};

View file

@ -0,0 +1,155 @@
import { render } from "ink-testing-library";
import React from "react";
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import {
TipsDisplay,
shouldShowTip,
CONTINUE_CLI_TIPS,
} from "./TipsDisplay.js";
describe("TipsDisplay", () => {
beforeEach(() => {
// Mock Math.random to make tests deterministic
vi.spyOn(Math, "random");
});
afterEach(() => {
vi.restoreAllMocks();
});
it("renders a random tip from the tips array", () => {
// Mock Math.random to return 0.5, which should select the middle tip
vi.mocked(Math.random).mockReturnValue(0.5);
const expectedTipIndex = Math.floor(0.5 * CONTINUE_CLI_TIPS.length);
const expectedTip = CONTINUE_CLI_TIPS[expectedTipIndex];
const { lastFrame } = render(<TipsDisplay />);
expect(lastFrame()).toContain("* Tip:");
expect(lastFrame()).toContain(expectedTip);
});
it("renders different tips based on random selection", () => {
// Test with first tip
vi.mocked(Math.random).mockReturnValue(0.0);
const { lastFrame: firstFrame } = render(<TipsDisplay />);
expect(firstFrame()).toContain(CONTINUE_CLI_TIPS[0]);
// Test with last tip - use partial match due to line wrapping
vi.mocked(Math.random).mockReturnValue(0.99);
const { lastFrame: lastFrame } = render(<TipsDisplay />);
const lastTip = CONTINUE_CLI_TIPS[CONTINUE_CLI_TIPS.length - 1];
const firstPartOfLastTip = lastTip.substring(0, 30); // Check first 30 chars
expect(lastFrame()).toContain(firstPartOfLastTip);
});
it("always renders the tip structure correctly", () => {
vi.mocked(Math.random).mockReturnValue(0.5);
const { lastFrame } = render(<TipsDisplay />);
const output = lastFrame();
// Should contain the tip icon and label
expect(output).toContain("* Tip:");
// Should contain one of the tips
const containsAtLeastOneTip = CONTINUE_CLI_TIPS.some(
(tip) => output?.includes(tip) ?? false,
);
expect(containsAtLeastOneTip).toBe(true);
});
});
describe("shouldShowTip", () => {
beforeEach(() => {
vi.spyOn(Math, "random");
});
afterEach(() => {
vi.restoreAllMocks();
});
it("returns true when random value is less than 0.2 (20%)", () => {
vi.mocked(Math.random).mockReturnValue(0.1);
expect(shouldShowTip()).toBe(true);
vi.mocked(Math.random).mockReturnValue(0.19);
expect(shouldShowTip()).toBe(true);
});
it("returns false when random value is 0.2 or greater", () => {
vi.mocked(Math.random).mockReturnValue(0.2);
expect(shouldShowTip()).toBe(false);
vi.mocked(Math.random).mockReturnValue(0.5);
expect(shouldShowTip()).toBe(false);
vi.mocked(Math.random).mockReturnValue(0.99);
expect(shouldShowTip()).toBe(false);
});
it("has approximately 20% probability over many calls", () => {
// Restore original Math.random for this statistical test
vi.restoreAllMocks();
// Test the probability distribution over many calls
let trueCount = 0;
const iterations = 1000;
for (let i = 0; i < iterations; i++) {
if (shouldShowTip()) {
trueCount++;
}
}
const probability = trueCount / iterations;
// Allow for some variance (15% to 25% range)
expect(probability).toBeGreaterThan(0.15);
expect(probability).toBeLessThan(0.25);
// Re-mock for proper cleanup
vi.spyOn(Math, "random");
});
});
describe("CONTINUE_CLI_TIPS", () => {
it("contains at least 6 tips", () => {
expect(CONTINUE_CLI_TIPS.length).toBeGreaterThanOrEqual(6);
});
it("all tips are non-empty strings", () => {
CONTINUE_CLI_TIPS.forEach((tip, index) => {
expect(typeof tip).toBe("string");
expect(tip.trim().length).toBeGreaterThan(0);
});
});
it("tips are helpful and informative", () => {
// Check that tips contain useful keywords
const usefulKeywords = [
"/help",
"escape",
"pause",
"arrow keys",
"multi-line",
"history",
"/resume",
"headless",
"flag",
"keyboard shortcuts",
];
const allTipsText = CONTINUE_CLI_TIPS.join(" ").toLowerCase();
// At least half of the keywords should appear in the tips
const foundKeywords = usefulKeywords.filter((keyword) =>
allTipsText.includes(keyword.toLowerCase()),
);
expect(foundKeywords.length).toBeGreaterThanOrEqual(
usefulKeywords.length / 2,
);
});
});

View file

@ -0,0 +1,51 @@
import { Box, Text } from "ink";
import React, { useMemo } from "react";
// Array of helpful tips for Continue CLI users
const CONTINUE_CLI_TIPS = [
"Use `/help` to learn keyboard shortcuts",
"Press escape to pause cn, and press enter to resume",
"Use arrow keys (↑/↓) to navigate through your input history",
'Multi-line input is supported by typing "\\" and pressing enter',
"Use `cn ls` or `/resume` to resume a previous conversation",
'Run `cn` with the `-p` flag for headless mode. For example: `cn -p "Generate a commit message for the current changes. Output _only_ the commit message and nothing else."`',
];
interface TipsDisplayProps {
// No props needed - component handles its own randomization
}
/**
* Randomly selects and displays a tip from the CONTINUE_CLI_TIPS array.
* Should only be shown 1 in 5 times (20% chance).
*/
const TipsDisplay: React.FC<TipsDisplayProps> = () => {
// Randomly select a tip, memoized to prevent changing on re-renders
const randomTip = useMemo(
() =>
CONTINUE_CLI_TIPS[Math.floor(Math.random() * CONTINUE_CLI_TIPS.length)],
[],
);
return (
<Box flexDirection="row" paddingX={1} paddingBottom={1}>
<Text color="green" bold>
* Tip:
</Text>
<Text color="gray" italic>
{" "}
{randomTip}
</Text>
<Text> </Text>
</Box>
);
};
/**
* Determines whether to show a tip (1 in 5 chance, 20% probability)
*/
export function shouldShowTip(): boolean {
return Math.random() < 0.2; // 20% chance (1 in 5)
}
export { CONTINUE_CLI_TIPS, TipsDisplay };