Merge branch 'main' into pe/assistant-unroll-bugfix
This commit is contained in:
commit
c5286fcd80
123 changed files with 6925 additions and 1331 deletions
99
.github/workflows/auto-release.yml
vendored
Normal file
99
.github/workflows/auto-release.yml
vendored
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
name: Create Automatic Release
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: "0 17 * * 1,3,5" # Run at 9am PST (17:00 UTC) on Monday, Wednesday, Friday
|
||||
workflow_dispatch: # Keep manual trigger option
|
||||
|
||||
jobs:
|
||||
create-vscode-release:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write # Needed for creating releases
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0 # Important for getting all tags and commits
|
||||
|
||||
- name: Get latest tag
|
||||
id: get_latest_tag
|
||||
run: |
|
||||
# Get the latest tag ending in -vscode or default to v1.1.0-vscode if none exists
|
||||
latest_tag=$(git tag --sort=-creatordate | grep -E "-vscode$" | head -n 1 || echo "v1.1.0-vscode")
|
||||
echo "Latest tag: $latest_tag"
|
||||
echo "LATEST_TAG=$latest_tag" >> $GITHUB_ENV
|
||||
|
||||
- name: Generate next version
|
||||
id: generate_version
|
||||
run: |
|
||||
# Extract version numbers (handle the -vscode suffix)
|
||||
version=${LATEST_TAG#v} # Remove v prefix
|
||||
version=${version%-vscode} # Remove -vscode suffix
|
||||
IFS='.' read -ra VERSION_PARTS <<< "$version"
|
||||
|
||||
# Increment patch version
|
||||
((VERSION_PARTS[2]++))
|
||||
|
||||
# Create new version string with -vscode suffix
|
||||
new_version="v${VERSION_PARTS[0]}.${VERSION_PARTS[1]}.${VERSION_PARTS[2]}-vscode"
|
||||
echo "New version will be: $new_version"
|
||||
echo "NEW_VERSION=$new_version" >> $GITHUB_ENV
|
||||
|
||||
- name: Create Release
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
# Create a new draft release with auto-generated release notes
|
||||
gh release create "$NEW_VERSION" \
|
||||
--generate-notes \
|
||||
--title "$NEW_VERSION" \
|
||||
--draft \
|
||||
--latest
|
||||
--prerelease
|
||||
|
||||
create-jetbrains-release:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write # Needed for creating releases
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0 # Important for getting all tags and commits
|
||||
|
||||
- name: Get latest tag
|
||||
id: get_latest_tag
|
||||
run: |
|
||||
# Get the latest tag ending in -jetbrains or default to v1.1.0-jetbrains if none exists
|
||||
latest_tag=$(git tag --sort=-creatordate | grep -E "-jetbrains$" | head -n 1 || echo "v1.1.0-jetbrains")
|
||||
echo "Latest tag: $latest_tag"
|
||||
echo "LATEST_TAG=$latest_tag" >> $GITHUB_ENV
|
||||
|
||||
- name: Generate next version
|
||||
id: generate_version
|
||||
run: |
|
||||
# Extract version numbers (handle the -jetbrains suffix)
|
||||
version=${LATEST_TAG#v} # Remove v prefix
|
||||
version=${version%-jetbrains} # Remove -jetbrains suffix
|
||||
IFS='.' read -ra VERSION_PARTS <<< "$version"
|
||||
|
||||
# Increment patch version
|
||||
((VERSION_PARTS[2]++))
|
||||
|
||||
# Create new version string with -jetbrains suffix
|
||||
new_version="v${VERSION_PARTS[0]}.${VERSION_PARTS[1]}.${VERSION_PARTS[2]}-jetbrains"
|
||||
echo "New version will be: $new_version"
|
||||
echo "NEW_VERSION=$new_version" >> $GITHUB_ENV
|
||||
|
||||
- name: Create Release
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
# Create a new draft release with auto-generated release notes
|
||||
gh release create "$NEW_VERSION" \
|
||||
--generate-notes \
|
||||
--title "$NEW_VERSION" \
|
||||
--draft \
|
||||
--latest
|
||||
--prerelease
|
||||
39
.github/workflows/preview.yaml
vendored
39
.github/workflows/preview.yaml
vendored
|
|
@ -1,4 +1,4 @@
|
|||
name: Publish Preview Extension
|
||||
name: Publish Pre-release Extension
|
||||
|
||||
on:
|
||||
release:
|
||||
|
|
@ -207,6 +207,7 @@ jobs:
|
|||
if: github.event_name != 'workflow_dispatch' || github.event.inputs.publish_build == 'true'
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
steps:
|
||||
# 0. Setup git
|
||||
- name: Checkout
|
||||
|
|
@ -242,12 +243,44 @@ jobs:
|
|||
cd extensions/vscode
|
||||
npx ovsx publish --pre-release -p ${{ secrets.VSX_REGISTRY_TOKEN }} --packagePath ../../vsix-artifacts/*.vsix
|
||||
|
||||
# 4. Update the package.json version and push changes
|
||||
# 4. Create PR with version bump
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
|
||||
- name: Create PR branch
|
||||
run: |
|
||||
BRANCH_NAME="chore/bump-vscode-version-$(date +%Y%m%d-%H%M%S)"
|
||||
git checkout -b $BRANCH_NAME
|
||||
echo "BRANCH_NAME=$BRANCH_NAME" >> $GITHUB_ENV
|
||||
|
||||
- name: Bump version in package.json
|
||||
run: |
|
||||
cd extensions/vscode
|
||||
npm version patch --no-git-tag-version
|
||||
VERSION=$(node -p "require('./package.json').version")
|
||||
echo "NEW_VERSION=$VERSION" >> $GITHUB_ENV
|
||||
|
||||
- name: Create Pull Request
|
||||
uses: peter-evans/create-pull-request@v5
|
||||
with:
|
||||
token: ${{ secrets.CI_GITHUB_TOKEN }}
|
||||
commit-message: "chore: bump vscode extension version to ${{ env.NEW_VERSION }}"
|
||||
title: "chore: bump vscode extension version to ${{ env.NEW_VERSION }}"
|
||||
body: |
|
||||
Automated PR to bump the VS Code extension version after successful pre-release publication.
|
||||
|
||||
- Bumped version in extensions/vscode/package.json to ${{ env.NEW_VERSION }}
|
||||
branch: ${{ env.BRANCH_NAME }}
|
||||
base: main
|
||||
delete-branch: true
|
||||
|
||||
# 5. Update version in package.json
|
||||
# - name: Update version in package.json
|
||||
# run: |
|
||||
# cd extensions/vscode
|
||||
# npm version patch
|
||||
|
||||
# - name: Commit changes
|
||||
# run: |
|
||||
# git config --local user.email "action@github.com"
|
||||
|
|
|
|||
46
.github/workflows/release-config-yaml.yml
vendored
Normal file
46
.github/workflows/release-config-yaml.yml
vendored
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
name: Release @continuedev/config-yaml
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- "packages/config-yaml/**"
|
||||
|
||||
jobs:
|
||||
release:
|
||||
name: Release
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Use Node.js from .nvmrc
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm ci
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Run tests
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm test
|
||||
|
||||
- name: Release
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npx semantic-release
|
||||
111
.github/workflows/vscode-version-bump.yml
vendored
Normal file
111
.github/workflows/vscode-version-bump.yml
vendored
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
name: VS Code Extension Version Bump
|
||||
on:
|
||||
schedule:
|
||||
# Runs at 7 AM PST (15:00 UTC) every Friday
|
||||
- cron: "0 15 * * 5"
|
||||
workflow_dispatch:
|
||||
# Allows manual triggering
|
||||
|
||||
jobs:
|
||||
version-bump:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0 # Fetch all history and tags
|
||||
|
||||
- name: Use Node.js from .nvmrc
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
|
||||
- name: Find and process version tags
|
||||
run: |
|
||||
echo "Starting version bump process..."
|
||||
|
||||
# Find last v1.1.x-vscode tag that's at least 6 days old
|
||||
CURRENT_TIMESTAMP=$(date +%s)
|
||||
SIX_DAYS_AGO=$((CURRENT_TIMESTAMP - 6*24*60*60))
|
||||
echo "Current timestamp: $(date -d @${CURRENT_TIMESTAMP})"
|
||||
echo "Six days ago: $(date -d @${SIX_DAYS_AGO})"
|
||||
|
||||
echo "Looking for v1.1.x-vscode tags..."
|
||||
git for-each-ref --sort=-creatordate --format '%(refname:short) %(creatordate:iso)' refs/tags | grep 'v1\.1\.[0-9]\+-vscode' || echo "No matching tags found"
|
||||
|
||||
LAST_1_1_TAG=$(git for-each-ref --sort=-creatordate --format '%(refname:short) %(creatordate:unix)' refs/tags \
|
||||
| grep 'v1\.1\.[0-9]\+-vscode' \
|
||||
| while read tag timestamp; do
|
||||
if [ $timestamp -le $SIX_DAYS_AGO ]; then
|
||||
echo ${tag% *}
|
||||
break
|
||||
fi
|
||||
done)
|
||||
|
||||
echo "Selected v1.1.x tag: $LAST_1_1_TAG"
|
||||
if [ -z "$LAST_1_1_TAG" ]; then
|
||||
echo "::error::No suitable v1.1.x-vscode tag found"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Find last v1.0.y-vscode tag
|
||||
echo "Looking for v1.0.y-vscode tags..."
|
||||
git tag --sort=-v:refname | grep '^v1\.0\.[0-9]\+-vscode' || echo "No matching tags found"
|
||||
|
||||
LAST_1_0_TAG=$(git tag --sort=-v:refname | grep '^v1\.0\.[0-9]\+-vscode' | head -n1)
|
||||
echo "Selected v1.0.y tag: $LAST_1_0_TAG"
|
||||
if [ -z "$LAST_1_0_TAG" ]; then
|
||||
echo "::error::No v1.0.y-vscode tag found"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Extract the y number and increment it
|
||||
Y_NUMBER=$(echo $LAST_1_0_TAG | sed 's/v1\.0\.\([0-9]\+\)-vscode/\1/')
|
||||
NEXT_Y=$((Y_NUMBER + 1))
|
||||
NEW_BRANCH="v1.0.${NEXT_Y}-vscode"
|
||||
NEW_VERSION="1.0.${NEXT_Y}"
|
||||
echo "Current Y number: $Y_NUMBER"
|
||||
echo "Next Y number: $NEXT_Y"
|
||||
echo "New branch name: $NEW_BRANCH"
|
||||
echo "New version: $NEW_VERSION"
|
||||
|
||||
# Create new branch from the v1.1.x tag
|
||||
echo "Creating new branch from $LAST_1_1_TAG..."
|
||||
git checkout $LAST_1_1_TAG
|
||||
git checkout -b $NEW_BRANCH
|
||||
|
||||
# Update the version in package.json
|
||||
echo "Current package.json version:"
|
||||
cat extensions/vscode/package.json | grep version
|
||||
|
||||
echo "Updating version in package.json..."
|
||||
jq ".version = \"$NEW_VERSION\"" extensions/vscode/package.json > temp.json && mv temp.json extensions/vscode/package.json
|
||||
|
||||
echo "New package.json version:"
|
||||
cat extensions/vscode/package.json | grep version
|
||||
|
||||
# Configure git
|
||||
echo "Configuring git..."
|
||||
git config user.name "GitHub Actions Bot"
|
||||
git config user.email "actions@github.com"
|
||||
|
||||
# Commit and push changes
|
||||
echo "Committing changes..."
|
||||
git add extensions/vscode/package.json
|
||||
git commit -m "Bump VS Code extension to ${NEW_VERSION}"
|
||||
|
||||
echo "Pushing branch to origin..."
|
||||
git push origin $NEW_BRANCH
|
||||
|
||||
echo "Version bump process completed successfully!"
|
||||
|
||||
- name: Check for errors
|
||||
if: failure()
|
||||
run: |
|
||||
echo "::error::Failed to process version tags and create new branch"
|
||||
echo "Last few lines of git log:"
|
||||
git log -n 5 --oneline
|
||||
echo "Current git status:"
|
||||
git status
|
||||
echo "Current branches:"
|
||||
git branch -a
|
||||
|
|
@ -44,11 +44,11 @@
|
|||
|
||||

|
||||
|
||||
## Actions
|
||||
## Agent
|
||||
|
||||
[Actions](https://continue.dev/docs/actions/how-to-use-it) are shortcuts for common use cases
|
||||
[Agent](https://continue.dev/docs/agent/how-to-use-it) enables you to make more substantial changes to your codebase
|
||||
|
||||

|
||||

|
||||
|
||||
</div>
|
||||
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import {
|
|||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
} from "../../index.js";
|
||||
import { formatGrepSearchResults } from "../../util/grepSearch.js";
|
||||
import { BaseContextProvider } from "../index.js";
|
||||
|
||||
class SearchContextProvider extends BaseContextProvider {
|
||||
|
|
@ -19,10 +20,11 @@ class SearchContextProvider extends BaseContextProvider {
|
|||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const results = await extras.ide.getSearchResults(query);
|
||||
const formatted = formatGrepSearchResults(results);
|
||||
return [
|
||||
{
|
||||
description: "Search results",
|
||||
content: `Results of searching codebase for "${query}":\n\n${results}`,
|
||||
content: `Results of searching codebase for "${query}":\n\n${formatted}`,
|
||||
name: "Search results",
|
||||
},
|
||||
];
|
||||
|
|
|
|||
4
core/index.d.ts
vendored
4
core/index.d.ts
vendored
|
|
@ -1,6 +1,7 @@
|
|||
import { DataDestination, ModelRole, Rule } from "@continuedev/config-yaml";
|
||||
import Parser from "web-tree-sitter";
|
||||
import { GetGhTokenArgs } from "./protocol/ide";
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
ide?: "vscode";
|
||||
|
|
@ -710,6 +711,8 @@ export interface IDE {
|
|||
|
||||
getSearchResults(query: string): Promise<string>;
|
||||
|
||||
getFileResults(pattern: string): Promise<string[]>;
|
||||
|
||||
subprocess(command: string, cwd?: string): Promise<[string, string]>;
|
||||
|
||||
getProblems(fileUri?: string | undefined): Promise<Problem[]>;
|
||||
|
|
@ -1142,6 +1145,7 @@ export interface ApplyState {
|
|||
numDiffs?: number;
|
||||
filepath?: string;
|
||||
fileContent?: string;
|
||||
toolCallId?: string;
|
||||
}
|
||||
|
||||
export interface RangeInFileWithContents {
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ import OpenAI from "./OpenAI.js";
|
|||
class Docker extends OpenAI implements ModelInstaller {
|
||||
static providerName = "docker";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "http://model-runner.docker.internal/v1/",
|
||||
apiBase: "http://localhost:12434/engines/v1",
|
||||
model: "gemma3-4B-F4", // Default model
|
||||
};
|
||||
|
||||
|
|
@ -41,9 +41,10 @@ class Docker extends OpenAI implements ModelInstaller {
|
|||
"llama3.2-1B-F8": "ai/llama3.2:1B-Q8_0",
|
||||
"qwq-32B-F16": "ai/qwq:32B-F16",
|
||||
"qwq-32B-F4": "ai/qwq:32B-Q4_K_M",
|
||||
"deepseek-r1-distill-llama-70B-F4": "ai/deepseek-r1-distill-llama:70B-Q4_K_M",
|
||||
"deepseek-r1-distill-llama-70B-F4":
|
||||
"ai/deepseek-r1-distill-llama:70B-Q4_K_M",
|
||||
"deepseek-r1-distill-llama-8B-F16": "ai/deepseek-r1-distill-llama:8B-F16",
|
||||
"deepseek-r1-distill-llama-8B-Q4": "ai/deepseek-r1-distill-llama:8B-Q4_K_M"
|
||||
"deepseek-r1-distill-llama-8B-Q4": "ai/deepseek-r1-distill-llama:8B-Q4_K_M",
|
||||
};
|
||||
|
||||
constructor(options: LLMOptions) {
|
||||
|
|
@ -53,38 +54,85 @@ class Docker extends OpenAI implements ModelInstaller {
|
|||
if (this.model && this.modelMap[this.model]) {
|
||||
this.model = this.modelMap[this.model];
|
||||
}
|
||||
|
||||
// Check if Docker Model Runner is active and enable it if needed
|
||||
this.ensureModelRunnerEnabled();
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if Docker Model Runner is running at the expected port
|
||||
* and enables it if not running
|
||||
*/
|
||||
private async ensureModelRunnerEnabled(): Promise<void> {
|
||||
try {
|
||||
// Check if the Model Runner service is running on the expected port
|
||||
const isRunning = await this.isPortBound(12434);
|
||||
|
||||
if (!isRunning) {
|
||||
console.log(
|
||||
"Docker Model Runner not detected. Attempting to enable it...",
|
||||
);
|
||||
await this.executeDockerCommand([
|
||||
"desktop",
|
||||
"enable",
|
||||
"model-runner",
|
||||
"--tcp",
|
||||
"12434",
|
||||
]);
|
||||
console.log("Docker Model Runner has been enabled on port 12434");
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn("Failed to enable Docker Model Runner:", error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a port is currently bound/in use
|
||||
*/
|
||||
private async isPortBound(port: number): Promise<boolean> {
|
||||
try {
|
||||
await this.fetch(`http://localhost:${port}`, {
|
||||
method: "HEAD",
|
||||
signal: AbortSignal.timeout(1000),
|
||||
});
|
||||
return true;
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private async executeDockerCommand(
|
||||
args: string[],
|
||||
signal?: AbortSignal
|
||||
signal?: AbortSignal,
|
||||
): Promise<{ stdout: string; stderr: string }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const proc = spawn('docker', args, { shell: true });
|
||||
const proc = spawn("docker", args, { shell: true });
|
||||
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
|
||||
proc.stdout.on('data', (data) => {
|
||||
proc.stdout.on("data", (data) => {
|
||||
stdout += data.toString();
|
||||
});
|
||||
|
||||
proc.stderr.on('data', (data) => {
|
||||
proc.stderr.on("data", (data) => {
|
||||
stderr += data.toString();
|
||||
});
|
||||
|
||||
proc.on('close', (code) => {
|
||||
proc.on("close", (code) => {
|
||||
if (code === 0) {
|
||||
resolve({ stdout, stderr });
|
||||
} else {
|
||||
reject(new Error(`Docker command failed with code ${code}: ${stderr}`));
|
||||
reject(
|
||||
new Error(`Docker command failed with code ${code}: ${stderr}`),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
if (signal) {
|
||||
signal.addEventListener('abort', () => {
|
||||
signal.addEventListener("abort", () => {
|
||||
proc.kill();
|
||||
reject(new Error('Docker command was aborted'));
|
||||
reject(new Error("Docker command was aborted"));
|
||||
});
|
||||
}
|
||||
});
|
||||
|
|
@ -93,9 +141,15 @@ class Docker extends OpenAI implements ModelInstaller {
|
|||
async listModels(): Promise<string[]> {
|
||||
try {
|
||||
// Execute docker model ls and parse the output
|
||||
const { stdout } = await this.executeDockerCommand(['model', 'ls', '--format', '{{.Repository}}/{{.Tag}}']);
|
||||
return stdout.split('\n')
|
||||
.map(line => line.trim())
|
||||
const { stdout } = await this.executeDockerCommand([
|
||||
"model",
|
||||
"ls",
|
||||
"--format",
|
||||
"{{.Repository}}/{{.Tag}}",
|
||||
]);
|
||||
return stdout
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter(Boolean);
|
||||
} catch (error) {
|
||||
console.error("Failed to list Docker models:", error);
|
||||
|
|
@ -106,7 +160,7 @@ class Docker extends OpenAI implements ModelInstaller {
|
|||
async installModel(
|
||||
modelName: string,
|
||||
signal: AbortSignal,
|
||||
progressReporter?: (task: string, increment: number, total: number) => void
|
||||
progressReporter?: (task: string, increment: number, total: number) => void,
|
||||
): Promise<any> {
|
||||
const targetModel = this.modelMap[modelName] || modelName;
|
||||
|
||||
|
|
@ -115,17 +169,27 @@ class Docker extends OpenAI implements ModelInstaller {
|
|||
progressReporter?.(`Installing Docker model ${targetModel}`, 0, 100);
|
||||
|
||||
// Pull the model
|
||||
const { stdout, stderr } = await this.executeDockerCommand(['model', 'pull', targetModel], signal);
|
||||
const { stdout, stderr } = await this.executeDockerCommand(
|
||||
["model", "pull", targetModel],
|
||||
signal,
|
||||
);
|
||||
|
||||
// Report completion
|
||||
progressReporter?.(`Docker model ${targetModel} installed successfully`, 100, 100);
|
||||
progressReporter?.(
|
||||
`Docker model ${targetModel} installed successfully`,
|
||||
100,
|
||||
100,
|
||||
);
|
||||
|
||||
return { success: true, stdout, stderr };
|
||||
} catch (error) {
|
||||
console.error(`Failed to install Docker model ${targetModel}:`, error);
|
||||
// Fix: Type check the error before accessing message property
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
throw new Error(`Failed to install Docker model ${targetModel}: ${errorMessage}`);
|
||||
const errorMessage =
|
||||
error instanceof Error ? error.message : String(error);
|
||||
throw new Error(
|
||||
`Failed to install Docker model ${targetModel}: ${errorMessage}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -31,6 +31,7 @@ export type ToIdeFromWebviewOrCoreProtocol = {
|
|||
openUrl: [string, void];
|
||||
runCommand: [{ command: string; options?: TerminalOptions }, void];
|
||||
getSearchResults: [{ query: string }, string];
|
||||
getFileResults: [{ pattern: string }, string[]];
|
||||
subprocess: [{ command: string; cwd?: string }, [string, string]];
|
||||
saveFile: [{ filepath: string }, void];
|
||||
fileExists: [{ filepath: string }, boolean];
|
||||
|
|
|
|||
|
|
@ -4,7 +4,6 @@ import { ToWebviewFromIdeOrCoreProtocol } from "./webview";
|
|||
import type {
|
||||
ApplyState,
|
||||
CodeToEdit,
|
||||
ContextSubmenuItem,
|
||||
EditStatus,
|
||||
MessageContent,
|
||||
RangeInFileWithContents,
|
||||
|
|
@ -20,6 +19,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
|
|||
streamId: string;
|
||||
curSelectedModelTitle: string;
|
||||
filepath?: string;
|
||||
toolCallId?: string;
|
||||
},
|
||||
void,
|
||||
];
|
||||
|
|
|
|||
|
|
@ -187,6 +187,10 @@ export class MessageIde implements IDE {
|
|||
return this.request("getSearchResults", { query });
|
||||
}
|
||||
|
||||
getFileResults(pattern: string): Promise<string[]> {
|
||||
return this.request("getFileResults", { pattern });
|
||||
}
|
||||
|
||||
getProblems(fileUri: string): Promise<Problem[]> {
|
||||
return this.request("getProblems", { filepath: fileUri });
|
||||
}
|
||||
|
|
|
|||
|
|
@ -166,6 +166,10 @@ export class ReverseMessageIde {
|
|||
return this.ide.getSearchResults(data.query);
|
||||
});
|
||||
|
||||
this.on("getFileResults", (data) => {
|
||||
return this.ide.getFileResults(data.pattern);
|
||||
});
|
||||
|
||||
this.on("getProblems", (data) => {
|
||||
return this.ide.getProblems(data.filepath);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,9 +1,11 @@
|
|||
export enum BuiltInToolNames {
|
||||
ReadFile = "builtin_read_file",
|
||||
EditExistingFile = "builtin_edit_existing_file",
|
||||
ReadCurrentlyOpenFile = "builtin_read_currently_open_file",
|
||||
CreateNewFile = "builtin_create_new_file",
|
||||
RunTerminalCommand = "builtin_run_terminal_command",
|
||||
ExactSearch = "builtin_exact_search",
|
||||
GrepSearch = "builtin_grep_search",
|
||||
FileGlobSearch = "builtin_file_glob_search",
|
||||
SearchWeb = "builtin_search_web",
|
||||
ViewDiff = "builtin_view_diff",
|
||||
LSTool = "builtin_ls",
|
||||
|
|
|
|||
|
|
@ -4,7 +4,8 @@ import { canParseUrl } from "../util/url";
|
|||
import { BuiltInToolNames } from "./builtIn";
|
||||
|
||||
import { createNewFileImpl } from "./implementations/createNewFile";
|
||||
import { exactSearchImpl } from "./implementations/exactSearch";
|
||||
import { fileGlobSearchImpl } from "./implementations/globSearch";
|
||||
import { grepSearchImpl } from "./implementations/grepSearch";
|
||||
import { lsToolImpl } from "./implementations/lsTool";
|
||||
import { readCurrentlyOpenFileImpl } from "./implementations/readCurrentlyOpenFile";
|
||||
import { readFileImpl } from "./implementations/readFile";
|
||||
|
|
@ -138,10 +139,13 @@ export async function callTool(
|
|||
switch (uri) {
|
||||
case BuiltInToolNames.ReadFile:
|
||||
return await readFileImpl(args, extras);
|
||||
// Note: Custom GUI handling for edit
|
||||
case BuiltInToolNames.CreateNewFile:
|
||||
return await createNewFileImpl(args, extras);
|
||||
case BuiltInToolNames.ExactSearch:
|
||||
return await exactSearchImpl(args, extras);
|
||||
case BuiltInToolNames.GrepSearch:
|
||||
return await grepSearchImpl(args, extras);
|
||||
case BuiltInToolNames.FileGlobSearch:
|
||||
return await fileGlobSearchImpl(args, extras);
|
||||
case BuiltInToolNames.RunTerminalCommand:
|
||||
return await runTerminalCommandImpl(args, extras);
|
||||
case BuiltInToolNames.SearchWeb:
|
||||
|
|
|
|||
37
core/tools/definitions/editFile.ts
Normal file
37
core/tools/definitions/editFile.ts
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
import { Tool } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
|
||||
export interface EditToolArgs {
|
||||
filepath: string;
|
||||
new_contents: string;
|
||||
}
|
||||
|
||||
export const editFileTool: Tool = {
|
||||
type: "function",
|
||||
displayTitle: "Edit File",
|
||||
wouldLikeTo: "edit {{{ filepath }}}",
|
||||
isCurrently: "editing {{{ filepath }}}",
|
||||
hasAlready: "edited {{{ filepath }}}",
|
||||
group: BUILT_IN_GROUP_NAME,
|
||||
readonly: false,
|
||||
function: {
|
||||
name: BuiltInToolNames.EditExistingFile,
|
||||
description:
|
||||
"Use this tool to edit an existing file. If you don't know the contents of the file, read it first.",
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["filepath", "new_contents"],
|
||||
properties: {
|
||||
filepath: {
|
||||
type: "string",
|
||||
description:
|
||||
"The path of the file to edit, relative to the root of the workspace.",
|
||||
},
|
||||
new_contents: {
|
||||
type: "string",
|
||||
description: "The new file contents",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
26
core/tools/definitions/globSearch.ts
Normal file
26
core/tools/definitions/globSearch.ts
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
import { Tool } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
|
||||
export const globSearchTool: Tool = {
|
||||
type: "function",
|
||||
displayTitle: "Glob File Search",
|
||||
wouldLikeTo: 'find file matches for "{{{ pattern }}}"',
|
||||
isCurrently: 'finding file matches for "{{{ pattern }}}"',
|
||||
hasAlready: 'retreived file matches for "{{{ pattern }}}"',
|
||||
readonly: true,
|
||||
group: BUILT_IN_GROUP_NAME,
|
||||
function: {
|
||||
name: BuiltInToolNames.FileGlobSearch,
|
||||
description: "Search for files in the project",
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["pattern"],
|
||||
properties: {
|
||||
pattern: {
|
||||
type: "string",
|
||||
description: "Glob pattern for file path matching",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
|
@ -1,17 +1,17 @@
|
|||
import { Tool } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
|
||||
export const exactSearchTool: Tool = {
|
||||
export const grepSearchTool: Tool = {
|
||||
type: "function",
|
||||
displayTitle: "Exact Search",
|
||||
displayTitle: "Grep Search",
|
||||
wouldLikeTo: 'search for "{{{ query }}}" in the repository',
|
||||
isCurrently: 'getting search results for "{{{ query }}}"',
|
||||
hasAlready: 'retreived search results for "{{{ query }}}"',
|
||||
hasAlready: 'retrieved search results for "{{{ query }}}"',
|
||||
readonly: true,
|
||||
group: BUILT_IN_GROUP_NAME,
|
||||
function: {
|
||||
name: BuiltInToolNames.ExactSearch,
|
||||
description: "Perform an exact search over the repository using ripgrep.",
|
||||
name: BuiltInToolNames.GrepSearch,
|
||||
description: "Perform a search over the repository using ripgrep.",
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["query"],
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
import { inferResolvedUriFromRelativePath } from "../../util/ideUtils";
|
||||
|
||||
import { ToolImpl } from ".";
|
||||
import { getCleanUriPath, getUriPathBasename } from "../../util/uri";
|
||||
|
||||
export const createNewFileImpl: ToolImpl = async (args, extras) => {
|
||||
const resolvedFileUri = await inferResolvedUriFromRelativePath(
|
||||
|
|
@ -8,8 +9,26 @@ export const createNewFileImpl: ToolImpl = async (args, extras) => {
|
|||
extras.ide,
|
||||
);
|
||||
if (resolvedFileUri) {
|
||||
const exists = await extras.ide.fileExists(resolvedFileUri);
|
||||
if (exists) {
|
||||
throw new Error(
|
||||
`File ${args.filepath} already exists. Use the edit tool to edit this file`,
|
||||
);
|
||||
}
|
||||
await extras.ide.writeFile(resolvedFileUri, args.contents);
|
||||
await extras.ide.openFile(resolvedFileUri);
|
||||
return [
|
||||
{
|
||||
name: getUriPathBasename(resolvedFileUri),
|
||||
description: getCleanUriPath(resolvedFileUri),
|
||||
content: "File created successfuly",
|
||||
uri: {
|
||||
type: "file",
|
||||
value: resolvedFileUri,
|
||||
},
|
||||
},
|
||||
];
|
||||
} else {
|
||||
throw new Error("Failed to resolve path");
|
||||
}
|
||||
return [];
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,12 +0,0 @@
|
|||
import { ToolImpl } from ".";
|
||||
|
||||
export const exactSearchImpl: ToolImpl = async (args, extras) => {
|
||||
const content = await extras.ide.getSearchResults(args.query);
|
||||
return [
|
||||
{
|
||||
name: "Search results",
|
||||
description: "Results from exact search",
|
||||
content,
|
||||
},
|
||||
];
|
||||
};
|
||||
12
core/tools/implementations/globSearch.ts
Normal file
12
core/tools/implementations/globSearch.ts
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
import { ToolImpl } from ".";
|
||||
|
||||
export const fileGlobSearchImpl: ToolImpl = async (args, extras) => {
|
||||
const results = await extras.ide.getFileResults(args.pattern);
|
||||
return [
|
||||
{
|
||||
name: "File results",
|
||||
description: "Results from file glob search",
|
||||
content: results.join("\n"),
|
||||
},
|
||||
];
|
||||
};
|
||||
13
core/tools/implementations/grepSearch.ts
Normal file
13
core/tools/implementations/grepSearch.ts
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
import { ToolImpl } from ".";
|
||||
import { formatGrepSearchResults } from "../../util/grepSearch";
|
||||
|
||||
export const grepSearchImpl: ToolImpl = async (args, extras) => {
|
||||
const results = await extras.ide.getSearchResults(args.query);
|
||||
return [
|
||||
{
|
||||
name: "Search results",
|
||||
description: "Results from grep search",
|
||||
content: formatGrepSearchResults(results),
|
||||
},
|
||||
];
|
||||
};
|
||||
|
|
@ -1,5 +1,7 @@
|
|||
import { createNewFileTool } from "./definitions/createNewFile";
|
||||
import { exactSearchTool } from "./definitions/exactSearch";
|
||||
import { editFileTool } from "./definitions/editFile";
|
||||
import { globSearchTool } from "./definitions/globSearch";
|
||||
import { grepSearchTool } from "./definitions/grepSearch";
|
||||
import { lsTool } from "./definitions/lsTool";
|
||||
import { readCurrentlyOpenFileTool } from "./definitions/readCurrentlyOpenFile";
|
||||
import { readFileTool } from "./definitions/readFile";
|
||||
|
|
@ -9,10 +11,12 @@ import { viewDiffTool } from "./definitions/viewDiff";
|
|||
|
||||
export const allTools = [
|
||||
readFileTool,
|
||||
editFileTool,
|
||||
createNewFileTool,
|
||||
runTerminalCommandTool,
|
||||
|
||||
exactSearchTool,
|
||||
grepSearchTool,
|
||||
globSearchTool,
|
||||
searchWebTool,
|
||||
viewDiffTool,
|
||||
readCurrentlyOpenFileTool,
|
||||
|
|
|
|||
|
|
@ -238,6 +238,10 @@ class FileSystemIde implements IDE {
|
|||
return "";
|
||||
}
|
||||
|
||||
async getFileResults(pattern: string): Promise<string[]> {
|
||||
return [];
|
||||
}
|
||||
|
||||
async getProblems(fileUri?: string | undefined): Promise<Problem[]> {
|
||||
return Promise.resolve([]);
|
||||
}
|
||||
|
|
|
|||
61
core/util/grepSearch.ts
Normal file
61
core/util/grepSearch.ts
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
export function formatGrepSearchResults(results: string): string {
|
||||
const keepLines: string[] = [];
|
||||
|
||||
function countLeadingSpaces(line: string) {
|
||||
return line?.match(/^ */)?.[0].length ?? 0;
|
||||
}
|
||||
|
||||
const processResult = (lines: string[]) => {
|
||||
// Skip results in which only the file path was kept
|
||||
const resultPath = lines[0];
|
||||
const resultContent = lines.slice(1);
|
||||
if (resultContent.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Add path
|
||||
keepLines.push(resultPath);
|
||||
|
||||
// Find the minimum indentation of content lines
|
||||
let minIndent = Infinity;
|
||||
for (const line of resultContent) {
|
||||
const indent = countLeadingSpaces(line);
|
||||
if (indent < minIndent) {
|
||||
minIndent = indent;
|
||||
}
|
||||
}
|
||||
|
||||
// Make all lines line up to 2-space indent
|
||||
const changeIndentBy = 2 - minIndent;
|
||||
if (changeIndentBy === 0) {
|
||||
keepLines.push(...resultContent);
|
||||
} else if (changeIndentBy < 0) {
|
||||
keepLines.push(
|
||||
...resultContent.map((line) => line.substring(-changeIndentBy)),
|
||||
);
|
||||
} else {
|
||||
keepLines.push(
|
||||
...resultContent.map((line) => " ".repeat(changeIndentBy) + line),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
let resultLines: string[] = [];
|
||||
for (const line of results.split("\n").filter((l) => !!l)) {
|
||||
if (line.startsWith("./") || line === "--") {
|
||||
processResult(resultLines); // process previous result
|
||||
resultLines = [line];
|
||||
continue;
|
||||
}
|
||||
|
||||
// Exclude leading zero- or single-char lines
|
||||
if (resultLines.length === 1 && line.trim().length <= 1) {
|
||||
continue;
|
||||
}
|
||||
|
||||
resultLines.push(line);
|
||||
}
|
||||
processResult(resultLines);
|
||||
|
||||
return keepLines.join("\n");
|
||||
}
|
||||
|
|
@ -80,7 +80,7 @@ We recommend configuring **Claude 3.5 Sonnet** as your chat model.
|
|||
|
||||
## Autocomplete model
|
||||
|
||||
Bedrock currently does not offer any autocomplete models. However, [Codestral from Mistral](https://mistral.ai/news/codestral-2501/) and [Point from Poolisde](https://aws.amazon.com/bedrock/poolside/) will be supported in the near future.
|
||||
Bedrock currently does not offer any autocomplete models. However, [Codestral from Mistral](https://mistral.ai/news/codestral-2501/) and [Point from Poolside](https://aws.amazon.com/bedrock/poolside/) will be supported in the near future.
|
||||
|
||||
In the meantime, you can view a list of autocomplete model providers [here](../../model-roles/autocomplete.md).
|
||||
|
||||
|
|
|
|||
|
|
@ -28,11 +28,11 @@ To enable it, simply click the "Continue" button in the status bar at the bottom
|
|||
|
||||
Highlight a block of code, describe your code changes, and a diff will be streamed inline to your file which you can accept or reject.
|
||||
|
||||
## Actions
|
||||
## Agent
|
||||
|
||||
[Actions](https://continue.dev/docs/actions/how-to-use-it) are shortcuts for common use cases.
|
||||
[Agent](https://continue.dev/docs/agent/how-to-use-it) enables you to make more substantial changes to your codebase
|
||||
|
||||
For example, you might want to review code, write tests, or add a docstring.
|
||||
Agent equips the Chat model with the tools needed to handle a wide range of coding tasks, allowing the model to make decisions and save you the work of manually finding context and performing actions.
|
||||
|
||||
</div>
|
||||
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ pluginGroup=com.github.continuedev.continueintellijextension
|
|||
pluginName=continue-intellij-extension
|
||||
pluginRepositoryUrl=https://github.com/continuedev/continue
|
||||
# SemVer format -> https://semver.org
|
||||
pluginVersion=1.0.11
|
||||
pluginVersion=1.0.12
|
||||
# Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html
|
||||
pluginSinceBuild=223
|
||||
# IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@ class MessageTypes {
|
|||
"getCurrentFile",
|
||||
"getPinnedFiles",
|
||||
"getSearchResults",
|
||||
"getFileResults",
|
||||
"getProblems",
|
||||
"subprocess",
|
||||
"getBranch",
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ import com.intellij.openapi.application.ApplicationManager
|
|||
import com.intellij.openapi.command.WriteCommandAction
|
||||
import com.intellij.openapi.components.ServiceManager
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.editor.Editor
|
||||
import com.intellij.openapi.editor.SelectionModel
|
||||
import com.intellij.openapi.fileEditor.FileDocumentManager
|
||||
import com.intellij.openapi.fileEditor.FileEditorManager
|
||||
|
|
@ -347,6 +348,15 @@ class IdeProtocolClient(
|
|||
respond(results)
|
||||
}
|
||||
|
||||
"getFileResults" -> {
|
||||
val params = Gson().fromJson(
|
||||
dataElement.toString(),
|
||||
GetFileResultsParams::class.java
|
||||
)
|
||||
val results = ide.getFileResults(params.pattern)
|
||||
respond(results)
|
||||
}
|
||||
|
||||
"getOpenFiles" -> {
|
||||
val openFiles = ide.getOpenFiles()
|
||||
respond(openFiles)
|
||||
|
|
@ -423,11 +433,43 @@ class IdeProtocolClient(
|
|||
dataElement.toString(),
|
||||
ApplyToFileParams::class.java
|
||||
)
|
||||
val filepath = params.filepath
|
||||
|
||||
val editor = FileEditorManager.getInstance(project).selectedTextEditor
|
||||
continuePluginService.sendToWebview("updateApplyState", mapOf(
|
||||
"streamId" to params.streamId,
|
||||
"status" to "streaming",
|
||||
"fileContent" to params.text,
|
||||
"toolCallId" to params.toolCallId,
|
||||
"filepath" to filepath
|
||||
))
|
||||
|
||||
|
||||
fun closeStream () {
|
||||
continuePluginService.sendToWebview("updateApplyState", mapOf(
|
||||
"numDiffs" to 0,
|
||||
"streamId" to params.streamId,
|
||||
"status" to "closed",
|
||||
"fileContent" to params.text,
|
||||
"toolCallId" to params.toolCallId,
|
||||
"filepath" to filepath
|
||||
))
|
||||
}
|
||||
|
||||
var editor: Editor? = null;
|
||||
|
||||
if (!filepath.isNullOrEmpty()) {
|
||||
val virtualFile = VirtualFileManager.getInstance().findFileByUrl(filepath)
|
||||
if (virtualFile != null) {
|
||||
ApplicationManager.getApplication().invokeAndWait {
|
||||
FileEditorManager.getInstance(project).openFile(virtualFile, true)?.first()
|
||||
}
|
||||
}
|
||||
}
|
||||
editor = FileEditorManager.getInstance(project).selectedTextEditor
|
||||
|
||||
if (editor == null) {
|
||||
ide.showToast(ToastType.ERROR, "No active editor to apply edits to")
|
||||
closeStream()
|
||||
respond(null)
|
||||
return@launch
|
||||
}
|
||||
|
|
@ -436,6 +478,7 @@ class IdeProtocolClient(
|
|||
WriteCommandAction.runWriteCommandAction(project) {
|
||||
editor.document.insertString(0, params.text)
|
||||
}
|
||||
closeStream()
|
||||
respond(null)
|
||||
return@launch
|
||||
}
|
||||
|
|
@ -481,6 +524,7 @@ class IdeProtocolClient(
|
|||
ToastType.ERROR, "Failed to fetch model configuration"
|
||||
)
|
||||
}
|
||||
closeStream()
|
||||
respond(null)
|
||||
return@launch
|
||||
}
|
||||
|
|
@ -519,7 +563,11 @@ class IdeProtocolClient(
|
|||
editor,
|
||||
rif?.range?.start?.line ?: 0,
|
||||
rif?.range?.end?.line ?: (editor.document.lineCount - 1),
|
||||
{}, {})
|
||||
{},
|
||||
{},
|
||||
params.streamId,
|
||||
params.toolCallId
|
||||
)
|
||||
|
||||
diffStreamService.register(diffStreamHandler, editor)
|
||||
|
||||
|
|
|
|||
|
|
@ -46,7 +46,6 @@ class IntelliJIDE(
|
|||
|
||||
private val gitService = GitService(project, continuePluginService)
|
||||
|
||||
|
||||
private val ripgrep: String
|
||||
|
||||
init {
|
||||
|
|
@ -309,12 +308,116 @@ class IntelliJIDE(
|
|||
return getOpenFiles()
|
||||
}
|
||||
|
||||
override suspend fun getSearchResults(query: String): String {
|
||||
val command = GeneralCommandLine(ripgrep, "-i", "-C", "2", "--heading", "-e", query, ".")
|
||||
command.setWorkDirectory(project.basePath)
|
||||
return ExecUtil.execAndGetOutput(command).stdout
|
||||
override suspend fun getFileResults(pattern: String): List<String> {
|
||||
val ideInfo = this.getIdeInfo()
|
||||
if (ideInfo.remoteName == "local") {
|
||||
val command = GeneralCommandLine(
|
||||
ripgrep,
|
||||
"--files",
|
||||
"--iglob",
|
||||
pattern,
|
||||
"--ignore-file",
|
||||
".continueignore",
|
||||
"--ignore-file",
|
||||
".gitignore",
|
||||
)
|
||||
|
||||
command.setWorkDirectory(project.basePath)
|
||||
val results = ExecUtil.execAndGetOutput(command).stdout
|
||||
return results.split("\n")
|
||||
} else {
|
||||
throw NotImplementedError("Ripgrep not supported, this workspace is remote")
|
||||
|
||||
// Leaving in here for ideas
|
||||
// val projectBasePath = project.basePath ?: return emptyList()
|
||||
// val scope = GlobalSearchScope.projectScope(project)
|
||||
//
|
||||
// // Get all ignore patterns from .continueignore files
|
||||
// val ignorePatterns = mutableSetOf<String>()
|
||||
// VirtualFileManager.getInstance().findFileByUrl("file://$projectBasePath")?.let { root ->
|
||||
// VfsUtil.collectChildrenRecursively(root).forEach { file ->
|
||||
// if (file.name == ".continueignore") {
|
||||
// file.inputStream.bufferedReader().useLines { lines ->
|
||||
// ignorePatterns.addAll(lines.filter { it.isNotBlank() && !it.startsWith("#") })
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// return FilenameIndex.getAllFilesByExt(project, "*", scope)
|
||||
// .filter { file ->
|
||||
// val relativePath = file.path.removePrefix("$projectBasePath/")
|
||||
// // Check if file matches pattern and isn't ignored
|
||||
// PatternUtil.(relativePath, pattern) &&
|
||||
// !ignorePatterns.any { PatternUtil.matchesGlob(relativePath, it) }
|
||||
// }
|
||||
// .map { it.path.removePrefix("$projectBasePath/") }
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun getSearchResults(query: String): String {
|
||||
val ideInfo = this.getIdeInfo()
|
||||
if (ideInfo.remoteName == "local") {
|
||||
val command = GeneralCommandLine(
|
||||
ripgrep,
|
||||
"-i",
|
||||
"--ignore-file",
|
||||
".continueignore",
|
||||
"--ignore-file",
|
||||
".gitignore",
|
||||
"-C",
|
||||
"2",
|
||||
"--heading",
|
||||
"-e",
|
||||
query,
|
||||
"."
|
||||
)
|
||||
|
||||
command.setWorkDirectory(project.basePath)
|
||||
return ExecUtil.execAndGetOutput(command).stdout
|
||||
} else {
|
||||
throw NotImplementedError("Ripgrep not supported, this workspace is remote")
|
||||
|
||||
// For remote workspaces, use JetBrains search functionality
|
||||
// val searchResults = StringBuilder()
|
||||
// ApplicationManager.getApplication().invokeAndWait {
|
||||
// val options = FindModel().apply {
|
||||
// stringToFind = query
|
||||
// isCaseSensitive = false
|
||||
// isRegularExpressions = false
|
||||
// isWholeWordsOnly = false
|
||||
// searchContext = FindModel.SearchContext.ANY // or IN_CODE, IN_COMMENTS, IN_STRING_LITERALS, etc.
|
||||
// isMultiline = true // Allow matching across multiple lines
|
||||
// }
|
||||
//
|
||||
// val progressIndicator = EmptyProgressIndicator()
|
||||
// val presentation = FindUsagesProcessPresentation(
|
||||
// UsageViewPresentation()
|
||||
// )
|
||||
// val filesToSearch = ProjectFileIndex.getInstance(project)
|
||||
// .iterateContent(::ArrayList)
|
||||
// .filterNot { it.isDirectory }
|
||||
// .toSet()
|
||||
//
|
||||
//
|
||||
// FindInProjectUtil.findUsages(
|
||||
// options,
|
||||
// project,
|
||||
// progressIndicator,
|
||||
// presentation,
|
||||
// filesToSearch
|
||||
// ) { result ->
|
||||
// val virtualFile = result.virtualFile
|
||||
// searchResults.append(virtualFile.path).append("\n")
|
||||
// searchResults.append("${result..trim()}\n")
|
||||
// true // continue searching
|
||||
// }
|
||||
// }
|
||||
// return searchResults.toString()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
override suspend fun subprocess(command: String, cwd: String?): List<Any> {
|
||||
val commandList = command.split(" ")
|
||||
val builder = ProcessBuilder(commandList)
|
||||
|
|
|
|||
|
|
@ -27,14 +27,15 @@ class DiffStreamHandler(
|
|||
private val startLine: Int,
|
||||
private val endLine: Int,
|
||||
private val onClose: () -> Unit,
|
||||
private val onFinish: () -> Unit
|
||||
private val onFinish: () -> Unit,
|
||||
private val streamId: String?,
|
||||
private val toolCallId: String?
|
||||
) {
|
||||
private data class CurLineState(
|
||||
var index: Int, var highlighter: RangeHighlighter? = null, var diffBlock: VerticalDiffBlock? = null
|
||||
)
|
||||
|
||||
private var curLine = CurLineState(startLine)
|
||||
|
||||
private var isRunning: Boolean = false
|
||||
private var hasAcceptedOrRejectedBlock: Boolean = false
|
||||
|
||||
|
|
@ -48,8 +49,26 @@ class DiffStreamHandler(
|
|||
initUnfinishedRangeHighlights()
|
||||
}
|
||||
|
||||
private fun sendUpdate(status: String) {
|
||||
if(this.streamId == null) {
|
||||
return
|
||||
}
|
||||
val virtualFile = getVirtualFile()
|
||||
val continuePluginService = ServiceManager.getService(project, ContinuePluginService::class.java)
|
||||
continuePluginService.sendToWebview("updateApplyState", mapOf(
|
||||
"numDiffs" to this.diffBlocks.size,
|
||||
"streamId" to this.streamId,
|
||||
"status" to status,
|
||||
"fileContent" to "not implemented",
|
||||
"toolCallId" to this.toolCallId,
|
||||
"filepath" to virtualFile?.url
|
||||
))
|
||||
}
|
||||
|
||||
fun acceptAll() {
|
||||
editor.markupModel.removeAllHighlighters()
|
||||
editor.markupModel.removeAllHighlighters();
|
||||
sendUpdate("closed")
|
||||
|
||||
resetState()
|
||||
}
|
||||
|
||||
|
|
@ -62,6 +81,7 @@ class DiffStreamHandler(
|
|||
} else {
|
||||
undoChanges()
|
||||
}
|
||||
sendUpdate("closed")
|
||||
|
||||
resetState()
|
||||
}
|
||||
|
|
@ -70,6 +90,7 @@ class DiffStreamHandler(
|
|||
input: String, prefix: String, highlighted: String, suffix: String, modelTitle: String
|
||||
) {
|
||||
isRunning = true
|
||||
this.sendUpdate("streaming")
|
||||
|
||||
val continuePluginService = ServiceManager.getService(project, ContinuePluginService::class.java)
|
||||
val virtualFile = getVirtualFile()
|
||||
|
|
@ -83,6 +104,7 @@ class DiffStreamHandler(
|
|||
|
||||
if (response["done"] as? Boolean == true) {
|
||||
handleFinishedResponse()
|
||||
sendUpdate(if (diffBlocks.isEmpty()) "closed" else "done")
|
||||
return@request
|
||||
}
|
||||
|
||||
|
|
@ -133,7 +155,10 @@ class DiffStreamHandler(
|
|||
}
|
||||
|
||||
if (diffBlocks.isEmpty()) {
|
||||
sendUpdate("closed")
|
||||
onClose()
|
||||
} else {
|
||||
sendUpdate("done")
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -144,6 +169,7 @@ class DiffStreamHandler(
|
|||
)
|
||||
|
||||
diffBlocks.add(diffBlock)
|
||||
sendUpdate("streaming")
|
||||
|
||||
return diffBlock
|
||||
}
|
||||
|
|
@ -234,6 +260,7 @@ class DiffStreamHandler(
|
|||
undoManager.undo(fileEditor)
|
||||
}
|
||||
}
|
||||
sendUpdate("done")
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -207,7 +207,10 @@ fun openInlineEdit(project: Project?, editor: Editor) {
|
|||
textArea.document.insertString(textArea.caretPosition, ", ", null)
|
||||
textArea.requestFocus()
|
||||
customPanelRef.get().finish()
|
||||
})
|
||||
},
|
||||
null,
|
||||
null
|
||||
)
|
||||
|
||||
val diffStreamService = project.service<DiffStreamService>()
|
||||
diffStreamService.register(diffStreamHandler, editor)
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@ typealias getTagsParams = String
|
|||
|
||||
data class GetSearchResultsParams(val query: String)
|
||||
|
||||
data class GetFileResultsParams(val pattern: String)
|
||||
|
||||
data class SaveFileParams(val filepath: String)
|
||||
|
||||
|
|
|
|||
|
|
@ -12,7 +12,8 @@ data class ApplyToFileParams(
|
|||
val text: String,
|
||||
val streamId: String,
|
||||
val curSelectedModelTitle: String,
|
||||
val filepath: String?
|
||||
val filepath: String?,
|
||||
val toolCallId: String?
|
||||
)
|
||||
|
||||
data class InsertAtCursorParams(
|
||||
|
|
|
|||
|
|
@ -159,6 +159,8 @@ interface IDE {
|
|||
|
||||
suspend fun getSearchResults(query: String): String
|
||||
|
||||
suspend fun getFileResults(pattern: String): List<String>
|
||||
|
||||
// Note: This should be a `Pair<String, String>` but we use `List<Any>` because the keys of `Pair`
|
||||
// will serialize to `first and `second` rather than `0` and `1` like in JavaScript
|
||||
suspend fun subprocess(command: String, cwd: String? = null): List<Any>
|
||||
|
|
|
|||
|
|
@ -44,11 +44,11 @@
|
|||
|
||||

|
||||
|
||||
## Actions
|
||||
## Agent
|
||||
|
||||
[Actions](https://continue.dev/docs/actions/how-to-use-it) are shortcuts for common use cases.
|
||||
[Agent](https://continue.dev/docs/agent/how-to-use-it) enables you to make more substantial changes to your codebase
|
||||
|
||||

|
||||

|
||||
|
||||
</div>
|
||||
|
||||
|
|
|
|||
12
extensions/vscode/package-lock.json
generated
12
extensions/vscode/package-lock.json
generated
|
|
@ -1,12 +1,12 @@
|
|||
{
|
||||
"name": "continue",
|
||||
"version": "1.1.18",
|
||||
"version": "1.1.21",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "continue",
|
||||
"version": "1.1.18",
|
||||
"version": "1.1.21",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@continuedev/fetch": "^1.0.3",
|
||||
|
|
@ -88,7 +88,7 @@
|
|||
"ovsx": "^0.8.3",
|
||||
"rimraf": "^5.0.5",
|
||||
"typescript": "^5.6.3",
|
||||
"vite": "^4.3.9",
|
||||
"vite": "^4.5.12",
|
||||
"vsce": "^2.15.0",
|
||||
"vscode-extension-tester": "^8.10.0"
|
||||
},
|
||||
|
|
@ -13322,9 +13322,9 @@
|
|||
}
|
||||
},
|
||||
"node_modules/vite": {
|
||||
"version": "4.5.9",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-4.5.9.tgz",
|
||||
"integrity": "sha512-qK9W4xjgD3gXbC0NmdNFFnVFLMWSNiR3swj957yutwzzN16xF/E7nmtAyp1rT9hviDroQANjE4HK3H4WqWdFtw==",
|
||||
"version": "4.5.12",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-4.5.12.tgz",
|
||||
"integrity": "sha512-qrMwavANtSz91nDy3zEiUHMtL09x0mniQsSMvDkNxuCBM1W5vriJ22hEmwTth6DhLSWsZnHBT0yHFAQXt6efGA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
"name": "continue",
|
||||
"icon": "media/icon.png",
|
||||
"author": "Continue Dev, Inc",
|
||||
"version": "1.1.20",
|
||||
"version": "1.1.21",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/continuedev/continue"
|
||||
|
|
@ -625,7 +625,7 @@
|
|||
"ovsx": "^0.8.3",
|
||||
"rimraf": "^5.0.5",
|
||||
"typescript": "^5.6.3",
|
||||
"vite": "^4.3.9",
|
||||
"vite": "^4.5.12",
|
||||
"vsce": "^2.15.0",
|
||||
"vscode-extension-tester": "^8.10.0"
|
||||
},
|
||||
|
|
|
|||
|
|
@ -1,6 +1,10 @@
|
|||
const { exec } = require("child_process");
|
||||
const fs = require("fs");
|
||||
|
||||
const version = JSON.parse(
|
||||
fs.readFileSync("./package.json", { encoding: "utf-8" }),
|
||||
).version;
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
let target;
|
||||
|
||||
|
|
@ -27,6 +31,6 @@ exec(command, (error) => {
|
|||
throw error;
|
||||
}
|
||||
console.log(
|
||||
"vsce package completed - extension created at extensions/vscode/build/continue-{version}.vsix",
|
||||
`vsce package completed - extension created at extensions/vscode/build/continue-${version}.vsix`,
|
||||
);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -555,25 +555,15 @@ class VsCodeIde implements IDE {
|
|||
.map((t) => (t.input as vscode.TabInputText).uri.toString());
|
||||
}
|
||||
|
||||
private async _searchDir(query: string, dir: string): Promise<string> {
|
||||
const relativeDir = vscode.Uri.parse(dir).fsPath;
|
||||
runRipgrepQuery(dirUri: string, args: string[]) {
|
||||
const relativeDir = vscode.Uri.parse(dirUri).fsPath;
|
||||
const ripGrepUri = vscode.Uri.joinPath(
|
||||
getExtensionUri(),
|
||||
"out/node_modules/@vscode/ripgrep/bin/rg",
|
||||
);
|
||||
const p = child_process.spawn(
|
||||
ripGrepUri.fsPath,
|
||||
[
|
||||
"-i", // Case-insensitive search
|
||||
"-C",
|
||||
"2", // Show 2 lines of context
|
||||
"--heading", // Only show filepath once per result
|
||||
"-e",
|
||||
query, // Pattern to search for
|
||||
".", // Directory to search in
|
||||
],
|
||||
{ cwd: relativeDir },
|
||||
);
|
||||
const p = child_process.spawn(ripGrepUri.fsPath, args, {
|
||||
cwd: relativeDir,
|
||||
});
|
||||
let output = "";
|
||||
|
||||
p.stdout.on("data", (data) => {
|
||||
|
|
@ -595,55 +585,118 @@ class VsCodeIde implements IDE {
|
|||
});
|
||||
}
|
||||
|
||||
async getFileResults(pattern: string): Promise<string[]> {
|
||||
const MAX_FILE_RESULTS = 200;
|
||||
if (vscode.env.remoteName) {
|
||||
// TODO better tests for this remote search implementation
|
||||
// throw new Error("Ripgrep not supported, this workspace is remote");
|
||||
|
||||
// IMPORTANT: findFiles automatically accounts for .gitignore
|
||||
const ignoreFiles = await vscode.workspace.findFiles(
|
||||
"**/.continueignore",
|
||||
null,
|
||||
);
|
||||
|
||||
const ignoreGlobs: Set<string> = new Set();
|
||||
for (const file of ignoreFiles) {
|
||||
const content = await vscode.workspace.fs.readFile(file);
|
||||
const filePath = vscode.workspace.asRelativePath(file);
|
||||
const fileDir = filePath
|
||||
.replace(/\\/g, "/")
|
||||
.replace(/\/$/, "")
|
||||
.split("/")
|
||||
.slice(0, -1)
|
||||
.join("/");
|
||||
|
||||
const patterns = Buffer.from(content)
|
||||
.toString()
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter(
|
||||
(line) => line && !line.startsWith("#") && !pattern.startsWith("!"),
|
||||
);
|
||||
// VSCode does not support negations
|
||||
|
||||
patterns
|
||||
// Handle prefix
|
||||
.map((pattern) => {
|
||||
const normalizedPattern = pattern.replace(/\\/g, "/");
|
||||
|
||||
if (normalizedPattern.startsWith("/")) {
|
||||
if (fileDir) {
|
||||
return `{/,}${normalizedPattern}`;
|
||||
} else {
|
||||
return `${fileDir}/${normalizedPattern.substring(1)}`;
|
||||
}
|
||||
} else {
|
||||
if (fileDir) {
|
||||
return `${fileDir}/${normalizedPattern}`;
|
||||
} else {
|
||||
return `**/${normalizedPattern}`;
|
||||
}
|
||||
}
|
||||
})
|
||||
// Handle suffix
|
||||
.map((pattern) => {
|
||||
return pattern.endsWith("/") ? `${pattern}**/*` : pattern;
|
||||
})
|
||||
.forEach((pattern) => {
|
||||
ignoreGlobs.add(pattern);
|
||||
});
|
||||
}
|
||||
|
||||
const ignoreGlobsArray = Array.from(ignoreGlobs);
|
||||
|
||||
const results = await vscode.workspace.findFiles(
|
||||
pattern,
|
||||
ignoreGlobs.size ? `{${ignoreGlobsArray.join(",")}}` : null,
|
||||
MAX_FILE_RESULTS,
|
||||
);
|
||||
return results.map((result) => vscode.workspace.asRelativePath(result));
|
||||
} else {
|
||||
const results: string[] = [];
|
||||
for (const dir of await this.getWorkspaceDirs()) {
|
||||
const dirResults = await this.runRipgrepQuery(dir, [
|
||||
"--files",
|
||||
"--iglob",
|
||||
pattern,
|
||||
"--ignore-file",
|
||||
".continueignore",
|
||||
"--ignore-file",
|
||||
".gitignore",
|
||||
]);
|
||||
|
||||
results.push(dirResults);
|
||||
}
|
||||
|
||||
return results.join("\n").split("\n").slice(0, MAX_FILE_RESULTS);
|
||||
}
|
||||
}
|
||||
|
||||
async getSearchResults(query: string): Promise<string> {
|
||||
if (vscode.env.remoteName) {
|
||||
throw new Error("Ripgrep not supported, this workspace is remote");
|
||||
}
|
||||
const results: string[] = [];
|
||||
for (const dir of await this.getWorkspaceDirs()) {
|
||||
const dirResults = await this._searchDir(query, dir);
|
||||
const dirResults = await this.runRipgrepQuery(dir, [
|
||||
"-i", // Case-insensitive search
|
||||
"--ignore-file",
|
||||
".continueignore",
|
||||
"--ignore-file",
|
||||
".gitignore",
|
||||
"-C",
|
||||
"2", // Show 2 lines of context
|
||||
"--heading", // Only show filepath once per result
|
||||
"-e",
|
||||
query, // Pattern to search for
|
||||
".", // Directory to search in
|
||||
]);
|
||||
|
||||
const keepLines: string[] = [];
|
||||
|
||||
function countLeadingSpaces(line: string) {
|
||||
return line?.match(/^ */)?.[0].length ?? 0;
|
||||
}
|
||||
|
||||
// function formatLine(line: string, sectionIndent: number): string {
|
||||
// return line.replace(new RegExp(`^[ ]{0,${sectionIndent}}`), "");
|
||||
// }
|
||||
|
||||
let leading = false;
|
||||
let sectionIndent = 0;
|
||||
// let sectionTrim = 0;
|
||||
for (const line of dirResults.split("\n").filter((l) => !!l)) {
|
||||
if (line.startsWith("./") || line === "--") {
|
||||
leading = true;
|
||||
keepLines.push(line);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (leading) {
|
||||
// Exclude leading single-char lines
|
||||
if (line.trim().length > 1) {
|
||||
// Record spacing at first non-single char line
|
||||
leading = false;
|
||||
sectionIndent = countLeadingSpaces(line);
|
||||
keepLines.push(line);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// Exclude trailing
|
||||
// TODO may exclude wanted results for lines that look like
|
||||
// ./filename
|
||||
// thisThing
|
||||
// relevantThing
|
||||
//
|
||||
if (countLeadingSpaces(line) >= sectionIndent) {
|
||||
keepLines.push(line);
|
||||
}
|
||||
}
|
||||
results.push(keepLines.join("\n"));
|
||||
results.push(dirResults);
|
||||
}
|
||||
|
||||
return results.join("\n\n");
|
||||
return results.join("\n");
|
||||
}
|
||||
|
||||
async getProblems(fileUri?: string | undefined): Promise<Problem[]> {
|
||||
|
|
|
|||
|
|
@ -247,6 +247,7 @@ async function processDiff(
|
|||
verticalDiffManager: VerticalDiffManager,
|
||||
newFileUri?: string,
|
||||
streamId?: string,
|
||||
toolCallId?: string,
|
||||
) {
|
||||
captureCommandTelemetry(`${action}Diff`);
|
||||
|
||||
|
|
@ -280,6 +281,7 @@ async function processDiff(
|
|||
streamId,
|
||||
status: "closed",
|
||||
numDiffs: 0,
|
||||
toolCallId,
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -190,6 +190,7 @@ export class VerticalDiffManager {
|
|||
diffStream: AsyncGenerator<DiffLine>,
|
||||
instant: boolean,
|
||||
streamId: string,
|
||||
toolCallId?: string,
|
||||
) {
|
||||
vscode.commands.executeCommand("setContext", "continue.diffVisible", true);
|
||||
|
||||
|
|
@ -226,6 +227,7 @@ export class VerticalDiffManager {
|
|||
numDiffs,
|
||||
fileContent,
|
||||
filepath: fileUri,
|
||||
toolCallId,
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
|
@ -276,6 +278,7 @@ export class VerticalDiffManager {
|
|||
quickEdit?: string,
|
||||
range?: vscode.Range,
|
||||
newCode?: string,
|
||||
toolCallId?: string,
|
||||
): Promise<string | undefined> {
|
||||
vscode.commands.executeCommand("setContext", "continue.diffVisible", true);
|
||||
|
||||
|
|
@ -351,6 +354,7 @@ export class VerticalDiffManager {
|
|||
numDiffs,
|
||||
fileContent,
|
||||
filepath: fileUri,
|
||||
toolCallId,
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@ import { stripImages } from "core/util/messageContent";
|
|||
import { getUriPathBasename } from "core/util/uri";
|
||||
import * as vscode from "vscode";
|
||||
|
||||
import { ILLM } from "core";
|
||||
import { VerticalDiffManager } from "../diff/vertical/manager";
|
||||
import EditDecorationManager from "../quickEdit/EditDecorationManager";
|
||||
import {
|
||||
|
|
@ -28,7 +29,6 @@ import { showTutorial } from "../util/tutorial";
|
|||
import { getExtensionUri } from "../util/vscode";
|
||||
import { VsCodeIde } from "../VsCodeIde";
|
||||
import { VsCodeWebviewProtocol } from "../webviewProtocol";
|
||||
import { ILLM } from "core";
|
||||
|
||||
/**
|
||||
* A shared messenger class between Core and Webview
|
||||
|
|
@ -133,6 +133,7 @@ export class VsCodeMessenger {
|
|||
streamId: data.streamId,
|
||||
status: "streaming",
|
||||
fileContent: data.text,
|
||||
toolCallId: data.toolCallId,
|
||||
});
|
||||
|
||||
if (data.filepath) {
|
||||
|
|
@ -164,6 +165,7 @@ export class VsCodeMessenger {
|
|||
status: "closed",
|
||||
numDiffs: 0,
|
||||
fileContent: data.text,
|
||||
toolCallId: data.toolCallId,
|
||||
});
|
||||
|
||||
return;
|
||||
|
|
@ -211,6 +213,7 @@ export class VsCodeMessenger {
|
|||
diffLines,
|
||||
instant,
|
||||
data.streamId,
|
||||
data.toolCallId,
|
||||
);
|
||||
} else {
|
||||
const prompt = `The following code was suggested as an edit:\n\`\`\`\n${data.text}\n\`\`\`\nPlease apply it to the previous code.`;
|
||||
|
|
@ -232,6 +235,7 @@ export class VsCodeMessenger {
|
|||
undefined,
|
||||
rangeToApplyTo,
|
||||
data.text,
|
||||
data.toolCallId,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
|
@ -391,6 +395,9 @@ export class VsCodeMessenger {
|
|||
this.onWebviewOrCore("getSearchResults", async (msg) => {
|
||||
return ide.getSearchResults(msg.data.query);
|
||||
});
|
||||
this.onWebviewOrCore("getFileResults", async (msg) => {
|
||||
return ide.getFileResults(msg.data.pattern);
|
||||
});
|
||||
this.onWebviewOrCore("subprocess", async (msg) => {
|
||||
return ide.subprocess(msg.data.command, msg.data.cwd);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { RouterProvider, createMemoryRouter } from "react-router-dom";
|
||||
import Layout from "./components/Layout";
|
||||
import { MainEditorProvider } from "./components/mainInput/TipTapEditor";
|
||||
import { SubmenuContextProvidersProvider } from "./context/SubmenuContextProviders";
|
||||
import { VscThemeProvider } from "./context/VscTheme";
|
||||
import useSetup from "./hooks/useSetup";
|
||||
|
|
@ -57,9 +58,11 @@ function SetupListeners() {
|
|||
function App() {
|
||||
return (
|
||||
<VscThemeProvider>
|
||||
<SubmenuContextProvidersProvider>
|
||||
<RouterProvider router={router} />
|
||||
</SubmenuContextProvidersProvider>
|
||||
<MainEditorProvider>
|
||||
<SubmenuContextProvidersProvider>
|
||||
<RouterProvider router={router} />
|
||||
</SubmenuContextProvidersProvider>
|
||||
</MainEditorProvider>
|
||||
<SetupListeners />
|
||||
</VscThemeProvider>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -2,14 +2,17 @@ import { SlashCommandDescription } from "core";
|
|||
import { useState } from "react";
|
||||
import { useBookmarkedSlashCommands } from "../../hooks/useBookmarkedSlashCommands";
|
||||
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
|
||||
import { setMainEditorContentTrigger } from "../../redux/slices/sessionSlice";
|
||||
import { getParagraphNodeFromString } from "../mainInput/utils";
|
||||
import { useMainEditor } from "../mainInput/TipTapEditor";
|
||||
import { ConversationStarterCard } from "./ConversationStarterCard";
|
||||
|
||||
const NUM_CARDS_TO_RENDER = 5;
|
||||
|
||||
/**
|
||||
* Displays a grid of conversation starter cards for bookmarked slash commands
|
||||
*/
|
||||
export function ConversationStarterCards() {
|
||||
const dispatch = useAppDispatch();
|
||||
const { mainEditor } = useMainEditor();
|
||||
const [showAll, setShowAll] = useState(false);
|
||||
const { isCommandBookmarked } = useBookmarkedSlashCommands();
|
||||
const slashCommands = useAppSelector(
|
||||
|
|
@ -21,11 +24,7 @@ export function ConversationStarterCards() {
|
|||
);
|
||||
|
||||
function onClick(command: SlashCommandDescription) {
|
||||
if (command.prompt) {
|
||||
dispatch(
|
||||
setMainEditorContentTrigger(getParagraphNodeFromString(command.prompt)),
|
||||
);
|
||||
}
|
||||
mainEditor?.commands.insertPrompt(command);
|
||||
}
|
||||
|
||||
if (bookmarkedSlashCommands.length === 0) {
|
||||
|
|
|
|||
|
|
@ -5,9 +5,10 @@ import { themeIcons } from "seti-file-icons";
|
|||
|
||||
export interface FileIconProps {
|
||||
filename: string;
|
||||
height: string;
|
||||
width: string;
|
||||
height: `${number}px`;
|
||||
width: `${number}px`;
|
||||
}
|
||||
|
||||
export default function FileIcon({ filename, height, width }: FileIconProps) {
|
||||
const file = useMemo(() => {
|
||||
if (filename.includes(" (")) {
|
||||
|
|
@ -45,7 +46,7 @@ export default function FileIcon({ filename, height, width }: FileIconProps) {
|
|||
height: height,
|
||||
fill: color,
|
||||
flexShrink: 0,
|
||||
display: "block",
|
||||
display: "flex",
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -12,7 +12,6 @@ import {
|
|||
newSession,
|
||||
selectIsInEditMode,
|
||||
setMode,
|
||||
updateApplyState,
|
||||
} from "../redux/slices/sessionSlice";
|
||||
import { setShowDialog } from "../redux/slices/uiSlice";
|
||||
import { exitEditMode } from "../redux/thunks";
|
||||
|
|
@ -125,20 +124,6 @@ const Layout = () => {
|
|||
[],
|
||||
);
|
||||
|
||||
useWebviewListener(
|
||||
"updateApplyState",
|
||||
async (state) => {
|
||||
// dispatch(
|
||||
// updateCurCheckpoint({
|
||||
// filepath: state.filepath,
|
||||
// content: state.fileContent,
|
||||
// }),
|
||||
// );
|
||||
dispatch(updateApplyState(state));
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
useWebviewListener(
|
||||
"openOnboardingCard",
|
||||
async () => {
|
||||
|
|
|
|||
|
|
@ -48,7 +48,7 @@ const HeaderButtonWithToolTip = React.forwardRef<
|
|||
</HeaderButton>
|
||||
|
||||
<ToolTip id={tooltipId} place={props.tooltipPlacement ?? "bottom"}>
|
||||
{props.text}
|
||||
<span className="text-xs">{props.text}</span>
|
||||
</ToolTip>
|
||||
</>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ import { selectSlashCommandComboBoxInputs } from "../../redux/selectors";
|
|||
import ContextItemsPeek from "./belowMainInput/ContextItemsPeek";
|
||||
import { ToolbarOptions } from "./InputToolbar";
|
||||
import { Lump } from "./Lump";
|
||||
import TipTapEditor from "./tiptap/TipTapEditor";
|
||||
import { TipTapEditor } from "./TipTapEditor";
|
||||
|
||||
interface ContinueInputBoxProps {
|
||||
isEditMode?: boolean;
|
||||
|
|
|
|||
|
|
@ -98,11 +98,16 @@ function InputToolbar(props: InputToolbarProps) {
|
|||
const hasCodeToEdit = useAppSelector(selectHasCodeToEdit);
|
||||
const toolCallState = useAppSelector(selectCurrentToolCall);
|
||||
const isEditModeAndNoCodeToEdit = isInEditMode && !hasCodeToEdit;
|
||||
const activeToolCallStreamId = useAppSelector(
|
||||
(store) => store.session.activeToolStreamId,
|
||||
);
|
||||
|
||||
const isEnterDisabled =
|
||||
props.disabled ||
|
||||
isEditModeAndNoCodeToEdit ||
|
||||
toolCallState?.status === "generated";
|
||||
toolCallState?.status === "generated" ||
|
||||
!!activeToolCallStreamId;
|
||||
|
||||
const toolsSupported = defaultModel && modelSupportsTools(defaultModel);
|
||||
|
||||
const supportsImages =
|
||||
|
|
|
|||
|
|
@ -9,11 +9,10 @@ import {
|
|||
WrenchScrewdriverIcon,
|
||||
} from "@heroicons/react/24/outline";
|
||||
import { vscBadgeBackground, vscBadgeForeground } from "../..";
|
||||
import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
|
||||
import { toggleBlockSettingsToolbar } from "../../../redux/slices/uiSlice";
|
||||
import { fontSize } from "../../../util";
|
||||
import AssistantSelect from "../../modelSelection/platform/AssistantSelect";
|
||||
import HoverItem from "../InputToolbar/HoverItem";
|
||||
import { useLump } from "./LumpContext";
|
||||
|
||||
interface BlockSettingsToolbarIcon {
|
||||
tooltip: string;
|
||||
|
|
@ -81,21 +80,19 @@ function BlockSettingsToolbarIcon(props: BlockSettingsToolbarIcon) {
|
|||
);
|
||||
}
|
||||
|
||||
interface BlockSettingsTopToolbarProps {
|
||||
selectedSection: string | null;
|
||||
setSelectedSection: (value: string | null) => void;
|
||||
}
|
||||
export function BlockSettingsTopToolbar() {
|
||||
const {
|
||||
isToolbarExpanded,
|
||||
toggleToolbar,
|
||||
selectedSection,
|
||||
setSelectedSection,
|
||||
} = useLump();
|
||||
|
||||
export function BlockSettingsTopToolbar(props: BlockSettingsTopToolbarProps) {
|
||||
const isExpanded = useAppSelector(
|
||||
(state) => state.ui.isBlockSettingsToolbarExpanded,
|
||||
);
|
||||
const dispatch = useAppDispatch();
|
||||
const handleEllipsisClick = () => {
|
||||
if (isExpanded) {
|
||||
props.setSelectedSection(null);
|
||||
if (isToolbarExpanded) {
|
||||
setSelectedSection(null);
|
||||
}
|
||||
dispatch(toggleBlockSettingsToolbar());
|
||||
toggleToolbar();
|
||||
};
|
||||
|
||||
return (
|
||||
|
|
@ -103,14 +100,14 @@ export function BlockSettingsTopToolbar(props: BlockSettingsTopToolbarProps) {
|
|||
<div className="xs:flex hidden items-center justify-center text-gray-400">
|
||||
<BlockSettingsToolbarIcon
|
||||
className="-ml-1.5"
|
||||
icon={isExpanded ? ChevronLeftIcon : EllipsisHorizontalIcon}
|
||||
tooltip={isExpanded ? "Collapse sections" : "Expand sections"}
|
||||
icon={isToolbarExpanded ? ChevronLeftIcon : EllipsisHorizontalIcon}
|
||||
tooltip={isToolbarExpanded ? "Collapse sections" : "Expand sections"}
|
||||
isSelected={false}
|
||||
onClick={handleEllipsisClick}
|
||||
/>
|
||||
<div
|
||||
className="flex overflow-hidden transition-all duration-200"
|
||||
style={{ width: isExpanded ? `160px` : "0px" }}
|
||||
style={{ width: isToolbarExpanded ? `160px` : "0px" }}
|
||||
>
|
||||
<div className="flex">
|
||||
{sections.map((section) => (
|
||||
|
|
@ -118,10 +115,10 @@ export function BlockSettingsTopToolbar(props: BlockSettingsTopToolbarProps) {
|
|||
key={section.id}
|
||||
icon={section.icon}
|
||||
tooltip={section.tooltip}
|
||||
isSelected={props.selectedSection === section.id}
|
||||
isSelected={selectedSection === section.id}
|
||||
onClick={() =>
|
||||
props.setSelectedSection(
|
||||
props.selectedSection === section.id ? null : section.id,
|
||||
setSelectedSection(
|
||||
selectedSection === section.id ? null : section.id,
|
||||
)
|
||||
}
|
||||
/>
|
||||
|
|
|
|||
115
gui/src/components/mainInput/Lump/LumpContext.tsx
Normal file
115
gui/src/components/mainInput/Lump/LumpContext.tsx
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
/**
|
||||
* Provides context for controlling the Lump component's visibility state
|
||||
*/
|
||||
import {
|
||||
createContext,
|
||||
ReactNode,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useState,
|
||||
} from "react";
|
||||
import { useAppSelector } from "../../../redux/hooks";
|
||||
|
||||
interface LumpContextType {
|
||||
isLumpVisible: boolean;
|
||||
selectedSection: string | null;
|
||||
displayedSection: string | null;
|
||||
isToolbarExpanded: boolean;
|
||||
hideLump: () => void;
|
||||
setSelectedSection: (section: string | null) => void;
|
||||
toggleToolbar: () => void;
|
||||
}
|
||||
|
||||
const LumpContext = createContext<LumpContextType | undefined>(undefined);
|
||||
|
||||
interface LumpProviderProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Provider component that makes Lump state available to any child component
|
||||
*/
|
||||
export function LumpProvider({ children }: LumpProviderProps) {
|
||||
const [selectedSection, setSelectedSection] = useState<string | null>(null);
|
||||
const [displayedSection, setDisplayedSection] = useState<string | null>(null);
|
||||
const [isVisible, setIsVisible] = useState(false);
|
||||
const [isToolbarExpanded, setIsToolbarExpanded] = useState(true);
|
||||
const isStreaming = useAppSelector((state) => state.session.isStreaming);
|
||||
|
||||
// Handle keyboard escape
|
||||
const handleKeyDown = useCallback(
|
||||
(event: KeyboardEvent) => {
|
||||
if (event.key === "Escape" && selectedSection) {
|
||||
setSelectedSection(null);
|
||||
}
|
||||
},
|
||||
[selectedSection],
|
||||
);
|
||||
|
||||
// Function to hide the lump
|
||||
const hideLump = useCallback(() => {
|
||||
setSelectedSection(null);
|
||||
}, []);
|
||||
|
||||
// Function to toggle toolbar expanded state
|
||||
const toggleToolbar = useCallback(() => {
|
||||
setIsToolbarExpanded((prev) => !prev);
|
||||
}, []);
|
||||
|
||||
// Update displayedSection and visibility when selectedSection changes
|
||||
useEffect(() => {
|
||||
if (selectedSection) {
|
||||
setDisplayedSection(selectedSection);
|
||||
setIsVisible(true);
|
||||
} else {
|
||||
setIsVisible(false);
|
||||
const timeout = setTimeout(() => {
|
||||
setDisplayedSection(null);
|
||||
}, 300);
|
||||
return () => clearTimeout(timeout);
|
||||
}
|
||||
}, [selectedSection]);
|
||||
|
||||
// Reset when streaming starts
|
||||
useEffect(() => {
|
||||
if (isStreaming && selectedSection) {
|
||||
setSelectedSection(null);
|
||||
}
|
||||
}, [isStreaming, selectedSection]);
|
||||
|
||||
// Set up keyboard listener
|
||||
useEffect(() => {
|
||||
if (selectedSection) {
|
||||
document.addEventListener("keydown", handleKeyDown);
|
||||
return () => document.removeEventListener("keydown", handleKeyDown);
|
||||
}
|
||||
}, [selectedSection, handleKeyDown]);
|
||||
|
||||
return (
|
||||
<LumpContext.Provider
|
||||
value={{
|
||||
isLumpVisible: isVisible,
|
||||
selectedSection,
|
||||
displayedSection,
|
||||
isToolbarExpanded,
|
||||
hideLump,
|
||||
setSelectedSection,
|
||||
toggleToolbar,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</LumpContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook that lets any component access the Lump context
|
||||
*/
|
||||
export function useLump() {
|
||||
const context = useContext(LumpContext);
|
||||
if (context === undefined) {
|
||||
throw new Error("useLump must be used within a LumpProvider");
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
|
@ -21,11 +21,6 @@ const StopButton = styled.div`
|
|||
cursor: pointer;
|
||||
`;
|
||||
|
||||
interface TopToolbarProps {
|
||||
selectedSection: string | null;
|
||||
setSelectedSection: (value: string | null) => void;
|
||||
}
|
||||
|
||||
function GeneratingIndicator() {
|
||||
return (
|
||||
<div className="text-xs text-gray-400">
|
||||
|
|
@ -35,7 +30,7 @@ function GeneratingIndicator() {
|
|||
);
|
||||
}
|
||||
|
||||
export function LumpToolbar(props: TopToolbarProps) {
|
||||
export function LumpToolbar() {
|
||||
const dispatch = useAppDispatch();
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const ttsActive = useAppSelector((state) => state.ui.ttsActive);
|
||||
|
|
@ -73,10 +68,5 @@ export function LumpToolbar(props: TopToolbarProps) {
|
|||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<BlockSettingsTopToolbar
|
||||
selectedSection={props.selectedSection}
|
||||
setSelectedSection={props.setSelectedSection}
|
||||
/>
|
||||
);
|
||||
return <BlockSettingsTopToolbar />;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,11 +1,10 @@
|
|||
import { useEffect, useState } from "react";
|
||||
import styled from "styled-components";
|
||||
import {
|
||||
defaultBorderRadius,
|
||||
vscCommandCenterInactiveBorder,
|
||||
vscInputBackground,
|
||||
} from "../..";
|
||||
import { useAppSelector } from "../../../redux/hooks";
|
||||
import { LumpProvider, useLump } from "./LumpContext";
|
||||
import { LumpToolbar } from "./LumpToolbar";
|
||||
import { SelectedSection } from "./sections/SelectedSection";
|
||||
|
||||
|
|
@ -30,62 +29,34 @@ const ContentDiv = styled.div<{ hasSection: boolean; isVisible: boolean }>`
|
|||
overflow-y: auto;
|
||||
`;
|
||||
|
||||
/**
|
||||
* Main component that displays the toolbar and selected content section
|
||||
*/
|
||||
export function Lump() {
|
||||
const [selectedSection, setSelectedSection] = useState<string | null>(null);
|
||||
const [displayedSection, setDisplayedSection] = useState<string | null>(null);
|
||||
const [isVisible, setIsVisible] = useState(false);
|
||||
const isStreaming = useAppSelector((state) => state.session.isStreaming);
|
||||
return (
|
||||
<LumpProvider>
|
||||
<LumpContent />
|
||||
</LumpProvider>
|
||||
);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedSection) {
|
||||
return;
|
||||
}
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") {
|
||||
setSelectedSection(null);
|
||||
}
|
||||
};
|
||||
document.addEventListener("keydown", handleKeyDown);
|
||||
return () => {
|
||||
document.removeEventListener("keydown", handleKeyDown);
|
||||
};
|
||||
}, [selectedSection]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isStreaming) {
|
||||
setSelectedSection(null);
|
||||
}
|
||||
}, [isStreaming]);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedSection) {
|
||||
setDisplayedSection(selectedSection);
|
||||
setIsVisible(true);
|
||||
} else {
|
||||
setIsVisible(false);
|
||||
const timeout = setTimeout(() => {
|
||||
setDisplayedSection(null);
|
||||
}, 300);
|
||||
return () => {
|
||||
clearTimeout(timeout);
|
||||
};
|
||||
}
|
||||
}, [selectedSection]);
|
||||
/**
|
||||
* Internal component that consumes the LumpContext
|
||||
*/
|
||||
function LumpContent() {
|
||||
const { isLumpVisible, selectedSection } = useLump();
|
||||
|
||||
return (
|
||||
<LumpDiv>
|
||||
<div className="mt-0.5 px-2">
|
||||
<LumpToolbar
|
||||
selectedSection={selectedSection}
|
||||
setSelectedSection={setSelectedSection}
|
||||
/>
|
||||
<LumpToolbar />
|
||||
|
||||
<ContentDiv
|
||||
className="no-scrollbar pr-0.5"
|
||||
hasSection={!!selectedSection}
|
||||
isVisible={isVisible}
|
||||
isVisible={isLumpVisible}
|
||||
>
|
||||
<SelectedSection selectedSection={displayedSection} />
|
||||
<SelectedSection />
|
||||
</ContentDiv>
|
||||
</div>
|
||||
</LumpDiv>
|
||||
|
|
|
|||
|
|
@ -50,7 +50,7 @@ export function ExploreBlocksButton(props: { blockType: string }) {
|
|||
|
||||
return (
|
||||
<GhostButton
|
||||
className="w-full cursor-pointer rounded px-2 text-center text-gray-400 hover:text-gray-300"
|
||||
className="w-full cursor-pointer rounded px-2 py-0.5 text-center text-gray-400 hover:text-gray-300"
|
||||
style={{
|
||||
fontSize: fontSize(-3),
|
||||
}}
|
||||
|
|
@ -60,7 +60,8 @@ export function ExploreBlocksButton(props: { blockType: string }) {
|
|||
}}
|
||||
>
|
||||
<div className="flex items-center justify-center gap-1">
|
||||
<Icon className="h-3 w-3" /> {text}
|
||||
<Icon className="h-2.5 w-2.5 pr-1" />
|
||||
<span className="text-[11px]">{text}</span>
|
||||
</div>
|
||||
</GhostButton>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -3,44 +3,74 @@ import {
|
|||
PencilIcon,
|
||||
} from "@heroicons/react/24/outline";
|
||||
import { BookmarkIcon as BookmarkSolid } from "@heroicons/react/24/solid";
|
||||
import { SlashCommandDescription } from "core";
|
||||
import { useBookmarkedSlashCommands } from "../../../../hooks/useBookmarkedSlashCommands";
|
||||
import { useAppSelector } from "../../../../redux/hooks";
|
||||
import { fontSize } from "../../../../util";
|
||||
import { useMainEditor } from "../../TipTapEditor";
|
||||
import { useLump } from "../LumpContext";
|
||||
import { ExploreBlocksButton } from "./ExploreBlocksButton";
|
||||
|
||||
interface PromptRowProps {
|
||||
command: string;
|
||||
description: string;
|
||||
prompt: SlashCommandDescription;
|
||||
isBookmarked: boolean;
|
||||
setIsBookmarked: (isBookmarked: boolean) => void;
|
||||
onEdit?: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays a single prompt row with bookmark and edit controls
|
||||
*/
|
||||
function PromptRow({
|
||||
command,
|
||||
description,
|
||||
prompt,
|
||||
isBookmarked,
|
||||
setIsBookmarked,
|
||||
onEdit,
|
||||
}: PromptRowProps) {
|
||||
const { mainEditor } = useMainEditor();
|
||||
const { hideLump } = useLump();
|
||||
|
||||
const handlePromptClick = (e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
mainEditor?.commands.insertPrompt(prompt);
|
||||
hideLump();
|
||||
};
|
||||
|
||||
const handleBookmarkClick = (e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
setIsBookmarked(!isBookmarked);
|
||||
};
|
||||
|
||||
const handleEditClick = (e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
if (onEdit) {
|
||||
onEdit();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className="flex items-center justify-between gap-3"
|
||||
className="hover:bg-list-active hover:text-list-active-foreground flex items-center justify-between gap-3 rounded-md px-2 py-1 hover:cursor-pointer"
|
||||
onClick={handlePromptClick}
|
||||
style={{
|
||||
fontSize: fontSize(-3),
|
||||
}}
|
||||
>
|
||||
<div className="flex min-w-0 gap-2">
|
||||
<span className="text-vscForeground shrink-0">{command}</span>
|
||||
<span className="truncate text-gray-400">{description}</span>
|
||||
<div className="flex min-w-0 flex-col">
|
||||
<span className="text-vscForeground shrink-0 font-medium">
|
||||
{prompt.name}
|
||||
</span>
|
||||
<span className="line-clamp-2 text-[11px] text-gray-400">
|
||||
{prompt.description}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<PencilIcon
|
||||
className="h-3 w-3 cursor-pointer text-gray-400 hover:brightness-125"
|
||||
onClick={onEdit}
|
||||
onClick={handleEditClick}
|
||||
/>
|
||||
<div
|
||||
onClick={() => setIsBookmarked(!isBookmarked)}
|
||||
onClick={handleBookmarkClick}
|
||||
className="cursor-pointer pt-0.5 text-gray-400 hover:brightness-125"
|
||||
>
|
||||
{isBookmarked ? (
|
||||
|
|
@ -54,8 +84,12 @@ function PromptRow({
|
|||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Section that displays all available prompts with bookmarking functionality
|
||||
*/
|
||||
export function PromptsSection() {
|
||||
const { isCommandBookmarked, toggleBookmark } = useBookmarkedSlashCommands();
|
||||
|
||||
const slashCommands = useAppSelector(
|
||||
(state) => state.config.config.slashCommands ?? [],
|
||||
);
|
||||
|
|
@ -74,12 +108,11 @@ export function PromptsSection() {
|
|||
});
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-1">
|
||||
<div className="flex flex-col">
|
||||
{sortedCommands.map((prompt) => (
|
||||
<PromptRow
|
||||
key={prompt.name}
|
||||
command={prompt.name}
|
||||
description={prompt.description}
|
||||
prompt={prompt}
|
||||
isBookmarked={isCommandBookmarked(prompt.name)}
|
||||
setIsBookmarked={() => toggleBookmark(prompt)}
|
||||
onEdit={() => handleEdit(prompt)}
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ import {
|
|||
import { RootState } from "../../../../redux/store";
|
||||
import { fontSize } from "../../../../util";
|
||||
import HeaderButtonWithToolTip from "../../../gui/HeaderButtonWithToolTip";
|
||||
import { useLump } from "../LumpContext";
|
||||
import { ExploreBlocksButton } from "./ExploreBlocksButton";
|
||||
|
||||
interface RuleCardProps {
|
||||
|
|
@ -102,6 +103,7 @@ const RuleCard: React.FC<RuleCardProps> = ({ index, rule, onClick, title }) => {
|
|||
export function RulesSection() {
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const { selectedProfile } = useAuth();
|
||||
const { hideLump } = useLump();
|
||||
|
||||
const rules = useSelector(
|
||||
(state: RootState) => state.config.config.rules ?? [],
|
||||
|
|
@ -117,11 +119,13 @@ export function RulesSection() {
|
|||
}));
|
||||
}, [rules]);
|
||||
|
||||
const openUrl = (path: string) =>
|
||||
const openUrl = (path: string) => {
|
||||
ideMessenger.request("controlPlane/openUrl", {
|
||||
path,
|
||||
orgSlug: undefined,
|
||||
});
|
||||
hideLump();
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
|
|
@ -133,11 +137,12 @@ export function RulesSection() {
|
|||
key={index}
|
||||
index={index}
|
||||
rule={rule.unrolledRule}
|
||||
onClick={() =>
|
||||
onClick={() => {
|
||||
ideMessenger.post("config/openProfile", {
|
||||
profileId: undefined,
|
||||
})
|
||||
}
|
||||
});
|
||||
hideLump();
|
||||
}}
|
||||
title="Locally Defined Rule"
|
||||
/>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import { useLump } from "../LumpContext";
|
||||
import { ContextSection } from "./ContextSection";
|
||||
import DocsSection from "./docs/DocsSection";
|
||||
import { MCPSection } from "./MCPSection";
|
||||
|
|
@ -6,12 +7,13 @@ import { PromptsSection } from "./PromptsSection";
|
|||
import { RulesSection } from "./RulesSection";
|
||||
import { ToolPoliciesSection } from "./tool-policies/ToolPoliciesSection";
|
||||
|
||||
interface SelectedSectionProps {
|
||||
selectedSection: string | null;
|
||||
}
|
||||
/**
|
||||
* Renders the appropriate section based on the selected section in the Lump context
|
||||
*/
|
||||
export function SelectedSection() {
|
||||
const { displayedSection } = useLump();
|
||||
|
||||
export function SelectedSection(props: SelectedSectionProps) {
|
||||
switch (props.selectedSection) {
|
||||
switch (displayedSection) {
|
||||
case "models":
|
||||
return <ModelsSection />;
|
||||
case "rules":
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ import {
|
|||
import { fontSize } from "../../../../../util";
|
||||
import ConfirmationDialog from "../../../../dialogs/ConfirmationDialog";
|
||||
import EditBlockButton from "../../EditBlockButton";
|
||||
import { useLump } from "../../LumpContext";
|
||||
import { StatusIndicator } from "./StatusIndicator";
|
||||
interface IndexingStatusViewerProps {
|
||||
docConfig: SiteIndexingConfig;
|
||||
|
|
@ -24,6 +25,7 @@ function DocsIndexingStatus({
|
|||
}: IndexingStatusViewerProps) {
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const dispatch = useAppDispatch();
|
||||
const { hideLump } = useLump();
|
||||
|
||||
const status = useAppSelector(
|
||||
(store) => store.indexing.indexing.statuses[docConfig.startUrl],
|
||||
|
|
@ -78,7 +80,7 @@ function DocsIndexingStatus({
|
|||
if (hasDeleted) return null;
|
||||
|
||||
return (
|
||||
<div className="mt-2 flex w-full flex-col">
|
||||
<div className="mt-1 flex w-full flex-col">
|
||||
<div
|
||||
className={`flex flex-row items-center justify-between gap-2 text-sm`}
|
||||
>
|
||||
|
|
@ -87,16 +89,10 @@ function DocsIndexingStatus({
|
|||
onClick={() => {
|
||||
if (status?.url) {
|
||||
ideMessenger.post("openUrl", status.url);
|
||||
hideLump();
|
||||
}
|
||||
}}
|
||||
>
|
||||
{docConfig.faviconUrl ? (
|
||||
<img
|
||||
src={docConfig.faviconUrl}
|
||||
alt="doc icon"
|
||||
className="h-3 w-3"
|
||||
/>
|
||||
) : null}
|
||||
<p
|
||||
style={{
|
||||
fontSize: fontSize(-3),
|
||||
|
|
|
|||
|
|
@ -14,7 +14,6 @@ function DocsIndexingStatuses() {
|
|||
(store) => store.indexing.indexing.statuses,
|
||||
);
|
||||
const { selectedProfile } = useAuth();
|
||||
|
||||
const mergedDocs = useMemo(() => {
|
||||
const parsed = selectedProfile?.rawYaml
|
||||
? parseConfigYaml(selectedProfile?.rawYaml ?? "")
|
||||
|
|
|
|||
117
gui/src/components/mainInput/TipTapEditor/MainEditorProvider.tsx
Normal file
117
gui/src/components/mainInput/TipTapEditor/MainEditorProvider.tsx
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
import { Editor } from "@tiptap/react";
|
||||
import { InputModifiers } from "core";
|
||||
import React, {
|
||||
createContext,
|
||||
useContext,
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
|
||||
import { setMainEditorContentTrigger } from "../../../redux/slices/sessionSlice";
|
||||
import { useMainEditorWebviewListeners } from "./useMainEditorWebviewListeners";
|
||||
|
||||
/**
|
||||
* Context for accessing the main editor instance
|
||||
*/
|
||||
interface MainEditorContextType {
|
||||
/** The current main editor instance */
|
||||
mainEditor: Editor | null;
|
||||
/** Set the current main editor instance */
|
||||
setMainEditor: (editor: Editor | null) => void;
|
||||
/** The current input ID */
|
||||
inputId: string | null;
|
||||
/** Set the current input ID */
|
||||
setInputId: (id: string) => void;
|
||||
/** Reference to the execute content function */
|
||||
onEnterRef: React.MutableRefObject<(modifiers: InputModifiers) => void>;
|
||||
}
|
||||
|
||||
const MainEditorContext = createContext<MainEditorContextType | undefined>(
|
||||
undefined,
|
||||
);
|
||||
|
||||
/**
|
||||
* Provider component that maintains a reference to the main editor
|
||||
*/
|
||||
export const MainEditorProvider: React.FC<{ children: React.ReactNode }> = ({
|
||||
children,
|
||||
}) => {
|
||||
const dispatch = useAppDispatch();
|
||||
const [mainEditor, setMainEditorInternal] = useState<Editor | null>(null);
|
||||
const [inputId, setInputId] = useState<string | null>(null);
|
||||
const onEnterRef = useRef<(modifiers: InputModifiers) => void>(() => {});
|
||||
const editorFocusedRef = useRef<boolean>(false);
|
||||
const historyLength = useAppSelector((store) => store.session.history.length);
|
||||
|
||||
// Listen for changes to mainEditorContentTrigger in Redux
|
||||
const mainEditorContentTrigger = useAppSelector(
|
||||
(store) => store.session.mainEditorContentTrigger,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (mainEditor && mainEditorContentTrigger) {
|
||||
queueMicrotask(() => {
|
||||
mainEditor.commands.setContent(mainEditorContentTrigger);
|
||||
});
|
||||
// Clear the trigger after using it
|
||||
dispatch(setMainEditorContentTrigger(undefined));
|
||||
}
|
||||
}, [mainEditor, mainEditorContentTrigger, dispatch]);
|
||||
|
||||
// Update focused ref when editor focus state changes
|
||||
useEffect(() => {
|
||||
if (mainEditor) {
|
||||
const updateFocus = () => {
|
||||
editorFocusedRef.current = mainEditor.isFocused || false;
|
||||
};
|
||||
|
||||
mainEditor.on("focus", updateFocus);
|
||||
mainEditor.on("blur", updateFocus);
|
||||
|
||||
return () => {
|
||||
mainEditor.off("focus", updateFocus);
|
||||
mainEditor.off("blur", updateFocus);
|
||||
};
|
||||
}
|
||||
}, [mainEditor]);
|
||||
|
||||
// Set up main editor webview listeners when we have a valid editor and input ID
|
||||
useMainEditorWebviewListeners({
|
||||
editor: mainEditor,
|
||||
onEnterRef,
|
||||
dispatch,
|
||||
historyLength,
|
||||
inputId: inputId || "",
|
||||
editorFocusedRef,
|
||||
});
|
||||
|
||||
const setMainEditor = (newEditor: Editor | null) => {
|
||||
setMainEditorInternal(newEditor);
|
||||
};
|
||||
|
||||
const value: MainEditorContextType = {
|
||||
mainEditor,
|
||||
setMainEditor,
|
||||
inputId,
|
||||
setInputId,
|
||||
onEnterRef,
|
||||
};
|
||||
|
||||
return (
|
||||
<MainEditorContext.Provider value={value}>
|
||||
{children}
|
||||
</MainEditorContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Hook to access the main editor context
|
||||
*/
|
||||
export const useMainEditor = (): MainEditorContextType => {
|
||||
const context = useContext(MainEditorContext);
|
||||
if (context === undefined) {
|
||||
throw new Error("useMainEditor must be used within a MainEditorProvider");
|
||||
}
|
||||
return context;
|
||||
};
|
||||
|
|
@ -7,19 +7,15 @@ import useIsOSREnabled from "../../../hooks/useIsOSREnabled";
|
|||
import useUpdatingRef from "../../../hooks/useUpdatingRef";
|
||||
import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
|
||||
import { selectDefaultModel } from "../../../redux/slices/configSlice";
|
||||
import {
|
||||
selectIsInEditMode,
|
||||
setMainEditorContentTrigger,
|
||||
} from "../../../redux/slices/sessionSlice";
|
||||
import { selectIsInEditMode } from "../../../redux/slices/sessionSlice";
|
||||
import InputToolbar, { ToolbarOptions } from "../InputToolbar";
|
||||
import { ComboBoxItem } from "../types";
|
||||
import { DragOverlay } from "./DragOverlay";
|
||||
import { createEditorConfig, getPlaceholderText } from "./editorConfig";
|
||||
import { handleImageFile } from "./imageUtils";
|
||||
import { useEditorEventHandlers } from "./keyHandlers";
|
||||
import { InputBoxDiv } from "./StyledComponents";
|
||||
import { DragOverlay, InputBoxDiv } from "./components";
|
||||
import { useMainEditor } from "./MainEditorProvider";
|
||||
import "./TipTapEditor.css";
|
||||
import { useWebviewListeners } from "./useWebviewListeners";
|
||||
import { handleImageFile } from "./utils";
|
||||
import { createEditorConfig, getPlaceholderText } from "./utils/editorConfig";
|
||||
import { useEditorEventHandlers } from "./utils/keyHandlers";
|
||||
|
||||
export interface TipTapEditorProps {
|
||||
availableContextProviders: ContextProviderDescription[];
|
||||
|
|
@ -34,13 +30,17 @@ export interface TipTapEditorProps {
|
|||
toolbarOptions?: ToolbarOptions;
|
||||
placeholder?: string;
|
||||
historyKey: string;
|
||||
|
||||
// TODO: This isn't actually used anywhere in this component, but it appears
|
||||
// to be pulled into some of our TipTap extensions.
|
||||
inputId: string;
|
||||
}
|
||||
|
||||
export const TIPPY_DIV_ID = "tippy-js-div";
|
||||
|
||||
function TipTapEditor(props: TipTapEditorProps) {
|
||||
export function TipTapEditor(props: TipTapEditorProps) {
|
||||
const dispatch = useAppDispatch();
|
||||
const mainEditorContext = useMainEditor();
|
||||
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
|
||||
|
|
@ -57,6 +57,15 @@ function TipTapEditor(props: TipTapEditorProps) {
|
|||
dispatch,
|
||||
});
|
||||
|
||||
// Register the main editor with the provider
|
||||
useEffect(() => {
|
||||
if (props.isMainInput && editor) {
|
||||
mainEditorContext.setMainEditor(editor);
|
||||
mainEditorContext.setInputId(props.inputId);
|
||||
mainEditorContext.onEnterRef.current = onEnterRef.current;
|
||||
}
|
||||
}, [editor, props.isMainInput, props.inputId, mainEditorContext, onEnterRef]);
|
||||
|
||||
const [shouldHideToolbar, setShouldHideToolbar] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
|
|
@ -101,30 +110,6 @@ function TipTapEditor(props: TipTapEditorProps) {
|
|||
}
|
||||
}, [props.isMainInput, isStreaming, editor]);
|
||||
|
||||
// This allows anywhere in the app to set the content of the main input
|
||||
const mainInputContentTrigger = useAppSelector(
|
||||
(store) => store.session.mainEditorContentTrigger,
|
||||
);
|
||||
useEffect(() => {
|
||||
if (!props.isMainInput || !mainInputContentTrigger) {
|
||||
return;
|
||||
}
|
||||
queueMicrotask(() => {
|
||||
editor?.commands.setContent(mainInputContentTrigger);
|
||||
});
|
||||
dispatch(setMainEditorContentTrigger(undefined));
|
||||
}, [editor, props.isMainInput, mainInputContentTrigger]);
|
||||
|
||||
// IDE event listeners
|
||||
useWebviewListeners({
|
||||
editor,
|
||||
onEnterRef,
|
||||
dispatch,
|
||||
historyLength,
|
||||
props,
|
||||
editorFocusedRef,
|
||||
});
|
||||
|
||||
const [showDragOverMsg, setShowDragOverMsg] = useState(false);
|
||||
|
||||
const [activeKey, setActiveKey] = useState<string | null>(null);
|
||||
|
|
@ -150,7 +135,6 @@ function TipTapEditor(props: TipTapEditorProps) {
|
|||
editor,
|
||||
isOSREnabled: isOSREnabled,
|
||||
editorFocusedRef,
|
||||
isInEditMode,
|
||||
setActiveKey,
|
||||
});
|
||||
|
||||
|
|
@ -187,9 +171,6 @@ function TipTapEditor(props: TipTapEditorProps) {
|
|||
setShouldHideToolbar(false);
|
||||
}, [cancelBlurTimeout]);
|
||||
|
||||
// TODO pass clear blur timeout to model and mode selectors
|
||||
// Seems like unnecessary for now?
|
||||
|
||||
return (
|
||||
<InputBoxDiv
|
||||
onFocus={handleFocus}
|
||||
|
|
@ -294,5 +275,3 @@ function TipTapEditor(props: TipTapEditorProps) {
|
|||
</InputBoxDiv>
|
||||
);
|
||||
}
|
||||
|
||||
export default TipTapEditor;
|
||||
|
|
@ -0,0 +1,235 @@
|
|||
import {
|
||||
ChevronDownIcon,
|
||||
EyeSlashIcon,
|
||||
XMarkIcon,
|
||||
} from "@heroicons/react/24/outline";
|
||||
import { EyeIcon } from "@heroicons/react/24/solid";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import styled from "styled-components";
|
||||
import {
|
||||
defaultBorderRadius,
|
||||
lightGray,
|
||||
vscBadgeBackground,
|
||||
vscCommandCenterInactiveBorder,
|
||||
vscEditorBackground,
|
||||
} from "../../..";
|
||||
import { useAppSelector } from "../../../../redux/hooks";
|
||||
import { getFontSize } from "../../../../util";
|
||||
import HeaderButtonWithToolTip from "../../../gui/HeaderButtonWithToolTip";
|
||||
|
||||
const MAX_PREVIEW_HEIGHT = 100;
|
||||
const MAX_EXPANED_PREVIEW_HEIGHT = MAX_PREVIEW_HEIGHT * 3;
|
||||
|
||||
const PreviewDiv = styled.div<{
|
||||
borderColor?: string;
|
||||
}>`
|
||||
background-color: ${vscEditorBackground};
|
||||
border-radius: ${defaultBorderRadius};
|
||||
border: 0.5px solid ${(props) => props.borderColor || lightGray};
|
||||
margin-top: 4px;
|
||||
margin-bottom: 4px;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
|
||||
& div {
|
||||
background-color: ${vscEditorBackground};
|
||||
}
|
||||
`;
|
||||
|
||||
const ContentContainer = styled.div<{ expanded: boolean }>`
|
||||
position: relative;
|
||||
max-height: ${(props) =>
|
||||
props.expanded
|
||||
? `${MAX_EXPANED_PREVIEW_HEIGHT}px`
|
||||
: `${MAX_PREVIEW_HEIGHT}px`};
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
`;
|
||||
|
||||
const ScrollableContent = styled.div<{ shouldShowChevron: boolean }>`
|
||||
overflow-y: auto;
|
||||
padding-bottom: ${(props) => (props.shouldShowChevron ? "24px" : "0px")};
|
||||
`;
|
||||
|
||||
const ChevronContainer = styled.div`
|
||||
position: sticky;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
background: ${vscEditorBackground};
|
||||
padding: 4px 0;
|
||||
z-index: 10;
|
||||
`;
|
||||
|
||||
/**
|
||||
* Props for the ExpandableToolbarPreview component
|
||||
*/
|
||||
interface ExpandableToolbarPreviewProps {
|
||||
/** Title to display in the header */
|
||||
title: string;
|
||||
/** Optional icon to display next to the title */
|
||||
icon?: React.ReactNode;
|
||||
/** ID of the input this preview is associated with (for toolbar hiding logic) */
|
||||
inputId?: string;
|
||||
/** ID of the item being displayed (for toolbar hiding logic) */
|
||||
itemId?: string;
|
||||
/** Whether the preview is initially hidden (overridden if inputId and itemId are provided) */
|
||||
initiallyHidden?: boolean;
|
||||
/** Callback when the delete button is clicked */
|
||||
onDelete?: () => void;
|
||||
/** Callback when the title is clicked */
|
||||
onTitleClick?: (e: React.MouseEvent) => void;
|
||||
/** Border color of the preview */
|
||||
borderColor?: string;
|
||||
/* Whether the preview is selected */
|
||||
isSelected?: boolean;
|
||||
/** Content to display in the preview */
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* A generalized expandable preview component for displaying content with a header and expandable body
|
||||
*/
|
||||
export function ExpandableToolbarPreview(props: ExpandableToolbarPreviewProps) {
|
||||
// Get toolbar visibility state from Redux if inputId and itemId are provided
|
||||
const newestCodeblockForInputId = useAppSelector((store) =>
|
||||
props.inputId
|
||||
? store.session.newestToolbarPreviewForInput[props.inputId]
|
||||
: undefined,
|
||||
);
|
||||
|
||||
const calculatedInitiallyHidden = useMemo(() => {
|
||||
// If initiallyHidden is explicitly set to false, always start visible
|
||||
if (props.initiallyHidden === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Otherwise, use the inputId/itemId logic
|
||||
if (props.inputId && props.itemId) {
|
||||
return newestCodeblockForInputId !== props.itemId;
|
||||
}
|
||||
return props.initiallyHidden ?? false;
|
||||
}, [
|
||||
newestCodeblockForInputId,
|
||||
props.inputId,
|
||||
props.itemId,
|
||||
props.initiallyHidden,
|
||||
]);
|
||||
|
||||
const [hidden, setHidden] = useState(calculatedInitiallyHidden);
|
||||
const [isExpanded, setIsExpanded] = useState(false);
|
||||
|
||||
// Track if user has manually toggled visibility
|
||||
const [userToggled, setUserToggled] = useState(false);
|
||||
|
||||
const contentRef = useRef<HTMLDivElement>(null);
|
||||
const [contentDims, setContentDims] = useState({ width: 0, height: 0 });
|
||||
|
||||
useEffect(() => {
|
||||
// Only update hidden state from props if user hasn't manually toggled
|
||||
// or if initiallyHidden isn't explicitly set to false
|
||||
if (!userToggled || props.initiallyHidden !== false) {
|
||||
setHidden(calculatedInitiallyHidden);
|
||||
}
|
||||
}, [calculatedInitiallyHidden, userToggled, props.initiallyHidden]);
|
||||
useEffect(() => {
|
||||
const resizeObserver = new ResizeObserver(() => {
|
||||
setContentDims({
|
||||
width: contentRef.current?.scrollWidth ?? 0,
|
||||
height: contentRef.current?.scrollHeight ?? 0,
|
||||
});
|
||||
});
|
||||
|
||||
if (contentRef.current) {
|
||||
resizeObserver.observe(contentRef.current);
|
||||
}
|
||||
|
||||
return () => {
|
||||
resizeObserver.disconnect();
|
||||
};
|
||||
}, [contentRef]);
|
||||
|
||||
return (
|
||||
<PreviewDiv
|
||||
spellCheck={false}
|
||||
borderColor={
|
||||
props.isSelected ? vscBadgeBackground : vscCommandCenterInactiveBorder
|
||||
}
|
||||
className="find-widget-skip !my-0"
|
||||
>
|
||||
<div
|
||||
className="border-b-vsc-commandCenter-inactiveBorder m-0 flex cursor-pointer items-center justify-between break-all border-0 border-b-[1px] border-solid px-[5px] py-1.5 hover:opacity-90"
|
||||
style={{
|
||||
fontSize: getFontSize() - 3,
|
||||
}}
|
||||
onClick={() => {
|
||||
setUserToggled(true);
|
||||
setHidden(!hidden);
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className="flex items-center gap-1 text-[11px] hover:underline"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
if (props.onTitleClick) {
|
||||
props.onTitleClick(e);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{props.icon}
|
||||
{props.title}
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<HeaderButtonWithToolTip text={hidden ? "Show" : "Hide"}>
|
||||
{hidden ? (
|
||||
<EyeIcon className="h-2.5 w-2.5" />
|
||||
) : (
|
||||
<EyeSlashIcon className="h-2.5 w-2.5" />
|
||||
)}
|
||||
</HeaderButtonWithToolTip>
|
||||
{props.onDelete && (
|
||||
<HeaderButtonWithToolTip
|
||||
text="Delete"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
props.onDelete?.();
|
||||
}}
|
||||
>
|
||||
<XMarkIcon className="h-2.5 w-2.5" />
|
||||
</HeaderButtonWithToolTip>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!hidden && (
|
||||
<ContentContainer expanded={isExpanded}>
|
||||
<ScrollableContent
|
||||
ref={contentRef}
|
||||
shouldShowChevron={contentDims.height > MAX_PREVIEW_HEIGHT}
|
||||
>
|
||||
{props.children}
|
||||
</ScrollableContent>
|
||||
|
||||
{contentDims.height > MAX_PREVIEW_HEIGHT && (
|
||||
<ChevronContainer>
|
||||
<HeaderButtonWithToolTip
|
||||
text={isExpanded ? "Collapse" : "Expand"}
|
||||
>
|
||||
<ChevronDownIcon
|
||||
className="h-3 w-3 transition-all"
|
||||
style={{
|
||||
transform: isExpanded ? "rotate(180deg)" : "",
|
||||
}}
|
||||
onClick={() => setIsExpanded((v) => !v)}
|
||||
/>
|
||||
</HeaderButtonWithToolTip>
|
||||
</ChevronContainer>
|
||||
)}
|
||||
</ContentContainer>
|
||||
)}
|
||||
</PreviewDiv>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
import {
|
||||
NodeViewWrapper as TiptapNodeViewWrapper,
|
||||
NodeViewWrapperProps as TiptapNodeViewWrapperProps,
|
||||
} from "@tiptap/react";
|
||||
import React from "react";
|
||||
|
||||
interface NodeViewWrapperProps {
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
export const NodeViewWrapper: React.FC<NodeViewWrapperProps> = ({
|
||||
children,
|
||||
}) => {
|
||||
// Not setting this as a "p" will cause issues with foreign keyboards
|
||||
// See https://github.com/continuedev/continue/issues/3199
|
||||
const nodeViewWrapperTag: TiptapNodeViewWrapperProps["as"] = "p";
|
||||
|
||||
return (
|
||||
<TiptapNodeViewWrapper className="my-1.5" as={nodeViewWrapperTag}>
|
||||
{children}
|
||||
</TiptapNodeViewWrapper>
|
||||
);
|
||||
};
|
||||
|
|
@ -8,8 +8,8 @@ import {
|
|||
vscForeground,
|
||||
vscInputBackground,
|
||||
vscInputBorderFocus,
|
||||
} from "../..";
|
||||
import { getFontSize } from "../../../util";
|
||||
} from "../../..";
|
||||
import { getFontSize } from "../../../../util";
|
||||
|
||||
export const InputBoxDiv = styled.div<{}>`
|
||||
resize: none;
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
export * from "./DragOverlay";
|
||||
export * from "./ExpandableToolbarPreview";
|
||||
export * from "./StyledComponents";
|
||||
|
|
@ -1,25 +1,16 @@
|
|||
import { mergeAttributes, Node } from "@tiptap/core";
|
||||
import { DOMOutputSpec, Node as ProseMirrorNode } from "@tiptap/pm/model";
|
||||
import { PluginKey } from "@tiptap/pm/state";
|
||||
import Suggestion, { SuggestionOptions } from "@tiptap/suggestion";
|
||||
|
||||
export type MentionOptions = {
|
||||
HTMLAttributes: Record<string, any>;
|
||||
renderHTML: (props: {
|
||||
options: MentionOptions;
|
||||
node: ProseMirrorNode;
|
||||
}) => DOMOutputSpec;
|
||||
suggestion: Omit<SuggestionOptions, "editor">;
|
||||
};
|
||||
|
||||
export const AddCodeToEditPluginKey = new PluginKey("add-code-to-edit");
|
||||
import Suggestion from "@tiptap/suggestion";
|
||||
import { MentionOptions } from "./types";
|
||||
|
||||
export const AddCodeToEdit = Node.create<MentionOptions>({
|
||||
name: "add-code-to-edit",
|
||||
|
||||
addOptions() {
|
||||
return {
|
||||
HTMLAttributes: {},
|
||||
HTMLAttributes: {
|
||||
class: "add-code-to-edit",
|
||||
},
|
||||
renderHTML({ options, node }) {
|
||||
return [
|
||||
"span",
|
||||
|
|
@ -29,7 +20,7 @@ export const AddCodeToEdit = Node.create<MentionOptions>({
|
|||
},
|
||||
suggestion: {
|
||||
char: "#",
|
||||
pluginKey: AddCodeToEditPluginKey,
|
||||
pluginKey: new PluginKey(this.name),
|
||||
allow: ({ state, range }) => {
|
||||
const $from = state.doc.resolve(range.from);
|
||||
const type = state.schema.nodes[this.name];
|
||||
|
|
@ -1,9 +1,9 @@
|
|||
import { mergeAttributes, Node } from "@tiptap/core";
|
||||
import { ReactNodeViewRenderer } from "@tiptap/react";
|
||||
import { CodeBlockComponent } from "../CodeBlockComponent";
|
||||
import { CodeBlockPreview } from "./CodeBlockPreview";
|
||||
|
||||
export const CodeBlockExtension = Node.create({
|
||||
name: "codeBlock",
|
||||
export const CodeBlock = Node.create({
|
||||
name: "code-block",
|
||||
|
||||
group: "block",
|
||||
|
||||
|
|
@ -37,6 +37,6 @@ export const CodeBlockExtension = Node.create({
|
|||
},
|
||||
|
||||
addNodeView() {
|
||||
return ReactNodeViewRenderer(CodeBlockComponent);
|
||||
return ReactNodeViewRenderer(CodeBlockPreview);
|
||||
},
|
||||
});
|
||||
|
|
@ -0,0 +1,76 @@
|
|||
import { NodeViewProps } from "@tiptap/react";
|
||||
import { ContextItemWithId } from "core";
|
||||
import { ctxItemToRifWithContents } from "core/commands/util";
|
||||
import { dedent, getMarkdownLanguageTagForFile } from "core/util";
|
||||
import { useContext, useMemo } from "react";
|
||||
import { vscBadgeBackground } from "../../../..";
|
||||
import { IdeMessengerContext } from "../../../../../context/IdeMessenger";
|
||||
import FileIcon from "../../../../FileIcon";
|
||||
import StyledMarkdownPreview from "../../../../markdown/StyledMarkdownPreview";
|
||||
import { ExpandableToolbarPreview } from "../../components/ExpandableToolbarPreview";
|
||||
import { NodeViewWrapper } from "../../components/NodeViewWrapper";
|
||||
|
||||
const backticksRegex = /`{3,}/gm;
|
||||
|
||||
/**
|
||||
* Component for displaying a code block in the TipTap editor
|
||||
*/
|
||||
export const CodeBlockPreview = ({
|
||||
node,
|
||||
deleteNode,
|
||||
selected,
|
||||
}: NodeViewProps) => {
|
||||
const item: ContextItemWithId = node.attrs.item;
|
||||
const inputId = node.attrs.inputId;
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
|
||||
const content = useMemo(() => {
|
||||
return dedent`${item.content}`;
|
||||
}, [item.content]);
|
||||
|
||||
const fence = useMemo(() => {
|
||||
const backticks = content.match(backticksRegex);
|
||||
return backticks ? backticks.sort().at(-1) + "`" : "```";
|
||||
}, [content]);
|
||||
|
||||
const handleTitleClick = (e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
|
||||
if (item.id.providerTitle === "file" && item.uri?.value) {
|
||||
ideMessenger.post("showFile", {
|
||||
filepath: item.uri.value,
|
||||
});
|
||||
} else if (item.id.providerTitle === "code") {
|
||||
const rif = ctxItemToRifWithContents(item, true);
|
||||
ideMessenger.ide.showLines(
|
||||
rif.filepath,
|
||||
rif.range.start.line,
|
||||
rif.range.end.line,
|
||||
);
|
||||
} else {
|
||||
ideMessenger.post("showVirtualFile", {
|
||||
content: item.content,
|
||||
name: item.name,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<NodeViewWrapper>
|
||||
<ExpandableToolbarPreview
|
||||
isSelected={selected}
|
||||
title={item.name}
|
||||
icon={<FileIcon height="16px" width="16px" filename={item.name} />}
|
||||
inputId={inputId}
|
||||
itemId={item.id.itemId}
|
||||
onDelete={() => deleteNode()}
|
||||
borderColor={selected ? vscBadgeBackground : undefined}
|
||||
onTitleClick={handleTitleClick}
|
||||
>
|
||||
<StyledMarkdownPreview
|
||||
source={`${fence}${getMarkdownLanguageTagForFile(item.name)} ${item.description}\n${content}\n${fence}`}
|
||||
/>
|
||||
</ExpandableToolbarPreview>
|
||||
</NodeViewWrapper>
|
||||
);
|
||||
};
|
||||
|
|
@ -0,0 +1 @@
|
|||
export * from "./CodeBlock";
|
||||
|
|
@ -1,25 +1,17 @@
|
|||
import { mergeAttributes, Node } from "@tiptap/core";
|
||||
import { DOMOutputSpec, Node as ProseMirrorNode } from "@tiptap/pm/model";
|
||||
import { PluginKey } from "@tiptap/pm/state";
|
||||
import Suggestion, { SuggestionOptions } from "@tiptap/suggestion";
|
||||
|
||||
export type MentionOptions = {
|
||||
HTMLAttributes: Record<string, any>;
|
||||
renderHTML: (props: {
|
||||
options: MentionOptions;
|
||||
node: ProseMirrorNode;
|
||||
}) => DOMOutputSpec;
|
||||
suggestion: Omit<SuggestionOptions, "editor">;
|
||||
};
|
||||
|
||||
export const MentionPluginKey = new PluginKey("mention");
|
||||
import Suggestion from "@tiptap/suggestion";
|
||||
import { MentionOptions } from "./types";
|
||||
|
||||
export const Mention = Node.create<MentionOptions>({
|
||||
name: "mention",
|
||||
|
||||
addOptions() {
|
||||
return {
|
||||
HTMLAttributes: {},
|
||||
HTMLAttributes: {
|
||||
class: "mention",
|
||||
},
|
||||
|
||||
renderHTML({ options, node }) {
|
||||
return [
|
||||
"span",
|
||||
|
|
@ -29,7 +21,7 @@ export const Mention = Node.create<MentionOptions>({
|
|||
},
|
||||
suggestion: {
|
||||
char: "@",
|
||||
pluginKey: MentionPluginKey,
|
||||
pluginKey: new PluginKey(this.name),
|
||||
command: ({ editor, range, props }) => {
|
||||
// increase range.to by one when the next node is of type "text"
|
||||
// and starts with a space character
|
||||
|
|
@ -0,0 +1,130 @@
|
|||
import { mergeAttributes, Node } from "@tiptap/core";
|
||||
import { Node as ProseMirrorNode } from "@tiptap/pm/model";
|
||||
import { ReactNodeViewRenderer } from "@tiptap/react";
|
||||
import { ContextItemWithId, SlashCommandDescription } from "core";
|
||||
import { MAIN_EDITOR_INPUT_ID } from "../../../../../pages/gui/Chat";
|
||||
import { PromptBlockPreview } from "./PromptBlockPreview";
|
||||
|
||||
export interface PromptBlockOptions {
|
||||
HTMLAttributes: Record<string, any>;
|
||||
}
|
||||
|
||||
export interface PromptBlockAttributes {
|
||||
item: ContextItemWithId;
|
||||
inputId: string;
|
||||
}
|
||||
|
||||
declare module "@tiptap/core" {
|
||||
interface Commands<ReturnType> {
|
||||
promptBlock: {
|
||||
/**
|
||||
* Insert a prompt block into the editor
|
||||
*/
|
||||
insertPrompt: (item: SlashCommandDescription) => ReturnType;
|
||||
|
||||
/**
|
||||
* Clear all prompt blocks from the editor
|
||||
*/
|
||||
clearPrompt: () => ReturnType;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extension for adding prompt blocks to the TipTap editor
|
||||
*/
|
||||
export const PromptBlock = Node.create<PromptBlockOptions>({
|
||||
name: "prompt-block",
|
||||
group: "block",
|
||||
content: "inline*",
|
||||
|
||||
addOptions() {
|
||||
return {
|
||||
HTMLAttributes: {
|
||||
class: "prompt-block",
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
addAttributes() {
|
||||
return {
|
||||
item: {
|
||||
default: null,
|
||||
},
|
||||
inputId: {
|
||||
default: null,
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
parseHTML() {
|
||||
return [
|
||||
{
|
||||
tag: "prompt-block",
|
||||
},
|
||||
];
|
||||
},
|
||||
|
||||
renderHTML({ HTMLAttributes }) {
|
||||
return ["prompt-block", mergeAttributes(HTMLAttributes), 0];
|
||||
},
|
||||
|
||||
addNodeView() {
|
||||
return ReactNodeViewRenderer(PromptBlockPreview);
|
||||
},
|
||||
|
||||
addCommands() {
|
||||
return {
|
||||
insertPrompt:
|
||||
(prompt: SlashCommandDescription) =>
|
||||
({ chain }) => {
|
||||
const item: ContextItemWithId = {
|
||||
content: prompt.prompt ?? "",
|
||||
name: prompt.name,
|
||||
description: prompt.description,
|
||||
id: {
|
||||
providerTitle: "prompt",
|
||||
itemId: prompt.name,
|
||||
},
|
||||
};
|
||||
|
||||
return chain()
|
||||
.insertContentAt(0, {
|
||||
type: this.name,
|
||||
attrs: {
|
||||
item,
|
||||
inputId: MAIN_EDITOR_INPUT_ID,
|
||||
},
|
||||
})
|
||||
.focus("end")
|
||||
.run();
|
||||
},
|
||||
|
||||
// TODO: This could probably be greatly simplified with something along the lines of
|
||||
// `editor.commands.deleteNode(this.name)`, but was unable to get it working
|
||||
clearPrompt:
|
||||
() =>
|
||||
({ state, commands }) => {
|
||||
// Find all prompt-block nodes in the document
|
||||
const promptNodes: { pos: number; node: ProseMirrorNode }[] = [];
|
||||
state.doc.descendants((node, pos) => {
|
||||
if (node.type.name === this.name) {
|
||||
promptNodes.push({ pos, node });
|
||||
return false; // Don't descend into this node
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
// Delete all found prompt blocks
|
||||
// We process them in reverse order so that deleting one doesn't affect the position of others
|
||||
for (let i = promptNodes.length - 1; i >= 0; i--) {
|
||||
const { pos, node } = promptNodes[i];
|
||||
commands.deleteRange({ from: pos, to: pos + node.nodeSize });
|
||||
}
|
||||
|
||||
// Return true if we deleted any nodes
|
||||
return promptNodes.length > 0;
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
|
|
@ -0,0 +1,51 @@
|
|||
import { ChatBubbleLeftIcon } from "@heroicons/react/24/outline";
|
||||
import { NodeViewProps } from "@tiptap/react";
|
||||
import { useContext } from "react";
|
||||
import { IdeMessengerContext } from "../../../../../context/IdeMessenger";
|
||||
import { ExpandableToolbarPreview } from "../../components/ExpandableToolbarPreview";
|
||||
import { NodeViewWrapper } from "../../components/NodeViewWrapper";
|
||||
import { PromptBlockAttributes } from "./PromptBlock";
|
||||
|
||||
/**
|
||||
* Component for prompt blocks in the Tiptap editor
|
||||
*/
|
||||
export const PromptBlockPreview = ({
|
||||
node,
|
||||
selected,
|
||||
editor,
|
||||
}: NodeViewProps) => {
|
||||
const { item, inputId } = node.attrs as PromptBlockAttributes;
|
||||
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
|
||||
const handleTitleClick = (e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
ideMessenger.post("showVirtualFile", {
|
||||
content: item.content,
|
||||
name: item.name,
|
||||
});
|
||||
};
|
||||
|
||||
const handleDelete = () => {
|
||||
editor.commands.clearPrompt();
|
||||
};
|
||||
|
||||
return (
|
||||
<NodeViewWrapper>
|
||||
<ExpandableToolbarPreview
|
||||
initiallyHidden={false}
|
||||
isSelected={selected}
|
||||
title={item.name}
|
||||
icon={<ChatBubbleLeftIcon className="h-3 w-3 pl-1 pr-0.5" />}
|
||||
inputId={inputId}
|
||||
itemId={item.id.itemId}
|
||||
onDelete={handleDelete}
|
||||
onTitleClick={handleTitleClick}
|
||||
>
|
||||
<div className="whitespace-pre-wrap px-3 py-1 text-xs">
|
||||
{item.content}
|
||||
</div>
|
||||
</ExpandableToolbarPreview>
|
||||
</NodeViewWrapper>
|
||||
);
|
||||
};
|
||||
|
|
@ -0,0 +1 @@
|
|||
export * from "./PromptBlock";
|
||||
|
|
@ -0,0 +1,58 @@
|
|||
// Adapted from SlashCommand extension (@tiptap/extension-mention/src/mention.ts)
|
||||
|
||||
import { Node } from "@tiptap/core";
|
||||
import { PluginKey } from "@tiptap/pm/state";
|
||||
import Suggestion, { SuggestionOptions } from "@tiptap/suggestion";
|
||||
import { ComboBoxItem } from "../../types";
|
||||
|
||||
export type SlashCommandOptions = {
|
||||
suggestion: Omit<SuggestionOptions<ComboBoxItem, ComboBoxItem>, "editor">;
|
||||
};
|
||||
|
||||
export const SlashCommand = Node.create<SlashCommandOptions>({
|
||||
name: "slash-command",
|
||||
|
||||
addOptions() {
|
||||
return {
|
||||
suggestion: {
|
||||
char: "/",
|
||||
pluginKey: new PluginKey(this.name),
|
||||
startOfLine: true,
|
||||
command: ({ editor, range, props }) => {
|
||||
// First delete the slash character and any text after it
|
||||
editor.chain().focus().deleteRange(range).run();
|
||||
|
||||
editor.commands.insertPrompt({
|
||||
name: props.title,
|
||||
description: props.description,
|
||||
prompt: props.content,
|
||||
});
|
||||
},
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
group: "inline",
|
||||
inline: true,
|
||||
selectable: false,
|
||||
atom: true,
|
||||
|
||||
// We don't need attributes since we won't be rendering any node
|
||||
addAttributes() {
|
||||
return {};
|
||||
},
|
||||
|
||||
// No need to parse HTML since we're not rendering anything
|
||||
parseHTML() {
|
||||
return [];
|
||||
},
|
||||
|
||||
addProseMirrorPlugins() {
|
||||
return [
|
||||
Suggestion({
|
||||
editor: this.editor,
|
||||
...this.options.suggestion,
|
||||
}),
|
||||
];
|
||||
},
|
||||
});
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
export * from "./AddCodeToEdit";
|
||||
export * from "./CodeBlock";
|
||||
export * from "./Mention";
|
||||
export * from "./Prompt";
|
||||
export * from "./SlashCommand";
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
import { DOMOutputSpec, Node as ProseMirrorNode } from "@tiptap/pm/model";
|
||||
import { SuggestionOptions } from "@tiptap/suggestion";
|
||||
|
||||
export type MentionOptions = {
|
||||
HTMLAttributes: Record<string, any>;
|
||||
renderHTML: (props: {
|
||||
options: MentionOptions;
|
||||
node: ProseMirrorNode;
|
||||
}) => DOMOutputSpec;
|
||||
suggestion: Omit<SuggestionOptions, "editor">;
|
||||
};
|
||||
4
gui/src/components/mainInput/TipTapEditor/index.ts
Normal file
4
gui/src/components/mainInput/TipTapEditor/index.ts
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
export * from "./extensions";
|
||||
export * from "./MainEditorProvider";
|
||||
export * from "./TipTapEditor";
|
||||
export * from "./utils";
|
||||
|
|
@ -1,43 +1,50 @@
|
|||
import { Editor } from "@tiptap/core";
|
||||
import { Editor } from "@tiptap/react";
|
||||
import { InputModifiers } from "core";
|
||||
import { rifWithContentsToContextItem } from "core/commands/util";
|
||||
import { MutableRefObject } from "react";
|
||||
import { useWebviewListener } from "../../../hooks/useWebviewListener";
|
||||
import {
|
||||
clearCodeToEdit,
|
||||
setNewestCodeblocksForInput,
|
||||
setNewestToolbarPreviewForInput,
|
||||
} from "../../../redux/slices/sessionSlice";
|
||||
import { AppDispatch } from "../../../redux/store";
|
||||
import { loadSession, saveCurrentSession } from "../../../redux/thunks/session";
|
||||
import { TipTapEditorProps } from "./TipTapEditor";
|
||||
import { CodeBlock, PromptBlock } from "./extensions";
|
||||
|
||||
export function useWebviewListeners(options: {
|
||||
/**
|
||||
* Hook for setting up main editor specific webview listeners
|
||||
*/
|
||||
export function useMainEditorWebviewListeners({
|
||||
editor,
|
||||
onEnterRef,
|
||||
dispatch,
|
||||
historyLength,
|
||||
inputId,
|
||||
editorFocusedRef,
|
||||
}: {
|
||||
editor: Editor | null;
|
||||
onEnterRef: MutableRefObject<(modifiers: InputModifiers) => void>;
|
||||
dispatch: AppDispatch;
|
||||
historyLength: number;
|
||||
props: TipTapEditorProps;
|
||||
inputId: string;
|
||||
editorFocusedRef: MutableRefObject<boolean | undefined>;
|
||||
}) {
|
||||
const {
|
||||
editor,
|
||||
onEnterRef,
|
||||
dispatch,
|
||||
historyLength,
|
||||
props,
|
||||
editorFocusedRef,
|
||||
} = options;
|
||||
useWebviewListener(
|
||||
"isContinueInputFocused",
|
||||
async () => {
|
||||
return !!editorFocusedRef.current;
|
||||
},
|
||||
[editorFocusedRef],
|
||||
);
|
||||
|
||||
useWebviewListener(
|
||||
"userInput",
|
||||
async (data) => {
|
||||
if (!props.isMainInput) {
|
||||
return;
|
||||
}
|
||||
editor?.commands.insertContent(data.input);
|
||||
if (!editor) return;
|
||||
editor.commands.insertContent(data.input);
|
||||
onEnterRef.current({ useCodebase: false, noContext: true });
|
||||
},
|
||||
[editor, onEnterRef.current, props.isMainInput],
|
||||
[editor, onEnterRef.current],
|
||||
);
|
||||
|
||||
useWebviewListener("jetbrains/editorInsetRefresh", async () => {
|
||||
|
|
@ -46,11 +53,7 @@ export function useWebviewListeners(options: {
|
|||
|
||||
useWebviewListener(
|
||||
"focusContinueInput",
|
||||
async (data) => {
|
||||
if (!props.isMainInput) {
|
||||
return;
|
||||
}
|
||||
|
||||
async () => {
|
||||
dispatch(clearCodeToEdit());
|
||||
|
||||
if (historyLength > 0) {
|
||||
|
|
@ -61,52 +64,46 @@ export function useWebviewListeners(options: {
|
|||
}),
|
||||
);
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
editor?.commands.blur();
|
||||
editor?.commands.focus("end");
|
||||
}, 20);
|
||||
},
|
||||
[historyLength, editor, props.isMainInput],
|
||||
[historyLength, editor, dispatch],
|
||||
);
|
||||
|
||||
useWebviewListener(
|
||||
"focusContinueInputWithoutClear",
|
||||
async () => {
|
||||
if (!props.isMainInput) {
|
||||
return;
|
||||
}
|
||||
setTimeout(() => {
|
||||
editor?.commands.focus("end");
|
||||
}, 20);
|
||||
},
|
||||
[editor, props.isMainInput],
|
||||
[editor],
|
||||
);
|
||||
|
||||
useWebviewListener(
|
||||
"focusContinueInputWithNewSession",
|
||||
async () => {
|
||||
if (!props.isMainInput) {
|
||||
return;
|
||||
}
|
||||
await dispatch(
|
||||
saveCurrentSession({
|
||||
openNewSession: true,
|
||||
generateTitle: true,
|
||||
}),
|
||||
);
|
||||
|
||||
setTimeout(() => {
|
||||
editor?.commands.focus("end");
|
||||
}, 20);
|
||||
},
|
||||
[editor, props.isMainInput],
|
||||
[editor, dispatch],
|
||||
);
|
||||
|
||||
useWebviewListener(
|
||||
"highlightedCode",
|
||||
async (data) => {
|
||||
if (!props.isMainInput || !editor) {
|
||||
return;
|
||||
}
|
||||
if (!editor) return;
|
||||
|
||||
const contextItem = rifWithContentsToContextItem(
|
||||
data.rangeInFileWithContents,
|
||||
|
|
@ -114,31 +111,38 @@ export function useWebviewListeners(options: {
|
|||
|
||||
let index = 0;
|
||||
for (const el of editor.getJSON()?.content ?? []) {
|
||||
// Prevent exact duplicate code blocks
|
||||
if (el.attrs?.item?.name === contextItem.name) {
|
||||
return; // Prevent exact duplicate code blocks
|
||||
return;
|
||||
}
|
||||
if (el.type === "codeBlock") {
|
||||
|
||||
if (el.type === CodeBlock.name || el.type === PromptBlock.name) {
|
||||
index += 2;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
debugger;
|
||||
|
||||
editor
|
||||
.chain()
|
||||
.insertContentAt(index, {
|
||||
type: "codeBlock",
|
||||
type: CodeBlock.name,
|
||||
attrs: {
|
||||
item: contextItem,
|
||||
inputId: props.inputId,
|
||||
inputId,
|
||||
},
|
||||
})
|
||||
.run();
|
||||
|
||||
dispatch(
|
||||
setNewestCodeblocksForInput({
|
||||
inputId: props.inputId,
|
||||
setNewestToolbarPreviewForInput({
|
||||
inputId,
|
||||
contextItemId: contextItem.id.itemId,
|
||||
}),
|
||||
);
|
||||
|
||||
if (data.prompt) {
|
||||
editor.commands.focus("end");
|
||||
editor.commands.insertContent(data.prompt);
|
||||
|
|
@ -153,52 +157,42 @@ export function useWebviewListeners(options: {
|
|||
editor.commands.focus("end");
|
||||
}, 20);
|
||||
},
|
||||
[editor, props.isMainInput, historyLength, onEnterRef.current],
|
||||
[editor, inputId, onEnterRef.current],
|
||||
);
|
||||
|
||||
useWebviewListener(
|
||||
"focusEdit",
|
||||
async () => {
|
||||
if (!props.isMainInput) {
|
||||
return;
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
editor?.commands.focus("end");
|
||||
}, 20);
|
||||
},
|
||||
[editor, props.isMainInput],
|
||||
[editor],
|
||||
);
|
||||
|
||||
useWebviewListener(
|
||||
"focusEditWithoutClear",
|
||||
async () => {
|
||||
if (!props.isMainInput) {
|
||||
return;
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
editor?.commands.focus("end");
|
||||
}, 2000);
|
||||
},
|
||||
[editor, props.isMainInput],
|
||||
[editor],
|
||||
);
|
||||
|
||||
useWebviewListener(
|
||||
"isContinueInputFocused",
|
||||
async () => {
|
||||
return props.isMainInput && !!editorFocusedRef.current;
|
||||
return !!editorFocusedRef.current;
|
||||
},
|
||||
[editorFocusedRef, props.isMainInput],
|
||||
!props.isMainInput,
|
||||
[editorFocusedRef],
|
||||
);
|
||||
|
||||
useWebviewListener(
|
||||
"focusContinueSessionId",
|
||||
async (data) => {
|
||||
if (!props.isMainInput || !data.sessionId) {
|
||||
return;
|
||||
}
|
||||
if (!data.sessionId) return;
|
||||
|
||||
await dispatch(
|
||||
loadSession({
|
||||
sessionId: data.sessionId,
|
||||
|
|
@ -206,6 +200,6 @@ export function useWebviewListeners(options: {
|
|||
}),
|
||||
);
|
||||
},
|
||||
[props.isMainInput],
|
||||
[],
|
||||
);
|
||||
}
|
||||
|
|
@ -11,32 +11,29 @@ import { InputModifiers } from "core";
|
|||
import { modelSupportsImages } from "core/llm/autodetect";
|
||||
import { usePostHog } from "posthog-js/react";
|
||||
import { useRef } from "react";
|
||||
import { IIdeMessenger } from "../../../context/IdeMessenger";
|
||||
import { useSubmenuContextProviders } from "../../../context/SubmenuContextProviders";
|
||||
import { useInputHistory } from "../../../hooks/useInputHistory";
|
||||
import useUpdatingRef from "../../../hooks/useUpdatingRef";
|
||||
import { useAppSelector } from "../../../redux/hooks";
|
||||
import { selectUseActiveFile } from "../../../redux/selectors";
|
||||
import { selectDefaultModel } from "../../../redux/slices/configSlice";
|
||||
import {
|
||||
getContextProviderDropdownOptions,
|
||||
getSlashCommandDropdownOptions,
|
||||
} from ".";
|
||||
import { IIdeMessenger } from "../../../../context/IdeMessenger";
|
||||
import { useSubmenuContextProviders } from "../../../../context/SubmenuContextProviders";
|
||||
import { useInputHistory } from "../../../../hooks/useInputHistory";
|
||||
import useUpdatingRef from "../../../../hooks/useUpdatingRef";
|
||||
import { useAppSelector } from "../../../../redux/hooks";
|
||||
import { selectUseActiveFile } from "../../../../redux/selectors";
|
||||
import { selectDefaultModel } from "../../../../redux/slices/configSlice";
|
||||
import {
|
||||
addCodeToEdit,
|
||||
selectHasCodeToEdit,
|
||||
selectIsInEditMode,
|
||||
} from "../../../redux/slices/sessionSlice";
|
||||
import { AppDispatch } from "../../../redux/store";
|
||||
import { exitEditMode } from "../../../redux/thunks";
|
||||
import { loadLastSession } from "../../../redux/thunks/session";
|
||||
import { getFontSize } from "../../../util";
|
||||
import { AddCodeToEdit } from "./extensions/AddCodeToEditExtension";
|
||||
import { CodeBlockExtension } from "./extensions/CodeBlockExtension";
|
||||
import { SlashCommand } from "./extensions/CommandsExtension";
|
||||
import { Mention } from "./extensions/MentionExtension";
|
||||
import {
|
||||
getContextProviderDropdownOptions,
|
||||
getSlashCommandDropdownOptions,
|
||||
} from "./getSuggestion";
|
||||
} from "../../../../redux/slices/sessionSlice";
|
||||
import { AppDispatch } from "../../../../redux/store";
|
||||
import { exitEditMode } from "../../../../redux/thunks";
|
||||
import { loadLastSession } from "../../../../redux/thunks/session";
|
||||
import { getFontSize } from "../../../../util";
|
||||
import * as ContinueExtensions from "../extensions";
|
||||
import { TipTapEditorProps } from "../TipTapEditor";
|
||||
import { handleImageFile } from "./imageUtils";
|
||||
import { TipTapEditorProps } from "./TipTapEditor";
|
||||
|
||||
export function getPlaceholderText(
|
||||
placeholder: TipTapEditorProps["placeholder"],
|
||||
|
|
@ -63,7 +60,6 @@ export function createEditorConfig(options: {
|
|||
|
||||
const posthog = usePostHog();
|
||||
|
||||
// #region Selectors
|
||||
const { getSubmenuContextItems } = useSubmenuContextProviders();
|
||||
const defaultModel = useAppSelector(selectDefaultModel);
|
||||
const isStreaming = useAppSelector((state) => state.session.isStreaming);
|
||||
|
|
@ -72,9 +68,7 @@ export function createEditorConfig(options: {
|
|||
const isInEditMode = useAppSelector(selectIsInEditMode);
|
||||
const hasCodeToEdit = useAppSelector(selectHasCodeToEdit);
|
||||
const isEditModeAndNoCodeToEdit = isInEditMode && !hasCodeToEdit;
|
||||
// #endregion
|
||||
|
||||
// #region Refs
|
||||
const inSubmenuRef = useRef<string | undefined>(undefined);
|
||||
const inDropdownRef = useRef(false);
|
||||
const defaultModelRef = useUpdatingRef(defaultModel);
|
||||
|
|
@ -90,8 +84,6 @@ export function createEditorConfig(options: {
|
|||
);
|
||||
const { prevRef, nextRef, addRef } = useInputHistory(props.historyKey);
|
||||
|
||||
// #endregion
|
||||
|
||||
const enterSubmenu = async (editor: Editor, providerId: string) => {
|
||||
const contents = editor.getText();
|
||||
const indexOfAt = contents.lastIndexOf("@");
|
||||
|
|
@ -294,10 +286,7 @@ export function createEditorConfig(options: {
|
|||
},
|
||||
}),
|
||||
Text,
|
||||
Mention.configure({
|
||||
HTMLAttributes: {
|
||||
class: "mention",
|
||||
},
|
||||
ContinueExtensions.Mention.configure({
|
||||
suggestion: getContextProviderDropdownOptions(
|
||||
availableContextProvidersRef,
|
||||
getSubmenuContextItemsRef,
|
||||
|
|
@ -307,15 +296,8 @@ export function createEditorConfig(options: {
|
|||
inSubmenuRef,
|
||||
ideMessenger,
|
||||
),
|
||||
renderHTML: (props) => {
|
||||
return `@${props.node.attrs.label || props.node.attrs.id}`;
|
||||
},
|
||||
}),
|
||||
|
||||
AddCodeToEdit.configure({
|
||||
HTMLAttributes: {
|
||||
class: "add-code-to-edit",
|
||||
},
|
||||
ContinueExtensions.AddCodeToEdit.configure({
|
||||
suggestion: {
|
||||
...getContextProviderDropdownOptions(
|
||||
availableContextProvidersRef,
|
||||
|
|
@ -351,25 +333,22 @@ export function createEditorConfig(options: {
|
|||
},
|
||||
},
|
||||
}),
|
||||
SlashCommand.configure({
|
||||
HTMLAttributes: {
|
||||
class: "mention",
|
||||
},
|
||||
ContinueExtensions.SlashCommand.configure({
|
||||
suggestion: getSlashCommandDropdownOptions(
|
||||
availableSlashCommandsRef,
|
||||
onClose,
|
||||
onOpen,
|
||||
ideMessenger,
|
||||
dispatch,
|
||||
props.inputId,
|
||||
),
|
||||
renderText: (props) => {
|
||||
return props.node.attrs.label;
|
||||
},
|
||||
}),
|
||||
CodeBlockExtension,
|
||||
ContinueExtensions.PromptBlock,
|
||||
ContinueExtensions.CodeBlock,
|
||||
],
|
||||
editorProps: {
|
||||
attributes: {
|
||||
class: "outline-none -mt-1 overflow-hidden",
|
||||
class: "outline-none overflow-hidden",
|
||||
style: `font-size: ${getFontSize()}px;`,
|
||||
},
|
||||
},
|
||||
|
|
@ -6,10 +6,12 @@ import {
|
|||
} from "core";
|
||||
import { MutableRefObject } from "react";
|
||||
import tippy from "tippy.js";
|
||||
import { IIdeMessenger } from "../../../context/IdeMessenger";
|
||||
import AtMentionDropdown from "../AtMentionDropdown";
|
||||
import { ComboBoxItem, ComboBoxItemType, ComboBoxSubAction } from "../types";
|
||||
import { TIPPY_DIV_ID } from "./TipTapEditor";
|
||||
import { IIdeMessenger } from "../../../../context/IdeMessenger";
|
||||
import { AppDispatch } from "../../../../redux/store";
|
||||
import AtMentionDropdown from "../../AtMentionDropdown";
|
||||
import { ComboBoxItem, ComboBoxItemType, ComboBoxSubAction } from "../../types";
|
||||
import { TIPPY_DIV_ID } from "../TipTapEditor";
|
||||
import { SlashCommand } from "../extensions";
|
||||
|
||||
function getSuggestion(
|
||||
items: (props: { query: string }) => Promise<ComboBoxItem[]>,
|
||||
|
|
@ -196,6 +198,8 @@ export function getSlashCommandDropdownOptions(
|
|||
onClose: () => void,
|
||||
onOpen: () => void,
|
||||
ideMessenger: IIdeMessenger,
|
||||
dispatch: AppDispatch,
|
||||
inputId: string,
|
||||
) {
|
||||
const items = async ({ query }: { query: string }) => {
|
||||
const options = [...availableSlashCommandsRef.current];
|
||||
|
|
@ -215,7 +219,8 @@ export function getSlashCommandDropdownOptions(
|
|||
id: provider.title,
|
||||
title: provider.title,
|
||||
label: provider.title,
|
||||
type: (provider.type ?? "slashCommand") as ComboBoxItemType,
|
||||
type: (provider.type ?? SlashCommand.name) as ComboBoxItemType,
|
||||
content: provider.content,
|
||||
action: provider.action,
|
||||
}));
|
||||
|
||||
|
|
@ -232,6 +237,7 @@ export function getSlashCommandDropdownOptions(
|
|||
name: "",
|
||||
id: "",
|
||||
label: "",
|
||||
content: "",
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
import { IIdeMessenger } from "../../../context/IdeMessenger";
|
||||
import { IIdeMessenger } from "../../../../context/IdeMessenger";
|
||||
|
||||
const IMAGE_RESOLUTION = 1024;
|
||||
|
||||
5
gui/src/components/mainInput/TipTapEditor/utils/index.ts
Normal file
5
gui/src/components/mainInput/TipTapEditor/utils/index.ts
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
export * from "./editorConfig";
|
||||
export * from "./getSuggestion";
|
||||
export * from "./imageUtils";
|
||||
export * from "./keyHandlers";
|
||||
export * from "./resolveEditorContent";
|
||||
|
|
@ -1,20 +1,18 @@
|
|||
import { Editor } from "@tiptap/react";
|
||||
import { KeyboardEvent } from "react";
|
||||
import { isJetBrains, isMetaEquivalentKeyPressed } from "../../../util";
|
||||
import { isJetBrains, isMetaEquivalentKeyPressed } from "../../../../util";
|
||||
import {
|
||||
handleJetBrainsOSRMetaKeyIssues,
|
||||
handleVSCMetaKeyIssues,
|
||||
} from "../util/handleMetaKeyIssues";
|
||||
} from "../../util/handleMetaKeyIssues";
|
||||
|
||||
export function useEditorEventHandlers(options: {
|
||||
editor: Editor | null;
|
||||
isOSREnabled: boolean;
|
||||
editorFocusedRef: React.MutableRefObject<boolean | undefined>;
|
||||
isInEditMode: boolean;
|
||||
setActiveKey: (key: string | null) => void;
|
||||
}) {
|
||||
const { editor, isOSREnabled, editorFocusedRef, isInEditMode, setActiveKey } =
|
||||
options;
|
||||
const { editor, isOSREnabled, editorFocusedRef, setActiveKey } = options;
|
||||
|
||||
/**
|
||||
* This handles various issues with meta key actions
|
||||
|
|
@ -0,0 +1,339 @@
|
|||
import { Dispatch } from "@reduxjs/toolkit";
|
||||
import Image from "@tiptap/extension-image";
|
||||
import { Paragraph } from "@tiptap/extension-paragraph";
|
||||
import { Text } from "@tiptap/extension-text";
|
||||
import { JSONContent } from "@tiptap/react";
|
||||
import {
|
||||
ContextItemWithId,
|
||||
DefaultContextProvider,
|
||||
InputModifiers,
|
||||
MessageContent,
|
||||
MessagePart,
|
||||
RangeInFile,
|
||||
SlashCommandDescription,
|
||||
TextMessagePart,
|
||||
} from "core";
|
||||
import { ctxItemToRifWithContents } from "core/commands/util";
|
||||
import { renderChatMessage, stripImages } from "core/util/messageContent";
|
||||
import { getUriFileExtension } from "core/util/uri";
|
||||
import { IIdeMessenger } from "../../../../context/IdeMessenger";
|
||||
import { setIsGatheringContext } from "../../../../redux/slices/sessionSlice";
|
||||
import { CodeBlock, Mention, PromptBlock } from "../extensions";
|
||||
|
||||
interface MentionAttrs {
|
||||
label: string;
|
||||
id: string;
|
||||
itemType?: string;
|
||||
query?: string;
|
||||
}
|
||||
|
||||
interface ResolveEditorContentInput {
|
||||
editorState: JSONContent;
|
||||
modifiers: InputModifiers;
|
||||
ideMessenger: IIdeMessenger;
|
||||
defaultContextProviders: DefaultContextProvider[];
|
||||
availableSlashCommands: SlashCommandDescription[];
|
||||
selectedModelTitle: string;
|
||||
dispatch: Dispatch;
|
||||
}
|
||||
|
||||
type ResolveEditorContentOutput = [
|
||||
ContextItemWithId[],
|
||||
RangeInFile[],
|
||||
MessageContent,
|
||||
(
|
||||
| {
|
||||
command: SlashCommandDescription;
|
||||
input: string;
|
||||
}
|
||||
| undefined
|
||||
),
|
||||
];
|
||||
|
||||
/**
|
||||
* This function converts the input from the editor to a string, resolving any context items
|
||||
* Context items are appended to the top of the prompt and then referenced within the input
|
||||
*/
|
||||
export async function resolveEditorContent({
|
||||
editorState,
|
||||
modifiers,
|
||||
ideMessenger,
|
||||
defaultContextProviders,
|
||||
availableSlashCommands,
|
||||
selectedModelTitle,
|
||||
dispatch,
|
||||
}: ResolveEditorContentInput): Promise<ResolveEditorContentOutput> {
|
||||
const { parts, contextItemAttrs, selectedCode, slashCommandName } =
|
||||
processEditorContent(editorState);
|
||||
|
||||
const slashCommandWithInput = processSlashCommand(
|
||||
slashCommandName,
|
||||
availableSlashCommands,
|
||||
parts,
|
||||
);
|
||||
|
||||
const shouldGatherContext = modifiers.useCodebase || slashCommandWithInput;
|
||||
if (shouldGatherContext) {
|
||||
dispatch(setIsGatheringContext(true));
|
||||
}
|
||||
|
||||
const contextItems = await gatherContextItems({
|
||||
contextItemAttrs,
|
||||
modifiers,
|
||||
ideMessenger,
|
||||
defaultContextProviders,
|
||||
parts,
|
||||
selectedCode,
|
||||
selectedModelTitle,
|
||||
});
|
||||
|
||||
if (shouldGatherContext) {
|
||||
dispatch(setIsGatheringContext(false));
|
||||
}
|
||||
|
||||
return [contextItems, selectedCode, parts, slashCommandWithInput];
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes editor content and extracts parts, context items, code, and slash commands
|
||||
*/
|
||||
function processEditorContent(editorState: JSONContent) {
|
||||
const contextItemAttrs: MentionAttrs[] = [];
|
||||
const selectedCode: RangeInFile[] = [];
|
||||
let slashCommandName: string | undefined;
|
||||
|
||||
const parts = (editorState?.content || []).reduce<MessagePart[]>(
|
||||
(parts, p) => {
|
||||
switch (p.type) {
|
||||
case PromptBlock.name: {
|
||||
slashCommandName = resvolePromptBlock(p);
|
||||
}
|
||||
|
||||
case Paragraph.name: {
|
||||
const [text, ctxItems] = resolveParagraph(p);
|
||||
|
||||
contextItemAttrs.push(...ctxItems);
|
||||
|
||||
if (!text) return parts;
|
||||
|
||||
// Merge with previous text part if possible
|
||||
if (parts[parts.length - 1]?.type === "text") {
|
||||
(parts[parts.length - 1] as TextMessagePart).text += "\n" + text;
|
||||
return parts;
|
||||
}
|
||||
|
||||
return [...parts, { type: "text", text }];
|
||||
}
|
||||
|
||||
case CodeBlock.name: {
|
||||
if (!p.attrs?.item) {
|
||||
console.warn("codeBlock has no item attribute");
|
||||
return parts;
|
||||
}
|
||||
|
||||
const contextItem = p.attrs.item as ContextItemWithId;
|
||||
const rif = ctxItemToRifWithContents(contextItem, true);
|
||||
selectedCode.push(rif);
|
||||
|
||||
// If editing, only include in selectedCode
|
||||
if (contextItem.editing) {
|
||||
return parts;
|
||||
}
|
||||
|
||||
const fileExtension = getUriFileExtension(rif.filepath);
|
||||
const codeText = [
|
||||
"\n\n```",
|
||||
fileExtension,
|
||||
" ",
|
||||
contextItem.description,
|
||||
"\n",
|
||||
contextItem.content,
|
||||
"\n```",
|
||||
].join("");
|
||||
|
||||
if (parts[parts.length - 1]?.type === "text") {
|
||||
(parts[parts.length - 1] as TextMessagePart).text +=
|
||||
"\n" + codeText;
|
||||
return parts;
|
||||
}
|
||||
|
||||
return [...parts, { type: "text", text: codeText }];
|
||||
}
|
||||
|
||||
case Image.name: {
|
||||
return [
|
||||
...parts,
|
||||
{
|
||||
type: "imageUrl",
|
||||
imageUrl: { url: p.attrs?.src },
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
default: {
|
||||
console.warn("Unexpected content type", p.type);
|
||||
return parts;
|
||||
}
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
return { parts, contextItemAttrs, selectedCode, slashCommandName };
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes slash commands and prepares the command with input
|
||||
*/
|
||||
function processSlashCommand(
|
||||
slashCommandName: string | undefined,
|
||||
availableSlashCommands: SlashCommandDescription[],
|
||||
parts: MessagePart[],
|
||||
): { command: SlashCommandDescription; input: string } | undefined {
|
||||
if (!slashCommandName) return;
|
||||
|
||||
const command = availableSlashCommands.find(
|
||||
(c) => c.name === slashCommandName,
|
||||
);
|
||||
|
||||
if (!command) return;
|
||||
|
||||
const lastTextIndex = findLastIndex(parts, (part) => part.type === "text");
|
||||
const lastTextPart = parts[lastTextIndex] as TextMessagePart;
|
||||
|
||||
let input: string;
|
||||
|
||||
/**
|
||||
* Although we no longer render slash command <span /> tags from the editor,
|
||||
* we are inserting a slash command style text back into the text here.
|
||||
* This is a a hack, but there's a number of assumptions in `core` that there
|
||||
* is slash command text at the beginning of the text in order to process slash commands.
|
||||
*/
|
||||
if (lastTextPart) {
|
||||
input = renderChatMessage({
|
||||
role: "user",
|
||||
content: lastTextPart.text,
|
||||
}).trimStart();
|
||||
lastTextPart.text = `/${command.name} ${lastTextPart.text}`;
|
||||
} else {
|
||||
input = "";
|
||||
parts.push({ type: "text", text: `/${command.name}` });
|
||||
}
|
||||
|
||||
return {
|
||||
command,
|
||||
input,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Gathers context items from various sources
|
||||
*/
|
||||
async function gatherContextItems({
|
||||
contextItemAttrs,
|
||||
modifiers,
|
||||
ideMessenger,
|
||||
defaultContextProviders,
|
||||
parts,
|
||||
selectedCode,
|
||||
selectedModelTitle,
|
||||
}: {
|
||||
contextItemAttrs: MentionAttrs[];
|
||||
modifiers: InputModifiers;
|
||||
ideMessenger: IIdeMessenger;
|
||||
defaultContextProviders: DefaultContextProvider[];
|
||||
parts: MessagePart[];
|
||||
selectedCode: RangeInFile[];
|
||||
selectedModelTitle: string;
|
||||
}): Promise<ContextItemWithId[]> {
|
||||
let contextItems: ContextItemWithId[] = [];
|
||||
|
||||
// Process context item attributes
|
||||
for (const item of contextItemAttrs) {
|
||||
const result = await ideMessenger.request("context/getContextItems", {
|
||||
name: item.itemType === "contextProvider" ? item.id : item.itemType!,
|
||||
query: item.query ?? "",
|
||||
fullInput: stripImages(parts),
|
||||
selectedCode,
|
||||
selectedModelTitle,
|
||||
});
|
||||
if (result.status === "success") {
|
||||
contextItems.push(...result.content);
|
||||
}
|
||||
}
|
||||
|
||||
// cmd+enter to use codebase
|
||||
if (modifiers.useCodebase) {
|
||||
const result = await ideMessenger.request("context/getContextItems", {
|
||||
name: "codebase",
|
||||
query: "",
|
||||
fullInput: stripImages(parts),
|
||||
selectedCode,
|
||||
selectedModelTitle,
|
||||
});
|
||||
|
||||
if (result.status === "success") {
|
||||
contextItems.push(...result.content);
|
||||
}
|
||||
}
|
||||
|
||||
// Include default context providers
|
||||
const defaultContextItems = await Promise.all(
|
||||
defaultContextProviders.map(async (provider) => {
|
||||
const result = await ideMessenger.request("context/getContextItems", {
|
||||
name: provider.name,
|
||||
query: provider.query ?? "",
|
||||
fullInput: stripImages(parts),
|
||||
selectedCode,
|
||||
selectedModelTitle,
|
||||
});
|
||||
if (result.status === "success") {
|
||||
return result.content;
|
||||
} else {
|
||||
return [];
|
||||
}
|
||||
}),
|
||||
);
|
||||
contextItems.push(...defaultContextItems.flat());
|
||||
|
||||
return contextItems;
|
||||
}
|
||||
|
||||
function findLastIndex<T>(
|
||||
array: T[],
|
||||
predicate: (value: T, index: number, obj: T[]) => boolean,
|
||||
): number {
|
||||
for (let i = array.length - 1; i >= 0; i--) {
|
||||
if (predicate(array[i], i, array)) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1; // if no element satisfies the predicate
|
||||
}
|
||||
|
||||
function resvolePromptBlock(p: JSONContent): string | undefined {
|
||||
return p.attrs?.item.name;
|
||||
}
|
||||
|
||||
function resolveParagraph(p: JSONContent): [string, MentionAttrs[]] {
|
||||
const contextItems: MentionAttrs[] = [];
|
||||
|
||||
const text = (p.content || [])
|
||||
.map((child) => {
|
||||
switch (child.type) {
|
||||
case Text.name:
|
||||
return child.text;
|
||||
case Mention.name:
|
||||
contextItems.push(child.attrs as MentionAttrs);
|
||||
return child.attrs?.renderInlineAs ?? child.attrs?.label;
|
||||
|
||||
default:
|
||||
console.warn("Unexpected child type", child.type);
|
||||
return "";
|
||||
}
|
||||
})
|
||||
.join("")
|
||||
.trimStart();
|
||||
|
||||
return [text, contextItems];
|
||||
}
|
||||
|
|
@ -1,42 +0,0 @@
|
|||
import { NodeViewWrapper, NodeViewWrapperProps } from "@tiptap/react";
|
||||
import { ContextItemWithId } from "core";
|
||||
import { vscBadgeBackground } from "../..";
|
||||
import CodeSnippetPreview from "../../markdown/CodeSnippetPreview";
|
||||
|
||||
export const CodeBlockComponent = (props: any) => {
|
||||
const { node, deleteNode, selected, editor, updateAttributes } = props;
|
||||
const item: ContextItemWithId = node.attrs.item;
|
||||
const inputId = node.attrs.inputId;
|
||||
// const contextItems = useSelector(
|
||||
// (store: RootState) =>
|
||||
// store.session.messages[store.session.messages.length - 1].contextItems,
|
||||
// );
|
||||
// const isFirstContextItem = item.id === contextItems[0]?.id;
|
||||
const isFirstContextItem = false; // TODO: fix this, decided not worth the insane renders for now
|
||||
|
||||
// Not setting this as a "p" will cause issues with foreign keyboards
|
||||
// See https://github.com/continuedev/continue/issues/3199
|
||||
const nodeViewWrapperTag: NodeViewWrapperProps["as"] = "p";
|
||||
|
||||
return (
|
||||
<NodeViewWrapper
|
||||
className="code-block-with-content"
|
||||
as={nodeViewWrapperTag}
|
||||
>
|
||||
<CodeSnippetPreview
|
||||
inputId={inputId}
|
||||
borderColor={
|
||||
isFirstContextItem
|
||||
? "#d0d"
|
||||
: selected
|
||||
? vscBadgeBackground
|
||||
: undefined
|
||||
}
|
||||
item={item}
|
||||
onDelete={() => {
|
||||
deleteNode();
|
||||
}}
|
||||
/>
|
||||
</NodeViewWrapper>
|
||||
);
|
||||
};
|
||||
|
|
@ -1,178 +0,0 @@
|
|||
// Adapted from SlashCommand extension (@tiptap/extension-mention/src/mention.ts)
|
||||
|
||||
import { mergeAttributes, Node } from "@tiptap/core";
|
||||
import { Node as ProseMirrorNode } from "@tiptap/pm/model";
|
||||
import { PluginKey } from "@tiptap/pm/state";
|
||||
import Suggestion, { SuggestionOptions } from "@tiptap/suggestion";
|
||||
|
||||
export type SlashCommandOptions = {
|
||||
HTMLAttributes: Record<string, any>;
|
||||
renderText: (props: {
|
||||
options: SlashCommandOptions;
|
||||
node: ProseMirrorNode;
|
||||
}) => string;
|
||||
suggestion: Omit<SuggestionOptions, "editor">;
|
||||
};
|
||||
|
||||
export const SlashCommandPluginKey = new PluginKey("slashcommand");
|
||||
|
||||
export const SlashCommand = Node.create<SlashCommandOptions>({
|
||||
name: "slashcommand",
|
||||
|
||||
addOptions() {
|
||||
return {
|
||||
HTMLAttributes: {},
|
||||
renderText({ options, node }) {
|
||||
return `${options.suggestion.char}${node.attrs.label ?? node.attrs.id}`;
|
||||
},
|
||||
suggestion: {
|
||||
char: "/",
|
||||
pluginKey: SlashCommandPluginKey,
|
||||
startOfLine: true,
|
||||
command: ({ editor, range, props }) => {
|
||||
// increase range.to by one when the next node is of type "text"
|
||||
// and starts with a space character
|
||||
const nodeAfter = editor.view.state.selection.$to.nodeAfter;
|
||||
const overrideSpace = nodeAfter?.text?.startsWith(" ");
|
||||
|
||||
if (overrideSpace) {
|
||||
range.to += 1;
|
||||
}
|
||||
|
||||
editor
|
||||
.chain()
|
||||
.focus()
|
||||
.insertContentAt(range, [
|
||||
{
|
||||
type: this.name,
|
||||
attrs: props,
|
||||
},
|
||||
{
|
||||
type: "text",
|
||||
text: " ",
|
||||
},
|
||||
])
|
||||
.run();
|
||||
|
||||
window.getSelection()?.collapseToEnd();
|
||||
},
|
||||
allow: ({ state, range }) => {
|
||||
const $from = state.doc.resolve(range.from);
|
||||
const type = state.schema.nodes[this.name];
|
||||
const allow = !!$from.parent.type.contentMatch.matchType(type);
|
||||
|
||||
return allow;
|
||||
},
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
group: "inline",
|
||||
|
||||
inline: true,
|
||||
|
||||
selectable: false,
|
||||
|
||||
atom: true,
|
||||
|
||||
addAttributes() {
|
||||
return {
|
||||
id: {
|
||||
default: null,
|
||||
parseHTML: (element) => element.getAttribute("data-id"),
|
||||
renderHTML: (attributes) => {
|
||||
if (!attributes.id) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return {
|
||||
"data-id": attributes.id,
|
||||
};
|
||||
},
|
||||
},
|
||||
|
||||
label: {
|
||||
default: null,
|
||||
parseHTML: (element) => element.getAttribute("data-label"),
|
||||
renderHTML: (attributes) => {
|
||||
if (!attributes.label) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return {
|
||||
"data-label": attributes.label,
|
||||
};
|
||||
},
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
parseHTML() {
|
||||
return [
|
||||
{
|
||||
tag: `span[data-type="${this.name}"]`,
|
||||
},
|
||||
];
|
||||
},
|
||||
|
||||
renderHTML({ node, HTMLAttributes }) {
|
||||
return [
|
||||
"span",
|
||||
mergeAttributes(
|
||||
{ "data-type": this.name },
|
||||
this.options.HTMLAttributes,
|
||||
HTMLAttributes,
|
||||
),
|
||||
this.options.renderText({
|
||||
options: this.options,
|
||||
node,
|
||||
}),
|
||||
];
|
||||
},
|
||||
|
||||
renderText({ node }) {
|
||||
return this.options.renderText({
|
||||
options: this.options,
|
||||
node,
|
||||
});
|
||||
},
|
||||
|
||||
addKeyboardShortcuts() {
|
||||
return {
|
||||
Backspace: () =>
|
||||
this.editor.commands.command(({ tr, state }) => {
|
||||
let isSlashCommand = false;
|
||||
const { selection } = state;
|
||||
const { empty, anchor } = selection;
|
||||
|
||||
if (!empty) {
|
||||
return false;
|
||||
}
|
||||
|
||||
state.doc.nodesBetween(anchor - 1, anchor, (node, pos) => {
|
||||
if (node.type.name === this.name) {
|
||||
isSlashCommand = true;
|
||||
tr.insertText(
|
||||
this.options.suggestion.char || "",
|
||||
pos,
|
||||
pos + node.nodeSize,
|
||||
);
|
||||
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
return isSlashCommand;
|
||||
}),
|
||||
};
|
||||
},
|
||||
|
||||
addProseMirrorPlugins() {
|
||||
return [
|
||||
Suggestion({
|
||||
editor: this.editor,
|
||||
...this.options.suggestion,
|
||||
}),
|
||||
];
|
||||
},
|
||||
});
|
||||
|
|
@ -1,277 +0,0 @@
|
|||
import { Dispatch } from "@reduxjs/toolkit";
|
||||
import { JSONContent } from "@tiptap/react";
|
||||
import {
|
||||
ContextItemWithId,
|
||||
DefaultContextProvider,
|
||||
InputModifiers,
|
||||
MessageContent,
|
||||
MessagePart,
|
||||
RangeInFile,
|
||||
SlashCommandDescription,
|
||||
TextMessagePart,
|
||||
} from "core";
|
||||
import { ctxItemToRifWithContents } from "core/commands/util";
|
||||
import { renderChatMessage, stripImages } from "core/util/messageContent";
|
||||
import { getUriFileExtension } from "core/util/uri";
|
||||
import { IIdeMessenger } from "../../../context/IdeMessenger";
|
||||
import { setIsGatheringContext } from "../../../redux/slices/sessionSlice";
|
||||
|
||||
interface MentionAttrs {
|
||||
label: string;
|
||||
id: string;
|
||||
itemType?: string;
|
||||
query?: string;
|
||||
}
|
||||
|
||||
interface ResolveEditorContentInput {
|
||||
editorState: JSONContent;
|
||||
modifiers: InputModifiers;
|
||||
ideMessenger: IIdeMessenger;
|
||||
defaultContextProviders: DefaultContextProvider[];
|
||||
availableSlashCommands: SlashCommandDescription[];
|
||||
selectedModelTitle: string;
|
||||
dispatch: Dispatch;
|
||||
}
|
||||
|
||||
/**
|
||||
* This function converts the input from the editor to a string, resolving any context items
|
||||
* Context items are appended to the top of the prompt and then referenced within the input
|
||||
*/
|
||||
async function resolveEditorContent({
|
||||
editorState,
|
||||
modifiers,
|
||||
ideMessenger,
|
||||
defaultContextProviders,
|
||||
availableSlashCommands,
|
||||
selectedModelTitle,
|
||||
dispatch,
|
||||
}: ResolveEditorContentInput): Promise<
|
||||
[
|
||||
ContextItemWithId[],
|
||||
RangeInFile[],
|
||||
MessageContent,
|
||||
(
|
||||
| {
|
||||
command: SlashCommandDescription;
|
||||
input: string;
|
||||
}
|
||||
| undefined
|
||||
),
|
||||
]
|
||||
> {
|
||||
let parts: MessagePart[] = [];
|
||||
let contextItemAttrs: MentionAttrs[] = [];
|
||||
const selectedCode: RangeInFile[] = [];
|
||||
let slashCommandName: string | undefined = undefined;
|
||||
let slashCommandWithInput:
|
||||
| { command: SlashCommandDescription; input: string }
|
||||
| undefined = undefined;
|
||||
if (editorState?.content) {
|
||||
for (const p of editorState.content) {
|
||||
if (p.type === "paragraph") {
|
||||
const [text, ctxItems, foundSlashCommand] = resolveParagraph(p);
|
||||
// Only take the first slash command
|
||||
if (foundSlashCommand && typeof slashCommandName === "undefined") {
|
||||
slashCommandName = foundSlashCommand;
|
||||
}
|
||||
|
||||
contextItemAttrs.push(...ctxItems);
|
||||
|
||||
if (text === "") {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (parts[parts.length - 1]?.type === "text") {
|
||||
(parts[parts.length - 1] as TextMessagePart).text += "\n" + text;
|
||||
} else {
|
||||
parts.push({ type: "text", text });
|
||||
}
|
||||
} else if (p.type === "codeBlock") {
|
||||
if (p.attrs?.item) {
|
||||
const contextItem = p.attrs.item as ContextItemWithId;
|
||||
const rif = ctxItemToRifWithContents(contextItem, true);
|
||||
// If not editing, include codeblocks in the prompt
|
||||
// If editing is handled by selectedCode below
|
||||
if (!contextItem.editing) {
|
||||
const fileExtension = getUriFileExtension(rif.filepath);
|
||||
// let extName = relativeFilepath.split(".").slice(-1)[0];
|
||||
const text =
|
||||
"\n\n" +
|
||||
"```" +
|
||||
fileExtension +
|
||||
" " +
|
||||
contextItem.description +
|
||||
"\n" +
|
||||
contextItem.content +
|
||||
"\n```";
|
||||
if (parts[parts.length - 1]?.type === "text") {
|
||||
(parts[parts.length - 1] as TextMessagePart).text += "\n" + text;
|
||||
} else {
|
||||
parts.push({
|
||||
type: "text",
|
||||
text,
|
||||
});
|
||||
}
|
||||
}
|
||||
selectedCode.push(rif);
|
||||
} else {
|
||||
console.warn("codeBlock has no item attribute");
|
||||
}
|
||||
} else if (p.type === "image") {
|
||||
parts.push({
|
||||
type: "imageUrl",
|
||||
imageUrl: {
|
||||
url: p.attrs?.src,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
console.warn("Unexpected content type", p.type);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (slashCommandName) {
|
||||
const command = availableSlashCommands.find(
|
||||
(c) => c.name === slashCommandName,
|
||||
);
|
||||
if (command) {
|
||||
const lastTextIndex = findLastIndex(
|
||||
parts,
|
||||
(part) => part.type === "text",
|
||||
);
|
||||
const lastTextPart = parts[lastTextIndex] as TextMessagePart;
|
||||
|
||||
let input: string;
|
||||
// Get input and add text of last slash command text back in to last text node
|
||||
if (lastTextPart) {
|
||||
input = renderChatMessage({
|
||||
role: "user",
|
||||
content: lastTextPart.text,
|
||||
}).trimStart();
|
||||
lastTextPart.text = `/${command.name} ${lastTextPart.text}`;
|
||||
} else {
|
||||
input = "";
|
||||
parts.push({ type: "text", text: `/${command.name}` });
|
||||
}
|
||||
|
||||
slashCommandWithInput = {
|
||||
command,
|
||||
input,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const shouldGatherContext = modifiers.useCodebase || slashCommandWithInput;
|
||||
if (shouldGatherContext) {
|
||||
dispatch(setIsGatheringContext(true));
|
||||
}
|
||||
|
||||
let contextItemsText = "";
|
||||
let contextItems: ContextItemWithId[] = [];
|
||||
for (const item of contextItemAttrs) {
|
||||
const result = await ideMessenger.request("context/getContextItems", {
|
||||
name: item.itemType === "contextProvider" ? item.id : item.itemType!,
|
||||
query: item.query ?? "",
|
||||
fullInput: stripImages(parts),
|
||||
selectedCode,
|
||||
selectedModelTitle,
|
||||
});
|
||||
if (result.status === "success") {
|
||||
const resolvedItems = result.content;
|
||||
contextItems.push(...resolvedItems);
|
||||
for (const resolvedItem of resolvedItems) {
|
||||
contextItemsText += resolvedItem.content + "\n\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// cmd+enter to use codebase
|
||||
if (modifiers.useCodebase) {
|
||||
const result = await ideMessenger.request("context/getContextItems", {
|
||||
name: "codebase",
|
||||
query: "",
|
||||
fullInput: stripImages(parts),
|
||||
selectedCode,
|
||||
selectedModelTitle,
|
||||
});
|
||||
|
||||
if (result.status === "success") {
|
||||
const codebaseItems = result.content;
|
||||
contextItems.push(...codebaseItems);
|
||||
for (const codebaseItem of codebaseItems) {
|
||||
contextItemsText += codebaseItem.content + "\n\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Include default context providers
|
||||
const defaultContextItems = await Promise.all(
|
||||
defaultContextProviders.map(async (provider) => {
|
||||
const result = await ideMessenger.request("context/getContextItems", {
|
||||
name: provider.name,
|
||||
query: provider.query ?? "",
|
||||
fullInput: stripImages(parts),
|
||||
selectedCode,
|
||||
selectedModelTitle,
|
||||
});
|
||||
if (result.status === "success") {
|
||||
return result.content;
|
||||
} else {
|
||||
return [];
|
||||
}
|
||||
}),
|
||||
);
|
||||
contextItems.push(...defaultContextItems.flat());
|
||||
|
||||
if (contextItemsText !== "") {
|
||||
contextItemsText += "\n";
|
||||
}
|
||||
|
||||
if (shouldGatherContext) {
|
||||
dispatch(setIsGatheringContext(false));
|
||||
}
|
||||
|
||||
return [contextItems, selectedCode, parts, slashCommandWithInput];
|
||||
}
|
||||
|
||||
function findLastIndex<T>(
|
||||
array: T[],
|
||||
predicate: (value: T, index: number, obj: T[]) => boolean,
|
||||
): number {
|
||||
for (let i = array.length - 1; i >= 0; i--) {
|
||||
if (predicate(array[i], i, array)) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1; // if no element satisfies the predicate
|
||||
}
|
||||
|
||||
function resolveParagraph(
|
||||
p: JSONContent,
|
||||
): [string, MentionAttrs[], string | undefined] {
|
||||
let text = "";
|
||||
const contextItems: MentionAttrs[] = [];
|
||||
let slashCommand: string | undefined = undefined;
|
||||
for (const child of p.content || []) {
|
||||
if (child.type === "text") {
|
||||
text += text === "" ? child.text?.trimStart() : child.text;
|
||||
} else if (child.type === "mention") {
|
||||
text +=
|
||||
typeof child.attrs?.renderInlineAs === "string"
|
||||
? child.attrs.renderInlineAs
|
||||
: child.attrs?.label;
|
||||
contextItems.push(child.attrs as MentionAttrs);
|
||||
} else if (child.type === "slashcommand") {
|
||||
if (typeof slashCommand === "undefined") {
|
||||
slashCommand = child.attrs?.id;
|
||||
} else {
|
||||
text += child.attrs?.label;
|
||||
}
|
||||
} else {
|
||||
console.warn("Unexpected child type", child.type);
|
||||
}
|
||||
}
|
||||
return [text, contextItems, slashCommand];
|
||||
}
|
||||
|
||||
export default resolveEditorContent;
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
import { Editor } from "@tiptap/react";
|
||||
import { KeyboardEvent } from "react";
|
||||
import { getPlatform, isWebEnvironment } from "../../../util";
|
||||
import { CodeBlock } from "../TipTapEditor";
|
||||
|
||||
const isWebEnv = isWebEnvironment();
|
||||
|
||||
|
|
@ -103,7 +104,7 @@ export const handleJetBrainsMetaBackspace = (editor: Editor) => {
|
|||
for (let i = doc.content.childCount - 1; i >= 0; i--) {
|
||||
const node = doc.content.child(i);
|
||||
|
||||
if (node.type.name === "codeBlock") {
|
||||
if (node.type.name === CodeBlock.name) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,184 +0,0 @@
|
|||
import {
|
||||
ChevronDownIcon,
|
||||
EyeSlashIcon,
|
||||
XMarkIcon,
|
||||
} from "@heroicons/react/24/outline";
|
||||
import { ContextItemWithId } from "core";
|
||||
import { dedent, getMarkdownLanguageTagForFile } from "core/util";
|
||||
import { useContext, useEffect, useMemo, useRef, useState } from "react";
|
||||
import styled from "styled-components";
|
||||
import { defaultBorderRadius, lightGray, vscEditorBackground } from "..";
|
||||
import { IdeMessengerContext } from "../../context/IdeMessenger";
|
||||
import { getFontSize } from "../../util";
|
||||
import FileIcon from "../FileIcon";
|
||||
import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip";
|
||||
import StyledMarkdownPreview from "./StyledMarkdownPreview";
|
||||
import { ctxItemToRifWithContents } from "core/commands/util";
|
||||
import { EyeIcon } from "@heroicons/react/24/solid";
|
||||
import { useAppSelector } from "../../redux/hooks";
|
||||
|
||||
const PreviewMarkdownDiv = styled.div<{
|
||||
borderColor?: string;
|
||||
}>`
|
||||
background-color: ${vscEditorBackground};
|
||||
border-radius: ${defaultBorderRadius};
|
||||
border: 0.5px solid ${(props) => props.borderColor || lightGray};
|
||||
margin-top: 4px;
|
||||
margin-bottom: 4px;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
|
||||
& div {
|
||||
background-color: ${vscEditorBackground};
|
||||
}
|
||||
`;
|
||||
|
||||
interface CodeSnippetPreviewProps {
|
||||
item: ContextItemWithId;
|
||||
onDelete?: () => void;
|
||||
borderColor?: string;
|
||||
inputId: string;
|
||||
}
|
||||
|
||||
const MAX_PREVIEW_HEIGHT = 100;
|
||||
|
||||
const backticksRegex = /`{3,}/gm;
|
||||
|
||||
function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
|
||||
const [localHidden, setLocalHidden] = useState<boolean | undefined>();
|
||||
const [isSizeLimited, setIsSizeLimited] = useState(true);
|
||||
|
||||
const newestCodeblockForInputId = useAppSelector(
|
||||
(store) => store.session.newestCodeblockForInput[props.inputId],
|
||||
);
|
||||
|
||||
const hidden = useMemo(() => {
|
||||
return localHidden ?? newestCodeblockForInputId !== props.item.id.itemId;
|
||||
}, [localHidden, newestCodeblockForInputId, props.item]);
|
||||
|
||||
const content = useMemo(() => {
|
||||
return dedent`${props.item.content}`;
|
||||
}, [props.item.content]);
|
||||
|
||||
const fence = useMemo(() => {
|
||||
const backticks = content.match(backticksRegex);
|
||||
return backticks ? backticks.sort().at(-1) + "`" : "```";
|
||||
}, [content]);
|
||||
|
||||
const codeBlockRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const [codeblockDims, setCodeblockDims] = useState({ width: 0, height: 0 });
|
||||
useEffect(() => {
|
||||
const resizeObserver = new ResizeObserver(() => {
|
||||
setCodeblockDims({
|
||||
width: codeBlockRef.current?.scrollWidth ?? 0,
|
||||
height: codeBlockRef.current?.scrollHeight ?? 0,
|
||||
});
|
||||
});
|
||||
|
||||
if (codeBlockRef.current) {
|
||||
resizeObserver.observe(codeBlockRef.current);
|
||||
}
|
||||
|
||||
return () => {
|
||||
resizeObserver.disconnect();
|
||||
};
|
||||
}, [codeBlockRef]);
|
||||
|
||||
return (
|
||||
<PreviewMarkdownDiv
|
||||
spellCheck={false}
|
||||
borderColor={props.borderColor}
|
||||
className="find-widget-skip"
|
||||
>
|
||||
<div
|
||||
className="m-0 flex cursor-pointer items-center justify-between break-all border-b px-[5px] py-1.5 hover:opacity-90"
|
||||
style={{
|
||||
fontSize: getFontSize() - 3,
|
||||
}}
|
||||
onClick={() => {
|
||||
setLocalHidden(!hidden);
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className="flex items-center gap-1 hover:underline"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
if (
|
||||
props.item.id.providerTitle === "file" &&
|
||||
props.item.uri?.value
|
||||
) {
|
||||
ideMessenger.post("showFile", {
|
||||
filepath: props.item.uri.value,
|
||||
});
|
||||
} else if (props.item.id.providerTitle === "code") {
|
||||
const rif = ctxItemToRifWithContents(props.item, true);
|
||||
ideMessenger.ide.showLines(
|
||||
rif.filepath,
|
||||
rif.range.start.line,
|
||||
rif.range.end.line,
|
||||
);
|
||||
} else {
|
||||
ideMessenger.post("showVirtualFile", {
|
||||
content,
|
||||
name: props.item.name,
|
||||
});
|
||||
}
|
||||
}}
|
||||
>
|
||||
<FileIcon height="16px" width="16px" filename={props.item.name} />
|
||||
{props.item.name}
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<HeaderButtonWithToolTip text={hidden ? "Show" : "Hide"}>
|
||||
{hidden ? (
|
||||
<EyeIcon width="1em" height="1em" />
|
||||
) : (
|
||||
<EyeSlashIcon width="1em" height="1em" />
|
||||
)}
|
||||
</HeaderButtonWithToolTip>
|
||||
<HeaderButtonWithToolTip
|
||||
text="Delete"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
props.onDelete?.();
|
||||
}}
|
||||
>
|
||||
<XMarkIcon width="1em" height="1em" />
|
||||
</HeaderButtonWithToolTip>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
contentEditable={false}
|
||||
className={`m-0 ${isSizeLimited ? "overflow-hidden" : "overflow-auto"} ${hidden ? "hidden" : ""}`}
|
||||
ref={codeBlockRef}
|
||||
style={{
|
||||
maxHeight: isSizeLimited ? MAX_PREVIEW_HEIGHT : undefined, // Could switch to max-h-[33vh] but then chevron icon shows when height can't change
|
||||
}}
|
||||
>
|
||||
<StyledMarkdownPreview
|
||||
source={`${fence}${getMarkdownLanguageTagForFile(props.item.name)} ${props.item.description}\n${content}\n${fence}`}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{codeblockDims.height > MAX_PREVIEW_HEIGHT && (
|
||||
<HeaderButtonWithToolTip
|
||||
className="absolute bottom-1 right-2"
|
||||
text={isSizeLimited ? "Expand" : "Collapse"}
|
||||
>
|
||||
<ChevronDownIcon
|
||||
className="h-5 w-5 transition-all"
|
||||
style={{
|
||||
transform: isSizeLimited ? "" : "rotate(180deg)",
|
||||
}}
|
||||
onClick={() => setIsSizeLimited((v) => !v)}
|
||||
/>
|
||||
</HeaderButtonWithToolTip>
|
||||
)}
|
||||
</PreviewMarkdownDiv>
|
||||
);
|
||||
}
|
||||
|
||||
export default CodeSnippetPreview;
|
||||
|
|
@ -7,6 +7,7 @@ import Spinner from "../../gui/Spinner";
|
|||
import { ToolbarButtonWithTooltip } from "./ToolbarButtonWithTooltip";
|
||||
|
||||
interface ApplyActionsProps {
|
||||
disableManualApply?: boolean;
|
||||
applyState?: ApplyState;
|
||||
onClickAccept: () => void;
|
||||
onClickReject: () => void;
|
||||
|
|
@ -59,8 +60,8 @@ export default function ApplyActions(props: ApplyActionsProps) {
|
|||
);
|
||||
case "done":
|
||||
return (
|
||||
<div className="xs:pl-2 xs:pr-1 flex items-center rounded bg-zinc-700">
|
||||
<span className="max-xs:hidden xs:mr-1 text-xs text-gray-400">
|
||||
<div className="flex items-center sm:gap-1">
|
||||
<span className="max-xs:hidden text-center text-xs text-gray-400">
|
||||
{`${props.applyState?.numDiffs === 1 ? "1 diff" : `${props.applyState?.numDiffs} diffs`}`}
|
||||
<span className="max-md:hidden">{` remaining`}</span>
|
||||
</span>
|
||||
|
|
@ -90,10 +91,15 @@ export default function ApplyActions(props: ApplyActionsProps) {
|
|||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
if (props.disableManualApply) {
|
||||
return null;
|
||||
}
|
||||
return applyButton("Reapply");
|
||||
}
|
||||
default:
|
||||
if (props.disableManualApply) {
|
||||
return null;
|
||||
}
|
||||
return applyButton("Apply");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
import FileIcon from "../../FileIcon";
|
||||
import { inferResolvedUriFromRelativePath } from "core/util/ideUtils";
|
||||
import { getLastNPathParts } from "core/util/uri";
|
||||
import { useContext } from "react";
|
||||
import { IdeMessengerContext } from "../../../context/IdeMessenger";
|
||||
import { getLastNPathParts, getUriPathBasename } from "core/util/uri";
|
||||
import { inferResolvedUriFromRelativePath } from "core/util/ideUtils";
|
||||
import FileIcon from "../../FileIcon";
|
||||
|
||||
export interface FileInfoProps {
|
||||
relativeFilepath: string;
|
||||
|
|
@ -23,17 +23,17 @@ const FileInfo = ({ relativeFilepath, range }: FileInfoProps) => {
|
|||
}
|
||||
|
||||
return (
|
||||
<div className="flex w-full min-w-0 items-center">
|
||||
<div
|
||||
className="mr-0.5 flex w-full min-w-0 cursor-pointer items-center gap-0.5"
|
||||
onClick={onClickFileName}
|
||||
>
|
||||
<div
|
||||
className="flex cursor-pointer flex-row items-center gap-0.5"
|
||||
onClick={onClickFileName}
|
||||
>
|
||||
<div>
|
||||
<FileIcon height="20px" width="20px" filename={relativeFilepath} />
|
||||
<span className="w-full truncate hover:underline">
|
||||
{getLastNPathParts(relativeFilepath, 1)}
|
||||
{range && ` ${range}`}
|
||||
</span>
|
||||
</div>
|
||||
<span className="line-clamp-1 break-all hover:underline">
|
||||
{getLastNPathParts(relativeFilepath, 1)}
|
||||
{range && ` ${range}`}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
|
|
|||
|
|
@ -3,7 +3,6 @@ import { inferResolvedUriFromRelativePath } from "core/util/ideUtils";
|
|||
import { debounce } from "lodash";
|
||||
import { useContext, useEffect, useRef, useState } from "react";
|
||||
import styled from "styled-components";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import {
|
||||
defaultBorderRadius,
|
||||
vscCommandCenterInactiveBorder,
|
||||
|
|
@ -26,6 +25,8 @@ import GeneratingCodeLoader from "./GeneratingCodeLoader";
|
|||
import RunInTerminalButton from "./RunInTerminalButton";
|
||||
|
||||
const TopDiv = styled.div`
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
outline: 1px solid ${vscCommandCenterInactiveBorder};
|
||||
outline-offset: -0.5px;
|
||||
border-radius: ${defaultBorderRadius};
|
||||
|
|
@ -38,7 +39,6 @@ const ToolbarDiv = styled.div<{ isExpanded: boolean }>`
|
|||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
background: inherit;
|
||||
font-size: ${getFontSize() - 2}px;
|
||||
padding: 4px 6px;
|
||||
margin: 0;
|
||||
|
|
@ -52,42 +52,32 @@ export interface StepContainerPreToolbarProps {
|
|||
relativeFilepath: string;
|
||||
isGeneratingCodeBlock: boolean;
|
||||
codeBlockIndex: number; // To track which codeblock we are applying
|
||||
codeBlockStreamId: string;
|
||||
range?: string;
|
||||
children: any;
|
||||
expanded?: boolean;
|
||||
hideApply?: boolean;
|
||||
disableManualApply?: boolean;
|
||||
}
|
||||
|
||||
export default function StepContainerPreToolbar(
|
||||
props: StepContainerPreToolbarProps,
|
||||
) {
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const streamIdRef = useRef<string>(uuidv4());
|
||||
const wasGeneratingRef = useRef(props.isGeneratingCodeBlock);
|
||||
const isInEditMode = useAppSelector(selectIsInEditMode);
|
||||
const [isExpanded, setIsExpanded] = useState(
|
||||
props.expanded ?? (isInEditMode ? false : true),
|
||||
);
|
||||
const [codeBlockContent, setCodeBlockContent] = useState("");
|
||||
const isStreaming = useAppSelector((state) => state.session.isStreaming);
|
||||
|
||||
const nextCodeBlockIndex = useAppSelector(
|
||||
(state) => state.session.codeBlockApplyStates.curIndex,
|
||||
);
|
||||
|
||||
const applyState = useAppSelector((state) =>
|
||||
selectApplyStateByStreamId(state, streamIdRef.current),
|
||||
selectApplyStateByStreamId(state, props.codeBlockStreamId),
|
||||
);
|
||||
|
||||
// This handles an edge case when the last node in the markdown syntax tree is a codeblock.
|
||||
// In this scenario, `isGeneratingCodeBlock` is never set to false since we determine if
|
||||
// we are done generating based on whether the next node in the tree is not a codeblock.
|
||||
// The tree parsing logic for Remark is defined on page load, so we can't access state
|
||||
// during the actual tree parsing.
|
||||
const isGeneratingCodeBlock = !isStreaming
|
||||
? false
|
||||
: props.isGeneratingCodeBlock;
|
||||
|
||||
const isNextCodeBlock = nextCodeBlockIndex === props.codeBlockIndex;
|
||||
const hasFileExtension = /\.[0-9a-z]+$/i.test(props.relativeFilepath);
|
||||
|
||||
|
|
@ -104,7 +94,7 @@ export default function StepContainerPreToolbar(
|
|||
);
|
||||
|
||||
ideMessenger.post("applyToFile", {
|
||||
streamId: streamIdRef.current,
|
||||
streamId: props.codeBlockStreamId,
|
||||
filepath: fileUri,
|
||||
text: codeBlockContent,
|
||||
curSelectedModelTitle: defaultModel.title,
|
||||
|
|
@ -135,19 +125,17 @@ export default function StepContainerPreToolbar(
|
|||
}
|
||||
}, [props.children, codeBlockContent]);
|
||||
|
||||
// Temporarily disabling auto apply for Edit mode
|
||||
// useEffect(() => {
|
||||
// const hasCompletedGenerating =
|
||||
// wasGeneratingRef.current && !isGeneratingCodeBlock;
|
||||
|
||||
// const shouldAutoApply = hasCompletedGenerating && isInEditMode;
|
||||
|
||||
// if (shouldAutoApply) {
|
||||
// onClickApply();
|
||||
// }
|
||||
|
||||
// wasGeneratingRef.current = isGeneratingCodeBlock;
|
||||
// }, [isGeneratingCodeBlock]);
|
||||
// if (hasCompletedGenerating) {
|
||||
// if (props.autoApply) {
|
||||
// onClickApply();
|
||||
// }
|
||||
// }
|
||||
// }, [wasGeneratingRef, isGeneratingCodeBlock, props.autoApply]);
|
||||
|
||||
async function onClickAcceptApply() {
|
||||
const fileUri = await inferResolvedUriFromRelativePath(
|
||||
|
|
@ -156,7 +144,7 @@ export default function StepContainerPreToolbar(
|
|||
);
|
||||
ideMessenger.post("acceptDiff", {
|
||||
filepath: fileUri,
|
||||
streamId: streamIdRef.current,
|
||||
streamId: props.codeBlockStreamId,
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -167,7 +155,7 @@ export default function StepContainerPreToolbar(
|
|||
);
|
||||
ideMessenger.post("rejectDiff", {
|
||||
filepath: fileUri,
|
||||
streamId: streamIdRef.current,
|
||||
streamId: props.codeBlockStreamId,
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -183,44 +171,40 @@ export default function StepContainerPreToolbar(
|
|||
|
||||
return (
|
||||
<TopDiv>
|
||||
<ToolbarDiv isExpanded={isExpanded} className="find-widget-skip">
|
||||
<div className="flex min-w-0 max-w-[45%] items-center">
|
||||
<ToolbarDiv isExpanded={isExpanded} className="find-widget-skip gap-3">
|
||||
<div className="flex max-w-72 flex-row items-center">
|
||||
<ChevronDownIcon
|
||||
onClick={onClickExpand}
|
||||
className={`h-3.5 w-3.5 shrink-0 cursor-pointer text-gray-400 hover:brightness-125 ${
|
||||
className={`h-3.5 w-3.5 flex-shrink-0 cursor-pointer text-gray-400 hover:brightness-125 ${
|
||||
isExpanded ? "rotate-0" : "-rotate-90"
|
||||
}`}
|
||||
/>
|
||||
<div className="w-full min-w-0">
|
||||
<FileInfo
|
||||
relativeFilepath={props.relativeFilepath}
|
||||
range={props.range}
|
||||
/>
|
||||
</div>
|
||||
<FileInfo
|
||||
relativeFilepath={props.relativeFilepath}
|
||||
range={props.range}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 max-sm:gap-1.5">
|
||||
{isGeneratingCodeBlock && (
|
||||
{props.isGeneratingCodeBlock ? (
|
||||
<GeneratingCodeLoader
|
||||
showLineCount={!isExpanded}
|
||||
codeBlockContent={codeBlockContent}
|
||||
/>
|
||||
)}
|
||||
|
||||
{!isGeneratingCodeBlock && (
|
||||
) : (
|
||||
<>
|
||||
<CopyButton text={props.codeBlockContent} />
|
||||
{props.hideApply ||
|
||||
(isTerminalCodeBlock(props.language, props.codeBlockContent) ? (
|
||||
<RunInTerminalButton command={props.codeBlockContent} />
|
||||
) : (
|
||||
<ApplyActions
|
||||
applyState={applyState}
|
||||
onClickApply={onClickApply}
|
||||
onClickAccept={onClickAcceptApply}
|
||||
onClickReject={onClickRejectApply}
|
||||
/>
|
||||
))}
|
||||
{isTerminalCodeBlock(props.language, props.codeBlockContent) ? (
|
||||
<RunInTerminalButton command={props.codeBlockContent} />
|
||||
) : (
|
||||
<ApplyActions
|
||||
disableManualApply={props.disableManualApply}
|
||||
applyState={applyState}
|
||||
onClickApply={onClickApply}
|
||||
onClickAccept={onClickAcceptApply}
|
||||
onClickReject={onClickRejectApply}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { ctxItemToRifWithContents } from "core/commands/util";
|
||||
import { memo, useEffect, useMemo } from "react";
|
||||
import { memo, useEffect, useMemo, useRef } from "react";
|
||||
import { useRemark } from "react-remark";
|
||||
import rehypeHighlight, { Options } from "rehype-highlight";
|
||||
import rehypeKatex from "rehype-katex";
|
||||
|
|
@ -17,7 +17,7 @@ import useUpdatingRef from "../../hooks/useUpdatingRef";
|
|||
import { useAppSelector } from "../../redux/hooks";
|
||||
import { selectUIConfig } from "../../redux/slices/configSlice";
|
||||
import { getContextItemsFromHistory } from "../../redux/thunks/updateFileSymbols";
|
||||
import { getFontSize, isJetBrains } from "../../util";
|
||||
import { getFontSize } from "../../util";
|
||||
import { ToolTip } from "../gui/Tooltip";
|
||||
import FilenameLink from "./FilenameLink";
|
||||
import "./katex.css";
|
||||
|
|
@ -69,7 +69,7 @@ const StyledMarkdown = styled.div<{
|
|||
overflow-x: scroll;
|
||||
overflow-y: hidden;
|
||||
|
||||
padding: 16px 8px;
|
||||
padding: 8px;
|
||||
}
|
||||
|
||||
code {
|
||||
|
|
@ -114,10 +114,6 @@ const StyledMarkdown = styled.div<{
|
|||
line-height: 1.5;
|
||||
}
|
||||
|
||||
> *:first-child {
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
> *:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
|
@ -130,6 +126,9 @@ interface StyledMarkdownPreviewProps {
|
|||
scrollLocked?: boolean;
|
||||
itemIndex?: number;
|
||||
useParentBackgroundColor?: boolean;
|
||||
disableManualApply?: boolean;
|
||||
singleCodeblockStreamId?: string;
|
||||
expandCodeblocks?: boolean;
|
||||
}
|
||||
|
||||
const HLJS_LANGUAGE_CLASSNAME_PREFIX = "language-";
|
||||
|
|
@ -196,6 +195,29 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
|
|||
}, [props.itemIndex, history, allSymbols]);
|
||||
const pastFileInfoRef = useUpdatingRef(pastFileInfo);
|
||||
|
||||
const isLastItem = useMemo(() => {
|
||||
return props.itemIndex && props.itemIndex === history.length - 1;
|
||||
}, [history.length, props.itemIndex]);
|
||||
const isLastItemRef = useUpdatingRef(isLastItem);
|
||||
|
||||
const isStreaming = useAppSelector((store) => store.session.isStreaming);
|
||||
const isStreamingRef = useUpdatingRef(isStreaming);
|
||||
|
||||
const codeblockState = useRef<{ streamId: string; isGenerating: boolean }[]>(
|
||||
[],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (props.singleCodeblockStreamId) {
|
||||
codeblockState.current = [
|
||||
{
|
||||
streamId: props.singleCodeblockStreamId,
|
||||
isGenerating: false,
|
||||
},
|
||||
];
|
||||
}
|
||||
}, [props.singleCodeblockStreamId]);
|
||||
|
||||
const [reactContent, setMarkdownSource] = useRemark({
|
||||
remarkPlugins: [
|
||||
remarkTables,
|
||||
|
|
@ -219,8 +241,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
|
|||
node.data = node.data || {};
|
||||
node.data.hProperties = node.data.hProperties || {};
|
||||
|
||||
node.data.hProperties["data-isgeneratingcodeblock"] =
|
||||
lastCodeNode === node;
|
||||
node.data.hProperties["data-islastcodeblock"] = lastCodeNode === node;
|
||||
node.data.hProperties["data-codeblockcontent"] = node.value;
|
||||
|
||||
if (node.meta) {
|
||||
|
|
@ -282,8 +303,6 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
|
|||
const { className, range } = preChildProps;
|
||||
const relativeFilePath = preChildProps["data-relativefilepath"];
|
||||
const codeBlockContent = preChildProps["data-codeblockcontent"];
|
||||
const isGeneratingCodeBlock =
|
||||
preChildProps["data-isgeneratingcodeblock"];
|
||||
|
||||
if (!props.isRenderingInStepContainer) {
|
||||
return <SyntaxHighlightedPre {...preProps} />;
|
||||
|
|
@ -291,11 +310,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
|
|||
|
||||
const language = getLanguageFromClassName(className);
|
||||
|
||||
// If we don't have a filepath show the more basic toolbar
|
||||
// that is just action buttons on hover.
|
||||
// We also use this in JB since we haven't yet implemented
|
||||
// the logic forfileUri lazy apply.
|
||||
if (!relativeFilePath || isJetBrains()) {
|
||||
if (!relativeFilePath) {
|
||||
return (
|
||||
<StepContainerPreActionButtons
|
||||
language={language}
|
||||
|
|
@ -307,6 +322,21 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
|
|||
);
|
||||
}
|
||||
|
||||
const isGeneratingCodeBlock =
|
||||
preChildProps["data-islastcodeblock"] &&
|
||||
isLastItemRef.current &&
|
||||
!isStreamingRef.current;
|
||||
|
||||
if (codeblockState.current[codeBlockIndex] === undefined) {
|
||||
codeblockState.current[codeBlockIndex] = {
|
||||
streamId: uuidv4(),
|
||||
isGenerating: isGeneratingCodeBlock,
|
||||
};
|
||||
} else {
|
||||
codeblockState.current[codeBlockIndex].isGenerating =
|
||||
isGeneratingCodeBlock;
|
||||
}
|
||||
|
||||
// We use a custom toolbar for codeblocks in the step container
|
||||
return (
|
||||
<StepContainerPreToolbar
|
||||
|
|
@ -316,6 +346,11 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
|
|||
relativeFilepath={relativeFilePath}
|
||||
isGeneratingCodeBlock={isGeneratingCodeBlock}
|
||||
range={range}
|
||||
codeBlockStreamId={
|
||||
codeblockState.current[codeBlockIndex].streamId
|
||||
}
|
||||
expanded={props.expandCodeblocks}
|
||||
disableManualApply={props.disableManualApply}
|
||||
>
|
||||
<SyntaxHighlightedPre {...preProps} />
|
||||
</StepContainerPreToolbar>
|
||||
|
|
|
|||
|
|
@ -10,7 +10,15 @@ export interface AssistantIconProps {
|
|||
export default function AssistantIcon({ assistant, size }: AssistantIconProps) {
|
||||
const sizeTw = size ?? 4;
|
||||
if (isLocalProfile(assistant)) {
|
||||
return <ComputerDesktopIcon className={`h-${sizeTw} w-${sizeTw}`} />;
|
||||
return (
|
||||
<div
|
||||
className={`h-${sizeTw} w-${sizeTw} bg-lightgray flex items-center justify-center rounded-full`}
|
||||
>
|
||||
<ComputerDesktopIcon
|
||||
className={`h-${sizeTw - 1} w-${sizeTw - 1} font-bold text-black`}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
} else if (assistant.iconUrl) {
|
||||
return (
|
||||
<img
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
import {
|
||||
ArrowTopRightOnSquareIcon,
|
||||
BuildingOfficeIcon,
|
||||
CheckIcon,
|
||||
ChevronDownIcon,
|
||||
Cog6ToothIcon,
|
||||
ExclamationTriangleIcon,
|
||||
|
|
@ -11,7 +10,7 @@ import { useContext, useEffect, useMemo, useRef } from "react";
|
|||
import { useAuth } from "../../../context/Auth";
|
||||
import { IdeMessengerContext } from "../../../context/IdeMessenger";
|
||||
import { cycleProfile, selectProfileThunk } from "../../../redux";
|
||||
import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
|
||||
import { useAppDispatch } from "../../../redux/hooks";
|
||||
import {
|
||||
fontSize,
|
||||
getMetaKeyLabel,
|
||||
|
|
@ -31,6 +30,7 @@ import { useNavigate } from "react-router-dom";
|
|||
import { vscCommandCenterInactiveBorder } from "../..";
|
||||
import { ROUTES } from "../../../util/navigation";
|
||||
import { ToolTip } from "../../gui/Tooltip";
|
||||
import { useLump } from "../../mainInput/Lump/LumpContext";
|
||||
import { useFontSize } from "../../ui/font";
|
||||
import AssistantIcon from "./AssistantIcon";
|
||||
|
||||
|
|
@ -45,6 +45,8 @@ const AssistantSelectOption = ({
|
|||
selected,
|
||||
onClick,
|
||||
}: AssistantSelectOptionProps) => {
|
||||
const tinyFont = useFontSize(-4);
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
const hasFatalErrors = useMemo(() => {
|
||||
|
|
@ -79,25 +81,30 @@ const AssistantSelectOption = ({
|
|||
disabled={hasFatalErrors}
|
||||
onClick={!hasFatalErrors ? handleOptionClick : undefined}
|
||||
fontSizeModifier={-2}
|
||||
className={selected ? "bg-list-active text-list-active-foreground" : ""}
|
||||
>
|
||||
<div className="flex w-full flex-col gap-0.5">
|
||||
<div className="flex w-full items-center justify-between">
|
||||
<div className="flex w-full items-center gap-2">
|
||||
<div className="mr-2 h-4 w-4 flex-shrink-0">
|
||||
<div
|
||||
className="flex w-full flex-col gap-0.5"
|
||||
style={{
|
||||
fontSize: tinyFont,
|
||||
}}
|
||||
>
|
||||
<div className="flex w-full items-center justify-between bg-transparent">
|
||||
<div className="flex w-full items-center gap-1.5">
|
||||
<div className="flex h-4 w-4 flex-shrink-0">
|
||||
<AssistantIcon assistant={profile} />
|
||||
</div>
|
||||
<span
|
||||
className={`line-clamp-1 flex-1 ${selected ? "font-bold" : ""}`}
|
||||
className={`line-clamp-1 flex-1 ${selected ? "font-semibold" : ""}`}
|
||||
>
|
||||
{profile.title}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex flex-row items-center gap-2">
|
||||
<div>{selected ? <CheckIcon className="h-3 w-3" /> : null}</div>
|
||||
<div className="flex flex-row items-center gap-1">
|
||||
{!profile.errors?.length ? (
|
||||
isLocalProfile(profile) ? (
|
||||
<Cog6ToothIcon
|
||||
className="h-3 w-3 flex-shrink-0 cursor-pointer"
|
||||
className="text-lightgray h-3 w-3 flex-shrink-0 cursor-pointer"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
|
|
@ -106,7 +113,7 @@ const AssistantSelectOption = ({
|
|||
/>
|
||||
) : (
|
||||
<ArrowTopRightOnSquareIcon
|
||||
className="h-3 w-3 flex-shrink-0 cursor-pointer"
|
||||
className="text-lightgray h-3 w-3 flex-shrink-0 cursor-pointer"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
|
|
@ -143,9 +150,7 @@ export default function AssistantSelect() {
|
|||
const buttonRef = useRef<HTMLButtonElement>(null);
|
||||
const { selectedProfile, selectedOrganization } = useAuth();
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const isLumpToolbarExpanded = useAppSelector(
|
||||
(state) => state.ui.isBlockSettingsToolbarExpanded,
|
||||
);
|
||||
const { isToolbarExpanded } = useLump();
|
||||
|
||||
const { profiles, session, login } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
|
|
@ -205,7 +210,7 @@ export default function AssistantSelect() {
|
|||
>
|
||||
<PlusIcon className="h-3 w-3 flex-shrink-0 select-none" />
|
||||
<span
|
||||
className={`line-clamp-1 select-none ${isLumpToolbarExpanded ? "xs:hidden sm:line-clamp-1" : ""}`}
|
||||
className={`line-clamp-1 select-none ${isToolbarExpanded ? "xs:hidden sm:line-clamp-1" : ""}`}
|
||||
>
|
||||
Create your first assistant
|
||||
</span>
|
||||
|
|
@ -227,7 +232,7 @@ export default function AssistantSelect() {
|
|||
<AssistantIcon size={3} assistant={selectedProfile} />
|
||||
</div>
|
||||
<span
|
||||
className={`line-clamp-1 select-none ${isLumpToolbarExpanded ? "xs:hidden sm:line-clamp-1" : ""}`}
|
||||
className={`line-clamp-1 select-none ${isToolbarExpanded ? "xs:hidden sm:line-clamp-1" : ""}`}
|
||||
>
|
||||
{selectedProfile.title}
|
||||
</span>
|
||||
|
|
@ -239,9 +244,9 @@ export default function AssistantSelect() {
|
|||
</ListboxButton>
|
||||
|
||||
<Transition>
|
||||
<ListboxOptions className="pb-0">
|
||||
<ListboxOptions className="min-w-[200px] pb-0">
|
||||
<div
|
||||
className={`thin-scrollbar flex max-h-[300px] flex-col gap-1 overflow-y-auto py-1`}
|
||||
className={`thin-scrollbar flex max-h-[300px] flex-col overflow-y-auto`}
|
||||
>
|
||||
{profiles?.map((profile, idx) => {
|
||||
return (
|
||||
|
|
@ -268,8 +273,13 @@ export default function AssistantSelect() {
|
|||
fontSizeModifier={-2}
|
||||
onClick={session ? onNewAssistant : () => login(false)}
|
||||
>
|
||||
<div className="flex flex-row items-center gap-2">
|
||||
<PlusIcon className="h-4 w-4 flex-shrink-0" />
|
||||
<div
|
||||
className="text-lightgray flex flex-row items-center gap-2"
|
||||
style={{
|
||||
fontSize: tinyFont,
|
||||
}}
|
||||
>
|
||||
<PlusIcon className="ml-0.5 h-3 w-3 flex-shrink-0" />
|
||||
New Assistant
|
||||
</div>
|
||||
</ListboxOption>
|
||||
|
|
@ -287,22 +297,32 @@ export default function AssistantSelect() {
|
|||
fontSize: tinyFont,
|
||||
}}
|
||||
>
|
||||
<span className="block">
|
||||
<span
|
||||
className="block"
|
||||
style={{
|
||||
fontSize: tinyFont - 1,
|
||||
}}
|
||||
>
|
||||
<code>{getMetaKeyLabel()} ⇧ '</code> to toggle
|
||||
</span>
|
||||
<div
|
||||
className="flex items-center gap-1"
|
||||
className="ml-auto flex items-center gap-1"
|
||||
onClick={() => navigate(ROUTES.CONFIG)}
|
||||
>
|
||||
{selectedOrganization?.iconUrl ? (
|
||||
<img
|
||||
src={selectedOrganization.iconUrl}
|
||||
className="h-4 w-4 rounded-full"
|
||||
className="h-3 w-3 rounded-full"
|
||||
/>
|
||||
) : (
|
||||
<BuildingOfficeIcon className="h-4 w-4" />
|
||||
)}
|
||||
<span className="hover:cursor-pointer hover:underline">
|
||||
<span
|
||||
className="hover:cursor-pointer hover:underline"
|
||||
style={{
|
||||
fontSize: tinyFont - 1,
|
||||
}}
|
||||
>
|
||||
{selectedOrganization?.name || "Personal"}
|
||||
</span>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -16,10 +16,14 @@ import {
|
|||
} from "../redux/slices/configSlice";
|
||||
import { updateIndexingStatus } from "../redux/slices/indexingSlice";
|
||||
import {
|
||||
acceptToolCall,
|
||||
addContextItemsAtIndex,
|
||||
setInactive,
|
||||
setToolCallOutput,
|
||||
updateApplyState,
|
||||
} from "../redux/slices/sessionSlice";
|
||||
import { setTTSActive } from "../redux/slices/uiSlice";
|
||||
import { streamResponseAfterToolCall } from "../redux/thunks";
|
||||
import { refreshSessionMetadata } from "../redux/thunks/session";
|
||||
import { streamResponseThunk } from "../redux/thunks/streamResponse";
|
||||
import { updateFileSymbolsFromHistory } from "../redux/thunks/updateFileSymbols";
|
||||
|
|
@ -245,6 +249,42 @@ function useSetup() {
|
|||
},
|
||||
[defaultModel],
|
||||
);
|
||||
|
||||
const activeToolStreamId = useAppSelector(
|
||||
(store) => store.session.activeToolStreamId,
|
||||
);
|
||||
useWebviewListener(
|
||||
"updateApplyState",
|
||||
async (state) => {
|
||||
// dispatch(
|
||||
// updateCurCheckpoint({
|
||||
// filepath: state.filepath,
|
||||
// content: state.fileContent,
|
||||
// }),
|
||||
// );
|
||||
dispatch(updateApplyState(state));
|
||||
if (
|
||||
activeToolStreamId &&
|
||||
state.streamId === activeToolStreamId[0] &&
|
||||
state.status === "closed"
|
||||
) {
|
||||
// const output: ContextItem = {
|
||||
// name: "Edit tool output",
|
||||
// content: "Completed edit",
|
||||
// description: "",
|
||||
// };
|
||||
dispatch(acceptToolCall());
|
||||
dispatch(setToolCallOutput([]));
|
||||
dispatch(
|
||||
streamResponseAfterToolCall({
|
||||
toolCallId: activeToolStreamId[1],
|
||||
toolOutput: [],
|
||||
}),
|
||||
);
|
||||
}
|
||||
},
|
||||
[activeToolStreamId],
|
||||
);
|
||||
}
|
||||
|
||||
export default useSetup;
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ import TimelineItem from "../../components/gui/TimelineItem";
|
|||
import { NewSessionButton } from "../../components/mainInput/belowMainInput/NewSessionButton";
|
||||
import ThinkingBlockPeek from "../../components/mainInput/belowMainInput/ThinkingBlockPeek";
|
||||
import ContinueInputBox from "../../components/mainInput/ContinueInputBox";
|
||||
import resolveEditorContent from "../../components/mainInput/tiptap/resolveInput";
|
||||
import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils";
|
||||
import { useOnboardingCard } from "../../components/OnboardingCard";
|
||||
import StepContainer from "../../components/StepContainer";
|
||||
import AcceptRejectAllButtons from "../../components/StepContainer/AcceptRejectAllButtons";
|
||||
|
|
@ -75,6 +75,8 @@ const StepsDiv = styled.div`
|
|||
}
|
||||
`;
|
||||
|
||||
export const MAIN_EDITOR_INPUT_ID = "main-editor-input";
|
||||
|
||||
function fallbackRender({ error, resetErrorBoundary }: any) {
|
||||
// Call resetErrorBoundary() to reset the error boundary and retry the render.
|
||||
|
||||
|
|
@ -295,7 +297,7 @@ export function Chat() {
|
|||
|
||||
<StepsDiv
|
||||
ref={stepsDivRef}
|
||||
className={`mt-[2px] overflow-y-scroll ${showPageHeader ? "" : "pt-[8px]"} ${showScrollbar ? "thin-scrollbar" : "no-scrollbar"} ${history.length > 0 ? "flex-1" : ""}`}
|
||||
className={`mt-3 overflow-y-scroll ${showPageHeader ? "" : "pt-[8px]"} ${showScrollbar ? "thin-scrollbar" : "no-scrollbar"} ${history.length > 0 ? "flex-1" : ""}`}
|
||||
>
|
||||
{highlights}
|
||||
{history.map((item, index: number) => (
|
||||
|
|
@ -406,7 +408,7 @@ export function Chat() {
|
|||
onEnter={(editorState, modifiers, editor) =>
|
||||
sendInput(editorState, modifiers, undefined, editor)
|
||||
}
|
||||
inputId={"main-editor"}
|
||||
inputId={MAIN_EDITOR_INPUT_ID}
|
||||
/>
|
||||
)}
|
||||
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue