symbols in chat p1

This commit is contained in:
Dallin Romney 2024-11-13 19:22:44 -08:00
parent 83bff02a15
commit bb7b9781fa
17 changed files with 228 additions and 102 deletions

View file

@ -32,9 +32,15 @@ import { editConfigJson, setupInitialDotContinueDirectory } from "./util/paths";
import { Telemetry } from "./util/posthog";
import { TTS } from "./util/tts";
import type { ContextItemId, IDE, IndexingProgressUpdate } from ".";
import type {
ContextItemId,
IDE,
IndexingProgressUpdate,
SymbolWithLocation,
} from ".";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
import type { IMessenger, Message } from "./util/messenger";
import { getFileSymbols, getSymbolsForFiles } from "./util/treeSitter";
export class Core {
// implements IMessenger<ToCoreProtocol, FromCoreProtocol>
@ -83,7 +89,7 @@ export class Core {
constructor(
private readonly messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>,
private readonly ide: IDE,
private readonly onWrite: (text: string) => Promise<void> = async () => { },
private readonly onWrite: (text: string) => Promise<void> = async () => {},
) {
// Ensure .continue directory is created
setupInitialDotContinueDirectory();
@ -174,7 +180,7 @@ export class Core {
this.configHandler,
ide,
getLlm,
(e) => { },
(e) => {},
(..._) => Promise.resolve([]),
);
@ -365,6 +371,11 @@ export class Core {
}
});
on("context/getSymbolsForFiles", async (msg) => {
const { uris } = msg.data;
return await getSymbolsForFiles(uris, this.ide);
});
on("config/getSerializedProfileInfo", async (msg) => {
return {
config: await this.configHandler.getSerializedConfig(),
@ -684,7 +695,7 @@ export class Core {
await codebaseIndexer.clearIndexes();
}
const dirs = data?.dirs ?? await this.ide.getWorkspaceDirs();
const dirs = data?.dirs ?? (await this.ide.getWorkspaceDirs());
await this.refreshCodebaseIndex(dirs);
});
on("index/setPaused", (msg) => {

11
core/index.d.ts vendored
View file

@ -1,3 +1,4 @@
import Parser from "web-tree-sitter";
import { GetGhTokenArgs } from "./protocol/ide";
declare global {
@ -298,18 +299,26 @@ export interface InputModifiers {
noContext: boolean;
}
export interface SymbolWithLocation {
name: string;
type: Parser.SyntaxNode["type"];
location: Location;
}
export type FileSymbolMap = Record<string, SymbolWithLocation[]>;
export interface PromptLog {
modelTitle: string;
completionOptions: CompletionOptions;
prompt: string;
completion: string;
}
export interface ChatHistoryItem {
message: ChatMessage;
editorState?: any;
modifiers?: InputModifiers;
contextItems: ContextItemWithId[];
contextSymbols?: SymbolWithLocation[];
promptLogs?: PromptLog[];
}

View file

@ -17,6 +17,7 @@ import type {
SerializedContinueConfig,
SessionInfo,
SiteIndexingConfig,
SymbolWithLocation,
} from "../";
export type ProtocolGeneratorType<T> = AsyncGenerator<{
@ -76,6 +77,10 @@ export type ToCoreFromIdeOrWebviewProtocol = {
},
ContextItemWithId[],
];
"context/getSymbolsForFiles": [
{ uris: string[] },
Record<string, SymbolWithLocation[]>,
];
"context/loadSubmenuItems": [{ title: string }, ContextSubmenuItem[]];
"autocomplete/complete": [AutocompleteInput, string[]];
"context/addDocs": [SiteIndexingConfig, void];

View file

@ -22,6 +22,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"config/deleteModel",
"config/reload",
"context/getContextItems",
"context/getSymbolsForFiles",
"context/loadSubmenuItems",
"context/addDocs",
"context/removeDocs",
@ -60,5 +61,5 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] =
"isContinueInputFocused",
"didChangeAvailableProfiles",
"setTTSActive",
"getWebviewHistoryLength"
"getWebviewHistoryLength",
];

View file

@ -2,6 +2,7 @@ import fs from "node:fs";
import * as path from "node:path";
import Parser, { Language } from "web-tree-sitter";
import { FileSymbolMap, IDE, SymbolWithLocation } from "..";
export const supportedLanguages: { [key: string]: string } = {
cpp: "cpp",
@ -178,3 +179,72 @@ async function loadLanguageForFileExt(
);
return await Parser.Language.load(wasmPath);
}
const GET_SYMBOLS_FOR_NODE_TYPES: Parser.SyntaxNode["type"][] = [
"class_declaration",
"function_item", // function name = first "identifier" child
"method_declaration", // method name = first "identifier" child
// "arrow_function",
];
export async function getSymbolsForFile(
filepath: string,
contents: string,
): Promise<SymbolWithLocation[] | undefined> {
const parser = await getParserForFile(filepath);
if (!parser) {
return;
}
const tree = parser.parse(contents);
console.log(`file: ${filepath}`);
// Function to recursively find all named nodes (classes and functions)
const symbols: SymbolWithLocation[] = [];
function findNamedNodesRecursive(node: Parser.SyntaxNode) {
if (GET_SYMBOLS_FOR_NODE_TYPES.includes(node.type)) {
console.log(`parent: ${node.type}, ${node.text.substring(0, 200)}`);
node.children.forEach((child) => {
console.log(`child: ${child.type}, ${child.text}`);
});
// Empirically, the actualy name is the last identifier in the node
// Especially with languages where return type is declared before the name
const identifier = node.children.findLast(
(child) => child.type === "identifier",
)?.text;
if (identifier) {
symbols.push({
type: node.type,
name: identifier,
location: {
filepath,
position: {
character: node.startPosition.column,
line: node.startPosition.row + 1,
},
},
});
}
}
node.children.forEach(findNamedNodesRecursive);
}
findNamedNodesRecursive(tree.rootNode);
return symbols;
}
export async function getSymbolsForFiles(
uris: string[],
ide: IDE,
): Promise<FileSymbolMap> {
const filesAndSymbols = await Promise.all(
uris.map(async (uri): Promise<[string, SymbolWithLocation[]]> => {
const contents = await ide.readFile(uri);
const symbols = await getSymbolsForFile(uri, contents);
return [uri, symbols ?? []];
}),
);
return Object.fromEntries(filesAndSymbols);
}

View file

@ -16,7 +16,7 @@ export const CodeBlockComponent = ({
const item: ContextItemWithId = node.attrs.item;
const contextItems = useSelector(
(state: RootState) => state.state.contextItems,
(state: RootState) => state.state.context.items,
);
return (
<NodeViewWrapper className="code-block-with-content" as="p">

View file

@ -10,10 +10,12 @@ import { INSTRUCTIONS_BASE_ITEM } from "core/context/providers/utils";
import { getIconFromDropdownItem } from "./MentionList";
import styled from "styled-components";
import { getBasename } from "core/util";
import { RootState } from "../../redux/store";
import { useSelector } from "react-redux";
interface ContextItemsPeekProps {
contextItems?: ContextItemWithId[];
isGatheringContext: boolean;
isCurrentContextPeek: boolean;
}
interface ContextItemsPeekItemProps {
@ -119,7 +121,7 @@ function ContextItemsPeekItem({ contextItem }: ContextItemsPeekItemProps) {
function ContextItemsPeek({
contextItems,
isGatheringContext,
isCurrentContextPeek,
}: ContextItemsPeekProps) {
const [open, setOpen] = useState(false);
@ -127,7 +129,16 @@ function ContextItemsPeek({
(ctxItem) => !ctxItem.name.includes(INSTRUCTIONS_BASE_ITEM.name),
);
if ((!ctxItems || ctxItems.length === 0) && !isGatheringContext) {
const isGatheringContext = useSelector(
(store: RootState) => store.state.context.isGathering,
);
const gatheringMessage = useSelector(
(store: RootState) => store.state.context.gatheringMessage,
);
const indicateIsGathering = isCurrentContextPeek && isGatheringContext;
if ((!ctxItems || ctxItems.length === 0) && !indicateIsGathering) {
return null;
}
@ -152,7 +163,7 @@ function ContextItemsPeek({
<span className="ml-1 text-xs text-gray-400 transition-colors duration-200">
{isGatheringContext ? (
<>
Gathering context
{gatheringMessage}
<AnimatedEllipsis />
</>
) : (

View file

@ -1,6 +1,5 @@
import { Editor, JSONContent } from "@tiptap/react";
import { ContextItemWithId, InputModifiers } from "core";
import { useEffect, useRef, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import styled, { keyframes } from "styled-components";
import { defaultBorderRadius, vscBackground } from "..";
@ -70,12 +69,6 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
const availableContextProviders = useSelector(
(store: RootState) => store.state.config.contextProviders,
);
const isGatheringContextStore = useSelector(
(store: RootState) => store.state.isGatheringContext,
);
const [isGatheringContext, setIsGatheringContext] = useState(false);
const timeoutRef = useRef<NodeJS.Timeout | null>(null);
const isInMultifileEdit = useSelector(
(state: RootState) => state.state.isInMultifileEdit,
@ -100,22 +93,6 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
[props.isMainInput],
);
useEffect(() => {
if (isGatheringContextStore && !isGatheringContext) {
// 500ms delay when going from false -> true to prevent flashing loading indicator
timeoutRef.current = setTimeout(() => setIsGatheringContext(true), 500);
} else {
// Update immediately otherwise (i.e. true -> false)
setIsGatheringContext(isGatheringContextStore);
}
return () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
};
}, [isGatheringContextStore]);
return (
<div className={`mb-1 ${props.hidden ? "hidden" : ""}`}>
{shouldShowAcceptRejectButtons && <AcceptRejectAllButtons />}
@ -145,7 +122,7 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
</div>
<ContextItemsPeek
contextItems={props.contextItems}
isGatheringContext={isGatheringContext && props.isLastUserInput}
isCurrentContextPeek={props.isLastUserInput}
/>
</div>
);

View file

@ -223,7 +223,7 @@ function TipTapEditor(props: TipTapEditorProps) {
};
const contextItems = useSelector(
(store: RootState) => store.state.contextItems,
(store: RootState) => store.state.context.items,
);
const defaultModel = useSelector(defaultModelSelector);

View file

@ -9,6 +9,8 @@ import {
} from "core";
import { stripImages } from "core/llm/images";
import { IIdeMessenger } from "../../context/IdeMessenger";
import { Dispatch } from "@reduxjs/toolkit";
import { setIsGatheringContext } from "../../redux/slices/stateSlice";
interface MentionAttrs {
label: string;
@ -29,6 +31,7 @@ async function resolveEditorContent(
modifiers: InputModifiers,
ideMessenger: IIdeMessenger,
defaultContextProviders: DefaultContextProvider[],
dispatch: Dispatch,
): Promise<[ContextItemWithId[], RangeInFile[], MessageContent]> {
let parts: MessagePart[] = [];
let contextItemAttrs: MentionAttrs[] = [];
@ -38,8 +41,7 @@ async function resolveEditorContent(
if (p.type === "paragraph") {
const [text, ctxItems, foundSlashCommand] = resolveParagraph(p);
// Only take the first slash command
// Only take the first slash command\
if (foundSlashCommand && typeof slashCommand === "undefined") {
slashCommand = foundSlashCommand;
}
@ -103,6 +105,17 @@ async function resolveEditorContent(
}
}
const shouldGatherContext = modifiers.useCodebase || slashCommand;
if (shouldGatherContext) {
dispatch(
setIsGatheringContext({
isGathering: true,
gatheringMessage: "Gathering context",
}),
);
}
let contextItemsText = "";
let contextItems: ContextItemWithId[] = [];
for (const item of contextItemAttrs) {
@ -158,6 +171,18 @@ async function resolveEditorContent(
);
contextItems.push(...defaultContextItems.flat());
const contextItemFileUris = Array.from(
new Set(
contextItems
.filter((item) => item.uri?.type === "file" && item?.uri?.value)
.map((item) => item.uri.value),
),
);
const symbols = await ideMessenger.request("context/getSymbolsForFiles", {
uris: contextItemFileUris,
});
if (contextItemsText !== "") {
contextItemsText += "\n";
}
@ -172,7 +197,16 @@ async function resolveEditorContent(
}
}
return [contextItems, selectedCode, parts];
if (shouldGatherContext) {
dispatch(
setIsGatheringContext({
isGathering: false,
gatheringMessage: "Gathering context",
}),
);
}
return [contextItems, selectedCode, parts, symbols];
}
function findLastIndex<T>(
@ -213,30 +247,30 @@ function resolveParagraph(p: JSONContent): [string, MentionAttrs[], string] {
return [text, contextItems, slashCommand];
}
export function hasSlashCommandOrContextProvider(
editorState: JSONContent,
): boolean {
if (!editorState.content) {
return false;
}
// export function hasSlashCommandOrContextProvider(
// editorState: JSONContent,
// ): boolean {
// if (!editorState.content) {
// return false;
// }
for (const p of editorState.content) {
if (p.type === "paragraph" && p.content) {
for (const child of p.content) {
if (child.type === "slashcommand") {
return true;
}
if (
child.type === "mention" &&
child.attrs?.itemType === "contextProvider"
) {
return true;
}
}
}
}
// for (const p of editorState.content) {
// if (p.type === "paragraph" && p.content) {
// for (const child of p.content) {
// if (child.type === "slashcommand") {
// return true;
// }
// if (
// child.type === "mention" &&
// child.attrs?.itemType === "contextProvider"
// ) {
// return true;
// }
// }
// }
// }
return false;
}
// return false;
// }
export default resolveEditorContent;

View file

@ -20,7 +20,7 @@ function FilenameLink({ rif }: FilenameLinkProps) {
}
return (
<div
<span
className="mb-0.5 inline-flex cursor-pointer items-center gap-0.5 rounded-md py-0.5 pl-0 pr-1 align-middle hover:bg-stone-800"
onClick={onClick}
>
@ -28,7 +28,7 @@ function FilenameLink({ rif }: FilenameLinkProps) {
<span className="align-middle underline decoration-gray-600 underline-offset-2">
{getBasename(rif.filepath)}
</span>
</div>
</span>
);
}

View file

@ -246,6 +246,8 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
return <FilenameLink rif={rif} />;
}
// const symbole = symboles
return <code {...codeProps}>{codeProps.children}</code>;
},
},

View file

@ -17,9 +17,7 @@ import { getBasename, getRelativePath } from "core/util";
import { usePostHog } from "posthog-js/react";
import { useEffect, useRef, useState } from "react";
import { useSelector } from "react-redux";
import resolveEditorContent, {
hasSlashCommandOrContextProvider,
} from "../components/mainInput/resolveInput";
import resolveEditorContent from "../components/mainInput/resolveInput";
import { IIdeMessenger } from "../context/IdeMessenger";
import { defaultModelSelector } from "../redux/selectors/modelSelectors";
import {
@ -51,7 +49,7 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) {
);
const contextItems = useSelector(
(state: RootState) => state.state.contextItems,
(store: RootState) => store.state.context.items,
);
const history = useSelector((store: RootState) => store.state.history);
@ -195,13 +193,6 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) {
// Reset current code block index
dispatch(resetNextCodeBlockToApplyIndex());
const shouldGatherContext =
modifiers.useCodebase || hasSlashCommandOrContextProvider(editorState);
if (shouldGatherContext) {
dispatch(setIsGatheringContext(true));
}
// Resolve context providers and construct new history
const [selectedContextItems, selectedCode, content] =
await resolveEditorContent(
@ -209,10 +200,9 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) {
modifiers,
ideMessenger,
defaultContextProviders,
dispatch,
);
dispatch(setIsGatheringContext(false));
// Automatically use currently open file
if (!modifiers.noContext) {
const usingFreeTrial = defaultModel?.provider === "free-trial";

View file

@ -20,7 +20,7 @@ import { getLocalStorage, setLocalStorage } from "../util/localStorage";
import useChatHandler from "./useChatHandler";
import { useWebviewListener } from "./useWebviewListener";
function useSetup(dispatch: Dispatch<any>) {
function useSetup(dispatch: Dispatch) {
const [configLoaded, setConfigLoaded] = useState<boolean>(false);
const ideMessenger = useContext(IdeMessengerContext);

View file

@ -174,6 +174,7 @@ function Edit() {
},
ideMessenger,
[],
dispatch,
);
const prompt = [

View file

@ -290,7 +290,7 @@ export function Chat() {
setLocalStorage("mainTextEntryCounter", 1);
}
},
[state.history, state.contextItems, defaultModel, state, streamResponse],
[state.history, state.context.items, defaultModel, state, streamResponse],
);
useWebviewListener(

View file

@ -15,16 +15,6 @@ import { createSelector } from "reselect";
import { v4 as uuidv4, v4 } from "uuid";
import { RootState } from "../store";
export const memoizedContextItemsSelector = createSelector(
[(state: RootState) => state.state.history],
(history) => {
return history.reduce<ContextItemWithId[]>((acc, item) => {
acc.push(...item.contextItems);
return acc;
}, []);
},
);
// We need this to handle reorderings (e.g. a mid-array deletion) of the messages array.
// The proper fix is adding a UUID to all chat messages, but this is the temp workaround.
type ChatHistoryItemWithMessageId = ChatHistoryItem & {
@ -33,10 +23,13 @@ type ChatHistoryItemWithMessageId = ChatHistoryItem & {
type State = {
history: ChatHistoryItemWithMessageId[];
contextItems: ContextItemWithId[];
context: {
items: ContextItemWithId[];
isGathering: boolean;
gatheringMessage: string;
};
ttsActive: boolean;
active: boolean;
isGatheringContext: boolean;
config: BrowserSerializedContinueConfig;
title: string;
sessionId: string;
@ -49,10 +42,13 @@ type State = {
const initialState: State = {
history: [],
contextItems: [],
context: {
items: [],
isGathering: false,
gatheringMessage: "Gathering Context",
},
ttsActive: false,
active: false,
isGatheringContext: false,
configError: undefined,
config: {
slashCommands: [
@ -116,8 +112,17 @@ export const stateSlice = createSlice({
setActive: (state) => {
state.active = true;
},
setIsGatheringContext: (state, { payload }: PayloadAction<boolean>) => {
state.isGatheringContext = payload;
setIsGatheringContext: (
state,
{
payload,
}: PayloadAction<{
isGathering: boolean;
gatheringMessage: string;
}>,
) => {
state.context.isGathering = payload.isGathering;
state.context.gatheringMessage = payload.gatheringMessage;
},
clearLastResponse: (state) => {
if (state.history.length < 2) {
@ -144,7 +149,7 @@ export const stateSlice = createSlice({
}
},
addContextItems: (state, action: PayloadAction<ContextItemWithId[]>) => {
state.contextItems = state.contextItems.concat(action.payload);
state.context.items = state.context.items.concat(action.payload);
},
resubmitAtIndex: (
state,
@ -190,7 +195,7 @@ export const stateSlice = createSlice({
) => {
state.history.push({
message: { role: "user", content: "", id: uuidv4() },
contextItems: state.contextItems,
contextItems: state.context.items,
editorState: payload.editorState,
});
state.history.push({
@ -253,7 +258,7 @@ export const stateSlice = createSlice({
historyItem.contextItems.push(...payload.contextItems);
},
setInactive: (state) => {
state.isGatheringContext = false;
state.context.isGathering = false;
state.active = false;
},
streamUpdate: (state, action: PayloadAction<string>) => {
@ -272,7 +277,7 @@ export const stateSlice = createSlice({
state.sessionId = payload.sessionId;
} else {
state.history = [];
state.contextItems = [];
state.context.items = [];
state.active = false;
state.title = "New Session";
state.sessionId = v4();
@ -289,7 +294,7 @@ export const stateSlice = createSlice({
const ids = new Set(payload.ids.map(getKey));
if (payload.index === undefined) {
state.contextItems = state.contextItems.filter(
state.context.items = state.context.items.filter(
(item) => !ids.has(getKey(item.id)),
);
} else {
@ -304,7 +309,7 @@ export const stateSlice = createSlice({
payload,
}: PayloadAction<{ rangeInFileWithContents: any; edit: boolean }>,
) => {
let contextItems = [...state.contextItems].map((item) => {
let contextItems = [...state.context.items].map((item) => {
return { ...item, editing: false };
});
const base = payload.rangeInFileWithContents.filepath
@ -372,7 +377,7 @@ export const stateSlice = createSlice({
if (typeof payload.index === "undefined") {
return {
...state,
contextItems: state.contextItems.map((item) => {
contextItems: state.context.items.map((item) => {
return {
...item,
editing: ids.includes(item.id.itemId),
@ -424,6 +429,16 @@ export const stateSlice = createSlice({
},
});
export const memoizedContextItemsSelector = createSelector(
[(state: RootState) => state.state.history],
(history) => {
return history.reduce<ContextItemWithId[]>((acc, item) => {
acc.push(...item.contextItems);
return acc;
}, []);
},
);
export const {
setContextItemsAtIndex,
addContextItems,