Merge branch 'main' into dallin/gui-strict-null-checks

This commit is contained in:
Nate 2024-11-27 13:45:37 -08:00
commit 591497a440
43 changed files with 3973 additions and 258 deletions

View file

@ -0,0 +1,25 @@
name: Submit Gradle Dependency Graph For Dependabot
on:
push:
branches: ['main']
permissions:
contents: write
jobs:
dependency-submission:
runs-on: ubuntu-latest
steps:
- name: Checkout sources
uses: actions/checkout@v4
- name: Setup Java
uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: 17
- name: Generate and submit dependency graph
uses: gradle/actions/dependency-submission@v4
with:
# The gradle project is not in the root of the repository.
build-root-directory: extensions/intellij

View file

@ -252,7 +252,7 @@ export class CompletionProvider {
//////////
// Save to cache
if (!outcome.cacheHit) {
if (!outcome.cacheHit && helper.options.useCache) {
(await this.autocompleteCache).put(outcome.prefix, outcome.completion);
}

View file

@ -87,7 +87,7 @@ const getDiffSnippets = async (
): Promise<AutocompleteDiffSnippet[]> => {
const diff = await ide.getDiff(true);
return [diff].map((item) => {
return diff.map((item) => {
return {
content: item,
type: AutocompleteSnippetType.Diff,

View file

@ -77,25 +77,32 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = {
suffix: string,
filepath: string,
reponame: string,
allSnippets: AutocompleteSnippet[],
snippets: AutocompleteSnippet[],
): [string, string] => {
const snippets = allSnippets.filter(
(snippet) => snippet.type === AutocompleteSnippetType.Code,
) as AutocompleteCodeSnippet[];
if (snippets.length === 0) {
if (suffix.trim().length === 0 && prefix.trim().length === 0) {
return [`+++++ ${getLastNPathParts(filepath, 2)}\n${prefix}`, suffix];
}
return [prefix, suffix];
}
const relativePaths = shortestRelativePaths([
...snippets.map((snippet) => snippet.filepath),
...snippets.map((snippet) =>
"filepath" in snippet ? snippet.filepath : "Untitled.txt",
),
filepath,
]);
const otherFiles = snippets
.map((snippet, i) => `+++++ ${relativePaths[i]}\n${snippet.content}`)
.map((snippet, i) => {
if (snippet.type === AutocompleteSnippetType.Diff) {
return snippet.content;
}
return `+++++ ${relativePaths[i]}\n${snippet.content}`;
})
.join("\n\n");
return [
`${otherFiles}\n\n+++++ ${
relativePaths[relativePaths.length - 1]

View file

@ -100,7 +100,7 @@ export const formatSnippets = (
return item.content + `\n${commentMark}\n${commentMark}`;
}
return item.content + "\n\n";
return item.content;
})
.join("\n") + `\n${currentFilepathComment}`
);

View file

@ -8,15 +8,16 @@ const CommitMessageCommand: SlashCommand = {
const includeUnstaged = params?.includeUnstaged ?? false;
const diff = await ide.getDiff(includeUnstaged);
if (!diff || diff.trim() === "") {
if (diff.length === 0) {
yield "No changes detected. Make sure you are in a git repository with current changes.";
return;
}
const prompt = `${diff}\n\nGenerate a commit message for the above set of changes. First, give a single sentence, no more than 80 characters. Then, after 2 line breaks, give a list of no more than 5 short bullet points, each no more than 40 characters. Output nothing except for the commit message, and don't surround it in quotes.`;
for await (const chunk of llm.streamChat([
{ role: "user", content: prompt },
], new AbortController().signal)) {
const prompt = `${diff.join("\n")}\n\nGenerate a commit message for the above set of changes. First, give a single sentence, no more than 80 characters. Then, after 2 line breaks, give a list of no more than 5 short bullet points, each no more than 40 characters. Output nothing except for the commit message, and don't surround it in quotes.`;
for await (const chunk of llm.streamChat(
[{ role: "user", content: prompt }],
new AbortController().signal,
)) {
yield stripImages(chunk.content);
}
},

View file

@ -125,7 +125,10 @@ export function slashCommandFromPromptFile(
systemMessage,
);
for await (const chunk of context.llm.streamChat(messages, new AbortController().signal)) {
for await (const chunk of context.llm.streamChat(
messages,
new AbortController().signal,
)) {
yield stripImages(chunk.content);
}
@ -173,7 +176,7 @@ async function renderPrompt(
const diff = await context.ide.getDiff(false);
const currentFile = await context.ide.getCurrentFile();
const inputData: Record<string, string> = {
diff,
diff: diff.join("\n"),
input: userInput,
};
if (currentFile) {

View file

@ -22,9 +22,9 @@ class DiffContextProvider extends BaseContextProvider {
{
description: "The current git diff",
content:
diff.trim() === ""
diff.length === 0
? "Git shows no current changes."
: `\`\`\`git diff\n${diff}\n\`\`\``,
: `\`\`\`git diff\n${diff.join("\n")}\n\`\`\``,
name: "Git Diff",
},
];

View file

@ -410,6 +410,16 @@ export class Core {
if (config.experimental?.readResponseTTS && "completion" in next.value) {
void TTS.read(next.value?.completion);
}
void Telemetry.capture(
"chat",
{
model: model.model,
provider: model.providerName,
},
true,
);
return { done: true, content: next.value };
}

2
core/index.d.ts vendored
View file

@ -503,7 +503,7 @@ export interface IdeSettings {
export interface IDE {
getIdeInfo(): Promise<IdeInfo>;
getIdeSettings(): Promise<IdeSettings>;
getDiff(includeUnstaged: boolean): Promise<string>;
getDiff(includeUnstaged: boolean): Promise<string[]>;
getClipboardContent(): Promise<{ text: string; copiedAt: string }>;
isTelemetryEnabled(): Promise<boolean>;
getUniqueId(): Promise<string>;

View file

@ -74,7 +74,7 @@ class OpenAI extends BaseLLM {
text: part.text,
};
if (part.type === "imageUrl") {
msg.image_url = { ...part.imageUrl, detail: "low" };
msg.image_url = { ...part.imageUrl, detail: "auto" };
msg.type = "image_url";
}
return msg;
@ -130,10 +130,7 @@ class OpenAI extends BaseLLM {
finalOptions.max_completion_tokens = options.maxTokens;
finalOptions.max_tokens = undefined;
// b) don't support streaming currently
finalOptions.stream = false;
// c) don't support system message
// b) don't support system message
finalOptions.messages = finalOptions.messages?.filter(
(message: any) => message?.role !== "system",
);
@ -229,7 +226,7 @@ class OpenAI extends BaseLLM {
...args,
stream: true,
}),
signal
signal,
});
for await (const value of streamSse(response)) {
@ -274,7 +271,7 @@ class OpenAI extends BaseLLM {
method: "POST",
headers: this._getHeaders(),
body: JSON.stringify(body),
signal
signal,
});
// Handle non-streaming response
@ -318,7 +315,7 @@ class OpenAI extends BaseLLM {
"x-api-key": this.apiKey ?? "",
Authorization: `Bearer ${this.apiKey}`,
},
signal
signal,
});
for await (const chunk of streamSse(resp)) {
yield chunk.choices[0].delta.content;

View file

@ -64,7 +64,7 @@ export type ToIdeFromWebviewOrCoreProtocol = {
getPinnedFiles: [undefined, string[]];
showLines: [{ filepath: string; startLine: number; endLine: number }, void];
readRangeInFile: [{ filepath: string; range: Range }, string];
getDiff: [{ includeUnstaged: boolean }, string];
getDiff: [{ includeUnstaged: boolean }, string[]];
getWorkspaceConfigs: [undefined, ContinueRcJson[]];
getTerminalContents: [undefined, string];
getDebugLocals: [{ threadIndex: number }, string];

View file

@ -125,8 +125,8 @@ class FileSystemIde implements IDE {
return Promise.resolve([]);
}
getDiff(includeUnstaged: boolean): Promise<string> {
return Promise.resolve("");
getDiff(includeUnstaged: boolean): Promise<string[]> {
return Promise.resolve([]);
}
getClipboardContent(): Promise<{ text: string; copiedAt: string }> {

View file

@ -15,7 +15,7 @@ The highlighted code you’ve selected by pressing <kbd>cmd/ctrl</kbd> + <kbd>L<
## Active file
You can include the currently open file as context by pressing <kbd>cmd/ctrl</kbd> + <kbd>opt</kbd> + <kbd>enter</kbd> when you send your request.
You can include the currently open file as context by pressing <kbd>cmd</kbd> + <kbd>opt</kbd> + <kbd>enter</kbd> (Mac) or <kbd>ctrl</kbd> + <kbd>alt</kbd> + <kbd>enter</kbd> (Windows) when you send your request.
## Specific file

View file

@ -36,7 +36,6 @@ import type {
RangeInFile,
Thread,
} from "core";
import { text } from "stream/consumers";
class VsCodeIde implements IDE {
ideUtils: VsCodeIdeUtils;
@ -312,7 +311,7 @@ class VsCodeIde implements IDE {
return Promise.resolve(vscode.env.machineId);
}
async getDiff(includeUnstaged: boolean): Promise<string> {
async getDiff(includeUnstaged: boolean): Promise<string[]> {
return await this.ideUtils.getDiff(includeUnstaged);
}

View file

@ -77,7 +77,7 @@ describe("IDE Utils", () => {
test("noDiff", async () => {
const noDiff = await utils.getDiff(false);
assert(noDiff === "");
assert(noDiff.length === 0);
});
test.skip("getBranch", async () => {

View file

@ -570,8 +570,20 @@ export class VsCodeIdeUtils {
return repo?.state?.HEAD?.name || "NONE";
}
async getDiff(includeUnstaged: boolean): Promise<string> {
let diffs: string[] = [];
private splitDiff(diffString: string): string[] {
const fileDiffHeaderRegex = /(?=diff --git a\/.* b\/.*)/;
const diffs = diffString.split(fileDiffHeaderRegex);
if (diffs[0].trim() === "") {
diffs.shift();
}
return diffs;
}
async getDiff(includeUnstaged: boolean): Promise<string[]> {
const diffs: string[] = [];
for (const dir of this.getWorkspaceDirectories()) {
const repo = await this.getRepo(vscode.Uri.file(dir));
@ -587,9 +599,7 @@ export class VsCodeIdeUtils {
}
}
const fullDiff = diffs.join("\n\n");
return fullDiff;
return diffs.flatMap((diff) => this.splitDiff(diff));
}
getHighlightedCode(): RangeInFile[] {

32
gui/.eslintrc.json Normal file
View file

@ -0,0 +1,32 @@
{
"root": true,
"parser": "@typescript-eslint/parser",
"plugins": [
"@typescript-eslint",
"strict-null-checks",
"eslint-plugin-react"
],
"parserOptions": {
"project": "gui/tsconfig.strictNullChecks.json"
},
// "extends": [
// "eslint:recommended",
// "plugin:@typescript-eslint/recommended",
// "plugin:@typescript-eslint/recommended-requiring-type-checking"
// "plugin:react/recommended"
// ],
"rules": {
"strict-null-checks/all": "warn"
},
"overrides": [
{
"files": ["src/**/*.{js,ts,jsx,tsx}"]
}
],
"ignorePatterns": ["dist/**/*"],
"env": {
"browser": true,
"node": true,
"es6": true
}
}

3542
gui/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -88,10 +88,14 @@
"@vitest/coverage-v8": "^2.1.3",
"@vitest/ui": "^2.1.3",
"autoprefixer": "^10.4.13",
"eslint": "^9.15.0",
"eslint-plugin-react": "^7.37.2",
"eslint-plugin-strict-null-checks": "^0.1.3",
"jsdom": "^25.0.1",
"postcss": "^8.4.21",
"tailwindcss": "^3.2.7",
"typescript": "^4.9.3",
"typescript-eslint": "^8.16.0",
"vite": "^4.1.0",
"vitest": "^2.1.3"
},

View file

@ -1,11 +1,8 @@
import { useDispatch } from "react-redux";
import { RouterProvider, createMemoryRouter } from "react-router-dom";
import Layout from "./components/Layout";
import { SubmenuContextProvidersContext } from "./context/SubmenuContextProviders";
import { VscThemeContext } from "./context/VscTheme";
import { VscThemeProvider } from "./context/VscTheme";
import useSetup from "./hooks/useSetup";
import useSubmenuContextProviders from "./hooks/useSubmenuContextProviders";
import { useVscTheme } from "./hooks/useVscTheme";
import { AddNewModel, ConfigureProvider } from "./pages/AddNewModel";
import ConfigErrorPage from "./pages/config-error";
import Edit from "./pages/edit";
@ -18,6 +15,7 @@ import MorePage from "./pages/More";
import SettingsPage from "./pages/settings";
import Stats from "./pages/stats";
import { ROUTES } from "./util/navigation";
import { SubmenuContextProvidersProvider } from "./context/SubmenuContextProviders";
const router = createMemoryRouter([
{
@ -77,21 +75,25 @@ const router = createMemoryRouter([
},
]);
function App() {
/*
Prevents entire app from rerendering continuously with useSetup in App
TODO - look into a more redux-esque way to do this
*/
function SetupListeners() {
const dispatch = useDispatch();
useSetup(dispatch);
return <></>;
}
const vscTheme = useVscTheme();
const submenuContextProvidersMethods = useSubmenuContextProviders();
function App() {
return (
<VscThemeContext.Provider value={vscTheme}>
<SubmenuContextProvidersContext.Provider
value={submenuContextProvidersMethods}
>
<VscThemeProvider>
<SubmenuContextProvidersProvider>
<RouterProvider router={router} />
</SubmenuContextProvidersContext.Provider>
</VscThemeContext.Provider>
</SubmenuContextProvidersProvider>
<SetupListeners />
</VscThemeProvider>
);
}

View file

@ -75,28 +75,6 @@ const Layout = () => {
(state: RootState) => state.uiState.showDialog,
);
const timeline = useSelector((state: RootState) => state.state.history);
useEffect(() => {
const handleKeyDown = (event: any) => {
if (isMetaEquivalentKeyPressed(event) && event.code === "KeyC") {
const selection = window.getSelection()?.toString();
if (selection) {
// Copy to clipboard
setTimeout(() => {
navigator.clipboard.writeText(selection);
}, 100);
}
}
};
window.addEventListener("keydown", handleKeyDown);
return () => {
window.removeEventListener("keydown", handleKeyDown);
};
}, [timeline]);
useWebviewListener(
"openDialogMessage",
async (message) => {
@ -211,14 +189,42 @@ const Layout = () => {
[navigate],
);
useWebviewListener("setEditStatus", async ({ status, fileAfterEdit }) => {
dispatch(setEditStatus({ status, fileAfterEdit }));
});
useWebviewListener(
"setEditStatus",
async ({ status, fileAfterEdit }) => {
dispatch(setEditStatus({ status, fileAfterEdit }));
},
[],
);
useWebviewListener("exitEditMode", async () => {
dispatch(setEditDone());
navigate("/");
});
useWebviewListener(
"exitEditMode",
async () => {
dispatch(setEditDone());
navigate("/");
},
[navigate],
);
useEffect(() => {
const handleKeyDown = (event: any) => {
if (isMetaEquivalentKeyPressed(event) && event.code === "KeyC") {
const selection = window.getSelection()?.toString();
if (selection) {
// Copy to clipboard
setTimeout(() => {
navigator.clipboard.writeText(selection);
}, 100);
}
}
};
window.addEventListener("keydown", handleKeyDown);
return () => {
window.removeEventListener("keydown", handleKeyDown);
};
}, []);
useEffect(() => {
if (

View file

@ -4,12 +4,11 @@ import { useDispatch, useSelector } from "react-redux";
import styled, { keyframes } from "styled-components";
import { defaultBorderRadius, vscBackground } from "..";
import { useWebviewListener } from "../../hooks/useWebviewListener";
import { selectSlashCommands } from "../../redux/selectors";
import { selectSlashCommandComboBoxInputs } from "../../redux/selectors";
import { newSession, setMessageAtIndex } from "../../redux/slices/stateSlice";
import { RootState } from "../../redux/store";
import ContextItemsPeek from "./ContextItemsPeek";
import TipTapEditor from "./TipTapEditor";
interface ContinueInputBoxProps {
isLastUserInput: boolean;
isMainInput?: boolean;
@ -64,7 +63,7 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
const dispatch = useDispatch();
const active = useSelector((store: RootState) => store.state.active);
const availableSlashCommands = useSelector(selectSlashCommands);
const availableSlashCommands = useSelector(selectSlashCommandComboBoxInputs);
const availableContextProviders = useSelector(
(store: RootState) => store.state.config.contextProviders,
);

View file

@ -37,7 +37,7 @@ import {
vscInputBorderFocus,
} from "..";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { SubmenuContextProvidersContext } from "../../context/SubmenuContextProviders";
import { useSubmenuContextProviders } from "../../context/SubmenuContextProviders";
import useHistory from "../../hooks/useHistory";
import { useInputHistory } from "../../hooks/useInputHistory";
import useIsOSREnabled from "../../hooks/useIsOSREnabled";
@ -131,12 +131,13 @@ const HoverTextDiv = styled.div`
justify-content: center;
`;
const IMAGE_RESOLUTION = 1024;
function getDataUrlForFile(
file: File,
img: HTMLImageElement,
): string | undefined {
const targetWidth = 512;
const targetHeight = 512;
const targetWidth = IMAGE_RESOLUTION;
const targetHeight = IMAGE_RESOLUTION;
const scaleFactor = Math.min(
targetWidth / img.width,
targetHeight / img.height,
@ -177,7 +178,7 @@ function TipTapEditor(props: TipTapEditorProps) {
const dispatch = useDispatch();
const ideMessenger = useContext(IdeMessengerContext);
const { getSubmenuContextItems } = useContext(SubmenuContextProvidersContext);
const { getSubmenuContextItems } = useSubmenuContextProviders();
const historyLength = useSelector(
(store: RootState) => store.state.history.length,
@ -660,11 +661,12 @@ function TipTapEditor(props: TipTapEditorProps) {
useWebviewListener(
"focusContinueInput",
async (data) => {
dispatch(clearCodeToEdit());
if (!props.isMainInput) {
return;
}
dispatch(clearCodeToEdit());
if (historyLength > 0) {
await saveSession();
}

View file

@ -1,6 +1,6 @@
import { ChevronDownIcon } from "@heroicons/react/24/outline";
import { debounce } from "lodash";
import { useContext, useEffect, useRef, useState } from "react";
import { useContext, useEffect, useMemo, useRef, useState } from "react";
import { useSelector } from "react-redux";
import styled, { css, keyframes } from "styled-components";
import { v4 as uuidv4 } from "uuid";
@ -80,11 +80,12 @@ export default function StepContainerPreToolbar(
(state: RootState) => state.state.nextCodeBlockToApplyIndex,
);
const applyState = useSelector((store: RootState) =>
store.state.applyStates.find(
(state) => state.streamId === streamIdRef.current,
),
const applyStates = useSelector(
(store: RootState) => store.state.applyStates,
);
const applyState = useMemo(() => {
return applyStates.find((state) => state.streamId === streamIdRef.current);
}, [applyStates, streamIdRef]);
// 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

View file

@ -24,6 +24,7 @@ import { RootState } from "../../redux/store";
import { ContextItemWithId, SymbolWithRange } from "core";
import SymbolLink from "./SymbolLink";
import { useSelector } from "react-redux";
import useUpdatingRef from "../../hooks/useUpdatingRef";
const StyledMarkdown = styled.div<{
fontSize?: number;
@ -155,21 +156,17 @@ function processCodeBlocks(tree: any) {
const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
props: StyledMarkdownPreviewProps,
) {
// The refs are a workaround because rehype options are stored on initiation
// So they won't use the most up-to-date state values
// So in this case we just put them in refs
const contextItems = useSelector(
(state: RootState) =>
state.state.history[props.itemIndex - 1]?.contextItems,
);
const contextItemsRef = useUpdatingRef(contextItems);
const symbols = useSelector((state: RootState) => state.state.symbols);
// The refs are a workaround because rehype options are stored on initiation
// So they won't use the most up-to-date state values
// So in this case we just put them in refs
const symbolsRef = useRef<SymbolWithRange[]>([]);
const contextItemsRef = useRef<ContextItemWithId[]>([]);
useEffect(() => {
contextItemsRef.current = contextItems || [];
}, [contextItems]);
useEffect(() => {
// Note, before I was only looking for symbols that matched
// Context item files on current history item

View file

@ -67,7 +67,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
setDialogMessage(
<ConfirmationDialog
text={
"Welcome to Continue for teams! Using the toggle in the bottom right, you can switch between your local profile (defined by config.json) and team profiles (defined in the Continue for teams web app). Each profile defines a set of models, slash commands, context providers, and other settings to customize Continue."
"Welcome to Continue for teams! Using account icon in the top right, you can switch between your local profile (defined by config.json) and team profiles (defined in the Continue for teams web app). Each profile defines a set of models, slash commands, context providers, and other settings to customize Continue."
}
hideCancelButton={true}
confirmText="Ok"

View file

@ -1,17 +0,0 @@
import { ContextSubmenuItem } from "core";
import { createContext } from "react";
export interface ContextSubmenuItemWithProvider extends ContextSubmenuItem {
providerTitle: string;
}
export const SubmenuContextProvidersContext = createContext<{
getSubmenuContextItems: (
providerTitle: string | undefined,
query: string,
) => ContextSubmenuItemWithProvider[];
addItem: (providerTitle: string, item: ContextSubmenuItem) => void;
}>({
getSubmenuContextItems: () => [],
addItem: () => {},
});

View file

@ -1,5 +1,5 @@
import { ContextSubmenuItem } from "core";
import { WebviewMessengerResult } from "core/protocol/util";
import { createContext } from "react";
import {
deduplicateArray,
getBasename,
@ -9,11 +9,10 @@ import {
import MiniSearch, { SearchResult } from "minisearch";
import { useCallback, useContext, useEffect, useMemo, useState } from "react";
import { useSelector } from "react-redux";
import { IdeMessengerContext } from "../context/IdeMessenger";
import { IdeMessengerContext } from "./IdeMessenger";
import { selectContextProviderDescriptions } from "../redux/selectors";
import { getLocalStorage } from "../util/localStorage";
import { useWebviewListener } from "./useWebviewListener";
import { RootState } from "../redux/store";
import { useWebviewListener } from "../hooks/useWebviewListener";
const MINISEARCH_OPTIONS = {
prefix: true,
@ -22,7 +21,31 @@ const MINISEARCH_OPTIONS = {
const MAX_LENGTH = 70;
function useSubmenuContextProviders() {
export interface ContextSubmenuItemWithProvider extends ContextSubmenuItem {
providerTitle: string;
}
interface SubtextContextProvidersContextType {
getSubmenuContextItems: (
providerTitle: string | undefined,
query: string,
) => (ContextSubmenuItem & { providerTitle: string })[];
addItem: (providerTitle: string, item: ContextSubmenuItem) => void;
}
const initialContextProviders: SubtextContextProvidersContextType = {
getSubmenuContextItems: () => [],
addItem: () => {},
};
const SubmenuContextProvidersContext =
createContext<SubtextContextProvidersContextType>(initialContextProviders);
export const SubmenuContextProvidersProvider = ({
children,
}: {
children: React.ReactNode;
}) => {
const [minisearches, setMinisearches] = useState<{
[id: string]: MiniSearch;
}>({});
@ -33,33 +56,30 @@ function useSubmenuContextProviders() {
const contextProviderDescriptions = useSelector(
selectContextProviderDescriptions,
);
const disableIndexing = useSelector(
(store: RootState) => store.state.config.disableIndexing,
);
const [loaded, setLoaded] = useState(false);
const [initialLoadComplete, setInitialLoadComplete] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [autoLoadTriggered, setAutoLoadTriggered] = useState(false);
const config = useSelector((store: RootState) => store.state.config);
const ideMessenger = useContext(IdeMessengerContext);
const memoizedGetOpenFileItems = useMemo(() => {
return async () => {
const openFiles = await ideMessenger.ide.getOpenFiles();
const openFileGroups = groupByLastNPathParts(openFiles, 2);
const getOpenFilesItems = useCallback(async () => {
const openFiles = await ideMessenger.ide.getOpenFiles();
const openFileGroups = groupByLastNPathParts(openFiles, 2);
return openFiles.map((file) => ({
id: file,
title: getBasename(file),
description: getUniqueFilePath(file, openFileGroups),
providerTitle: "file",
}));
};
return openFiles.map((file) => ({
id: file,
title: getBasename(file),
description: getUniqueFilePath(file, openFileGroups),
providerTitle: "file",
}));
}, [ideMessenger]);
useWebviewListener("refreshSubmenuItems", async (data) => {
if (!isLoading) {
setLoaded(false);
setInitialLoadComplete(false);
setAutoLoadTriggered((prev) => !prev); // Toggle to trigger effect
}
@ -76,7 +96,7 @@ function useSubmenuContextProviders() {
setMinisearches((prev) => ({ ...prev, [data.provider]: minisearch }));
if (data.provider === "file") {
const openFiles = await memoizedGetOpenFileItems();
const openFiles = await getOpenFilesItems();
setFallbackResults((prev) => ({
...prev,
file: [
@ -106,7 +126,7 @@ function useSubmenuContextProviders() {
let isMounted = true;
const refreshOpenFiles = async () => {
if (!isMounted) return;
const openFiles = await memoizedGetOpenFileItems();
const openFiles = await getOpenFilesItems();
setFallbackResults((prev) => ({
...prev,
file: deduplicateArray(
@ -124,7 +144,7 @@ function useSubmenuContextProviders() {
isMounted = false;
clearInterval(interval);
};
}, [memoizedGetOpenFileItems]);
}, [getOpenFilesItems]);
const getSubmenuSearchResults = useMemo(
() =>
@ -208,10 +228,9 @@ function useSubmenuContextProviders() {
);
useEffect(() => {
if (contextProviderDescriptions.length === 0 || loaded || isLoading) {
if (contextProviderDescriptions.length === 0 || isLoading) {
return;
}
setLoaded(true);
setIsLoading(true);
const loadSubmenuItems = async () => {
@ -219,7 +238,7 @@ function useSubmenuContextProviders() {
await Promise.all(
contextProviderDescriptions.map(async (description) => {
const shouldSkipProvider =
description.dependsOnIndexing && config.disableIndexing;
description.dependsOnIndexing && disableIndexing;
if (shouldSkipProvider) {
console.debug(
@ -258,7 +277,7 @@ function useSubmenuContextProviders() {
}));
if (description.title === "file") {
const openFiles = await memoizedGetOpenFileItems();
const openFiles = await getOpenFilesItems();
setFallbackResults((prev) => ({
...prev,
file: [
@ -289,23 +308,20 @@ function useSubmenuContextProviders() {
}
};
loadSubmenuItems().catch((error) => {
console.error("Error in loadSubmenuItems:", error);
setInitialLoadComplete(true);
setIsLoading(false);
});
}, [contextProviderDescriptions, loaded, autoLoadTriggered]);
loadSubmenuItems();
}, [contextProviderDescriptions, autoLoadTriggered]);
useWebviewListener("configUpdate", async () => {
// When config is updated (for example switching to a different workspace)
// we need to reload the context providers.
setLoaded(false);
});
return (
<SubmenuContextProvidersContext.Provider
value={{
getSubmenuContextItems,
addItem,
}}
>
{children}
</SubmenuContextProvidersContext.Provider>
);
};
return {
getSubmenuContextItems,
addItem,
};
}
export default useSubmenuContextProviders;
export const useSubmenuContextProviders = () =>
useContext(SubmenuContextProvidersContext);

View file

@ -1,3 +0,0 @@
import { createContext } from "react";
export const VscThemeContext = createContext<any>(undefined);

View file

@ -1,6 +1,6 @@
import { useState } from "react";
import { createContext, useContext, useState } from "react";
import { parseHexColor } from "../components";
import { useWebviewListener } from "./useWebviewListener";
import { useWebviewListener } from "../hooks/useWebviewListener";
const hljsToTextMate: Record<string, string[]> = {
".hljs-comment": ["comment"],
@ -149,9 +149,24 @@ function fallbackTheme() {
};
}
export function useVscTheme() {
const [theme, setTheme] = useState<any>(
constructTheme(window.fullColorTheme || {}),
interface VscThemeContextType {
theme: Record<string, string>;
}
const initialVscThemeContext: VscThemeContextType = {
theme: constructTheme(window.fullColorTheme || {}),
};
export const VscThemeContext = createContext<VscThemeContextType>(
initialVscThemeContext,
);
export const VscThemeProvider = ({
children,
}: {
children: React.ReactNode;
}) => {
const [theme, setTheme] = useState<Record<string, string>>(
initialVscThemeContext.theme,
);
useWebviewListener("setTheme", async (data) => {
@ -159,5 +174,11 @@ export function useVscTheme() {
setTheme(constructTheme(data.theme));
});
return theme;
}
return (
<VscThemeContext.Provider value={{ theme }}>
{children}
</VscThemeContext.Provider>
);
};
export const useVscTheme = () => useContext(VscThemeContext);

View file

@ -5,7 +5,7 @@ import { defaultBorderRadius } from "../components";
import TipTapEditor from "../components/mainInput/TipTapEditor";
import { IdeMessengerContext } from "../context/IdeMessenger";
import useSetup from "../hooks/useSetup";
import { selectSlashCommands } from "../redux/selectors";
import { selectSlashCommandComboBoxInputs } from "../redux/selectors";
import { RootState } from "../redux/store";
const EditorInsetDiv = styled.div`
@ -18,7 +18,7 @@ const EditorInsetDiv = styled.div`
function EditorInset() {
const dispatch = useDispatch();
const availableSlashCommands = useSelector(selectSlashCommands);
const availableSlashCommands = useSelector(selectSlashCommandComboBoxInputs);
const availableContextProviders = useSelector(
(store: RootState) => store.state.config.contextProviders,
);

View file

@ -14,7 +14,7 @@ import { constructMessages } from "core/llm/constructMessages";
import { stripImages } from "core/llm/images";
import { getBasename, getRelativePath } from "core/util";
import { usePostHog } from "posthog-js/react";
import { useEffect, useRef, useState } from "react";
import { useEffect, useMemo, useRef, useState } from "react";
import { useSelector } from "react-redux";
import resolveEditorContent, {
hasSlashCommandOrContextProvider,
@ -37,18 +37,18 @@ import { resetNextCodeBlockToApplyIndex } from "../redux/slices/stateSlice";
import { RootState } from "../redux/store";
import useHistory from "./useHistory";
import { updateFileSymbolsFromContextItems } from "../util/symbols";
import {
selectDefaultContextProviders,
selectSlashCommands,
} from "../redux/selectors";
function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) {
const posthog = usePostHog();
const defaultModel = useSelector(defaultModelSelector);
const defaultContextProviders = useSelector(
(store: RootState) => store.state.config.experimental?.defaultContext ?? [],
);
const defaultContextProviders = useSelector(selectDefaultContextProviders);
const slashCommands = useSelector(
(store: RootState) => store.state.config.slashCommands || [],
);
const slashCommands = useSelector(selectSlashCommands);
const history = useSelector((store: RootState) => store.state.history);
const active = useSelector((store: RootState) => store.state.active);

View file

@ -1,5 +1,5 @@
import { Dispatch } from "@reduxjs/toolkit";
import { useCallback, useContext, useEffect, useRef, useState } from "react";
import { useCallback, useContext, useEffect, useRef } from "react";
import { useSelector } from "react-redux";
import { VSC_THEME_COLOR_VARS } from "../components";
import { IdeMessengerContext } from "../context/IdeMessenger";
@ -16,9 +16,8 @@ import {
} from "../redux/slices/stateSlice";
import { RootState } from "../redux/store";
import { debounce } from "lodash";
import { isJetBrains } from "../util";
import { getLocalStorage, setLocalStorage } from "../util/localStorage";
import { setLocalStorage } from "../util/localStorage";
import useChatHandler from "./useChatHandler";
import { useWebviewListener } from "./useWebviewListener";
import { updateFileSymbolsFromContextItems } from "../util/symbols";
@ -27,33 +26,38 @@ function useSetup(dispatch: Dispatch) {
const ideMessenger = useContext(IdeMessengerContext);
const history = useSelector((store: RootState) => store.state.history);
const initialConfigLoad = useRef(false);
const loadConfig = useCallback(async () => {
const result = await ideMessenger.request(
"config/getSerializedProfileInfo",
undefined,
);
if (result.status === "error") {
return;
}
const { config, profileId } = result.content;
dispatch(setConfig(config));
dispatch(setSelectedProfileId(profileId));
initialConfigLoad.current = true;
setLocalStorage("disableIndexing", config.disableIndexing || false);
const hasLoadedConfig = useRef(false);
const loadConfig = useCallback(
async (initial: boolean) => {
const result = await ideMessenger.request(
"config/getSerializedProfileInfo",
undefined,
);
if (result.status === "error") {
return;
}
const { config, profileId } = result.content;
if (initial && hasLoadedConfig.current) {
return;
}
hasLoadedConfig.current = true;
dispatch(setConfig(config));
dispatch(setSelectedProfileId(profileId));
// Perform any actions needed with the config
if (config.ui?.fontSize) {
setLocalStorage("fontSize", config.ui.fontSize);
document.body.style.fontSize = `${config.ui.fontSize}px`;
}
}, [dispatch, ideMessenger, initialConfigLoad]);
// Perform any actions needed with the config
if (config.ui?.fontSize) {
setLocalStorage("fontSize", config.ui.fontSize);
document.body.style.fontSize = `${config.ui.fontSize}px`;
}
},
[dispatch, ideMessenger, hasLoadedConfig],
);
// Load config from the IDE
useEffect(() => {
loadConfig();
loadConfig(true);
const interval = setInterval(() => {
if (initialConfigLoad.current) {
if (hasLoadedConfig.current) {
// Docs init on config load
ideMessenger.post("docs/getSuggestedDocs", undefined);
ideMessenger.post("docs/initStatuses", undefined);
@ -62,15 +66,19 @@ function useSetup(dispatch: Dispatch) {
clearInterval(interval);
return;
}
loadConfig();
loadConfig(true);
}, 2_000);
return () => clearInterval(interval);
}, [initialConfigLoad, loadConfig, ideMessenger]);
}, [hasLoadedConfig, loadConfig, ideMessenger]);
useWebviewListener("configUpdate", async () => {
await loadConfig();
});
useWebviewListener(
"configUpdate",
async () => {
await loadConfig(false);
},
[loadConfig],
);
// Load symbols for chat on any session change
const sessionId = useSelector((store: RootState) => store.state.sessionId);
@ -125,10 +133,6 @@ function useSetup(dispatch: Dispatch) {
const { streamResponse } = useChatHandler(dispatch, ideMessenger);
const defaultModelTitle = useSelector(
(store: RootState) => store.state.defaultModelTitle,
);
// IDE event listeners
useWebviewListener(
"getWebviewHistoryLength",
@ -179,6 +183,10 @@ function useSetup(dispatch: Dispatch) {
dispatch(updateIndexingStatus(data));
});
const defaultModelTitle = useSelector(
(store: RootState) => store.state.defaultModelTitle,
);
useWebviewListener(
"getDefaultModelTitle",
async () => {

View file

@ -32,6 +32,6 @@ export function useWebviewListener<T extends keyof ToWebviewProtocol>(
}
};
},
dependencies ? [...dependencies, skip] : [skip],
dependencies ? [...dependencies, skip, ideMessenger] : [skip, ideMessenger],
);
}

View file

@ -1,7 +1,7 @@
import { useState, useContext, useEffect, useRef } from "react";
import { useState, useEffect, useRef } from "react";
import {
ContextSubmenuItemWithProvider,
SubmenuContextProvidersContext,
useSubmenuContextProviders,
} from "../../context/SubmenuContextProviders";
import { Combobox } from "@headlessui/react";
import FileIcon from "../../components/FileIcon";
@ -24,7 +24,7 @@ export default function AddFileCombobox({
const inputRef = useRef<HTMLInputElement>(null);
const buttonRef = useRef<HTMLButtonElement>(null);
const { getSubmenuContextItems } = useContext(SubmenuContextProvidersContext);
const { getSubmenuContextItems } = useSubmenuContextProviders();
const allFiles = getSubmenuContextItems("file", "");
const codeToEdit = useSelector(
(state: RootState) => state.editModeState.codeToEdit,

View file

@ -21,6 +21,7 @@ import AcceptRejectAllButtons from "../../components/StepContainer/AcceptRejectA
import ContinueInputBox from "../../components/mainInput/ContinueInputBox";
import StepContainer from "../../components/StepContainer";
import getMultifileEditPrompt from "./getMultifileEditPrompt";
import { selectApplyState } from "../../redux/selectors";
const EDIT_DISALLOWED_CONTEXT_PROVIDERS = [
"codebase",
@ -59,11 +60,7 @@ export default function Edit() {
(state: RootState) => state.state.applyStates,
);
const applyState = useSelector(
(store: RootState) =>
store.state.applyStates.find((state) => state.streamId === "edit")
?.status ?? "closed",
);
const applyState = useSelector(selectApplyState);
const isSingleRangeEdit =
editModeState.codeToEdit.length === 0 ||
@ -83,8 +80,6 @@ export default function Edit() {
}
}, [applyState, editModeState.editStatus]);
// const active = useSelector((state: RootState) => state.state.active);
const pendingApplyStates = applyStates.filter(
(state) => state.status === "done",
);

View file

@ -12,6 +12,7 @@ import {
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
} from "react";
@ -131,7 +132,10 @@ export function Chat() {
const mainTextInputRef = useRef<HTMLInputElement>(null);
const stepsDivRef = useRef<HTMLDivElement>(null);
const [isAtBottom, setIsAtBottom] = useState<boolean>(false);
const state = useSelector((state: RootState) => state.state);
const history = useSelector((store: RootState) => store.state.history);
const showChatScrollbar = useSelector(
(store: RootState) => store.state.config?.ui?.showChatScrollbar,
);
const { saveSession, getLastSessionId, loadLastSession } =
useHistory(dispatch);
@ -289,7 +293,7 @@ export function Chat() {
setLocalStorage("mainTextEntryCounter", 1);
}
},
[state.history, defaultModel, state, streamResponse],
[history, defaultModel, streamResponse],
);
useWebviewListener(
@ -303,26 +307,27 @@ export function Chat() {
const isLastUserInput = useCallback(
(index: number): boolean => {
return !state.history
return !history
.slice(index + 1)
.some((entry) => entry.message.role === "user");
},
[state.history],
[history],
);
const showScrollbar =
state.config.ui?.showChatScrollbar || window.innerHeight > 5000;
const showScrollbar = useMemo(() => {
return showChatScrollbar ?? window.innerHeight > 5000;
}, [showChatScrollbar]);
return (
<>
{widget}
<StepsDiv
ref={stepsDivRef}
className={`overflow-y-scroll pt-[8px] ${showScrollbar ? "thin-scrollbar" : "no-scrollbar"} ${state.history.length > 0 ? "flex-1" : ""}`}
className={`overflow-y-scroll pt-[8px] ${showScrollbar ? "thin-scrollbar" : "no-scrollbar"} ${history.length > 0 ? "flex-1" : ""}`}
onScroll={handleScroll}
>
{highlights}
{state.history.map((item, index: number) => (
{history.map((item, index: number) => (
<Fragment key={item.message.id}>
<ErrorBoundary
FallbackComponent={fallbackRender}
@ -368,7 +373,7 @@ export function Chat() {
>
<StepContainer
index={index}
isLast={index === state.history.length - 1}
isLast={index === history.length - 1}
item={item}
/>
</TimelineItem>
@ -421,7 +426,7 @@ export function Chat() {
>
<div className="flex flex-row items-center justify-between pb-1 pl-0.5 pr-2">
<div className="xs:inline hidden">
{state.history.length === 0 && getLastSessionId() ? (
{history.length === 0 && getLastSessionId() ? (
<div className="xs:inline hidden">
<NewSessionButton
onClick={async () => {
@ -440,7 +445,7 @@ export function Chat() {
<ConfigErrorIndicator />
</div>
{state.history.length === 0 && (
{history.length === 0 && (
<>
{onboardingCard.show && (
<div className="mx-2 mt-10">
@ -458,7 +463,7 @@ export function Chat() {
</div>
</div>
<div
className={`${state.history.length === 0 ? "h-full" : ""} flex flex-col justify-end`}
className={`${history.length === 0 ? "h-full" : ""} flex flex-col justify-end`}
>
<ChatIndexingPeeks />
</div>

View file

@ -2,7 +2,7 @@ import { createSelector } from "@reduxjs/toolkit";
import { ComboBoxItemType } from "../../components/mainInput/types";
import { RootState } from "../store";
export const selectSlashCommands = createSelector(
export const selectSlashCommandComboBoxInputs = createSelector(
[(store: RootState) => store.state.config.slashCommands],
(slashCommands) => {
return (
@ -17,6 +17,13 @@ export const selectSlashCommands = createSelector(
},
);
export const selectSlashCommands = createSelector(
[(store: RootState) => store.state.config.slashCommands],
(slashCommands) => {
return slashCommands || [];
},
);
export const selectContextProviderDescriptions = createSelector(
[(store: RootState) => store.state.config.contextProviders],
(providers) => {
@ -24,7 +31,23 @@ export const selectContextProviderDescriptions = createSelector(
},
);
export const selectDefaultContextProviders = createSelector(
[(store: RootState) => store.state.config.experimental?.defaultContext],
(defaultProviders) => {
return defaultProviders ?? [];
},
);
export const selectUseActiveFile = createSelector(
[(store: RootState) => store.state.config.experimental?.defaultContext],
(defaultContext) => defaultContext?.includes("activeFile" as any),
);
export const selectApplyState = createSelector(
[(store: RootState) => store.state.applyStates],
(applyStates) => {
return (
applyStates.find((state) => state.streamId === "edit")?.status ?? "closed"
);
},
);

View file

@ -1,11 +1,12 @@
import { DEFAULT_MAX_TOKENS } from "core/llm/constants";
import { RootState } from "../store";
import { createSelector } from "@reduxjs/toolkit";
export const defaultModelSelector = (state: RootState) => {
const title = state.state.defaultModelTitle;
return state.state.config.models.find((model) => model.title === title);
};
export const contextLengthSelector = (state: RootState) => {
return defaultModelSelector(state)?.contextLength || DEFAULT_MAX_TOKENS;
};
export const defaultModelSelector = createSelector(
[
(store: RootState) => store.state.defaultModelTitle,
(store: RootState) => store.state.config.models,
],
(defaultModelTitle, models) => {
return models?.find((model) => model.title === defaultModelTitle);
},
);

View file

@ -370,10 +370,7 @@ export const stateSlice = createSlice({
};
},
setSelectedProfileId: (state, { payload }: PayloadAction<string>) => {
return {
...state,
selectedProfileId: payload,
};
state.selectedProfileId = payload;
},
setCurCheckpointIndex: (state, { payload }: PayloadAction<number>) => {
state.curCheckpointIndex = payload;

View file

@ -40,6 +40,7 @@ const windowIDTransform = (windowID: string) =>
const saveSubsetFilters = [
createFilter("state", ["history", "sessionId", "defaultModelTitle"]),
createFilter("editModeState", []),
];
const persistConfig = {

View file

@ -0,0 +1,31 @@
{
"compilerOptions": {
"strictNullChecks": true,
"target": "ESNext",
"useDefineForClassFields": true,
"lib": ["DOM", "DOM.Iterable", "ESNext"],
"allowJs": false,
"skipLibCheck": true,
"esModuleInterop": false,
"allowSyntheticDefaultImports": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "Node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"noEmitOnError": false,
"types": ["vitest/globals"]
},
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.js", "src/**/*.jsx"],
"exclude": ["dist", "node_modules"],
}