From bb7b9781fa71f5d0fae6e6206978d73cd6138996 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 13 Nov 2024 19:22:44 -0800 Subject: [PATCH 01/13] symbols in chat p1 --- core/core.ts | 19 +++- core/index.d.ts | 11 ++- core/protocol/core.ts | 5 ++ core/protocol/passThrough.ts | 3 +- core/util/treeSitter.ts | 70 +++++++++++++++ .../mainInput/CodeBlockComponent.tsx | 2 +- .../components/mainInput/ContextItemsPeek.tsx | 19 +++- .../components/mainInput/ContinueInputBox.tsx | 25 +----- gui/src/components/mainInput/TipTapEditor.tsx | 2 +- gui/src/components/mainInput/resolveInput.ts | 86 +++++++++++++------ gui/src/components/markdown/FilenameLink.tsx | 4 +- .../markdown/StyledMarkdownPreview.tsx | 2 + gui/src/hooks/useChatHandler.ts | 16 +--- gui/src/hooks/useSetup.ts | 2 +- gui/src/pages/edit/index.tsx | 1 + gui/src/pages/gui/Chat.tsx | 2 +- gui/src/redux/slices/stateSlice.ts | 61 ++++++++----- 17 files changed, 228 insertions(+), 102 deletions(-) diff --git a/core/core.ts b/core/core.ts index 6df1482ef..dfe3a4f4a 100644 --- a/core/core.ts +++ b/core/core.ts @@ -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 @@ -83,7 +89,7 @@ export class Core { constructor( private readonly messenger: IMessenger, private readonly ide: IDE, - private readonly onWrite: (text: string) => Promise = async () => { }, + private readonly onWrite: (text: string) => Promise = 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) => { diff --git a/core/index.d.ts b/core/index.d.ts index 1bad9fd74..2e6d79318 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -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; + 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[]; } diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 2c9af1433..3f02c3fc0 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -17,6 +17,7 @@ import type { SerializedContinueConfig, SessionInfo, SiteIndexingConfig, + SymbolWithLocation, } from "../"; export type ProtocolGeneratorType = AsyncGenerator<{ @@ -76,6 +77,10 @@ export type ToCoreFromIdeOrWebviewProtocol = { }, ContextItemWithId[], ]; + "context/getSymbolsForFiles": [ + { uris: string[] }, + Record, + ]; "context/loadSubmenuItems": [{ title: string }, ContextSubmenuItem[]]; "autocomplete/complete": [AutocompleteInput, string[]]; "context/addDocs": [SiteIndexingConfig, void]; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 1c0f5e962..d05d773c4 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -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", ]; diff --git a/core/util/treeSitter.ts b/core/util/treeSitter.ts index b877a251b..566917ecc 100644 --- a/core/util/treeSitter.ts +++ b/core/util/treeSitter.ts @@ -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 { + 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 { + 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); +} diff --git a/gui/src/components/mainInput/CodeBlockComponent.tsx b/gui/src/components/mainInput/CodeBlockComponent.tsx index 217fcc293..4266db4f5 100644 --- a/gui/src/components/mainInput/CodeBlockComponent.tsx +++ b/gui/src/components/mainInput/CodeBlockComponent.tsx @@ -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 ( diff --git a/gui/src/components/mainInput/ContextItemsPeek.tsx b/gui/src/components/mainInput/ContextItemsPeek.tsx index 3ae178abf..33bdbff6d 100644 --- a/gui/src/components/mainInput/ContextItemsPeek.tsx +++ b/gui/src/components/mainInput/ContextItemsPeek.tsx @@ -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({ {isGatheringContext ? ( <> - Gathering context + {gatheringMessage} ) : ( diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index c98a69403..544eb8f63 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -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(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 (
{shouldShowAcceptRejectButtons && } @@ -145,7 +122,7 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
); diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index c2646415e..cb57681ea 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -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); diff --git a/gui/src/components/mainInput/resolveInput.ts b/gui/src/components/mainInput/resolveInput.ts index 64acba85a..85ac9e398 100644 --- a/gui/src/components/mainInput/resolveInput.ts +++ b/gui/src/components/mainInput/resolveInput.ts @@ -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( @@ -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; diff --git a/gui/src/components/markdown/FilenameLink.tsx b/gui/src/components/markdown/FilenameLink.tsx index 3674fc418..0d1166a00 100644 --- a/gui/src/components/markdown/FilenameLink.tsx +++ b/gui/src/components/markdown/FilenameLink.tsx @@ -20,7 +20,7 @@ function FilenameLink({ rif }: FilenameLinkProps) { } return ( -
@@ -28,7 +28,7 @@ function FilenameLink({ rif }: FilenameLinkProps) { {getBasename(rif.filepath)} -
+
); } diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index 77158e96a..c5190d8e8 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -246,6 +246,8 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( return ; } + // const symbole = symboles + return {codeProps.children}; }, }, diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index 2e35acc53..8517ea5d9 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -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"; diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 2fed805da..4378059e0 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -20,7 +20,7 @@ import { getLocalStorage, setLocalStorage } from "../util/localStorage"; import useChatHandler from "./useChatHandler"; import { useWebviewListener } from "./useWebviewListener"; -function useSetup(dispatch: Dispatch) { +function useSetup(dispatch: Dispatch) { const [configLoaded, setConfigLoaded] = useState(false); const ideMessenger = useContext(IdeMessengerContext); diff --git a/gui/src/pages/edit/index.tsx b/gui/src/pages/edit/index.tsx index 5b1b71e66..af33ee99d 100644 --- a/gui/src/pages/edit/index.tsx +++ b/gui/src/pages/edit/index.tsx @@ -174,6 +174,7 @@ function Edit() { }, ideMessenger, [], + dispatch, ); const prompt = [ diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 78bbcd262..85f4eb416 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -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( diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index e3ce22eb6..cd1e4a8bc 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -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((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) => { - 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) => { - 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) => { @@ -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((acc, item) => { + acc.push(...item.contextItems); + return acc; + }, []); + }, +); + export const { setContextItemsAtIndex, addContextItems, From faf45035f9f214ad231a89a2f0d2220bd3d5e4b3 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 14 Nov 2024 09:37:20 -0800 Subject: [PATCH 02/13] symbol links p3 --- core/core.ts | 9 +--- core/index.d.ts | 7 ++- core/protocol/core.ts | 7 +-- core/util/treeSitter.ts | 53 +++++++++++++------ .../mainInput/CodeBlockComponent.tsx | 1 - gui/src/components/mainInput/resolveInput.ts | 19 +++++-- .../markdown/StyledMarkdownPreview.tsx | 47 +++++++++++++--- gui/src/components/markdown/SymbolLink.tsx | 33 ++++++++++++ gui/src/redux/slices/stateSlice.ts | 10 ++++ 9 files changed, 141 insertions(+), 45 deletions(-) create mode 100644 gui/src/components/markdown/SymbolLink.tsx diff --git a/core/core.ts b/core/core.ts index dfe3a4f4a..727e5f200 100644 --- a/core/core.ts +++ b/core/core.ts @@ -30,17 +30,12 @@ import { GlobalContext } from "./util/GlobalContext"; import historyManager from "./util/history"; import { editConfigJson, setupInitialDotContinueDirectory } from "./util/paths"; import { Telemetry } from "./util/posthog"; +import { getSymbolsForFiles } from "./util/treeSitter"; import { TTS } from "./util/tts"; -import type { - ContextItemId, - IDE, - IndexingProgressUpdate, - SymbolWithLocation, -} from "."; +import type { ContextItemId, IDE, IndexingProgressUpdate } 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 diff --git a/core/index.d.ts b/core/index.d.ts index 2e6d79318..25d5c346d 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -299,13 +299,12 @@ export interface InputModifiers { noContext: boolean; } -export interface SymbolWithLocation { +export interface SymbolWithRange extends RangeInFile { name: string; type: Parser.SyntaxNode["type"]; - location: Location; } -export type FileSymbolMap = Record; +export type FileSymbolMap = Record; export interface PromptLog { modelTitle: string; @@ -318,7 +317,7 @@ export interface ChatHistoryItem { editorState?: any; modifiers?: InputModifiers; contextItems: ContextItemWithId[]; - contextSymbols?: SymbolWithLocation[]; + contextSymbols?: SymbolWithRange[]; promptLogs?: PromptLog[]; } diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 3f02c3fc0..cef8c38c9 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -7,6 +7,7 @@ import type { ContextItemWithId, ContextSubmenuItem, DiffLine, + FileSymbolMap, IdeSettings, LLMFullCompletionOptions, MessageContent, @@ -17,7 +18,6 @@ import type { SerializedContinueConfig, SessionInfo, SiteIndexingConfig, - SymbolWithLocation, } from "../"; export type ProtocolGeneratorType = AsyncGenerator<{ @@ -77,10 +77,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { }, ContextItemWithId[], ]; - "context/getSymbolsForFiles": [ - { uris: string[] }, - Record, - ]; + "context/getSymbolsForFiles": [{ uris: string[] }, FileSymbolMap]; "context/loadSubmenuItems": [{ title: string }, ContextSubmenuItem[]]; "autocomplete/complete": [AutocompleteInput, string[]]; "context/addDocs": [SiteIndexingConfig, void]; diff --git a/core/util/treeSitter.ts b/core/util/treeSitter.ts index 566917ecc..18ac14d16 100644 --- a/core/util/treeSitter.ts +++ b/core/util/treeSitter.ts @@ -2,7 +2,8 @@ import fs from "node:fs"; import * as path from "node:path"; import Parser, { Language } from "web-tree-sitter"; -import { FileSymbolMap, IDE, SymbolWithLocation } from ".."; + +import { FileSymbolMap, IDE, SymbolWithRange } from ".."; export const supportedLanguages: { [key: string]: string } = { cpp: "cpp", @@ -180,17 +181,24 @@ async function loadLanguageForFileExt( return await Parser.Language.load(wasmPath); } +// See https://tree-sitter.github.io/tree-sitter/using-parsers const GET_SYMBOLS_FOR_NODE_TYPES: Parser.SyntaxNode["type"][] = [ "class_declaration", + "class_definition", "function_item", // function name = first "identifier" child + "function_definition", "method_declaration", // method name = first "identifier" child + "method_definition", + "generator_function_declaration", + // property_identifier + // field_declaration // "arrow_function", ]; export async function getSymbolsForFile( filepath: string, contents: string, -): Promise { +): Promise { const parser = await getParserForFile(filepath); if (!parser) { @@ -201,28 +209,39 @@ export async function getSymbolsForFile( console.log(`file: ${filepath}`); // Function to recursively find all named nodes (classes and functions) - const symbols: SymbolWithLocation[] = []; + const symbols: SymbolWithRange[] = []; function findNamedNodesRecursive(node: Parser.SyntaxNode) { + // console.log(`node: ${node.type}, ${node.text}`); 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}`); - }); + // 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) { + // TODO use findLast in newer version of node target + let identifier: Parser.SyntaxNode | undefined = undefined; + for (let i = node.children.length - 1; i >= 0; i--) { + if (node.children[i].type === "identifier") { + identifier = node.children[i]; + break; + } + } + + if (identifier?.text) { symbols.push({ + filepath, type: node.type, - name: identifier, - location: { - filepath, - position: { + name: identifier.text, + range: { + start: { character: node.startPosition.column, - line: node.startPosition.row + 1, + line: node.startPosition.row, + }, + end: { + character: node.endPosition.column + 1, + line: node.endPosition.row + 1, }, }, }); @@ -240,7 +259,7 @@ export async function getSymbolsForFiles( ide: IDE, ): Promise { const filesAndSymbols = await Promise.all( - uris.map(async (uri): Promise<[string, SymbolWithLocation[]]> => { + uris.map(async (uri): Promise<[string, SymbolWithRange[]]> => { const contents = await ide.readFile(uri); const symbols = await getSymbolsForFile(uri, contents); return [uri, symbols ?? []]; diff --git a/gui/src/components/mainInput/CodeBlockComponent.tsx b/gui/src/components/mainInput/CodeBlockComponent.tsx index 4266db4f5..2a63d889e 100644 --- a/gui/src/components/mainInput/CodeBlockComponent.tsx +++ b/gui/src/components/mainInput/CodeBlockComponent.tsx @@ -12,7 +12,6 @@ export const CodeBlockComponent = ({ editor, updateAttributes, }: any) => { - const dispatch = useDispatch(); const item: ContextItemWithId = node.attrs.item; const contextItems = useSelector( diff --git a/gui/src/components/mainInput/resolveInput.ts b/gui/src/components/mainInput/resolveInput.ts index 85ac9e398..a4598ae93 100644 --- a/gui/src/components/mainInput/resolveInput.ts +++ b/gui/src/components/mainInput/resolveInput.ts @@ -10,7 +10,10 @@ import { import { stripImages } from "core/llm/images"; import { IIdeMessenger } from "../../context/IdeMessenger"; import { Dispatch } from "@reduxjs/toolkit"; -import { setIsGatheringContext } from "../../redux/slices/stateSlice"; +import { + setIsGatheringContext, + updateFileSymbols, +} from "../../redux/slices/stateSlice"; interface MentionAttrs { label: string; @@ -179,9 +182,15 @@ async function resolveEditorContent( ), ); - const symbols = await ideMessenger.request("context/getSymbolsForFiles", { - uris: contextItemFileUris, - }); + const symbolsResult = await ideMessenger.request( + "context/getSymbolsForFiles", + { + uris: contextItemFileUris, + }, + ); + if (symbolsResult.status === "success") { + dispatch(updateFileSymbols(symbolsResult.content)); + } if (contextItemsText !== "") { contextItemsText += "\n"; @@ -206,7 +215,7 @@ async function resolveEditorContent( ); } - return [contextItems, selectedCode, parts, symbols]; + return [contextItems, selectedCode, parts]; } function findLastIndex( diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index c5190d8e8..70af5b6b4 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -1,4 +1,4 @@ -import { memo, useEffect } from "react"; +import { memo, useEffect, useMemo } from "react"; import { useRemark } from "react-remark"; import rehypeHighlight, { Options } from "rehype-highlight"; import rehypeKatex from "rehype-katex"; @@ -21,6 +21,9 @@ import FilenameLink from "./FilenameLink"; import StepContainerPreToolbar from "./StepContainerPreToolbar"; import { SyntaxHighlightedPre } from "./SyntaxHighlightedPre"; import StepContainerPreActionButtons from "./StepContainerPreActionButtons"; +import { RootState } from "../../redux/store"; +import { SymbolWithRange } from "core"; +import SymbolLink from "./SymbolLink"; const StyledMarkdown = styled.div<{ fontSize?: number; @@ -112,16 +115,16 @@ function getLanuageFromClassName(className: any): string | null { function getCodeChildrenContent(children: any) { if (typeof children === "string") { + console.log(children); return children; } else if ( Array.isArray(children) && children.length > 0 && - typeof children[0] === "string" && - children[0] !== "" + typeof children[0] === "string" ) { + console.log(children[0]); return children[0]; } - return undefined; } @@ -154,6 +157,25 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( props: StyledMarkdownPreviewProps, ) { const contextItems = useSelector(memoizedContextItemsSelector); + const symbols = useSelector( + (state: RootState) => state.state.context.symbols, + ); + const symbolsForContextItems: SymbolWithRange[] = useMemo(() => { + const contextUris = Array.from( + new Set( + contextItems.filter((item) => item?.uri).map((item) => item.uri!.value), + ), + ); + const contextSymbols: SymbolWithRange[] = []; + contextUris.forEach((uri) => { + const fileSymbols = symbols[uri]; + if (fileSymbols) { + contextSymbols.push(...fileSymbols); + } + }); + console.log(contextSymbols.map((s) => s.name)); + return contextSymbols; + }, [contextItems, symbols]); const [reactContent, setMarkdownSource] = useRemark({ remarkPlugins: [remarkMath, () => processCodeBlocks], @@ -245,9 +267,22 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( const rif = ctxItemToRifWithContents(ctxItem); return ; } + // console.log("content", content); + const exactSymbol = symbolsForContextItems.find( + (s) => s.name === content, + ); + if (exactSymbol) { + return ; + } - // const symbole = symboles - + // PARTIAL - PARENTHESES + const partialSymbol = symbolsForContextItems.find( + (s) => false, + // content.startsWith(s.name), + ); + if (partialSymbol) { + return ; + } return {codeProps.children}; }, }, diff --git a/gui/src/components/markdown/SymbolLink.tsx b/gui/src/components/markdown/SymbolLink.tsx new file mode 100644 index 000000000..84c1e8984 --- /dev/null +++ b/gui/src/components/markdown/SymbolLink.tsx @@ -0,0 +1,33 @@ +import { SymbolWithRange } from "core"; +import { useContext } from "react"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; + +interface SymbolLinkProps { + symbol: SymbolWithRange; + content: string; +} + +function SymbolLink({ symbol, content }: SymbolLinkProps) { + const ideMessenger = useContext(IdeMessengerContext); + + function onClick() { + ideMessenger.post("showLines", { + filepath: symbol.filepath, + startLine: symbol.range.start.line, + endLine: symbol.range.end.line, + }); + } + + return ( + + + {content} + + + ); +} + +export default SymbolLink; diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index cd1e4a8bc..22c76e9ee 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -5,6 +5,7 @@ import { ChatMessage, ContextItemId, ContextItemWithId, + FileSymbolMap, PersistedSessionInfo, PromptLog, } from "core"; @@ -25,6 +26,7 @@ type State = { history: ChatHistoryItemWithMessageId[]; context: { items: ContextItemWithId[]; + symbols: FileSymbolMap; isGathering: boolean; gatheringMessage: string; }; @@ -44,6 +46,7 @@ const initialState: State = { history: [], context: { items: [], + symbols: {}, isGathering: false, gatheringMessage: "Gathering Context", }, @@ -135,6 +138,12 @@ export const stateSlice = createSlice({ consumeMainEditorContent: (state) => { state.mainEditorContent = undefined; }, + updateFileSymbols: (state, action: PayloadAction) => { + state.context.symbols = Object.assign( + state.context.symbols, + action.payload, + ); + }, setContextItemsAtIndex: ( state, { @@ -440,6 +449,7 @@ export const memoizedContextItemsSelector = createSelector( ); export const { + updateFileSymbols, setContextItemsAtIndex, addContextItems, addContextItemsAtIndex, From 0ba023cd91858f7fd8b84e1143146d5ebe837fe9 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 18 Nov 2024 02:26:46 -0800 Subject: [PATCH 03/13] clickable symbols to code + working for js --- core/core.ts | 4 +- core/util/treeSitter.ts | 9 ++- gui/src/components/gui/StepContainer.tsx | 2 +- .../markdown/CodeSnippetPreview.tsx | 1 - .../markdown/StyledMarkdownPreview.tsx | 58 ++++++++++--------- gui/src/components/markdown/SymbolLink.tsx | 6 +- gui/src/redux/slices/stateSlice.ts | 6 +- gui/src/redux/store.ts | 7 ++- 8 files changed, 54 insertions(+), 39 deletions(-) diff --git a/core/core.ts b/core/core.ts index 53a2a068d..8825f235c 100644 --- a/core/core.ts +++ b/core/core.ts @@ -30,7 +30,7 @@ import { GlobalContext } from "./util/GlobalContext"; import historyManager from "./util/history"; import { editConfigJson, setupInitialDotContinueDirectory } from "./util/paths"; import { Telemetry } from "./util/posthog"; -import { getSymbolsForFiles } from "./util/treeSitter"; +import { getSymbolsForManyFiles } from "./util/treeSitter"; import { TTS } from "./util/tts"; import type { ContextItemId, IDE, IndexingProgressUpdate } from "."; @@ -368,7 +368,7 @@ export class Core { on("context/getSymbolsForFiles", async (msg) => { const { uris } = msg.data; - return await getSymbolsForFiles(uris, this.ide); + return await getSymbolsForManyFiles(uris, this.ide); }); on("config/getSerializedProfileInfo", async (msg) => { diff --git a/core/util/treeSitter.ts b/core/util/treeSitter.ts index 3b7a34c29..22a59e85c 100644 --- a/core/util/treeSitter.ts +++ b/core/util/treeSitter.ts @@ -232,7 +232,7 @@ export async function getSymbolsForFile( } const tree = parser.parse(contents); - console.log(`file: ${filepath}`); + // console.log(`file: ${filepath}`); // Function to recursively find all named nodes (classes and functions) const symbols: SymbolWithRange[] = []; @@ -249,7 +249,10 @@ export async function getSymbolsForFile( // TODO use findLast in newer version of node target let identifier: Parser.SyntaxNode | undefined = undefined; for (let i = node.children.length - 1; i >= 0; i--) { - if (node.children[i].type === "identifier") { + if ( + node.children[i].type === "identifier" || + node.children[i].type === "property_identifier" + ) { identifier = node.children[i]; break; } @@ -280,7 +283,7 @@ export async function getSymbolsForFile( return symbols; } -export async function getSymbolsForFiles( +export async function getSymbolsForManyFiles( uris: string[], ide: IDE, ): Promise { diff --git a/gui/src/components/gui/StepContainer.tsx b/gui/src/components/gui/StepContainer.tsx index 22523cfb2..613b98b5b 100644 --- a/gui/src/components/gui/StepContainer.tsx +++ b/gui/src/components/gui/StepContainer.tsx @@ -105,7 +105,7 @@ function StepContainer(props: StepContainerProps) { )} diff --git a/gui/src/components/markdown/CodeSnippetPreview.tsx b/gui/src/components/markdown/CodeSnippetPreview.tsx index 39c09cfb6..639e14cc8 100644 --- a/gui/src/components/markdown/CodeSnippetPreview.tsx +++ b/gui/src/components/markdown/CodeSnippetPreview.tsx @@ -124,7 +124,6 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) { source={`${fence}${getMarkdownLanguageTagForFile( props.item.description.split(" ")[0], )} ${props.item.description}\n${content}\n${fence}`} - contextItems={[props.item]} /> diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index aca1cca2b..a2b55ba26 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -1,4 +1,4 @@ -import { memo, useEffect, useMemo } from "react"; +import { memo, useCallback, useEffect, useMemo } from "react"; import { useRemark } from "react-remark"; import rehypeHighlight, { Options } from "rehype-highlight"; import rehypeKatex from "rehype-katex"; @@ -22,7 +22,6 @@ import StepContainerPreActionButtons from "./StepContainerPreActionButtons"; import { RootState } from "../../redux/store"; import { SymbolWithRange } from "core"; import SymbolLink from "./SymbolLink"; -import { ContextItemWithId } from "core"; import { useSelector } from "react-redux"; const StyledMarkdown = styled.div<{ @@ -96,7 +95,7 @@ interface StyledMarkdownPreviewProps { className?: string; isRenderingInStepContainer?: boolean; // Currently only used to control the rendering of codeblocks scrollLocked?: boolean; - contextItems?: ContextItemWithId[]; + itemIndex?: number; } const HLJS_LANGUAGE_CLASSNAME_PREFIX = "language-"; @@ -116,14 +115,12 @@ function getLanuageFromClassName(className: any): string | null { function getCodeChildrenContent(children: any) { if (typeof children === "string") { - console.log(children); return children; } else if ( Array.isArray(children) && children.length > 0 && typeof children[0] === "string" ) { - console.log(children[0]); return children[0]; } return undefined; @@ -156,13 +153,20 @@ function processCodeBlocks(tree: any) { const StyledMarkdownPreview = memo(function StyledMarkdownPreview( props: StyledMarkdownPreviewProps, ) { + // Grab context items from the user history item before it + const contextItems = useSelector( + (state: RootState) => + state.state.history[props.itemIndex - 1]?.contextItems, + ); const symbols = useSelector((state: RootState) => state.state.symbols); + const symbolsForContextItems: SymbolWithRange[] = useMemo(() => { + if (!contextItems) { + return []; + } const contextUris = Array.from( new Set( - props.contextItems - .filter((item) => item?.uri) - .map((item) => item.uri!.value), + contextItems.filter((item) => item?.uri).map((item) => item.uri!.value), ), ); const contextSymbols: SymbolWithRange[] = []; @@ -172,9 +176,9 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( contextSymbols.push(...fileSymbols); } }); - console.log(contextSymbols.map((s) => s.name)); + console.log(contextSymbols); return contextSymbols; - }, [props.contextItems, symbols]); + }, [contextItems, symbols]); const [reactContent, setMarkdownSource] = useRemark({ remarkPlugins: [remarkMath, () => processCodeBlocks], @@ -258,30 +262,30 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( code: ({ node, ...codeProps }) => { const content = getCodeChildrenContent(codeProps.children); - if (props.contextItems) { - const ctxItem = props.contextItems.find((ctxItem) => + if (content && contextItems) { + const ctxItem = contextItems.find((ctxItem) => ctxItem.uri?.value.includes(content), ); + console.log("CTX item", ctxItem); if (ctxItem) { const rif = ctxItemToRifWithContents(ctxItem); return ; } - } - // console.log("content", content); - const exactSymbol = symbolsForContextItems.find( - (s) => s.name === content, - ); - if (exactSymbol) { - return ; - } - // PARTIAL - PARENTHESES - const partialSymbol = symbolsForContextItems.find( - (s) => false, - // content.startsWith(s.name), - ); - if (partialSymbol) { - return ; + const exactSymbol = symbolsForContextItems.find( + (s) => s.name === content, + ); + if (exactSymbol) { + return ; + } + + // PARTIAL - this is the case where the llm returns e.g. `subtract(number)` instead of `subtract` + const partialSymbol = symbolsForContextItems.find((s) => + content.startsWith(s.name), + ); + if (partialSymbol) { + return ; + } } return {codeProps.children}; }, diff --git a/gui/src/components/markdown/SymbolLink.tsx b/gui/src/components/markdown/SymbolLink.tsx index 84c1e8984..b18d302df 100644 --- a/gui/src/components/markdown/SymbolLink.tsx +++ b/gui/src/components/markdown/SymbolLink.tsx @@ -20,12 +20,12 @@ function SymbolLink({ symbol, content }: SymbolLinkProps) { return ( - + {content} - + ); } diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 8f46f50ec..460b55af8 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -137,6 +137,7 @@ export const stateSlice = createSlice({ state.mainEditorContent = undefined; }, updateFileSymbols: (state, action: PayloadAction) => { + console.log("UPDATE SYMBOLS", action.payload); state.symbols = Object.assign(state.symbols, action.payload); }, setContextItemsAtIndex: ( @@ -254,7 +255,10 @@ export const stateSlice = createSlice({ if (!historyItem) { return; } - historyItem.contextItems.push(...payload.contextItems); + historyItem.contextItems = [ + ...historyItem.contextItems, + ...payload.contextItems, + ]; }, setInactive: (state) => { state.context.isGathering = false; diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index 221d275c9..0c92e7f26 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -40,7 +40,12 @@ const windowIDTransform = (windowID: string) => ); const saveSubsetFilters = [ - createFilter("state", ["history", "sessionId", "defaultModelTitle"]), + createFilter("state", [ + "history", + "sessionId", + "defaultModelTitle", + "symbols", + ]), ]; const persistConfig = { From 1ef7087a8923a8c6cf7628b4fbf7d7ec1e2d20e8 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 18 Nov 2024 02:41:59 -0800 Subject: [PATCH 04/13] chat symbols cleanup --- core/index.d.ts | 1 - gui/src/components/mainInput/resolveInput.ts | 26 ------------------- .../markdown/StyledMarkdownPreview.tsx | 2 -- 3 files changed, 29 deletions(-) diff --git a/core/index.d.ts b/core/index.d.ts index 25d5c346d..c22a66aff 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -317,7 +317,6 @@ export interface ChatHistoryItem { editorState?: any; modifiers?: InputModifiers; contextItems: ContextItemWithId[]; - contextSymbols?: SymbolWithRange[]; promptLogs?: PromptLog[]; } diff --git a/gui/src/components/mainInput/resolveInput.ts b/gui/src/components/mainInput/resolveInput.ts index a4598ae93..e8502d89c 100644 --- a/gui/src/components/mainInput/resolveInput.ts +++ b/gui/src/components/mainInput/resolveInput.ts @@ -256,30 +256,4 @@ function resolveParagraph(p: JSONContent): [string, MentionAttrs[], string] { return [text, contextItems, slashCommand]; } -// 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; -// } -// } -// } -// } - -// return false; -// } - export default resolveEditorContent; diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index a2b55ba26..29bef8c91 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -176,7 +176,6 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( contextSymbols.push(...fileSymbols); } }); - console.log(contextSymbols); return contextSymbols; }, [contextItems, symbols]); @@ -266,7 +265,6 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( const ctxItem = contextItems.find((ctxItem) => ctxItem.uri?.value.includes(content), ); - console.log("CTX item", ctxItem); if (ctxItem) { const rif = ctxItemToRifWithContents(ctxItem); return ; From 7a3f297b20cd1abe32dcd60b7bf5d6590f94eaff Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 18 Nov 2024 03:10:39 -0800 Subject: [PATCH 05/13] fix symbols not rendering bug --- .../markdown/StyledMarkdownPreview.tsx | 26 ++++++++++++------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index 29bef8c91..be438e408 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -1,4 +1,4 @@ -import { memo, useCallback, useEffect, useMemo } from "react"; +import { memo, useCallback, useEffect, useMemo, useRef } from "react"; import { useRemark } from "react-remark"; import rehypeHighlight, { Options } from "rehype-highlight"; import rehypeKatex from "rehype-katex"; @@ -20,7 +20,7 @@ import StepContainerPreToolbar from "./StepContainerPreToolbar"; import { SyntaxHighlightedPre } from "./SyntaxHighlightedPre"; import StepContainerPreActionButtons from "./StepContainerPreActionButtons"; import { RootState } from "../../redux/store"; -import { SymbolWithRange } from "core"; +import { ContextItemWithId, SymbolWithRange } from "core"; import SymbolLink from "./SymbolLink"; import { useSelector } from "react-redux"; @@ -153,17 +153,23 @@ function processCodeBlocks(tree: any) { const StyledMarkdownPreview = memo(function StyledMarkdownPreview( props: StyledMarkdownPreviewProps, ) { - // Grab context items from the user history item before it const contextItems = useSelector( (state: RootState) => state.state.history[props.itemIndex - 1]?.contextItems, ); const symbols = useSelector((state: RootState) => state.state.symbols); - const symbolsForContextItems: SymbolWithRange[] = useMemo(() => { + // 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 symbolsForContextItems = useRef([]); + const contextItemsRef = useRef([]); + useEffect(() => { + contextItemsRef.current = contextItems || []; if (!contextItems) { - return []; + symbolsForContextItems.current = []; } + // Get unique URIs and then find relevant symbols const contextUris = Array.from( new Set( contextItems.filter((item) => item?.uri).map((item) => item.uri!.value), @@ -176,7 +182,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( contextSymbols.push(...fileSymbols); } }); - return contextSymbols; + symbolsForContextItems.current = contextSymbols; }, [contextItems, symbols]); const [reactContent, setMarkdownSource] = useRemark({ @@ -261,8 +267,8 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( code: ({ node, ...codeProps }) => { const content = getCodeChildrenContent(codeProps.children); - if (content && contextItems) { - const ctxItem = contextItems.find((ctxItem) => + if (content && contextItemsRef.current) { + const ctxItem = contextItemsRef.current.find((ctxItem) => ctxItem.uri?.value.includes(content), ); if (ctxItem) { @@ -270,7 +276,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( return ; } - const exactSymbol = symbolsForContextItems.find( + const exactSymbol = symbolsForContextItems.current.find( (s) => s.name === content, ); if (exactSymbol) { @@ -278,7 +284,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( } // PARTIAL - this is the case where the llm returns e.g. `subtract(number)` instead of `subtract` - const partialSymbol = symbolsForContextItems.find((s) => + const partialSymbol = symbolsForContextItems.current.find((s) => content.startsWith(s.name), ); if (partialSymbol) { From f76c69dfda0ae439f16a5e28db48328dfabb9309 Mon Sep 17 00:00:00 2001 From: Test Date: Mon, 18 Nov 2024 12:23:43 -0800 Subject: [PATCH 06/13] chore: merge main --- core/llm/llms/Bedrock.ts | 11 ++++++-- .../StepContainer/StepContainer.tsx | 1 + gui/src/components/mainInput/resolveInput.ts | 26 +++++++++++++++++++ 3 files changed, 36 insertions(+), 2 deletions(-) diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index 67d8a4167..9d9f3af87 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -14,6 +14,11 @@ import { import { stripImages } from "../images.js"; import { BaseLLM } from "../index.js"; +/** + * Bedrock class implements AWS Bedrock LLM integration. + * It handles streaming completions and chat messages using AWS Bedrock runtime. + * Supports both text and image inputs through Claude 3 models. + */ class Bedrock extends BaseLLM { static providerName: ModelProvider = "bedrock"; static defaultOptions: Partial = { @@ -120,7 +125,9 @@ class Bedrock extends BaseLLM { // TODO: Additionally, consider implementing a global exception handler for the providers to give users clearer feedback. // For example, differentiate between client-side errors (4XX status codes) and server-side issues (5XX status codes), // providing meaningful error messages to improve the user experience. - stopSequences: options.stop?.filter((stop) => stop.trim() !== "").slice(0, 4), + stopSequences: options.stop + ?.filter((stop) => stop.trim() !== "") + .slice(0, 4), }, }; } @@ -162,7 +169,7 @@ class Bedrock extends BaseLLM { try { return await fromIni({ profile: this.profile, - ignoreCache: true + ignoreCache: true, })(); } catch (e) { console.warn( diff --git a/gui/src/components/StepContainer/StepContainer.tsx b/gui/src/components/StepContainer/StepContainer.tsx index f5673e4e8..4fdd6eda2 100644 --- a/gui/src/components/StepContainer/StepContainer.tsx +++ b/gui/src/components/StepContainer/StepContainer.tsx @@ -93,6 +93,7 @@ export default function StepContainer(props: StepContainerProps) { )} diff --git a/gui/src/components/mainInput/resolveInput.ts b/gui/src/components/mainInput/resolveInput.ts index e8502d89c..4c7f4c640 100644 --- a/gui/src/components/mainInput/resolveInput.ts +++ b/gui/src/components/mainInput/resolveInput.ts @@ -256,4 +256,30 @@ function resolveParagraph(p: JSONContent): [string, MentionAttrs[], string] { return [text, contextItems, slashCommand]; } +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; + } + } + } + } + + return false; +} + export default resolveEditorContent; From 389b2c94c2f6ed178c109bb3872fd368c24155b5 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 19 Nov 2024 16:39:28 -0800 Subject: [PATCH 07/13] symbols bug fixes --- .../components/History/HistoryTableRow.tsx | 13 +++++-- gui/src/components/mainInput/resolveInput.ts | 19 ++--------- gui/src/components/markdown/FilenameLink.tsx | 4 +-- .../markdown/StyledMarkdownPreview.tsx | 32 ++++++----------- gui/src/components/markdown/SymbolLink.tsx | 4 +-- gui/src/hooks/useHistory.tsx | 15 ++++++-- gui/src/redux/slices/stateSlice.ts | 4 +-- gui/src/redux/store.ts | 7 +--- gui/src/util/symbols.ts | 34 +++++++++++++++++++ 9 files changed, 76 insertions(+), 56 deletions(-) create mode 100644 gui/src/util/symbols.ts diff --git a/gui/src/components/History/HistoryTableRow.tsx b/gui/src/components/History/HistoryTableRow.tsx index 26107c199..695389c29 100644 --- a/gui/src/components/History/HistoryTableRow.tsx +++ b/gui/src/components/History/HistoryTableRow.tsx @@ -1,11 +1,12 @@ import { PencilSquareIcon, TrashIcon } from "@heroicons/react/24/outline"; import { SessionInfo } from "core"; import React, { useState } from "react"; -import { useDispatch } from "react-redux"; +import { useDispatch, useSelector } from "react-redux"; import { useNavigate } from "react-router-dom"; import { Input } from ".."; import useHistory from "../../hooks/useHistory"; import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; +import { RootState } from "../../redux/store"; function lastPartOfPath(path: string): string { const sep = path.includes("/") ? "/" : "\\"; @@ -29,6 +30,9 @@ export function HistoryTableRow({ const [sessionTitleEditValue, setSessionTitleEditValue] = useState( session.title, ); + const currentSessionId = useSelector( + (state: RootState) => state.state.sessionId, + ); const { saveSession, deleteSession, loadSession, getSession, updateSession } = useHistory(dispatch); @@ -59,8 +63,11 @@ export function HistoryTableRow({ className="hover:bg-vsc-editor-background relative box-border flex max-w-full cursor-pointer overflow-hidden rounded-lg p-3" onClick={async () => { // Save current session - await saveSession(); - await loadSession(session.sessionId); + if (session.sessionId !== currentSessionId) { + await saveSession(); + await loadSession(session.sessionId); + } + navigate("/"); }} > diff --git a/gui/src/components/mainInput/resolveInput.ts b/gui/src/components/mainInput/resolveInput.ts index 4c7f4c640..a933bd1a3 100644 --- a/gui/src/components/mainInput/resolveInput.ts +++ b/gui/src/components/mainInput/resolveInput.ts @@ -14,6 +14,7 @@ import { setIsGatheringContext, updateFileSymbols, } from "../../redux/slices/stateSlice"; +import { updateFileSymbolsFromContextItems } from "../../util/symbols"; interface MentionAttrs { label: string; @@ -174,23 +175,7 @@ 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 symbolsResult = await ideMessenger.request( - "context/getSymbolsForFiles", - { - uris: contextItemFileUris, - }, - ); - if (symbolsResult.status === "success") { - dispatch(updateFileSymbols(symbolsResult.content)); - } + await updateFileSymbolsFromContextItems(contextItems, ideMessenger, dispatch); if (contextItemsText !== "") { contextItemsText += "\n"; diff --git a/gui/src/components/markdown/FilenameLink.tsx b/gui/src/components/markdown/FilenameLink.tsx index 0d1166a00..d63bf8309 100644 --- a/gui/src/components/markdown/FilenameLink.tsx +++ b/gui/src/components/markdown/FilenameLink.tsx @@ -21,11 +21,11 @@ function FilenameLink({ rif }: FilenameLinkProps) { return ( - + {getBasename(rif.filepath)} diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index 9ded0464f..ca1ea2afd 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -164,28 +164,18 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( // 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 symbolsForContextItems = useRef([]); + const symbolsRef = useRef([]); const contextItemsRef = useRef([]); + useEffect(() => { contextItemsRef.current = contextItems || []; - if (!contextItems) { - symbolsForContextItems.current = []; - } - // Get unique URIs and then find relevant symbols - const contextUris = Array.from( - new Set( - contextItems.filter((item) => item?.uri).map((item) => item.uri!.value), - ), - ); - const contextSymbols: SymbolWithRange[] = []; - contextUris.forEach((uri) => { - const fileSymbols = symbols[uri]; - if (fileSymbols) { - contextSymbols.push(...fileSymbols); - } - }); - symbolsForContextItems.current = contextSymbols; - }, [contextItems, symbols]); + }, [contextItems]); + useEffect(() => { + // Note, before I was only looking for symbols that matched + // Context item files on current history item + // but in practice global symbols for session makes way more sense + symbolsRef.current = Object.values(symbols).flat(); + }, [symbols]); const [reactContent, setMarkdownSource] = useRemark({ remarkPlugins: [remarkMath, () => processCodeBlocks], @@ -278,7 +268,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( return ; } - const exactSymbol = symbolsForContextItems.current.find( + const exactSymbol = symbolsRef.current.find( (s) => s.name === content, ); if (exactSymbol) { @@ -286,7 +276,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( } // PARTIAL - this is the case where the llm returns e.g. `subtract(number)` instead of `subtract` - const partialSymbol = symbolsForContextItems.current.find((s) => + const partialSymbol = symbolsRef.current.find((s) => content.startsWith(s.name), ); if (partialSymbol) { diff --git a/gui/src/components/markdown/SymbolLink.tsx b/gui/src/components/markdown/SymbolLink.tsx index b18d302df..569a493e5 100644 --- a/gui/src/components/markdown/SymbolLink.tsx +++ b/gui/src/components/markdown/SymbolLink.tsx @@ -20,10 +20,10 @@ function SymbolLink({ symbol, content }: SymbolLinkProps) { return ( - + {content} diff --git a/gui/src/hooks/useHistory.tsx b/gui/src/hooks/useHistory.tsx index f159ffea3..b52271ab4 100644 --- a/gui/src/hooks/useHistory.tsx +++ b/gui/src/hooks/useHistory.tsx @@ -7,9 +7,10 @@ import { useSelector } from "react-redux"; import { IdeMessengerContext } from "../context/IdeMessenger"; import { useLastSessionContext } from "../context/LastSessionContext"; import { defaultModelSelector } from "../redux/selectors/modelSelectors"; -import { newSession } from "../redux/slices/stateSlice"; +import { newSession, updateFileSymbols } from "../redux/slices/stateSlice"; import { RootState } from "../redux/store"; import { getLocalStorage, setLocalStorage } from "../util/localStorage"; +import { updateFileSymbolsFromContextItems } from "../util/symbols"; const MAX_TITLE_LENGTH = 100; @@ -22,7 +23,6 @@ function truncateText(text: string, maxLength: number) { function useHistory(dispatch: Dispatch) { const state = useSelector((state: RootState) => state.state); - const defaultModel = useSelector(defaultModelSelector); const ideMessenger = useContext(IdeMessengerContext); const { lastSessionId, setLastSessionId } = useLastSessionContext(); @@ -122,7 +122,18 @@ function useHistory(dispatch: Dispatch) { if (result.status === "error") { throw new Error(result.error); } + const persistedSessionInfo = result.content; + + // Update file symbols on session load for all context items + await updateFileSymbolsFromContextItems( + persistedSessionInfo.history + .map((item) => item.contextItems ?? []) + .flat(), + ideMessenger, + dispatch, + ); + dispatch(newSession(persistedSessionInfo)); return persistedSessionInfo; } diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index c8abe266e..09735499f 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -4,7 +4,6 @@ import { ChatHistoryItem, ChatMessage, Checkpoint, - ContextItemId, ContextItemWithId, FileSymbolMap, PersistedSessionInfo, @@ -146,7 +145,6 @@ export const stateSlice = createSlice({ state.mainEditorContent = undefined; }, updateFileSymbols: (state, action: PayloadAction) => { - console.log("UPDATE SYMBOLS", action.payload); state.symbols = Object.assign(state.symbols, action.payload); }, setContextItemsAtIndex: ( @@ -379,7 +377,7 @@ export const stateSlice = createSlice({ curApplyState.numDiffs = payload.numDiffs ?? curApplyState.numDiffs; curApplyState.filepath = payload.filepath ?? curApplyState.filepath; } - if(payload.status === "done"){ + if (payload.status === "done") { state.nextCodeBlockToApplyIndex++; } }, diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index 986075a84..725d88c01 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -39,12 +39,7 @@ const windowIDTransform = (windowID: string) => ); const saveSubsetFilters = [ - createFilter("state", [ - "history", - "sessionId", - "defaultModelTitle", - "symbols", - ]), + createFilter("state", ["history", "sessionId", "defaultModelTitle"]), ]; const persistConfig = { diff --git a/gui/src/util/symbols.ts b/gui/src/util/symbols.ts new file mode 100644 index 000000000..98848053a --- /dev/null +++ b/gui/src/util/symbols.ts @@ -0,0 +1,34 @@ +import { ContextItemWithId } from "core"; +import { IIdeMessenger } from "../context/IdeMessenger"; +import { updateFileSymbols } from "../redux/slices/stateSlice"; +import { Dispatch } from "@reduxjs/toolkit"; + +export async function updateFileSymbolsFromContextItems( + contextItems: ContextItemWithId[], + ideMessenger: IIdeMessenger, + dispatch: Dispatch, +) { + // Given a list of context items, + // Get unique file uris + try { + const contextUris = Array.from( + new Set( + contextItems + .filter((item) => item.uri?.type === "file" && item?.uri?.value) + .map((item) => item.uri.value), + ), + ); + // And then update symbols for those files + if (contextUris.length > 0) { + const symbolsResult = await ideMessenger.request( + "context/getSymbolsForFiles", + { uris: contextUris }, + ); + if (symbolsResult.status === "success") { + dispatch(updateFileSymbols(symbolsResult.content)); + } + } + } catch (e) { + console.error("Error updating file symbols from context items", e); + } +} From 3b292cf732b73e9d4bd57354042ab165f1321a86 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 19 Nov 2024 23:40:47 -0800 Subject: [PATCH 08/13] update symbols on load --- gui/src/hooks/useSetup.ts | 14 +++++++++++++- gui/src/redux/slices/stateSlice.ts | 10 ---------- 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 593283849..6aeaae25c 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -19,9 +19,11 @@ import { isJetBrains } from "../util"; import { getLocalStorage, setLocalStorage } from "../util/localStorage"; import useChatHandler from "./useChatHandler"; import { useWebviewListener } from "./useWebviewListener"; +import { updateFileSymbolsFromContextItems } from "../util/symbols"; function useSetup(dispatch: Dispatch) { const ideMessenger = useContext(IdeMessengerContext); + const history = useSelector((store: RootState) => store.state.history); const initialConfigLoad = useRef(false); const loadConfig = useCallback(async () => { @@ -59,6 +61,17 @@ function useSetup(dispatch: Dispatch) { return () => clearInterval(interval); }, [initialConfigLoad, loadConfig]); + useEffect(() => { + // currently persist gate ensures that + // State.history is loaded before this is called + // Load symbols for chat on startup + updateFileSymbolsFromContextItems( + history.flatMap((item) => item.contextItems), + ideMessenger, + dispatch, + ); + }, []); + useEffect(() => { // Override persisted state dispatch(setInactive()); @@ -86,7 +99,6 @@ function useSetup(dispatch: Dispatch) { ); // IDE event listeners - const history = useSelector((store: RootState) => store.state.history); useWebviewListener( "getWebviewHistoryLength", async () => { diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 09735499f..56bc9d7b5 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -387,16 +387,6 @@ export const stateSlice = createSlice({ }, }); -export const memoizedContextItemsSelector = createSelector( - [(state: RootState) => state.state.history], - (history) => { - return history.reduce((acc, item) => { - acc.push(...item.contextItems); - return acc; - }, []); - }, -); - export const { updateFileSymbols, setContextItemsAtIndex, From b80833158b430779dbc4141cc6dac68ab3b7b447 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 19 Nov 2024 23:47:43 -0800 Subject: [PATCH 09/13] better styling on file and symbol links --- gui/src/components/markdown/FilenameLink.tsx | 2 +- gui/src/components/markdown/SymbolLink.tsx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/gui/src/components/markdown/FilenameLink.tsx b/gui/src/components/markdown/FilenameLink.tsx index d63bf8309..20b7c0343 100644 --- a/gui/src/components/markdown/FilenameLink.tsx +++ b/gui/src/components/markdown/FilenameLink.tsx @@ -21,7 +21,7 @@ function FilenameLink({ rif }: FilenameLinkProps) { return ( diff --git a/gui/src/components/markdown/SymbolLink.tsx b/gui/src/components/markdown/SymbolLink.tsx index 569a493e5..0dea98a28 100644 --- a/gui/src/components/markdown/SymbolLink.tsx +++ b/gui/src/components/markdown/SymbolLink.tsx @@ -20,7 +20,7 @@ function SymbolLink({ symbol, content }: SymbolLinkProps) { return ( From f210faf09d36805f58ff3a843383d665027c036f Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 19 Nov 2024 23:57:11 -0800 Subject: [PATCH 10/13] chat symbols - active file working --- gui/src/components/mainInput/resolveInput.ts | 8 +------- gui/src/hooks/useChatHandler.ts | 7 ++++++- gui/src/hooks/useHistory.tsx | 3 +-- gui/src/pages/edit/index.tsx | 2 ++ gui/src/util/symbols.ts | 1 + 5 files changed, 11 insertions(+), 10 deletions(-) diff --git a/gui/src/components/mainInput/resolveInput.ts b/gui/src/components/mainInput/resolveInput.ts index a933bd1a3..b12804d72 100644 --- a/gui/src/components/mainInput/resolveInput.ts +++ b/gui/src/components/mainInput/resolveInput.ts @@ -10,11 +10,7 @@ import { import { stripImages } from "core/llm/images"; import { IIdeMessenger } from "../../context/IdeMessenger"; import { Dispatch } from "@reduxjs/toolkit"; -import { - setIsGatheringContext, - updateFileSymbols, -} from "../../redux/slices/stateSlice"; -import { updateFileSymbolsFromContextItems } from "../../util/symbols"; +import { setIsGatheringContext } from "../../redux/slices/stateSlice"; interface MentionAttrs { label: string; @@ -175,8 +171,6 @@ async function resolveEditorContent( ); contextItems.push(...defaultContextItems.flat()); - await updateFileSymbolsFromContextItems(contextItems, ideMessenger, dispatch); - if (contextItemsText !== "") { contextItemsText += "\n"; } diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index b9342d4e9..a4aeb799e 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -37,6 +37,7 @@ import { import { resetNextCodeBlockToApplyIndex } from "../redux/slices/stateSlice"; import { RootState } from "../redux/store"; import useHistory from "./useHistory"; +import { updateFileSymbolsFromContextItems } from "../util/symbols"; function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { const posthog = usePostHog(); @@ -256,7 +257,11 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { } } - // dispatch(addContextItems(contextItems)); + await updateFileSymbolsFromContextItems( + selectedContextItems, + ideMessenger, + dispatch, + ); const message: ChatMessage = { role: "user", diff --git a/gui/src/hooks/useHistory.tsx b/gui/src/hooks/useHistory.tsx index b52271ab4..4bdd1e2c1 100644 --- a/gui/src/hooks/useHistory.tsx +++ b/gui/src/hooks/useHistory.tsx @@ -6,8 +6,7 @@ import { useCallback, useContext } from "react"; import { useSelector } from "react-redux"; import { IdeMessengerContext } from "../context/IdeMessenger"; import { useLastSessionContext } from "../context/LastSessionContext"; -import { defaultModelSelector } from "../redux/selectors/modelSelectors"; -import { newSession, updateFileSymbols } from "../redux/slices/stateSlice"; +import { newSession } from "../redux/slices/stateSlice"; import { RootState } from "../redux/store"; import { getLocalStorage, setLocalStorage } from "../util/localStorage"; import { updateFileSymbolsFromContextItems } from "../util/symbols"; diff --git a/gui/src/pages/edit/index.tsx b/gui/src/pages/edit/index.tsx index 2e93a16aa..26fbacbb1 100644 --- a/gui/src/pages/edit/index.tsx +++ b/gui/src/pages/edit/index.tsx @@ -177,6 +177,8 @@ function Edit() { dispatch, ); + // Note, not currently updating file symbols in edit mode + const prompt = [ ...contextItems.map((item) => item.content), stripImages(userInstructions), diff --git a/gui/src/util/symbols.ts b/gui/src/util/symbols.ts index 98848053a..5c4e1be12 100644 --- a/gui/src/util/symbols.ts +++ b/gui/src/util/symbols.ts @@ -29,6 +29,7 @@ export async function updateFileSymbolsFromContextItems( } } } catch (e) { + // Catch all - don't want file symbols to break the chat experience for now console.error("Error updating file symbols from context items", e); } } From f5ab00d3ae0da78318af4e1463756a5d3be1f20c Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 20 Nov 2024 00:02:50 -0800 Subject: [PATCH 11/13] chat symbols style tweaks --- gui/src/components/markdown/FilenameLink.tsx | 2 +- gui/src/components/markdown/SymbolLink.tsx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/gui/src/components/markdown/FilenameLink.tsx b/gui/src/components/markdown/FilenameLink.tsx index 20b7c0343..161bd0b0a 100644 --- a/gui/src/components/markdown/FilenameLink.tsx +++ b/gui/src/components/markdown/FilenameLink.tsx @@ -21,7 +21,7 @@ function FilenameLink({ rif }: FilenameLinkProps) { return ( diff --git a/gui/src/components/markdown/SymbolLink.tsx b/gui/src/components/markdown/SymbolLink.tsx index 0dea98a28..45d54ba8f 100644 --- a/gui/src/components/markdown/SymbolLink.tsx +++ b/gui/src/components/markdown/SymbolLink.tsx @@ -20,7 +20,7 @@ function SymbolLink({ symbol, content }: SymbolLinkProps) { return ( From f9c1b37c80b35aec65f4eb376ea4b965f098f37b Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 20 Nov 2024 01:15:59 -0800 Subject: [PATCH 12/13] move update file symbols on load to use setup --- gui/src/hooks/useHistory.tsx | 9 --------- gui/src/hooks/useSetup.ts | 21 ++++++++++++--------- gui/src/redux/slices/stateSlice.ts | 7 +++++-- 3 files changed, 17 insertions(+), 20 deletions(-) diff --git a/gui/src/hooks/useHistory.tsx b/gui/src/hooks/useHistory.tsx index 38aa5ec2b..e6feec628 100644 --- a/gui/src/hooks/useHistory.tsx +++ b/gui/src/hooks/useHistory.tsx @@ -9,7 +9,6 @@ import { useLastSessionContext } from "../context/LastSessionContext"; import { newSession } from "../redux/slices/stateSlice"; import { RootState } from "../redux/store"; import { getLocalStorage, setLocalStorage } from "../util/localStorage"; -import { updateFileSymbolsFromContextItems } from "../util/symbols"; const MAX_TITLE_LENGTH = 100; @@ -123,14 +122,6 @@ function useHistory(dispatch: Dispatch) { } const sessionContent = result.content; - - // Update file symbols on session load for all context items - await updateFileSymbolsFromContextItems( - sessionContent.history.map((item) => item.contextItems ?? []).flat(), - ideMessenger, - dispatch, - ); - dispatch(newSession(sessionContent)); return sessionContent; } diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index e95db68b3..ee80c36c3 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -61,16 +61,19 @@ function useSetup(dispatch: Dispatch) { return () => clearInterval(interval); }, [initialConfigLoad, loadConfig]); + // Load symbols for chat on any session change + const sessionId = useSelector((store: RootState) => store.state.sessionId); + const sessionIdRef = useRef(""); useEffect(() => { - // currently persist gate ensures that - // State.history is loaded before this is called - // Load symbols for chat on startup - updateFileSymbolsFromContextItems( - history.flatMap((item) => item.contextItems), - ideMessenger, - dispatch, - ); - }, []); + if (sessionIdRef.current !== sessionId) { + updateFileSymbolsFromContextItems( + history.flatMap((item) => item.contextItems), + ideMessenger, + dispatch, + ); + } + sessionIdRef.current = sessionId; + }, [sessionId, history, ideMessenger, dispatch]); useEffect(() => { // Override persisted state diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 8f1906409..c0132cf41 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -145,7 +145,10 @@ export const stateSlice = createSlice({ state.mainEditorContent = undefined; }, updateFileSymbols: (state, action: PayloadAction) => { - state.symbols = Object.assign(state.symbols, action.payload); + state.symbols = { + ...state.symbols, + ...action.payload, + }; }, setContextItemsAtIndex: ( state, @@ -290,7 +293,7 @@ export const stateSlice = createSlice({ state.streamAborter = new AbortController(); state.active = false; - state.isGatheringContext = false; + state.context.isGathering = false; state.isMultifileEdit = false; if (payload) { state.history = payload.history as any; From eb4030207f41ee68f3e6de433b1d0023d2b030b8 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 20 Nov 2024 10:31:49 -0800 Subject: [PATCH 13/13] clear symbols on new session --- gui/src/redux/slices/stateSlice.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index c0132cf41..29fee95d3 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -12,8 +12,8 @@ import { import { BrowserSerializedContinueConfig } from "core/config/load"; import { ConfigValidationError } from "core/config/validation"; import { stripImages } from "core/llm/images"; -import { v4 as uuidv4, v4 } from "uuid"; import { ApplyState } from "core/protocol/ideWebview"; +import { v4 as uuidv4, v4 } from "uuid"; // 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. @@ -295,6 +295,7 @@ export const stateSlice = createSlice({ state.active = false; state.context.isGathering = false; state.isMultifileEdit = false; + state.symbols = {}; if (payload) { state.history = payload.history as any; state.title = payload.title;