Merge branch 'main' into abort2error
This commit is contained in:
commit
035263e888
164 changed files with 10046 additions and 1694 deletions
1
.github/workflows/cli-pr-checks.yml
vendored
1
.github/workflows/cli-pr-checks.yml
vendored
|
|
@ -59,6 +59,7 @@ jobs:
|
|||
matrix:
|
||||
os: [ubuntu-latest, windows-latest, macos-latest]
|
||||
node-version: [18, 20, 22, 24]
|
||||
fail-fast: false
|
||||
runs-on: ${{ matrix.os }}
|
||||
|
||||
steps:
|
||||
|
|
|
|||
2
.github/workflows/compliance.yaml
vendored
2
.github/workflows/compliance.yaml
vendored
|
|
@ -41,7 +41,7 @@ jobs:
|
|||
|
||||
- name: Add PR title guidance comment
|
||||
if: always() && steps.pr-title-check.outputs.valid == 'false'
|
||||
uses: actions/github-script@v7
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
const { data: comments } = await github.rest.issues.listComments({
|
||||
|
|
|
|||
2
.github/workflows/label-merged-prs.yml
vendored
2
.github/workflows/label-merged-prs.yml
vendored
|
|
@ -44,7 +44,7 @@ jobs:
|
|||
|
||||
- name: Determine and apply tier label
|
||||
if: steps.check-author.outputs.should_label == 'true'
|
||||
uses: actions/github-script@v7
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
const pr = context.payload.pull_request;
|
||||
|
|
|
|||
2
.github/workflows/main.yaml
vendored
2
.github/workflows/main.yaml
vendored
|
|
@ -20,7 +20,7 @@ jobs:
|
|||
- id: check
|
||||
working-directory: .
|
||||
run: |
|
||||
if [[ "${{ github.event.release.tag_name }}" == v1.0.*-vscode ]]; then
|
||||
if [[ "${{ github.event.release.tag_name }}" == v1.2.*-vscode ]]; then
|
||||
echo "should_run=true" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "should_run=false" >> $GITHUB_OUTPUT
|
||||
|
|
|
|||
30
.github/workflows/respond-to-cubic.yaml
vendored
30
.github/workflows/respond-to-cubic.yaml
vendored
|
|
@ -27,6 +27,18 @@ jobs:
|
|||
echo "contains_mention=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Add eyes reaction to comment
|
||||
if: steps.check-mention.outputs.contains_mention == 'true'
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
await github.rest.reactions.createForIssueComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
comment_id: ${{ github.event.comment.id }},
|
||||
content: 'eyes'
|
||||
});
|
||||
|
||||
- name: Checkout PR branch
|
||||
if: steps.check-mention.outputs.contains_mention == 'true'
|
||||
uses: actions/checkout@v5
|
||||
|
|
@ -37,7 +49,7 @@ jobs:
|
|||
- name: Get PR information
|
||||
if: steps.check-mention.outputs.contains_mention == 'true'
|
||||
id: pr-info
|
||||
uses: actions/github-script@v7
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
const { data: pr } = await github.rest.pulls.get({
|
||||
|
|
@ -95,7 +107,7 @@ jobs:
|
|||
|
||||
- name: Comment with session URL
|
||||
if: steps.check-mention.outputs.contains_mention == 'true' && steps.remote-session.outputs.session_url
|
||||
uses: actions/github-script@v7
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
const commentBody = `I've started [a remote session](${{ steps.remote-session.outputs.session_url }}) to help with your request:
|
||||
|
|
@ -130,6 +142,18 @@ jobs:
|
|||
echo "contains_mention=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Add eyes reaction to comment
|
||||
if: steps.check-mention.outputs.contains_mention == 'true'
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
await github.rest.reactions.createForPullRequestReviewComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
comment_id: ${{ github.event.comment.id }},
|
||||
content: 'eyes'
|
||||
});
|
||||
|
||||
- name: Checkout PR branch
|
||||
if: steps.check-mention.outputs.contains_mention == 'true'
|
||||
uses: actions/checkout@v5
|
||||
|
|
@ -187,7 +211,7 @@ jobs:
|
|||
|
||||
- name: Comment with session URL
|
||||
if: steps.check-mention.outputs.contains_mention == 'true' && steps.remote-session.outputs.session_url
|
||||
uses: actions/github-script@v7
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
const commentBody = `I've started [a remote session](${{ steps.remote-session.outputs.session_url }}) to help with your request:
|
||||
|
|
|
|||
4
.github/workflows/similar-issues.yml
vendored
4
.github/workflows/similar-issues.yml
vendored
|
|
@ -190,7 +190,7 @@ jobs:
|
|||
echo "confidence=$CONFIDENCE" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Comment with analysis
|
||||
uses: actions/github-script@v7
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
let comment = '';
|
||||
|
|
@ -307,7 +307,7 @@ jobs:
|
|||
|
||||
- name: Add labels
|
||||
if: github.event_name == 'issues'
|
||||
uses: actions/github-script@v7
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
const labels = [];
|
||||
|
|
|
|||
|
|
@ -23,5 +23,5 @@ CHANGELOG.md
|
|||
**/CODEOWNERS
|
||||
core/vendor
|
||||
coverage
|
||||
e2e
|
||||
# e2e
|
||||
packages/continue-sdk
|
||||
|
|
@ -176,9 +176,9 @@ See [`intellij/CONTRIBUTING.md`](./extensions/intellij/CONTRIBUTING.md) for the
|
|||
### Our Git Workflow
|
||||
|
||||
We keep a single permanent branch: `main`. When we are ready to create a "pre-release" version, we create a tag on the
|
||||
`main` branch titled `v1.1.x-vscode`, which automatically triggers the workflow
|
||||
`main` branch titled `v1.3.x-vscode`, which automatically triggers the workflow
|
||||
in [preview.yaml](./.github/workflows/preview.yaml), which builds and releases a version of the VS Code extension. When
|
||||
a release has been sufficiently tested, we will create a new release titled `v1.0x-vscode`, triggering a similar
|
||||
a release has been sufficiently tested, we will create a new release titled `v1.2.x-vscode`, triggering a similar
|
||||
workflow in [main.yaml](./.github/workflows/main.yaml), which will build and release a main release of the VS Code
|
||||
extension. Any hotfixes can be made by creating a feature branch from the tag for the release in question. This workflow
|
||||
is well explained by <http://releaseflow.org>.
|
||||
|
|
|
|||
|
|
@ -73,7 +73,7 @@ runs:
|
|||
- name: Install Continue CLI
|
||||
if: env.SKIP_REVIEW != 'true'
|
||||
shell: bash
|
||||
run: npm install -g @continuedev/cli@1.4.25
|
||||
run: npm install -g @continuedev/cli@1.4.30
|
||||
|
||||
- name: Build Inline Review Prompt
|
||||
if: env.SKIP_REVIEW != 'true'
|
||||
|
|
@ -194,6 +194,21 @@ runs:
|
|||
exit 1
|
||||
fi
|
||||
|
||||
# Validate API key
|
||||
if [ -z "$CONTINUE_API_KEY" ]; then
|
||||
echo "Warning: CONTINUE_API_KEY environment variable is not set"
|
||||
# Create fallback review and continue
|
||||
cat > inline_review.json << 'EOF'
|
||||
{
|
||||
"review_summary": "AI review skipped: CONTINUE_API_KEY not configured.",
|
||||
"comments": []
|
||||
}
|
||||
EOF
|
||||
echo "SKIP_CLI=true" >> $GITHUB_ENV
|
||||
else
|
||||
echo "SKIP_CLI=false" >> $GITHUB_ENV
|
||||
fi
|
||||
|
||||
# Log the prompt for debugging
|
||||
echo "===== START REVIEW PROMPT ====="
|
||||
head -n 50 inline_review_prompt.txt
|
||||
|
|
@ -201,23 +216,67 @@ runs:
|
|||
tail -n 20 inline_review_prompt.txt
|
||||
echo "===== END REVIEW PROMPT ====="
|
||||
|
||||
# Run the CLI and capture JSON output
|
||||
cn --readonly --format json --org "${{ inputs.continue-org }}" --config "${{ inputs.continue-config }}" -p "$(cat inline_review_prompt.txt)" > inline_review_raw.json
|
||||
|
||||
# Log the output for debugging
|
||||
echo "Initial Continue CLI output:"
|
||||
cat inline_review_raw.json
|
||||
|
||||
# Validate JSON output and use it directly
|
||||
if ! jq empty inline_review_raw.json 2>/dev/null; then
|
||||
echo "Error: Invalid JSON output from Continue CLI"
|
||||
exit 1
|
||||
# Test Continue CLI availability
|
||||
if [ "$SKIP_CLI" != "true" ]; then
|
||||
echo "Testing Continue CLI..."
|
||||
if ! cn --version; then
|
||||
echo "Warning: Continue CLI not found or not working"
|
||||
cat > inline_review.json << 'EOF'
|
||||
{
|
||||
"review_summary": "AI review skipped: Continue CLI installation failed.",
|
||||
"comments": []
|
||||
}
|
||||
EOF
|
||||
echo "SKIP_CLI=true" >> $GITHUB_ENV
|
||||
else
|
||||
echo "Continue CLI version: $(cn --version)"
|
||||
fi
|
||||
fi
|
||||
|
||||
# Run the CLI and capture JSON output with error handling
|
||||
if [ "$SKIP_CLI" != "true" ]; then
|
||||
echo "Executing Continue CLI with config: ${{ inputs.continue-org }}/${{ inputs.continue-config }}"
|
||||
|
||||
# Write prompt to temp file for better handling
|
||||
PROMPT_FILE="/tmp/continue-prompt-$.txt"
|
||||
cp inline_review_prompt.txt "$PROMPT_FILE"
|
||||
|
||||
# Use timeout to prevent hanging (240 seconds = 4 minutes)
|
||||
if ! timeout 240 cn --config "${{ inputs.continue-org }}/${{ inputs.continue-config }}" -p "@$PROMPT_FILE" --allow Bash --format json > inline_review_raw.json 2>cli_error.log; then
|
||||
echo "Warning: Continue CLI command failed"
|
||||
echo "CLI error log:"
|
||||
cat cli_error.log
|
||||
|
||||
# Create fallback review
|
||||
cat > inline_review.json << 'EOF'
|
||||
{
|
||||
"review_summary": "AI review failed due to service initialization issues. Please check the Continue API key and configuration.",
|
||||
"comments": []
|
||||
}
|
||||
EOF
|
||||
echo "Created fallback review due to CLI failure"
|
||||
else
|
||||
# Log the output for debugging
|
||||
echo "Initial Continue CLI output:"
|
||||
cat inline_review_raw.json
|
||||
|
||||
# Validate JSON output and use it directly
|
||||
if ! jq empty inline_review_raw.json 2>/dev/null; then
|
||||
echo "Warning: Invalid JSON output from Continue CLI, using fallback"
|
||||
cat > inline_review.json << 'EOF'
|
||||
{
|
||||
"review_summary": "AI review completed but failed to parse output correctly.",
|
||||
"comments": []
|
||||
}
|
||||
EOF
|
||||
else
|
||||
# Use the JSON output directly
|
||||
cp inline_review_raw.json inline_review.json
|
||||
echo "Review output:"
|
||||
cat inline_review.json
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# Use the JSON output directly
|
||||
cp inline_review_raw.json inline_review.json
|
||||
echo "Review output:"
|
||||
cat inline_review.json
|
||||
|
||||
- name: Post Inline Review Comments
|
||||
if: env.SKIP_REVIEW != 'true'
|
||||
|
|
|
|||
|
|
@ -68,7 +68,7 @@ runs:
|
|||
- name: Install Continue CLI
|
||||
if: env.SHOULD_RUN == 'true'
|
||||
shell: bash
|
||||
run: npm install -g @continuedev/cli@1.4.25
|
||||
run: npm install -g @continuedev/cli@1.4.30
|
||||
|
||||
- name: Build PR Review Prompt
|
||||
if: env.SHOULD_RUN == 'true'
|
||||
|
|
@ -157,6 +157,24 @@ runs:
|
|||
echo "=================================="
|
||||
echo ""
|
||||
|
||||
# Validate API key
|
||||
if [ -z "$CONTINUE_API_KEY" ]; then
|
||||
echo "Warning: CONTINUE_API_KEY environment variable is not set"
|
||||
# Create fallback review and continue
|
||||
cat > code_review.md << 'EOF'
|
||||
## Code Review Summary
|
||||
|
||||
⚠️ AI review skipped: CONTINUE_API_KEY not configured.
|
||||
|
||||
### Configuration Required
|
||||
- Please set the CONTINUE_API_KEY secret in repository settings
|
||||
- Verify that the organization and config path are valid
|
||||
EOF
|
||||
echo "SKIP_CLI=true" >> $GITHUB_ENV
|
||||
else
|
||||
echo "SKIP_CLI=false" >> $GITHUB_ENV
|
||||
fi
|
||||
|
||||
# Validate inputs to prevent command injection
|
||||
if [[ ! "$CONTINUE_ORG" =~ ^[a-zA-Z0-9_-]+$ ]]; then
|
||||
echo "Error: Invalid organization name. Must contain only alphanumeric characters, hyphens, and underscores."
|
||||
|
|
@ -168,8 +186,55 @@ runs:
|
|||
exit 1
|
||||
fi
|
||||
|
||||
# Run the CLI with validated config
|
||||
cn --readonly --org "$CONTINUE_ORG" --config "$CONTINUE_CONFIG" -p "$(cat review_prompt.txt)" > code_review.md
|
||||
# Test Continue CLI availability
|
||||
if [ "$SKIP_CLI" != "true" ]; then
|
||||
echo "Testing Continue CLI..."
|
||||
if ! cn --version; then
|
||||
echo "Warning: Continue CLI not found or not working"
|
||||
cat > code_review.md << 'EOF'
|
||||
## Code Review Summary
|
||||
|
||||
⚠️ AI review skipped: Continue CLI installation failed.
|
||||
|
||||
### Troubleshooting
|
||||
- Check that npm installation succeeded
|
||||
- Verify @continuedev/cli package is available
|
||||
EOF
|
||||
echo "SKIP_CLI=true" >> $GITHUB_ENV
|
||||
else
|
||||
echo "Continue CLI version: $(cn --version)"
|
||||
fi
|
||||
fi
|
||||
|
||||
# Run the CLI with validated config and error handling
|
||||
if [ "$SKIP_CLI" != "true" ]; then
|
||||
echo "Executing Continue CLI with config: $CONTINUE_ORG/$CONTINUE_CONFIG"
|
||||
|
||||
# Write prompt to temp file for better handling
|
||||
PROMPT_FILE="/tmp/continue-prompt-$.txt"
|
||||
cp review_prompt.txt "$PROMPT_FILE"
|
||||
|
||||
# Use timeout to prevent hanging (240 seconds = 4 minutes)
|
||||
if ! timeout 240 cn --config "$CONTINUE_ORG/$CONTINUE_CONFIG" -p "@$PROMPT_FILE" --allow Bash > code_review.md 2>cli_error.log; then
|
||||
echo "Error: Continue CLI command failed"
|
||||
echo "CLI error log:"
|
||||
cat cli_error.log
|
||||
|
||||
# Create fallback review
|
||||
cat > code_review.md << 'EOF'
|
||||
## Code Review Summary
|
||||
|
||||
⚠️ AI review failed due to service initialization issues. Please check the Continue API key and configuration.
|
||||
|
||||
### Troubleshooting
|
||||
- Verify the CONTINUE_API_KEY secret is set correctly
|
||||
- Check that the organization and config path are valid
|
||||
- Ensure the Continue service is accessible
|
||||
EOF
|
||||
else
|
||||
echo "Review generated successfully"
|
||||
fi
|
||||
fi
|
||||
|
||||
- name: Upload Review Results
|
||||
if: env.SHOULD_RUN == 'true' && always()
|
||||
|
|
|
|||
2
binary/package-lock.json
generated
2
binary/package-lock.json
generated
|
|
@ -106,6 +106,7 @@
|
|||
"quick-lru": "^7.0.0",
|
||||
"replicate": "^0.26.0",
|
||||
"request": "^2.88.2",
|
||||
"shell-quote": "^1.8.3",
|
||||
"socket.io-client": "^4.7.3",
|
||||
"sqlite": "^5.1.1",
|
||||
"sqlite3": "^5.1.7",
|
||||
|
|
@ -140,6 +141,7 @@
|
|||
"@types/pg": "^8.11.6",
|
||||
"@types/plist": "^3.0.5",
|
||||
"@types/request": "^2.48.12",
|
||||
"@types/shell-quote": "^1.7.5",
|
||||
"@types/tar": "^6.1.13",
|
||||
"@types/uuid": "^9.0.7",
|
||||
"@types/win-ca": "^3.5.4",
|
||||
|
|
|
|||
|
|
@ -202,6 +202,8 @@ export class ConfigHandler {
|
|||
message: `Error loading Continue Hub assistants${e instanceof Error ? ":\n" + e.message : ""}`,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
PolicySingleton.getInstance().policy = null;
|
||||
}
|
||||
// Load local org if not signed in or hub orgs fail
|
||||
try {
|
||||
|
|
|
|||
|
|
@ -57,6 +57,7 @@ import {
|
|||
} from "../util/paths";
|
||||
import { localPathToUri } from "../util/pathToUri";
|
||||
|
||||
import { PolicySingleton } from "../control-plane/PolicySingleton";
|
||||
import CustomContextProviderClass from "../context/providers/CustomContextProvider";
|
||||
import { getBaseToolDefinitions } from "../tools";
|
||||
import { resolveRelativePathInDir } from "../util/ideUtils";
|
||||
|
|
@ -544,16 +545,21 @@ async function intermediateToFinalConfig({
|
|||
|
||||
// Trigger MCP server refreshes (Config is reloaded again once connected!)
|
||||
const mcpManager = MCPManagerSingleton.getInstance();
|
||||
mcpManager.setConnections(
|
||||
(config.experimental?.modelContextProtocolServers ?? []).map(
|
||||
(server, index) => ({
|
||||
id: `continue-mcp-server-${index + 1}`,
|
||||
name: `MCP Server`,
|
||||
...server,
|
||||
}),
|
||||
),
|
||||
false,
|
||||
);
|
||||
const orgPolicy = PolicySingleton.getInstance().policy;
|
||||
if (orgPolicy?.policy?.allowMcpServers === false) {
|
||||
await mcpManager.shutdown();
|
||||
} else {
|
||||
mcpManager.setConnections(
|
||||
(config.experimental?.modelContextProtocolServers ?? []).map(
|
||||
(server, index) => ({
|
||||
id: `continue-mcp-server-${index + 1}`,
|
||||
name: `MCP Server`,
|
||||
...server,
|
||||
}),
|
||||
),
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
// Handle experimental modelRole config values for apply and edit
|
||||
const inlineEditModel = getModelByRole(continueConfig, "inlineEdit")?.title;
|
||||
|
|
|
|||
|
|
@ -332,12 +332,14 @@ export default async function doLoadConfig(options: {
|
|||
}
|
||||
}
|
||||
|
||||
if (
|
||||
PolicySingleton.getInstance().policy?.policy?.allowAnonymousTelemetry ===
|
||||
false
|
||||
) {
|
||||
// Org policies
|
||||
const policy = PolicySingleton.getInstance().policy?.policy;
|
||||
if (policy?.allowAnonymousTelemetry === false) {
|
||||
newConfig.allowAnonymousTelemetry = false;
|
||||
}
|
||||
if (policy?.allowCodebaseIndexing === false) {
|
||||
newConfig.disableIndexing = true;
|
||||
}
|
||||
|
||||
// Setup telemetry only after (and if) we know it is enabled
|
||||
await Telemetry.setup(
|
||||
|
|
|
|||
|
|
@ -25,6 +25,7 @@ import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
|
|||
import { convertPromptBlockToSlashCommand } from "../../commands/slash/promptBlockSlashCommand";
|
||||
import { slashCommandFromPromptFile } from "../../commands/slash/promptFileSlashCommand";
|
||||
import { getControlPlaneEnvSync } from "../../control-plane/env";
|
||||
import { PolicySingleton } from "../../control-plane/PolicySingleton";
|
||||
import { getBaseToolDefinitions } from "../../tools";
|
||||
import { getCleanUriPath } from "../../util/uri";
|
||||
import { loadConfigContextProviders } from "../loadContextProviders";
|
||||
|
|
@ -378,21 +379,26 @@ async function configYamlToContinueConfig(options: {
|
|||
|
||||
// Trigger MCP server refreshes (Config is reloaded again once connected!)
|
||||
const mcpManager = MCPManagerSingleton.getInstance();
|
||||
mcpManager.setConnections(
|
||||
(config.mcpServers ?? []).map((server) => ({
|
||||
id: server.name,
|
||||
name: server.name,
|
||||
sourceFile: server.sourceFile,
|
||||
transport: {
|
||||
type: "stdio",
|
||||
args: [],
|
||||
...(server as any), // TODO: fix the types on mcpServers in config-yaml
|
||||
},
|
||||
timeout: server.connectionTimeout,
|
||||
})),
|
||||
false,
|
||||
{ ide },
|
||||
);
|
||||
const orgPolicy = PolicySingleton.getInstance().policy;
|
||||
if (orgPolicy?.policy?.allowMcpServers === false) {
|
||||
await mcpManager.shutdown();
|
||||
} else {
|
||||
mcpManager.setConnections(
|
||||
(config.mcpServers ?? []).map((server) => ({
|
||||
id: server.name,
|
||||
name: server.name,
|
||||
sourceFile: server.sourceFile,
|
||||
transport: {
|
||||
type: "stdio",
|
||||
args: [],
|
||||
...(server as any), // TODO: fix the types on mcpServers in config-yaml
|
||||
},
|
||||
timeout: server.connectionTimeout,
|
||||
})),
|
||||
false,
|
||||
{ ide },
|
||||
);
|
||||
}
|
||||
|
||||
return { config: continueConfig, errors: localErrors };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -48,6 +48,21 @@ export class MCPManagerSingleton {
|
|||
this.connections.delete(id);
|
||||
}
|
||||
|
||||
async shutdown() {
|
||||
if (this.connections.size > 0) {
|
||||
await Promise.allSettled(
|
||||
Array.from(this.connections.entries()).map(([id, connection]) => {
|
||||
try {
|
||||
connection.abortController.abort();
|
||||
void connection.client.close();
|
||||
} finally {
|
||||
this.connections.delete(id);
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
setConnections(
|
||||
servers: MCPOptions[],
|
||||
forceRefresh: boolean,
|
||||
|
|
|
|||
31
core/core.ts
31
core/core.ts
|
|
@ -1009,6 +1009,37 @@ export class Core {
|
|||
this.handleToolCall(toolCall),
|
||||
);
|
||||
|
||||
on(
|
||||
"tools/evaluatePolicy",
|
||||
async ({ data: { toolName, basePolicy, args } }) => {
|
||||
const { config } = await this.configHandler.loadConfig();
|
||||
if (!config) {
|
||||
throw new Error("Config not loaded");
|
||||
}
|
||||
|
||||
const tool = config.tools.find((t) => t.function.name === toolName);
|
||||
if (!tool) {
|
||||
// Tool not found, return base policy
|
||||
return { policy: basePolicy };
|
||||
}
|
||||
|
||||
// Extract display value for specific tools
|
||||
let displayValue: string | undefined;
|
||||
if (toolName === "runTerminalCommand" && args.command) {
|
||||
displayValue = args.command as string;
|
||||
}
|
||||
|
||||
// If tool has evaluateToolCallPolicy function, use it
|
||||
if (tool.evaluateToolCallPolicy) {
|
||||
const evaluatedPolicy = tool.evaluateToolCallPolicy(basePolicy, args);
|
||||
return { policy: evaluatedPolicy, displayValue };
|
||||
}
|
||||
|
||||
// Otherwise return base policy unchanged
|
||||
return { policy: basePolicy, displayValue };
|
||||
},
|
||||
);
|
||||
|
||||
on("isItemTooBig", async ({ data: { item } }) => {
|
||||
return this.isItemTooBig(item);
|
||||
});
|
||||
|
|
|
|||
9
core/index.d.ts
vendored
9
core/index.d.ts
vendored
|
|
@ -1070,11 +1070,6 @@ export interface ToolExtras {
|
|||
codeBaseIndexer?: CodebaseIndexer;
|
||||
}
|
||||
|
||||
export type ToolPolicy =
|
||||
| "allowedWithPermission"
|
||||
| "allowedWithoutPermission"
|
||||
| "disabled";
|
||||
|
||||
export interface Tool {
|
||||
type: "function";
|
||||
function: {
|
||||
|
|
@ -1099,6 +1094,10 @@ export interface Tool {
|
|||
exampleArgs?: Array<[string, string | number]>;
|
||||
};
|
||||
defaultToolPolicy?: ToolPolicy;
|
||||
evaluateToolCallPolicy?: (
|
||||
basePolicy: ToolPolicy,
|
||||
parsedArgs: Record<string, unknown>,
|
||||
) => ToolPolicy;
|
||||
}
|
||||
|
||||
interface ToolChoice {
|
||||
|
|
|
|||
40
core/package-lock.json
generated
40
core/package-lock.json
generated
|
|
@ -17,6 +17,7 @@
|
|||
"@continuedev/fetch": "file:../packages/fetch",
|
||||
"@continuedev/llm-info": "file:../packages/llm-info",
|
||||
"@continuedev/openai-adapters": "file:../packages/openai-adapters",
|
||||
"@continuedev/terminal-security": "file:../packages/terminal-security",
|
||||
"@modelcontextprotocol/sdk": "^1.12.0",
|
||||
"@mozilla/readability": "^0.5.0",
|
||||
"@octokit/rest": "^20.1.1",
|
||||
|
|
@ -67,6 +68,7 @@
|
|||
"quick-lru": "^7.0.0",
|
||||
"replicate": "^0.26.0",
|
||||
"request": "^2.88.2",
|
||||
"shell-quote": "^1.8.3",
|
||||
"socket.io-client": "^4.7.3",
|
||||
"sqlite": "^5.1.1",
|
||||
"sqlite3": "^5.1.7",
|
||||
|
|
@ -101,6 +103,7 @@
|
|||
"@types/pg": "^8.11.6",
|
||||
"@types/plist": "^3.0.5",
|
||||
"@types/request": "^2.48.12",
|
||||
"@types/shell-quote": "^1.7.5",
|
||||
"@types/tar": "^6.1.13",
|
||||
"@types/uuid": "^9.0.7",
|
||||
"@types/win-ca": "^3.5.4",
|
||||
|
|
@ -236,6 +239,20 @@
|
|||
"vitest": "^3.2.4"
|
||||
}
|
||||
},
|
||||
"../packages/terminal-security": {
|
||||
"name": "@continuedev/terminal-security",
|
||||
"version": "1.0.0",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"shell-quote": "^1.8.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.11.19",
|
||||
"@types/shell-quote": "^1.7.5",
|
||||
"typescript": "^5.5.2",
|
||||
"vitest": "^1.6.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@75lb/deep-merge": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/@75lb/deep-merge/-/deep-merge-1.1.2.tgz",
|
||||
|
|
@ -2955,6 +2972,10 @@
|
|||
"resolved": "../packages/openai-adapters",
|
||||
"link": true
|
||||
},
|
||||
"node_modules/@continuedev/terminal-security": {
|
||||
"resolved": "../packages/terminal-security",
|
||||
"link": true
|
||||
},
|
||||
"node_modules/@dabh/diagnostics": {
|
||||
"version": "2.0.3",
|
||||
"resolved": "https://registry.npmjs.org/@dabh/diagnostics/-/diagnostics-2.0.3.tgz",
|
||||
|
|
@ -6892,6 +6913,13 @@
|
|||
"node": ">= 0.12"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/shell-quote": {
|
||||
"version": "1.7.5",
|
||||
"resolved": "https://registry.npmjs.org/@types/shell-quote/-/shell-quote-1.7.5.tgz",
|
||||
"integrity": "sha512-+UE8GAGRPbJVQDdxi16dgadcBfQ+KG2vgZhV1+3A1XmHbmwcdwhCUwIdy+d3pAGrbvgRoVSjeI9vOWyq376Yzw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/shimmer": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/shimmer/-/shimmer-1.2.0.tgz",
|
||||
|
|
@ -17459,6 +17487,18 @@
|
|||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/shell-quote": {
|
||||
"version": "1.8.3",
|
||||
"resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.3.tgz",
|
||||
"integrity": "sha512-ObmnIF4hXNg1BqhnHmgbDETF8dLPCggZWBjkQfhZpbszZnYur5DUljTcCHii5LC3J5E0yeO/1LIMyH+UvHQgyw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/shiki": {
|
||||
"version": "3.7.0",
|
||||
"resolved": "https://registry.npmjs.org/shiki/-/shiki-3.7.0.tgz",
|
||||
|
|
|
|||
|
|
@ -34,6 +34,7 @@
|
|||
"@types/pg": "^8.11.6",
|
||||
"@types/plist": "^3.0.5",
|
||||
"@types/request": "^2.48.12",
|
||||
"@types/shell-quote": "^1.7.5",
|
||||
"@types/tar": "^6.1.13",
|
||||
"@types/uuid": "^9.0.7",
|
||||
"@types/win-ca": "^3.5.4",
|
||||
|
|
@ -61,6 +62,7 @@
|
|||
"@continuedev/fetch": "file:../packages/fetch",
|
||||
"@continuedev/llm-info": "file:../packages/llm-info",
|
||||
"@continuedev/openai-adapters": "file:../packages/openai-adapters",
|
||||
"@continuedev/terminal-security": "file:../packages/terminal-security",
|
||||
"@modelcontextprotocol/sdk": "^1.12.0",
|
||||
"@mozilla/readability": "^0.5.0",
|
||||
"@octokit/rest": "^20.1.1",
|
||||
|
|
@ -111,6 +113,7 @@
|
|||
"quick-lru": "^7.0.0",
|
||||
"replicate": "^0.26.0",
|
||||
"request": "^2.88.2",
|
||||
"shell-quote": "^1.8.3",
|
||||
"socket.io-client": "^4.7.3",
|
||||
"sqlite": "^5.1.1",
|
||||
"sqlite3": "^5.1.7",
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import {
|
|||
DevDataLogEvent,
|
||||
ModelRole,
|
||||
} from "@continuedev/config-yaml";
|
||||
import { ToolPolicy } from "@continuedev/terminal-security";
|
||||
|
||||
import {
|
||||
AutocompleteInput,
|
||||
|
|
@ -293,6 +294,10 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
{ toolCall: ToolCall },
|
||||
{ contextItems: ContextItem[]; errorMessage?: string },
|
||||
];
|
||||
"tools/evaluatePolicy": [
|
||||
{ toolName: string; basePolicy: ToolPolicy; args: Record<string, unknown> },
|
||||
{ policy: ToolPolicy; displayValue?: string },
|
||||
];
|
||||
"clipboardCache/add": [{ content: string }, void];
|
||||
"controlPlane/openUrl": [{ path: string; orgSlug?: string }, void];
|
||||
"controlPlane/getEnvironment": [undefined, ControlPlaneEnv];
|
||||
|
|
|
|||
|
|
@ -78,6 +78,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
|
|||
"didChangeSelectedProfile",
|
||||
"didChangeSelectedOrg",
|
||||
"tools/call",
|
||||
"tools/evaluatePolicy",
|
||||
"controlPlane/getEnvironment",
|
||||
"controlPlane/getFreeTrialStatus",
|
||||
"controlPlane/getModelsAddOnUpgradeUrl",
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
export enum BuiltInToolNames {
|
||||
ReadFile = "read_file",
|
||||
ReadFileRange = "read_file_range",
|
||||
EditExistingFile = "edit_existing_file",
|
||||
SingleFindAndReplace = "single_find_and_replace",
|
||||
MultiEdit = "multi_edit",
|
||||
|
|
|
|||
|
|
@ -12,6 +12,8 @@ import { grepSearchImpl } from "./implementations/grepSearch";
|
|||
import { lsToolImpl } from "./implementations/lsTool";
|
||||
import { readCurrentlyOpenFileImpl } from "./implementations/readCurrentlyOpenFile";
|
||||
import { readFileImpl } from "./implementations/readFile";
|
||||
|
||||
import { readFileRangeImpl } from "./implementations/readFileRange";
|
||||
import { requestRuleImpl } from "./implementations/requestRule";
|
||||
import { runTerminalCommandImpl } from "./implementations/runTerminalCommand";
|
||||
import { searchWebImpl } from "./implementations/searchWeb";
|
||||
|
|
@ -145,6 +147,8 @@ export async function callBuiltInTool(
|
|||
switch (functionName) {
|
||||
case BuiltInToolNames.ReadFile:
|
||||
return await readFileImpl(args, extras);
|
||||
case BuiltInToolNames.ReadFileRange:
|
||||
return await readFileRangeImpl(args, extras);
|
||||
case BuiltInToolNames.CreateNewFile:
|
||||
return await createNewFileImpl(args, extras);
|
||||
case BuiltInToolNames.GrepSearch:
|
||||
|
|
|
|||
|
|
@ -9,6 +9,8 @@ export { lsTool } from "./ls";
|
|||
export { multiEditTool } from "./multiEdit";
|
||||
export { readCurrentlyOpenFileTool } from "./readCurrentlyOpenFile";
|
||||
export { readFileTool } from "./readFile";
|
||||
|
||||
export { readFileRangeTool } from "./readFileRange";
|
||||
export { requestRuleTool } from "./requestRule";
|
||||
export { runTerminalCommandTool } from "./runTerminalCommand";
|
||||
export { searchWebTool } from "./searchWeb";
|
||||
|
|
|
|||
51
core/tools/definitions/readFileRange.ts
Normal file
51
core/tools/definitions/readFileRange.ts
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
import { Tool } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
|
||||
export const readFileRangeTool: Tool = {
|
||||
type: "function",
|
||||
displayTitle: "Read File Range",
|
||||
wouldLikeTo:
|
||||
"read lines {{{ startLine }}}-{{{ endLine }}} of {{{ filepath }}}",
|
||||
isCurrently:
|
||||
"reading lines {{{ startLine }}}-{{{ endLine }}} of {{{ filepath }}}",
|
||||
hasAlready:
|
||||
"viewed lines {{{ startLine }}}-{{{ endLine }}} of {{{ filepath }}}",
|
||||
readonly: true,
|
||||
isInstant: true,
|
||||
group: BUILT_IN_GROUP_NAME,
|
||||
function: {
|
||||
name: BuiltInToolNames.ReadFileRange,
|
||||
description:
|
||||
"Use this tool to read a specific range of lines from an existing file. Only supports positive line numbers (1-based from start). For reading from the end of a file, use the terminal tool with 'tail' command instead.",
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["filepath", "startLine", "endLine"],
|
||||
properties: {
|
||||
filepath: {
|
||||
type: "string",
|
||||
description:
|
||||
"The path of the file to read, relative to the root of the workspace (NOT uri or absolute path)",
|
||||
},
|
||||
startLine: {
|
||||
type: "number",
|
||||
description:
|
||||
"The starting line number (1-based from start). Must be a positive integer. Example: 1 = first line, 10 = tenth line",
|
||||
},
|
||||
endLine: {
|
||||
type: "number",
|
||||
description:
|
||||
"The ending line number (1-based from start). Must be a positive integer greater than or equal to startLine. Example: 10 = tenth line, 20 = twentieth line",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
systemMessageDescription: {
|
||||
prefix: `To read a specific range of lines from a file, use the ${BuiltInToolNames.ReadFileRange} tool. Only supports positive line numbers (1-based from start). For reading from the end of files, use the terminal tool with 'tail' command instead:`,
|
||||
exampleArgs: [
|
||||
["filepath", "path/to/the_file.txt"],
|
||||
["startLine", 10],
|
||||
["endLine", 20],
|
||||
],
|
||||
},
|
||||
defaultToolPolicy: "allowedWithoutPermission",
|
||||
};
|
||||
|
|
@ -1,6 +1,10 @@
|
|||
import os from "os";
|
||||
import { Tool } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
import {
|
||||
evaluateTerminalCommandSecurity,
|
||||
ToolPolicy,
|
||||
} from "@continuedev/terminal-security";
|
||||
|
||||
/**
|
||||
* Get the preferred shell for the current platform
|
||||
|
|
@ -56,6 +60,15 @@ export const runTerminalCommandTool: Tool = {
|
|||
},
|
||||
},
|
||||
defaultToolPolicy: "allowedWithPermission",
|
||||
evaluateToolCallPolicy: (
|
||||
basePolicy: ToolPolicy,
|
||||
parsedArgs: Record<string, unknown>,
|
||||
): ToolPolicy => {
|
||||
return evaluateTerminalCommandSecurity(
|
||||
basePolicy,
|
||||
parsedArgs.command as string,
|
||||
);
|
||||
},
|
||||
systemMessageDescription: {
|
||||
prefix: `To run a terminal command, use the ${BuiltInToolNames.RunTerminalCommand} tool
|
||||
${RUN_COMMAND_NOTES}
|
||||
|
|
|
|||
204
core/tools/implementations/readFileRange.integration.vitest.ts
Normal file
204
core/tools/implementations/readFileRange.integration.vitest.ts
Normal file
|
|
@ -0,0 +1,204 @@
|
|||
import { expect, test, vi } from "vitest";
|
||||
import { ToolExtras } from "../..";
|
||||
import { readFileRangeImpl } from "./readFileRange";
|
||||
|
||||
// Mock the dependencies
|
||||
vi.mock("../../util/ideUtils", () => ({
|
||||
resolveRelativePathInDir: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../../util/uri", () => ({
|
||||
getUriPathBasename: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("./readFileLimit", () => ({
|
||||
throwIfFileExceedsHalfOfContext: vi.fn(),
|
||||
}));
|
||||
|
||||
test("readFileRangeImpl handles out-of-bounds ranges gracefully", async () => {
|
||||
const { resolveRelativePathInDir } = await import("../../util/ideUtils");
|
||||
const { getUriPathBasename } = await import("../../util/uri");
|
||||
const { throwIfFileExceedsHalfOfContext } = await import("./readFileLimit");
|
||||
|
||||
// Mock the utility functions
|
||||
vi.mocked(resolveRelativePathInDir).mockResolvedValue("file:///test.txt");
|
||||
vi.mocked(getUriPathBasename).mockReturnValue("test.txt");
|
||||
vi.mocked(throwIfFileExceedsHalfOfContext).mockResolvedValue(undefined);
|
||||
|
||||
// Test case 1: Start line beyond end of file
|
||||
const mockIdeOutOfBounds = {
|
||||
readRangeInFile: vi.fn().mockResolvedValue(""), // IDE returns empty string
|
||||
};
|
||||
|
||||
const mockExtras1 = {
|
||||
ide: mockIdeOutOfBounds,
|
||||
config: { selectedModelByRole: { chat: { contextLength: 8192 } } },
|
||||
} as unknown as ToolExtras;
|
||||
|
||||
const result1 = await readFileRangeImpl(
|
||||
{
|
||||
filepath: "test.txt",
|
||||
startLine: 100, // Beyond end of file
|
||||
endLine: 105,
|
||||
},
|
||||
mockExtras1,
|
||||
);
|
||||
|
||||
expect(result1).toHaveLength(1);
|
||||
expect(result1[0].content).toBe("");
|
||||
expect(result1[0].description).toBe("test.txt (lines 100-105)");
|
||||
|
||||
// Test case 2: End line beyond end of file
|
||||
const mockIdePartialRange = {
|
||||
readRangeInFile: vi.fn().mockResolvedValue("line5\nline6"), // IDE returns available content
|
||||
};
|
||||
|
||||
const mockExtras2 = {
|
||||
ide: mockIdePartialRange,
|
||||
config: { selectedModelByRole: { chat: { contextLength: 8192 } } },
|
||||
} as unknown as ToolExtras;
|
||||
|
||||
const result2 = await readFileRangeImpl(
|
||||
{
|
||||
filepath: "test.txt",
|
||||
startLine: 5,
|
||||
endLine: 100, // Beyond end of file
|
||||
},
|
||||
mockExtras2,
|
||||
);
|
||||
|
||||
expect(result2).toHaveLength(1);
|
||||
expect(result2[0].content).toBe("line5\nline6");
|
||||
expect(result2[0].description).toBe("test.txt (lines 5-100)");
|
||||
|
||||
// Verify that IDE methods were called with correct 0-based ranges
|
||||
expect(mockIdeOutOfBounds.readRangeInFile).toHaveBeenCalledWith(
|
||||
"file:///test.txt",
|
||||
{
|
||||
start: { line: 99, character: 0 }, // 100 - 1
|
||||
end: { line: 104, character: Number.MAX_SAFE_INTEGER }, // 105 - 1
|
||||
},
|
||||
);
|
||||
|
||||
expect(mockIdePartialRange.readRangeInFile).toHaveBeenCalledWith(
|
||||
"file:///test.txt",
|
||||
{
|
||||
start: { line: 4, character: 0 }, // 5 - 1
|
||||
end: { line: 99, character: Number.MAX_SAFE_INTEGER }, // 100 - 1
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test("readFileRangeImpl validates line number constraints", async () => {
|
||||
const mockExtras = {
|
||||
ide: { readRangeInFile: vi.fn(), readFile: vi.fn() },
|
||||
config: { selectedModelByRole: { chat: { contextLength: 8192 } } },
|
||||
} as unknown as ToolExtras;
|
||||
|
||||
// Test startLine < 1 (invalid)
|
||||
await expect(
|
||||
readFileRangeImpl(
|
||||
{
|
||||
filepath: "test.txt",
|
||||
startLine: 0,
|
||||
endLine: 5,
|
||||
},
|
||||
mockExtras,
|
||||
),
|
||||
).rejects.toThrow("startLine must be 1 or greater");
|
||||
|
||||
// Test negative startLine (no longer supported)
|
||||
await expect(
|
||||
readFileRangeImpl(
|
||||
{
|
||||
filepath: "test.txt",
|
||||
startLine: -1,
|
||||
endLine: 5,
|
||||
},
|
||||
mockExtras,
|
||||
),
|
||||
).rejects.toThrow("Negative line numbers are not supported");
|
||||
|
||||
// Test endLine < 1 (invalid)
|
||||
await expect(
|
||||
readFileRangeImpl(
|
||||
{
|
||||
filepath: "test.txt",
|
||||
startLine: 1,
|
||||
endLine: 0,
|
||||
},
|
||||
mockExtras,
|
||||
),
|
||||
).rejects.toThrow("endLine must be 1 or greater");
|
||||
|
||||
// Test negative endLine (no longer supported)
|
||||
await expect(
|
||||
readFileRangeImpl(
|
||||
{
|
||||
filepath: "test.txt",
|
||||
startLine: 1,
|
||||
endLine: -1,
|
||||
},
|
||||
mockExtras,
|
||||
),
|
||||
).rejects.toThrow("Negative line numbers are not supported");
|
||||
|
||||
// Test endLine < startLine
|
||||
await expect(
|
||||
readFileRangeImpl(
|
||||
{
|
||||
filepath: "test.txt",
|
||||
startLine: 10,
|
||||
endLine: 5,
|
||||
},
|
||||
mockExtras,
|
||||
),
|
||||
).rejects.toThrow(
|
||||
"endLine (5) must be greater than or equal to startLine (10)",
|
||||
);
|
||||
});
|
||||
|
||||
test("readFileRangeImpl handles normal ranges correctly", async () => {
|
||||
const { resolveRelativePathInDir } = await import("../../util/ideUtils");
|
||||
const { getUriPathBasename } = await import("../../util/uri");
|
||||
const { throwIfFileExceedsHalfOfContext } = await import("./readFileLimit");
|
||||
|
||||
vi.mocked(resolveRelativePathInDir).mockResolvedValue("file:///test.txt");
|
||||
vi.mocked(getUriPathBasename).mockReturnValue("test.txt");
|
||||
vi.mocked(throwIfFileExceedsHalfOfContext).mockResolvedValue(undefined);
|
||||
|
||||
const mockIde = {
|
||||
readRangeInFile: vi.fn().mockResolvedValue("line2\nline3\nline4"),
|
||||
};
|
||||
|
||||
const mockExtras = {
|
||||
ide: mockIde,
|
||||
config: { selectedModelByRole: { chat: { contextLength: 8192 } } },
|
||||
} as unknown as ToolExtras;
|
||||
|
||||
const result = await readFileRangeImpl(
|
||||
{
|
||||
filepath: "src/test.py",
|
||||
startLine: 2,
|
||||
endLine: 4,
|
||||
},
|
||||
mockExtras,
|
||||
);
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]).toEqual({
|
||||
name: "test.txt",
|
||||
description: "src/test.py (lines 2-4)",
|
||||
content: "line2\nline3\nline4",
|
||||
uri: {
|
||||
type: "file",
|
||||
value: "file:///test.txt",
|
||||
},
|
||||
});
|
||||
|
||||
// Verify correct 0-based conversion
|
||||
expect(mockIde.readRangeInFile).toHaveBeenCalledWith("file:///test.txt", {
|
||||
start: { line: 1, character: 0 }, // 2 - 1
|
||||
end: { line: 3, character: Number.MAX_SAFE_INTEGER }, // 4 - 1
|
||||
});
|
||||
});
|
||||
68
core/tools/implementations/readFileRange.ts
Normal file
68
core/tools/implementations/readFileRange.ts
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
import { resolveRelativePathInDir } from "../../util/ideUtils";
|
||||
import { getUriPathBasename } from "../../util/uri";
|
||||
|
||||
import { ToolImpl } from ".";
|
||||
import { getNumberArg, getStringArg } from "../parseArgs";
|
||||
import { throwIfFileExceedsHalfOfContext } from "./readFileLimit";
|
||||
|
||||
export const readFileRangeImpl: ToolImpl = async (args, extras) => {
|
||||
const filepath = getStringArg(args, "filepath");
|
||||
const startLine = getNumberArg(args, "startLine");
|
||||
const endLine = getNumberArg(args, "endLine");
|
||||
|
||||
// Validate that line numbers are positive integers
|
||||
if (startLine < 1) {
|
||||
throw new Error(
|
||||
"startLine must be 1 or greater. Negative line numbers are not supported - use the terminal tool with 'tail' command for reading from file end.",
|
||||
);
|
||||
}
|
||||
if (endLine < 1) {
|
||||
throw new Error(
|
||||
"endLine must be 1 or greater. Negative line numbers are not supported - use the terminal tool with 'tail' command for reading from file end.",
|
||||
);
|
||||
}
|
||||
if (endLine < startLine) {
|
||||
throw new Error(
|
||||
`endLine (${endLine}) must be greater than or equal to startLine (${startLine})`,
|
||||
);
|
||||
}
|
||||
|
||||
const firstUriMatch = await resolveRelativePathInDir(filepath, extras.ide);
|
||||
if (!firstUriMatch) {
|
||||
throw new Error(
|
||||
`File "${filepath}" does not exist. You might want to check the path and try again.`,
|
||||
);
|
||||
}
|
||||
|
||||
// Use the IDE's readRangeInFile method with 0-based range (IDE expects 0-based internally)
|
||||
const content = await extras.ide.readRangeInFile(firstUriMatch, {
|
||||
start: {
|
||||
line: startLine - 1, // Convert from 1-based to 0-based
|
||||
character: 0,
|
||||
},
|
||||
end: {
|
||||
line: endLine - 1, // Convert from 1-based to 0-based
|
||||
character: Number.MAX_SAFE_INTEGER, // Read to end of line
|
||||
},
|
||||
});
|
||||
|
||||
await throwIfFileExceedsHalfOfContext(
|
||||
filepath,
|
||||
content,
|
||||
extras.config.selectedModelByRole.chat,
|
||||
);
|
||||
|
||||
const rangeDescription = `${filepath} (lines ${startLine}-${endLine})`;
|
||||
|
||||
return [
|
||||
{
|
||||
name: getUriPathBasename(firstUriMatch),
|
||||
description: rangeDescription,
|
||||
content,
|
||||
uri: {
|
||||
type: "file",
|
||||
value: firstUriMatch,
|
||||
},
|
||||
},
|
||||
];
|
||||
};
|
||||
60
core/tools/implementations/readFileRange.vitest.ts
Normal file
60
core/tools/implementations/readFileRange.vitest.ts
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
import { expect, test } from "vitest";
|
||||
import { getNumberArg } from "../parseArgs";
|
||||
|
||||
test("readFileRange should validate positive line number arguments", () => {
|
||||
// Test positive startLine validation
|
||||
expect(() => getNumberArg({ startLine: 1 }, "startLine")).not.toThrow();
|
||||
expect(() => getNumberArg({ startLine: "1" }, "startLine")).not.toThrow();
|
||||
expect(() => getNumberArg({ startLine: 100 }, "startLine")).not.toThrow();
|
||||
|
||||
// Test positive endLine validation
|
||||
expect(() => getNumberArg({ endLine: 5 }, "endLine")).not.toThrow();
|
||||
expect(() => getNumberArg({ endLine: "10" }, "endLine")).not.toThrow();
|
||||
expect(() => getNumberArg({ endLine: 1000 }, "endLine")).not.toThrow();
|
||||
|
||||
// Test missing arguments
|
||||
expect(() => getNumberArg({}, "startLine")).toThrow(
|
||||
"Argument `startLine` is required (type number)",
|
||||
);
|
||||
expect(() => getNumberArg({}, "endLine")).toThrow(
|
||||
"Argument `endLine` is required (type number)",
|
||||
);
|
||||
|
||||
// Test invalid arguments
|
||||
expect(() =>
|
||||
getNumberArg({ startLine: "not-a-number" }, "startLine"),
|
||||
).toThrow("Argument `startLine` must be a valid number");
|
||||
expect(() => getNumberArg({ endLine: true }, "endLine")).toThrow(
|
||||
"Argument `endLine` must be a valid number",
|
||||
);
|
||||
});
|
||||
|
||||
test("readFileRange should handle line number conversion", () => {
|
||||
// Test that our parsing function converts correctly
|
||||
expect(getNumberArg({ line: 1 }, "line")).toBe(1);
|
||||
expect(getNumberArg({ line: "5" }, "line")).toBe(5);
|
||||
expect(getNumberArg({ line: 10.7 }, "line")).toBe(10); // Should floor
|
||||
expect(getNumberArg({ line: "15.9" }, "line")).toBe(15); // Should floor
|
||||
});
|
||||
|
||||
test("readFileRange parses negative numbers (validation happens in implementation)", () => {
|
||||
// The parseArgs function should parse negative numbers correctly
|
||||
// but the implementation will reject them with helpful error messages
|
||||
expect(getNumberArg({ line: -1 }, "line")).toBe(-1);
|
||||
expect(getNumberArg({ line: -10 }, "line")).toBe(-10);
|
||||
expect(getNumberArg({ line: "-5" }, "line")).toBe(-5);
|
||||
});
|
||||
|
||||
test("readFileRange handles out-of-bounds ranges gracefully", () => {
|
||||
// IDE implementations handle out-of-bounds gracefully:
|
||||
// - VS Code: Uses array.slice() which handles out-of-bounds gracefully
|
||||
// - IntelliJ: Uses lines.getOrNull() which returns null for out-of-bounds
|
||||
// Both return empty content or available content without throwing errors
|
||||
|
||||
expect(() => {
|
||||
const startLine = getNumberArg({ startLine: 1000 }, "startLine");
|
||||
const endLine = getNumberArg({ endLine: 2000 }, "endLine");
|
||||
expect(startLine).toBe(1000);
|
||||
expect(endLine).toBe(2000);
|
||||
}).not.toThrow();
|
||||
});
|
||||
|
|
@ -1,4 +1,12 @@
|
|||
import { jest } from "@jest/globals";
|
||||
import {
|
||||
describe,
|
||||
it,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach,
|
||||
afterAll,
|
||||
vi,
|
||||
} from "vitest";
|
||||
import * as childProcess from "node:child_process";
|
||||
import * as fs from "node:fs";
|
||||
import * as os from "node:os";
|
||||
|
|
@ -6,17 +14,18 @@ import * as path from "node:path";
|
|||
import { IDE, ToolExtras } from "../..";
|
||||
import * as processBackgroundStates from "../../util/processTerminalBackgroundStates";
|
||||
import { runTerminalCommandImpl } from "./runTerminalCommand";
|
||||
import { runTerminalCommandTool } from "../definitions/runTerminalCommand";
|
||||
|
||||
// We're using real child processes, so ensure these aren't mocked
|
||||
jest.unmock("node:child_process");
|
||||
jest.unmock("node:util");
|
||||
vi.unmock("node:child_process");
|
||||
vi.unmock("node:util");
|
||||
|
||||
describe("runTerminalCommandImpl", () => {
|
||||
// Setup mocks and spies
|
||||
const mockGetIdeInfo = jest.fn();
|
||||
const mockGetWorkspaceDirs = jest.fn();
|
||||
const mockOnPartialOutput = jest.fn();
|
||||
const mockRunCommand = jest.fn();
|
||||
const mockGetIdeInfo = vi.fn();
|
||||
const mockGetWorkspaceDirs = vi.fn();
|
||||
const mockOnPartialOutput = vi.fn();
|
||||
const mockRunCommand = vi.fn();
|
||||
|
||||
// Use a simple approach to ensure background processes are terminated
|
||||
let testPid: number | null = null;
|
||||
|
|
@ -27,7 +36,7 @@ describe("runTerminalCommandImpl", () => {
|
|||
);
|
||||
|
||||
beforeEach(() => {
|
||||
jest.resetAllMocks();
|
||||
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
|
||||
|
|
@ -73,7 +82,7 @@ describe("runTerminalCommandImpl", () => {
|
|||
// Helper function to create a ToolExtras object
|
||||
const createMockExtras = (
|
||||
overrides: Partial<{
|
||||
onPartialOutput?: jest.Mock;
|
||||
onPartialOutput?: any;
|
||||
remoteName?: string;
|
||||
}> = {},
|
||||
): ToolExtras => {
|
||||
|
|
@ -90,16 +99,16 @@ describe("runTerminalCommandImpl", () => {
|
|||
getWorkspaceDirs: mockGetWorkspaceDirs,
|
||||
runCommand: mockRunCommand,
|
||||
// Add stubs for other required IDE methods
|
||||
getIdeSettings: jest.fn(),
|
||||
getDiff: jest.fn(),
|
||||
getClipboardContent: jest.fn(),
|
||||
isTelemetryEnabled: jest.fn(),
|
||||
readFile: jest.fn(),
|
||||
writeFile: jest.fn(),
|
||||
renameFile: jest.fn(),
|
||||
deleteFile: jest.fn(),
|
||||
globFiles: jest.fn(),
|
||||
ls: jest.fn(),
|
||||
getIdeSettings: vi.fn(),
|
||||
getDiff: vi.fn(),
|
||||
getClipboardContent: vi.fn(),
|
||||
isTelemetryEnabled: vi.fn(),
|
||||
readFile: vi.fn(),
|
||||
writeFile: vi.fn(),
|
||||
renameFile: vi.fn(),
|
||||
deleteFile: vi.fn(),
|
||||
globFiles: vi.fn(),
|
||||
ls: vi.fn(),
|
||||
};
|
||||
|
||||
// Create a base ToolExtras object with required properties
|
||||
|
|
@ -147,7 +156,7 @@ describe("runTerminalCommandImpl", () => {
|
|||
"`;
|
||||
|
||||
const args = { command, waitForCompletion: true };
|
||||
const mockOutputFn = jest.fn();
|
||||
const mockOutputFn = vi.fn();
|
||||
const extras = createMockExtras({ onPartialOutput: mockOutputFn });
|
||||
|
||||
// Execute the command with streaming
|
||||
|
|
@ -191,7 +200,7 @@ describe("runTerminalCommandImpl", () => {
|
|||
"`;
|
||||
|
||||
const args = { command, waitForCompletion: false };
|
||||
const mockOutputFn = jest.fn();
|
||||
const mockOutputFn = vi.fn();
|
||||
const extras = createMockExtras({ onPartialOutput: mockOutputFn });
|
||||
|
||||
const result = await runTerminalCommandImpl(args, extras);
|
||||
|
|
@ -355,25 +364,25 @@ describe("runTerminalCommandImpl", () => {
|
|||
|
||||
it("should handle missing workspace directory gracefully", async () => {
|
||||
// Mock IDE to return empty workspace directories
|
||||
const mockEmptyWorkspace = jest.fn().mockReturnValue(Promise.resolve([]));
|
||||
const mockEmptyWorkspace = vi.fn().mockReturnValue(Promise.resolve([]));
|
||||
|
||||
// Create IDE mock with empty workspace
|
||||
const mockIde = {
|
||||
getIdeInfo: jest
|
||||
getIdeInfo: vi
|
||||
.fn()
|
||||
.mockReturnValue(Promise.resolve({ remoteName: "local" })),
|
||||
getWorkspaceDirs: mockEmptyWorkspace,
|
||||
runCommand: jest.fn(),
|
||||
getIdeSettings: jest.fn(),
|
||||
getDiff: jest.fn(),
|
||||
getClipboardContent: jest.fn(),
|
||||
isTelemetryEnabled: jest.fn(),
|
||||
readFile: jest.fn(),
|
||||
writeFile: jest.fn(),
|
||||
renameFile: jest.fn(),
|
||||
deleteFile: jest.fn(),
|
||||
globFiles: jest.fn(),
|
||||
ls: jest.fn(),
|
||||
runCommand: vi.fn(),
|
||||
getIdeSettings: vi.fn(),
|
||||
getDiff: vi.fn(),
|
||||
getClipboardContent: vi.fn(),
|
||||
isTelemetryEnabled: vi.fn(),
|
||||
readFile: vi.fn(),
|
||||
writeFile: vi.fn(),
|
||||
renameFile: vi.fn(),
|
||||
deleteFile: vi.fn(),
|
||||
globFiles: vi.fn(),
|
||||
ls: vi.fn(),
|
||||
};
|
||||
|
||||
const extras = {
|
||||
|
|
@ -402,7 +411,7 @@ describe("runTerminalCommandImpl", () => {
|
|||
|
||||
it("should handle case where cwd fallbacks all fail", async () => {
|
||||
// Mock IDE to return empty workspace directories
|
||||
const mockEmptyWorkspace = jest.fn().mockReturnValue(Promise.resolve([]));
|
||||
const mockEmptyWorkspace = vi.fn().mockReturnValue(Promise.resolve([]));
|
||||
|
||||
// Save original environment variables and process.cwd
|
||||
const originalHome = process.env.HOME;
|
||||
|
|
@ -413,27 +422,27 @@ describe("runTerminalCommandImpl", () => {
|
|||
// Mock all fallbacks to fail
|
||||
delete process.env.HOME;
|
||||
delete process.env.USERPROFILE;
|
||||
process.cwd = jest.fn().mockImplementation(() => {
|
||||
process.cwd = vi.fn().mockImplementation(() => {
|
||||
throw new Error("Current directory unavailable");
|
||||
}) as jest.MockedFunction<() => string>;
|
||||
}) as any;
|
||||
|
||||
// Create IDE mock with empty workspace
|
||||
const mockIde = {
|
||||
getIdeInfo: jest
|
||||
getIdeInfo: vi
|
||||
.fn()
|
||||
.mockReturnValue(Promise.resolve({ remoteName: "local" })),
|
||||
getWorkspaceDirs: mockEmptyWorkspace,
|
||||
runCommand: jest.fn(),
|
||||
getIdeSettings: jest.fn(),
|
||||
getDiff: jest.fn(),
|
||||
getClipboardContent: jest.fn(),
|
||||
isTelemetryEnabled: jest.fn(),
|
||||
readFile: jest.fn(),
|
||||
writeFile: jest.fn(),
|
||||
renameFile: jest.fn(),
|
||||
deleteFile: jest.fn(),
|
||||
globFiles: jest.fn(),
|
||||
ls: jest.fn(),
|
||||
runCommand: vi.fn(),
|
||||
getIdeSettings: vi.fn(),
|
||||
getDiff: vi.fn(),
|
||||
getClipboardContent: vi.fn(),
|
||||
isTelemetryEnabled: vi.fn(),
|
||||
readFile: vi.fn(),
|
||||
writeFile: vi.fn(),
|
||||
renameFile: vi.fn(),
|
||||
deleteFile: vi.fn(),
|
||||
globFiles: vi.fn(),
|
||||
ls: vi.fn(),
|
||||
};
|
||||
|
||||
const extras = {
|
||||
|
|
@ -472,3 +481,125 @@ describe("runTerminalCommandImpl", () => {
|
|||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("runTerminalCommandTool.evaluateToolCallPolicy", () => {
|
||||
it("should return base policy for safe commands like echo", () => {
|
||||
const basePolicy = "allowedWithoutPermission";
|
||||
const args = { command: "echo hello world" };
|
||||
|
||||
const result = runTerminalCommandTool.evaluateToolCallPolicy!(
|
||||
basePolicy,
|
||||
args,
|
||||
);
|
||||
|
||||
expect(result).toBe("allowedWithoutPermission");
|
||||
});
|
||||
|
||||
it("should respect disabled policy even for non-echo commands", () => {
|
||||
const basePolicy = "disabled";
|
||||
const args = { command: "ls -la" };
|
||||
|
||||
const result = runTerminalCommandTool.evaluateToolCallPolicy!(
|
||||
basePolicy,
|
||||
args,
|
||||
);
|
||||
|
||||
expect(result).toBe("disabled");
|
||||
});
|
||||
|
||||
it("should respect disabled policy even for safe commands", () => {
|
||||
const basePolicy = "disabled";
|
||||
const args = { command: "echo test" };
|
||||
|
||||
const result = runTerminalCommandTool.evaluateToolCallPolicy!(
|
||||
basePolicy,
|
||||
args,
|
||||
);
|
||||
|
||||
expect(result).toBe("disabled");
|
||||
});
|
||||
|
||||
it("should return base policy for non-echo commands", () => {
|
||||
const basePolicy = "allowedWithoutPermission";
|
||||
const args = { command: "ls -la" };
|
||||
|
||||
const result = runTerminalCommandTool.evaluateToolCallPolicy!(
|
||||
basePolicy,
|
||||
args,
|
||||
);
|
||||
|
||||
expect(result).toBe("allowedWithoutPermission");
|
||||
});
|
||||
|
||||
it("should return base policy for git commands", () => {
|
||||
const basePolicy = "allowedWithPermission";
|
||||
const args = { command: "git status" };
|
||||
|
||||
const result = runTerminalCommandTool.evaluateToolCallPolicy!(
|
||||
basePolicy,
|
||||
args,
|
||||
);
|
||||
|
||||
expect(result).toBe("allowedWithPermission");
|
||||
});
|
||||
|
||||
it("should handle undefined command gracefully", () => {
|
||||
const basePolicy = "allowedWithoutPermission";
|
||||
const args = { command: undefined };
|
||||
|
||||
const result = runTerminalCommandTool.evaluateToolCallPolicy!(
|
||||
basePolicy,
|
||||
args,
|
||||
);
|
||||
|
||||
expect(result).toBe("allowedWithoutPermission");
|
||||
});
|
||||
|
||||
it("should handle null command gracefully", () => {
|
||||
const basePolicy = "allowedWithoutPermission";
|
||||
const args = { command: null };
|
||||
|
||||
const result = runTerminalCommandTool.evaluateToolCallPolicy!(
|
||||
basePolicy,
|
||||
args,
|
||||
);
|
||||
|
||||
expect(result).toBe("allowedWithoutPermission");
|
||||
});
|
||||
|
||||
it("should handle empty command string", () => {
|
||||
const basePolicy = "allowedWithoutPermission";
|
||||
const args = { command: "" };
|
||||
|
||||
const result = runTerminalCommandTool.evaluateToolCallPolicy!(
|
||||
basePolicy,
|
||||
args,
|
||||
);
|
||||
|
||||
expect(result).toBe("allowedWithoutPermission");
|
||||
});
|
||||
|
||||
it("should disable dangerous commands like rm -rf /", () => {
|
||||
const basePolicy = "allowedWithoutPermission";
|
||||
const args = { command: "rm -rf /" };
|
||||
|
||||
const result = runTerminalCommandTool.evaluateToolCallPolicy!(
|
||||
basePolicy,
|
||||
args,
|
||||
);
|
||||
|
||||
expect(result).toBe("disabled");
|
||||
});
|
||||
|
||||
it("should require permission for high-risk network commands", () => {
|
||||
const basePolicy = "allowedWithoutPermission";
|
||||
const args = { command: "curl http://example.com" };
|
||||
|
||||
const result = runTerminalCommandTool.evaluateToolCallPolicy!(
|
||||
basePolicy,
|
||||
args,
|
||||
);
|
||||
|
||||
expect(result).toBe("allowedWithPermission");
|
||||
});
|
||||
});
|
||||
|
|
@ -4,6 +4,7 @@ import * as toolDefinitions from "./definitions";
|
|||
// I'm writing these as functions because we've messed up 3 TIMES by pushing to const, causing duplicate tool definitions on subsequent config loads.
|
||||
export const getBaseToolDefinitions = () => [
|
||||
toolDefinitions.readFileTool,
|
||||
|
||||
toolDefinitions.createNewFileTool,
|
||||
toolDefinitions.runTerminalCommandTool,
|
||||
toolDefinitions.globSearchTool,
|
||||
|
|
@ -33,6 +34,7 @@ export const getConfigDependentToolDefinitions = (
|
|||
toolDefinitions.viewRepoMapTool,
|
||||
toolDefinitions.viewSubdirectoryTool,
|
||||
toolDefinitions.codebaseTool,
|
||||
toolDefinitions.readFileRangeTool,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -40,6 +40,24 @@ export function getOptionalStringArg(
|
|||
return getStringArg(args, argName, allowEmpty);
|
||||
}
|
||||
|
||||
export function getNumberArg(args: any, argName: string): number {
|
||||
if (!args || !(argName in args)) {
|
||||
throw new Error(`Argument \`${argName}\` is required (type number)`);
|
||||
}
|
||||
const value = args[argName];
|
||||
if (typeof value === "string") {
|
||||
const parsed = parseInt(value, 10);
|
||||
if (isNaN(parsed)) {
|
||||
throw new Error(`Argument \`${argName}\` must be a valid number`);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
if (typeof value !== "number" || isNaN(value)) {
|
||||
throw new Error(`Argument \`${argName}\` must be a valid number`);
|
||||
}
|
||||
return Math.floor(value); // Ensure integer for line numbers (supports negative numbers)
|
||||
}
|
||||
|
||||
export function getBooleanArg(args: any, argName: string, required = false) {
|
||||
if (!args || !(argName in args)) {
|
||||
if (required) {
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
|
|||
import { ToolCallDelta } from "..";
|
||||
import {
|
||||
getBooleanArg,
|
||||
getNumberArg,
|
||||
getOptionalStringArg,
|
||||
getStringArg,
|
||||
safeParseToolCallArgs,
|
||||
|
|
@ -246,3 +247,86 @@ describe("getBooleanArg", () => {
|
|||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getNumberArg", () => {
|
||||
it("should return number argument when valid", () => {
|
||||
const args = { count: 42 };
|
||||
const result = getNumberArg(args, "count");
|
||||
expect(result).toBe(42);
|
||||
});
|
||||
|
||||
it("should parse string numbers", () => {
|
||||
const args = { count: "42" };
|
||||
const result = getNumberArg(args, "count");
|
||||
expect(result).toBe(42);
|
||||
});
|
||||
|
||||
it("should floor decimal numbers", () => {
|
||||
const args = { count: 42.7 };
|
||||
const result = getNumberArg(args, "count");
|
||||
expect(result).toBe(42);
|
||||
});
|
||||
|
||||
it("should parse and floor string decimal numbers", () => {
|
||||
const args = { count: "42.7" };
|
||||
const result = getNumberArg(args, "count");
|
||||
expect(result).toBe(42);
|
||||
});
|
||||
|
||||
it("should throw error when argument is missing", () => {
|
||||
const args = { otherArg: 42 };
|
||||
expect(() => getNumberArg(args, "count")).toThrowError(
|
||||
"Argument `count` is required (type number)",
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw error when argument is not a number", () => {
|
||||
const argsString = { count: "not-a-number" };
|
||||
const argsBoolean = { count: true };
|
||||
const argsObject = { count: {} };
|
||||
|
||||
expect(() => getNumberArg(argsString, "count")).toThrowError(
|
||||
"Argument `count` must be a valid number",
|
||||
);
|
||||
expect(() => getNumberArg(argsBoolean, "count")).toThrowError(
|
||||
"Argument `count` must be a valid number",
|
||||
);
|
||||
expect(() => getNumberArg(argsObject, "count")).toThrowError(
|
||||
"Argument `count` must be a valid number",
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw error when argument is NaN", () => {
|
||||
const args = { count: NaN };
|
||||
expect(() => getNumberArg(args, "count")).toThrowError(
|
||||
"Argument `count` must be a valid number",
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle negative numbers", () => {
|
||||
const args = { count: -5 };
|
||||
const result = getNumberArg(args, "count");
|
||||
expect(result).toBe(-5);
|
||||
});
|
||||
|
||||
it("should handle negative string numbers", () => {
|
||||
const args = { count: "-10" };
|
||||
const result = getNumberArg(args, "count");
|
||||
expect(result).toBe(-10);
|
||||
});
|
||||
|
||||
it("should handle zero", () => {
|
||||
const args = { count: 0 };
|
||||
const result = getNumberArg(args, "count");
|
||||
expect(result).toBe(0);
|
||||
});
|
||||
|
||||
it("should handle null or undefined args", () => {
|
||||
expect(() => getNumberArg(null, "count")).toThrowError(
|
||||
"Argument `count` is required (type number)",
|
||||
);
|
||||
expect(() => getNumberArg(undefined, "count")).toThrowError(
|
||||
"Argument `count` is required (type number)",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -234,6 +234,7 @@
|
|||
"guides/continuous-ai",
|
||||
"guides/plan-mode-guide",
|
||||
"guides/ollama-guide",
|
||||
"guides/instinct",
|
||||
"guides/running-continue-without-internet",
|
||||
"guides/custom-code-rag",
|
||||
"guides/how-to-self-host-a-model"
|
||||
|
|
|
|||
|
|
@ -3,6 +3,6 @@ title: “Customize Autocomplete Settings in Continue”
|
|||
description: “Learn how to customize autocomplete behavior in Continue, including user settings, configuration options, and adjustments to improve AI code suggestions in your IDE.”
|
||||
---
|
||||
|
||||
Continue offers a handful of settings to customize autocomplete behavior. Visit the [User Settings Page](/customize/settings) to manage these settings.
|
||||
Continue offers a handful of settings to customize autocomplete behavior. Visit the User Settings Page (Gear Icon) to manage these settings.
|
||||
|
||||
For a comprehensive guide on all configuration options and their impacts, see the [Autocomplete deep dive](/customize/deep-dives/autocomplete).
|
||||
|
|
|
|||
|
|
@ -4,7 +4,8 @@ description: "Learn how Continue's Next Edit feature predicts and suggests your
|
|||
---
|
||||
|
||||
<Warning>
|
||||
Next Edit is currently an experimental feature. It requires [Mercury Coder
|
||||
Next Edit is currently an experimental feature. It requires
|
||||
[Instinct](https://hub.continue.dev/continuedev/instinct) or [Mercury Coder
|
||||
model](https://hub.continue.dev/inceptionlabs/mercury-coder) configured in
|
||||
your Continue autocomplete settings and is not yet available for JetBrains
|
||||
use.
|
||||
|
|
@ -71,18 +72,18 @@ Next Edit activates automatically when:
|
|||
|
||||
Next Edit requires:
|
||||
|
||||
- Compatible AI models (Mercury Coder)
|
||||
- Compatible AI models (Mercury Coder or Instinct)
|
||||
- Continue development team access
|
||||
- VS Code (JetBrains support coming soon)
|
||||
- **API Keys**: Organizations can add API keys to [org secrets](/hub/secrets/secret-types) for team-wide access. Individual users need to provide their own API keys in their [model configuration](/customize/model-providers/overview)
|
||||
|
||||
<Note>
|
||||
To use Next Edit, you must have the Mercury Coder model configured in your
|
||||
Continue autocomplete model settings. This model is specifically designed for
|
||||
next edit predictions. Once it's been loaded, you must reload VS Code to
|
||||
activate it.
|
||||
To use Next Edit, you must have the Instinct or Mercury Coder model configured
|
||||
in your Continue autocomplete model settings. This model is specifically
|
||||
designed for next edit predictions. Once it's been loaded, you must reload VS
|
||||
Code to activate it.
|
||||
<img
|
||||
src="/images/features/autocomplete/images/mercury-coder-next-edit.png"
|
||||
src="/images/features/autocomplete/images/instinct-autocomplete.png"
|
||||
alt="Next Edit Model Setup"
|
||||
/>
|
||||
</Note>
|
||||
|
|
@ -117,6 +118,7 @@ Next Edit requires:
|
|||
Next Edit requires AI models specifically trained for code prediction:
|
||||
|
||||
- **Mercury Coder**: Primary model optimized for next edit prediction
|
||||
- **Instinct**: The leading open Next Edit model, trained by Continue
|
||||
|
||||
### Automatic Detection
|
||||
|
||||
|
|
|
|||
|
|
@ -84,7 +84,6 @@ You can use the `gh` CLI to:
|
|||
#### DeepWiki MCP
|
||||
|
||||
[DeepWiki MCP](https://hub.continue.dev/deepwiki/deepwiki-mcp) lets your agent explore any public GitHub repository.
|
||||
```
|
||||
|
||||
Once configured, your agent can explore repositories like:
|
||||
- "Explore the React repository structure"
|
||||
|
|
@ -180,4 +179,4 @@ The new approach provides better integration with Continue's Agent features and
|
|||
|
||||
- Learn more about [MCP servers](/reference/continue-mcp)
|
||||
- Explore [rules configuration](/customize/deep-dives/rules)
|
||||
- Set up [custom assistants](/guides/understanding-assistants) with specific knowledge domains
|
||||
- Set up [custom assistants](/guides/understanding-assistants) with specific knowledge domains
|
||||
|
|
|
|||
39
docs/guides/instinct.mdx
Normal file
39
docs/guides/instinct.mdx
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
---
|
||||
title: "Using Instinct with Ollama in Continue"
|
||||
description: "Learn how to run Instinct, Continue's leading open Next Edit model, on your own hardware with Ollama"
|
||||
---
|
||||
|
||||
<Warning>
|
||||
Instinct is a 7 billion parameter model. You should expect slow responses if
|
||||
running on a laptop. To learn how to inference Instinct on a GPU, see our
|
||||
[HuggingFace model card](https://huggingface.co/continuedev/instinct).
|
||||
</Warning>
|
||||
|
||||
We recently released Instinct, a state-of-the-art open Next Edit model. Robustly fine-tuned from Qwen2.5-Coder-7B, Instinct intelligently predicts your next move to keep you in flow. To learn more about the model, check out [our blog post](https://blog.continue.dev).
|
||||
|
||||
<Frame>
|
||||
<img src="/images/instinct.gif" />
|
||||
</Frame>
|
||||
|
||||
### 1. Install Ollama
|
||||
|
||||
If you haven't already installed Ollama, see our guide [here](./ollama-guide.mdx).
|
||||
|
||||
### 2. Download Instinct
|
||||
|
||||
```bash
|
||||
ollama run nate/instinct
|
||||
```
|
||||
|
||||
### 3. Update your `config.yaml`
|
||||
|
||||
Open your `config.yaml` and add Instinct to the models section:
|
||||
|
||||
```yaml
|
||||
# ... rest of config.yaml ...
|
||||
|
||||
models:
|
||||
- uses: continuedev/instinct
|
||||
```
|
||||
|
||||
Alternatively, you can just click to add the block at https://hub.continue.dev/continuedev/instinct.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 66 KiB |
BIN
docs/images/instinct.gif
Normal file
BIN
docs/images/instinct.gif
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 2.3 MiB |
|
|
@ -408,4 +408,4 @@ The following configuration example includes:
|
|||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
This setup could also involve enabling Chromium as a backup for local documentation through the [User Settings Page](../customize/settings).
|
||||
This setup could also involve enabling Chromium as a backup for local documentation through the User Settings Page (Gear Icon).
|
||||
|
|
@ -117,11 +117,11 @@ export const ModelRecommendations = ({ role = "all" }) => {
|
|||
notes: "Open models are beginning to emerge for this model role",
|
||||
},
|
||||
next_edit: {
|
||||
open: ["N/A"],
|
||||
open: ["[Instinct](https://hub.continue.dev/continuedev/instinct)"],
|
||||
closed: [
|
||||
"[Mercury Coder](https://hub.continue.dev/inceptionlabs/mercury-coder)",
|
||||
],
|
||||
notes: "Closed models are significantly better than open models",
|
||||
notes: "Closed models are better than open models",
|
||||
},
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -68,6 +68,10 @@ try {
|
|||
__dirname,
|
||||
"../../packages/llm-info/dist/index.js",
|
||||
),
|
||||
"@continuedev/terminal-security": resolve(
|
||||
__dirname,
|
||||
"../../packages/terminal-security/dist/index.js",
|
||||
),
|
||||
},
|
||||
|
||||
// Add banner to create require for CommonJS packages
|
||||
|
|
|
|||
23
extensions/cli/package-lock.json
generated
23
extensions/cli/package-lock.json
generated
|
|
@ -18,6 +18,7 @@
|
|||
"@continuedev/config-yaml": "file:../../packages/config-yaml",
|
||||
"@continuedev/openai-adapters": "file:../../packages/openai-adapters",
|
||||
"@continuedev/sdk": "^0.0.13",
|
||||
"@continuedev/terminal-security": "file:../../packages/terminal-security",
|
||||
"@modelcontextprotocol/sdk": "^1.17.2",
|
||||
"@opentelemetry/api": "^1.9.0",
|
||||
"@opentelemetry/exporter-metrics-otlp-grpc": "^0.203.0",
|
||||
|
|
@ -123,6 +124,7 @@
|
|||
"@continuedev/fetch": "file:../packages/fetch",
|
||||
"@continuedev/llm-info": "file:../packages/llm-info",
|
||||
"@continuedev/openai-adapters": "file:../packages/openai-adapters",
|
||||
"@continuedev/terminal-security": "file:../packages/terminal-security",
|
||||
"@modelcontextprotocol/sdk": "^1.12.0",
|
||||
"@mozilla/readability": "^0.5.0",
|
||||
"@octokit/rest": "^20.1.1",
|
||||
|
|
@ -173,6 +175,7 @@
|
|||
"quick-lru": "^7.0.0",
|
||||
"replicate": "^0.26.0",
|
||||
"request": "^2.88.2",
|
||||
"shell-quote": "^1.8.3",
|
||||
"socket.io-client": "^4.7.3",
|
||||
"sqlite": "^5.1.1",
|
||||
"sqlite3": "^5.1.7",
|
||||
|
|
@ -207,6 +210,7 @@
|
|||
"@types/pg": "^8.11.6",
|
||||
"@types/plist": "^3.0.5",
|
||||
"@types/request": "^2.48.12",
|
||||
"@types/shell-quote": "^1.7.5",
|
||||
"@types/tar": "^6.1.13",
|
||||
"@types/uuid": "^9.0.7",
|
||||
"@types/win-ca": "^3.5.4",
|
||||
|
|
@ -294,6 +298,21 @@
|
|||
"vitest": "^3.2.4"
|
||||
}
|
||||
},
|
||||
"../../packages/terminal-security": {
|
||||
"name": "@continuedev/terminal-security",
|
||||
"version": "1.0.0",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"shell-quote": "^1.8.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.11.19",
|
||||
"@types/shell-quote": "^1.7.5",
|
||||
"typescript": "^5.5.2",
|
||||
"vitest": "^1.6.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@alcalzone/ansi-tokenize": {
|
||||
"version": "0.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@alcalzone/ansi-tokenize/-/ansi-tokenize-0.2.0.tgz",
|
||||
|
|
@ -386,6 +405,10 @@
|
|||
"openai": "^4.96.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@continuedev/terminal-security": {
|
||||
"resolved": "../../packages/terminal-security",
|
||||
"link": true
|
||||
},
|
||||
"node_modules/@cspotcode/source-map-support": {
|
||||
"version": "0.8.1",
|
||||
"resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz",
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@
|
|||
"test:e2e": "vitest run --config vitest.e2e.config.ts",
|
||||
"test:smoke": "node smoke-test.mjs",
|
||||
"build:tsc": "tsc -p tsconfig.build.json",
|
||||
"build:local-deps": "cd ../../packages/config-types && npm i && npm run build && cd ../fetch && npm i && npm run build && cd ../llm-info && npm i && npm run build && cd ../config-yaml && npm i && npm run build && cd ../openai-adapters && npm i && npm run build && cd ../../core && npm i && npm run build && cd ../extensions/cli && npm i",
|
||||
"build:local-deps": "cd ../../packages/config-types && npm i && npm run build && cd ../fetch && npm i && npm run build && cd ../llm-info && npm i && npm run build && cd ../terminal-security && npm i && npm run build && cd ../config-yaml && npm i && npm run build && cd ../openai-adapters && npm i && npm run build && cd ../../core && npm i && npm run build && cd ../extensions/cli && npm i",
|
||||
"build:validate": "node validate-aliases.mjs",
|
||||
"build:bundle": "node build.mjs",
|
||||
"build": "npm run build:validate && npm run build:bundle",
|
||||
|
|
@ -50,6 +50,7 @@
|
|||
"@continuedev/config-yaml": "file:../../packages/config-yaml",
|
||||
"@continuedev/openai-adapters": "file:../../packages/openai-adapters",
|
||||
"@continuedev/sdk": "^0.0.13",
|
||||
"@continuedev/terminal-security": "file:../../packages/terminal-security",
|
||||
"@modelcontextprotocol/sdk": "^1.17.2",
|
||||
"@opentelemetry/api": "^1.9.0",
|
||||
"@opentelemetry/exporter-metrics-otlp-grpc": "^0.203.0",
|
||||
|
|
|
|||
32
extensions/cli/spec/ctrl-c-behavior.md
Normal file
32
extensions/cli/spec/ctrl-c-behavior.md
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
# Ctrl+C Exit Behavior
|
||||
|
||||
## Overview
|
||||
|
||||
Ctrl+C operates on two levels:
|
||||
|
||||
1. **Menus/Selectors**: Immediate cancellation and return to previous state
|
||||
2. **Main Application**: Two-stage exit requiring double Ctrl+C within 1 second
|
||||
|
||||
## Two-Stage Exit (Main Application)
|
||||
|
||||
### First Ctrl+C
|
||||
|
||||
- Shows temporary status message "ctrl+c to exit" in bottom-left status bar
|
||||
- Message automatically disappears after 1 second
|
||||
- Clears any text in the input field (if focused)
|
||||
- Does **not** exit the application
|
||||
|
||||
### Second Ctrl+C (within 1 second)
|
||||
|
||||
- Exits the application immediately
|
||||
- Performs graceful shutdown
|
||||
|
||||
### Second Ctrl+C (after 1 second)
|
||||
|
||||
- Treated as a new "first Ctrl+C"
|
||||
- Shows exit message again
|
||||
- User must press Ctrl+C twice within 1 second window to actually exit
|
||||
|
||||
## Menu/Selector Cancellation
|
||||
|
||||
Ctrl+C immediately cancels and returns to the previous state in all interactive menus and selectors.
|
||||
|
|
@ -51,7 +51,7 @@ All metrics and events share these standard attributes:
|
|||
|
||||
## Core Metrics
|
||||
|
||||
### ✅ `continue.cli.session.count`
|
||||
### ✅ `continue_cli_session_count`
|
||||
|
||||
**Type:** Counter
|
||||
**Unit:** `count`
|
||||
|
|
@ -65,7 +65,7 @@ All metrics and events share these standard attributes:
|
|||
|
||||
---
|
||||
|
||||
### ✅ `continue.cli.lines_of_code.count`
|
||||
### ✅ `continue_cli_lines_of_code_count`
|
||||
|
||||
**Type:** Counter
|
||||
**Unit:** `count`
|
||||
|
|
@ -80,7 +80,7 @@ All metrics and events share these standard attributes:
|
|||
|
||||
---
|
||||
|
||||
### ✅ `continue.cli.pull_request.count`
|
||||
### ✅ `continue_cli_pull_request_count`
|
||||
|
||||
**Type:** Counter
|
||||
**Unit:** `count`
|
||||
|
|
@ -94,7 +94,7 @@ All metrics and events share these standard attributes:
|
|||
|
||||
---
|
||||
|
||||
### ✅ `continue.cli.commit.count`
|
||||
### ✅ `continue_cli_commit_count`
|
||||
|
||||
**Type:** Counter
|
||||
**Unit:** `count`
|
||||
|
|
@ -108,7 +108,7 @@ All metrics and events share these standard attributes:
|
|||
|
||||
---
|
||||
|
||||
### ✅ `continue.cli.cost.usage`
|
||||
### ✅ `continue_cli_cost_usage`
|
||||
|
||||
**Type:** Counter
|
||||
**Unit:** `USD`
|
||||
|
|
@ -123,7 +123,7 @@ All metrics and events share these standard attributes:
|
|||
|
||||
---
|
||||
|
||||
### ✅ `continue.cli.token.usage`
|
||||
### ✅ `continue_cli_token_usage`
|
||||
|
||||
**Type:** Counter
|
||||
**Unit:** `tokens`
|
||||
|
|
@ -139,7 +139,7 @@ All metrics and events share these standard attributes:
|
|||
|
||||
---
|
||||
|
||||
### ❌ `continue.cli.code_edit_tool.decision`
|
||||
### ❌ `continue_cli_code_edit_tool_decision`
|
||||
|
||||
**Type:** Counter
|
||||
**Unit:** `count`
|
||||
|
|
@ -156,7 +156,7 @@ All metrics and events share these standard attributes:
|
|||
|
||||
---
|
||||
|
||||
### ✅ `continue.cli.active_time.total`
|
||||
### ✅ `continue_cli_active_time_total`
|
||||
|
||||
**Type:** Counter
|
||||
**Unit:** `s`
|
||||
|
|
@ -172,7 +172,7 @@ All metrics and events share these standard attributes:
|
|||
|
||||
### ✅ User Prompt Event
|
||||
|
||||
**Event Name:** `continue.cli.user_prompt`
|
||||
**Event Name:** `continue_cli_user_prompt`
|
||||
|
||||
**Attributes:**
|
||||
|
||||
|
|
@ -188,7 +188,7 @@ All metrics and events share these standard attributes:
|
|||
|
||||
### ✅ Tool Result Event
|
||||
|
||||
**Event Name:** `continue.cli.tool_result`
|
||||
**Event Name:** `continue_cli_tool_result`
|
||||
|
||||
**Attributes:**
|
||||
|
||||
|
|
@ -209,7 +209,7 @@ All metrics and events share these standard attributes:
|
|||
|
||||
### ✅ API Request Event
|
||||
|
||||
**Event Name:** `continue.cli.api_request`
|
||||
**Event Name:** `continue_cli_api_request`
|
||||
|
||||
**Attributes:**
|
||||
|
||||
|
|
@ -232,7 +232,7 @@ These metrics are unique to Continue CLI and provide additional insights without
|
|||
|
||||
### Authentication Metrics
|
||||
|
||||
#### ✅ `continue.cli.auth.attempts`
|
||||
#### ✅ `continue_cli_auth_attempts`
|
||||
|
||||
**Type:** Counter
|
||||
**Unit:** `{attempt}`
|
||||
|
|
@ -248,7 +248,7 @@ These metrics are unique to Continue CLI and provide additional insights without
|
|||
|
||||
### MCP Integration Metrics
|
||||
|
||||
#### ❌ `continue.cli.mcp.connections`
|
||||
#### ❌ `continue_cli_mcp_connections`
|
||||
|
||||
**Type:** Gauge
|
||||
**Unit:** `{connection}`
|
||||
|
|
@ -264,7 +264,7 @@ These metrics are unique to Continue CLI and provide additional insights without
|
|||
|
||||
### Performance Metrics
|
||||
|
||||
#### ❌ `continue.cli.startup.time`
|
||||
#### ❌ `continue_cli_startup_time`
|
||||
|
||||
**Type:** Histogram
|
||||
**Unit:** `ms`
|
||||
|
|
@ -278,7 +278,7 @@ These metrics are unique to Continue CLI and provide additional insights without
|
|||
|
||||
**Implementation:** Track in `src/index.ts` and `src/commands/chat.ts`
|
||||
|
||||
#### ✅ `continue.cli.response_time`
|
||||
#### ✅ `continue_cli_response_time`
|
||||
|
||||
**Type:** Histogram
|
||||
**Unit:** `ms`
|
||||
|
|
@ -297,7 +297,7 @@ These metrics are unique to Continue CLI and provide additional insights without
|
|||
|
||||
### Migration from Claude Code Dashboards
|
||||
|
||||
The core metrics (`session.count`, `lines_of_code.count`, `token.usage`, `cost.usage`, etc.) use identical naming and attribute structures to Claude Code, allowing for easy dashboard migration by simply changing the metric prefix from `claude_code.*` to `continue.cli.*`.
|
||||
The core metrics (`session_count`, `lines_of_code_count`, `token_usage`, `cost_usage`, etc.) use identical naming and attribute structures to Claude Code, allowing for easy dashboard migration by simply changing the metric prefix from `claude_code_*` to `continue_cli_*`.
|
||||
|
||||
### Privacy Considerations
|
||||
|
||||
|
|
@ -337,6 +337,6 @@ All metrics should include these resource attributes:
|
|||
|
||||
**Missing implementations:**
|
||||
|
||||
- `continue.cli.code_edit_tool.decision` - requires user confirmation UI
|
||||
- `continue.cli.mcp.connections` - needs MCP service monitoring
|
||||
- `continue.cli.startup.time` - needs startup time tracking
|
||||
- `continue_cli_code_edit_tool_decision` - requires user confirmation UI
|
||||
- `continue_cli_mcp_connections` - needs MCP service monitoring
|
||||
- `continue_cli_startup_time` - needs startup time tracking
|
||||
|
|
|
|||
138
extensions/cli/spec/shell-mode.md
Normal file
138
extensions/cli/spec/shell-mode.md
Normal file
|
|
@ -0,0 +1,138 @@
|
|||
shell Mode (CLI TUI)
|
||||
|
||||
Overview
|
||||
|
||||
- shell mode lets users run shell commands directly from the chat input by starting their input with an exclamation mark (!).
|
||||
- It is intended for quick terminal command execution without leaving the TUI.
|
||||
|
||||
Activation
|
||||
|
||||
- shell mode is activated when the current input (trimmed) starts with !
|
||||
- Example: "!git status" or " !ls -la" both activate shell mode.
|
||||
- Visual indicator:
|
||||
- Input border color changes to yellow.
|
||||
- The input prompt indicator changes to a yellow "$".
|
||||
- The input placeholder includes "! for shell mode".
|
||||
|
||||
Deactivation / Exiting shell Mode
|
||||
|
||||
- Pressing Enter to submit the input exits shell mode immediately after submission, regardless of the command result.
|
||||
- Pressing Esc when the input (trimmed) is exactly ! clears the input and exits shell mode.
|
||||
- Editing the input so it no longer starts with ! also exits shell mode and restores normal input behavior.
|
||||
|
||||
Interaction with other input helpers
|
||||
|
||||
- When in shell mode (input starts with !):
|
||||
- "@" file search suggestions are disabled.
|
||||
- "/" slash command UI is disabled.
|
||||
- When in slash command mode (input starts with /):
|
||||
- "@" file search suggestions are disabled.
|
||||
|
||||
Submission behavior
|
||||
|
||||
- On submit (Enter) with a shell-mode input:
|
||||
- The leading ! is removed and the remainder is treated as the shell command to run.
|
||||
- The TUI immediately appends an assistant message representing a shell tool call, with status set to calling, so users can see that the command is in progress.
|
||||
- The shell command is executed asynchronously; when it completes, the tool call status is updated to done (or error) and the output is populated.
|
||||
|
||||
Execution semantics
|
||||
|
||||
- The command is executed in the same way as terminal tool commands, minus permissions
|
||||
|
||||
Output handling
|
||||
|
||||
- Stdout is streamed into memory; Stderr is captured and appended as a trailing "Stderr: ..." section on success.
|
||||
- If the process exits non-zero and Stderr contains content, the tool call is marked as error and the error text is shown.
|
||||
- Output is truncated to the first 5000 lines if exceeded.
|
||||
- Timeout behavior: If no output is received for 30 seconds (configurable in tests), the process is terminated and the result includes a note like:
|
||||
"[Command timed out after 30 seconds of no output]".
|
||||
|
||||
Keyboard behaviors (summary)
|
||||
|
||||
- Enter: submit input. If in shell mode, exits shell mode after submission and shows the pending shell tool call immediately.
|
||||
- Shift+Enter: new line.
|
||||
- Backslash (\) at end-of-line: inserts a new line (line continuation) as usual.
|
||||
- Esc: if only ! (trimmed) is present, clears input and exits shell mode; otherwise cancels streaming or closes suggestions depending on context.
|
||||
|
||||
Scope / Modes
|
||||
|
||||
- shell mode applies to interactive (TUI/standard) CLI usage. It is not part of headless (-p/--print) processing.
|
||||
|
||||
Error handling
|
||||
|
||||
- Command execution errors are captured and surfaced in the tool call as status error with human-readable error text (including Stderr when available).
|
||||
|
||||
Examples
|
||||
|
||||
- "!git status" → shows a shell tool call immediately, then populates with the git status output.
|
||||
- "!echo hello" → shows a shell tool call immediately, then output "hello".
|
||||
- "!some-unknown-cmd" → shows a shell tool call immediately, then sets status to error with an error message.
|
||||
Shell Mode (CLI TUI)
|
||||
|
||||
Overview
|
||||
|
||||
- Shell mode lets users run shell commands directly from the chat input by starting their input with an exclamation mark (!).
|
||||
- It is intended for quick terminal command execution without leaving the TUI.
|
||||
|
||||
Activation
|
||||
|
||||
- Shell mode is activated when the current input (trimmed) starts with !
|
||||
- Example: "!git status" or " !ls -la" both activate Shell mode.
|
||||
- Visual indicator:
|
||||
- Input border color changes to yellow.
|
||||
- The input prompt indicator changes to a yellow "$".
|
||||
- The input placeholder includes "! for shell mode".
|
||||
|
||||
Deactivation / Exiting Shell Mode
|
||||
|
||||
- Pressing Enter to submit the input exits shell mode immediately after submission, regardless of the command result.
|
||||
- Pressing Esc when the input (trimmed) is exactly ! clears the input and exits shell mode.
|
||||
- Editing the input so it no longer starts with ! also exits shell mode and restores normal input behavior.
|
||||
|
||||
Interaction with other input helpers
|
||||
|
||||
- When in shell mode (input starts with !):
|
||||
- "@" file search suggestions are disabled.
|
||||
- "/" slash command UI is disabled.
|
||||
- When in slash command mode (input starts with /):
|
||||
- "@" file search suggestions are disabled.
|
||||
|
||||
Submission behavior
|
||||
|
||||
- On submit (Enter) with a shell-mode input:
|
||||
- The leading ! is removed and the remainder is treated as the shell command to run.
|
||||
- The TUI immediately appends an assistant message representing a Shell tool call, with status set to calling, so users can see that the command is in progress.
|
||||
- The shell command is executed asynchronously; when it completes, the tool call status is updated to done (or error) and the output is populated.
|
||||
|
||||
Execution semantics
|
||||
|
||||
- The command is executed in the same way as terminal tool commands, minus permissions, and inserted into the chat history the same.
|
||||
|
||||
Output handling
|
||||
|
||||
- Stdout is streamed into memory; Stderr is captured and appended as a trailing "Stderr: ..." section on success.
|
||||
- If the process exits non-zero and Stderr contains content, the tool call is marked as error and the error text is shown.
|
||||
- Output is truncated to the first 5000 lines if exceeded.
|
||||
- Timeout behavior: If no output is received for 30 seconds (configurable in tests), the process is terminated and the result includes a note like:
|
||||
"[Command timed out after 30 seconds of no output]".
|
||||
|
||||
Keyboard behaviors (summary)
|
||||
|
||||
- Enter: submit input. If in shell mode, exits shell mode after submission and shows the pending Shell tool call immediately.
|
||||
- Shift+Enter: new line.
|
||||
- Backslash (\) at end-of-line: inserts a new line (line continuation) as usual.
|
||||
- Esc: if only ! (trimmed) is present, clears input and exits shell mode; otherwise cancels streaming or closes suggestions depending on context.
|
||||
|
||||
Scope / Modes
|
||||
|
||||
- Shell mode applies to interactive (TUI/standard) CLI usage. It is not part of headless (-p/--print) processing.
|
||||
|
||||
Error handling
|
||||
|
||||
- Command execution errors are captured and surfaced in the tool call as status error with human-readable error text (including Stderr when available).
|
||||
|
||||
Examples
|
||||
|
||||
- "!git status" → shows a Shell tool call immediately, then populates with the git status output.
|
||||
- "!echo hello" → shows a Shell tool call immediately, then output "hello".
|
||||
- "!some-unknown-cmd" → shows a Shell tool call immediately, then sets status to error with an error message.
|
||||
12
extensions/cli/src/__tests__/CtrlCProcessHandling.test.ts
Normal file
12
extensions/cli/src/__tests__/CtrlCProcessHandling.test.ts
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
|
||||
describe("Process SIGINT handling functions", () => {
|
||||
it("exports the necessary functions for exit message handling", async () => {
|
||||
const indexModule = await import("../index.js");
|
||||
|
||||
// Verify the functions exist
|
||||
expect(typeof indexModule.shouldShowExitMessage).toBe("function");
|
||||
expect(typeof indexModule.setExitMessageCallback).toBe("function");
|
||||
expect(typeof indexModule.setTUIUnmount).toBe("function");
|
||||
});
|
||||
});
|
||||
|
|
@ -23,6 +23,35 @@ import { logger } from "./util/logger.js";
|
|||
import { readStdinSync } from "./util/stdin.js";
|
||||
import { getVersion } from "./version.js";
|
||||
|
||||
// TUI lifecycle and two-stage exit state management
|
||||
let tuiUnmount: (() => void) | null;
|
||||
let showExitMessage: boolean;
|
||||
let exitMessageCallback: (() => void) | null;
|
||||
let lastCtrlCTime: number;
|
||||
|
||||
// Initialize state immediately to avoid temporal dead zone issues with exported functions
|
||||
(function initializeTUIState() {
|
||||
tuiUnmount = null;
|
||||
showExitMessage = false;
|
||||
exitMessageCallback = null;
|
||||
lastCtrlCTime = 0;
|
||||
})();
|
||||
|
||||
// Register TUI cleanup function for graceful shutdown
|
||||
export function setTUIUnmount(unmount: () => void) {
|
||||
tuiUnmount = unmount;
|
||||
}
|
||||
|
||||
// Register callback to trigger UI updates when exit message state changes
|
||||
export function setExitMessageCallback(callback: () => void) {
|
||||
exitMessageCallback = callback;
|
||||
}
|
||||
|
||||
// Check if "ctrl+c to exit" message should be displayed
|
||||
export function shouldShowExitMessage(): boolean {
|
||||
return showExitMessage;
|
||||
}
|
||||
|
||||
// Add global error handlers to prevent uncaught errors from crashing the process
|
||||
process.on("unhandledRejection", (reason, promise) => {
|
||||
logger.error("Unhandled Rejection at:", { promise, reason });
|
||||
|
|
@ -265,10 +294,39 @@ try {
|
|||
process.exit(1);
|
||||
}
|
||||
|
||||
// Graceful shutdown - flush Sentry data
|
||||
// Graceful shutdown with two-stage Ctrl+C exit
|
||||
|
||||
// Remove all existing SIGINT listeners first
|
||||
process.removeAllListeners("SIGINT");
|
||||
|
||||
process.on("SIGINT", async () => {
|
||||
await sentryService.flush();
|
||||
process.exit(0);
|
||||
const now = Date.now();
|
||||
const timeSinceLastCtrlC = now - lastCtrlCTime;
|
||||
|
||||
if (timeSinceLastCtrlC <= 1000 && lastCtrlCTime !== 0) {
|
||||
// Second Ctrl+C within 1 second - exit
|
||||
showExitMessage = false;
|
||||
if (tuiUnmount) {
|
||||
tuiUnmount();
|
||||
}
|
||||
await sentryService.flush();
|
||||
process.exit(0);
|
||||
} else {
|
||||
// First Ctrl+C or too much time elapsed - show exit message
|
||||
lastCtrlCTime = now;
|
||||
showExitMessage = true;
|
||||
if (exitMessageCallback) {
|
||||
exitMessageCallback();
|
||||
}
|
||||
|
||||
// Hide message after 1 second
|
||||
setTimeout(() => {
|
||||
showExitMessage = false;
|
||||
if (exitMessageCallback) {
|
||||
exitMessageCallback();
|
||||
}
|
||||
}, 1000);
|
||||
}
|
||||
});
|
||||
|
||||
process.on("SIGTERM", async () => {
|
||||
|
|
|
|||
|
|
@ -1,3 +1,7 @@
|
|||
import { vi, describe, it, expect, beforeEach, afterEach } from "vitest";
|
||||
|
||||
import * as toolsModule from "../tools/index.js";
|
||||
|
||||
import {
|
||||
checkToolPermission,
|
||||
filterExcludedTools,
|
||||
|
|
@ -593,4 +597,373 @@ describe("Permission Checker", () => {
|
|||
expect(filtered).toEqual(tools);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Hybrid Permission Model with Dynamic Evaluation", () => {
|
||||
// Mock the runTerminalCommand tool with evaluateToolCallPolicy
|
||||
const mockBashTool = {
|
||||
name: "Bash",
|
||||
displayName: "Bash",
|
||||
description: "Execute bash commands",
|
||||
parameters: {},
|
||||
isBuiltIn: true,
|
||||
evaluateToolCallPolicy: vi.fn(),
|
||||
run: vi.fn(),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
// Mock getAllBuiltinTools to return our test tool
|
||||
vi.spyOn(toolsModule, "getAllBuiltinTools").mockReturnValue([
|
||||
mockBashTool,
|
||||
]);
|
||||
|
||||
// Reset mock between tests
|
||||
mockBashTool.evaluateToolCallPolicy.mockClear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("User has Bash in 'allow' mode", () => {
|
||||
const permissions: ToolPermissions = {
|
||||
policies: [
|
||||
{ tool: "Bash", permission: "allow" },
|
||||
{ tool: "*", permission: "ask" },
|
||||
],
|
||||
};
|
||||
|
||||
it("should allow safe commands (echo hello)", () => {
|
||||
mockBashTool.evaluateToolCallPolicy.mockReturnValue(
|
||||
"allowedWithoutPermission",
|
||||
);
|
||||
|
||||
const result = checkToolPermission(
|
||||
{ name: "Bash", arguments: { command: "echo hello" } },
|
||||
permissions,
|
||||
);
|
||||
|
||||
expect(result.permission).toBe("allow"); // User preference wins
|
||||
expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith(
|
||||
"allowedWithoutPermission", // converted from "allow"
|
||||
{ command: "echo hello" },
|
||||
);
|
||||
});
|
||||
|
||||
it("should allow risky commands based on user preference (curl)", () => {
|
||||
mockBashTool.evaluateToolCallPolicy.mockReturnValue(
|
||||
"allowedWithPermission",
|
||||
);
|
||||
|
||||
const result = checkToolPermission(
|
||||
{ name: "Bash", arguments: { command: "curl https://example.com" } },
|
||||
permissions,
|
||||
);
|
||||
|
||||
expect(result.permission).toBe("allow"); // User preference wins over "ask"
|
||||
expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith(
|
||||
"allowedWithoutPermission", // converted from "allow"
|
||||
{ command: "curl https://example.com" },
|
||||
);
|
||||
});
|
||||
|
||||
it("should block dangerous commands despite user preference (eval)", () => {
|
||||
mockBashTool.evaluateToolCallPolicy.mockReturnValue("disabled");
|
||||
|
||||
const result = checkToolPermission(
|
||||
{ name: "Bash", arguments: { command: "eval 'echo safe'" } },
|
||||
permissions,
|
||||
);
|
||||
|
||||
expect(result.permission).toBe("exclude"); // Security wins
|
||||
expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith(
|
||||
"allowedWithoutPermission", // converted from "allow"
|
||||
{ command: "eval 'echo safe'" },
|
||||
);
|
||||
});
|
||||
|
||||
it("should block sudo commands despite user preference", () => {
|
||||
mockBashTool.evaluateToolCallPolicy.mockReturnValue("disabled");
|
||||
|
||||
const result = checkToolPermission(
|
||||
{ name: "Bash", arguments: { command: "sudo rm -rf /" } },
|
||||
permissions,
|
||||
);
|
||||
|
||||
expect(result.permission).toBe("exclude"); // Security wins
|
||||
});
|
||||
});
|
||||
|
||||
describe("User has Bash in 'ask' mode (default)", () => {
|
||||
const permissions: ToolPermissions = {
|
||||
policies: [
|
||||
{ tool: "Bash", permission: "ask" },
|
||||
{ tool: "*", permission: "ask" },
|
||||
],
|
||||
};
|
||||
|
||||
it("should ask for safe commands based on user preference (echo)", () => {
|
||||
mockBashTool.evaluateToolCallPolicy.mockReturnValue(
|
||||
"allowedWithoutPermission",
|
||||
);
|
||||
|
||||
const result = checkToolPermission(
|
||||
{ name: "Bash", arguments: { command: "echo hello" } },
|
||||
permissions,
|
||||
);
|
||||
|
||||
expect(result.permission).toBe("ask"); // User preference wins
|
||||
expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith(
|
||||
"allowedWithPermission", // converted from "ask"
|
||||
{ command: "echo hello" },
|
||||
);
|
||||
});
|
||||
|
||||
it("should ask for risky commands (curl)", () => {
|
||||
mockBashTool.evaluateToolCallPolicy.mockReturnValue(
|
||||
"allowedWithPermission",
|
||||
);
|
||||
|
||||
const result = checkToolPermission(
|
||||
{ name: "Bash", arguments: { command: "curl https://example.com" } },
|
||||
permissions,
|
||||
);
|
||||
|
||||
expect(result.permission).toBe("ask"); // Both agree on "ask"
|
||||
expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith(
|
||||
"allowedWithPermission", // converted from "ask"
|
||||
{ command: "curl https://example.com" },
|
||||
);
|
||||
});
|
||||
|
||||
it("should block dangerous commands (eval)", () => {
|
||||
mockBashTool.evaluateToolCallPolicy.mockReturnValue("disabled");
|
||||
|
||||
const result = checkToolPermission(
|
||||
{ name: "Bash", arguments: { command: "eval 'echo safe'" } },
|
||||
permissions,
|
||||
);
|
||||
|
||||
expect(result.permission).toBe("exclude"); // Security wins
|
||||
expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith(
|
||||
"allowedWithPermission", // converted from "ask"
|
||||
{ command: "eval 'echo safe'" },
|
||||
);
|
||||
});
|
||||
|
||||
it("should block rm -rf commands", () => {
|
||||
mockBashTool.evaluateToolCallPolicy.mockReturnValue("disabled");
|
||||
|
||||
const result = checkToolPermission(
|
||||
{ name: "Bash", arguments: { command: "rm -rf /tmp/important" } },
|
||||
permissions,
|
||||
);
|
||||
|
||||
expect(result.permission).toBe("exclude"); // Security wins
|
||||
});
|
||||
});
|
||||
|
||||
describe("User has Bash in 'exclude' mode", () => {
|
||||
const permissions: ToolPermissions = {
|
||||
policies: [{ tool: "Bash", permission: "exclude" }],
|
||||
};
|
||||
|
||||
it("should always exclude regardless of dynamic evaluation", () => {
|
||||
// Even if dynamic evaluation would allow it
|
||||
mockBashTool.evaluateToolCallPolicy.mockReturnValue(
|
||||
"allowedWithoutPermission",
|
||||
);
|
||||
|
||||
const result = checkToolPermission(
|
||||
{ name: "Bash", arguments: { command: "echo hello" } },
|
||||
permissions,
|
||||
);
|
||||
|
||||
expect(result.permission).toBe("exclude"); // User excluded the tool entirely
|
||||
expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith(
|
||||
"disabled", // converted from "exclude"
|
||||
{ command: "echo hello" },
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Comprehensive command testing", () => {
|
||||
const permissions: ToolPermissions = {
|
||||
policies: [{ tool: "Bash", permission: "allow" }],
|
||||
};
|
||||
|
||||
const testCases = [
|
||||
// Safe commands
|
||||
{
|
||||
command: "ls",
|
||||
dynamicResult: "allowedWithoutPermission",
|
||||
expected: "allow",
|
||||
},
|
||||
{
|
||||
command: "pwd",
|
||||
dynamicResult: "allowedWithoutPermission",
|
||||
expected: "allow",
|
||||
},
|
||||
{
|
||||
command: "date",
|
||||
dynamicResult: "allowedWithoutPermission",
|
||||
expected: "allow",
|
||||
},
|
||||
{
|
||||
command: "echo test",
|
||||
dynamicResult: "allowedWithoutPermission",
|
||||
expected: "allow",
|
||||
},
|
||||
{
|
||||
command: "git status",
|
||||
dynamicResult: "allowedWithoutPermission",
|
||||
expected: "allow",
|
||||
},
|
||||
|
||||
// Risky commands (user preference wins when not disabled)
|
||||
{
|
||||
command: "npm install pkg",
|
||||
dynamicResult: "allowedWithPermission",
|
||||
expected: "allow",
|
||||
},
|
||||
{
|
||||
command: "rm file.txt",
|
||||
dynamicResult: "allowedWithPermission",
|
||||
expected: "allow",
|
||||
},
|
||||
{
|
||||
command: "curl https://api.example.com",
|
||||
dynamicResult: "allowedWithPermission",
|
||||
expected: "allow",
|
||||
},
|
||||
{
|
||||
command: "wget https://example.com/file",
|
||||
dynamicResult: "allowedWithPermission",
|
||||
expected: "allow",
|
||||
},
|
||||
|
||||
// Dangerous commands (always blocked)
|
||||
{
|
||||
command: "sudo rm -rf /",
|
||||
dynamicResult: "disabled",
|
||||
expected: "exclude",
|
||||
},
|
||||
{
|
||||
command: "exec bash",
|
||||
dynamicResult: "disabled",
|
||||
expected: "exclude",
|
||||
},
|
||||
{
|
||||
command: "eval 'malicious code'",
|
||||
dynamicResult: "disabled",
|
||||
expected: "exclude",
|
||||
},
|
||||
{ command: "rm -rf /", dynamicResult: "disabled", expected: "exclude" },
|
||||
];
|
||||
|
||||
testCases.forEach(({ command, dynamicResult, expected }) => {
|
||||
it(`should handle '${command}' correctly`, () => {
|
||||
mockBashTool.evaluateToolCallPolicy.mockReturnValue(dynamicResult);
|
||||
|
||||
const result = checkToolPermission(
|
||||
{ name: "Bash", arguments: { command } },
|
||||
permissions,
|
||||
);
|
||||
|
||||
expect(result.permission).toBe(expected);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Edge cases", () => {
|
||||
it("should handle tools without dynamic evaluation", () => {
|
||||
// Mock a Read tool without evaluateToolCallPolicy
|
||||
const mockReadTool = {
|
||||
name: "Read",
|
||||
displayName: "Read",
|
||||
description: "Read files",
|
||||
parameters: {},
|
||||
isBuiltIn: true,
|
||||
run: vi.fn(),
|
||||
// No evaluateToolCallPolicy
|
||||
};
|
||||
vi.mocked(toolsModule.getAllBuiltinTools).mockReturnValue([
|
||||
mockReadTool,
|
||||
mockBashTool,
|
||||
]);
|
||||
|
||||
const permissions: ToolPermissions = {
|
||||
policies: [{ tool: "Read", permission: "allow" }],
|
||||
};
|
||||
|
||||
const result = checkToolPermission(
|
||||
{ name: "Read", arguments: { path: "/tmp/file.txt" } },
|
||||
permissions,
|
||||
);
|
||||
|
||||
expect(result.permission).toBe("allow");
|
||||
expect(mockBashTool.evaluateToolCallPolicy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should use default 'ask' when no policy matches", () => {
|
||||
const permissions: ToolPermissions = {
|
||||
policies: [],
|
||||
};
|
||||
|
||||
mockBashTool.evaluateToolCallPolicy.mockReturnValue(
|
||||
"allowedWithPermission",
|
||||
);
|
||||
|
||||
const result = checkToolPermission(
|
||||
{ name: "Bash", arguments: { command: "echo test" } },
|
||||
permissions,
|
||||
);
|
||||
|
||||
expect(result.permission).toBe("ask"); // Default fallback, user preference wins
|
||||
expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith(
|
||||
"allowedWithPermission", // converted from default "ask"
|
||||
{ command: "echo test" },
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle null/undefined arguments gracefully", () => {
|
||||
mockBashTool.evaluateToolCallPolicy.mockReturnValue(
|
||||
"allowedWithPermission",
|
||||
);
|
||||
|
||||
const permissions: ToolPermissions = {
|
||||
policies: [{ tool: "Bash", permission: "allow" }],
|
||||
};
|
||||
|
||||
const result = checkToolPermission(
|
||||
{ name: "Bash", arguments: {} },
|
||||
permissions,
|
||||
);
|
||||
|
||||
expect(result.permission).toBe("allow");
|
||||
expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith(
|
||||
"allowedWithoutPermission",
|
||||
{},
|
||||
);
|
||||
});
|
||||
|
||||
it("should maintain matched policy information", () => {
|
||||
mockBashTool.evaluateToolCallPolicy.mockReturnValue(
|
||||
"allowedWithoutPermission",
|
||||
);
|
||||
|
||||
const policy = { tool: "Bash", permission: "allow" as const };
|
||||
const permissions: ToolPermissions = {
|
||||
policies: [policy],
|
||||
};
|
||||
|
||||
const result = checkToolPermission(
|
||||
{ name: "Bash", arguments: { command: "ls" } },
|
||||
permissions,
|
||||
);
|
||||
|
||||
expect(result.matchedPolicy).toBe(policy);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,10 +1,14 @@
|
|||
import type { ToolPolicy } from "@continuedev/terminal-security";
|
||||
|
||||
import { getServiceSync } from "../services/index.js";
|
||||
import type { ToolPermissionServiceState } from "../services/types.js";
|
||||
import { SERVICE_NAMES } from "../services/types.js";
|
||||
import { getAllBuiltinTools } from "../tools/index.js";
|
||||
|
||||
import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js";
|
||||
import {
|
||||
PermissionCheckResult,
|
||||
PermissionPolicy,
|
||||
ToolCallRequest,
|
||||
ToolPermissions,
|
||||
} from "./types.js";
|
||||
|
|
@ -103,6 +107,24 @@ export function matchesArguments(
|
|||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts CLI's PermissionPolicy to core's ToolPolicy
|
||||
*/
|
||||
function permissionPolicyToToolPolicy(
|
||||
permission: PermissionPolicy,
|
||||
): ToolPolicy {
|
||||
switch (permission) {
|
||||
case "allow":
|
||||
return "allowedWithoutPermission";
|
||||
case "ask":
|
||||
return "allowedWithPermission";
|
||||
case "exclude":
|
||||
return "disabled";
|
||||
default:
|
||||
return "allowedWithPermission";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluates a tool call request against a set of permission policies.
|
||||
* Returns the permission for the first matching policy.
|
||||
|
|
@ -129,21 +151,54 @@ export function checkToolPermission(
|
|||
}
|
||||
}
|
||||
|
||||
// First, get the base permission from static policies
|
||||
let basePermission: PermissionPolicy = "ask";
|
||||
let matchedPolicy = undefined;
|
||||
|
||||
for (const policy of policies) {
|
||||
if (
|
||||
matchesToolPattern(toolCall.name, policy.tool, toolCall.arguments) &&
|
||||
matchesArguments(toolCall.arguments, policy.argumentMatches)
|
||||
) {
|
||||
return {
|
||||
permission: policy.permission,
|
||||
matchedPolicy: policy,
|
||||
};
|
||||
basePermission = policy.permission;
|
||||
matchedPolicy = policy;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to "ask" if no policy matches
|
||||
// Check if tool has dynamic policy evaluation
|
||||
const builtinTools = getAllBuiltinTools();
|
||||
const tool = builtinTools.find((t) => t.name === toolCall.name);
|
||||
|
||||
if (tool?.evaluateToolCallPolicy) {
|
||||
// Convert CLI permission to core policy
|
||||
const basePolicy = permissionPolicyToToolPolicy(basePermission);
|
||||
|
||||
// Evaluate the dynamic policy
|
||||
const evaluatedPolicy = tool.evaluateToolCallPolicy(
|
||||
basePolicy,
|
||||
toolCall.arguments,
|
||||
);
|
||||
|
||||
// If dynamic evaluation says disabled, that ALWAYS takes precedence
|
||||
if (evaluatedPolicy === "disabled") {
|
||||
return {
|
||||
permission: "exclude",
|
||||
matchedPolicy,
|
||||
};
|
||||
}
|
||||
|
||||
// Otherwise, user preference wins - return the original base permission
|
||||
return {
|
||||
permission: basePermission,
|
||||
matchedPolicy,
|
||||
};
|
||||
}
|
||||
|
||||
// No dynamic evaluation, return static result
|
||||
return {
|
||||
permission: "ask",
|
||||
permission: basePermission,
|
||||
matchedPolicy,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { AssistantConfig } from "@continuedev/sdk";
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { MCPService } from "./MCPService.js";
|
||||
|
||||
|
|
@ -21,6 +21,14 @@ vi.mock("@modelcontextprotocol/sdk/client/stdio.js", () => ({
|
|||
StdioClientTransport: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@modelcontextprotocol/sdk/client/sse.js", () => ({
|
||||
SSEClientTransport: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@modelcontextprotocol/sdk/client/streamableHttp.js", () => ({
|
||||
StreamableHTTPClientTransport: vi.fn(),
|
||||
}));
|
||||
|
||||
describe("MCPService", () => {
|
||||
let mcpService: MCPService;
|
||||
let mockAssistant: AssistantConfig;
|
||||
|
|
@ -152,4 +160,56 @@ describe("MCPService", () => {
|
|||
await expect(mcpService.cleanup()).resolves.not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("transport types", () => {
|
||||
it("should support SSE transport", async () => {
|
||||
const sseAssistant: AssistantConfig = {
|
||||
name: "sse-assistant",
|
||||
version: "1.0.0",
|
||||
mcpServers: [
|
||||
{
|
||||
name: "sse-server",
|
||||
type: "sse",
|
||||
url: "https://example.com/sse",
|
||||
},
|
||||
],
|
||||
} as AssistantConfig;
|
||||
|
||||
await expect(mcpService.initialize(sseAssistant)).resolves.not.toThrow();
|
||||
});
|
||||
|
||||
it("should support streamable-http transport", async () => {
|
||||
const httpAssistant: AssistantConfig = {
|
||||
name: "http-assistant",
|
||||
version: "1.0.0",
|
||||
mcpServers: [
|
||||
{
|
||||
name: "http-server",
|
||||
type: "streamable-http",
|
||||
url: "https://example.com/http",
|
||||
},
|
||||
],
|
||||
} as AssistantConfig;
|
||||
|
||||
await expect(mcpService.initialize(httpAssistant)).resolves.not.toThrow();
|
||||
});
|
||||
|
||||
it("should default to stdio transport when type is not specified", async () => {
|
||||
const defaultAssistant: AssistantConfig = {
|
||||
name: "default-assistant",
|
||||
version: "1.0.0",
|
||||
mcpServers: [
|
||||
{
|
||||
name: "default-server",
|
||||
command: "npx",
|
||||
args: ["-v"],
|
||||
},
|
||||
],
|
||||
} as AssistantConfig;
|
||||
|
||||
await expect(
|
||||
mcpService.initialize(defaultAssistant),
|
||||
).resolves.not.toThrow();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,6 +1,9 @@
|
|||
import { type AssistantConfig } from "@continuedev/sdk";
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
||||
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
||||
import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
|
||||
|
||||
import { getErrorString } from "../util/error.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
|
@ -9,9 +12,9 @@ import { BaseService, ServiceWithDependencies } from "./BaseService.js";
|
|||
import { serviceContainer } from "./ServiceContainer.js";
|
||||
import {
|
||||
MCPConnectionInfo,
|
||||
MCPServerConfig,
|
||||
MCPServiceState,
|
||||
SERVICE_NAMES,
|
||||
MCPServerConfig,
|
||||
} from "./types.js";
|
||||
|
||||
interface ServerConnection extends MCPConnectionInfo {
|
||||
|
|
@ -214,31 +217,12 @@ export class MCPService
|
|||
this.updateState();
|
||||
|
||||
try {
|
||||
if (serverConfig.type && serverConfig.type !== "stdio") {
|
||||
throw new Error(
|
||||
`${serverConfig.type} MCP servers are not yet supported in the Continue CLI`,
|
||||
);
|
||||
}
|
||||
if (!serverConfig.command) {
|
||||
throw new Error("MCP server command is not specified");
|
||||
}
|
||||
|
||||
const client = new Client(
|
||||
{ name: "continue-cli-client", version: "1.0.0" },
|
||||
{ capabilities: {} },
|
||||
);
|
||||
|
||||
const env: Record<string, string> = serverConfig.env || {};
|
||||
if (process.env.PATH !== undefined) {
|
||||
env.PATH = process.env.PATH;
|
||||
}
|
||||
|
||||
const transport = new StdioClientTransport({
|
||||
command: serverConfig.command,
|
||||
args: serverConfig.args,
|
||||
env,
|
||||
stderr: "ignore",
|
||||
});
|
||||
const transport = await this.constructTransport(serverConfig);
|
||||
|
||||
logger.debug("Connecting to MCP server", {
|
||||
name: serverName,
|
||||
|
|
@ -363,4 +347,68 @@ export class MCPService
|
|||
logger.debug("Shutting down MCPService");
|
||||
await this.shutdownConnections();
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct transport based on server configuration
|
||||
*/
|
||||
private async constructTransport(
|
||||
serverConfig: MCPServerConfig,
|
||||
): Promise<Transport> {
|
||||
const transportType = serverConfig.type || "stdio";
|
||||
|
||||
switch (transportType) {
|
||||
case "stdio":
|
||||
if (!serverConfig.command) {
|
||||
throw new Error(
|
||||
"MCP server command is not specified for stdio transport",
|
||||
);
|
||||
}
|
||||
|
||||
const env: Record<string, string> = serverConfig.env || {};
|
||||
if (process.env.PATH !== undefined) {
|
||||
env.PATH = process.env.PATH;
|
||||
}
|
||||
|
||||
return new StdioClientTransport({
|
||||
command: serverConfig.command,
|
||||
args: serverConfig.args || [],
|
||||
env,
|
||||
cwd: serverConfig.cwd,
|
||||
stderr: "ignore",
|
||||
});
|
||||
|
||||
case "sse":
|
||||
if (!serverConfig.url) {
|
||||
throw new Error("MCP server URL is not specified for SSE transport");
|
||||
}
|
||||
return new SSEClientTransport(new URL(serverConfig.url), {
|
||||
eventSourceInit: {
|
||||
fetch: (input, init) =>
|
||||
fetch(input, {
|
||||
...init,
|
||||
headers: {
|
||||
...init?.headers,
|
||||
...(serverConfig.requestOptions?.headers as
|
||||
| Record<string, string>
|
||||
| undefined),
|
||||
},
|
||||
}),
|
||||
},
|
||||
requestInit: { headers: serverConfig.requestOptions?.headers },
|
||||
});
|
||||
|
||||
case "streamable-http":
|
||||
if (!serverConfig.url) {
|
||||
throw new Error(
|
||||
"MCP server URL is not specified for streamable-http transport",
|
||||
);
|
||||
}
|
||||
return new StreamableHTTPClientTransport(new URL(serverConfig.url), {
|
||||
requestInit: { headers: serverConfig.requestOptions?.headers },
|
||||
});
|
||||
|
||||
default:
|
||||
throw new Error(`Unsupported transport type: ${transportType}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@ async function handleHelp(_args: string[], _assistant: AssistantConfig) {
|
|||
` ${chalk.cyan("Enter")} Submit message`,
|
||||
` ${chalk.cyan("Shift+Enter")} New line`,
|
||||
` ${chalk.cyan("\\")} Line continuation (at end of line)`,
|
||||
` ${chalk.cyan("!")} Shell mode - run shell commands`,
|
||||
"",
|
||||
chalk.white("Controls:"),
|
||||
` ${chalk.cyan("Ctrl+C")} Clear input`,
|
||||
|
|
@ -39,9 +40,11 @@ async function handleHelp(_args: string[], _assistant: AssistantConfig) {
|
|||
chalk.white("Special Characters:"),
|
||||
` ${chalk.cyan("@")} Search and attach files for context`,
|
||||
` ${chalk.cyan("/")} Access slash commands`,
|
||||
` ${chalk.cyan("!")} Execute bash commands directly`,
|
||||
"",
|
||||
chalk.white("Available Commands:"),
|
||||
` Type ${chalk.cyan("/")} to see available slash commands`,
|
||||
` Type ${chalk.cyan("!")} followed by a command to execute bash directly`,
|
||||
].join("\n");
|
||||
posthogService.capture("useSlashCommand", { name: "help" });
|
||||
return { output: helpMessage };
|
||||
|
|
|
|||
|
|
@ -25,11 +25,17 @@ export function handlePermissionDenied(
|
|||
toolCall: PreprocessedToolCall,
|
||||
chatHistoryEntries: ChatCompletionToolMessageParam[],
|
||||
callbacks?: StreamCallbacks,
|
||||
reason: "user" | "policy" = "user",
|
||||
): void {
|
||||
const deniedMessage = `Permission denied by user`;
|
||||
const deniedMessage =
|
||||
reason === "policy"
|
||||
? `Command blocked by security policy`
|
||||
: `Permission denied by user`;
|
||||
|
||||
logger.info("Tool call denied", {
|
||||
name: toolCall.name,
|
||||
arguments: toolCall.arguments,
|
||||
reason,
|
||||
});
|
||||
|
||||
chatHistoryEntries.push({
|
||||
|
|
@ -39,7 +45,7 @@ export function handlePermissionDenied(
|
|||
});
|
||||
|
||||
callbacks?.onToolResult?.(deniedMessage, toolCall.name, "canceled");
|
||||
logger.debug("Tool call rejected - stopping stream");
|
||||
logger.debug(`Tool call rejected (${reason}) - stopping stream`);
|
||||
}
|
||||
|
||||
// Helper function to handle headless mode permission
|
||||
|
|
@ -114,22 +120,25 @@ export async function checkToolPermissionApproval(
|
|||
toolCall: PreprocessedToolCall,
|
||||
callbacks?: StreamCallbacks,
|
||||
isHeadless?: boolean,
|
||||
): Promise<boolean> {
|
||||
): Promise<{ approved: boolean; denialReason?: "user" | "policy" }> {
|
||||
const permissionCheck = checkToolPermission(toolCall);
|
||||
|
||||
if (permissionCheck.permission === "allow") {
|
||||
return true;
|
||||
return { approved: true };
|
||||
} else if (permissionCheck.permission === "ask") {
|
||||
if (isHeadless) {
|
||||
handleHeadlessPermission(toolCall);
|
||||
}
|
||||
return await requestUserPermission(toolCall, callbacks);
|
||||
const userApproved = await requestUserPermission(toolCall, callbacks);
|
||||
return userApproved
|
||||
? { approved: true }
|
||||
: { approved: false, denialReason: "user" };
|
||||
} else if (permissionCheck.permission === "exclude") {
|
||||
// This shouldn't happen as excluded tools are filtered out earlier
|
||||
return false;
|
||||
// Tool blocked by security policy
|
||||
return { approved: false, denialReason: "policy" };
|
||||
}
|
||||
|
||||
return false;
|
||||
return { approved: false, denialReason: "policy" };
|
||||
}
|
||||
|
||||
// Helper function to track first token time
|
||||
|
|
@ -401,18 +410,25 @@ export async function executeStreamedToolCalls(
|
|||
// Notify tool start before permission check to display in UI fallbacks
|
||||
callbacks?.onToolStart?.(call.name, call.arguments);
|
||||
|
||||
const approved = await checkToolPermissionApproval(
|
||||
// Check tool permissions using helper
|
||||
const permissionResult = await checkToolPermissionApproval(
|
||||
call,
|
||||
callbacks,
|
||||
isHeadless,
|
||||
);
|
||||
|
||||
if (!approved) {
|
||||
if (!permissionResult.approved) {
|
||||
// Permission denied: record and mark rejection
|
||||
const denialReason = permissionResult.denialReason || "user";
|
||||
const deniedMessage =
|
||||
denialReason === "policy"
|
||||
? `Command blocked by security policy`
|
||||
: `Permission denied by user`;
|
||||
|
||||
const deniedEntry: ChatCompletionToolMessageParam = {
|
||||
role: "tool",
|
||||
tool_call_id: call.id,
|
||||
content: `Permission denied by user`,
|
||||
content: deniedMessage,
|
||||
};
|
||||
entriesByIndex.set(index, deniedEntry);
|
||||
callbacks?.onToolResult?.(
|
||||
|
|
|
|||
|
|
@ -37,6 +37,7 @@ class TelemetryService {
|
|||
private startTime = Date.now();
|
||||
private activeStartTime: number | null = null;
|
||||
private totalActiveTime = 0;
|
||||
private shutdownHandlersRegistered = false;
|
||||
|
||||
// Metrics
|
||||
private sessionCounter: any = null;
|
||||
|
|
@ -114,7 +115,7 @@ class TelemetryService {
|
|||
),
|
||||
}),
|
||||
exportIntervalMillis: parseInt(
|
||||
process.env.OTEL_METRIC_EXPORT_INTERVAL || "60000",
|
||||
process.env.OTEL_METRIC_EXPORT_INTERVAL || "20000",
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
|
@ -124,7 +125,7 @@ class TelemetryService {
|
|||
new PeriodicExportingMetricReader({
|
||||
exporter: new ConsoleMetricExporter(),
|
||||
exportIntervalMillis: parseInt(
|
||||
process.env.OTEL_METRIC_EXPORT_INTERVAL || "60000",
|
||||
process.env.OTEL_METRIC_EXPORT_INTERVAL || "20000",
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
|
@ -143,15 +144,38 @@ class TelemetryService {
|
|||
|
||||
this.initializeMetrics();
|
||||
|
||||
logger.debug("Telemetry service initialized", {
|
||||
// Set up graceful shutdown handlers
|
||||
this.setupShutdownHandlers();
|
||||
|
||||
logger.info("Telemetry service initialized", {
|
||||
sessionId: this.config.sessionId,
|
||||
exporters: metricsExporters,
|
||||
exportInterval: process.env.OTEL_METRIC_EXPORT_INTERVAL || "20000",
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error("Failed to initialize telemetry", error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set up process handlers to ensure metrics are flushed on shutdown
|
||||
*/
|
||||
private setupShutdownHandlers() {
|
||||
if (this.shutdownHandlersRegistered) return;
|
||||
|
||||
const shutdownHandler = async () => {
|
||||
logger.debug("Process shutdown detected, flushing telemetry...");
|
||||
await this.shutdown();
|
||||
};
|
||||
|
||||
// Handle graceful shutdown - use once() to avoid duplicate handlers
|
||||
process.once("beforeExit", shutdownHandler);
|
||||
process.once("SIGINT", shutdownHandler);
|
||||
process.once("SIGTERM", shutdownHandler);
|
||||
|
||||
this.shutdownHandlersRegistered = true;
|
||||
}
|
||||
|
||||
private parseHeaders(headersStr: string): Record<string, string> {
|
||||
const headers: Record<string, string> = {};
|
||||
if (!headersStr) return headers;
|
||||
|
|
@ -171,7 +195,7 @@ class TelemetryService {
|
|||
|
||||
// Core metrics (Claude Code compatible)
|
||||
this.sessionCounter = this.meter.createCounter(
|
||||
"continue.cli.session.count",
|
||||
"continue_cli_session_count",
|
||||
{
|
||||
description: "Count of CLI sessions started",
|
||||
unit: "count",
|
||||
|
|
@ -179,7 +203,7 @@ class TelemetryService {
|
|||
);
|
||||
|
||||
this.linesOfCodeCounter = this.meter.createCounter(
|
||||
"continue.cli.lines_of_code.count",
|
||||
"continue_cli_lines_of_code_count",
|
||||
{
|
||||
description: "Count of lines of code modified",
|
||||
unit: "count",
|
||||
|
|
@ -187,30 +211,30 @@ class TelemetryService {
|
|||
);
|
||||
|
||||
this.pullRequestCounter = this.meter.createCounter(
|
||||
"continue.cli.pull_request.count",
|
||||
"continue_cli_pull_request_count",
|
||||
{
|
||||
description: "Number of pull requests created",
|
||||
unit: "count",
|
||||
},
|
||||
);
|
||||
|
||||
this.commitCounter = this.meter.createCounter("continue.cli.commit.count", {
|
||||
this.commitCounter = this.meter.createCounter("continue_cli_commit_count", {
|
||||
description: "Number of git commits created",
|
||||
unit: "count",
|
||||
});
|
||||
|
||||
this.costCounter = this.meter.createCounter("continue.cli.cost.usage", {
|
||||
this.costCounter = this.meter.createCounter("continue_cli_cost_usage", {
|
||||
description: "Cost of the Continue CLI session",
|
||||
unit: "USD",
|
||||
});
|
||||
|
||||
this.tokenCounter = this.meter.createCounter("continue.cli.token.usage", {
|
||||
this.tokenCounter = this.meter.createCounter("continue_cli_token_usage", {
|
||||
description: "Number of tokens used",
|
||||
unit: "tokens",
|
||||
});
|
||||
|
||||
this.codeEditDecisionCounter = this.meter.createCounter(
|
||||
"continue.cli.code_edit_tool.decision",
|
||||
"continue_cli_code_edit_tool_decision",
|
||||
{
|
||||
description: "Count of code editing tool permission decisions",
|
||||
unit: "count",
|
||||
|
|
@ -218,7 +242,7 @@ class TelemetryService {
|
|||
);
|
||||
|
||||
this.activeTimeCounter = this.meter.createCounter(
|
||||
"continue.cli.active_time.total",
|
||||
"continue_cli_active_time_total",
|
||||
{
|
||||
description: "Total active time in seconds",
|
||||
unit: "s",
|
||||
|
|
@ -227,7 +251,7 @@ class TelemetryService {
|
|||
|
||||
// Additional Continue CLI specific metrics
|
||||
this.authAttemptsCounter = this.meter.createCounter(
|
||||
"continue.cli.auth.attempts",
|
||||
"continue_cli_auth_attempts",
|
||||
{
|
||||
description: "Authentication attempts",
|
||||
unit: "{attempt}",
|
||||
|
|
@ -235,7 +259,7 @@ class TelemetryService {
|
|||
);
|
||||
|
||||
this.mcpConnectionsGauge = this.meter.createObservableGauge(
|
||||
"continue.cli.mcp.connections",
|
||||
"continue_cli_mcp_connections",
|
||||
{
|
||||
description: "Active MCP connections",
|
||||
unit: "{connection}",
|
||||
|
|
@ -243,7 +267,7 @@ class TelemetryService {
|
|||
);
|
||||
|
||||
this.startupTimeHistogram = this.meter.createHistogram(
|
||||
"continue.cli.startup.time",
|
||||
"continue_cli_startup_time",
|
||||
{
|
||||
description: "Time from CLI start to ready state",
|
||||
unit: "ms",
|
||||
|
|
@ -251,7 +275,7 @@ class TelemetryService {
|
|||
);
|
||||
|
||||
this.responseTimeHistogram = this.meter.createHistogram(
|
||||
"continue.cli.response_time",
|
||||
"continue_cli_response_time",
|
||||
{
|
||||
description: "LLM response time metrics",
|
||||
unit: "ms",
|
||||
|
|
@ -312,6 +336,7 @@ class TelemetryService {
|
|||
public recordSessionStart() {
|
||||
if (!this.isEnabled()) return;
|
||||
|
||||
logger.debug("Recording session start with telemetry");
|
||||
this.sessionCounter.add(1, this.getStandardAttributes());
|
||||
this.recordStartupTime(Date.now() - this.startTime);
|
||||
}
|
||||
|
|
@ -542,9 +567,26 @@ class TelemetryService {
|
|||
return this.config.sessionId;
|
||||
}
|
||||
|
||||
public shutdown() {
|
||||
/**
|
||||
* Shutdown telemetry service and ensure all metrics are flushed
|
||||
*/
|
||||
public async shutdown(): Promise<void> {
|
||||
this.stopActiveTime();
|
||||
return this.meterProvider?.shutdown();
|
||||
|
||||
if (this.meterProvider) {
|
||||
try {
|
||||
logger.debug("Flushing telemetry metrics before shutdown...");
|
||||
// Force flush any pending metrics before shutdown
|
||||
await this.meterProvider.forceFlush();
|
||||
logger.debug("Telemetry metrics flushed successfully");
|
||||
|
||||
// Now shutdown the provider
|
||||
await this.meterProvider.shutdown();
|
||||
logger.debug("Telemetry service shut down successfully");
|
||||
} catch (error) {
|
||||
logger.error("Failed to shutdown telemetry service", error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,10 @@
|
|||
import { spawn } from "child_process";
|
||||
|
||||
import {
|
||||
evaluateTerminalCommandSecurity,
|
||||
type ToolPolicy,
|
||||
} from "@continuedev/terminal-security";
|
||||
|
||||
import { telemetryService } from "../telemetry/telemetryService.js";
|
||||
import {
|
||||
isGitCommitCommand,
|
||||
|
|
@ -39,6 +44,15 @@ The command will be executed from the current working directory: ${process.cwd()
|
|||
},
|
||||
readonly: false,
|
||||
isBuiltIn: true,
|
||||
evaluateToolCallPolicy: (
|
||||
basePolicy: ToolPolicy,
|
||||
parsedArgs: Record<string, unknown>,
|
||||
): ToolPolicy => {
|
||||
return evaluateTerminalCommandSecurity(
|
||||
basePolicy,
|
||||
parsedArgs.command as string,
|
||||
);
|
||||
},
|
||||
preprocess: async (args) => {
|
||||
const command = args.command;
|
||||
if (!command || typeof command !== "string") {
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
import type { ToolPolicy } from "@continuedev/terminal-security";
|
||||
|
||||
export type ToolParameters = Record<
|
||||
string,
|
||||
{
|
||||
|
|
@ -31,6 +33,10 @@ export interface Tool {
|
|||
run: (args: any) => Promise<string>;
|
||||
readonly?: boolean; // Indicates if the tool is readonly
|
||||
isBuiltIn: boolean;
|
||||
evaluateToolCallPolicy?: (
|
||||
basePolicy: ToolPolicy,
|
||||
parsedArgs: Record<string, unknown>,
|
||||
) => ToolPolicy;
|
||||
}
|
||||
|
||||
export interface ToolCall {
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ import {
|
|||
} from "../auth/workos.js";
|
||||
import { getApiClient } from "../config.js";
|
||||
import { env } from "../env.js";
|
||||
import { services } from "../services/index.js";
|
||||
|
||||
import { Selector, SelectorOption } from "./Selector.js";
|
||||
|
||||
|
|
@ -118,8 +119,10 @@ const ConfigSelector: React.FC<ConfigSelectorProps> = ({
|
|||
displaySuffix: " (opens web)",
|
||||
});
|
||||
|
||||
// Determine current config by checking auth config
|
||||
// Determine current config by checking both auth config and service state
|
||||
const assistantSlug = getAssistantSlug(authConfig);
|
||||
const currentConfigState = services.config.getState();
|
||||
|
||||
if (assistantSlug) {
|
||||
// Find the matching config by slug and organization
|
||||
const matchingConfig = options.find(
|
||||
|
|
@ -129,8 +132,12 @@ const ConfigSelector: React.FC<ConfigSelectorProps> = ({
|
|||
opt.organizationId === currentOrganizationId,
|
||||
);
|
||||
currentId = matchingConfig?.id || null;
|
||||
} else if (fs.existsSync(CONFIG_PATH)) {
|
||||
// No assistant slug means local config is current
|
||||
} else if (
|
||||
currentConfigState.configPath === CONFIG_PATH &&
|
||||
fs.existsSync(CONFIG_PATH)
|
||||
) {
|
||||
// Only mark local config as current if it's actually the active config path in the service
|
||||
// This ensures we don't show a green checkmark for first-time users just because the file exists
|
||||
currentId = "local";
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ import {
|
|||
import { updateAnthropicModelInYaml } from "../util/yamlConfigUpdater.js";
|
||||
|
||||
import { useNavigation } from "./context/NavigationContext.js";
|
||||
import { defaultBoxStyles } from "./styles.js";
|
||||
|
||||
const CONFIG_PATH = path.join(env.continueHome, "config.yaml");
|
||||
|
||||
|
|
@ -130,6 +131,18 @@ const FreeTrialTransitionUI: React.FC<FreeTrialTransitionUIProps> = ({
|
|||
const hasOrganizations = organizations && organizations.length > 0;
|
||||
|
||||
useInput((input, key) => {
|
||||
// Allow Escape to cancel immediately, but Ctrl+C uses two-stage exit
|
||||
if (key.escape) {
|
||||
closeCurrentScreen();
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle Ctrl+C with two-stage exit (delegates to main process)
|
||||
if (key.ctrl && input === "c") {
|
||||
process.kill(process.pid, "SIGINT");
|
||||
return;
|
||||
}
|
||||
|
||||
if (currentStep === "choice") {
|
||||
handleChoiceInput({
|
||||
input,
|
||||
|
|
@ -215,39 +228,38 @@ const FreeTrialTransitionUI: React.FC<FreeTrialTransitionUIProps> = ({
|
|||
};
|
||||
|
||||
if (currentStep === "choice") {
|
||||
const options = [
|
||||
{ num: 1, text: "💳 Sign up for models add-on (recommended)" },
|
||||
{ num: 2, text: "🔑 Enter your Anthropic API key" },
|
||||
{ num: 3, text: "⚙️ Switch to a different configuration" },
|
||||
];
|
||||
|
||||
if (hasOrganizations) {
|
||||
options.push({
|
||||
num: 4,
|
||||
text: "🏢 Switch to organization configuration",
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<Box
|
||||
flexDirection="column"
|
||||
padding={1}
|
||||
borderStyle="round"
|
||||
borderColor="yellow"
|
||||
>
|
||||
<Box {...defaultBoxStyles("yellow")}>
|
||||
<Text bold color="yellow">
|
||||
🚀 Free trial limit reached!
|
||||
</Text>
|
||||
<Text>Choose how you'd like to continue:</Text>
|
||||
<Text></Text>
|
||||
<Text color={selectedOption === 1 ? "cyan" : "white"}>
|
||||
{selectedOption === 1 ? "▶ " : " "}1. 💳 Sign up for models add-on
|
||||
(recommended)
|
||||
</Text>
|
||||
<Text color={selectedOption === 2 ? "cyan" : "white"}>
|
||||
{selectedOption === 2 ? "▶ " : " "}2. 🔑 Enter your Anthropic API
|
||||
key
|
||||
</Text>
|
||||
<Text color={selectedOption === 3 ? "cyan" : "white"}>
|
||||
{selectedOption === 3 ? "▶ " : " "}3. ⚙️ Switch to a different
|
||||
configuration
|
||||
</Text>
|
||||
{hasOrganizations && (
|
||||
<Text color={selectedOption === 4 ? "cyan" : "white"}>
|
||||
{selectedOption === 4 ? "▶ " : " "}4. 🏢 Switch to organization
|
||||
configuration
|
||||
{options.map((option) => (
|
||||
<Text
|
||||
key={option.num}
|
||||
color={selectedOption === option.num ? "cyan" : "white"}
|
||||
>
|
||||
{selectedOption === option.num ? "➤ " : " "}
|
||||
{option.num}. {option.text}
|
||||
</Text>
|
||||
)}
|
||||
))}
|
||||
<Text></Text>
|
||||
<Text color="gray">
|
||||
Use ↑↓ arrows or {hasOrganizations ? "1/2/3/4" : "1/2/3"} to select,
|
||||
↑/↓ to navigate or {hasOrganizations ? "1/2/3/4" : "1/2/3"} to select,
|
||||
Enter to confirm
|
||||
</Text>
|
||||
</Box>
|
||||
|
|
@ -256,12 +268,7 @@ const FreeTrialTransitionUI: React.FC<FreeTrialTransitionUIProps> = ({
|
|||
|
||||
if (currentStep === "enterApiKey") {
|
||||
return (
|
||||
<Box
|
||||
flexDirection="column"
|
||||
padding={1}
|
||||
borderStyle="round"
|
||||
borderColor="yellow"
|
||||
>
|
||||
<Box {...defaultBoxStyles("yellow")}>
|
||||
<Text bold color="yellow">
|
||||
Enter your Anthropic API key
|
||||
</Text>
|
||||
|
|
@ -278,12 +285,7 @@ const FreeTrialTransitionUI: React.FC<FreeTrialTransitionUIProps> = ({
|
|||
|
||||
if (currentStep === "processing") {
|
||||
return (
|
||||
<Box
|
||||
flexDirection="column"
|
||||
padding={1}
|
||||
borderStyle="round"
|
||||
borderColor="blue"
|
||||
>
|
||||
<Box {...defaultBoxStyles("blue")}>
|
||||
<Text bold color="blue">
|
||||
Processing...
|
||||
</Text>
|
||||
|
|
@ -294,12 +296,7 @@ const FreeTrialTransitionUI: React.FC<FreeTrialTransitionUIProps> = ({
|
|||
|
||||
if (currentStep === "success") {
|
||||
return (
|
||||
<Box
|
||||
flexDirection="column"
|
||||
padding={1}
|
||||
borderStyle="round"
|
||||
borderColor="green"
|
||||
>
|
||||
<Box {...defaultBoxStyles("green")}>
|
||||
<Text bold color="green">
|
||||
Success!
|
||||
</Text>
|
||||
|
|
@ -316,12 +313,7 @@ const FreeTrialTransitionUI: React.FC<FreeTrialTransitionUIProps> = ({
|
|||
|
||||
if (currentStep === "error") {
|
||||
return (
|
||||
<Box
|
||||
flexDirection="column"
|
||||
padding={1}
|
||||
borderStyle="round"
|
||||
borderColor="red"
|
||||
>
|
||||
<Box {...defaultBoxStyles("red")}>
|
||||
<Text bold color="red">
|
||||
Error
|
||||
</Text>
|
||||
|
|
|
|||
|
|
@ -3,11 +3,18 @@ import React, { useState } from "react";
|
|||
import { quote } from "shell-quote";
|
||||
|
||||
import { useServices } from "../hooks/useService.js";
|
||||
import { MCPServiceState, SERVICE_NAMES } from "../services/types.js";
|
||||
import {
|
||||
MCPConnectionInfo,
|
||||
MCPServerStatus,
|
||||
MCPServiceState,
|
||||
SERVICE_NAMES,
|
||||
} from "../services/types.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
import { defaultBoxStyles } from "./styles.js";
|
||||
|
||||
// Utility function to get status icon and color based on server connection
|
||||
const getServerStatusDisplay = (conn: any) => {
|
||||
const getServerStatusDisplay = (conn: MCPConnectionInfo) => {
|
||||
let icon = "⚪️"; // note, white circle causes extra blank line bug
|
||||
let color: "green" | "yellow" | "red" | "white" | "dim" = "white";
|
||||
let statusText = conn.status;
|
||||
|
|
@ -22,7 +29,7 @@ const getServerStatusDisplay = (conn: any) => {
|
|||
if (conn.warnings && conn.warnings.length > 0) {
|
||||
icon = "🟡";
|
||||
color = "yellow";
|
||||
statusText = "connected (with warnings)";
|
||||
statusText = "connected (with warnings)" as MCPServerStatus;
|
||||
} else {
|
||||
icon = "🟢";
|
||||
color = "green";
|
||||
|
|
@ -170,7 +177,7 @@ export const MCPSelector: React.FC<MCPSelectorProps> = ({ onCancel }) => {
|
|||
{/* Add prompts if any */}
|
||||
{serverInfo.prompts.length > 0 && (
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Text color="cyan">📝 Prompts: {serverInfo.prompts.length}</Text>
|
||||
<Text color="blue">📝 Prompts: {serverInfo.prompts.length}</Text>
|
||||
{serverInfo.prompts.map((prompt, index) => (
|
||||
<Text key={index} color="dim">
|
||||
• {prompt.name}
|
||||
|
|
@ -182,7 +189,7 @@ export const MCPSelector: React.FC<MCPSelectorProps> = ({ onCancel }) => {
|
|||
{/* Add tools if any */}
|
||||
{serverInfo.tools.length > 0 && (
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Text color="cyan">🔧 Tools: {serverInfo.tools.length}</Text>
|
||||
<Text color="blue">🔧 Tools: {serverInfo.tools.length}</Text>
|
||||
{serverInfo.tools.map((tool, index) => (
|
||||
<Text key={index} color="dim">
|
||||
• {tool.name}
|
||||
|
|
@ -210,13 +217,14 @@ export const MCPSelector: React.FC<MCPSelectorProps> = ({ onCancel }) => {
|
|||
const maxIndex = Math.max(0, items.length - 1);
|
||||
|
||||
useInput(async (input, key) => {
|
||||
if (isLoading) return;
|
||||
|
||||
if (key.escape) {
|
||||
// Always allow escape/Ctrl+C so users can cancel even when loading
|
||||
if (key.escape || (key.ctrl && input === "c")) {
|
||||
handleBack();
|
||||
return;
|
||||
}
|
||||
|
||||
if (isLoading) return;
|
||||
|
||||
if (key.upArrow) {
|
||||
setSelectedIndex(selectedIndex <= 0 ? maxIndex : selectedIndex - 1);
|
||||
return;
|
||||
|
|
@ -302,7 +310,7 @@ export const MCPSelector: React.FC<MCPSelectorProps> = ({ onCancel }) => {
|
|||
const renderHeader = () => {
|
||||
return (
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Text bold color="cyan">
|
||||
<Text bold color="blue">
|
||||
{menuState === "server-detail" && selectedServer
|
||||
? `Server: ${selectedServer}`
|
||||
: "MCP Servers"}
|
||||
|
|
@ -336,13 +344,7 @@ export const MCPSelector: React.FC<MCPSelectorProps> = ({ onCancel }) => {
|
|||
};
|
||||
|
||||
return (
|
||||
<Box
|
||||
flexDirection="column"
|
||||
borderStyle="round"
|
||||
borderColor="cyan"
|
||||
padding={1}
|
||||
minHeight={10}
|
||||
>
|
||||
<Box {...defaultBoxStyles("blue", { minHeight: 10 })}>
|
||||
{renderHeader()}
|
||||
|
||||
{message && (
|
||||
|
|
@ -369,9 +371,8 @@ export const MCPSelector: React.FC<MCPSelectorProps> = ({ onCancel }) => {
|
|||
key={`${item.value}-${index}`}
|
||||
color={isSelected ? "blue" : "white"}
|
||||
bold={isSelected}
|
||||
inverse={isSelected}
|
||||
>
|
||||
{isSelected ? "> " : " "}
|
||||
{isSelected ? "➤ " : " "}
|
||||
{item.label}
|
||||
</Text>
|
||||
);
|
||||
|
|
@ -381,7 +382,7 @@ export const MCPSelector: React.FC<MCPSelectorProps> = ({ onCancel }) => {
|
|||
|
||||
<Box marginTop={1}>
|
||||
<Text color="dim">
|
||||
Use ↑/↓ to navigate, Enter to select, Esc to go back
|
||||
↑/↓ to navigate, Enter to select, Esc to go back
|
||||
</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
|
|
|
|||
|
|
@ -1,20 +1,14 @@
|
|||
import { Box, Text, useInput } from "ink";
|
||||
import React, { ReactNode } from "react";
|
||||
|
||||
import { defaultBoxStyles } from "./styles.js";
|
||||
|
||||
export interface SelectorOption {
|
||||
id: string;
|
||||
name: string;
|
||||
displaySuffix?: string;
|
||||
}
|
||||
|
||||
const boxStyles: React.ComponentProps<typeof Box> = {
|
||||
flexDirection: "column",
|
||||
paddingX: 2,
|
||||
paddingY: 1,
|
||||
borderStyle: "round",
|
||||
borderColor: "blue",
|
||||
};
|
||||
|
||||
interface SelectorProps<T extends SelectorOption> {
|
||||
title: string;
|
||||
options: T[];
|
||||
|
|
@ -46,8 +40,20 @@ export function Selector<T extends SelectorOption>({
|
|||
onNavigate,
|
||||
renderOption,
|
||||
}: SelectorProps<T>) {
|
||||
// Handle input for loading and error states
|
||||
useInput((input, key) => {
|
||||
if (key.escape) {
|
||||
if (loading || error) {
|
||||
if (key.escape || (key.ctrl && input === "c")) {
|
||||
onCancel();
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
useInput((input, key) => {
|
||||
if (loading || error) return; // Skip normal input handling during loading/error
|
||||
|
||||
if (key.escape || (key.ctrl && input === "c")) {
|
||||
onCancel();
|
||||
return;
|
||||
}
|
||||
|
|
@ -70,7 +76,7 @@ export function Selector<T extends SelectorOption>({
|
|||
|
||||
if (loading) {
|
||||
return (
|
||||
<Box {...boxStyles}>
|
||||
<Box {...defaultBoxStyles("blue")}>
|
||||
<Text color="blue" bold>
|
||||
{title}
|
||||
</Text>
|
||||
|
|
@ -84,13 +90,13 @@ export function Selector<T extends SelectorOption>({
|
|||
|
||||
if (error) {
|
||||
return (
|
||||
<Box {...boxStyles}>
|
||||
<Box {...defaultBoxStyles("blue")}>
|
||||
<Text color="red" bold>
|
||||
Error
|
||||
</Text>
|
||||
<Text color="red">{error}</Text>
|
||||
<Text color="gray" dimColor>
|
||||
Press Escape to cancel
|
||||
Press Esc to cancel
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
|
|
@ -106,7 +112,7 @@ export function Selector<T extends SelectorOption>({
|
|||
color={isSelected ? "blue" : isCurrent ? "green" : "white"}
|
||||
bold={isSelected}
|
||||
>
|
||||
{isSelected ? "→ " : " "}
|
||||
{isSelected ? "➤ " : " "}
|
||||
{option.name}
|
||||
{option.displaySuffix || ""}
|
||||
</Text>
|
||||
|
|
@ -119,7 +125,7 @@ export function Selector<T extends SelectorOption>({
|
|||
);
|
||||
|
||||
return (
|
||||
<Box {...boxStyles}>
|
||||
<Box {...defaultBoxStyles("blue")}>
|
||||
<Text color="blue" bold>
|
||||
{title}
|
||||
</Text>
|
||||
|
|
@ -136,7 +142,7 @@ export function Selector<T extends SelectorOption>({
|
|||
</Box>
|
||||
<Box marginTop={1}>
|
||||
<Text color="gray" dimColor>
|
||||
↑/↓ to navigate, Enter to select, Escape to cancel
|
||||
↑/↓ to navigate, Enter to select, Esc to cancel
|
||||
</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
|
|
|
|||
|
|
@ -9,6 +9,8 @@ import {
|
|||
ModelServiceState,
|
||||
} from "../services/types.js";
|
||||
|
||||
import { defaultBoxStyles } from "./styles.js";
|
||||
|
||||
interface ServiceDebuggerProps {
|
||||
services: {
|
||||
auth?: AuthServiceState;
|
||||
|
|
@ -60,13 +62,7 @@ const ServiceDebugger: React.FC<ServiceDebuggerProps> = ({
|
|||
};
|
||||
|
||||
return (
|
||||
<Box
|
||||
flexDirection="column"
|
||||
paddingX={1}
|
||||
paddingY={1}
|
||||
borderStyle="round"
|
||||
borderColor="cyan"
|
||||
>
|
||||
<Box {...defaultBoxStyles("cyan")}>
|
||||
<Text bold color="cyan">
|
||||
🔧 Service Debug Info
|
||||
</Text>
|
||||
|
|
|
|||
|
|
@ -1,10 +1,11 @@
|
|||
import { format, isToday, isYesterday, isThisWeek, isThisYear } from "date-fns";
|
||||
import { format, isThisWeek, isThisYear, isToday, isYesterday } from "date-fns";
|
||||
import { Box, Text, useInput } from "ink";
|
||||
import React, { useMemo, useState } from "react";
|
||||
|
||||
import { SessionMetadata } from "../session.js";
|
||||
|
||||
import { useTerminalSize } from "./hooks/useTerminalSize.js";
|
||||
import { defaultBoxStyles } from "./styles.js";
|
||||
|
||||
interface SessionSelectorProps {
|
||||
sessions: SessionMetadata[];
|
||||
|
|
@ -70,33 +71,31 @@ export function SessionSelector({
|
|||
|
||||
if (sessions.length === 0) {
|
||||
return (
|
||||
<Box flexDirection="column" padding={1}>
|
||||
<Box {...defaultBoxStyles("blue")}>
|
||||
<Text color="yellow">No previous sessions found.</Text>
|
||||
<Text color="gray">Start a new conversation with: cn</Text>
|
||||
<Text color="gray">Press ESC or Ctrl+D to exit</Text>
|
||||
<Text color="gray">Press Esc to exit</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" padding={1}>
|
||||
<Box {...defaultBoxStyles("blue")}>
|
||||
<Text color="blue" bold>
|
||||
Recent Sessions
|
||||
</Text>
|
||||
<Text color="gray">
|
||||
Use ↑↓ arrows to navigate, Enter to select, ESC or Ctrl+D to exit
|
||||
</Text>
|
||||
<Text color="gray">↑/↓ to navigate, Enter to select, Esc to exit</Text>
|
||||
<Text> </Text>
|
||||
|
||||
{displaySessions.map((session, index) => {
|
||||
const isSelected = index === selectedIndex;
|
||||
const indicator = isSelected ? "► " : " ";
|
||||
const color = isSelected ? "cyan" : "white";
|
||||
const indicator = isSelected ? "➤ " : " ";
|
||||
const color = isSelected ? "blue" : "white";
|
||||
|
||||
return (
|
||||
<Box key={session.sessionId} flexDirection="column">
|
||||
<Box paddingRight={3}>
|
||||
<Text color={color} wrap="truncate-end">
|
||||
<Text bold={isSelected} color={color} wrap="truncate-end">
|
||||
{indicator}
|
||||
{formatMessage(session.title)}
|
||||
</Text>
|
||||
|
|
|
|||
|
|
@ -73,7 +73,7 @@ const SlashCommandUI: React.FC<SlashCommandUIProps> = ({
|
|||
{" "}
|
||||
{paddedCommandName}
|
||||
<Text color={isSelected ? "blue" : "gray"}>
|
||||
{" "}
|
||||
{" "}
|
||||
{command.description}
|
||||
</Text>
|
||||
</Text>
|
||||
|
|
|
|||
|
|
@ -20,6 +20,77 @@ import {
|
|||
import { SlashCommandUI } from "./SlashCommandUI.js";
|
||||
import { TextBuffer } from "./TextBuffer.js";
|
||||
|
||||
// Small presentational helpers to reduce cyclomatic complexity in UserInput
|
||||
const InterruptedBanner: React.FC<{ wasInterrupted: boolean }> = ({
|
||||
wasInterrupted,
|
||||
}) => {
|
||||
if (!wasInterrupted) return null;
|
||||
return (
|
||||
<Box paddingX={1} marginBottom={0}>
|
||||
<Text color="yellow">⚠ Interrupted by user - Press enter to resume</Text>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
const SlashCommandsMaybe: React.FC<{
|
||||
show: boolean;
|
||||
inputMode: boolean;
|
||||
hideNormalUI: boolean;
|
||||
isRemoteMode: boolean;
|
||||
assistant?: AssistantConfig;
|
||||
filter: string;
|
||||
selectedIndex: number;
|
||||
}> = ({
|
||||
show,
|
||||
inputMode,
|
||||
hideNormalUI,
|
||||
isRemoteMode,
|
||||
assistant,
|
||||
filter,
|
||||
selectedIndex,
|
||||
}) => {
|
||||
if (!show || !inputMode || hideNormalUI || !(isRemoteMode || assistant))
|
||||
return null;
|
||||
return (
|
||||
<SlashCommandUI
|
||||
assistant={assistant}
|
||||
filter={filter}
|
||||
selectedIndex={selectedIndex}
|
||||
isRemoteMode={isRemoteMode}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const FileSearchMaybe: React.FC<{
|
||||
show: boolean;
|
||||
inputMode: boolean;
|
||||
hideNormalUI: boolean;
|
||||
isRemoteMode: boolean;
|
||||
filter: string;
|
||||
selectedIndex: number;
|
||||
onSelect: (path: string) => void | Promise<void>;
|
||||
onFilesUpdated: (files: Array<{ path: string; displayName: string }>) => void;
|
||||
}> = ({
|
||||
show,
|
||||
inputMode,
|
||||
hideNormalUI,
|
||||
isRemoteMode,
|
||||
filter,
|
||||
selectedIndex,
|
||||
onSelect,
|
||||
onFilesUpdated,
|
||||
}) => {
|
||||
if (!show || !inputMode || hideNormalUI || isRemoteMode) return null;
|
||||
return (
|
||||
<FileSearchUI
|
||||
filter={filter}
|
||||
selectedIndex={selectedIndex}
|
||||
onSelect={onSelect}
|
||||
onFilesUpdated={onFilesUpdated}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
interface UserInputProps {
|
||||
onSubmit: (message: string, imageMap?: Map<string, Buffer>) => void;
|
||||
isWaitingForResponse: boolean;
|
||||
|
|
@ -70,8 +141,21 @@ const UserInput: React.FC<UserInputProps> = ({
|
|||
const [inputText, setInputText] = useState("");
|
||||
const [cursorPosition, setCursorPosition] = useState(0);
|
||||
const [showSlashCommands, setShowSlashCommands] = useState(false);
|
||||
|
||||
// Clear input function for Ctrl+C
|
||||
const clearInput = useCallback(() => {
|
||||
textBuffer.clear();
|
||||
setInputText("");
|
||||
setCursorPosition(0);
|
||||
setShowSlashCommands(false);
|
||||
setShowFileSearch(false);
|
||||
setShowBashMode(false);
|
||||
inputHistory.resetNavigation();
|
||||
}, [textBuffer]);
|
||||
|
||||
const [slashCommandFilter, setSlashCommandFilter] = useState("");
|
||||
const [selectedCommandIndex, setSelectedCommandIndex] = useState(0);
|
||||
const [showBashMode, setShowBashMode] = useState(false);
|
||||
const [showFileSearch, setShowFileSearch] = useState(false);
|
||||
const [fileSearchFilter, setFileSearchFilter] = useState("");
|
||||
const [selectedFileIndex, setSelectedFileIndex] = useState(0);
|
||||
|
|
@ -121,6 +205,18 @@ const UserInput: React.FC<UserInputProps> = ({
|
|||
return nextMode;
|
||||
};
|
||||
|
||||
// Update shell mode state based on input
|
||||
const updateBashModeState = (text: string) => {
|
||||
const trimmed = text.trimStart();
|
||||
const isBash = trimmed.startsWith("!");
|
||||
setShowBashMode(isBash);
|
||||
if (isBash) {
|
||||
// Disable other helpers while in shell mode
|
||||
setShowSlashCommands(false);
|
||||
setShowFileSearch(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Update slash command UI state based on input
|
||||
const updateSlashCommandState = (text: string, cursor: number) => {
|
||||
// Only show slash commands if slash is the very first character
|
||||
|
|
@ -129,6 +225,9 @@ const UserInput: React.FC<UserInputProps> = ({
|
|||
return;
|
||||
}
|
||||
|
||||
// When using slash commands, disable file search
|
||||
setShowFileSearch(false);
|
||||
|
||||
const trimmedText = text.trimStart();
|
||||
const beforeCursor = trimmedText.slice(
|
||||
0,
|
||||
|
|
@ -141,13 +240,8 @@ const UserInput: React.FC<UserInputProps> = ({
|
|||
return;
|
||||
}
|
||||
|
||||
const afterSlash = beforeCursor.slice(1);
|
||||
|
||||
// Check if we have whitespace in the command
|
||||
if (afterSlash.includes(" ") || afterSlash.includes("\n")) {
|
||||
setShowSlashCommands(false);
|
||||
return;
|
||||
}
|
||||
// Get the complete slash command, not just the part before cursor
|
||||
const afterSlash = trimmedText.slice(1).split(/[\s\n]/)[0];
|
||||
|
||||
// We're in a slash command context - check if it's a complete command
|
||||
const allCommands = getSlashCommands();
|
||||
|
|
@ -191,6 +285,13 @@ const UserInput: React.FC<UserInputProps> = ({
|
|||
return;
|
||||
}
|
||||
|
||||
// Disable file search if we're in shell mode or slash command mode
|
||||
const trimmed = text.trimStart();
|
||||
if (trimmed.startsWith("!") || trimmed.startsWith("/")) {
|
||||
setShowFileSearch(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if we're in a file search context
|
||||
const beforeCursor = text.slice(0, cursor);
|
||||
const lastAtIndex = beforeCursor.lastIndexOf("@");
|
||||
|
|
@ -229,6 +330,7 @@ const UserInput: React.FC<UserInputProps> = ({
|
|||
setFileSearchFilter(afterAt);
|
||||
setSelectedFileIndex(0);
|
||||
setShowSlashCommands(false);
|
||||
setShowBashMode(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
|
@ -273,6 +375,7 @@ const UserInput: React.FC<UserInputProps> = ({
|
|||
setInputText(newText);
|
||||
setCursorPosition(newCursorPos);
|
||||
setShowSlashCommands(false);
|
||||
setShowBashMode(false);
|
||||
}
|
||||
};
|
||||
|
||||
|
|
@ -432,6 +535,7 @@ const UserInput: React.FC<UserInputProps> = ({
|
|||
setInputText("");
|
||||
setCursorPosition(0);
|
||||
setShowSlashCommands(false);
|
||||
setShowBashMode(false);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
|
@ -457,6 +561,15 @@ const UserInput: React.FC<UserInputProps> = ({
|
|||
const handleEscapeKey = (key: any): boolean => {
|
||||
if (!key.escape) return false;
|
||||
|
||||
// If only "!" is present, clear shell mode
|
||||
if (inputMode && showBashMode && inputText.trim() === "!") {
|
||||
textBuffer.clear();
|
||||
setInputText("");
|
||||
setCursorPosition(0);
|
||||
setShowBashMode(false);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Handle escape key to interrupt streaming
|
||||
if (isWaitingForResponse && onInterrupt) {
|
||||
onInterrupt();
|
||||
|
|
@ -478,16 +591,6 @@ const UserInput: React.FC<UserInputProps> = ({
|
|||
return false;
|
||||
};
|
||||
|
||||
// Clear input function
|
||||
const clearInput = () => {
|
||||
textBuffer.clear();
|
||||
setInputText("");
|
||||
setCursorPosition(0);
|
||||
setShowSlashCommands(false);
|
||||
setShowFileSearch(false);
|
||||
inputHistory.resetNavigation();
|
||||
};
|
||||
|
||||
// Handle text buffer updates for async operations like image pasting
|
||||
const handleTextBufferUpdate = () => {
|
||||
const newText = textBuffer.text;
|
||||
|
|
@ -496,6 +599,7 @@ const UserInput: React.FC<UserInputProps> = ({
|
|||
setCursorPosition(newCursor);
|
||||
updateSlashCommandState(newText, newCursor);
|
||||
updateFileSearchState(newText, newCursor);
|
||||
updateBashModeState(newText);
|
||||
inputHistory.resetNavigation();
|
||||
};
|
||||
|
||||
|
|
@ -592,14 +696,16 @@ const UserInput: React.FC<UserInputProps> = ({
|
|||
setCursorPosition,
|
||||
updateSlashCommandState,
|
||||
updateFileSearchState,
|
||||
updateBashModeState,
|
||||
inputHistory,
|
||||
});
|
||||
});
|
||||
|
||||
const renderInputText = () => {
|
||||
const placeholderText = isRemoteMode
|
||||
? "Ask anything, / for slash commands"
|
||||
: placeholder || "Ask anything, @ for context, / for slash commands";
|
||||
? "Ask anything, / for slash commands, ! for shell mode"
|
||||
: placeholder ||
|
||||
"Ask anything, @ for context, / for slash commands, ! for shell mode";
|
||||
if (inputText.length === 0) {
|
||||
return (
|
||||
<>
|
||||
|
|
@ -682,50 +788,44 @@ const UserInput: React.FC<UserInputProps> = ({
|
|||
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
{/* Interruption message - shown just above the input box */}
|
||||
{wasInterrupted && (
|
||||
<Box paddingX={1} marginBottom={0}>
|
||||
<Text color="yellow">
|
||||
⚠ Interrupted by user - Press enter to resume
|
||||
</Text>
|
||||
</Box>
|
||||
)}
|
||||
<InterruptedBanner wasInterrupted={!!wasInterrupted} />
|
||||
|
||||
{/* Input box */}
|
||||
<Box
|
||||
borderStyle="round"
|
||||
borderTop={true}
|
||||
paddingX={1}
|
||||
borderColor={isRemoteMode ? "cyan" : "gray"}
|
||||
borderColor={showBashMode ? "yellow" : isRemoteMode ? "cyan" : "gray"}
|
||||
>
|
||||
<Text color={isRemoteMode ? "cyan" : "blue"} bold>
|
||||
{isRemoteMode ? "◉" : "●"}{" "}
|
||||
<Text
|
||||
color={showBashMode ? "yellow" : isRemoteMode ? "cyan" : "blue"}
|
||||
bold
|
||||
>
|
||||
{showBashMode ? "$" : isRemoteMode ? "◉" : "●"}
|
||||
</Text>
|
||||
{renderInputText()}
|
||||
</Box>
|
||||
|
||||
{/* Slash command UI - show in remote mode OR when assistant is available */}
|
||||
{showSlashCommands &&
|
||||
inputMode &&
|
||||
!hideNormalUI &&
|
||||
(isRemoteMode || assistant) && (
|
||||
<SlashCommandUI
|
||||
assistant={assistant}
|
||||
filter={slashCommandFilter}
|
||||
selectedIndex={selectedCommandIndex}
|
||||
isRemoteMode={isRemoteMode}
|
||||
/>
|
||||
)}
|
||||
<SlashCommandsMaybe
|
||||
show={showSlashCommands}
|
||||
inputMode={inputMode}
|
||||
hideNormalUI={!!hideNormalUI}
|
||||
isRemoteMode={!!isRemoteMode}
|
||||
assistant={assistant}
|
||||
filter={slashCommandFilter}
|
||||
selectedIndex={selectedCommandIndex}
|
||||
/>
|
||||
|
||||
{/* File search UI - only show in local mode */}
|
||||
{showFileSearch && inputMode && !hideNormalUI && !isRemoteMode && (
|
||||
<FileSearchUI
|
||||
filter={fileSearchFilter}
|
||||
selectedIndex={selectedFileIndex}
|
||||
onSelect={selectFile}
|
||||
onFilesUpdated={setCurrentFiles}
|
||||
/>
|
||||
)}
|
||||
<FileSearchMaybe
|
||||
show={showFileSearch}
|
||||
inputMode={inputMode}
|
||||
hideNormalUI={!!hideNormalUI}
|
||||
isRemoteMode={!!isRemoteMode}
|
||||
filter={fileSearchFilter}
|
||||
selectedIndex={selectedFileIndex}
|
||||
onSelect={selectFile}
|
||||
onFilesUpdated={setCurrentFiles}
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
|
|
|||
|
|
@ -0,0 +1,65 @@
|
|||
import { render } from "ink-testing-library";
|
||||
import React from "react";
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
|
||||
|
||||
import { BottomStatusBar } from "../components/BottomStatusBar.js";
|
||||
|
||||
// Mock the index module functions
|
||||
vi.mock("../../index.js", () => ({
|
||||
shouldShowExitMessage: vi.fn(() => false),
|
||||
setExitMessageCallback: vi.fn(),
|
||||
}));
|
||||
|
||||
describe("BottomStatusBar Ctrl+C message", () => {
|
||||
const defaultProps = {
|
||||
currentMode: "normal" as const,
|
||||
repoURLText: "github.com/user/repo",
|
||||
isRemoteMode: false,
|
||||
services: { model: { model: null } },
|
||||
navState: { currentScreen: "chat" },
|
||||
navigateTo: vi.fn(),
|
||||
closeCurrentScreen: vi.fn(),
|
||||
contextPercentage: undefined,
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
// Reset mocks to default state
|
||||
const indexModule = (await vi.importMock("../../index.js")) as any;
|
||||
indexModule.shouldShowExitMessage.mockReturnValue(false);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("shows repo URL when not in exit message mode", async () => {
|
||||
const indexModule = (await vi.importMock("../../index.js")) as any;
|
||||
indexModule.shouldShowExitMessage.mockReturnValue(false);
|
||||
|
||||
const { lastFrame } = render(<BottomStatusBar {...defaultProps} />);
|
||||
|
||||
expect(lastFrame()).toContain("github.com/user/repo");
|
||||
expect(lastFrame()).not.toContain("ctrl+c to exit");
|
||||
});
|
||||
|
||||
it("shows exit message when shouldShowExitMessage returns true", async () => {
|
||||
const indexModule = (await vi.importMock("../../index.js")) as any;
|
||||
indexModule.shouldShowExitMessage.mockReturnValue(true);
|
||||
|
||||
const { lastFrame } = render(<BottomStatusBar {...defaultProps} />);
|
||||
|
||||
expect(lastFrame()).toContain("ctrl+c to exit");
|
||||
expect(lastFrame()).not.toContain("github.com/user/repo");
|
||||
});
|
||||
|
||||
it("registers exit message callback on mount", async () => {
|
||||
const indexModule = (await vi.importMock("../../index.js")) as any;
|
||||
|
||||
render(<BottomStatusBar {...defaultProps} />);
|
||||
|
||||
expect(indexModule.setExitMessageCallback).toHaveBeenCalledWith(
|
||||
expect.any(Function),
|
||||
);
|
||||
});
|
||||
});
|
||||
115
extensions/cli/src/ui/__tests__/CtrlC.test.tsx
Normal file
115
extensions/cli/src/ui/__tests__/CtrlC.test.tsx
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
import { render } from "ink-testing-library";
|
||||
import React from "react";
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
|
||||
|
||||
import { ConfigSelector } from "../ConfigSelector.js";
|
||||
import { Selector } from "../Selector.js";
|
||||
|
||||
describe("Ctrl+C behavior", () => {
|
||||
let mockOnCancel: ReturnType<typeof vi.fn>;
|
||||
let mockOnSelect: ReturnType<typeof vi.fn>;
|
||||
let mockProcess: any;
|
||||
|
||||
beforeEach(() => {
|
||||
mockOnCancel = vi.fn();
|
||||
mockOnSelect = vi.fn();
|
||||
|
||||
// Mock process.exit for testing
|
||||
mockProcess = {
|
||||
exit: vi.fn(),
|
||||
kill: vi.fn(),
|
||||
};
|
||||
vi.stubGlobal("process", mockProcess);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe("Selector component", () => {
|
||||
it("calls onCancel when Ctrl+C is pressed", () => {
|
||||
const options = [
|
||||
{ id: "1", name: "Option 1" },
|
||||
{ id: "2", name: "Option 2" },
|
||||
];
|
||||
|
||||
const { stdin } = render(
|
||||
<Selector
|
||||
title="Test"
|
||||
options={options}
|
||||
selectedIndex={0}
|
||||
loading={false}
|
||||
error={null}
|
||||
onSelect={mockOnSelect}
|
||||
onCancel={mockOnCancel}
|
||||
onNavigate={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
// Simulate Ctrl+C
|
||||
stdin.write("\u0003");
|
||||
|
||||
expect(mockOnCancel).toHaveBeenCalledTimes(1);
|
||||
expect(mockOnSelect).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("calls onCancel when Ctrl+C is pressed during loading", () => {
|
||||
const options: any[] = [];
|
||||
|
||||
const { stdin } = render(
|
||||
<Selector
|
||||
title="Loading Test"
|
||||
options={options}
|
||||
selectedIndex={0}
|
||||
loading={true}
|
||||
error={null}
|
||||
loadingMessage="Loading..."
|
||||
onSelect={mockOnSelect}
|
||||
onCancel={mockOnCancel}
|
||||
onNavigate={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
// Simulate Ctrl+C during loading
|
||||
stdin.write("\u0003");
|
||||
|
||||
expect(mockOnCancel).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("calls onCancel when Ctrl+C is pressed during error state", () => {
|
||||
const options: any[] = [];
|
||||
|
||||
const { stdin } = render(
|
||||
<Selector
|
||||
title="Error Test"
|
||||
options={options}
|
||||
selectedIndex={0}
|
||||
loading={false}
|
||||
error="Something went wrong"
|
||||
onSelect={mockOnSelect}
|
||||
onCancel={mockOnCancel}
|
||||
onNavigate={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
// Simulate Ctrl+C during error
|
||||
stdin.write("\u0003");
|
||||
|
||||
expect(mockOnCancel).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("ConfigSelector component", () => {
|
||||
it("calls onCancel when Ctrl+C is pressed", () => {
|
||||
const { stdin } = render(
|
||||
<ConfigSelector onSelect={mockOnSelect} onCancel={mockOnCancel} />,
|
||||
);
|
||||
|
||||
// Simulate Ctrl+C
|
||||
stdin.write("\u0003");
|
||||
|
||||
expect(mockOnCancel).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
61
extensions/cli/src/ui/__tests__/CtrlCInputClearing.test.tsx
Normal file
61
extensions/cli/src/ui/__tests__/CtrlCInputClearing.test.tsx
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
import { render } from "ink-testing-library";
|
||||
import React from "react";
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
|
||||
|
||||
import { UserInput } from "../UserInput.js";
|
||||
|
||||
describe("Ctrl+C input clearing", () => {
|
||||
let mockOnSubmit: ReturnType<typeof vi.fn>;
|
||||
let mockProcessKill: any;
|
||||
|
||||
beforeEach(() => {
|
||||
mockOnSubmit = vi.fn();
|
||||
|
||||
// Mock process.kill using vi.spyOn
|
||||
mockProcessKill = vi.spyOn(process, "kill").mockImplementation(() => {
|
||||
return true;
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("sends SIGINT when Ctrl+C is pressed (input clearing tested implicitly)", () => {
|
||||
const { stdin } = render(
|
||||
<UserInput
|
||||
onSubmit={mockOnSubmit}
|
||||
inputMode={true}
|
||||
disabled={false}
|
||||
isWaitingForResponse={false}
|
||||
/>,
|
||||
);
|
||||
|
||||
// Type some text first
|
||||
stdin.write("hello world");
|
||||
|
||||
// Simulate Ctrl+C using raw character code (like other tests in codebase)
|
||||
stdin.write("\u0003");
|
||||
|
||||
// Should send SIGINT to process (which handles the two-stage exit)
|
||||
expect(mockProcessKill).toHaveBeenCalledWith(process.pid, "SIGINT");
|
||||
});
|
||||
|
||||
it("sends SIGINT to main process for two-stage exit handling", () => {
|
||||
const { stdin } = render(
|
||||
<UserInput
|
||||
onSubmit={mockOnSubmit}
|
||||
inputMode={true}
|
||||
disabled={false}
|
||||
isWaitingForResponse={false}
|
||||
/>,
|
||||
);
|
||||
|
||||
// Simulate Ctrl+C using raw character code (like other tests in codebase)
|
||||
stdin.write("\u0003");
|
||||
|
||||
// Should delegate to main process SIGINT handler
|
||||
expect(mockProcessKill).toHaveBeenCalledWith(process.pid, "SIGINT");
|
||||
});
|
||||
});
|
||||
|
|
@ -37,7 +37,7 @@ describe("FreeTrialTransitionUI - Rendering and Props Tests", () => {
|
|||
expect(frame).toContain("1. 💳 Sign up for models add-on");
|
||||
expect(frame).toContain("2. 🔑 Enter your Anthropic API key");
|
||||
expect(frame).toContain("3. ⚙️ Switch to a different configuration");
|
||||
expect(frame).toContain("Use ↑↓ arrows or 1/2/3 to select");
|
||||
expect(frame).toContain("↑/↓ to navigate or 1/2/3 to select");
|
||||
});
|
||||
|
||||
it("highlights first option by default", () => {
|
||||
|
|
@ -46,10 +46,10 @@ describe("FreeTrialTransitionUI - Rendering and Props Tests", () => {
|
|||
);
|
||||
|
||||
const frame = lastFrame();
|
||||
expect(frame).toContain("▶ 1. 💳 Sign up for models add-on");
|
||||
expect(frame).not.toContain("▶ 2. 🔑 Enter your Anthropic API key");
|
||||
expect(frame).toContain("➤ 1. 💳 Sign up for models add-on");
|
||||
expect(frame).not.toContain("➤ 2. 🔑 Enter your Anthropic API key");
|
||||
expect(frame).not.toContain(
|
||||
"▶ 3. ⚙️ Switch to a different configuration",
|
||||
"➤ 3. ⚙️ Switch to a different configuration",
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -85,7 +85,7 @@ describe("FreeTrialTransitionUI - Rendering and Props Tests", () => {
|
|||
const frame = lastFrame();
|
||||
expect(frame).toContain("Choose how you'd like to continue:");
|
||||
expect(frame).toContain(
|
||||
"Use ↑↓ arrows or 1/2/3 to select, Enter to confirm",
|
||||
"↑/↓ to navigate or 1/2/3 to select, Enter to confirm",
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -155,9 +155,9 @@ describe("FreeTrialTransitionUI - Rendering and Props Tests", () => {
|
|||
line.includes("Switch to a different configuration"),
|
||||
);
|
||||
|
||||
expect(modelsLine).toContain("▶");
|
||||
expect(apiKeyLine).not.toContain("▶");
|
||||
expect(configLine).not.toContain("▶");
|
||||
expect(modelsLine).toContain("➤");
|
||||
expect(apiKeyLine).not.toContain("➤");
|
||||
expect(configLine).not.toContain("➤");
|
||||
});
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { Box, Text } from "ink";
|
||||
import React from "react";
|
||||
import React, { useEffect, useState } from "react";
|
||||
|
||||
import { setExitMessageCallback, shouldShowExitMessage } from "../../index.js";
|
||||
import type { PermissionMode } from "../../permissions/types.js";
|
||||
import type { NavigationScreen } from "../context/NavigationContext.js";
|
||||
import { FreeTrialStatus } from "../FreeTrialStatus.js";
|
||||
|
|
@ -31,51 +32,66 @@ export const BottomStatusBar: React.FC<BottomStatusBarProps> = ({
|
|||
closeCurrentScreen,
|
||||
contextPercentage,
|
||||
hasImageInClipboard,
|
||||
}) => (
|
||||
<Box flexDirection="row" justifyContent="space-between" alignItems="center">
|
||||
<Box marginLeft={2} flexDirection="row" alignItems="center">
|
||||
{currentMode === "normal" && (
|
||||
<React.Fragment>
|
||||
{hasImageInClipboard ? (
|
||||
<Text key="image-paste-hint" color="cyan" wrap="truncate-start">
|
||||
Press Ctrl+V to paste image
|
||||
}) => {
|
||||
const [_refreshTrigger, setRefreshTrigger] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
setExitMessageCallback(() => {
|
||||
setRefreshTrigger((prev) => prev + 1);
|
||||
});
|
||||
}, []);
|
||||
|
||||
const showingExitMessage = shouldShowExitMessage();
|
||||
|
||||
return (
|
||||
<Box flexDirection="row" justifyContent="space-between" alignItems="center">
|
||||
<Box marginLeft={2} flexDirection="row" alignItems="center">
|
||||
{currentMode === "normal" && (
|
||||
<React.Fragment>
|
||||
{hasImageInClipboard ? (
|
||||
<Text key="image-paste-hint" color="cyan" wrap="truncate-start">
|
||||
Press Ctrl+V to paste image
|
||||
</Text>
|
||||
) : (
|
||||
<Text key="repo-url" color="dim" wrap="truncate-start">
|
||||
{showingExitMessage ? "ctrl+c to exit" : repoURLText}
|
||||
</Text>
|
||||
)}
|
||||
<Text key="repo-separator"> </Text>
|
||||
</React.Fragment>
|
||||
)}
|
||||
<ModeIndicator />
|
||||
{contextPercentage !== undefined && contextPercentage > 75 && (
|
||||
<React.Fragment>
|
||||
<Text key="context-separator" color="dim">
|
||||
{" "}
|
||||
•{" "}
|
||||
</Text>
|
||||
) : (
|
||||
<Text key="repo-url" color="dim" wrap="truncate-start">
|
||||
{repoURLText}
|
||||
</Text>
|
||||
)}
|
||||
<Text key="repo-separator"> </Text>
|
||||
</React.Fragment>
|
||||
)}
|
||||
<ModeIndicator />
|
||||
{contextPercentage !== undefined && contextPercentage > 75 && (
|
||||
<React.Fragment>
|
||||
<Text key="context-separator" color="dim">
|
||||
{" "}
|
||||
•{" "}
|
||||
</Text>
|
||||
<ContextPercentageDisplay percentage={contextPercentage} />
|
||||
</React.Fragment>
|
||||
)}
|
||||
<ContextPercentageDisplay percentage={contextPercentage} />
|
||||
</React.Fragment>
|
||||
)}
|
||||
</Box>
|
||||
<Box>
|
||||
{!isRemoteMode && services.model?.model && (
|
||||
<FreeTrialStatus
|
||||
apiClient={services.apiClient?.apiClient || undefined}
|
||||
model={services.model.model}
|
||||
onTransitionStateChange={(shouldShow) => {
|
||||
if (shouldShow && navState.currentScreen === "chat") {
|
||||
navigateTo("free-trial");
|
||||
} else if (
|
||||
!shouldShow &&
|
||||
navState.currentScreen === "free-trial"
|
||||
) {
|
||||
closeCurrentScreen();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
<Box marginRight={2} marginLeft={2}>
|
||||
<UpdateNotification isRemoteMode={isRemoteMode} />
|
||||
</Box>
|
||||
</Box>
|
||||
<Box>
|
||||
{!isRemoteMode && services.model?.model && (
|
||||
<FreeTrialStatus
|
||||
apiClient={services.apiClient?.apiClient || undefined}
|
||||
model={services.model.model}
|
||||
onTransitionStateChange={(shouldShow) => {
|
||||
if (shouldShow && navState.currentScreen === "chat") {
|
||||
navigateTo("free-trial");
|
||||
} else if (!shouldShow && navState.currentScreen === "free-trial") {
|
||||
closeCurrentScreen();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
<Box marginRight={2} marginLeft={2}>
|
||||
<UpdateNotification isRemoteMode={isRemoteMode} />
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
);
|
||||
};
|
||||
|
|
|
|||
|
|
@ -140,6 +140,7 @@ export const ScreenContent: React.FC<ScreenContentProps> = ({
|
|||
toolArgs={activePermissionRequest.toolArgs}
|
||||
requestId={activePermissionRequest.requestId}
|
||||
toolCallPreview={activePermissionRequest.toolCallPreview}
|
||||
hasDynamicEvaluation={activePermissionRequest.hasDynamicEvaluation}
|
||||
onResponse={handleToolPermissionResponse}
|
||||
/>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import React, { useState } from "react";
|
|||
import { ToolCallTitle } from "src/tools/ToolCallTitle.js";
|
||||
|
||||
import { ToolCallPreview } from "../../tools/types.js";
|
||||
import { defaultBoxStyles } from "../styles.js";
|
||||
|
||||
import { ToolPreview } from "./ToolPreview.js";
|
||||
|
||||
|
|
@ -21,6 +22,7 @@ interface ToolPermissionSelectorProps {
|
|||
toolArgs: any;
|
||||
requestId: string;
|
||||
toolCallPreview?: ToolCallPreview[];
|
||||
hasDynamicEvaluation?: boolean;
|
||||
onResponse: (
|
||||
requestId: string,
|
||||
approved: boolean,
|
||||
|
|
@ -29,36 +31,40 @@ interface ToolPermissionSelectorProps {
|
|||
) => void;
|
||||
}
|
||||
|
||||
const PERMISSION_OPTIONS: PermissionOption[] = [
|
||||
{ id: "approve", name: "Continue", color: "green", approved: true },
|
||||
{
|
||||
id: "approve_policy",
|
||||
name: "Continue + don't ask again",
|
||||
color: "cyan",
|
||||
approved: true,
|
||||
createPolicy: true,
|
||||
},
|
||||
{
|
||||
id: "deny_stop",
|
||||
name: "No, and tell Continue what to do differently",
|
||||
color: "yellow",
|
||||
approved: false,
|
||||
stopStream: true,
|
||||
},
|
||||
];
|
||||
const getPermissionOptions = (): PermissionOption[] => {
|
||||
return [
|
||||
{ id: "approve", name: "Continue", color: "green", approved: true },
|
||||
{
|
||||
id: "approve_policy",
|
||||
name: "Continue + don't ask again",
|
||||
color: "cyan",
|
||||
approved: true,
|
||||
createPolicy: true,
|
||||
},
|
||||
{
|
||||
id: "deny_stop",
|
||||
name: "No, and tell Continue what to do differently",
|
||||
color: "yellow",
|
||||
approved: false,
|
||||
stopStream: true,
|
||||
},
|
||||
];
|
||||
};
|
||||
|
||||
export const ToolPermissionSelector: React.FC<ToolPermissionSelectorProps> = ({
|
||||
toolName,
|
||||
toolArgs,
|
||||
requestId,
|
||||
toolCallPreview,
|
||||
hasDynamicEvaluation = false,
|
||||
onResponse,
|
||||
}) => {
|
||||
const permissionOptions = getPermissionOptions();
|
||||
const [selectedIndex, setSelectedIndex] = useState(0);
|
||||
|
||||
useInput((input, key) => {
|
||||
if (key.return) {
|
||||
const selectedOption = PERMISSION_OPTIONS[selectedIndex];
|
||||
const selectedOption = permissionOptions[selectedIndex];
|
||||
onResponse(
|
||||
requestId,
|
||||
selectedOption.approved,
|
||||
|
|
@ -80,8 +86,8 @@ export const ToolPermissionSelector: React.FC<ToolPermissionSelectorProps> = ({
|
|||
return;
|
||||
}
|
||||
|
||||
// Escape to reject with stop stream
|
||||
if (key.escape) {
|
||||
// Escape or Ctrl+C to reject with stop stream
|
||||
if (key.escape || (key.ctrl && input === "c")) {
|
||||
onResponse(requestId, false, false, true);
|
||||
return;
|
||||
}
|
||||
|
|
@ -90,7 +96,7 @@ export const ToolPermissionSelector: React.FC<ToolPermissionSelectorProps> = ({
|
|||
setSelectedIndex(Math.max(0, selectedIndex - 1));
|
||||
} else if (key.downArrow) {
|
||||
setSelectedIndex(
|
||||
Math.min(PERMISSION_OPTIONS.length - 1, selectedIndex + 1),
|
||||
Math.min(permissionOptions.length - 1, selectedIndex + 1),
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -103,12 +109,7 @@ export const ToolPermissionSelector: React.FC<ToolPermissionSelectorProps> = ({
|
|||
});
|
||||
|
||||
return (
|
||||
<Box
|
||||
flexDirection="column"
|
||||
padding={1}
|
||||
borderStyle="round"
|
||||
borderColor="magenta"
|
||||
>
|
||||
<Box {...defaultBoxStyles("magenta")}>
|
||||
<Text color="magenta" bold>
|
||||
<ToolCallTitle toolName={toolName} args={toolArgs} />
|
||||
</Text>
|
||||
|
|
@ -124,7 +125,15 @@ export const ToolPermissionSelector: React.FC<ToolPermissionSelectorProps> = ({
|
|||
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<Text color="dim">Would you like to continue?</Text>
|
||||
{PERMISSION_OPTIONS.map((option, index) => {
|
||||
{hasDynamicEvaluation && (
|
||||
<Box marginTop={1}>
|
||||
<Text color="yellow" dimColor>
|
||||
Note: Dangerous commands will be blocked regardless of your
|
||||
preference.
|
||||
</Text>
|
||||
</Box>
|
||||
)}
|
||||
{permissionOptions.map((option, index) => {
|
||||
const isSelected = index === selectedIndex;
|
||||
let shortcut = "";
|
||||
if (option.id === "approve") shortcut = "(tab)";
|
||||
|
|
|
|||
148
extensions/cli/src/ui/hooks/useChat.shellMode.test.ts
Normal file
148
extensions/cli/src/ui/hooks/useChat.shellMode.test.ts
Normal file
|
|
@ -0,0 +1,148 @@
|
|||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { runTerminalCommandTool } from "src/tools/runTerminalCommand.js";
|
||||
|
||||
import { services } from "../../services/index.js";
|
||||
|
||||
import { handleBashModeProcessing } from "./useChat.shellMode.js";
|
||||
|
||||
// Mock the runTerminalCommandTool with the correct path for the import in shellMode.ts
|
||||
vi.mock("src/tools/runTerminalCommand.js", () => ({
|
||||
runTerminalCommandTool: {
|
||||
run: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock the services
|
||||
vi.mock("../../services/index.js", () => ({
|
||||
services: {
|
||||
chatHistory: {
|
||||
addAssistantMessage: vi.fn(),
|
||||
updateToolStatus: vi.fn(),
|
||||
addToolResult: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
describe("handleBashModeProcessing", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("should detect bash mode when message starts with !", async () => {
|
||||
const mockRun = vi.mocked(runTerminalCommandTool.run);
|
||||
mockRun.mockResolvedValue(
|
||||
"total 5\ndrwxr-xr-x 2 user user 4096 Jan 1 12:00 .\ndrwxr-xr-x 3 user user 4096 Jan 1 12:00 ..",
|
||||
);
|
||||
|
||||
const result = await handleBashModeProcessing("!ls -la");
|
||||
|
||||
expect(result).toBe(null); // Processed, no further handling needed
|
||||
expect(services.chatHistory.addAssistantMessage).toHaveBeenCalled();
|
||||
expect(services.chatHistory.updateToolStatus).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
"calling",
|
||||
);
|
||||
|
||||
// Use vi.waitFor to wait for async operations in the void expression
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(mockRun).toHaveBeenCalledWith({ command: "ls -la" });
|
||||
},
|
||||
{ timeout: 1000 },
|
||||
);
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(services.chatHistory.addToolResult).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
"total 5\ndrwxr-xr-x 2 user user 4096 Jan 1 12:00 .\ndrwxr-xr-x 3 user user 4096 Jan 1 12:00 ..",
|
||||
"done",
|
||||
);
|
||||
},
|
||||
{ timeout: 1000 },
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle bash command errors", async () => {
|
||||
const mockRun = vi.mocked(runTerminalCommandTool.run);
|
||||
mockRun.mockRejectedValue(new Error("Command not found"));
|
||||
|
||||
const result = await handleBashModeProcessing("!invalidcommand");
|
||||
|
||||
expect(result).toBe(null); // Processed, no further handling needed
|
||||
expect(services.chatHistory.addAssistantMessage).toHaveBeenCalled();
|
||||
expect(services.chatHistory.updateToolStatus).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
"calling",
|
||||
);
|
||||
|
||||
// Use vi.waitFor to wait for async operations in the void expression
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(mockRun).toHaveBeenCalledWith({ command: "invalidcommand" });
|
||||
},
|
||||
{ timeout: 1000 },
|
||||
);
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(services.chatHistory.addToolResult).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
"Bash command failed: Command not found",
|
||||
"errored",
|
||||
);
|
||||
},
|
||||
{ timeout: 1000 },
|
||||
);
|
||||
});
|
||||
|
||||
it("should not trigger bash mode for regular messages", async () => {
|
||||
const mockRun = vi.mocked(runTerminalCommandTool.run);
|
||||
|
||||
const result = await handleBashModeProcessing("Hello! How are you?");
|
||||
|
||||
expect(result).toBe("Hello! How are you?"); // Pass through unchanged
|
||||
expect(mockRun).not.toHaveBeenCalled();
|
||||
expect(services.chatHistory.addAssistantMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should handle empty bash command", async () => {
|
||||
const mockRun = vi.mocked(runTerminalCommandTool.run);
|
||||
|
||||
const result = await handleBashModeProcessing("!");
|
||||
|
||||
expect(result).toBe("!"); // Pass through unchanged for empty command
|
||||
expect(mockRun).not.toHaveBeenCalled();
|
||||
expect(services.chatHistory.addAssistantMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should handle bash command with leading whitespace", async () => {
|
||||
const mockRun = vi.mocked(runTerminalCommandTool.run);
|
||||
mockRun.mockResolvedValue("echo test output");
|
||||
|
||||
const result = await handleBashModeProcessing(" !echo hello");
|
||||
|
||||
expect(result).toBe(null); // Processed, no further handling needed
|
||||
expect(services.chatHistory.addAssistantMessage).toHaveBeenCalled();
|
||||
|
||||
// Use vi.waitFor to wait for async operations in the void expression
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(mockRun).toHaveBeenCalledWith({ command: "echo hello" });
|
||||
},
|
||||
{ timeout: 1000 },
|
||||
);
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(services.chatHistory.addToolResult).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
"echo test output",
|
||||
"done",
|
||||
);
|
||||
},
|
||||
{ timeout: 1000 },
|
||||
);
|
||||
});
|
||||
});
|
||||
51
extensions/cli/src/ui/hooks/useChat.shellMode.ts
Normal file
51
extensions/cli/src/ui/hooks/useChat.shellMode.ts
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
import { runTerminalCommandTool } from "src/tools/runTerminalCommand.js";
|
||||
import { getErrorString } from "src/util/error.js";
|
||||
|
||||
import { services } from "../../services/index.js";
|
||||
|
||||
export const handleBashModeProcessing = async (
|
||||
message: string,
|
||||
): Promise<string | null> => {
|
||||
// Handle shell mode commands (starting with !)
|
||||
if (!message.trimStart().startsWith("!")) {
|
||||
return message;
|
||||
}
|
||||
|
||||
// Extract the command after the !
|
||||
const bashCommand = message.trimStart().slice(1).trim();
|
||||
|
||||
if (!bashCommand) {
|
||||
return message; // No command provided, treat as regular message
|
||||
}
|
||||
|
||||
// Show tool call immediately, then run asynchronously and populate result
|
||||
const toolCallId = `shell-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
||||
const toolCall = {
|
||||
id: toolCallId,
|
||||
type: "function" as const,
|
||||
function: {
|
||||
name: "Bash",
|
||||
arguments: JSON.stringify({ command: bashCommand }),
|
||||
},
|
||||
};
|
||||
|
||||
// Add assistant message with tool call immediately
|
||||
services.chatHistory.addAssistantMessage("", [toolCall]);
|
||||
// Mark as calling for immediate UI feedback
|
||||
services.chatHistory.updateToolStatus(toolCallId, "calling");
|
||||
|
||||
// Execute the bash command asynchronously - don't block UI
|
||||
void runTerminalCommandTool
|
||||
.run({
|
||||
command: bashCommand,
|
||||
})
|
||||
.then((result) => {
|
||||
services.chatHistory.addToolResult(toolCallId, result, "done");
|
||||
})
|
||||
.catch((error) => {
|
||||
const errorMessage = `Bash command failed: ${getErrorString(error)}`;
|
||||
services.chatHistory.addToolResult(toolCallId, errorMessage, "errored");
|
||||
});
|
||||
|
||||
return null; // Processed, no further message handling needed
|
||||
};
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
import type { ChatHistoryItem, ToolCallState, ToolStatus } from "core/index.js";
|
||||
|
||||
import { getAllBuiltinTools } from "src/tools/index.js";
|
||||
import { logger } from "src/util/logger.js";
|
||||
|
||||
import { services } from "../../services/index.js";
|
||||
|
|
@ -201,11 +202,16 @@ export function createStreamCallbacks(
|
|||
requestId: string,
|
||||
toolCallPreview?: any[],
|
||||
) => {
|
||||
// Check if this tool has dynamic evaluation
|
||||
const tool = getAllBuiltinTools().find((t: any) => t.name === toolName);
|
||||
const hasDynamicEvaluation = !!tool?.evaluateToolCallPolicy;
|
||||
|
||||
setActivePermissionRequest({
|
||||
toolName,
|
||||
toolArgs,
|
||||
requestId,
|
||||
toolCallPreview,
|
||||
hasDynamicEvaluation,
|
||||
});
|
||||
},
|
||||
|
||||
|
|
|
|||
|
|
@ -30,6 +30,7 @@ import {
|
|||
handleRemoteMessage,
|
||||
setupRemotePolling,
|
||||
} from "./useChat.remote.helpers.js";
|
||||
import { handleBashModeProcessing } from "./useChat.shellMode.js";
|
||||
import {
|
||||
createStreamCallbacks,
|
||||
executeStreaming,
|
||||
|
|
@ -423,6 +424,13 @@ export function useChat({
|
|||
|
||||
if (handled) return;
|
||||
|
||||
// Handle shell mode commands (before slash commands)
|
||||
const bashProcessedMessage = await handleBashModeProcessing(message);
|
||||
if (bashProcessedMessage === null) {
|
||||
return; // Bash command was handled and no further processing needed
|
||||
}
|
||||
message = bashProcessedMessage;
|
||||
|
||||
// Handle slash commands
|
||||
const processedMessage = await handleSlashCommandProcessing(message);
|
||||
if (processedMessage === null) {
|
||||
|
|
|
|||
|
|
@ -32,9 +32,14 @@ export function handleControlKeys(options: ControlKeysOptions): boolean {
|
|||
onTextBufferUpdate,
|
||||
} = options;
|
||||
|
||||
// Handle Ctrl+C to clear input
|
||||
if (key.ctrl && input === "c" && clearInput) {
|
||||
clearInput();
|
||||
// Handle Ctrl+C with two-stage exit, Ctrl+D immediately exits
|
||||
if (key.ctrl && input === "c") {
|
||||
// Clear input box if clearInput function is provided
|
||||
if (clearInput) {
|
||||
clearInput();
|
||||
}
|
||||
// Let the main process SIGINT handler handle Ctrl+C logic
|
||||
process.kill(process.pid, "SIGINT");
|
||||
return true;
|
||||
}
|
||||
|
||||
|
|
@ -99,6 +104,7 @@ interface TextBufferStateOptions {
|
|||
setCursorPosition: (pos: number) => void;
|
||||
updateSlashCommandState: (text: string, cursor: number) => void;
|
||||
updateFileSearchState: (text: string, cursor: number) => void;
|
||||
updateBashModeState: (text: string) => void;
|
||||
inputHistory: any;
|
||||
}
|
||||
|
||||
|
|
@ -110,6 +116,7 @@ export function updateTextBufferState(options: TextBufferStateOptions) {
|
|||
setCursorPosition,
|
||||
updateSlashCommandState,
|
||||
updateFileSearchState,
|
||||
updateBashModeState,
|
||||
inputHistory,
|
||||
} = options;
|
||||
|
||||
|
|
@ -121,6 +128,7 @@ export function updateTextBufferState(options: TextBufferStateOptions) {
|
|||
setCursorPosition(newCursor);
|
||||
updateSlashCommandState(newText, newCursor);
|
||||
updateFileSearchState(newText, newCursor);
|
||||
updateBashModeState(newText);
|
||||
inputHistory.resetNavigation();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { render } from "ink";
|
||||
import { render, RenderOptions } from "ink";
|
||||
import React from "react";
|
||||
|
||||
import { setTUIUnmount } from "../index.js";
|
||||
import { PermissionMode } from "../permissions/types.js";
|
||||
import { initializeServices } from "../services/index.js";
|
||||
import { ServiceContainerProvider } from "../services/ServiceContainerContext.js";
|
||||
|
|
@ -54,7 +55,9 @@ export async function startTUIChat(
|
|||
// Use static imports since we're always loading TUI when there's piped input
|
||||
|
||||
// Start the TUI immediately - it will handle loading states
|
||||
const renderOptions: any = {};
|
||||
const renderOptions: RenderOptions = {
|
||||
exitOnCtrlC: false, // Disable Ink's default Ctrl+C handling so we can implement two-stage exit
|
||||
};
|
||||
if (customStdin) {
|
||||
renderOptions.stdin = customStdin;
|
||||
}
|
||||
|
|
@ -73,11 +76,8 @@ export async function startTUIChat(
|
|||
renderOptions,
|
||||
);
|
||||
|
||||
// Handle cleanup
|
||||
process.on("SIGINT", () => {
|
||||
unmount();
|
||||
process.exit(0);
|
||||
});
|
||||
// Register unmount function with main process for two-stage Ctrl+C exit
|
||||
setTUIUnmount(unmount);
|
||||
|
||||
return { unmount };
|
||||
}
|
||||
|
|
@ -96,11 +96,8 @@ export async function startRemoteTUIChat(
|
|||
}),
|
||||
);
|
||||
|
||||
// Handle cleanup
|
||||
process.on("SIGINT", () => {
|
||||
unmount();
|
||||
process.exit(0);
|
||||
});
|
||||
// Register unmount function with main process for two-stage Ctrl+C exit
|
||||
setTUIUnmount(unmount);
|
||||
|
||||
return { unmount };
|
||||
}
|
||||
|
|
|
|||
17
extensions/cli/src/ui/styles.ts
Normal file
17
extensions/cli/src/ui/styles.ts
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
import { Box } from "ink";
|
||||
|
||||
export const baseBoxStyles: React.ComponentProps<typeof Box> = {
|
||||
flexDirection: "column",
|
||||
paddingX: 2,
|
||||
paddingY: 1,
|
||||
borderStyle: "round",
|
||||
};
|
||||
|
||||
export const defaultBoxStyles = (
|
||||
borderColor: string,
|
||||
overrides?: Partial<React.ComponentProps<typeof Box>>,
|
||||
): React.ComponentProps<typeof Box> => ({
|
||||
...baseBoxStyles,
|
||||
borderColor,
|
||||
...overrides,
|
||||
});
|
||||
|
|
@ -4,6 +4,7 @@ import com.github.continuedev.continueintellijextension.FimResult
|
|||
import com.github.continuedev.continueintellijextension.Position
|
||||
import com.github.continuedev.continueintellijextension.nextEdit.NextEditJumpManager
|
||||
import com.github.continuedev.continueintellijextension.nextEdit.NextEditService
|
||||
import com.github.continuedev.continueintellijextension.nextEdit.NextEditStatusService
|
||||
import com.github.continuedev.continueintellijextension.nextEdit.NextEditUtils
|
||||
import com.github.continuedev.continueintellijextension.nextEdit.NextEditWindowManager
|
||||
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
|
||||
|
|
@ -41,8 +42,7 @@ class ContinueInlineCompletionProvider : InlineCompletionProvider {
|
|||
lastUuid = uuid()
|
||||
lastProject = project
|
||||
|
||||
// Check if Next Edit is supported
|
||||
val isNextEditSupported = NextEditUtils.isNextEditSupported(project)
|
||||
val isNextEditSupported = project.service<NextEditStatusService>().isNextEditEnabled()
|
||||
|
||||
if (isNextEditSupported) {
|
||||
isUsingNextEdit = true
|
||||
|
|
|
|||
|
|
@ -142,6 +142,7 @@ class MessageTypes {
|
|||
"didChangeSelectedProfile",
|
||||
"didChangeSelectedOrg",
|
||||
"tools/call",
|
||||
"tools/evaluatePolicy",
|
||||
"controlPlane/openUrl",
|
||||
"isItemTooBig",
|
||||
"process/markAsBackgrounded",
|
||||
|
|
|
|||
|
|
@ -199,7 +199,9 @@ class IntelliJIDE(
|
|||
}
|
||||
|
||||
override suspend fun openFile(path: String) =
|
||||
fileUtils.openFile(path)
|
||||
withContext(Dispatchers.EDT) {
|
||||
fileUtils.openFile(path)
|
||||
}
|
||||
|
||||
override suspend fun openUrl(url: String) {
|
||||
withContext(Dispatchers.IO) {
|
||||
|
|
|
|||
|
|
@ -43,10 +43,14 @@ class ContinueProcessHandler(
|
|||
}
|
||||
scope.launch(Dispatchers.IO) {
|
||||
for (message in pendingWrites) {
|
||||
log.debug("Write: $message")
|
||||
writer.write(message)
|
||||
writer.write("\r\n")
|
||||
writer.flush()
|
||||
try {
|
||||
log.debug("Write: $message")
|
||||
writer.write(message)
|
||||
writer.write("\r\n")
|
||||
writer.flush()
|
||||
} catch (e: IOException) {
|
||||
log.warn(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ import com.intellij.openapi.util.TextRange
|
|||
import com.intellij.ui.JBColor
|
||||
import com.intellij.util.application
|
||||
import com.intellij.util.ui.JBUI
|
||||
import com.intellij.util.ui.UIUtil
|
||||
import java.awt.*
|
||||
import javax.swing.JButton
|
||||
import javax.swing.JTextArea
|
||||
|
|
@ -229,7 +230,7 @@ class VerticalDiffBlock(
|
|||
border = JBUI.Borders.empty()
|
||||
lineWrap = false
|
||||
wrapStyleWord = false
|
||||
font = editor.colorsScheme.getFont(EditorFontType.PLAIN)
|
||||
font = UIUtil.getFontWithFallback(editor.colorsScheme.getFont(EditorFontType.PLAIN))
|
||||
}
|
||||
|
||||
private fun getButtonsXYPositions(): Pair<Int, Int> {
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@ class ContinueErrorSubmitter : ErrorReportSubmitter() {
|
|||
consumer: Consumer<in SubmittedReportInfo>
|
||||
): Boolean {
|
||||
try {
|
||||
// todo: IdeaReportingEvent is deprecated; migrate to IdeaLoggingEvent + figure out how to read attachments
|
||||
val event = events.filterIsInstance<IdeaReportingEvent>()
|
||||
.firstOrNull() ?: return false
|
||||
service<ContinueSentryService>().report(
|
||||
|
|
|
|||
|
|
@ -5,22 +5,27 @@ import com.github.continuedev.continueintellijextension.utils.castNestedOrNull
|
|||
import com.intellij.notification.NotificationAction
|
||||
import com.intellij.notification.NotificationGroupManager
|
||||
import com.intellij.notification.NotificationType
|
||||
import com.intellij.openapi.actionSystem.ActionManager
|
||||
import com.intellij.openapi.actionSystem.ActionPlaces
|
||||
import com.intellij.openapi.actionSystem.AnAction
|
||||
import com.intellij.openapi.actionSystem.AnActionEvent
|
||||
import com.intellij.openapi.application.ApplicationManager
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.project.Project
|
||||
import com.intellij.openapi.ui.DialogWrapper
|
||||
|
||||
class AddLicenseKey : AnAction() {
|
||||
|
||||
override fun actionPerformed(e: AnActionEvent) {
|
||||
val dialog = AddLicenseKeyDialog(e.project)
|
||||
performAddLicenseKey(e.project)
|
||||
}
|
||||
|
||||
private fun performAddLicenseKey(project: Project?) {
|
||||
if (project == null)
|
||||
return
|
||||
val dialog = AddLicenseKeyDialog(project)
|
||||
dialog.show()
|
||||
if (dialog.exitCode != DialogWrapper.OK_EXIT_CODE)
|
||||
return
|
||||
val messenger = e.project?.service<ContinuePluginService>()?.coreMessenger
|
||||
val messenger = project.service<ContinuePluginService>().coreMessenger
|
||||
?: return
|
||||
messenger.request("mdm/setLicenseKey", mapOf("licenseKey" to dialog.licenseKey), null) { response ->
|
||||
val isValid = response.castNestedOrNull<Boolean>("content") ?: false
|
||||
|
|
@ -28,7 +33,7 @@ class AddLicenseKey : AnAction() {
|
|||
createSuccessAction()
|
||||
else
|
||||
createErrorAction()
|
||||
notification.notify(e.project)
|
||||
notification.notify(project)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -37,7 +42,7 @@ class AddLicenseKey : AnAction() {
|
|||
"License key is valid. A restart is required for it to take effect.",
|
||||
NotificationType.INFORMATION
|
||||
).addAction(
|
||||
NotificationAction.create("Restart IDE") { event, notification ->
|
||||
NotificationAction.create("Restart IDE") { _, _ ->
|
||||
ApplicationManager.getApplication().restart()
|
||||
}
|
||||
)
|
||||
|
|
@ -49,17 +54,7 @@ class AddLicenseKey : AnAction() {
|
|||
).addAction(
|
||||
NotificationAction.create("Try again") { event, notification ->
|
||||
notification.expire()
|
||||
val action = this@AddLicenseKey
|
||||
action.actionPerformed(
|
||||
AnActionEvent(
|
||||
null,
|
||||
event.dataContext,
|
||||
ActionPlaces.UNKNOWN,
|
||||
action.templatePresentation.clone(),
|
||||
ActionManager.getInstance(),
|
||||
0
|
||||
)
|
||||
)
|
||||
performAddLicenseKey(event.project)
|
||||
}
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -3,9 +3,9 @@ package com.github.continuedev.continueintellijextension.license
|
|||
import com.intellij.openapi.project.Project
|
||||
import com.intellij.openapi.ui.DialogWrapper
|
||||
import com.intellij.openapi.ui.ValidationInfo
|
||||
import com.intellij.ui.dsl.builder.AlignX
|
||||
import com.intellij.ui.dsl.builder.bindText
|
||||
import com.intellij.ui.dsl.builder.panel
|
||||
import com.intellij.ui.dsl.gridLayout.HorizontalAlign
|
||||
import javax.swing.JComponent
|
||||
|
||||
class AddLicenseKeyDialog(project: Project?) : DialogWrapper(project) {
|
||||
|
|
@ -22,7 +22,7 @@ class AddLicenseKeyDialog(project: Project?) : DialogWrapper(project) {
|
|||
panel {
|
||||
row {
|
||||
textField().bindText(::licenseKey)
|
||||
.horizontalAlign(HorizontalAlign.FILL)
|
||||
.align(AlignX.FILL)
|
||||
.focused()
|
||||
.validationOnApply {
|
||||
if (it.text.isBlank())
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
package com.github.continuedev.continueintellijextension.listeners
|
||||
|
||||
import com.github.continuedev.continueintellijextension.nextEdit.NextEditService
|
||||
import com.github.continuedev.continueintellijextension.nextEdit.NextEditStatusService
|
||||
import com.intellij.openapi.components.Service
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.editor.Editor
|
||||
import com.intellij.openapi.editor.LogicalPosition
|
||||
import com.intellij.openapi.editor.event.CaretEvent
|
||||
|
|
@ -100,7 +102,7 @@ class ActiveHandlerManager(private val project: Project) : SelectionListener, Ca
|
|||
|
||||
// SelectionListener implementation
|
||||
override fun selectionChanged(event: SelectionEvent) {
|
||||
if (isHandlingEvent || event.editor.isDisposed) return
|
||||
if (isHandlingEvent || event.editor.isDisposed || !isNextEditEnabled()) return
|
||||
|
||||
coroutineScope.launch {
|
||||
handleCursorMovement(event.editor, event.newRange.startOffset)
|
||||
|
|
@ -109,7 +111,7 @@ class ActiveHandlerManager(private val project: Project) : SelectionListener, Ca
|
|||
|
||||
// CaretListener implementation
|
||||
override fun caretPositionChanged(event: CaretEvent) {
|
||||
if (isHandlingEvent || event.editor.isDisposed) return
|
||||
if (isHandlingEvent || event.editor.isDisposed || !isNextEditEnabled()) return
|
||||
|
||||
coroutineScope.launch {
|
||||
handleCursorMovement(event.editor, event.caret?.offset ?: return@launch)
|
||||
|
|
@ -168,6 +170,9 @@ class ActiveHandlerManager(private val project: Project) : SelectionListener, Ca
|
|||
}
|
||||
}
|
||||
|
||||
private fun isNextEditEnabled() =
|
||||
project.service<NextEditStatusService>().isNextEditEnabled()
|
||||
|
||||
fun dispose() {
|
||||
clearActiveHandler()
|
||||
coroutineScope.cancel()
|
||||
|
|
|
|||
|
|
@ -0,0 +1,115 @@
|
|||
package com.github.continuedev.continueintellijextension.nextEdit
|
||||
|
||||
import com.github.continuedev.continueintellijextension.auth.ContinueAuthService
|
||||
import com.github.continuedev.continueintellijextension.`continue`.ProfileInfoService
|
||||
import com.github.continuedev.continueintellijextension.utils.castNestedOrNull
|
||||
import com.intellij.openapi.components.Service
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.project.Project
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import kotlin.text.endsWith
|
||||
|
||||
/**
|
||||
* This cache-like service is introduced to enable checking the Next Edit status in a non-blocking way (e.g., while
|
||||
* moving the cursor/selection or triggering autocompletion).
|
||||
*
|
||||
* Checking this status is problematic on the EDT because it requires making a request to the binary (settings JSON)
|
||||
* and decrypting the username from the PasswordSafe, which is considered a _slow operation_.
|
||||
*/
|
||||
@Service(Service.Level.PROJECT)
|
||||
class NextEditStatusService(private val project: Project) {
|
||||
|
||||
@Volatile
|
||||
private var isEnabledLastValue: Boolean = false
|
||||
private val updateInProgress = AtomicBoolean(false)
|
||||
private val scope = CoroutineScope(Dispatchers.Default)
|
||||
|
||||
fun isNextEditEnabled(): Boolean {
|
||||
if (updateInProgress.compareAndSet(false, true))
|
||||
scope.launch {
|
||||
try {
|
||||
isEnabledLastValue = isNextEditEnabledAsync(project)
|
||||
} catch (_: Exception) {
|
||||
} finally {
|
||||
updateInProgress.set(false)
|
||||
}
|
||||
}
|
||||
return isEnabledLastValue
|
||||
}
|
||||
|
||||
// The code below is copied from NextEditUtils
|
||||
// -------------------------------------------
|
||||
|
||||
private suspend fun isNextEditEnabledAsync(project: Project): Boolean {
|
||||
return try {
|
||||
// NOTE: Quick filter for non-continue users.
|
||||
// Remove this once we have a FIM - Next Edit toggle UI.
|
||||
val authService = project.service<ContinueAuthService>()
|
||||
val sessionInfo = authService.loadControlPlaneSessionInfo()
|
||||
val userEmail = sessionInfo?.account?.id
|
||||
|
||||
if (userEmail == null || !userEmail.endsWith("@continue.dev")) {
|
||||
return false
|
||||
}
|
||||
|
||||
val profileInfoService = project.service<ProfileInfoService>()
|
||||
val selectedModelByRole = profileInfoService.fetchSelectedModelByRoleOrNull()
|
||||
|
||||
// Use the existing utility function
|
||||
val autocompleteModel = selectedModelByRole?.get("autocomplete").castNestedOrNull<Map<String, Any>>()
|
||||
|
||||
if (autocompleteModel != null) {
|
||||
val modelName = autocompleteModel["model"] as? String ?: ""
|
||||
val title = autocompleteModel["title"] as? String
|
||||
val capabilities = autocompleteModel["capabilities"].castNestedOrNull<Map<String, Any>>()
|
||||
|
||||
isNextEditModel(modelName, title, capabilities)
|
||||
} else {
|
||||
false
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
println("Error checking Next Edit support: ${e.message}")
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
private fun isNextEditModel(
|
||||
model: String,
|
||||
title: String?,
|
||||
capabilities: Map<String, Any>?
|
||||
): Boolean {
|
||||
// Check capabilities first - this takes precedence.
|
||||
val hasNextEditCapability = capabilities?.get("nextEdit") as? Boolean ?: false
|
||||
|
||||
// Check model name and title against known Next Edit models.
|
||||
return hasNextEditCapability || NextEditModelMatcher.isSupported(model, title)
|
||||
}
|
||||
|
||||
sealed class NextEditModelMatcher {
|
||||
abstract fun matches(modelName: String?, title: String?): Boolean
|
||||
|
||||
data object MercuryCoder : NextEditModelMatcher() {
|
||||
override fun matches(modelName: String?, title: String?): Boolean =
|
||||
modelName?.lowercase()?.contains("mercury-coder") == true ||
|
||||
title?.lowercase()?.contains("mercury coder") == true
|
||||
}
|
||||
|
||||
data object Instinct : NextEditModelMatcher() {
|
||||
override fun matches(modelName: String?, title: String?): Boolean =
|
||||
modelName?.lowercase()?.contains("instinct") == true ||
|
||||
title?.lowercase()?.contains("instinct") == true
|
||||
}
|
||||
|
||||
companion object {
|
||||
private val allMatchers = listOf(MercuryCoder, Instinct)
|
||||
|
||||
fun isSupported(modelName: String?, title: String?): Boolean {
|
||||
return allMatchers.any { it.matches(modelName, title) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -7,76 +7,8 @@ import com.github.continuedev.continueintellijextension.utils.castNestedOrNull
|
|||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.project.Project
|
||||
|
||||
sealed class NextEditModelMatcher {
|
||||
abstract fun matches(modelName: String?, title: String?): Boolean
|
||||
|
||||
data object MercuryCoder : NextEditModelMatcher() {
|
||||
override fun matches(modelName: String?, title: String?): Boolean =
|
||||
modelName?.lowercase()?.contains("mercury-coder") == true ||
|
||||
title?.lowercase()?.contains("mercury coder") == true
|
||||
}
|
||||
|
||||
data object Instinct : NextEditModelMatcher() {
|
||||
override fun matches(modelName: String?, title: String?): Boolean =
|
||||
modelName?.lowercase()?.contains("instinct") == true ||
|
||||
title?.lowercase()?.contains("instinct") == true
|
||||
}
|
||||
|
||||
companion object {
|
||||
private val allMatchers = listOf(MercuryCoder, Instinct)
|
||||
|
||||
fun isSupported(modelName: String?, title: String?): Boolean {
|
||||
return allMatchers.any { it.matches(modelName, title) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
object NextEditUtils {
|
||||
suspend fun isNextEditSupported(project: Project): Boolean {
|
||||
return try {
|
||||
// NOTE: Quick filter for non-continue users.
|
||||
// Remove this once we have a FIM - Next Edit toggle UI.
|
||||
val authService = project.service<ContinueAuthService>()
|
||||
val sessionInfo = authService.loadControlPlaneSessionInfo()
|
||||
val userEmail = sessionInfo?.account?.id
|
||||
|
||||
if (userEmail == null || !userEmail.endsWith("@continue.dev")) {
|
||||
return false
|
||||
}
|
||||
|
||||
val profileInfoService = project.service<ProfileInfoService>()
|
||||
val selectedModelByRole = profileInfoService.fetchSelectedModelByRoleOrNull()
|
||||
|
||||
// Use the existing utility function
|
||||
val autocompleteModel = selectedModelByRole?.get("autocomplete").castNestedOrNull<Map<String, Any>>()
|
||||
|
||||
if (autocompleteModel != null) {
|
||||
val modelName = autocompleteModel["model"] as? String ?: ""
|
||||
val title = autocompleteModel["title"] as? String
|
||||
val capabilities = autocompleteModel["capabilities"].castNestedOrNull<Map<String, Any>>()
|
||||
|
||||
isNextEditModel(modelName, title, capabilities)
|
||||
} else {
|
||||
false
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
println("Error checking Next Edit support: ${e.message}")
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
private fun isNextEditModel(
|
||||
model: String,
|
||||
title: String?,
|
||||
capabilities: Map<String, Any>?
|
||||
): Boolean {
|
||||
// Check capabilities first - this takes precedence.
|
||||
val hasNextEditCapability = capabilities?.get("nextEdit") as? Boolean ?: false
|
||||
|
||||
// Check model name and title against known Next Edit models.
|
||||
return hasNextEditCapability || NextEditModelMatcher.isSupported(model, title)
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the diff is indeed a FIM (Fill-In-Middle).
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ import com.github.continuedev.continueintellijextension.listeners.ActiveHandlerM
|
|||
import com.github.continuedev.continueintellijextension.listeners.DocumentChangeTracker
|
||||
import com.github.continuedev.continueintellijextension.toolWindow.ContinuePluginToolWindowFactory
|
||||
import com.github.continuedev.continueintellijextension.utils.uuid
|
||||
import com.intellij.openapi.Disposable
|
||||
import com.intellij.openapi.components.Service
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.editor.EditorFactory
|
||||
|
|
@ -20,7 +21,7 @@ import kotlinx.coroutines.cancel
|
|||
import kotlin.properties.Delegates
|
||||
|
||||
@Service(Service.Level.PROJECT)
|
||||
class ContinuePluginService(private val project: Project) : DumbAware {
|
||||
class ContinuePluginService(private val project: Project) : Disposable, DumbAware {
|
||||
private val coroutineScope = CoroutineScope(Dispatchers.Main)
|
||||
var listener: (() -> Unit)? = null
|
||||
var ideProtocolClient: IdeProtocolClient? by Delegates.observable(null) { _, _, _ ->
|
||||
|
|
@ -57,7 +58,7 @@ class ContinuePluginService(private val project: Project) : DumbAware {
|
|||
}
|
||||
}
|
||||
|
||||
fun dispose() {
|
||||
override fun dispose() {
|
||||
coroutineScope.cancel()
|
||||
coreMessenger?.coroutineScope?.let {
|
||||
it.cancel()
|
||||
|
|
|
|||
|
|
@ -134,7 +134,7 @@ export class GUIActions {
|
|||
public static async toggleToolPolicy(
|
||||
view: WebView,
|
||||
toolName: string,
|
||||
n: number,
|
||||
desiredState: number | string,
|
||||
) {
|
||||
const toolButton = await TestUtils.waitForSuccess(() =>
|
||||
GUISelectors.getToolButton(view),
|
||||
|
|
@ -145,9 +145,41 @@ export class GUIActions {
|
|||
);
|
||||
await TestUtils.waitForTimeout(500);
|
||||
|
||||
// Enabled -> Excluded -> Ask first
|
||||
for (let i = 0; i < n; i++) {
|
||||
await TestUtils.waitForSuccess(() => toolPolicyButton.click());
|
||||
// Map old number format to state names for backward compatibility
|
||||
// 0 = Automatic/Auto, 1 = Excluded/Off, 2 = Ask First/Ask
|
||||
let targetStates: string[];
|
||||
if (typeof desiredState === "number") {
|
||||
const stateMap = [
|
||||
["Automatic", "Auto"], // 0
|
||||
["Excluded", "Off"], // 1
|
||||
["Ask First", "Ask"], // 2
|
||||
];
|
||||
targetStates = stateMap[desiredState] || ["Ask First", "Ask"];
|
||||
} else {
|
||||
targetStates = [desiredState];
|
||||
}
|
||||
|
||||
// Keep clicking until we reach the desired state
|
||||
let maxAttempts = 5; // Safety limit to prevent infinite loops
|
||||
while (maxAttempts > 0) {
|
||||
const currentText = await toolPolicyButton.getText();
|
||||
|
||||
// Check if we've reached any of the target states
|
||||
if (targetStates.some((state) => currentText.includes(state))) {
|
||||
break;
|
||||
}
|
||||
|
||||
// Click to move to next state
|
||||
await toolPolicyButton.click();
|
||||
await TestUtils.waitForTimeout(200); // Small delay for UI update
|
||||
|
||||
maxAttempts--;
|
||||
}
|
||||
|
||||
if (maxAttempts === 0) {
|
||||
throw new Error(
|
||||
`Failed to set tool policy to ${targetStates.join(" or ")} after 5 attempts`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import {
|
|||
InputBox,
|
||||
TextEditor,
|
||||
VSBrowser,
|
||||
Workbench
|
||||
Workbench,
|
||||
} from "vscode-extension-tester";
|
||||
|
||||
import { DEFAULT_TIMEOUT } from "../constants";
|
||||
|
|
@ -86,76 +86,69 @@ export class GlobalActions {
|
|||
|
||||
static async setNextEditEnabled(enabled: boolean) {
|
||||
const workbench = new Workbench();
|
||||
|
||||
await workbench.openCommandPrompt();
|
||||
process.env.CONTINUE_E2E_NON_NEXT_EDIT_TEST = 'true';
|
||||
|
||||
|
||||
await workbench.openCommandPrompt();
|
||||
process.env.CONTINUE_E2E_NON_NEXT_EDIT_TEST = "true";
|
||||
|
||||
// Initial wait and clear
|
||||
await TestUtils.waitForTimeout(1000);
|
||||
await GlobalActions.clearAllNotifications();
|
||||
|
||||
|
||||
const statusBar = await workbench.getStatusBar();
|
||||
|
||||
|
||||
// Robust element finding with text validation
|
||||
const continueItem = await TestUtils.waitForSuccess(
|
||||
async () => {
|
||||
// Clear any new notifications
|
||||
try {
|
||||
await GlobalActions.clearAllNotifications();
|
||||
} catch (e) {
|
||||
// Ignore
|
||||
const continueItem = await TestUtils.waitForSuccess(async () => {
|
||||
// Clear any new notifications
|
||||
try {
|
||||
await GlobalActions.clearAllNotifications();
|
||||
} catch (e) {
|
||||
// Ignore
|
||||
}
|
||||
|
||||
const element = await statusBar.findElement(
|
||||
By.xpath("//*[contains(text(), 'Continue')]"),
|
||||
);
|
||||
|
||||
// Validate we can get text
|
||||
const text = await element.getText();
|
||||
if (!text || text.trim() === "") {
|
||||
// Try alternative methods
|
||||
const textContent = await element.getAttribute("textContent");
|
||||
if (!textContent || textContent.trim() === "") {
|
||||
throw new Error("Text not yet available");
|
||||
}
|
||||
|
||||
const element = await statusBar.findElement(
|
||||
By.xpath("//*[contains(text(), 'Continue')]")
|
||||
);
|
||||
|
||||
// Validate we can get text
|
||||
const text = await element.getText();
|
||||
if (!text || text.trim() === '') {
|
||||
// Try alternative methods
|
||||
const textContent = await element.getAttribute('textContent');
|
||||
if (!textContent || textContent.trim() === '') {
|
||||
throw new Error('Text not yet available');
|
||||
}
|
||||
}
|
||||
|
||||
return element;
|
||||
},
|
||||
DEFAULT_TIMEOUT.MD
|
||||
);
|
||||
}
|
||||
|
||||
return element;
|
||||
}, DEFAULT_TIMEOUT.MD);
|
||||
|
||||
// Get text with retry
|
||||
const text = await TestUtils.waitForSuccess(
|
||||
async () => {
|
||||
const itemText = await continueItem.getText();
|
||||
if (!itemText || itemText.trim() === '') {
|
||||
// Fallback to textContent
|
||||
const textContent = await continueItem.getAttribute('textContent');
|
||||
if (textContent && textContent.trim() !== '') {
|
||||
return textContent;
|
||||
}
|
||||
throw new Error('Text content not yet available');
|
||||
const text = await TestUtils.waitForSuccess(async () => {
|
||||
const itemText = await continueItem.getText();
|
||||
if (!itemText || itemText.trim() === "") {
|
||||
// Fallback to textContent
|
||||
const textContent = await continueItem.getAttribute("textContent");
|
||||
if (textContent && textContent.trim() !== "") {
|
||||
return textContent;
|
||||
}
|
||||
return itemText;
|
||||
},
|
||||
DEFAULT_TIMEOUT.MD
|
||||
);
|
||||
|
||||
throw new Error("Text content not yet available");
|
||||
}
|
||||
return itemText;
|
||||
}, DEFAULT_TIMEOUT.MD);
|
||||
|
||||
console.log("Final text:", text);
|
||||
|
||||
const hasNE = text.includes('(NE)');
|
||||
|
||||
const hasNE = text.includes("(NE)");
|
||||
console.log("hasNE:", hasNE);
|
||||
|
||||
|
||||
if (hasNE !== enabled) {
|
||||
await workbench.executeCommand('Continue: Toggle Next Edit');
|
||||
await workbench.executeCommand("Continue: Toggle Next Edit");
|
||||
// Clear any resulting notifications
|
||||
await TestUtils.waitForTimeout(500);
|
||||
await GlobalActions.clearAllNotifications();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
static async disableNextEdit() {
|
||||
await this.setNextEditEnabled(false);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ import {
|
|||
WebDriver,
|
||||
WebElement,
|
||||
WebView,
|
||||
until
|
||||
until,
|
||||
} from "vscode-extension-tester";
|
||||
|
||||
import { GlobalActions } from "../actions/Global.actions";
|
||||
|
|
|
|||
2
extensions/vscode/package-lock.json
generated
2
extensions/vscode/package-lock.json
generated
|
|
@ -158,6 +158,7 @@
|
|||
"quick-lru": "^7.0.0",
|
||||
"replicate": "^0.26.0",
|
||||
"request": "^2.88.2",
|
||||
"shell-quote": "^1.8.3",
|
||||
"socket.io-client": "^4.7.3",
|
||||
"sqlite": "^5.1.1",
|
||||
"sqlite3": "^5.1.7",
|
||||
|
|
@ -192,6 +193,7 @@
|
|||
"@types/pg": "^8.11.6",
|
||||
"@types/plist": "^3.0.5",
|
||||
"@types/request": "^2.48.12",
|
||||
"@types/shell-quote": "^1.7.5",
|
||||
"@types/tar": "^6.1.13",
|
||||
"@types/uuid": "^9.0.7",
|
||||
"@types/win-ca": "^3.5.4",
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
"name": "continue",
|
||||
"icon": "media/icon.png",
|
||||
"author": "Continue Dev, Inc",
|
||||
"version": "1.3.2",
|
||||
"version": "1.3.3",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/continuedev/continue"
|
||||
|
|
@ -183,7 +183,7 @@
|
|||
{
|
||||
"command": "continue.focusEdit",
|
||||
"category": "Continue",
|
||||
"title": "Edit Highlighted Code",
|
||||
"title": "Add to Edit",
|
||||
"group": "Continue"
|
||||
},
|
||||
{
|
||||
|
|
@ -195,7 +195,7 @@
|
|||
{
|
||||
"command": "continue.focusContinueInputWithoutClear",
|
||||
"category": "Continue",
|
||||
"title": "Add Highlighted Code to Context",
|
||||
"title": "Add to Chat",
|
||||
"group": "Continue"
|
||||
},
|
||||
{
|
||||
|
|
@ -547,31 +547,6 @@
|
|||
"command": "continue.focusEdit",
|
||||
"group": "Continue",
|
||||
"when": "editorHasSelection && !editorReadonly"
|
||||
},
|
||||
{
|
||||
"command": "continue.writeCommentsForCode",
|
||||
"group": "Continue",
|
||||
"when": "editorHasSelection && !editorReadonly"
|
||||
},
|
||||
{
|
||||
"command": "continue.writeDocstringForCode",
|
||||
"group": "Continue",
|
||||
"when": "editorHasSelection && !editorReadonly"
|
||||
},
|
||||
{
|
||||
"command": "continue.fixCode",
|
||||
"group": "Continue",
|
||||
"when": "editorHasSelection && !editorReadonly"
|
||||
},
|
||||
{
|
||||
"command": "continue.optimizeCode",
|
||||
"group": "Continue",
|
||||
"when": "editorHasSelection && !editorReadonly"
|
||||
},
|
||||
{
|
||||
"command": "continue.fixGrammar",
|
||||
"group": "Continue",
|
||||
"when": "editorHasSelection && editorLangId == 'markdown' && !editorReadonly"
|
||||
}
|
||||
],
|
||||
"explorer/context": [
|
||||
|
|
|
|||
|
|
@ -3,7 +3,6 @@ import { Telemetry } from "core/util/posthog";
|
|||
import * as vscode from "vscode";
|
||||
|
||||
import { VsCodeExtension } from "../extension/VsCodeExtension";
|
||||
import registerQuickFixProvider from "../lang-server/codeActions";
|
||||
import { getExtensionVersion, isUnsupportedPlatform } from "../util/util";
|
||||
|
||||
import { GlobalContext } from "core/util/GlobalContext";
|
||||
|
|
@ -41,7 +40,6 @@ export async function activateExtension(context: vscode.ExtensionContext) {
|
|||
getContinueRcPath();
|
||||
|
||||
// Register commands and providers
|
||||
registerQuickFixProvider();
|
||||
setupInlineTips(context);
|
||||
|
||||
const vscodeExtension = new VsCodeExtension(context);
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue