Merge branch 'main' of https://github.com/continuedev/continue into uinstinct/cli-skip-telemetry-tests

This commit is contained in:
Dallin Romney 2025-09-10 18:41:57 -07:00
commit 934799eedf
184 changed files with 10808 additions and 6974 deletions

View file

@ -1,20 +0,0 @@
#!/bin/bash
# Get file path from hook input
FILE_PATH=$(cat | jq -r '.tool_input.file_path // .tool_input.edits[].file_path // empty' | head -n1)
# Function to run lint and typecheck
run_checks() {
local dir=$1
cd "$dir"
npm run lint >&2 && npm run tsc:check >&2
}
# Run checks based on file location
if [[ "$FILE_PATH" == *"/core/"* ]]; then
run_checks core
elif [[ "$FILE_PATH" == *"/gui/"* ]]; then
run_checks gui
elif [[ "$FILE_PATH" == *"/extensions/vscode/"* ]]; then
run_checks extensions/vscode
fi

View file

@ -1,15 +0,0 @@
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit|MultiEdit",
"hooks": [
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/lint-check.sh"
}
]
}
]
}
}

View file

@ -91,7 +91,7 @@ jobs:
Please analyze the current PR, understand the request, implement the necessary changes, and commit them to this branch."
# Start remote session and capture JSON output
SESSION_OUTPUT=$(echo "$PROMPT" | cn remote -s --branch ${{ steps.pr-info.outputs.head_ref }})
SESSION_OUTPUT=$(echo "$PROMPT" | cn remote -s --config continuedev/address-code-review --branch ${{ steps.pr-info.outputs.head_ref }})
echo "Raw session output: $SESSION_OUTPUT"
# Extract URL from JSON output
@ -233,7 +233,7 @@ jobs:
# Start remote session and capture JSON output
echo "Starting cn with prompt..."
SESSION_OUTPUT=$(cat /tmp/prompt.txt | cn remote -s --branch ${{ github.event.pull_request.head.ref }})
SESSION_OUTPUT=$(cat /tmp/prompt.txt | cn remote -s --config continuedev/address-code-review --branch ${{ github.event.pull_request.head.ref }})
echo "Raw session output: $SESSION_OUTPUT"
# Extract URL from JSON output

View file

@ -43,7 +43,8 @@
"extensions/vscode/e2e/storage": true,
"extensions/vscode/e2e/vsix": true,
"extensions/.continue-debug": true,
"extensions/cli/dist/**": true
"extensions/cli/dist/**": true,
"packages/config-yaml/dist/**": true
// "sync/**": true
},
"editor.formatOnSave": true,

View file

@ -166,8 +166,13 @@ export const CODE_KEYWORDS_ENDING_IN_SEMICOLON = ["def"];
export const CODE_STOP_BLOCK = "[/CODE]";
export const BRACKET_ENDING_CHARS = [")", "]", "}", ";"];
export const PREFIXES_TO_SKIP = ["<COMPLETION>"];
export const LINES_TO_STOP_AT = ["# End of file.", "<STOP EDITING HERE"];
export const LINES_TO_SKIP = ["</START EDITING HERE>"];
export const LINES_TO_STOP_AT = [
"# End of file.",
"<STOP EDITING HERE",
"<|/updated_code|>",
"```",
];
export const LINES_TO_SKIP = ["</START EDITING HERE>", "<|updated_code|>"];
export const LINES_TO_REMOVE_BEFORE_START = [
"<COMPLETION>",
"[CODE]",

View file

@ -1,32 +1,32 @@
import { IDE } from "..";
import { joinPathsToUri } from "../util/uri";
const DEFAULT_ASSISTANT_FILE = `# This is an example assistant configuration file
# It is used to define custom AI assistants within Continue
# Each assistant file can be accessed by selecting it from the assistant dropdown
const DEFAULT_ASSISTANT_FILE = `# This is an example agent configuration file
# It is used to define custom AI agents within Continue
# Each agent file can be accessed by selecting it from the agent dropdown
# To learn more, see the full assistant reference: https://docs.continue.dev/reference
# To learn more, see the full config.yaml reference: https://docs.continue.dev/reference
name: Example Assistant
name: Example Agent
version: 1.0.0
schema: v1
# Models define which AI models this assistant can use
# Models define which AI models this agent can use
# https://docs.continue.dev/customization/models
models:
- name: my gpt-5
provider: openai
model: gpt-5
apiKey: YOUR_API_KEY_HERE
apiKey: YOUR_OPENAI_API_KEY_HERE
- uses: ollama/qwen2.5-coder-7b
- uses: anthropic/claude-4-sonnet
with:
ANTHROPIC_API_KEY: \${{ secrets.ANTHROPIC_API_KEY }}
# Context providers define what information the assistant can access
context:
- provider: code
- provider: docs
- provider: diff
- provider: terminal
- provider: problems
- provider: folder
- provider: codebase
# MCP Servers the agent can use
# https://docs.continue.dev/customization/mcp-tools
mcpServers:
- uses: anthropic/memory-mcp
`;
export async function createNewAssistantFile(
@ -42,7 +42,7 @@ export async function createNewAssistantFile(
const baseDirUri = joinPathsToUri(
workspaceDirs[0],
assistantPath ?? ".continue/assistants",
assistantPath ?? ".continue/agents",
);
// Find the first available filename
@ -50,10 +50,7 @@ export async function createNewAssistantFile(
let assistantFileUri: string;
do {
const suffix = counter === 0 ? "" : `-${counter}`;
assistantFileUri = joinPathsToUri(
baseDirUri,
`new-assistant${suffix}.yaml`,
);
assistantFileUri = joinPathsToUri(baseDirUri, `new-agent${suffix}.yaml`);
counter++;
} while (await ide.fileExists(assistantFileUri));

View file

@ -29,8 +29,9 @@ import { editConfigFile, migrateV1DevDataFiles } from "./util/paths";
import { Telemetry } from "./util/posthog";
import {
isProcessBackgrounded,
killTerminalProcess,
markProcessAsBackgrounded,
} from "./util/processTerminalBackgroundStates";
} from "./util/processTerminalStates";
import { getSymbolsForManyFiles } from "./util/treeSitter";
import { TTS } from "./util/tts";
@ -1062,6 +1063,10 @@ export class Core {
},
);
on("process/killTerminalProcess", async ({ data: { toolCallId } }) => {
await killTerminalProcess(toolCallId);
});
on("mdm/setLicenseKey", ({ data: { licenseKey } }) => {
const isValid = setMdmLicenseKey(licenseKey);
return isValid;

View file

@ -108,23 +108,24 @@ export async function* streamDiffLines({
// Rules can be included with edit prompt
// If any rules are present this will result in using chat instead of legacy completion
const systemMessage = rulesToInclude
? getSystemMessageWithRules({
availableRules: rulesToInclude,
userMessage:
typeof prompt === "string"
? ({
role: "user",
content: prompt,
} as UserChatMessage)
: (findLast(
prompt,
(msg) => msg.role === "user" || msg.role === "tool",
) as UserChatMessage | ToolResultChatMessage | undefined),
baseSystemMessage: undefined,
contextItems: [],
}).systemMessage
: undefined;
const systemMessage =
rulesToInclude || llm.baseChatSystemMessage
? getSystemMessageWithRules({
availableRules: rulesToInclude ?? [],
userMessage:
typeof prompt === "string"
? ({
role: "user",
content: prompt,
} as UserChatMessage)
: (findLast(
prompt,
(msg) => msg.role === "user" || msg.role === "tool",
) as UserChatMessage | ToolResultChatMessage | undefined),
baseSystemMessage: llm.baseChatSystemMessage,
contextItems: [],
}).systemMessage
: undefined;
if (systemMessage) {
if (typeof prompt === "string") {

View file

@ -532,7 +532,7 @@ describe("Bedrock", () => {
);
});
it("should add cache points for prompt caching when needed", () => {
it("should add cache points when cacheBehavior.cacheConversation is enabled", () => {
// Create a test instance with caching behavior enabled
const bedrockWithCaching = new TestBedrock({
apiKey: "test-key",
@ -576,5 +576,95 @@ describe("Bedrock", () => {
const userMessageText = converted[0].content?.[0].text;
expect(userMessageText).toMatch(/First message.+/);
});
it("should add cache points when completionOptions.promptCaching is enabled", () => {
// Create a test instance with prompt caching enabled via completionOptions
const bedrockWithPromptCaching = new TestBedrock({
apiKey: "test-key",
model: "anthropic.claude-3-sonnet-20240229-v1:0",
region: "us-east-1",
});
// Set completionOptions.promptCaching (without cacheBehavior)
bedrockWithPromptCaching.completionOptions = {
...bedrockWithPromptCaching.completionOptions,
promptCaching: true,
};
const messages: ChatMessage[] = [
{ role: "user", content: "First message" } as UserChatMessage,
{ role: "assistant", content: "First response" },
{ role: "user", content: "Second message" } as UserChatMessage,
];
const availableTools = new Set<string>();
const converted = bedrockWithPromptCaching["_convertMessages"](
messages,
availableTools,
);
// The last two user messages should have cache points
expect(converted.length).toBe(3);
expect(converted[0].role).toBe("user");
expect(converted[0].content?.some((block) => block.cachePoint)).toBe(
true,
);
expect(converted[1].role).toBe("assistant");
expect(converted[2].role).toBe("user");
expect(converted[2].content?.some((block) => block.cachePoint)).toBe(
true,
);
// Verify that text content includes a cache ID suffix
const userMessageText = converted[0].content?.[0].text;
expect(userMessageText).toMatch(/First message.+/);
});
it("should not add cache points when both caching options are disabled", () => {
// Create a test instance with no caching enabled
const bedrockNoCaching = new TestBedrock({
apiKey: "test-key",
model: "anthropic.claude-3-sonnet-20240229-v1:0",
region: "us-east-1",
});
// Explicitly set no caching
bedrockNoCaching.cacheBehavior = {
cacheConversation: false,
cacheSystemMessage: false,
};
bedrockNoCaching.completionOptions = {
...bedrockNoCaching.completionOptions,
promptCaching: false,
};
const messages: ChatMessage[] = [
{ role: "user", content: "First message" } as UserChatMessage,
{ role: "assistant", content: "First response" },
{ role: "user", content: "Second message" } as UserChatMessage,
];
const availableTools = new Set<string>();
const converted = bedrockNoCaching["_convertMessages"](
messages,
availableTools,
);
// No cache points should be added
expect(converted.length).toBe(3);
expect(converted[0].role).toBe("user");
expect(converted[0].content?.some((block) => block.cachePoint)).toBe(
false,
);
expect(converted[1].role).toBe("assistant");
expect(converted[2].role).toBe("user");
expect(converted[2].content?.some((block) => block.cachePoint)).toBe(
false,
);
// Verify that text content doesn't include a cache ID suffix
const userMessageText = converted[0].content?.[0].text;
expect(userMessageText).toBe("First message");
});
});
});

View file

@ -513,7 +513,10 @@ class Bedrock extends BaseLLM {
// The second-to-last because it retrieves potentially already cached contents,
// The last one because we want it cached for later retrieval.
// See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html
if (this.cacheBehavior?.cacheConversation) {
if (
this.cacheBehavior?.cacheConversation ||
this.completionOptions.promptCaching
) {
this._addCachingToLastTwoUserMessages(converted);
}

View file

@ -250,7 +250,7 @@
"@types/node": "^20.11.19",
"@types/shell-quote": "^1.7.5",
"typescript": "^5.5.2",
"vitest": "^1.6.0"
"vitest": "^3.2.4"
}
},
"node_modules/@75lb/deep-merge": {
@ -19351,9 +19351,9 @@
}
},
"node_modules/vite": {
"version": "6.3.5",
"resolved": "https://registry.npmjs.org/vite/-/vite-6.3.5.tgz",
"integrity": "sha512-cZn6NDFE7wdTpINgs++ZJ4N49W2vRp8LCKrn3Ob1kYNtOo21vfDoaV5GzBfLU4MovSAB8uNRm4jgzVQZ+mBzPQ==",
"version": "6.3.6",
"resolved": "https://registry.npmjs.org/vite/-/vite-6.3.6.tgz",
"integrity": "sha512-0msEVHJEScQbhkbVTb/4iHZdJ6SXp/AvxL2sjwYQFfBqleHtnCqv1J3sa9zbWz/6kW1m9Tfzn92vW+kZ1WV6QA==",
"dev": true,
"license": "MIT",
"dependencies": {

View file

@ -313,5 +313,6 @@ export type ToCoreFromIdeOrWebviewProtocol = {
];
"process/markAsBackgrounded": [{ toolCallId: string }, void];
"process/isBackgrounded": [{ toolCallId: string }, boolean];
"process/killTerminalProcess": [{ toolCallId: string }, void];
"mdm/setLicenseKey": [{ licenseKey: string }, boolean];
};

View file

@ -86,6 +86,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"isItemTooBig",
"process/markAsBackgrounded",
"process/isBackgrounded",
"process/killTerminalProcess",
];
// Message types to pass through from core to webview

View file

@ -7,7 +7,7 @@ export interface EditToolArgs {
changes: string;
}
export const NO_PARALLEL_TOOL_CALLING_INTSRUCTION =
export const NO_PARALLEL_TOOL_CALLING_INSTRUCTION =
"This tool CANNOT be called in parallel with other tools.";
const CHANGES_DESCRIPTION =
@ -24,7 +24,7 @@ export const editFileTool: Tool = {
isInstant: false,
function: {
name: BuiltInToolNames.EditExistingFile,
description: `Use this tool to edit an existing file. If you don't know the contents of the file, read it first.\n${EDIT_CODE_INSTRUCTIONS}\n${NO_PARALLEL_TOOL_CALLING_INTSRUCTION}`,
description: `Use this tool to edit an existing file. If you don't know the contents of the file, read it first.\n${EDIT_CODE_INSTRUCTIONS}\n${NO_PARALLEL_TOOL_CALLING_INSTRUCTION}`,
parameters: {
type: "object",
required: ["filepath", "changes"],

View file

@ -1,6 +1,6 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { NO_PARALLEL_TOOL_CALLING_INTSRUCTION } from "./editFile";
import { NO_PARALLEL_TOOL_CALLING_INSTRUCTION } from "./editFile";
import { singleFindAndReplaceTool } from "./singleFindAndReplace";
export interface EditOperation {
@ -43,7 +43,7 @@ IMPORTANT:
CRITICAL REQUIREMENTS:
1. ALWAYS use the ${BuiltInToolNames.ReadFile} tool just before making edits, to understand the file's up-to-date contents and context. The user can also edit the file while you are working with it.
2. ${NO_PARALLEL_TOOL_CALLING_INTSRUCTION}
2. ${NO_PARALLEL_TOOL_CALLING_INSTRUCTION}
3. When making edits:
- Ensure all edits result in idiomatic, correct code
- Do not leave the code in a broken state

View file

@ -1,6 +1,6 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { NO_PARALLEL_TOOL_CALLING_INTSRUCTION } from "./editFile";
import { NO_PARALLEL_TOOL_CALLING_INSTRUCTION } from "./editFile";
export interface SingleFindAndReplaceArgs {
filepath: string;
@ -24,7 +24,7 @@ export const singleFindAndReplaceTool: Tool = {
IMPORTANT:
- ALWAYS use the \`${BuiltInToolNames.ReadFile}\` tool just before making edits, to understand the file's up-to-date contents and context. The user can also edit the file while you are working with it.
- ${NO_PARALLEL_TOOL_CALLING_INTSRUCTION}
- ${NO_PARALLEL_TOOL_CALLING_INSTRUCTION}
- When editing text from \`${BuiltInToolNames.ReadFile}\` tool output, ensure you preserve exact whitespace/indentation.
- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.
- Use \`replace_all\` for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable, for instance.

View file

@ -36,8 +36,11 @@ import { fileURLToPath } from "node:url";
import { ToolImpl } from ".";
import {
isProcessBackgrounded,
markProcessAsRunning,
removeBackgroundedProcess,
} from "../../util/processTerminalBackgroundStates";
removeRunningProcess,
updateProcessOutput,
} from "../../util/processTerminalStates";
import { getBooleanArg, getStringArg } from "../parseArgs";
const asyncExec = util.promisify(childProcess.exec);
@ -120,6 +123,16 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
env: getColorEnv(), // Add enhanced environment for colors
});
// Track this process for foreground cancellation
if (toolCallId && waitForCompletion) {
markProcessAsRunning(
toolCallId,
childProc,
extras.onPartialOutput,
terminalOutput,
);
}
childProc.stdout?.on("data", (data) => {
// Skip if this process has been backgrounded
if (isProcessBackgrounded(toolCallId)) return;
@ -127,6 +140,11 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
const newOutput = getDecodedOutput(data);
terminalOutput += newOutput;
// Update the tracked output for potential cancellation notifications
if (toolCallId && waitForCompletion) {
updateProcessOutput(toolCallId, terminalOutput);
}
// Send partial output to UI
if (extras.onPartialOutput) {
const status = waitForCompletion
@ -153,6 +171,11 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
const newOutput = getDecodedOutput(data);
terminalOutput += newOutput;
// Update the tracked output for potential cancellation notifications
if (toolCallId && waitForCompletion) {
updateProcessOutput(toolCallId, terminalOutput);
}
// Send partial output to UI, status is not required
if (extras.onPartialOutput) {
extras.onPartialOutput({
@ -182,15 +205,19 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
}
childProc.on("close", (code) => {
// If this process has been backgrounded, clean it up from the map and return
if (isProcessBackgrounded(toolCallId)) {
removeBackgroundedProcess(toolCallId);
return;
// Clean up process tracking
if (toolCallId) {
if (isProcessBackgrounded(toolCallId)) {
removeBackgroundedProcess(toolCallId);
return;
}
// Remove from foreground tracking if it was tracked
removeRunningProcess(toolCallId);
}
if (waitForCompletion) {
// Normal completion, resolve now
if (code === 0) {
if (!code || code === 0) {
const status = "Command completed";
resolve([
{
@ -234,10 +261,14 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
});
childProc.on("error", (error) => {
// If this process has been backgrounded, clean it up from the map and return
if (isProcessBackgrounded(toolCallId)) {
removeBackgroundedProcess(toolCallId);
return;
// Clean up process tracking
if (toolCallId) {
if (isProcessBackgrounded(toolCallId)) {
removeBackgroundedProcess(toolCallId);
return;
}
// Remove from foreground tracking if it was tracked
removeRunningProcess(toolCallId);
}
reject(error);
@ -281,6 +312,11 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
},
);
// Track this process for foreground cancellation
if (toolCallId) {
markProcessAsRunning(toolCallId, childProc, undefined, "");
}
let stdout = "";
let stderr = "";
@ -293,6 +329,11 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
});
childProc.on("close", (code) => {
// Clean up process tracking
if (toolCallId) {
removeRunningProcess(toolCallId);
}
if (code === 0) {
resolve({ stdout, stderr });
} else {
@ -305,6 +346,10 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
});
childProc.on("error", (error) => {
// Clean up process tracking
if (toolCallId) {
removeRunningProcess(toolCallId);
}
reject(error);
});
},

View file

@ -12,7 +12,7 @@ import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { IDE, ToolExtras } from "../..";
import * as processBackgroundStates from "../../util/processTerminalBackgroundStates";
import * as processTerminalStates from "../../util/processTerminalStates";
import { runTerminalCommandImpl } from "./runTerminalCommand";
import { runTerminalCommandTool } from "../definitions/runTerminalCommand";
@ -39,12 +39,8 @@ describe("runTerminalCommandImpl", () => {
vi.resetAllMocks();
// Setup backgrounded processes handling - don't mock, just make sure it's empty
// Get any processes that might be already tracked and clear them
const processMap = (processBackgroundStates as any)
.processTerminalBackgroundStates;
if (processMap && typeof processMap.clear === "function") {
processMap.clear();
}
// Clear any processes that might be already tracked
processTerminalStates.clearAllBackgroundProcesses();
// Setup IDE mocks
mockGetIdeInfo.mockReturnValue(Promise.resolve({ remoteName: "local" }));

View file

@ -35,6 +35,21 @@ export function renderContextItems(contextItems: ContextItem[]): string {
return contextItems.map((item) => item.content).join("\n\n");
}
export function renderContextItemsWithStatus(contextItems: any[]): string {
return contextItems
.map((item) => {
let result = item.content;
// If this item has a status, append it directly after the content
if (item.status) {
result += `\n[Status: ${item.status}]`;
}
return result;
})
.join("\n\n");
}
export function normalizeToMessageParts(message: ChatMessage): MessagePart[] {
switch (message.role) {
case "user":

View file

@ -1,73 +0,0 @@
import {
markProcessAsBackgrounded,
isProcessBackgrounded,
removeBackgroundedProcess,
} from "./processTerminalBackgroundStates";
describe("processTerminalBackgroundStates", () => {
beforeEach(() => {
// Clear any backgrounded processes before each test
const backgroundedProcesses = Array.from(
Object.getOwnPropertySymbols(global),
).find(
(symbol) => String(symbol) === "Symbol(processTerminalBackgroundStates)",
);
if (backgroundedProcesses) {
// Reset the map by reimporting the module
jest.resetModules();
}
});
test("should mark a process as backgrounded", () => {
const toolCallId = "test-123";
markProcessAsBackgrounded(toolCallId);
expect(isProcessBackgrounded(toolCallId)).toBe(true);
});
test("should correctly identify non-backgrounded processes", () => {
const toolCallId = "test-123";
const anotherToolCallId = "test-456";
markProcessAsBackgrounded(toolCallId);
expect(isProcessBackgrounded(toolCallId)).toBe(true);
expect(isProcessBackgrounded(anotherToolCallId)).toBe(false);
});
test("should remove a process from backgrounded state", () => {
const toolCallId = "test-123";
markProcessAsBackgrounded(toolCallId);
expect(isProcessBackgrounded(toolCallId)).toBe(true);
removeBackgroundedProcess(toolCallId);
expect(isProcessBackgrounded(toolCallId)).toBe(false);
});
test("should handle removing non-existent processes", () => {
const toolCallId = "test-123";
// Should not throw an error
removeBackgroundedProcess(toolCallId);
expect(isProcessBackgrounded(toolCallId)).toBe(false);
});
test("should handle multiple processes", () => {
const toolCallId1 = "test-123";
const toolCallId2 = "test-456";
const toolCallId3 = "test-789";
markProcessAsBackgrounded(toolCallId1);
markProcessAsBackgrounded(toolCallId2);
expect(isProcessBackgrounded(toolCallId1)).toBe(true);
expect(isProcessBackgrounded(toolCallId2)).toBe(true);
expect(isProcessBackgrounded(toolCallId3)).toBe(false);
removeBackgroundedProcess(toolCallId1);
expect(isProcessBackgrounded(toolCallId1)).toBe(false);
expect(isProcessBackgrounded(toolCallId2)).toBe(true);
});
});

View file

@ -1,17 +0,0 @@
// Track which processes have been backgrounded
const processTerminalBackgroundStates = new Map<string, boolean>();
// Function to mark a process as backgrounded
export function markProcessAsBackgrounded(toolCallId: string): void {
processTerminalBackgroundStates.set(toolCallId, true);
}
// Function to check if a process is backgrounded
export function isProcessBackgrounded(toolCallId: string): boolean {
return processTerminalBackgroundStates.has(toolCallId);
}
// Function to remove a process from the backgrounded processes map
export function removeBackgroundedProcess(toolCallId: string): void {
processTerminalBackgroundStates.delete(toolCallId);
}

View file

@ -0,0 +1,367 @@
import { ChildProcess } from "child_process";
import {
clearAllBackgroundProcesses,
getAllBackgroundedProcessIds,
getAllRunningProcessIds,
getRunningProcess,
isProcessBackgrounded,
isProcessRunning,
killAllRunningTerminalProcesses,
killMultipleTerminalProcesses,
killTerminalProcess,
markProcessAsBackgrounded,
markProcessAsRunning,
removeBackgroundedProcess,
removeRunningProcess,
updateProcessOutput,
} from "./processTerminalStates";
// Mock ChildProcess
const createMockProcess = (
pid: number = 123,
killed: boolean = false,
): jest.Mocked<ChildProcess> => {
const mockProcess = {
pid,
killed,
kill: jest.fn(),
} as unknown as jest.Mocked<ChildProcess>;
// Make kill() update the killed property
mockProcess.kill.mockImplementation(() => {
(mockProcess as any).killed = true;
return true;
});
return mockProcess;
};
describe("processTerminalStates", () => {
beforeEach(() => {
// Clear all running processes
const runningIds = getAllRunningProcessIds();
runningIds.forEach((id) => removeRunningProcess(id));
// Clear all backgrounded processes
const backgroundedIds = getAllBackgroundedProcessIds();
backgroundedIds.forEach((id) => removeBackgroundedProcess(id));
// Clear all timers
jest.clearAllTimers();
});
test("should mark a process as backgrounded", () => {
const toolCallId = "test-123";
markProcessAsBackgrounded(toolCallId);
expect(isProcessBackgrounded(toolCallId)).toBe(true);
});
test("should correctly identify non-backgrounded processes", () => {
const toolCallId = "test-123";
const anotherToolCallId = "test-456";
markProcessAsBackgrounded(toolCallId);
expect(isProcessBackgrounded(toolCallId)).toBe(true);
expect(isProcessBackgrounded(anotherToolCallId)).toBe(false);
});
test("should remove a process from backgrounded state", () => {
const toolCallId = "test-123";
markProcessAsBackgrounded(toolCallId);
expect(isProcessBackgrounded(toolCallId)).toBe(true);
removeBackgroundedProcess(toolCallId);
expect(isProcessBackgrounded(toolCallId)).toBe(false);
});
test("should handle removing non-existent processes", () => {
const toolCallId = "test-123";
// Should not throw an error
removeBackgroundedProcess(toolCallId);
expect(isProcessBackgrounded(toolCallId)).toBe(false);
});
test("should handle multiple processes", () => {
const toolCallId1 = "test-123";
const toolCallId2 = "test-456";
const toolCallId3 = "test-789";
markProcessAsBackgrounded(toolCallId1);
markProcessAsBackgrounded(toolCallId2);
expect(isProcessBackgrounded(toolCallId1)).toBe(true);
expect(isProcessBackgrounded(toolCallId2)).toBe(true);
expect(isProcessBackgrounded(toolCallId3)).toBe(false);
removeBackgroundedProcess(toolCallId1);
expect(isProcessBackgrounded(toolCallId1)).toBe(false);
expect(isProcessBackgrounded(toolCallId2)).toBe(true);
});
describe("foreground process functions", () => {
test("should mark a process as running", () => {
const toolCallId = "test-123";
const mockProcess = createMockProcess();
const mockCallback = jest.fn();
const initialOutput = "initial output";
markProcessAsRunning(
toolCallId,
mockProcess,
mockCallback,
initialOutput,
);
expect(isProcessRunning(toolCallId)).toBe(true);
expect(getRunningProcess(toolCallId)).toBe(mockProcess);
});
test("should handle process without callback or initial output", () => {
const toolCallId = "test-123";
const mockProcess = createMockProcess();
markProcessAsRunning(toolCallId, mockProcess);
expect(isProcessRunning(toolCallId)).toBe(true);
expect(getRunningProcess(toolCallId)).toBe(mockProcess);
});
test("should correctly identify non-running processes", () => {
const toolCallId = "test-123";
const anotherToolCallId = "test-456";
const mockProcess = createMockProcess();
markProcessAsRunning(toolCallId, mockProcess);
expect(isProcessRunning(toolCallId)).toBe(true);
expect(isProcessRunning(anotherToolCallId)).toBe(false);
});
test("should update process output", () => {
const toolCallId = "test-123";
const mockProcess = createMockProcess();
const initialOutput = "initial";
const updatedOutput = "updated output";
markProcessAsRunning(toolCallId, mockProcess, undefined, initialOutput);
updateProcessOutput(toolCallId, updatedOutput);
// We can't directly test the output value, but we can ensure the function doesn't throw
expect(() =>
updateProcessOutput(toolCallId, updatedOutput),
).not.toThrow();
});
test("should handle updating output for non-existent process", () => {
const toolCallId = "non-existent";
expect(() =>
updateProcessOutput(toolCallId, "some output"),
).not.toThrow();
});
test("should remove a process from running state", () => {
const toolCallId = "test-123";
const mockProcess = createMockProcess();
markProcessAsRunning(toolCallId, mockProcess);
expect(isProcessRunning(toolCallId)).toBe(true);
removeRunningProcess(toolCallId);
expect(isProcessRunning(toolCallId)).toBe(false);
expect(getRunningProcess(toolCallId)).toBeUndefined();
});
test("should handle removing non-existent running processes", () => {
const toolCallId = "test-123";
expect(() => removeRunningProcess(toolCallId)).not.toThrow();
expect(isProcessRunning(toolCallId)).toBe(false);
});
test("should return undefined for non-existent running process", () => {
const toolCallId = "non-existent";
expect(getRunningProcess(toolCallId)).toBeUndefined();
});
});
describe("terminal command cancellation", () => {
beforeEach(() => {
jest.useFakeTimers();
});
afterEach(() => {
jest.useRealTimers();
});
test("should cancel a running terminal command", async () => {
const toolCallId = "test-123";
const mockProcess = createMockProcess();
markProcessAsRunning(toolCallId, mockProcess);
expect(isProcessRunning(toolCallId)).toBe(true);
await killTerminalProcess(toolCallId);
expect(mockProcess.kill).toHaveBeenCalledWith("SIGTERM");
expect(isProcessRunning(toolCallId)).toBe(false);
});
test("should handle cancelling non-existent process", async () => {
const toolCallId = "non-existent";
await expect(killTerminalProcess(toolCallId)).resolves.not.toThrow();
});
test("should handle cancelling already killed process", async () => {
const toolCallId = "test-123";
const mockProcess = createMockProcess(123, true); // Already killed
markProcessAsRunning(toolCallId, mockProcess);
await killTerminalProcess(toolCallId);
expect(mockProcess.kill).not.toHaveBeenCalled();
});
test("should send SIGKILL after timeout if process not killed", async () => {
const toolCallId = "test-123";
const mockProcess = createMockProcess();
// Mock kill to not actually set killed=true for SIGTERM
mockProcess.kill.mockImplementation((signal) => {
if (signal === "SIGKILL") {
(mockProcess as any).killed = true;
}
return true;
});
markProcessAsRunning(toolCallId, mockProcess);
const cancelPromise = killTerminalProcess(toolCallId);
// Fast-forward time to trigger the timeout
jest.advanceTimersByTime(5000);
await cancelPromise;
expect(mockProcess.kill).toHaveBeenCalledWith("SIGTERM");
expect(mockProcess.kill).toHaveBeenCalledWith("SIGKILL");
});
test("should not send SIGKILL if process was already killed", async () => {
const toolCallId = "test-123";
const mockProcess = createMockProcess();
markProcessAsRunning(toolCallId, mockProcess);
const cancelPromise = killTerminalProcess(toolCallId);
// Fast-forward time to trigger the timeout
jest.advanceTimersByTime(5000);
await cancelPromise;
expect(mockProcess.kill).toHaveBeenCalledWith("SIGTERM");
expect(mockProcess.kill).toHaveBeenCalledTimes(1); // Only SIGTERM, no SIGKILL
});
});
describe("utility functions", () => {
test("should get all running process IDs", () => {
const toolCallId1 = "test-123";
const toolCallId2 = "test-456";
const mockProcess1 = createMockProcess(123);
const mockProcess2 = createMockProcess(456);
markProcessAsRunning(toolCallId1, mockProcess1);
markProcessAsRunning(toolCallId2, mockProcess2);
const runningIds = getAllRunningProcessIds();
expect(runningIds).toContain(toolCallId1);
expect(runningIds).toContain(toolCallId2);
expect(runningIds).toHaveLength(2);
});
test("should get all backgrounded process IDs", () => {
const toolCallId1 = "test-123";
const toolCallId2 = "test-456";
markProcessAsBackgrounded(toolCallId1);
markProcessAsBackgrounded(toolCallId2);
const backgroundedIds = getAllBackgroundedProcessIds();
expect(backgroundedIds).toContain(toolCallId1);
expect(backgroundedIds).toContain(toolCallId2);
expect(backgroundedIds).toHaveLength(2);
});
test("should return empty arrays when no processes", () => {
expect(getAllRunningProcessIds()).toEqual([]);
expect(getAllBackgroundedProcessIds()).toEqual([]);
});
test("should cancel multiple terminal commands", async () => {
const toolCallId1 = "test-123";
const toolCallId2 = "test-456";
const mockProcess1 = createMockProcess(123);
const mockProcess2 = createMockProcess(456);
markProcessAsRunning(toolCallId1, mockProcess1);
markProcessAsRunning(toolCallId2, mockProcess2);
await killMultipleTerminalProcesses([toolCallId1, toolCallId2]);
expect(mockProcess1.kill).toHaveBeenCalledWith("SIGTERM");
expect(mockProcess2.kill).toHaveBeenCalledWith("SIGTERM");
expect(isProcessRunning(toolCallId1)).toBe(false);
expect(isProcessRunning(toolCallId2)).toBe(false);
});
test("should cancel all running terminal commands", async () => {
const toolCallId1 = "test-123";
const toolCallId2 = "test-456";
const mockProcess1 = createMockProcess(123);
const mockProcess2 = createMockProcess(456);
markProcessAsRunning(toolCallId1, mockProcess1);
markProcessAsRunning(toolCallId2, mockProcess2);
const cancelledIds = await killAllRunningTerminalProcesses();
expect(cancelledIds).toContain(toolCallId1);
expect(cancelledIds).toContain(toolCallId2);
expect(cancelledIds).toHaveLength(2);
expect(mockProcess1.kill).toHaveBeenCalledWith("SIGTERM");
expect(mockProcess2.kill).toHaveBeenCalledWith("SIGTERM");
expect(isProcessRunning(toolCallId1)).toBe(false);
expect(isProcessRunning(toolCallId2)).toBe(false);
});
test("should return empty array when no running commands to cancel", async () => {
const cancelledIds = await killAllRunningTerminalProcesses();
expect(cancelledIds).toEqual([]);
});
test("should clear all background processes", () => {
const toolCallId1 = "test-123";
const toolCallId2 = "test-456";
markProcessAsBackgrounded(toolCallId1);
markProcessAsBackgrounded(toolCallId2);
expect(getAllBackgroundedProcessIds()).toHaveLength(2);
clearAllBackgroundProcesses();
expect(getAllBackgroundedProcessIds()).toEqual([]);
expect(isProcessBackgrounded(toolCallId1)).toBe(false);
expect(isProcessBackgrounded(toolCallId2)).toBe(false);
});
});
});

View file

@ -0,0 +1,119 @@
import { ChildProcess } from "child_process";
// Track which processes have been backgrounded
const processTerminalBackgroundStates = new Map<string, boolean>();
// Track which foreground processes are currently running
interface RunningProcessInfo {
process: ChildProcess;
onPartialOutput?: (params: {
toolCallId: string;
contextItems: any[];
}) => void;
currentOutput: string;
}
const processTerminalForegroundStates = new Map<string, RunningProcessInfo>();
// Background process functions (existing)
export function markProcessAsBackgrounded(toolCallId: string): void {
processTerminalBackgroundStates.set(toolCallId, true);
}
export function isProcessBackgrounded(toolCallId: string): boolean {
return processTerminalBackgroundStates.has(toolCallId);
}
export function removeBackgroundedProcess(toolCallId: string): void {
processTerminalBackgroundStates.delete(toolCallId);
}
// Foreground process functions (new)
export function markProcessAsRunning(
toolCallId: string,
process: ChildProcess,
onPartialOutput?: (params: {
toolCallId: string;
contextItems: any[];
}) => void,
currentOutput: string = "",
): void {
processTerminalForegroundStates.set(toolCallId, {
process,
onPartialOutput,
currentOutput,
});
}
export function isProcessRunning(toolCallId: string): boolean {
return processTerminalForegroundStates.has(toolCallId);
}
export function getRunningProcess(
toolCallId: string,
): ChildProcess | undefined {
const info = processTerminalForegroundStates.get(toolCallId);
return info?.process;
}
export function updateProcessOutput(toolCallId: string, output: string): void {
const info = processTerminalForegroundStates.get(toolCallId);
if (info) {
info.currentOutput = output;
}
}
export function removeRunningProcess(toolCallId: string): void {
processTerminalForegroundStates.delete(toolCallId);
}
export async function killTerminalProcess(toolCallId: string): Promise<void> {
const processInfo = processTerminalForegroundStates.get(toolCallId);
if (processInfo && !processInfo.process.killed) {
const { process } = processInfo;
process.kill("SIGTERM");
// Force kill after 5 seconds if still running
setTimeout(() => {
if (!process.killed) {
process.kill("SIGKILL");
}
}, 5000);
processTerminalForegroundStates.delete(toolCallId);
}
}
// Function to cancel multiple terminal commands at once
export async function killMultipleTerminalProcesses(
toolCallIds: string[],
): Promise<void> {
const cancelPromises = toolCallIds.map((toolCallId) =>
killTerminalProcess(toolCallId),
);
await Promise.all(cancelPromises);
}
// Function to cancel ALL currently running terminal commands
export async function killAllRunningTerminalProcesses(): Promise<string[]> {
const runningIds = getAllRunningProcessIds();
if (runningIds.length > 0) {
await killMultipleTerminalProcesses(runningIds);
}
return runningIds; // Return the IDs that were cancelled
}
// Utility functions
export function getAllRunningProcessIds(): string[] {
return Array.from(processTerminalForegroundStates.keys());
}
export function getAllBackgroundedProcessIds(): string[] {
return Array.from(processTerminalBackgroundStates.keys());
}
// Utility function for testing - clears all background process states
export function clearAllBackgroundProcesses(): void {
processTerminalBackgroundStates.clear();
}

View file

@ -1,7 +1,7 @@
#!/usr/bin/env node
import * as esbuild from "esbuild";
import { chmodSync, writeFileSync } from "fs";
import { chmodSync, writeFileSync, copyFileSync } from "fs";
import { dirname, resolve } from "path";
import { fileURLToPath } from "url";
@ -13,6 +13,7 @@ const __dirname = dirname(fileURLToPath(import.meta.url));
const external = [
"@sentry/profiling-node", // Contains native profiler bindings (optional)
"fsevents", // macOS native file watcher (optional dependency)
"./xhr-sync-worker.js", // JSDOM worker file that needs to be copied separately
];
console.log("Building CLI with esbuild...");
@ -84,6 +85,16 @@ const require = createRequire(import.meta.url);`,
// Write metafile for analysis
writeFileSync("dist/meta.json", JSON.stringify(result.metafile, null, 2));
// Copy worker files needed by JSDOM
const workerSource = resolve(__dirname, "node_modules/jsdom/lib/jsdom/living/xhr/xhr-sync-worker.js");
const workerDest = resolve(__dirname, "dist/xhr-sync-worker.js");
try {
copyFileSync(workerSource, workerDest);
console.log("✓ Copied xhr-sync-worker.js");
} catch (error) {
console.warn("Warning: Could not copy xhr-sync-worker.js:", error.message);
}
// Create wrapper script with shebang
writeFileSync("dist/cn.js", "#!/usr/bin/env node\nimport('./index.js');");

View file

@ -65,7 +65,11 @@ export const SYSTEM_SLASH_COMMANDS: SystemCommand[] = [
description: "Manage MCP server connections",
category: "system",
},
{
name: "init",
description: "Create an AGENTS.md file",
category: "system",
},
{
name: "compact",
description: "Summarize chat history into a compact form",

View file

@ -0,0 +1,45 @@
import { type AssistantConfig } from "@continuedev/sdk";
import { SlashCommandResult } from "../ui/hooks/useChat.types.js";
function createInitPrompt(): string {
return `Please analyze this repository and create a comprehensive AGENTS.md file. Use your available tools to understand the project structure, read important files like README.md, package.json, requirements.txt, and other configuration files to understand the technology stack and setup.
Create an AGENTS.md file with the following structure:
# Repository Overview
## Project Description
- What this project does
- Main purpose and goals
- Key technologies used
## Architecture Overview
- High-level architecture
- Main components and their relationships
- Data flow and system interactions
## Directory Structure
- Important directories and their purposes
- Key files and configuration
- Entry points and main modules
## Development Workflow
- How to build/run the project
- Testing approach
- Development environment setup
- Lint and format commands
Please create the AGENTS.md file using the Write tool after analyzing the repository. Focus on providing actionable information that would help both AI agents and human developers understand and work effectively with this codebase. Keep the file concise but informational.`;
}
export async function handleInit(
_args: string[],
_assistant: AssistantConfig,
): Promise<SlashCommandResult> {
const prompt = createInitPrompt();
return {
newInput: prompt,
};
}

View file

@ -236,6 +236,71 @@ describe("remote command", () => {
prompt: "test prompt",
idempotencyKey: testIdempotencyKey,
branchName: testBranch,
agent: undefined,
config: undefined,
});
});
it("should include config in request body when config option is provided", async () => {
const testConfig = "test-config-path";
await remote("test prompt", { config: testConfig });
expect(mockFetch).toHaveBeenCalledWith(
new URL("agents/devboxes", mockEnv.env.apiBase),
expect.objectContaining({
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-token",
},
body: expect.stringContaining(`"config":"${testConfig}"`),
}),
);
expect(mockFetch).toHaveBeenCalledWith(
new URL("agents/devboxes", mockEnv.env.apiBase),
expect.objectContaining({
body: expect.stringContaining(`"agent":"${testConfig}"`),
}),
);
});
it("should handle proper request body structure with config field", async () => {
const testConfig = "my-agent-config";
const testIdempotencyKey = "test-with-config";
await remote("test prompt", {
config: testConfig,
idempotencyKey: testIdempotencyKey,
});
const fetchCall = mockFetch.mock.calls[0];
const requestBody = JSON.parse(fetchCall[1].body);
expect(requestBody).toEqual({
repoUrl: "https://github.com/user/test-repo.git",
name: expect.stringMatching(/^devbox-\d+$/),
prompt: "test prompt",
idempotencyKey: testIdempotencyKey,
agent: testConfig,
config: testConfig,
});
});
it("should not include config in request body when config option is not provided", async () => {
await remote("test prompt", {});
const fetchCall = mockFetch.mock.calls[0];
const requestBody = JSON.parse(fetchCall[1].body);
expect(requestBody).toEqual({
repoUrl: "https://github.com/user/test-repo.git",
name: expect.stringMatching(/^devbox-\d+$/),
prompt: "test prompt",
idempotencyKey: undefined,
agent: undefined,
config: undefined,
});
});

View file

@ -16,6 +16,7 @@ export async function remote(
start?: boolean;
branch?: string;
repo?: string;
config?: string;
} = {},
) {
// Check if prompt should come from stdin instead of parameter
@ -84,6 +85,8 @@ export async function remote(
name: `devbox-${Date.now()}`,
prompt: actualPrompt,
idempotencyKey: options.idempotencyKey,
agent: options.config,
config: options.config,
};
// Add branchName to request body if branch option is provided

View file

@ -113,7 +113,7 @@ program
.description(
"Continue CLI - AI-powered development assistant. Starts an interactive session by default, use -p/--print for non-interactive output.",
)
.version(getVersion());
.version(getVersion(), "-v, --version", "Display version number");
// Root command - chat functionality (default)
// Add common options to the root command
@ -254,9 +254,11 @@ program
});
// Remote subcommand
program
.command("remote [prompt]", { hidden: true })
.description("Launch a remote instance of the cn agent")
addCommonOptions(
program
.command("remote [prompt]", { hidden: true })
.description("Launch a remote instance of the cn agent"),
)
.option(
"--url <url>",
"Connect directly to the specified URL instead of creating a new remote environment",

View file

@ -3,10 +3,11 @@
* This file intercepts console and stdout/stderr to prevent dependency logging
*/
import { isHeadlessMode as checkIsHeadlessMode } from "./util/cli.js";
// Check if we're in headless mode by looking at process arguments
// We need to do this before any imports to catch early logging
const args = process.argv.slice(2);
const isHeadlessMode = args.includes("-p") || args.includes("--print");
const isHeadlessMode = checkIsHeadlessMode();
// Store original methods before ANY dependencies can use them
const originalStdoutWrite = process.stdout.write.bind(process.stdout);

View file

@ -3,6 +3,7 @@ import { glob, GlobOptionsWithFileTypesFalse } from "glob";
import { FILE_IGNORE_PATTERNS, FILE_PATTERNS } from "../util/filePatterns.js";
import { getFileWatcher } from "../util/fileWatcher.js";
import { isGitRepo } from "../util/git.js";
import { isInHomeDirectory } from "../util/isInHomeDirectory.js";
import { logger } from "../util/logger.js";
import { BaseService } from "./BaseService.js";
@ -69,6 +70,15 @@ export class FileIndexService extends BaseService<FileIndexServiceState> {
try {
const inGitRepo = isGitRepo();
if (isInHomeDirectory()) {
this.setState({
isIndexing: false,
error: "Skipping full index as in home directory",
});
return;
}
const allMatches = await this.throttledGlob(FILE_PATTERNS, {
maxDepth: inGitRepo ? 15 : 3,
ignore: FILE_IGNORE_PATTERNS,

View file

@ -13,7 +13,7 @@ export function addCommonOptions(command: Command): Command {
)
.option("--readonly", "Start in plan mode (read-only tools)")
.option("--auto", "Start in auto mode (all tools allowed)")
.option("-v, --verbose", "Enable verbose logging")
.option("--verbose", "Enable verbose logging")
.option(
"--rule <rule>",
"Add a rule (can be a file path, hub slug, or string content). Can be specified multiple times.",

View file

@ -7,6 +7,7 @@ import {
loadAuthConfig,
} from "./auth/workos.js";
import { getAllSlashCommands } from "./commands/commands.js";
import { handleInit } from "./commands/init.js";
import { handleInfoSlashCommand } from "./infoScreen.js";
import { reloadService, SERVICE_NAMES, services } from "./services/index.js";
import { getCurrentSession } from "./session.js";
@ -176,6 +177,10 @@ const commandHandlers: Record<string, CommandHandler> = {
return { openSessionSelector: true };
},
fork: handleFork,
init: (args, assistant) => {
posthogService.capture("useSlashCommand", { name: "init" });
return handleInit(args, assistant);
},
};
export async function handleSlashCommands(

View file

@ -5,6 +5,7 @@ import node_machine_id from "node-machine-id";
import type { PostHog as PostHogType } from "posthog-node";
import { isAuthenticatedConfig, loadAuthConfig } from "../auth/workos.js";
import { isHeadlessMode } from "../util/cli.js";
import { isGitHubActions } from "../util/git.js";
import { logger } from "../util/logger.js";
import { getVersion } from "../version.js";
@ -38,14 +39,6 @@ export class PosthogService {
return this._hasInternetConnection;
}
/**
* Check if running in headless mode (-p/--print flags)
*/
private isHeadlessMode(): boolean {
const args = process.argv.slice(2);
return args.includes("-p") || args.includes("--print");
}
get isEnabled() {
return process.env.CONTINUE_CLI_ENABLE_TELEMETRY !== "0";
}
@ -100,7 +93,7 @@ export class PosthogService {
extensionVersion: getVersion(),
ideName: "cn",
ideType: "cli",
isHeadless: this.isHeadlessMode(),
isHeadless: isHeadlessMode(),
isGitHubCI: isGitHubActions(),
};
const payload = {

View file

@ -0,0 +1,238 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { telemetryService } from "./telemetryService.js";
describe("TelemetryService - Session Metadata", () => {
let originalEnv: NodeJS.ProcessEnv;
let originalArgv: string[];
beforeEach(() => {
// Save original environment and argv
originalEnv = { ...process.env };
originalArgv = [...process.argv];
// Mock logger to prevent console output during tests
vi.mock("../util/logger.js", () => ({
logger: {
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
},
}));
// Enable telemetry for tests
process.env.CONTINUE_CLI_ENABLE_TELEMETRY = "1";
process.env.OTEL_METRICS_EXPORTER = "console";
});
afterEach(() => {
// Restore original environment and argv
process.env = originalEnv;
process.argv = originalArgv;
vi.clearAllMocks();
});
describe("recordSessionStart", () => {
it("should include is_headless=false when not in headless mode", () => {
// Set up non-headless mode (no -p or --print flags)
process.argv = ["node", "cli.js", "chat"];
const mockAdd = vi.fn();
const mockRecord = vi.fn();
const service = telemetryService as any;
// Mock the session counter and startup time histogram
service.sessionCounter = { add: mockAdd };
service.startupTimeHistogram = { record: mockRecord };
service.config = { enabled: true };
service.meter = {};
service.recordSessionStart();
expect(mockAdd).toHaveBeenCalledWith(
1,
expect.objectContaining({
is_headless: "false",
}),
);
});
it("should include is_headless=true when -p flag is present", () => {
// Set up headless mode with -p flag
process.argv = ["node", "cli.js", "-p", "What is the weather?"];
const mockAdd = vi.fn();
const mockRecord = vi.fn();
const service = telemetryService as any;
// Mock the session counter and startup time histogram
service.sessionCounter = { add: mockAdd };
service.startupTimeHistogram = { record: mockRecord };
service.config = { enabled: true };
service.meter = {};
service.recordSessionStart();
expect(mockAdd).toHaveBeenCalledWith(
1,
expect.objectContaining({
is_headless: "true",
}),
);
});
it("should include is_headless=true when --print flag is present", () => {
// Set up headless mode with --print flag
process.argv = ["node", "cli.js", "--print", "What is the weather?"];
const mockAdd = vi.fn();
const mockRecord = vi.fn();
const service = telemetryService as any;
// Mock the session counter and startup time histogram
service.sessionCounter = { add: mockAdd };
service.startupTimeHistogram = { record: mockRecord };
service.config = { enabled: true };
service.meter = {};
service.recordSessionStart();
expect(mockAdd).toHaveBeenCalledWith(
1,
expect.objectContaining({
is_headless: "true",
}),
);
});
it("should include is_github_actions=false when not in GitHub Actions", () => {
// Ensure GITHUB_ACTIONS is not set
delete process.env.GITHUB_ACTIONS;
const mockAdd = vi.fn();
const mockRecord = vi.fn();
const service = telemetryService as any;
// Mock the session counter and startup time histogram
service.sessionCounter = { add: mockAdd };
service.startupTimeHistogram = { record: mockRecord };
service.config = { enabled: true };
service.meter = {};
service.recordSessionStart();
expect(mockAdd).toHaveBeenCalledWith(
1,
expect.objectContaining({
is_github_actions: "false",
is_continue_remote_agent: "false",
}),
);
});
it("should include is_github_actions=true when in GitHub Actions", () => {
// Set GitHub Actions environment
process.env.GITHUB_ACTIONS = "true";
const mockAdd = vi.fn();
const mockRecord = vi.fn();
const service = telemetryService as any;
// Mock the session counter and startup time histogram
service.sessionCounter = { add: mockAdd };
service.startupTimeHistogram = { record: mockRecord };
service.config = { enabled: true };
service.meter = {};
service.recordSessionStart();
expect(mockAdd).toHaveBeenCalledWith(
1,
expect.objectContaining({
is_github_actions: "true",
is_continue_remote_agent: "false",
}),
);
});
it("should include both headless and GitHub Actions metadata when both are true", () => {
// Set both headless mode and GitHub Actions
process.argv = ["node", "cli.js", "-p", "What is the weather?"];
process.env.GITHUB_ACTIONS = "true";
const mockAdd = vi.fn();
const mockRecord = vi.fn();
const service = telemetryService as any;
// Mock the session counter and startup time histogram
service.sessionCounter = { add: mockAdd };
service.startupTimeHistogram = { record: mockRecord };
service.config = { enabled: true };
service.meter = {};
service.recordSessionStart();
expect(mockAdd).toHaveBeenCalledWith(
1,
expect.objectContaining({
is_headless: "true",
is_github_actions: "true",
is_continue_remote_agent: "false",
}),
);
});
it("should include is_continue_remote_agent=true when in remote agent mode", () => {
// Set Continue remote agent environment
process.env.CONTINUE_REMOTE = "true";
const mockAdd = vi.fn();
const mockRecord = vi.fn();
const service = telemetryService as any;
// Mock the session counter and startup time histogram
service.sessionCounter = { add: mockAdd };
service.startupTimeHistogram = { record: mockRecord };
service.config = { enabled: true };
service.meter = {};
service.recordSessionStart();
expect(mockAdd).toHaveBeenCalledWith(
1,
expect.objectContaining({
is_continue_remote_agent: "true",
}),
);
});
it("should include all environment flags when all are true", () => {
// Set all environments
process.argv = ["node", "cli.js", "-p", "What is the weather?"];
process.env.GITHUB_ACTIONS = "true";
process.env.CONTINUE_REMOTE = "true";
const mockAdd = vi.fn();
const mockRecord = vi.fn();
const service = telemetryService as any;
// Mock the session counter and startup time histogram
service.sessionCounter = { add: mockAdd };
service.startupTimeHistogram = { record: mockRecord };
service.config = { enabled: true };
service.meter = {};
service.recordSessionStart();
expect(mockAdd).toHaveBeenCalledWith(
1,
expect.objectContaining({
is_headless: "true",
is_github_actions: "true",
is_continue_remote_agent: "true",
}),
);
});
});
});

View file

@ -19,6 +19,8 @@ import {
} from "@opentelemetry/semantic-conventions";
import { v4 as uuidv4 } from "uuid";
import { isHeadlessMode } from "../util/cli.js";
import { isContinueRemoteAgent, isGitHubActions } from "../util/git.js";
import { logger } from "../util/logger.js";
import { getVersion } from "../version.js";
@ -350,7 +352,16 @@ class TelemetryService {
if (!this.isEnabled()) return;
logger.debug("Recording session start with telemetry");
this.sessionCounter.add(1, this.getStandardAttributes());
// Add extra metadata for session breakdown
const isGitHubActionsEnv = isGitHubActions();
const sessionAttributes = this.getStandardAttributes({
is_headless: isHeadlessMode().toString(),
is_github_actions: isGitHubActionsEnv.toString(),
is_continue_remote_agent: isContinueRemoteAgent().toString(),
});
this.sessionCounter.add(1, sessionAttributes);
this.recordStartupTime(Date.now() - this.startTime);
}

View file

@ -0,0 +1,169 @@
import type { ContextItem } from "core/index.js";
import { fetchUrlContentImpl } from "core/tools/implementations/fetchUrlContent.js";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { fetchTool } from "./fetch.js";
// Mock the core fetchUrlContent implementation
vi.mock("core/tools/implementations/fetchUrlContent.js", () => ({
fetchUrlContentImpl: vi.fn(),
}));
const mockFetchUrlContentImpl = vi.mocked(fetchUrlContentImpl);
describe("fetchTool", () => {
let originalConsoleError: typeof console.error;
beforeEach(() => {
originalConsoleError = console.error;
console.error = vi.fn();
mockFetchUrlContentImpl.mockReset();
});
afterEach(() => {
console.error = originalConsoleError;
});
it("should return clean content from successful fetch", async () => {
const mockContextItems: ContextItem[] = [
{
name: "Example Page",
description: "https://example.com",
content:
"# Example Page\n\nThis is some example content from a webpage.",
uri: { type: "url", value: "https://example.com" },
},
];
mockFetchUrlContentImpl.mockResolvedValue(mockContextItems);
const result = await fetchTool.run({ url: "https://example.com" });
expect(result).toBe(
"# Example Page\n\nThis is some example content from a webpage.",
);
expect(mockFetchUrlContentImpl).toHaveBeenCalledWith(
{ url: "https://example.com" },
{ fetch },
);
});
it("should handle truncation warnings from core implementation", async () => {
const mockContextItems: ContextItem[] = [
{
name: "Long Page",
description: "https://example.com",
content: "This is the main content that was truncated.",
uri: { type: "url", value: "https://example.com" },
},
{
name: "Truncation warning",
description: "",
content:
"The content from https://example.com was truncated because it exceeded the 20000 character limit.",
},
];
mockFetchUrlContentImpl.mockResolvedValue(mockContextItems);
const result = await fetchTool.run({ url: "https://example.com" });
expect(result).toBe(
"This is the main content that was truncated.\n\nThe content from https://example.com was truncated because it exceeded the 20000 character limit.",
);
});
it("should handle multiple content items", async () => {
const mockContextItems: ContextItem[] = [
{
name: "Page 1",
description: "https://example.com",
content: "Content from page 1",
uri: { type: "url", value: "https://example.com" },
},
{
name: "Page 2",
description: "https://example.com",
content: "Content from page 2",
uri: { type: "url", value: "https://example.com" },
},
];
mockFetchUrlContentImpl.mockResolvedValue(mockContextItems);
const result = await fetchTool.run({ url: "https://example.com" });
expect(result).toBe("Content from page 1\n\nContent from page 2");
});
it("should return error message when no content items returned", async () => {
mockFetchUrlContentImpl.mockResolvedValue([]);
const result = await fetchTool.run({ url: "https://example.com" });
expect(result).toBe(
"Error: Could not fetch content from https://example.com",
);
});
it("should handle errors from core implementation", async () => {
const error = new Error("Network error");
mockFetchUrlContentImpl.mockRejectedValue(error);
const result = await fetchTool.run({ url: "https://example.com" });
expect(result).toBe("Error: Network error");
});
it("should call fetchUrlContentImpl with correct arguments", async () => {
const mockContextItems: ContextItem[] = [
{
name: "Test Page",
description: "https://example.com",
content: "Test content",
uri: { type: "url", value: "https://example.com" },
},
];
mockFetchUrlContentImpl.mockResolvedValue(mockContextItems);
await fetchTool.run({ url: "https://example.com" });
expect(mockFetchUrlContentImpl).toHaveBeenCalledWith(
{ url: "https://example.com" },
{ fetch },
);
});
it("should have correct tool metadata", () => {
expect(fetchTool.name).toBe("Fetch");
expect(fetchTool.displayName).toBe("Fetch");
expect(fetchTool.description).toBe(
"Fetches content from a URL, converts to markdown, and handles long content with truncation",
);
expect(fetchTool.readonly).toBe(true);
expect(fetchTool.isBuiltIn).toBe(true);
expect(fetchTool.parameters).toEqual({
url: {
type: "string",
description: "The URL to fetch content from",
required: true,
},
});
});
it("should provide correct preview in preprocess", async () => {
const args = { url: "https://example.com" };
const result = await fetchTool.preprocess?.(args);
expect(result).toEqual({
preview: [
{
type: "text",
content: "Will fetch: https://example.com",
},
],
args,
});
});
});

View file

@ -1,50 +1,19 @@
import TurndownService from "turndown";
import type { ContextItem } from "core/index.js";
import { fetchUrlContentImpl } from "core/tools/implementations/fetchUrlContent.js";
import { Tool } from "./types.js";
const turndownService = new TurndownService({
headingStyle: "atx",
codeBlockStyle: "fenced",
fence: "```",
emDelimiter: "*",
strongDelimiter: "**",
linkStyle: "inlined",
linkReferenceStyle: "full",
});
// Configure turndown for better markdown output
turndownService.addRule("strikethrough", {
filter: ["del", "s"],
replacement: function (content) {
return "~~" + content + "~~";
},
});
// Handle code blocks better
turndownService.addRule("pre", {
filter: "pre",
replacement: function (content, node) {
const codeEl = node.querySelector("code");
const language = codeEl?.className.match(/language-(\w+)/)?.[1] || "";
return "\n\n```" + language + "\n" + content + "\n```\n\n";
},
});
export const fetchTool: Tool = {
name: "Fetch",
displayName: "Fetch",
description: "Fetches content from a URL and converts it to markdown format",
description:
"Fetches content from a URL, converts to markdown, and handles long content with truncation",
parameters: {
url: {
type: "string",
description: "The URL to fetch content from",
required: true,
},
timeout: {
type: "number",
description: "Request timeout in milliseconds (default: 10000)",
required: false,
},
},
readonly: true,
isBuiltIn: true,
@ -59,76 +28,34 @@ export const fetchTool: Tool = {
args,
};
},
run: async (args: { url: string; timeout?: number }): Promise<string> => {
const { url, timeout = 10000 } = args;
run: async (args: { url: string }): Promise<string> => {
const { url } = args;
try {
// Validate URL
const urlObj = new URL(url);
if (!["http:", "https:"].includes(urlObj.protocol)) {
return "Error: Only HTTP and HTTPS URLs are supported";
// Suppress console errors from JSDOM CSS parsing
const originalConsoleError = console.error;
console.error = () => {};
// Use the core fetchUrlContent implementation
const contextItems = await fetchUrlContentImpl({ url }, { fetch });
// Restore console.error
console.error = originalConsoleError;
if (contextItems.length === 0) {
return `Error: Could not fetch content from ${url}`;
}
// Fetch the content
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeout);
const response = await fetch(url, {
signal: controller.signal,
headers: {
"User-Agent": "Continue-CLI/1.0 (https://continue.dev)",
Accept:
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.5",
"Accept-Encoding": "gzip, deflate",
"Cache-Control": "no-cache",
},
});
clearTimeout(timeoutId);
if (!response.ok) {
return `Error: HTTP ${response.status} - ${response.statusText}`;
}
const contentType = response.headers.get("content-type") || "";
// Handle different content types
if (contentType.includes("application/json")) {
const json = await response.json();
return "```json\n" + JSON.stringify(json, null, 2) + "\n```";
}
if (contentType.includes("text/plain")) {
const text = await response.text();
return text;
}
if (!contentType.includes("text/html")) {
return `Error: Unsupported content type: ${contentType}`;
}
// Process HTML content
const html = await response.text();
// Convert HTML to markdown
const markdown = turndownService.turndown(html);
// Clean up the markdown
const cleanedMarkdown = markdown
.replace(/\n\s*\n\s*\n/g, "\n\n") // Remove excessive newlines
.replace(/^\s+|\s+$/g, "") // Trim whitespace
.replace(/\\\[/g, "[") // Unescape brackets
.replace(/\\\]/g, "]");
return `# Content from ${url}\n\n${cleanedMarkdown}`;
// Format the results for CLI display
return contextItems
.map((item: ContextItem) => {
if (item.name === "Truncation warning") {
return item.content;
}
return item.content;
})
.join("\n\n");
} catch (error) {
if (error instanceof TypeError && error.message.includes("fetch")) {
return `Error: Failed to fetch URL "${url}". Please check the URL and try again.`;
}
if (error instanceof Error && error.name === "AbortError") {
return `Error: Request timed out after ${timeout}ms`;
}
return `Error: ${error instanceof Error ? error.message : String(error)}`;
}
},

View file

@ -1,12 +1,10 @@
import * as os from "node:os";
import * as path from "node:path";
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import { Box, Text } from "ink";
import React, { useMemo } from "react";
import { getDisplayableAsciiArt } from "../asciiArt.js";
import { MCPService } from "../services/MCPService.js";
import { isInHomeDirectory } from "../util/isInHomeDirectory.js";
import { isModelCapable } from "../utils/modelCapability.js";
import { ModelCapabilityWarning } from "./ModelCapabilityWarning.js";
@ -29,6 +27,8 @@ const extractRuleNames = (rules: any[] = []): string[] => {
);
};
const userInHomeDirectory = isInHomeDirectory();
const IntroMessage: React.FC<IntroMessageProps> = ({
config,
model,
@ -40,18 +40,6 @@ const IntroMessage: React.FC<IntroMessageProps> = ({
// Determine if we should show a tip (1 in 5 chance) - computed once on mount
const showTip = useMemo(() => shouldShowTip(), []);
// Check if current working directory is the home directory
const isInHomeDirectory = useMemo(() => {
const cwd = process.cwd();
const homedir = os.homedir();
const resolvedCwd = path.resolve(cwd);
const resolvedHome = path.resolve(homedir);
if (process.platform === "win32") {
return resolvedCwd.toLowerCase() === resolvedHome.toLowerCase();
}
return resolvedCwd === resolvedHome;
}, []);
// Memoize expensive operations to avoid running on every resize
const { allRules, modelCapable } = useMemo(() => {
const allRules = extractRuleNames(config?.rules);
@ -153,7 +141,7 @@ const IntroMessage: React.FC<IntroMessageProps> = ({
{renderMcpServers()}
{/* Home directory warning */}
{isInHomeDirectory && (
{userInHomeDirectory && (
<>
<Text color="yellow">{HOME_DIRECTORY_WARNING}</Text>
<Text> </Text>

View file

@ -0,0 +1,36 @@
import { render } from "ink-testing-library";
import React from "react";
import { MarkdownRenderer } from "./MarkdownRenderer.js";
describe("MarkdownRenderer - thinking tags", () => {
it("handles multiple thinking tags", () => {
const content =
"Text <think>First thought</think> middle <think>Second thought</think> end";
const { lastFrame } = render(<MarkdownRenderer content={content} />);
expect(lastFrame()).toContain("First thought");
expect(lastFrame()).toContain("Second thought");
});
it("handles thinking tags with multiline content", () => {
const content = `<think>
This is a multiline
thinking block
</think>`;
const { lastFrame } = render(<MarkdownRenderer content={content} />);
expect(lastFrame()).toContain("This is a multiline");
expect(lastFrame()).toContain("thinking block");
});
it("ignores thinking tags inside code blocks", () => {
const content = "```\n<think>This should not be processed</think>\n```";
const { lastFrame } = render(<MarkdownRenderer content={content} />);
// The thinking tag should appear as literal text within the code block
expect(lastFrame()).toContain(
"<think>This should not be processed</think>",
);
});
});

View file

@ -2,10 +2,10 @@ import { Text } from "ink";
import React from "react";
import {
highlightCode,
detectLanguage,
SyntaxHighlighterTheme,
defaultTheme,
detectLanguage,
highlightCode,
SyntaxHighlighterTheme,
} from "./SyntaxHighlighter.js";
interface MarkdownRendererProps {
@ -28,6 +28,14 @@ const MarkdownRenderer: React.FC<MarkdownRendererProps> = React.memo(
return null; // This will be handled separately
},
},
{
regex: /<think>([\s\S]*?)<\/think>/g,
render: (content, key) => (
<Text key={key} color="gray">
{content.trim()}
</Text>
),
},
{
regex: /^(#{1,6})\s+(.+)$/gm,
render: (content, key) => (
@ -225,6 +233,5 @@ const MarkdownRenderer: React.FC<MarkdownRendererProps> = React.memo(
MarkdownRenderer.displayName = "MarkdownRenderer";
export { MarkdownRenderer };
export { defaultTheme, MarkdownRenderer };
export type { SyntaxHighlighterTheme };
export { defaultTheme };

View file

@ -9,6 +9,7 @@ const CONTINUE_CLI_TIPS = [
'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."`',
"Use the /init slash command to generate an AGENTS.md file. This will help `cn` understand your codebase and generate better responses.",
];
interface TipsDisplayProps {

View file

@ -13,6 +13,13 @@ vi.mock("../../index.js", () => ({
setExitMessageCallback: vi.fn(),
}));
// Mock git utility functions
vi.mock("../../util/git.js", () => ({
isGitRepo: vi.fn(() => false),
getGitRemoteUrl: vi.fn(() => null),
getGitBranch: vi.fn(() => null),
}));
describe("BottomStatusBar Ctrl+C message", () => {
const defaultProps: BottomStatusBarProps = {
currentMode: "normal" as const,

View file

@ -0,0 +1,11 @@
/**
* Utility functions for CLI operations
*/
/**
* Check if running in headless mode (-p/--print flags)
*/
export function isHeadlessMode(): boolean {
const args = process.argv.slice(2);
return args.includes("-p") || args.includes("--print");
}

View file

@ -57,6 +57,13 @@ export function isGitHubActions(): boolean {
return process.env.GITHUB_ACTIONS === "true";
}
/**
* Check if running in Continue remote agents
*/
export function isContinueRemoteAgent(): boolean {
return process.env.CONTINUE_REMOTE === "true";
}
/**
* Get repository URL from GitHub Actions environment variables
* @returns GitHub repository URL or null if not available

View file

@ -0,0 +1,85 @@
// eslint-disable-next-line import/order
import { vi } from "vitest";
vi.mock("node:os", () => ({
default: {
homedir: vi.fn(),
},
}));
vi.mock("node:path", () => ({
default: {
resolve: vi.fn(),
},
}));
import os from "node:os";
import path from "node:path";
import { isInHomeDirectory } from "./isInHomeDirectory.js";
describe("isInHomeDirectory", () => {
const originalCwd = process.cwd;
const originalPlatform = process.platform;
beforeEach(() => {
vi.clearAllMocks();
process.cwd = vi.fn();
});
afterEach(() => {
process.cwd = originalCwd;
Object.defineProperty(process, "platform", {
value: originalPlatform,
writable: true,
});
});
it("should return true when current directory is home directory on Unix", () => {
Object.defineProperty(process, "platform", {
value: "linux",
writable: true,
});
const mockCwd = "/home/user";
const mockHome = "/home/user";
vi.mocked(process.cwd).mockReturnValue(mockCwd);
vi.mocked(os.homedir).mockReturnValue(mockHome);
vi.mocked(path.resolve).mockImplementation((p: string) => p);
expect(isInHomeDirectory()).toBe(true);
});
it("should return false when current directory is not home directory on Unix", () => {
Object.defineProperty(process, "platform", {
value: "linux",
writable: true,
});
const mockCwd = "/home/user/projects";
const mockHome = "/home/user";
vi.mocked(process.cwd).mockReturnValue(mockCwd);
vi.mocked(os.homedir).mockReturnValue(mockHome);
vi.mocked(path.resolve).mockImplementation((p: string) => p);
expect(isInHomeDirectory()).toBe(false);
});
it("should return true when current directory is home directory on Windows (case insensitive)", () => {
Object.defineProperty(process, "platform", {
value: "win32",
writable: true,
});
const mockCwd = "C:\\Users\\User";
const mockHome = "c:\\users\\user";
vi.mocked(process.cwd).mockReturnValue(mockCwd);
vi.mocked(os.homedir).mockReturnValue(mockHome);
vi.mocked(path.resolve).mockImplementation((p: string) => p);
expect(isInHomeDirectory()).toBe(true);
});
});

View file

@ -0,0 +1,13 @@
import os from "node:os";
import path from "node:path";
export function isInHomeDirectory(): boolean {
const cwd = process.cwd();
const homedir = os.homedir();
const resolvedCwd = path.resolve(cwd);
const resolvedHome = path.resolve(homedir);
if (process.platform === "win32") {
return resolvedCwd.toLowerCase() === resolvedHome.toLowerCase();
}
return resolvedCwd === resolvedHome;
}

View file

@ -146,6 +146,7 @@ class MessageTypes {
"isItemTooBig",
"process/markAsBackgrounded",
"process/isBackgrounded",
"process/killTerminalProcess"
)
}
}

View file

@ -46,7 +46,7 @@ class ApplyToFileHandler(
}
// Handle search/replace mode
if (params.isSearchReplace == true) {
if (params.isSearchAndReplace == true) {
handleSearchReplace(editorUtils)
return
}

View file

@ -9,7 +9,7 @@ data class ApplyToFileParams(
val streamId: String,
val filepath: String?,
val toolCallId: String?,
val isSearchReplace: Boolean? = null
val isSearchAndReplace: Boolean? = null
)
data class InsertAtCursorParams(

View file

@ -151,9 +151,9 @@
<action id="continue.openConfigPage"
class="com.github.continuedev.continueintellijextension.actions.OpenConfigAction"
icon="AllIcons.General.GearPlain"
text="Continue Config"
description="Continue Config">
<override-text place="GoToAction" text="Continue Config"/>
text="Settings"
description="Settings">
<override-text place="GoToAction" text="Settings"/>
</action>
<action id="continue.openLogs"

View file

@ -136,10 +136,22 @@ export class GUIActions {
toolName: string,
desiredState: number | string,
) {
const toolButton = await TestUtils.waitForSuccess(() =>
GUISelectors.getToolButton(view),
// Navigate to config page
const settingsButton = await TestUtils.waitForSuccess(() =>
GUISelectors.getSettingsNavButton(view),
);
await toolButton.click();
await settingsButton.click();
await TestUtils.waitForTimeout(500);
// Click on tools tab
const toolsTab = await TestUtils.waitForSuccess(() =>
GUISelectors.getToolsTab(view),
);
await toolsTab.click();
await TestUtils.waitForTimeout(500);
// Find and click the tool policy button
const toolPolicyButton = await TestUtils.waitForSuccess(() =>
GUISelectors.getToolPolicyButton(view, toolName),
);
@ -181,5 +193,12 @@ export class GUIActions {
`Failed to set tool policy to ${targetStates.join(" or ")} after 5 attempts`,
);
}
// Navigate back to chat
const backButton = await TestUtils.waitForSuccess(() =>
GUISelectors.getBackButton(view),
);
await backButton.click();
await TestUtils.waitForTimeout(500);
}
}

View file

@ -47,11 +47,12 @@ export class GUISelectors {
return SelectorUtils.getElementByDataTestId(view, "tool-call-title");
}
public static getToolButton(view: WebView) {
return SelectorUtils.getElementByDataTestId(
view,
`block-settings-toolbar-icon-tools`,
);
public static getToolsTab(view: WebView) {
return SelectorUtils.getElementByDataTestId(view, "tab-tools");
}
public static getBackButton(view: WebView) {
return SelectorUtils.getElementByDataTestId(view, "tab-back");
}
public static getToolPolicyButton(view: WebView, toolName: string) {
@ -150,6 +151,10 @@ export class GUISelectors {
return SelectorUtils.getElementByAriaLabel(view, "View History");
}
public static getSettingsNavButton(view: WebView) {
return SelectorUtils.getElementByAriaLabel(view, "Open Settings");
}
public static getNewSessionNavButton(view: WebView) {
return SelectorUtils.getElementByAriaLabel(view, "New Session");
}

View file

@ -16,7 +16,7 @@ import { DEFAULT_TIMEOUT } from "../constants";
import { GUISelectors } from "../selectors/GUI.selectors";
import { TestUtils } from "../TestUtils";
describe("GUI Test", () => {
describe.skip("GUI Test", () => {
let view: WebView;
let driver: WebDriver;

View file

@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
"version": "1.3.6",
"version": "1.3.7",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"
@ -210,13 +210,6 @@
"title": "Exit Edit Mode",
"group": "Continue"
},
{
"command": "continue.toggleFullScreen",
"category": "Continue",
"title": "Open in new window",
"icon": "$(link-external)",
"group": "Continue"
},
{
"command": "continue.openConfigPage",
"category": "Continue",
@ -444,12 +437,6 @@
"mac": "cmd+shift+r",
"key": "ctrl+shift+r"
},
{
"command": "continue.toggleFullScreen",
"mac": "cmd+k cmd+m",
"key": "ctrl+k ctrl+m",
"when": "!terminalFocus"
},
{
"command": "continue.toggleTabAutocompleteEnabled",
"mac": "cmd+k cmd+a",
@ -511,9 +498,6 @@
{
"command": "continue.debugTerminal"
},
{
"command": "continue.toggleFullScreen"
},
{
"command": "continue.newSession"
},
@ -566,11 +550,6 @@
"group": "navigation@2",
"when": "view == continue.continueGUIView"
},
{
"command": "continue.toggleFullScreen",
"group": "navigation@3",
"when": "view == continue.continueGUIView"
},
{
"command": "continue.openConfigPage",
"group": "navigation@4",

View file

@ -7,6 +7,9 @@ import { ApplyToFilePayload } from "core";
import { myersDiff } from "core/diff/myers";
import { generateLines } from "core/diff/util";
import { ApplyAbortManager } from "core/edit/applyAbortManager";
import { streamDiffLines } from "core/edit/streamDiffLines";
import { pruneLinesFromBottom, pruneLinesFromTop } from "core/llm/countTokens";
import { getMarkdownLanguageTagForFile } from "core/util";
import { VerticalDiffManager } from "../diff/vertical/manager";
import { VsCodeIde } from "../VsCodeIde";
import { VsCodeWebviewProtocol } from "../webviewProtocol";
@ -92,6 +95,10 @@ export class ApplyManager {
await this.ide.openFile(filepath);
}
private modelIsTooFastForStreaming(model: string): boolean {
return [/mercury/].some((r) => r.test(model));
}
private async handleEmptyDocument(
editor: vscode.TextEditor,
text: string,
@ -159,6 +166,7 @@ export class ApplyManager {
streamId,
this.verticalDiffManager,
toolCallId,
!this.modelIsTooFastForStreaming(llm.model),
);
}
}
@ -170,6 +178,37 @@ export class ApplyManager {
return `The following code was suggested as an edit:\n\`\`\`\n${text}\n\`\`\`\nPlease apply it to the previous code.`;
}
/**
* Calculates prefix and suffix for a given range, shared between streaming and non-streaming modes
*/
private calculatePrefixSuffix(
editor: vscode.TextEditor,
range: vscode.Range,
llm: any,
): { prefix: string; suffix: string; rangeContent: string } {
const rangeContent = editor.document.getText(range);
const prefix = pruneLinesFromTop(
editor.document.getText(
new vscode.Range(new vscode.Position(0, 0), range.start),
),
llm.contextLength / 4,
llm.model,
);
const suffix = pruneLinesFromBottom(
editor.document.getText(
new vscode.Range(
range.end,
new vscode.Position(editor.document.lineCount, 0),
),
),
llm.contextLength / 4,
llm.model,
);
return { prefix, suffix, rangeContent };
}
private async handleNonInstantDiff(
editor: vscode.TextEditor,
text: string,
@ -177,6 +216,7 @@ export class ApplyManager {
streamId: string,
verticalDiffManager: VerticalDiffManager,
toolCallId?: string,
streaming: boolean = true,
) {
const { config } = await this.configHandler.loadConfig();
if (!config) {
@ -195,14 +235,93 @@ export class ApplyManager {
? fullEditorRange
: editor.selection;
await verticalDiffManager.streamEdit({
input: prompt,
if (streaming) {
await verticalDiffManager.streamEdit({
input: prompt,
llm,
streamId,
range: rangeToApplyTo,
newCode: text,
toolCallId,
rulesToInclude: undefined, // No rules for apply
});
} else {
// Non-streaming: accumulate LLM output, then apply via Myers diff
const finalContent = await this.generateAppliedContent(
editor,
prompt,
llm,
rangeToApplyTo,
text,
);
if (finalContent) {
const diffLinesGenerator = generateLines(
myersDiff(editor.document.getText(), finalContent),
);
await verticalDiffManager.streamDiffLines(
diffLinesGenerator,
true, // Apply instantly since we accumulated all content
streamId,
toolCallId,
);
}
}
}
/**
* Generates the final applied content by accumulating all LLM output
* Similar to streamEdit but collects all output before applying
*/
private async generateAppliedContent(
editor: vscode.TextEditor,
prompt: string,
llm: any,
range: vscode.Range,
newCode: string,
): Promise<string | undefined> {
const fileUri = editor.document.uri.toString();
const { prefix, suffix, rangeContent } = this.calculatePrefixSuffix(
editor,
range,
llm,
streamId,
range: rangeToApplyTo,
newCode: text,
toolCallId,
rulesToInclude: undefined, // No rules for apply
});
);
const abortManager = ApplyAbortManager.getInstance();
const abortController = abortManager.get(fileUri);
try {
const streamedLines: string[] = [];
// Use streamDiffLines to get the LLM output
const stream = streamDiffLines({
highlighted: rangeContent,
prefix,
suffix,
llm,
rulesToInclude: undefined, // No rules for apply
input: prompt,
language: getMarkdownLanguageTagForFile(fileUri),
overridePrompt: undefined,
abortController,
});
// Accumulate all the streamed content
for await (const line of stream) {
if (abortController.signal.aborted) {
return undefined;
}
if (line.type === "new" || line.type === "same") {
streamedLines.push(line.line);
}
}
// Return the complete file content
return `${prefix}${streamedLines.join("\n")}${suffix}`;
} catch (error) {
console.error("Error generating applied content:", error);
return undefined;
}
}
}

View file

@ -45,15 +45,6 @@ import { getMetaKeyLabel } from "./util/util";
import { openEditorAndRevealRange } from "./util/vscode";
import { VsCodeIde } from "./VsCodeIde";
let fullScreenPanel: vscode.WebviewPanel | undefined;
function getFullScreenTab() {
const tabs = vscode.window.tabGroups.all.flatMap((tabGroup) => tabGroup.tabs);
return tabs.find((tab) =>
(tab.input as any)?.viewType?.endsWith("continue.continueGUIView"),
);
}
type TelemetryCaptureParams = Parameters<typeof Telemetry.capture>;
/**
@ -67,27 +58,15 @@ function captureCommandTelemetry(
}
function focusGUI() {
const fullScreenTab = getFullScreenTab();
if (fullScreenTab) {
// focus fullscreen
fullScreenPanel?.reveal();
} else {
// focus sidebar
vscode.commands.executeCommand("continue.continueGUIView.focus");
// vscode.commands.executeCommand("workbench.action.focusAuxiliaryBar");
}
// focus sidebar
vscode.commands.executeCommand("continue.continueGUIView.focus");
// vscode.commands.executeCommand("workbench.action.focusAuxiliaryBar");
}
function hideGUI() {
const fullScreenTab = getFullScreenTab();
if (fullScreenTab) {
// focus fullscreen
fullScreenPanel?.dispose();
} else {
// focus sidebar
vscode.commands.executeCommand("workbench.action.closeAuxiliaryBar");
// vscode.commands.executeCommand("workbench.action.toggleAuxiliaryBar");
}
// focus sidebar
vscode.commands.executeCommand("workbench.action.closeAuxiliaryBar");
// vscode.commands.executeCommand("workbench.action.toggleAuxiliaryBar");
}
function waitForSidebarReady(
@ -436,74 +415,6 @@ const getCommandsMap: (
"continue.applyCodeFromChat": () => {
void sidebar.webviewProtocol.request("applyCodeFromChat", undefined);
},
"continue.toggleFullScreen": async () => {
focusGUI();
const sessionId = await sidebar.webviewProtocol.request(
"getCurrentSessionId",
undefined,
);
// Check if full screen is already open by checking open tabs
const fullScreenTab = getFullScreenTab();
if (fullScreenTab && fullScreenPanel) {
// Full screen open, but not focused - focus it
fullScreenPanel.reveal();
return;
}
// Clear the sidebar to prevent overwriting changes made in fullscreen
vscode.commands.executeCommand("continue.newSession");
// Full screen not open - open it
captureCommandTelemetry("openFullScreen");
// Create the full screen panel
let panel = vscode.window.createWebviewPanel(
"continue.continueGUIView",
"Continue",
vscode.ViewColumn.One,
{
retainContextWhenHidden: true,
enableScripts: true,
},
);
fullScreenPanel = panel;
// Add content to the panel
panel.webview.html = sidebar.getSidebarContent(
extensionContext,
panel,
undefined,
undefined,
true,
);
const sessionLoader = panel.onDidChangeViewState(() => {
vscode.commands.executeCommand("continue.newSession");
if (sessionId) {
vscode.commands.executeCommand(
"continue.focusContinueSessionId",
sessionId,
);
}
panel.reveal();
sessionLoader.dispose();
});
// When panel closes, reset the webview and focus
panel.onDidDispose(
() => {
sidebar.resetWebviewProtocolWebview();
vscode.commands.executeCommand("continue.focusContinueInput");
},
null,
extensionContext.subscriptions,
);
vscode.commands.executeCommand("workbench.action.copyEditorToNewWindow");
vscode.commands.executeCommand("workbench.action.closeAuxiliaryBar");
},
"continue.openConfigPage": () => {
vscode.commands.executeCommand("continue.navigateTo", "/config", false);
},
@ -652,11 +563,6 @@ const getCommandsMap: (
label: "$(comment) Open chat",
description: getMetaKeyLabel() + " + L",
},
{
label: "$(screen-full) Open full screen chat",
description:
getMetaKeyLabel() + " + K, " + getMetaKeyLabel() + " + M",
},
{
label: quickPickStatusText(targetStatus),
description:
@ -699,8 +605,6 @@ const getCommandsMap: (
}
} else if (selectedOption === "$(comment) Open chat") {
vscode.commands.executeCommand("continue.focusContinueInput");
} else if (selectedOption === "$(screen-full) Open full screen chat") {
vscode.commands.executeCommand("continue.toggleFullScreen");
} else if (selectedOption === "$(gear) Open settings") {
vscode.commands.executeCommand("continue.navigateTo", "/config");
}

View file

@ -13,6 +13,7 @@ import { VsCodeWebviewProtocol } from "../../webviewProtocol";
import { ApplyAbortManager } from "core/edit/applyAbortManager";
import { EDIT_MODE_STREAM_ID } from "core/edit/constants";
import { stripImages } from "core/util/messageContent";
import { getLastNPathParts } from "core/util/uri";
import { editOutcomeTracker } from "../../extension/EditOutcomeTracker";
import { VerticalDiffHandler, VerticalDiffHandlerOptions } from "./handler";
@ -432,9 +433,11 @@ export class VerticalDiffManager {
let overridePrompt: ChatMessage[] | undefined;
if (llm.promptTemplates?.apply) {
const filepath = getLastNPathParts(fileUri, 1);
const rendered = llm.renderPromptTemplate(llm.promptTemplates.apply, [], {
original_code: rangeContent,
new_code: newCode ?? "",
filepath,
});
overridePrompt =
typeof rendered === "string"

View file

@ -112,9 +112,6 @@ export class VsCodeMessenger {
this.onWebview("focusEditor", (msg) => {
vscode.commands.executeCommand("workbench.action.focusActiveEditorGroup");
});
this.onWebview("toggleFullScreen", (msg) => {
vscode.commands.executeCommand("continue.toggleFullScreen");
});
this.onWebview("acceptDiff", async ({ data: { filepath, streamId } }) => {
await vscode.commands.executeCommand(

6243
gui/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -31,7 +31,7 @@ const router = createMemoryRouter([
element: <History />,
},
{
path: "/stats",
path: ROUTES.STATS,
element: <Stats />,
},
{

View file

@ -1,33 +1,28 @@
import { ComputerDesktopIcon, SparklesIcon } from "@heroicons/react/24/outline";
import { SparklesIcon } from "@heroicons/react/24/outline";
import { ProfileDescription } from "core/config/ProfileLifecycleManager";
import { isLocalProfile } from "../../util";
import { BotIcon } from "../svg/BotIcon";
export interface AssistantIconProps {
assistant: ProfileDescription;
size?: number;
size?: string;
}
export function AssistantIcon({ assistant, size }: AssistantIconProps) {
const sizeTw = size ?? 4;
export function AssistantIcon({
assistant,
size = "h-4 w-4",
}: AssistantIconProps) {
if (isLocalProfile(assistant)) {
return (
<div
className={`h-${sizeTw} w-${sizeTw} bg-lightgray flex items-center justify-center rounded-full`}
>
<ComputerDesktopIcon
className={`h-${sizeTw - 1} w-${sizeTw - 1} font-bold text-black`}
/>
</div>
);
return <BotIcon className={`text-foreground ${size} flex-shrink-0`} />;
} else if (assistant.iconUrl) {
return (
<img
src={assistant.iconUrl}
className={`h-${sizeTw} w-${sizeTw} rounded-full`}
className={`${size} flex-shrink-0 rounded-full`}
alt=""
/>
);
} else {
return <SparklesIcon />;
return <SparklesIcon className={`${size} flex-shrink-0`} />;
}
}

View file

@ -1,18 +1,13 @@
import {
ArrowTopRightOnSquareIcon,
Cog6ToothIcon,
ExclamationTriangleIcon,
} from "@heroicons/react/24/outline";
import { ExclamationTriangleIcon } from "@heroicons/react/24/outline";
import { ProfileDescription } from "core/config/ProfileLifecycleManager";
import { useContext, useMemo } from "react";
import { useNavigate } from "react-router-dom";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppDispatch } from "../../redux/hooks";
import { setSelectedProfile } from "../../redux/slices/profilesSlice";
import { isLocalProfile } from "../../util";
import { ROUTES } from "../../util/navigation";
import { useLump } from "../mainInput/Lump/LumpContext";
import { ListboxOption, useFontSize } from "../ui";
import { CONFIG_ROUTES } from "../../util/navigation";
import { ToolTip } from "../gui/Tooltip";
import { Button, ListboxOption, useFontSize } from "../ui";
import { AssistantIcon } from "./AssistantIcon";
interface AssistantOptionProps {
@ -28,7 +23,6 @@ export function AssistantOption({
}: AssistantOptionProps) {
const tinyFont = useFontSize(-4);
const navigate = useNavigate();
const { setSelectedSection } = useLump();
const dispatch = useAppDispatch();
const ideMessenger = useContext(IdeMessengerContext);
@ -37,27 +31,14 @@ export function AssistantOption({
}, [profile.errors]);
function handleOptionClick() {
// Always select the agent first (even if it has errors)
// optimistic update
dispatch(setSelectedProfile(profile.id));
// notify core which will handle actual update
ideMessenger.post("didChangeSelectedProfile", {
id: profile.id,
});
onClick();
}
function handleConfigure() {
ideMessenger.post("config/openProfile", { profileId: profile.id });
onClick();
}
function handleClickError() {
if (profile.id === "local") {
navigate(ROUTES.HOME);
setSelectedSection("error");
} else {
ideMessenger.post("config/openProfile", { profileId: profile.id });
}
onClick();
}
@ -69,47 +50,32 @@ export function AssistantOption({
fontSizeModifier={-2}
className={selected ? "bg-list-active text-list-active-foreground" : ""}
>
<div className="flex w-full items-center justify-between gap-2">
<div className="flex w-full items-center gap-2">
<div className="flex h-4 w-4 flex-shrink-0">
<AssistantIcon size={3.5} assistant={profile} />
<div className="flex w-full items-center justify-between gap-10 py-0.5">
<div className="flex w-full items-center gap-3">
<div className="flex h-4 w-4 flex-shrink-0 items-center justify-center">
<AssistantIcon assistant={profile} />
</div>
<span
className={`line-clamp-1 flex-1 ${selected ? "font-semibold" : ""}`}
className={`line-clamp-1 flex-1 ${selected ? "font-semibold" : ""} ${profile.errors && profile.errors.length > 0 ? "text-error" : ""}`}
>
{profile.title}
</span>
</div>
<div className="flex flex-row items-center gap-1">
<div className="flex flex-row items-center gap-1.5">
{profile.errors && profile.errors?.length > 0 && (
<ExclamationTriangleIcon
data-tooltip-id={`${profile.id}-errors-tooltip`}
className="text-error h-3 w-3 flex-shrink-0 cursor-pointer"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
handleClickError();
}}
/>
)}
{isLocalProfile(profile) ? (
<Cog6ToothIcon
className="text-description h-3 w-3 flex-shrink-0 cursor-pointer"
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
handleConfigure();
}}
/>
) : (
<ArrowTopRightOnSquareIcon
className="text-description h-3 w-3 flex-shrink-0 cursor-pointer"
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
handleConfigure();
}}
/>
<ToolTip content="View errors">
<Button
variant="ghost"
size="sm"
className="text-error hover:enabled:text-error my-0 h-4 w-4 p-0"
onClick={(e) => {
e.stopPropagation();
navigate(CONFIG_ROUTES.AGENTS);
}}
>
<ExclamationTriangleIcon className="h-3.5 w-3.5" />
</Button>
</ToolTip>
)}
</div>
</div>

View file

@ -13,28 +13,21 @@ export function AssistantOptions({
const { profiles } = useAuth();
return (
<>
<div className="flex gap-1.5 px-3 pb-1 pt-2">
<label className="text-vsc-foreground font-semibold">Agents</label>
<div className="flex cursor-pointer flex-row items-center gap-1 hover:brightness-125"></div>
</div>
<div className="thin-scrollbar flex max-h-[300px] flex-col overflow-y-auto">
{profiles?.length === 0 ? (
<div className="text-vsc-foreground px-3 py-2 opacity-70">
No agents found
</div>
) : (
profiles?.map((profile, idx) => (
<AssistantOption
key={idx}
profile={profile}
onClick={onClose}
selected={profile.id === selectedProfileId}
/>
))
)}
</div>
</>
<div className="thin-scrollbar flex max-h-32 flex-col overflow-y-auto">
{profiles?.length === 0 ? (
<div className="text-vsc-foreground px-3 py-2 opacity-70">
No agents found
</div>
) : (
profiles?.map((profile, idx) => (
<AssistantOption
key={idx}
profile={profile}
onClick={onClose}
selected={profile.id === selectedProfileId}
/>
))
)}
</div>
);
}

View file

@ -0,0 +1,86 @@
import { CheckIcon } from "@heroicons/react/24/outline";
import {
BuildingOfficeIcon,
UserCircleIcon,
UserIcon,
} from "@heroicons/react/24/solid";
import { useContext } from "react";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { setSelectedOrgId } from "../../redux/slices/profilesSlice";
import { ListboxOption } from "../ui";
interface OrganizationOptionProps {
organization: { id: string; name: string; iconUrl?: string | null };
onClose: () => void;
}
function getOrgIcon(
org: { name: string; iconUrl?: string | null },
size: "sm" | "md" = "sm",
) {
const sizeClasses = size === "sm" ? "h-3.5 w-3.5" : "xs:h-4 xs:w-4 h-3 w-3";
if (org.iconUrl) {
return (
<img
src={org.iconUrl}
alt=""
className={`${sizeClasses} flex-shrink-0 rounded-full`}
/>
);
}
const IconComponent =
org.name === "Personal"
? size === "md"
? UserIcon
: UserCircleIcon
: BuildingOfficeIcon;
return <IconComponent className={`${sizeClasses} flex-shrink-0`} />;
}
export function OrganizationOption({
organization,
onClose,
}: OrganizationOptionProps) {
const dispatch = useAppDispatch();
const ideMessenger = useContext(IdeMessengerContext);
const selectedOrgId = useAppSelector(
(state) => state.profiles.selectedOrganizationId,
);
const isSelected = selectedOrgId === organization.id;
function handleOptionClick() {
dispatch(setSelectedOrgId(organization.id));
ideMessenger.post("didChangeSelectedOrg", {
id: organization.id,
});
onClose();
}
return (
<ListboxOption
value={organization.id}
onClick={handleOptionClick}
fontSizeModifier={-2}
className={isSelected ? "bg-list-active text-list-active-foreground" : ""}
>
<div className="flex w-full items-center justify-between gap-10 py-0.5">
<div className="flex w-full items-center gap-3">
<div className="flex h-4 w-4 flex-shrink-0 items-center justify-center">
{getOrgIcon(organization, "sm")}
</div>
<span
className={`line-clamp-1 flex-1 ${isSelected ? "font-semibold" : ""}`}
>
{organization.name}
</span>
</div>
<div className="flex flex-row items-center gap-1.5">
{isSelected && <CheckIcon className="h-3.5 w-3.5 flex-shrink-0" />}
</div>
</div>
</ListboxOption>
);
}

View file

@ -0,0 +1,18 @@
import { useAuth } from "../../context/Auth";
import { OrganizationOption } from "./OrganizationOption";
interface OrganizationOptionsProps {
onClose: () => void;
}
export function OrganizationOptions({ onClose }: OrganizationOptionsProps) {
const { organizations } = useAuth();
return (
<div className="thin-scrollbar flex max-h-24 flex-col overflow-y-auto">
{organizations.map((org) => (
<OrganizationOption key={org.id} organization={org} onClose={onClose} />
))}
</div>
);
}

View file

@ -1,86 +0,0 @@
import {
BuildingOfficeIcon,
ChevronUpDownIcon,
} from "@heroicons/react/24/outline";
import { UserCircleIcon } from "@heroicons/react/24/solid";
import { useContext } from "react";
import { useAuth } from "../../context/Auth";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import {
selectCurrentOrg,
setSelectedOrgId,
} from "../../redux/slices/profilesSlice";
import {
Listbox,
ListboxButton,
ListboxOption,
ListboxOptions,
} from "../ui/Listbox";
interface ScopeSelectProps {
onSelect?: () => void;
}
function getOrgIcon(org: { name: string; iconUrl?: string | null }) {
if (org.iconUrl) {
return (
<img src={org.iconUrl} alt="" className="h-3.5 w-3.5 rounded-full" />
);
}
const IconComponent =
org.name === "Personal" ? UserCircleIcon : BuildingOfficeIcon;
return <IconComponent className="h-3.5 w-3.5" />;
}
export function ScopeSelect({ onSelect }: ScopeSelectProps) {
const { organizations } = useAuth();
const ideMessenger = useContext(IdeMessengerContext);
const selectedOrgId = useAppSelector(
(state) => state.profiles.selectedOrganizationId,
);
const currentOrg = useAppSelector(selectCurrentOrg);
const dispatch = useAppDispatch();
const handleChange = (newValue: string) => {
// optimisitic update
dispatch(setSelectedOrgId(newValue));
ideMessenger.post("didChangeSelectedOrg", {
id: newValue,
});
onSelect?.();
};
const selectedDisplay = currentOrg ?? {
name: "Personal",
iconUrl: null,
};
return (
<Listbox value={selectedOrgId} onChange={handleChange}>
<div className="relative">
<ListboxButton className="hover:bg-list-active hover:text-list-active-foreground w-full min-w-[140px] justify-between px-4 py-2 sm:min-w-[200px]">
<div className="flex items-center gap-2">
{getOrgIcon(selectedDisplay)}
<span className="truncate">
{selectedDisplay?.name || "Select Organization"}
</span>
</div>
<ChevronUpDownIcon className="h-3.5 w-3.5" aria-hidden="true" />
</ListboxButton>
<ListboxOptions className="z-[1000] min-w-[140px] pt-0.5 sm:min-w-[200px]">
{organizations.map((org) => (
<ListboxOption key={org.id} value={org.id} className="py-2">
<div className="flex items-center gap-2">
{getOrgIcon(org)}
<span>{org.name}</span>
</div>
</ListboxOption>
))}
</ListboxOptions>
</div>
</Listbox>
);
}

View file

@ -4,56 +4,63 @@ import type { ProfileDescription } from "core/config/ConfigHandler";
import { useAppSelector } from "../../redux/hooks";
import { fontSize } from "../../util";
import { cn } from "../../util/cn";
import { useLump } from "../mainInput/Lump/LumpContext";
import { ListboxButton } from "../ui";
import { AssistantIcon } from "./AssistantIcon";
interface SelectedAssistantButtonProps {
selectedProfile: ProfileDescription | null;
variant?: "lump" | "sidebar";
}
export function SelectedAssistantButton({
selectedProfile,
variant,
}: SelectedAssistantButtonProps) {
const { isToolbarExpanded } = useLump();
const configLoading = useAppSelector((store) => store.config.loading);
const isSidebar = variant === "sidebar";
const iconSize = isSidebar ? "h-4 w-4" : "h-3 w-3";
const buttonPadding = isSidebar ? "px-2 py-1.5" : "px-0 py-0.5";
const buttonStyle = isSidebar ? {} : { fontSize: fontSize(-3) };
return (
<ListboxButton
data-testid="assistant-select-button"
className="text-description border-none bg-transparent hover:brightness-125"
style={{ fontSize: fontSize(-3) }}
className={`text-description overflow-hidden border-none bg-transparent hover:brightness-110 ${isSidebar ? "w-full justify-start" : "gap-1.5"} ${buttonPadding}`}
style={buttonStyle}
>
<div className="flex flex-row items-center gap-1.5">
{selectedProfile === null ? (
"Create your first agent"
) : configLoading ? (
<span className="text-description flex flex-row items-center">
<ArrowPathIcon
className={cn(
"text-description mr-1.5 h-3 w-3",
configLoading && "animate-spin-slow",
)}
/>
Loading
</span>
) : (
<>
<div className="h-3 w-3 flex-shrink-0 select-none">
<AssistantIcon size={3} assistant={selectedProfile} />
</div>
<span
className={`line-clamp-1 select-none break-all ${isToolbarExpanded ? "xs:hidden sm:line-clamp-1" : ""}`}
>
{selectedProfile.title}
<div
className={`flex flex-row items-center ${isSidebar ? "w-full justify-between" : "gap-1.5"}`}
>
<div className="flex min-w-0 flex-1 flex-row items-center gap-2">
{selectedProfile === null ? (
"Create your first agent"
) : configLoading ? (
<span className="text-description flex flex-row items-center">
<ArrowPathIcon
className={cn(
`text-description mr-1.5 ${iconSize}`,
configLoading && "animate-spin-slow",
)}
/>
Loading
</span>
</>
)}
) : (
<>
<AssistantIcon assistant={selectedProfile} size={iconSize} />
<span
className={`select-none truncate text-xs ${isSidebar && "hidden md:block"}`}
>
{selectedProfile.title}
</span>
</>
)}
</div>
<ChevronDownIcon
className={`text-description ml-0.5 h-3 w-3 flex-shrink-0 select-none ${isSidebar && "hidden md:block"}`}
aria-hidden="true"
/>
</div>
<ChevronDownIcon
className="h-2 w-2 flex-shrink-0 select-none"
aria-hidden="true"
/>
</ListboxButton>
);
}

View file

@ -1,11 +1,14 @@
import {
ArrowPathIcon,
ArrowRightEndOnRectangleIcon,
ArrowRightStartOnRectangleIcon,
Cog6ToothIcon,
PencilIcon,
PlusIcon,
WrenchScrewdriverIcon,
} from "@heroicons/react/24/outline";
import { AuthType, isOnPremSession } from "core/control-plane/AuthTypes";
import { isOnPremSession } from "core/control-plane/AuthTypes";
import { useContext, useEffect, useRef } from "react";
import { useNavigate } from "react-router-dom";
import { useAuth } from "../../context/Auth";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
@ -15,20 +18,28 @@ import {
} from "../../redux/slices/profilesSlice";
import { getMetaKeyLabel, isMetaEquivalentKeyPressed } from "../../util";
import { cn } from "../../util/cn";
import { ToolTip } from "../gui/Tooltip";
import { CONFIG_ROUTES } from "../../util/navigation";
import {
Button,
Listbox,
ListboxOption,
ListboxOptions,
Transition,
useFontSize,
} from "../ui";
import { Divider } from "../ui/Divider";
import { AssistantOptions } from "./AssistantOptions";
import { ScopeSelect } from "./ScopeSelect";
import { OrganizationOptions } from "./OrganizationOptions";
import { SelectedAssistantButton } from "./SelectedAssistantButton";
export function AssistantAndOrgListbox() {
export interface AssistantAndOrgListboxProps {
variant: "lump" | "sidebar";
}
export function AssistantAndOrgListbox({
variant = "sidebar",
}: AssistantAndOrgListboxProps) {
const dispatch = useAppDispatch();
const navigate = useNavigate();
const listboxRef = useRef<HTMLDivElement>(null);
const currentOrg = useAppSelector(selectCurrentOrg);
const ideMessenger = useContext(IdeMessengerContext);
@ -36,8 +47,8 @@ export function AssistantAndOrgListbox() {
profiles,
selectedProfile,
session,
login,
logout,
login,
organizations,
refreshProfiles,
} = useAuth();
@ -64,8 +75,30 @@ export function AssistantAndOrgListbox() {
close();
}
function onLogout() {
logout();
function onNewOrganization() {
void ideMessenger.request("controlPlane/openUrl", {
path: "/organizations/new",
});
close();
}
function onAgentsConfig() {
navigate(CONFIG_ROUTES.AGENTS);
close();
}
function onOrganizationsConfig() {
navigate(CONFIG_ROUTES.ORGANIZATIONS);
close();
}
function onRulesConfig() {
navigate(CONFIG_ROUTES.RULES);
close();
}
function onToolsConfig() {
navigate(CONFIG_ROUTES.TOOLS);
close();
}
@ -113,41 +146,42 @@ export function AssistantAndOrgListbox() {
return (
<Listbox>
<div className="relative" ref={listboxRef}>
<SelectedAssistantButton selectedProfile={selectedProfile} />
<SelectedAssistantButton
selectedProfile={selectedProfile}
variant={variant}
/>
<Transition>
<ListboxOptions
className="-translate-x-1.5 pb-0"
className="max-h-32 -translate-x-1.5 overflow-y-auto pb-0"
style={{ zIndex: 200 }}
>
<div className="border-border border-x-0 border-t-0 border-solid px-2 py-2">
<div className="flex flex-col gap-2 pl-1">
{session ? (
<span className="text-description-muted flex items-center justify-between gap-x-1">
{session?.AUTH_TYPE !== AuthType.OnPrem &&
session?.account.id}
<ToolTip content="Logout">
<ArrowRightStartOnRectangleIcon
className="h-3 w-3 cursor-pointer hover:brightness-125"
onClick={onLogout}
/>
</ToolTip>
</span>
) : (
<span
className="text-description-muted flex cursor-pointer items-center justify-end gap-x-1 hover:brightness-125"
onClick={() => login(false)}
>
Log In <ArrowRightEndOnRectangleIcon className="h-3 w-3" />
</span>
)}
{shouldRenderOrgInfo && (
<>
<label className="text-vsc-foreground font-semibold">
Organization
</label>
<ScopeSelect />
</>
)}
<div className="flex items-center justify-between p-2">
<span className="text-description text-xs font-medium">
Agents
</span>
<div className="flex items-center gap-0.5">
<Button
onClick={(e) => {
e.stopPropagation();
onNewAssistant();
}}
variant="ghost"
size="sm"
className="my-0 h-5 w-5 p-0"
>
<PlusIcon className="text-description h-3.5 w-3.5" />
</Button>
<Button
onClick={(e) => {
e.stopPropagation();
onAgentsConfig();
}}
variant="ghost"
size="sm"
className="my-0 h-5 w-5 p-0"
>
<Cog6ToothIcon className="text-description h-3.5 w-3.5" />
</Button>
</div>
</div>
@ -156,50 +190,137 @@ export function AssistantAndOrgListbox() {
onClose={close}
/>
{shouldRenderOrgInfo && (
<>
<Divider className="!mb-0.5 !mt-0" />
<div className="flex items-center justify-between p-2">
<span className="text-description text-xs font-medium">
Organizations
</span>
<div className="flex items-center gap-0.5">
<Button
onClick={(e) => {
e.stopPropagation();
onNewOrganization();
}}
variant="ghost"
size="sm"
className="my-0 h-5 w-5 p-0"
>
<PlusIcon className="text-description h-3.5 w-3.5" />
</Button>
<Button
onClick={(e) => {
e.stopPropagation();
onOrganizationsConfig();
}}
variant="ghost"
size="sm"
className="my-0 h-5 w-5 p-0"
>
<Cog6ToothIcon className="text-description h-3.5 w-3.5" />
</Button>
</div>
</div>
<OrganizationOptions onClose={close} />
<Divider className="!mb-0 mt-0.5" />
</>
)}
{/* Settings Section */}
{variant !== "sidebar" && (
<div>
<Button
onClick={(e) => {
e.stopPropagation();
onRulesConfig();
}}
variant="ghost"
size="sm"
className="text-description hover:bg-input my-0 w-full justify-start py-1.5 pl-1 text-left"
>
<div className="flex w-full items-center">
<PencilIcon className="ml-1.5 mr-2 h-3.5 w-3.5 flex-shrink-0" />
<span className="text-2xs">Rules</span>
</div>
</Button>
<Button
onClick={(e) => {
e.stopPropagation();
onToolsConfig();
}}
variant="ghost"
size="sm"
className="text-description hover:bg-input my-0 w-full justify-start py-1.5 pl-1 text-left"
>
<div className="flex w-full items-center">
<WrenchScrewdriverIcon className="ml-1.5 mr-2 h-3.5 w-3.5 flex-shrink-0" />
<span className="text-2xs">Tools</span>
</div>
</Button>
<Button
onClick={(e) => {
e.stopPropagation();
void refreshProfiles("Manual refresh from assistant list");
}}
variant="ghost"
size="sm"
className="text-description hover:bg-input my-0 w-full justify-start py-1.5 pl-1 text-left"
>
<div className="flex w-full items-center">
<ArrowPathIcon
className={cn(
"ml-1.5 mr-2 h-3.5 w-3.5 flex-shrink-0",
configLoading && "animate-spin-slow",
)}
/>
<span className="text-2xs">Reload</span>
</div>
</Button>
{session ? (
<Button
onClick={(e) => {
e.stopPropagation();
logout();
close();
}}
variant="ghost"
size="sm"
className="text-description hover:bg-input my-0 w-full justify-start py-1.5 pl-1 text-left"
>
<div className="flex w-full items-center">
<ArrowRightStartOnRectangleIcon className="ml-1.5 mr-2 h-3.5 w-3.5 flex-shrink-0" />
<span className="text-2xs">Log out</span>
</div>
</Button>
) : (
<Button
onClick={(e) => {
e.stopPropagation();
login(false);
close();
}}
variant="ghost"
size="sm"
className="text-description hover:bg-input my-0 w-full justify-start py-1.5 pl-1 text-left"
>
<div className="flex w-full items-center">
<ArrowRightStartOnRectangleIcon className="ml-1.5 mr-2 h-3.5 w-3.5 flex-shrink-0 rotate-180" />
<span className="text-2xs">Log in</span>
</div>
</Button>
)}
<Divider className="!mt-0" />
</div>
)}
{/* Bottom Actions */}
<div className="border-border border-x-0 border-b-0 border-t border-solid">
<ListboxOption
value="new-assistant"
fontSizeModifier={-2}
className="border-border border-b px-2 py-1.5"
onClick={onNewAssistant}
>
<span
className="text-description flex flex-row items-center"
style={{ fontSize: tinyFont }}
>
<PlusIcon className="mr-1 h-3 w-3" /> New Agent
</span>
</ListboxOption>
<ListboxOption
value="reload-assistant"
fontSizeModifier={-2}
className="border-border border-b px-2 py-1.5"
onClick={(e: React.MouseEvent) => {
e.stopPropagation();
refreshProfiles("Manual refresh from assistant list");
}}
>
<span
className="text-description flex flex-row items-center"
style={{ fontSize: tinyFont }}
>
<ArrowPathIcon
className={cn(
"mr-1 h-3 w-3",
configLoading && "animate-spin-slow",
)}
/>
Reload agents
</span>
</ListboxOption>
<div
className="text-description border-border flex items-center justify-between gap-1.5 border-x-0 border-b-0 border-t border-solid px-2 py-2"
style={{ fontSize: tinyFont }}
>
<span className="block" style={{ fontSize: tinyFont - 1 }}>
<div>
<div className="text-description flex items-center justify-start px-2 py-1">
<span className="block" style={{ fontSize: tinyFont }}>
<code>{getMetaKeyLabel()} ⇧ '</code> to toggle agent
</span>
</div>

View file

@ -65,7 +65,7 @@ export function HistoryTableRow({
onMouseEnter={() => setHovered(true)}
onMouseLeave={() => setHovered(false)}
data-testid={`history-row-${index}`}
className="border-border relative mb-2 box-border flex w-full cursor-pointer overflow-hidden rounded-lg border border-solid p-3"
className="hover:bg-input relative mb-2 box-border flex w-full cursor-pointer overflow-hidden rounded-lg p-3"
onClick={async () => {
await dispatch(exitEdit({}));
if (sessionMetadata.sessionId !== currentSessionId) {
@ -117,7 +117,7 @@ export function HistoryTableRow({
</td>
{hovered && !editing && (
<td className="bg-badge absolute right-2 top-1/2 ml-auto flex -translate-y-1/2 transform items-center gap-x-1 rounded-full px-2 py-1 shadow-md">
<td className="bg-input absolute right-2 top-1/2 ml-auto flex -translate-y-1/2 transform items-center gap-x-1 rounded-full px-2 py-1 shadow-md">
<HeaderButtonWithToolTip
text="Edit"
onClick={async (e) => {

View file

@ -146,7 +146,7 @@ export function History() {
return (
<div
style={{ fontSize: getFontSize() }}
className="flex flex-1 flex-col overflow-auto px-1"
className="flex flex-1 flex-col overflow-auto overflow-x-hidden px-1"
>
<div className="relative my-2 mt-4 flex justify-center space-x-2">
<input
@ -170,7 +170,7 @@ export function History() {
)}
</div>
<div className="thin-scrollbar flex flex-1 flex-col overflow-y-auto">
<div className="thin-scrollbar flex w-full flex-1 flex-col overflow-y-auto">
{filteredAndSortedSessions.length === 0 && (
<div className="m-3 text-center">
{isSessionMetadataLoading ? (
@ -185,7 +185,7 @@ export function History() {
</div>
)}
<table className="flex flex-1 flex-col">
<table className="flex w-full flex-1 flex-col">
<tbody className="">
{sessionGroups.map((group, groupIndex) => (
<Fragment key={group.label}>

View file

@ -1,22 +1,33 @@
import { InformationCircleIcon } from "@heroicons/react/24/outline";
import { ReactNode } from "react";
import { ToolTip } from "./gui/Tooltip";
const DEFAULT_SIZE = "5";
const sizeMap = {
"3": "h-3 w-3",
"4": "h-4 w-4",
"5": "h-5 w-5",
"6": "h-6 w-6",
"8": "h-8 w-8",
} as const;
const InfoHover = ({
msg,
size,
id,
}: {
id: string;
msg: string;
msg: ReactNode;
size?: string;
}) => {
const sizeClasses =
sizeMap[size as keyof typeof sizeMap] ||
sizeMap[DEFAULT_SIZE as keyof typeof sizeMap];
return (
<ToolTip content={msg} place="bottom">
<InformationCircleIcon
className={`h-${size ?? DEFAULT_SIZE} w-${size ?? DEFAULT_SIZE} cursor-help text-gray-500`}
/>
<InformationCircleIcon className={`${sizeClasses} text-gray-500`} />
</ToolTip>
);
};

View file

@ -18,7 +18,6 @@ import { incrementFreeTrialCount } from "../util/freeTrial";
import { ROUTES } from "../util/navigation";
import TextDialog from "./dialogs";
import { GenerateRuleDialog } from "./GenerateRuleDialog";
import { LumpProvider } from "./mainInput/Lump/LumpContext";
import { useMainEditor } from "./mainInput/TipTapEditor";
import {
isNewUserOnboarding,
@ -258,35 +257,33 @@ const Layout = () => {
}}
/>
)}
<LumpProvider>
<OSRContextMenu />
<div
style={{
scrollbarGutter: "stable both-edges",
minHeight: "100%",
display: "grid",
gridTemplateRows: "1fr auto",
<OSRContextMenu />
<div
style={{
scrollbarGutter: "stable both-edges",
minHeight: "100%",
display: "grid",
gridTemplateRows: "1fr auto",
}}
>
<TextDialog
showDialog={showDialog}
onEnter={() => {
dispatch(setShowDialog(false));
}}
>
<TextDialog
showDialog={showDialog}
onEnter={() => {
dispatch(setShowDialog(false));
}}
onClose={() => {
dispatch(setShowDialog(false));
}}
message={dialogMessage}
/>
onClose={() => {
dispatch(setShowDialog(false));
}}
message={dialogMessage}
/>
<GridDiv>
<PostHogPageView />
<Outlet />
<FatalErrorIndicator />
</GridDiv>
</div>
<div style={{ fontSize: fontSize(-4) }} id="tooltip-portal-div" />
</LumpProvider>
<GridDiv>
<PostHogPageView />
<Outlet />
<FatalErrorIndicator />
</GridDiv>
</div>
<div style={{ fontSize: fontSize(-4) }} id="tooltip-portal-div" />
</LayoutTopDiv>
</TelemetryProviders>
</AuthProvider>

View file

@ -3,14 +3,12 @@ import { usePostHog } from "posthog-js/react";
import { useContext } from "react";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
import { getLocalStorage, setLocalStorage } from "../../../util/localStorage";
import { useLump } from "../../mainInput/Lump/LumpContext";
import { useOnboardingCard } from "./useOnboardingCard";
export function useSubmitOnboarding(mode: OnboardingModes, isDialog = false) {
const posthog = usePostHog();
const ideMessenger = useContext(IdeMessengerContext);
const { close: closeOnboardingCard } = useOnboardingCard();
const { setSelectedSection } = useLump();
function submitOnboarding(provider?: string, apiKey?: string) {
const onboardingStatus = getLocalStorage("onboardingStatus");
@ -39,7 +37,6 @@ export function useSubmitOnboarding(mode: OnboardingModes, isDialog = false) {
}
ideMessenger.post("config/openProfile", { profileId: undefined });
setSelectedSection("models");
}
return {

View file

@ -1,49 +1,27 @@
import { ArrowLeftIcon } from "@heroicons/react/24/outline";
import { useFontSize } from "./ui/font";
export interface PageHeaderProps {
onTitleClick?: () => void;
title?: string;
rightContent?: React.ReactNode;
showBorder?: boolean;
}
export function PageHeader({
onTitleClick,
title,
rightContent,
showBorder,
showBorder = true,
}: PageHeaderProps) {
const fontSize = useFontSize(-1);
return (
<div
className={`sticky top-0 z-20 m-0 flex items-center justify-between bg-inherit py-1 ${
showBorder
? "border-0 border-b-[1px] border-solid border-b-zinc-700"
: ""
}`}
className={`border-command-border sticky top-0 z-20 m-0 flex items-center justify-between border border-x-0 ${showBorder ? "border-b" : "border-b-0"} border-t-0 border-solid bg-inherit py-3.5`}
>
{title ? (
<div
className="flex cursor-pointer items-center transition-colors duration-200 hover:brightness-125"
onClick={onTitleClick}
>
<ArrowLeftIcon className="ml-3 inline-block h-3 w-3" />
<span
className="mx-2 inline-block text-lg font-bold"
style={{
fontSize,
}}
>
{title}
</span>
</div>
) : (
<div />
)}
{rightContent && <div className="pr-2">{rightContent}</div>}
<div
className="flex cursor-pointer items-center transition-colors duration-200 hover:brightness-125"
onClick={onTitleClick}
>
<ArrowLeftIcon className="ml-3 inline-block h-3 w-3" />
{title && <span className="mx-2 inline-block font-bold">{title}</span>}
</div>
</div>
);
}

View file

@ -22,9 +22,6 @@ export default function StepContainer(props: StepContainerProps) {
const dispatch = useDispatch();
const [isTruncated, setIsTruncated] = useState(false);
const isStreaming = useAppSelector((state) => state.session.isStreaming);
const historyItemAfterThis = useAppSelector(
(state) => state.session.history[props.index + 1],
);
const uiConfig = useAppSelector(selectUIConfig);
// Calculate dimming and indicator state based on latest summary index
@ -34,22 +31,12 @@ export default function StepContainer(props: StepContainerProps) {
const isLatestSummary =
latestSummaryIndex !== -1 && props.index === latestSummaryIndex;
const isNextMsgAssistantOrThinking =
historyItemAfterThis?.message.role === "assistant" ||
historyItemAfterThis?.message.role === "thinking" ||
historyItemAfterThis?.message.role === "tool";
const shouldRenderResponseAction = () => {
if (isNextMsgAssistantOrThinking) {
return false;
}
if (!historyItemAfterThis) {
return !props.item.toolCallStates;
}
return true;
};
const historyItemAfterThis = useAppSelector(
(state) => state.session.history[props.index + 1],
);
const showResponseActions =
(props.isLast || historyItemAfterThis?.message.role === "user") &&
!(props.isLast && (isStreaming || props.item.toolCallStates));
useEffect(() => {
if (!isStreaming) {
@ -110,9 +97,9 @@ export default function StepContainer(props: StepContainerProps) {
{props.isLast && <ThinkingIndicator historyItem={props.item} />}
</div>
{shouldRenderResponseAction() && !isStreaming && (
{showResponseActions && (
<div
className={`mt-2 h-7 transition-opacity duration-300 ease-in-out ${isBeforeLatestSummary ? "opacity-35" : ""}`}
className={`mt-2 h-7 transition-opacity duration-300 ease-in-out ${isBeforeLatestSummary || isStreaming ? "opacity-35" : ""} ${isStreaming && "pointer-events-none cursor-not-allowed"}`}
>
<ResponseActions
isTruncated={isTruncated}

View file

@ -3,9 +3,8 @@ import { useNavigate } from "react-router-dom";
import { useAuth } from "../../context/Auth";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppSelector } from "../../redux/hooks";
import { ROUTES } from "../../util/navigation";
import { CONFIG_ROUTES } from "../../util/navigation";
import Alert from "../gui/Alert";
import { useLump } from "../mainInput/Lump/LumpContext";
export const FatalErrorIndicator = () => {
const { refreshProfiles } = useAuth();
@ -18,12 +17,10 @@ export const FatalErrorIndicator = () => {
return configError?.some((error) => error.fatal);
}, [configError]);
const { setSelectedSection, selectedSection } = useLump();
const configLoading = useAppSelector((state) => state.config.loading);
const showLumpErrorSection = () => {
navigate(ROUTES.HOME);
setSelectedSection("error");
const showConfigPage = () => {
navigate(CONFIG_ROUTES.AGENTS);
};
const { selectedProfile } = useAuth();
@ -67,10 +64,7 @@ export const FatalErrorIndicator = () => {
Reload
</div>
)}
<div
onClick={showLumpErrorSection}
className={`cursor-pointer underline transition-all ${selectedSection === "error" ? "opacity-0" : ""}`}
>
<div onClick={showConfigPage} className="cursor-pointer underline">
View
</div>
</div>

View file

@ -9,7 +9,7 @@ import { useAppSelector } from "../../redux/hooks";
import { updateIndexingStatus } from "../../redux/slices/indexingSlice";
import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice";
import { ToolTip } from "../gui/Tooltip";
import DocsIndexingPeeks from "../mainInput/Lump/sections/docs/DocsIndexingPeeks";
import DocsIndexingPeeks from "../../pages/config/sections/docs/DocsIndexingPeeks";
function AddDocsDialog() {
const posthog = usePostHog();

View file

@ -4,6 +4,7 @@ import {
ExclamationTriangleIcon,
InformationCircleIcon,
} from "@heroicons/react/16/solid";
import { varWithFallback } from "../../styles/theme";
import { cn } from "../../util/cn";
type AlertTypes = "info" | "success" | "warning" | "error";
@ -18,7 +19,6 @@ type AlertConfig = {
[key in AlertTypes]: {
Icon: any;
iconColor: string;
background: string;
border: string;
text: string;
};
@ -27,28 +27,24 @@ type AlertConfig = {
const ALERT_CONFIGS: AlertConfig = {
info: {
Icon: InformationCircleIcon,
background: "bg-background",
border: "border-foreground",
iconColor: "text-foreground",
border: "border-info",
iconColor: "text-info",
text: "text-foreground",
},
success: {
Icon: CheckCircleIcon,
background: "bg-green-600/20",
border: "border-success",
iconColor: "text-success",
text: "text-foreground",
},
warning: {
Icon: ExclamationTriangleIcon,
background: "bg-yellow-600/20",
border: "border-warning",
iconColor: "text-warning",
text: "text-foreground",
},
error: {
Icon: ExclamationCircleIcon,
background: "bg-red-600/20",
border: "border-error",
iconColor: "text-error",
text: "text-foreground",
@ -56,33 +52,50 @@ const ALERT_CONFIGS: AlertConfig = {
};
const alertSizes = {
sm: "px-3 py-1.5 rounded-md border",
lg: "px-4 py-3 rounded-md border",
sm: "px-3 py-2 rounded-md",
lg: "px-3 py-2.5 rounded-md",
};
const iconSizes = {
sm: "h-4 w-4 mt-1",
lg: "h-5 w-5 mt-0.5",
sm: "h-4 w-4",
lg: "h-4 w-4",
};
const spacingSizes = {
sm: "ml-2",
lg: "ml-3",
lg: "ml-2",
};
function Alert({ type = "info", size = "lg", ...props }: AlertProps) {
const { Icon, background, border, text, iconColor } = ALERT_CONFIGS[type];
function Alert({
type = "info",
size = "lg",
className,
children,
...props
}: AlertProps) {
const { Icon, border, text, iconColor } = ALERT_CONFIGS[type];
const colorMap = {
info: varWithFallback("info"),
success: varWithFallback("success"),
warning: varWithFallback("warning"),
error: varWithFallback("error"),
};
return (
<div
className={cn(
`flex flex-row items-start ${background} border-[0.5px] border-solid ${border} shadow-sm ${alertSizes[size]}`,
props.className,
`flex flex-row items-start border-[0.5px] ${border} border-solid shadow-sm ${alertSizes[size]}`,
className,
)}
style={{
backgroundColor: `color-mix(in srgb, ${colorMap[type]} 20%, transparent)`,
}}
{...props}
>
<Icon className={`flex-shrink-0 ${iconColor} ${iconSizes[size]}`} />
<div className="flex flex-1 flex-col">
<div className={`${spacingSizes[size]} ${text}`}>{props.children}</div>
<div className={`${spacingSizes[size]} ${text}`}>{children}</div>
</div>
</div>
);

View file

@ -1,91 +0,0 @@
import React, { useState } from "react";
interface NumberInputProps {
value: number;
onChange: (value: number) => void;
max: number;
min: number;
}
const NumberInput: React.FC<NumberInputProps> = ({
value,
onChange,
max,
min,
}) => {
const [inputValue, setInputValue] = useState(value.toString());
const handleIncrement = () => {
if (value < max) {
const newValue = value + 1;
onChange(newValue);
setInputValue(newValue.toString());
}
};
const handleDecrement = () => {
if (value > min) {
const newValue = value - 1;
onChange(newValue);
setInputValue(newValue.toString());
}
};
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const newInputValue = e.target.value;
setInputValue(newInputValue);
// Only update the actual value if it's a valid number
const numValue = parseInt(newInputValue, 10);
if (!isNaN(numValue)) {
// Apply min/max constraints
const constrainedValue = Math.min(Math.max(numValue, min), max);
onChange(constrainedValue);
}
};
const handleBlur = () => {
// When input loses focus, ensure the displayed value matches the actual value
// This handles cases where the user entered an invalid value
setInputValue(value.toString());
};
return (
<div className="border-vsc-input-border bg-vsc-input-background flex flex-row overflow-hidden rounded-md border border-solid">
<input
type="text"
value={inputValue}
onChange={handleInputChange}
onBlur={handleBlur}
className="text-vsc-foreground max-w-9 border-none bg-inherit pr-1.5 text-right outline-none ring-0 focus:border-none focus:outline-none focus:ring-0"
style={{
appearance: "none",
WebkitAppearance: "none",
MozAppearance: "none",
}}
min={min}
max={max}
/>
<div className="flex flex-col">
<button
style={{ fontSize: "9px" }}
onClick={handleIncrement}
disabled={value >= max}
className="text-vsc-foreground m-0 mb-0.5 cursor-pointer border-none bg-inherit px-1.5 py-0 hover:opacity-80"
>
▲
</button>
<button
style={{ fontSize: "9px" }}
className="text-vsc-foreground m-0 mb-0.5 cursor-pointer border-none bg-inherit px-1.5 py-0 hover:opacity-80"
onClick={handleDecrement}
disabled={value <= min}
>
▼
</button>
</div>
</div>
);
};
export default NumberInput;

View file

@ -5,7 +5,12 @@
// background-color: ${vscBackground};
// color: ${vscForeground};
import { vscBackground, vscForeground, vscInputBorder } from "..";
import {
vscCommandCenterInactiveBorder,
vscForeground,
vscInputBackground,
} from "..";
import { cn } from "../../util/cn";
// appearance: none;
// -webkit-appearance: none;
@ -19,9 +24,9 @@ import { vscBackground, vscForeground, vscInputBorder } from "..";
// // gui/src/components/gui/Select.tsx
// import React from 'react';
export const Select: React.FC<React.SelectHTMLAttributes<HTMLSelectElement>> = (
props,
) => (
export const Select: React.FC<
React.SelectHTMLAttributes<HTMLSelectElement>
> = ({ className, ...props }) => (
<div
style={{
color: vscForeground,
@ -29,10 +34,10 @@ export const Select: React.FC<React.SelectHTMLAttributes<HTMLSelectElement>> = (
>
<select
{...props}
className="rounded border px-3 py-2"
className={cn("rounded-default border px-3 py-1.5", className)}
style={{
borderColor: vscInputBorder,
backgroundColor: vscBackground,
borderColor: vscCommandCenterInactiveBorder,
backgroundColor: vscInputBackground,
color: vscForeground,
appearance: "none",
WebkitAppearance: "none",

View file

@ -37,7 +37,7 @@ const ToggleSwitch: React.FC<ToggleSwitchProps> = ({
<div className="flex flex-row items-center gap-1">
{isToggled && !!showIfToggled && showIfToggled}
<div
className={`border-vsc-input-border bg-vsc-input-background relative flex items-center rounded-full border border-solid`}
className={`border-command-border bg-vsc-input-background relative flex items-center rounded-full border border-solid`}
onClick={disabled ? undefined : onToggle}
style={{
height: size,

View file

@ -9,7 +9,7 @@ import { fontSize } from "../../util";
const TooltipStyles: CSSProperties = {
fontSize: fontSize(-4),
backgroundColor: vscBackground,
outline: `0.5px solid ${varWithFallback("badge-background")}`,
outline: `0.5px solid ${varWithFallback("description")}`,
color: vscForeground,
padding: "4px 8px",
zIndex: 1000,

View file

@ -68,7 +68,7 @@ const ContextStatus = () => {
</div>
}
>
<div className="border-description-muted relative h-[14px] w-[7px] rounded-[1px] border-[0.5px] border-solid md:h-[10px] md:w-[5px]">
<div className="border-command-border relative h-[14px] w-[7px] rounded-[1px] border-[0.5px] border-solid md:h-[10px] md:w-[5px]">
<div
className={`transition-height absolute bottom-0 left-0 w-full duration-300 ease-in-out ${barColorClass}`}
style={{ height: `${percent}%` }}

View file

@ -13,7 +13,7 @@ import { selectUseActiveFile } from "../../redux/selectors";
import { selectSelectedChatModel } from "../../redux/slices/configSlice";
import { setHasReasoningEnabled } from "../../redux/slices/sessionSlice";
import { exitEdit } from "../../redux/thunks/edit";
import { getAltKeyLabel, isMetaEquivalentKeyPressed } from "../../util";
import { getMetaKeyLabel, isMetaEquivalentKeyPressed } from "../../util";
import { ToolTip } from "../gui/Tooltip";
import ModelSelect from "../modelSelection/ModelSelect";
import { ModeSelect } from "../ModeSelect";
@ -165,7 +165,13 @@ function InputToolbar(props: InputToolbarProps) {
{!props.toolbarOptions?.hideUseCodebase && !isInEdit && (
<div className="hidden transition-colors duration-200 hover:underline md:flex">
<HoverItem
className={props.activeKey === "Alt" ? "underline" : ""}
className={
props.activeKey === "Meta" ||
props.activeKey === "Control" ||
props.activeKey === "Alt"
? "underline"
: ""
}
onClick={(e) =>
props.onEnter?.({
useCodebase: false,
@ -175,15 +181,14 @@ function InputToolbar(props: InputToolbarProps) {
>
<ToolTip
place="top-end"
content={`
${
useActiveFile
? "Send Without Active File"
: "Send With Active File"
} (${getAltKeyLabel()}⏎)`}
content={`${
useActiveFile
? "Send Without Active File"
: "Send With Active File"
} (${getMetaKeyLabel()}⏎)`}
>
<span>
{getAltKeyLabel()}⏎{" "}
{getMetaKeyLabel()}⏎{" "}
{useActiveFile ? "No active file" : "Active file"}
</span>
</ToolTip>
@ -211,8 +216,10 @@ function InputToolbar(props: InputToolbarProps) {
onClick={async (e) => {
if (props.onEnter) {
props.onEnter({
useCodebase: isMetaEquivalentKeyPressed(e as any),
noContext: useActiveFile ? e.altKey : !e.altKey,
useCodebase: false,
noContext: useActiveFile
? !(isMetaEquivalentKeyPressed(e as any) || e.altKey)
: isMetaEquivalentKeyPressed(e as any) || e.altKey,
});
}
}}

View file

@ -1,124 +0,0 @@
/**
* Provides context for controlling the Lump component's visibility state
*/
import {
createContext,
ReactNode,
useCallback,
useContext,
useEffect,
useState,
} from "react";
import { useAppSelector } from "../../../redux/hooks";
interface LumpContextType {
isLumpVisible: boolean;
selectedSection: string | null;
displayedSection: string | null;
isToolbarExpanded: boolean;
hideLump: () => void;
setSelectedSection: (section: string | null) => void;
toggleToolbar: () => void;
}
const LumpContext = createContext<LumpContextType | undefined>(undefined);
interface LumpProviderProps {
children: ReactNode;
}
/**
* Provider component that makes Lump state available to any child component
*/
export function LumpProvider({ children }: LumpProviderProps) {
const [selectedSection, setSelectedSection] = useState<string | null>(null);
const [displayedSection, setDisplayedSection] = useState<string | null>(null);
const [isVisible, setIsVisible] = useState(false);
const [isToolbarExpanded, setIsToolbarExpanded] = useState(true);
const isStreaming = useAppSelector((state) => state.session.isStreaming);
const configError = useAppSelector((store) => store.config.configError);
// Handle keyboard escape
const handleKeyDown = useCallback(
(event: KeyboardEvent) => {
if (event.key === "Escape" && selectedSection) {
setSelectedSection(null);
}
},
[selectedSection],
);
// Function to hide the lump
const hideLump = useCallback(() => {
setSelectedSection(null);
}, []);
// Function to toggle toolbar expanded state
const toggleToolbar = useCallback(() => {
setIsToolbarExpanded((prev) => !prev);
}, []);
// Update displayedSection and visibility when selectedSection changes
useEffect(() => {
if (selectedSection) {
setDisplayedSection(selectedSection);
setIsVisible(true);
} else {
setIsVisible(false);
const timeout = setTimeout(() => {
setDisplayedSection(null);
}, 300);
return () => clearTimeout(timeout);
}
}, [selectedSection]);
// Don't allow selection error section if there are no errors
useEffect(() => {
if (selectedSection === "error" && !configError) {
setSelectedSection(null);
}
}, [selectedSection, configError]);
// Reset when streaming starts
useEffect(() => {
if (isStreaming && selectedSection) {
setSelectedSection(null);
}
}, [isStreaming, selectedSection]);
// Set up keyboard listener
useEffect(() => {
if (selectedSection) {
document.addEventListener("keydown", handleKeyDown);
return () => document.removeEventListener("keydown", handleKeyDown);
}
}, [selectedSection, handleKeyDown]);
return (
<LumpContext.Provider
value={{
isLumpVisible: isVisible,
selectedSection,
displayedSection,
isToolbarExpanded,
hideLump,
setSelectedSection,
toggleToolbar,
}}
>
{children}
</LumpContext.Provider>
);
}
/**
* Hook that lets any component access the Lump context
*/
export function useLump() {
const context = useContext(LumpContext);
if (context === undefined) {
throw new Error("useLump must be used within a LumpProvider");
}
return context;
}

View file

@ -1,140 +1,19 @@
import {
ChatBubbleLeftIcon,
ChevronLeftIcon,
CubeIcon,
EllipsisHorizontalIcon,
ExclamationTriangleIcon,
PencilIcon,
Squares2X2Icon,
WrenchScrewdriverIcon,
} from "@heroicons/react/24/outline";
import { ReactNode, useContext, useEffect, useState } from "react";
import { vscBadgeForeground } from "../../..";
import { ExclamationTriangleIcon } from "@heroicons/react/24/outline";
import { useContext, useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { IdeMessengerContext } from "../../../../context/IdeMessenger";
import { useAppSelector } from "../../../../redux/hooks";
import FreeTrialButton from "../../../FreeTrialButton";
import { ToolTip } from "../../../gui/Tooltip";
import { useFontSize } from "../../../ui/font";
import HoverItem from "../../InputToolbar/HoverItem";
import { useLump } from "../LumpContext";
import { ErrorsSectionTooltip } from "../sections/errors/ErrorsSectionTooltip";
import { McpSectionTooltip } from "../sections/mcp/MCPTooltip";
import { ToolsSectionTooltip } from "../sections/tool-policies/ToolPoliciesSectionTooltip";
import { usesFreeTrialApiKey } from "core/config/usesFreeTrialApiKey";
import type { FreeTrialStatus } from "core/control-plane/client";
import { getLocalStorage } from "../../../../util/localStorage";
import { CONFIG_ROUTES } from "../../../../util/navigation";
import { AssistantAndOrgListbox } from "../../../AssistantAndOrgListbox";
interface BlockSettingsToolbarIcon {
title: string;
tooltip: ReactNode;
icon: React.ComponentType<any>;
itemCount?: number;
onClick: () => void;
isSelected?: boolean;
className?: string;
}
interface Section {
id: string;
title: string;
tooltip: ReactNode;
icon: React.ComponentType<any>;
}
const sections: Section[] = [
{ id: "models", title: "Models", tooltip: "Models", icon: CubeIcon },
{ id: "rules", title: "Rules", tooltip: "Rules", icon: PencilIcon },
{
id: "prompts",
title: "Prompts",
tooltip: "Prompts",
icon: ChatBubbleLeftIcon,
},
{
id: "tools",
title: "Tools",
tooltip: <ToolsSectionTooltip />,
icon: WrenchScrewdriverIcon,
},
{
id: "mcp",
title: "MCP",
tooltip: <McpSectionTooltip />,
icon: Squares2X2Icon,
},
{
id: "error",
title: "Errors",
tooltip: <ErrorsSectionTooltip />,
icon: ExclamationTriangleIcon,
},
];
function BlockSettingsToolbarIcon(
props: BlockSettingsToolbarIcon & { sectionId?: string },
) {
const isErrorSection = props.sectionId === "error";
const id = `block-settings-toolbar-icon-${props.sectionId}`;
const fontSize = useFontSize(-3);
return (
<ToolTip delayShow={700} content={props.tooltip}>
<HoverItem px={0} onClick={props.onClick} data-testid={id}>
<div
role="button"
tabIndex={0}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
props.onClick();
}
}}
className={`${
props.isSelected
? isErrorSection
? "bg-error"
: "bg-badge"
: undefined
} relative flex select-none items-center rounded-full px-[3px] py-0.5 transition-all duration-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500/50 sm:px-1 ${props.className || ""}`}
>
<props.icon
className={`h-[13px] w-[13px] flex-shrink-0 hover:brightness-125 ${
isErrorSection ? "text-error" : ""
}`}
style={{
color: props.isSelected ? vscBadgeForeground : undefined,
}}
aria-hidden="true"
/>
<div
style={{ fontSize }}
className={`overflow-hidden transition-all duration-200 ${
props.isSelected ? "ml-1 w-auto opacity-100" : "w-0 opacity-0"
}`}
>
<span
className="whitespace-nowrap"
style={{ color: vscBadgeForeground }}
>
{props.title}
</span>
</div>
</div>
</HoverItem>
</ToolTip>
);
}
export function BlockSettingsTopToolbar() {
const {
isToolbarExpanded,
toggleToolbar,
selectedSection,
setSelectedSection,
} = useLump();
const navigate = useNavigate();
const configError = useAppSelector((store) => store.config.configError);
const config = useAppSelector((state) => state.config.config);
@ -172,71 +51,46 @@ export function BlockSettingsTopToolbar() {
};
}, [ideMessenger, isUsingFreeTrial]);
const handleEllipsisClick = () => {
if (isToolbarExpanded) {
setSelectedSection(null);
}
toggleToolbar();
};
const visibleSections = sections.filter(
(section) =>
section.id !== "error" ||
(section.id === "error" && configError && configError?.length > 0),
);
const shouldShowError = configError && configError?.length > 0;
return (
<div className="flex flex-1 items-center justify-between gap-2">
<div className="flex flex-row">
<div className="xs:flex text-description hidden items-center justify-center gap-0.5">
<BlockSettingsToolbarIcon
className="-ml-1.5"
icon={isToolbarExpanded ? ChevronLeftIcon : EllipsisHorizontalIcon}
tooltip={isToolbarExpanded ? "Collapse Toolbar" : "Expand Toolbar"}
title=""
isSelected={false}
onClick={handleEllipsisClick}
/>
<div
className={`${isToolbarExpanded ? "w-min" : "w-0"} flex overflow-hidden transition-all duration-200`}
>
<div className="flex">
{visibleSections.map((section) => (
<BlockSettingsToolbarIcon
key={section.id}
sectionId={section.id}
icon={section.icon}
tooltip={section.tooltip}
title={section.title}
isSelected={selectedSection === section.id}
onClick={() =>
setSelectedSection(
selectedSection === section.id ? null : section.id,
)
}
/>
))}
<div className="flex flex-1 items-center justify-between gap-1.5">
<div>
{shouldShowError && (
<ToolTip delayShow={700} content="View configuration errors">
<div
role="button"
tabIndex={0}
onClick={() => navigate(CONFIG_ROUTES.AGENTS)}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
navigate(CONFIG_ROUTES.AGENTS);
}
}}
data-testid="block-settings-toolbar-icon-error"
className="relative flex cursor-pointer select-none items-center rounded-full px-1.5 py-1 sm:px-1.5"
>
<ExclamationTriangleIcon
className="text-warning h-[13px] w-[13px] flex-shrink-0"
aria-hidden="true"
/>
</div>
</div>
</ToolTip>
)}
</div>
<ToolTip
place="top"
content={isUsingFreeTrial ? "View free trial usage" : "Select Agent"}
>
<div>
{isUsingFreeTrial ? (
<FreeTrialButton freeTrialStatus={freeTrialStatus} />
) : (
<AssistantAndOrgListbox variant="lump" />
)}
</div>
</div>
<div className="flex gap-0.5">
<ToolTip
place="top"
content={isUsingFreeTrial ? "View free trial usage" : "Select Agent"}
>
<HoverItem
data-tooltip-id="assistant-select-tooltip"
className="!m-0 !p-0"
>
{isUsingFreeTrial ? (
<FreeTrialButton freeTrialStatus={freeTrialStatus} />
) : (
<AssistantAndOrgListbox />
)}
</HoverItem>
</ToolTip>
</div>
</ToolTip>
</div>
);
}

View file

@ -1,13 +1,15 @@
import { BuiltInToolNames } from "core/tools/builtIn";
import { useContext, useEffect } from "react";
import { useSelector } from "react-redux";
import { IdeMessengerContext } from "../../../../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../../../../redux/hooks";
import {
selectFirstPendingToolCall,
selectPendingToolCalls,
selectToolCallsByStatus,
} from "../../../../redux/selectors/selectToolCalls";
import { cancelToolCall } from "../../../../redux/slices/sessionSlice";
import { callToolById } from "../../../../redux/thunks/callToolById";
import { cancelStream } from "../../../../redux/thunks/cancelStream";
import { logToolUsage } from "../../../../redux/util";
import { isJetBrains } from "../../../../util";
import { BlockSettingsTopToolbar } from "./BlockSettingsTopToolbar";
@ -35,6 +37,14 @@ const isCancelToolCallShortcut = (
return modifierKey && event.key === "Backspace";
};
// Check if a tool call is a terminal command
const isTerminalCommand = (toolCallState: any) => {
return (
toolCallState?.toolCall?.function?.name ===
BuiltInToolNames.RunTerminalCommand
);
};
export function LumpToolbar() {
const dispatch = useAppDispatch();
const ideMessenger = useContext(IdeMessengerContext);
@ -55,13 +65,67 @@ export function LumpToolbar() {
);
const isApplying = applyStates.some((state) => state.status === "streaming");
// Get ALL running terminal commands
const runningToolCalls = useAppSelector((state) =>
selectToolCallsByStatus(state, "calling"),
);
const runningTerminalCalls = runningToolCalls.filter(isTerminalCommand);
const hasRunningTerminalCommand = runningTerminalCalls.length > 0;
// Simple handler: stop ALL running terminal commands
const handleStopAllTerminalCommands = async () => {
if (runningTerminalCalls.length === 0) {
return;
}
// Stop all terminal commands concurrently
const stopPromises = runningTerminalCalls.map(async (terminalCall) => {
try {
// Cancel the process on the backend
await ideMessenger.request("process/killTerminalProcess", {
toolCallId: terminalCall.toolCallId,
});
// Cancel the tool call in the UI
dispatch(
cancelToolCall({
toolCallId: terminalCall.toolCallId,
}),
);
logToolUsage(terminalCall, false, true, ideMessenger);
} catch (error) {
console.error(
`Failed to cancel terminal command ${terminalCall.toolCallId}:`,
error,
);
}
});
// Wait for all cancellations to complete
await Promise.all(stopPromises);
};
// Combined stop handler
const handleStopAction = async () => {
// Stop all terminal commands if any are running
if (hasRunningTerminalCommand) {
await handleStopAllTerminalCommands();
}
// Also stop regular streaming if it's happening
if (isStreaming) {
dispatch(cancelStream());
}
};
useEffect(() => {
if (!firstPendingToolCall) {
if (!firstPendingToolCall && !hasRunningTerminalCommand) {
return;
}
const handleToolCallKeyboardShortcuts = (event: KeyboardEvent) => {
if (isExecuteToolCallShortcut(event)) {
if (isExecuteToolCallShortcut(event) && firstPendingToolCall) {
event.preventDefault();
event.stopPropagation();
@ -71,13 +135,19 @@ export function LumpToolbar() {
} else if (isCancelToolCallShortcut(event, jetbrains)) {
event.preventDefault();
event.stopPropagation();
void dispatch(
cancelToolCall({
toolCallId: firstPendingToolCall.toolCallId,
}),
);
logToolUsage(firstPendingToolCall, false, true, ideMessenger);
if (hasRunningTerminalCommand) {
// Stop running terminal commands
void handleStopAction();
} else if (firstPendingToolCall) {
// Cancel pending tool call
void dispatch(
cancelToolCall({
toolCallId: firstPendingToolCall.toolCallId,
}),
);
logToolUsage(firstPendingToolCall, false, true, ideMessenger);
}
}
};
@ -85,7 +155,7 @@ export function LumpToolbar() {
return () => {
document.removeEventListener("keydown", handleToolCallKeyboardShortcuts);
};
}, [firstPendingToolCall]);
}, [firstPendingToolCall, hasRunningTerminalCommand, runningTerminalCalls]);
if (isApplying) {
return <IsApplyingToolbar />;
@ -103,8 +173,18 @@ export function LumpToolbar() {
return <TtsActiveToolbar />;
}
// Only show terminal streaming for actual terminal commands
if (hasRunningTerminalCommand) {
const count = runningTerminalCalls.length;
const stopText = `Stop Terminal${count > 1 ? ` (${count})` : ""}`;
return (
<StreamingToolbar onStop={handleStopAction} displayText={stopText} />
);
}
// Regular streaming (non-terminal)
if (isStreaming) {
return <StreamingToolbar />;
return <StreamingToolbar onStop={() => dispatch(cancelStream())} />;
}
if (pendingToolCalls.length > 0) {

View file

@ -1,20 +1,25 @@
import { useAppDispatch } from "../../../../redux/hooks";
import { cancelStream } from "../../../../redux/thunks/cancelStream";
import { getAltKeyLabel, getMetaKeyLabel, isJetBrains } from "../../../../util";
import { GeneratingIndicator } from "./GeneratingIndicator";
export function StreamingToolbar() {
interface StreamingToolbarProps {
onStop: () => void;
displayText?: string;
}
export function StreamingToolbar({
onStop,
displayText = "Stop",
}: StreamingToolbarProps) {
const jetbrains = isJetBrains();
const dispatch = useAppDispatch();
return (
<div className="flex w-full items-center justify-between">
<GeneratingIndicator />
<div
onClick={() => void dispatch(cancelStream())}
onClick={onStop}
className="text-2xs cursor-pointer px-1.5 py-0.5 hover:brightness-125"
>
<span className="text-description">Stop</span>
<span className="text-description">{displayText}</span>
{/* JetBrains overrides cmd+backspace, so we have to use another shortcut */}
<span className="text-description-muted ml-1 opacity-75">
{jetbrains ? getAltKeyLabel() : getMetaKeyLabel()}⌫

View file

@ -1,27 +1,13 @@
import { useLump } from "./LumpContext";
import { LumpToolbar } from "./LumpToolbar/LumpToolbar";
import { SelectedSection } from "./sections/SelectedSection";
/**
* Internal component that consumes the LumpContext
* Simplified toolbar component that only shows the toolbar without expansion
*/
export function Lump() {
const { isLumpVisible, selectedSection } = useLump();
return (
<div className="bg-input rounded-t-default border-command-border mx-1.5 border-l border-r border-t">
<div className="xs:px-2 px-1 py-0.5">
<LumpToolbar />
<div
className={`no-scrollbar overflow-y-auto pr-0.5 transition-all duration-300 ease-in-out ${
selectedSection
? "my-1 max-h-[200px] opacity-100"
: "my-0 max-h-0 opacity-0"
} ${isLumpVisible ? "opacity-100" : "opacity-0"}`}
>
<SelectedSection />
</div>
</div>
</div>
);

View file

@ -1,3 +0,0 @@
export function ContextSection() {
return <div>Context content</div>;
}

View file

@ -1,55 +0,0 @@
import { BlockType } from "@continuedev/config-yaml";
import {
ArrowTopRightOnSquareIcon,
PlusIcon,
} from "@heroicons/react/24/outline";
import { useContext } from "react";
import { GhostButton } from "../../..";
import { useAuth } from "../../../../context/Auth";
import { IdeMessengerContext } from "../../../../context/IdeMessenger";
import { fontSize } from "../../../../util";
export function ExploreBlocksButton(props: { blockType: string }) {
const { selectedProfile } = useAuth();
const ideMessenger = useContext(IdeMessengerContext);
const isLocal = selectedProfile?.profileType === "local";
const Icon = isLocal ? PlusIcon : ArrowTopRightOnSquareIcon;
const text = `${isLocal ? "Add" : "Explore"} ${
props.blockType === "mcpServers"
? "MCP Servers"
: props.blockType.charAt(0).toUpperCase() + props.blockType.slice(1)
}`;
const handleClick = () => {
if (isLocal) {
void ideMessenger.request("config/addLocalWorkspaceBlock", {
blockType: props.blockType as BlockType,
});
} else {
void ideMessenger.request("controlPlane/openUrl", {
path: `new?type=block&blockType=${props.blockType}`,
orgSlug: undefined,
});
}
};
return (
<GhostButton
className="w-full cursor-pointer rounded px-2 py-0.5 text-center"
style={{
fontSize: fontSize(-3),
}}
onClick={(e) => {
e.preventDefault();
handleClick();
}}
>
<div className="flex items-center justify-center gap-1">
<Icon className="h-3 w-3 pr-1" />
<span className="text-[11px]">{text}</span>
</div>
</GhostButton>
);
}

View file

@ -1,87 +0,0 @@
import { ModelRole } from "@continuedev/config-yaml";
import { ModelDescription } from "core";
import { useAuth } from "../../../../context/Auth";
import ModelRoleSelector from "../../../../pages/config/ModelRoleSelector";
import { useAppDispatch, useAppSelector } from "../../../../redux/hooks";
import { updateSelectedModelByRole } from "../../../../redux/thunks/updateSelectedModelByRole";
import { isJetBrains } from "../../../../util";
export function ModelsSection() {
const { selectedProfile } = useAuth();
const dispatch = useAppDispatch();
const config = useAppSelector((state) => state.config.config);
const jetbrains = isJetBrains();
function handleRoleUpdate(role: ModelRole, model: ModelDescription | null) {
if (!model) {
return;
}
void dispatch(
updateSelectedModelByRole({
role,
selectedProfile,
modelTitle: model.title,
}),
);
}
return (
<div>
<div className="text-[${getFontSize() - 1}px] grid grid-cols-1 gap-x-2 gap-y-1 sm:grid-cols-[auto_1fr]">
<ModelRoleSelector
displayName="Chat"
description="Used in the chat interface"
models={config.modelsByRole.chat}
selectedModel={config.selectedModelByRole.chat}
onSelect={(model) => handleRoleUpdate("chat", model)}
setupURL="https://docs.continue.dev/chat/model-setup"
/>
<ModelRoleSelector
displayName="Autocomplete"
description="Used to generate code completion suggestions"
models={config.modelsByRole.autocomplete}
selectedModel={config.selectedModelByRole.autocomplete}
onSelect={(model) => handleRoleUpdate("autocomplete", model)}
setupURL="https://docs.continue.dev/autocomplete/model-setup"
/>
{/* Jetbrains has a model selector inline */}
{!jetbrains && (
<ModelRoleSelector
displayName="Edit"
description="Used for inline edits"
models={config.modelsByRole.edit}
selectedModel={config.selectedModelByRole.edit}
onSelect={(model) => handleRoleUpdate("edit", model)}
setupURL="https://docs.continue.dev/edit/model-setup"
/>
)}
<ModelRoleSelector
displayName="Apply"
description="Used to apply generated codeblocks to files"
models={config.modelsByRole.apply}
selectedModel={config.selectedModelByRole.apply}
onSelect={(model) => handleRoleUpdate("apply", model)}
setupURL="https://docs.continue.dev/customize/model-roles/apply"
/>
<ModelRoleSelector
displayName="Embed"
description="Used to generate and query embeddings for the @codebase and @docs context providers"
models={config.modelsByRole.embed}
selectedModel={config.selectedModelByRole.embed}
onSelect={(model) => handleRoleUpdate("embed", model)}
setupURL="https://docs.continue.dev/customize/model-roles/embeddings"
/>
<ModelRoleSelector
displayName="Rerank"
description="Used for reranking results from the @codebase and @docs context providers"
models={config.modelsByRole.rerank}
selectedModel={config.selectedModelByRole.rerank}
onSelect={(model) => handleRoleUpdate("rerank", model)}
setupURL="https://docs.continue.dev/customize/model-roles/reranking"
/>
</div>
</div>
);
}

View file

@ -1,273 +0,0 @@
import { parseConfigYaml } from "@continuedev/config-yaml";
import {
ArrowsPointingOutIcon,
EyeIcon,
PencilIcon,
} from "@heroicons/react/24/outline";
import { RuleWithSource } from "core";
import {
DEFAULT_AGENT_SYSTEM_MESSAGE,
DEFAULT_CHAT_SYSTEM_MESSAGE,
DEFAULT_SYSTEM_MESSAGES_URL,
} from "core/llm/defaultSystemMessages";
import { useContext, useMemo } from "react";
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";
interface RuleCardProps {
rule: RuleWithSource;
}
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) {
void ideMessenger.request("controlPlane/openUrl", {
path: `${rule.slug}/new-version`,
orgSlug: undefined,
});
} else if (rule.ruleFile) {
ideMessenger.post("openFile", {
path: rule.ruleFile,
});
} else if (
rule.source === "default-chat" ||
rule.source === "default-plan" ||
rule.source === "default-agent"
) {
ideMessenger.post("openUrl", DEFAULT_SYSTEM_MESSAGES_URL);
} else {
ideMessenger.post("config/openProfile", {
profileId: undefined,
element: { sourceFile: (rule as any).sourceFile },
});
}
};
const handleTogglePolicy = () => {
if (rule.name) {
dispatch(toggleRuleSetting(rule.name));
}
};
const title = useMemo(() => {
if (rule.name) {
return rule.name;
} else {
if (rule.source === ".continuerules") {
return "Project rules";
} else if (rule.source === "default-chat") {
return "Default chat system message";
} else if (rule.source === "default-agent") {
return "Default agent system message";
} else if (rule.source === "json-systemMessage") {
return "JSON systemMessage)";
} else if (rule.source === "model-options-agent") {
return "Base System Agent Message";
} else if (rule.source === "model-options-plan") {
return "Base System Plan Message";
} else if (rule.source === "model-options-chat") {
return "Base System Chat Message";
} else {
return "Agent rule";
}
}
}, [rule]);
function onClickExpand() {
dispatch(setShowDialog(true));
dispatch(
setDialogMessage(
<div className="max-h-4/5 p-4">
<h3>{title}</h3>
<pre className="max-w-full overflow-scroll">{rule.rule}</pre>
</div>,
),
);
}
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 ${isDisabled ? "opacity-50" : ""}`}
>
<div className="flex flex-col">
<div className="flex flex-row justify-between gap-1">
<span
className={`line-clamp-2 ${isDisabled ? "text-gray-400" : "text-vsc-foreground"}`}
style={{
fontSize: smallFont,
}}
>
{title}
</span>
<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>
<span
style={{
fontSize: tinyFont,
}}
className={`mt-1 line-clamp-3 ${isDisabled ? "text-gray-500" : "text-gray-400"}`}
>
{rule.rule}
</span>
{rule.globs ? (
<div
style={{
fontSize: tinyFont,
}}
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 ${isDisabled ? "text-gray-500" : "text-gray-400"}`}
>
{rule.globs}
</code>
</div>
) : null}
</div>
</div>
);
};
export function RulesSection() {
const { selectedProfile } = useAuth();
const config = useAppSelector((store) => store.config.config);
const mode = useAppSelector((store) => store.session.mode);
const sortedRules: RuleWithSource[] = useMemo(() => {
const rules = [...config.rules.map((rule) => ({ ...rule }))];
// Use profile rawYaml to infer slugs
if (selectedProfile?.rawYaml) {
try {
const parsed = parseConfigYaml(selectedProfile.rawYaml);
const parsedRules = parsed?.rules ?? [];
let index = 0;
for (const rule of rules) {
if (rule.source === "rules-block") {
let slug: string | undefined = undefined;
const yamlRule = parsedRules[index];
if (yamlRule) {
if (typeof yamlRule !== "string" && "uses" in yamlRule) {
slug = yamlRule.uses;
} else {
slug = `${selectedProfile?.fullSlug.ownerSlug}/${selectedProfile?.fullSlug.packageSlug}`;
}
}
if (slug) {
rule.slug = slug;
}
index++;
}
}
} catch (e) {
console.error(
"Rules notch section: failed to parse selected profile",
e,
);
}
}
if (mode === "chat") {
if (config.selectedModelByRole.chat?.baseChatSystemMessage) {
rules.unshift({
rule: config.selectedModelByRole.chat?.baseChatSystemMessage,
source: "model-options-chat",
});
} else {
rules.unshift({
rule: DEFAULT_CHAT_SYSTEM_MESSAGE,
source: "default-chat",
});
}
} else if (mode === "agent") {
// agent
if (config.selectedModelByRole.chat?.baseAgentSystemMessage) {
rules.unshift({
rule: config.selectedModelByRole.chat?.baseAgentSystemMessage,
source: "model-options-agent",
});
} else {
rules.unshift({
rule: DEFAULT_AGENT_SYSTEM_MESSAGE,
source: "default-agent",
});
}
} else {
// plan
if (config.selectedModelByRole.chat?.basePlanSystemMessage) {
rules.unshift({
rule: config.selectedModelByRole.chat?.basePlanSystemMessage,
source: "model-options-plan",
});
} else {
rules.unshift({
rule: DEFAULT_AGENT_SYSTEM_MESSAGE,
source: "default-agent",
});
}
}
return rules;
}, [config, selectedProfile, mode]);
return (
<div className="flex flex-col gap-3">
{sortedRules.map((rule, index) => (
<RuleCard key={index} rule={rule} />
))}
<ExploreBlocksButton blockType="rules" />
</div>
);
}

View file

@ -1,34 +0,0 @@
import { useLump } from "../LumpContext";
import { ContextSection } from "./ContextSection";
import { ErrorSection } from "./errors/ErrorSection";
import MCPSection from "./mcp/MCPSection";
import { ModelsSection } from "./ModelsSection";
import { PromptsSection } from "./PromptsSection";
import { RulesSection } from "./RulesSection";
import { ToolPoliciesSection } from "./tool-policies/ToolPoliciesSection";
/**
* Renders the appropriate section based on the selected section in the Lump context
*/
export function SelectedSection() {
const { displayedSection } = useLump();
switch (displayedSection) {
case "models":
return <ModelsSection />;
case "rules":
return <RulesSection />;
case "prompts":
return <PromptsSection />;
case "context":
return <ContextSection />;
case "tools":
return <ToolPoliciesSection />;
case "mcp":
return <MCPSection />;
case "error":
return <ErrorSection />;
default:
return null;
}
}

View file

@ -1,70 +0,0 @@
import {
ExclamationCircleIcon,
ExclamationTriangleIcon,
} from "@heroicons/react/24/outline";
import { useContext } from "react";
import { useAuth } from "../../../../../context/Auth";
import { IdeMessengerContext } from "../../../../../context/IdeMessenger";
import { useAppSelector } from "../../../../../redux/hooks";
export function ErrorSection() {
const configError = useAppSelector((state) => state.config.configError);
const configLoading = useAppSelector((state) => state.config.loading);
const ideMessenger = useContext(IdeMessengerContext);
const { refreshProfiles } = useAuth();
const sortedErrors = configError
? [...configError].sort((a, b) => (b.fatal ? 1 : 0) - (a.fatal ? 1 : 0))
: [];
return (
<div className="flex flex-col gap-2 p-2">
<div className="flex flex-row items-center justify-end gap-1.5">
<div
className={`text-description cursor-pointer text-xs underline transition-all ${configLoading ? "opacity-0" : ""}`}
onClick={() => {
refreshProfiles("Clicked reload in Error section");
}}
>
Reload
</div>
<div
onClick={() => {
ideMessenger.post(
"openUrl",
"https://docs.continue.dev/troubleshooting",
);
}}
className="text-description cursor-pointer text-xs underline"
>
Help
</div>
</div>
<ul className="m-0 list-none space-y-4 p-0">
{sortedErrors.map((error, index) => (
<li
key={index}
className={`flex items-start rounded-md p-2 text-sm shadow-md ${
error.fatal
? "bg-red-100 text-red-800"
: "bg-yellow-100 text-yellow-800"
}`}
>
{error.fatal ? (
<ExclamationCircleIcon className="mr-2 mt-1 h-3.5 w-3.5 shrink-0" />
) : (
<ExclamationTriangleIcon className="mr-2 mt-1 h-3.5 w-3.5 shrink-0" />
)}
<p
className="m-0 whitespace-pre-wrap text-wrap"
style={{ wordBreak: "break-word" }}
>
{error.message}
</p>
</li>
))}
</ul>
</div>
);
}

View file

@ -1,14 +0,0 @@
import { useAppSelector } from "../../../../../redux/hooks";
export const ErrorsSectionTooltip = () => {
const configError = useAppSelector((store) => store.config.configError);
const numErrors = configError?.length ?? 0;
const plural = numErrors === 1 ? "" : "s";
return (
<div>
<span>{`${numErrors} Config Error${plural}`}</span>
</div>
);
};

View file

@ -1,273 +0,0 @@
import { ConfigYaml, parseConfigYaml } from "@continuedev/config-yaml";
import {
ArrowPathIcon,
CircleStackIcon,
CommandLineIcon,
GlobeAltIcon,
InformationCircleIcon,
ShieldCheckIcon,
ShieldExclamationIcon,
WrenchScrewdriverIcon,
} from "@heroicons/react/24/outline";
import { MCPServerStatus } from "core";
import { Fragment, useContext, useMemo } from "react";
import { useAuth } from "../../../../../context/Auth";
import { IdeMessengerContext } from "../../../../../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../../../../../redux/hooks";
import { updateConfig } from "../../../../../redux/slices/configSlice";
import { selectCurrentOrg } from "../../../../../redux/slices/profilesSlice";
import { fontSize } from "../../../../../util";
import { ToolTip } from "../../../../gui/Tooltip";
import { Button } from "../../../../ui";
import EditBlockButton from "../../EditBlockButton";
import { ExploreBlocksButton } from "../ExploreBlocksButton";
interface MCPServerStatusProps {
server: MCPServerStatus;
serverFromYaml?: NonNullable<ConfigYaml["mcpServers"]>[number];
}
function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) {
const ideMessenger = useContext(IdeMessengerContext);
const config = useAppSelector((store) => store.config.config);
const dispatch = useAppDispatch();
const updateMCPServerStatus = (status: MCPServerStatus["status"]) => {
// optimistic config update
dispatch(
updateConfig({
...config,
mcpServerStatuses: config.mcpServerStatuses.map((s) =>
s.id === server.id
? {
...s,
status,
}
: s,
),
}),
);
};
const onAuthenticate = async () => {
updateMCPServerStatus("authenticating");
await ideMessenger.request("mcp/startAuthentication", server);
};
const onRemoveAuth = async () => {
updateMCPServerStatus("authenticating");
await ideMessenger.request("mcp/removeAuthentication", server);
};
const onRefresh = async () => {
updateMCPServerStatus("connecting");
ideMessenger.post("mcp/reloadServer", {
id: server.id,
});
};
return (
<div
style={{
fontSize: fontSize(-2),
}}
className={`flex flex-row items-center justify-between gap-3 ${server.status === "authenticating" ? "my-0.5" : ""}`}
>
<div className="flex flex-row items-center gap-3">
{/* Name and Status */}
<span className="m-0 font-semibold">{server.name}</span>
{/* Error indicator if any */}
{server.errors.length ? (
<ToolTip
clickable
delayHide={
server.errors.some((error) => error.length > 150) ? 1500 : 0
}
className="flex flex-col gap-0.5"
content={server.errors.map((error, idx) => (
<Fragment key={idx}>
<div>
{error.length > 150 ? error.substring(0, 150) + "..." : error}
</div>
{error.length > 150 && (
<Button
className="my-0"
size="sm"
variant="ghost"
onClick={() =>
void ideMessenger.ide.showVirtualFile(server.name, error)
}
>
View full error
</Button>
)}
</Fragment>
))}
>
<InformationCircleIcon
className={`h-3 w-3 ${server.status === "error" ? "text-red-500" : "text-yellow-500"}`}
/>
</ToolTip>
) : null}
{/* Tools, Prompts, Resources with counts */}
<div className="flex flex-row items-center gap-3">
<ToolTip
className="flex flex-col gap-0.5"
content={
<>
{server.tools.map((tool, idx) => (
<code key={idx}>{tool.name}</code>
))}
{server.tools.length === 0 && (
<span className="text-lightgray">No tools</span>
)}
</>
}
>
<div className="flex cursor-zoom-in items-center gap-1 hover:opacity-80">
<WrenchScrewdriverIcon className="h-3 w-3" />
<span className="text-xs">{server.tools.length}</span>
</div>
</ToolTip>
<ToolTip
className="flex flex-col gap-0.5"
content={
<>
{server.prompts.map((prompt, idx) => (
<code key={idx}>{prompt.name}</code>
))}
{server.prompts.length === 0 && (
<span className="text-lightgray">No prompts</span>
)}
</>
}
>
<div className="flex cursor-zoom-in items-center gap-1 hover:opacity-80">
<CommandLineIcon className="h-3 w-3" />
<span className="text-xs">{server.prompts.length}</span>
</div>
</ToolTip>
<ToolTip
className="flex flex-col gap-0.5"
content={
<>
{[...server.resources, ...server.resourceTemplates].map(
(resource, idx) => (
<code key={idx}>{resource.name}</code>
),
)}
{server.resources.length === 0 && (
<span className="text-lightgray">No resources</span>
)}
</>
}
>
<div className="flex cursor-zoom-in items-center gap-1 hover:opacity-80">
<CircleStackIcon className="h-3 w-3" />
<span className="text-xs">
{server.resources.length + server.resourceTemplates.length}
</span>
</div>
</ToolTip>
</div>
</div>
<div className="flex items-center gap-2">
{server.isProtectedResource && (
<ToolTip
place="left"
hidden={server.status === "authenticating"}
content={server.status === "error" ? "Authenticate" : "Logout"}
>
<div className="text-lightgray flex cursor-pointer items-center hover:text-white hover:opacity-80">
{server.status === "error" ? (
<ShieldExclamationIcon
className="h-3 w-3"
onClick={onAuthenticate}
/>
) : server.status === "authenticating" ? (
<GlobeAltIcon className="animate-spin-slow h-3 w-3" />
) : (
<ShieldCheckIcon className="h-3 w-3" onClick={onRemoveAuth} />
)}
</div>
</ToolTip>
)}
<EditBlockButton
blockType={"mcpServers"}
block={serverFromYaml}
sourceFile={server.sourceFile}
/>
<div
className="text-lightgray flex cursor-pointer items-center hover:opacity-80"
onClick={onRefresh}
>
<ArrowPathIcon className="h-3 w-3" />
</div>
<div
className="hidden h-2 w-2 rounded-full sm:flex"
style={{
backgroundColor:
server.status === "connected"
? "#22c55e" // green-500
: server.status === "connecting"
? "#eab308" // yellow-500
: server.status === "not-connected"
? "#78716c" // stone-500
: "#ef4444", // red-500 for error
}}
/>
</div>
</div>
);
}
function MCPSection() {
const currentOrg = useAppSelector(selectCurrentOrg);
const servers = useAppSelector(
(store) => store.config.config.mcpServerStatuses,
);
const { selectedProfile } = useAuth();
const disableMcp = currentOrg?.policy?.allowMcpServers === false;
const mergedBlocks = useMemo(() => {
const parsed = selectedProfile?.rawYaml
? parseConfigYaml(selectedProfile?.rawYaml ?? "")
: undefined;
return (servers ?? []).map((doc, index) => ({
block: doc,
blockFromYaml: parsed?.mcpServers?.[index],
}));
}, [servers, selectedProfile]);
if (disableMcp) {
return (
<div className="flex flex-col items-center justify-center p-2">
<span className="text-description">
MCP servers are disabled in your organization
</span>
</div>
);
}
return (
<div className="flex flex-col gap-1">
<div className="flex max-h-[170px] flex-col gap-1 overflow-y-auto overflow-x-hidden pr-2">
{mergedBlocks.map(({ block, blockFromYaml }, idx) => (
<MCPServerPreview
key={idx}
server={block}
serverFromYaml={blockFromYaml}
/>
))}
</div>
<ExploreBlocksButton blockType="mcpServers" />
</div>
);
}
export default MCPSection;

View file

@ -1,18 +0,0 @@
import { useAppSelector } from "../../../../../redux/hooks";
export const McpSectionTooltip = () => {
const mcpServers = useAppSelector(
(store) => store.config.config.mcpServerStatuses,
);
const numServers = mcpServers.length;
const numActiveServers = mcpServers.filter(
(server) => server.status === "connected",
).length;
return (
<div>
<span>{`MCP Servers (${numActiveServers}/${numServers} active)`}</span>
</div>
);
};

View file

@ -1,110 +0,0 @@
import { MessageModes, Tool } from "core";
import { useMemo } from "react";
import { useAppDispatch, useAppSelector } from "../../../../../redux/hooks";
import { toggleToolGroupSetting } from "../../../../../redux/slices/uiSlice";
import { fontSize } from "../../../../../util";
import Alert from "../../../../gui/Alert";
import ToggleSwitch from "../../../../gui/Switch";
import ToolPolicyItem from "./ToolPolicyItem";
export const ToolPoliciesSection = () => {
const mode = useAppSelector((state) => state.session.mode);
const availableTools = useAppSelector((state) => state.config.config.tools);
const toolGroupSettings = useAppSelector(
(store) => store.ui.toolGroupSettings,
);
const dispatch = useAppDispatch();
const toolsByGroup = useMemo(() => {
const byGroup: Record<string, Tool[]> = {};
for (const tool of availableTools) {
if (!byGroup[tool.group]) {
byGroup[tool.group] = [];
}
byGroup[tool.group].push(tool);
}
return Object.entries(byGroup);
}, [availableTools]);
// Detect duplicate tool names
const duplicateDetection = useMemo(() => {
const counts: Record<string, number> = {};
availableTools.forEach((tool) => {
if (counts[tool.function.name]) {
counts[tool.function.name] = counts[tool.function.name] + 1;
} else {
counts[tool.function.name] = 1;
}
});
return Object.fromEntries(
Object.entries(counts).map(([k, v]) => [k, v > 1]),
);
}, [availableTools]);
const allToolsOff = mode === "chat";
const getMessage = (mode: MessageModes) => {
switch (mode) {
case "chat":
return "All tools disabled in Chat, switch to Plan or Agent mode to use tools";
case "plan":
return "Read-only/MCP tools available in Plan mode";
default:
return "";
}
};
const message = getMessage(mode);
return (
<>
{(mode === "chat" || mode === "plan") && (
<div className="bg-background sticky top-0 z-10 my-1 mb-3">
<Alert type="info" size="sm">
<span className="text-2xs italic">{message}</span>
</Alert>
</div>
)}
{toolsByGroup.length === 0 && (
<span className="text-description text-sm italic">
No tools available
</span>
)}
{toolsByGroup.map(([groupName, tools]) => {
const isGroupEnabled =
!allToolsOff && toolGroupSettings[groupName] !== "exclude";
return (
<div key={groupName} className="mt-2 flex flex-col pr-1">
<div className="flex flex-row items-center justify-between px-1">
<h3
className="m-0 p-0 font-bold"
style={{
fontSize: fontSize(-2),
}}
>
{groupName}
</h3>
<ToggleSwitch
isToggled={isGroupEnabled}
onToggle={() => dispatch(toggleToolGroupSetting(groupName))}
text=""
size={10}
disabled={allToolsOff}
/>
</div>
<div className={`relative flex flex-col p-1`}>
{tools.map((tool) => (
<ToolPolicyItem
key={tool.uri + tool.function.name}
tool={tool}
duplicatesDetected={duplicateDetection[tool.function.name]}
isGroupEnabled={isGroupEnabled}
/>
))}
</div>
</div>
);
})}
</>
);
};

Some files were not shown because too many files have changed in this diff Show more