merge main

This commit is contained in:
Dallin Romney 2024-11-20 10:36:58 -08:00
commit af5e2ed10d
39 changed files with 1571 additions and 586 deletions

View file

@ -9,7 +9,6 @@ import {
} from "../..";
import DocsService from "../../indexing/docs/DocsService";
import preIndexedDocs from "../../indexing/docs/preIndexedDocs";
import { Telemetry } from "../../util/posthog";
import { INSTRUCTIONS_BASE_ITEM } from "./utils";
@ -88,38 +87,10 @@ class DocsContextProvider extends BaseContextProvider {
return [];
}
const isJetBrainsAndPreIndexedDocsProvider =
await docsService.isJetBrainsAndPreIndexedDocsProvider();
if (isJetBrainsAndPreIndexedDocsProvider) {
void extras.ide.showToast(
"error",
`${DocsService.preIndexedDocsEmbeddingsProvider.id} is configured as ` +
"the embeddings provider, but it cannot be used with JetBrains. " +
"Please select a different embeddings provider to use the '@docs' " +
"context provider.",
);
return [];
}
const preIndexedDoc = preIndexedDocs[query];
if (!!preIndexedDoc) {
void Telemetry.capture("docs_pre_indexed_doc_used", {
doc: preIndexedDoc["title"],
});
}
const embeddingsProvider = await docsService.getEmbeddingsProvider(
!!preIndexedDoc,
);
const [vector] = await embeddingsProvider.embed([extras.fullInput]);
let chunks = await docsService.retrieveChunks(
await docsService.isInitialized;
let chunks = await docsService.retrieveChunksFromQuery(
extras.fullInput, // confusing: fullInput = the query, query = startUrl in this case
query,
vector,
this.options?.nRetrieve ?? DocsContextProvider.nRetrieve,
);
@ -175,7 +146,7 @@ class DocsContextProvider extends BaseContextProvider {
return [];
}
const docs = (await docsService.list()) ?? [];
const docs = (await docsService.listMetadata()) ?? [];
const canUsePreindexedDocs = await docsService.canUsePreindexedDocs();
const submenuItemsMap = new Map<string, ContextSubmenuItem>();

View file

@ -30,6 +30,7 @@ import { GlobalContext } from "./util/GlobalContext";
import historyManager from "./util/history";
import { editConfigJson, setupInitialDotContinueDirectory } from "./util/paths";
import { Telemetry } from "./util/posthog";
import { getSymbolsForManyFiles } from "./util/treeSitter";
import { TTS } from "./util/tts";
import type { ContextItemId, IDE, IndexingProgressUpdate } from ".";
@ -42,7 +43,7 @@ export class Core {
codebaseIndexerPromise: Promise<CodebaseIndexer>;
completionProvider: CompletionProvider;
continueServerClientPromise: Promise<ContinueServerClient>;
indexingState: IndexingProgressUpdate;
codebaseIndexingState: IndexingProgressUpdate;
controlPlaneClient: ControlPlaneClient;
private docsService: DocsService;
private globalContext = new GlobalContext();
@ -88,7 +89,11 @@ export class Core {
// Ensure .continue directory is created
setupInitialDotContinueDirectory();
this.indexingState = { status: "loading", desc: "loading", progress: 0 };
this.codebaseIndexingState = {
status: "loading",
desc: "loading",
progress: 0,
};
const ideSettingsPromise = messenger.request("getIdeSettings", undefined);
const sessionInfoPromise = messenger.request("getControlPlaneSessionInfo", {
@ -148,6 +153,7 @@ export class Core {
// Index on initialization
void this.ide.getWorkspaceDirs().then(async (dirs) => {
// Respect pauseCodebaseIndexOnStart user settings
this.indexingPauseToken.paused = true;
if (ideSettings.pauseCodebaseIndexOnStart) {
void this.messenger.request("indexProgress", {
progress: 1,
@ -272,34 +278,15 @@ export class Core {
// Context providers
on("context/addDocs", async (msg) => {
let hasFailed = false;
for await (const result of this.docsService.indexAndAdd(msg.data)) {
if (result.status === "failed") {
hasFailed = true;
break;
}
}
if (hasFailed) {
void this.ide.showToast("info", `Failed to index ${msg.data.startUrl}`);
} else {
void this.ide.showToast(
"info",
`Successfully indexed ${msg.data.startUrl}`,
);
this.messenger.send("refreshSubmenuItems", undefined);
}
void this.docsService.indexAndAdd(msg.data);
});
on("context/removeDocs", async (msg) => {
await this.docsService.delete(msg.data.startUrl);
this.messenger.send("refreshSubmenuItems", undefined);
});
on("context/indexDocs", async (msg) => {
await this.docsService.indexAllDocs(msg.data.reIndex);
this.messenger.send("refreshSubmenuItems", undefined);
await this.docsService.syncOrReindexAllDocsWithPrompt(msg.data.reIndex);
});
on("context/loadSubmenuItems", async (msg) => {
@ -365,6 +352,11 @@ export class Core {
}
});
on("context/getSymbolsForFiles", async (msg) => {
const { uris } = msg.data;
return await getSymbolsForManyFiles(uris, this.ide);
});
on("config/getSerializedProfileInfo", async (msg) => {
return {
config: await this.configHandler.getSerializedConfig(),
@ -687,6 +679,8 @@ export class Core {
const rows = await DevDataSqliteDb.getTokensPerModel();
return rows;
});
// Codebase indexing
on("index/forceReIndex", async ({ data }) => {
if (data?.shouldClearIndexes) {
const codebaseIndexer = await this.codebaseIndexerPromise;
@ -702,17 +696,41 @@ export class Core {
}
});
on("index/setPaused", (msg) => {
new GlobalContext().update("indexingPaused", msg.data);
this.globalContext.update("indexingPaused", msg.data);
this.indexingPauseToken.paused = msg.data;
});
on("index/indexingProgressBarInitialized", async (msg) => {
// Triggered when progress bar is initialized.
// If a non-default state has been stored, update the indexing display to that state
if (this.indexingState.status !== "loading") {
void this.messenger.request("indexProgress", this.indexingState);
if (this.codebaseIndexingState.status !== "loading") {
void this.messenger.request(
"indexProgress",
this.codebaseIndexingState,
);
}
});
// Docs, etc. indexing
on("indexing/reindex", async (msg) => {
if (msg.data.type === "docs") {
void this.docsService.reindexDoc(msg.data.id);
}
});
on("indexing/abort", async (msg) => {
if (msg.data.type === "docs") {
this.docsService.abort(msg.data.id);
}
});
on("indexing/setPaused", async (msg) => {
if (msg.data.type === "docs") {
this.docsService.setPaused(msg.data.id, msg.data.paused);
}
});
on("indexing/initStatuses", async (msg) => {
return this.docsService.initStatuses();
});
//
on("didChangeSelectedProfile", (msg) => {
void this.configHandler.setSelectedProfile(msg.data.id);
void this.configHandler.reloadConfig();
@ -769,7 +787,7 @@ export class Core {
}
void this.messenger.request("indexProgress", updateToSend);
this.indexingState = updateToSend;
this.codebaseIndexingState = updateToSend;
if (update.status === "failed") {
void this.sendIndexingErrorTelemetry(update);
@ -803,7 +821,7 @@ export class Core {
}
void this.messenger.request("indexProgress", updateToSend);
this.indexingState = updateToSend;
this.codebaseIndexingState = updateToSend;
if (update.status === "failed") {
void this.sendIndexingErrorTelemetry(update);
@ -812,4 +830,6 @@ export class Core {
this.messenger.send("refreshSubmenuItems", undefined);
}
// private
}

33
core/index.d.ts vendored
View file

@ -1,3 +1,4 @@
import Parser from "web-tree-sitter";
import { GetGhTokenArgs } from "./protocol/ide";
declare global {
@ -45,6 +46,30 @@ export interface IndexingProgressUpdate {
debugInfo?: string;
}
// This is more or less a V2 of IndexingProgressUpdate
export interface IndexingStatus {
id: string;
type: "docs";
progress: number;
description: string;
status:
| "indexing"
| "complete"
| "paused"
| "failed"
| "aborted"
| "deleted"
| "pending";
embeddingsProviderId: string;
isReindexing?: boolean;
debugInfo?: string;
title: string;
icon?: string;
url?: string;
}
export type IndexingStatusMap = Map<string, IndexingStatus>;
export type PromptTemplateFunction = (
history: ChatMessage[],
otherData: Record<string, string>,
@ -311,13 +336,19 @@ export interface InputModifiers {
noContext: boolean;
}
export interface SymbolWithRange extends RangeInFile {
name: string;
type: Parser.SyntaxNode["type"];
}
export type FileSymbolMap = Record<string, SymbolWithRange[]>;
export interface PromptLog {
modelTitle: string;
completionOptions: CompletionOptions;
prompt: string;
completion: string;
}
export interface ChatHistoryItem {
message: ChatMessage;
editorState?: any;

View file

@ -95,6 +95,6 @@ export default DocsCrawler;
export {
CheerioCrawler,
ChromiumCrawler,
ChromiumInstaller as ChromiumInstaller,
ChromiumInstaller,
GitHubCrawler,
};

View file

@ -66,23 +66,20 @@ describe.skip("DocsService Integration Tests", () => {
});
test("Indexing, retrieval, and deletion of a new documentation site", async () => {
const generator = docsService.indexAndAdd(mockSiteConfig);
while (!(await generator.next()).done) {}
await docsService.indexAndAdd(mockSiteConfig);
let latestConfig = await getReloadedConfig();
// Sqlite check
expect(await docsService.has(mockSiteConfig.startUrl)).toBe(true);
expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(true);
// config.json check
expect(latestConfig.docs).toContainEqual(mockSiteConfig);
// Lance DB check
const embeddingsProvider = await docsService.getEmbeddingsProvider();
const [mockVector] = await embeddingsProvider.embed(["test"]);
let retrievedChunks = await docsService.retrieveChunks(
let retrievedChunks = await docsService.retrieveChunksFromQuery(
"test",
mockSiteConfig.startUrl,
mockVector,
5,
);
@ -91,7 +88,7 @@ describe.skip("DocsService Integration Tests", () => {
await docsService.delete(mockSiteConfig.startUrl);
// Sqlite check
expect(await docsService.has(mockSiteConfig.startUrl)).toBe(false);
expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(false);
// config.json check
latestConfig = await getReloadedConfig();
@ -100,9 +97,9 @@ describe.skip("DocsService Integration Tests", () => {
);
// LanceDB check
retrievedChunks = await docsService.retrieveChunks(
retrievedChunks = await docsService.retrieveChunksFromQuery(
"test",
mockSiteConfig.startUrl,
mockVector,
5,
);
expect(retrievedChunks.length).toBe(0);
@ -133,17 +130,15 @@ describe.skip("DocsService Integration Tests", () => {
test("Handles pulling down and adding pre-indexed docs", async () => {
const preIndexedDoc = Object.values(preIndexedDocs)[0];
const generator = docsService.indexAndAdd(preIndexedDoc);
while (!(await generator.next()).done) {}
await docsService.indexAndAdd(preIndexedDoc);
});
test("Config synchronization with SQLite", async () => {
const generator = docsService.indexAndAdd(mockSiteConfig);
while (!(await generator.next()).done) {}
await docsService.indexAndAdd(mockSiteConfig);
await getReloadedConfig();
expect(await docsService.has(mockSiteConfig.startUrl)).toBe(true);
expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(true);
editConfigJson((config) => {
const { docs, ...restConfig } = config;
@ -164,6 +159,6 @@ describe.skip("DocsService Integration Tests", () => {
await new Promise((resolve) => setTimeout(resolve, 100));
}
expect(await docsService.has(mockSiteConfig.startUrl)).toBe(false);
expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(false);
});
});

File diff suppressed because it is too large Load diff

View file

@ -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<LLMOptions> = {
@ -122,7 +127,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),
},
};
}
@ -164,7 +171,7 @@ class Bedrock extends BaseLLM {
try {
return await fromIni({
profile: this.profile,
ignoreCache: true
ignoreCache: true,
})();
} catch (e) {
console.warn(

View file

@ -7,7 +7,9 @@ import type {
ContextItemWithId,
ContextSubmenuItem,
DiffLine,
FileSymbolMap,
IdeSettings,
IndexingStatusMap,
LLMFullCompletionOptions,
MessageContent,
ModelDescription,
@ -76,6 +78,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
},
ContextItemWithId[],
];
"context/getSymbolsForFiles": [{ uris: string[] }, FileSymbolMap];
"context/loadSubmenuItems": [{ title: string }, ContextSubmenuItem[]];
"autocomplete/complete": [AutocompleteInput, string[]];
"context/addDocs": [SiteIndexingConfig, void];
@ -142,6 +145,8 @@ export type ToCoreFromIdeOrWebviewProtocol = {
{ model: string; promptTokens: number; generatedTokens: number }[],
];
"tts/kill": [undefined, void];
// Codebase indexing
"index/setPaused": [boolean, void];
"index/forceReIndex": [
undefined | { dirs?: string[]; shouldClearIndexes?: boolean },
@ -155,6 +160,13 @@ export type ToCoreFromIdeOrWebviewProtocol = {
},
void,
];
// Docs etc. Indexing. TODO move codebase to this
"indexing/reindex": [{ type: string; id: string }, void];
"indexing/abort": [{ type: string; id: string }, void];
"indexing/setPaused": [{ type: string; id: string; paused: boolean }, void];
"indexing/initStatuses": [undefined, void];
addAutocompleteModel: [{ model: ModelDescription }, void];
"profiles/switch": [{ id: string }, undefined];

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",
@ -39,10 +40,17 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"chatDescriber/describe",
"stats/getTokensPerDay",
"stats/getTokensPerModel",
// Codebase
"index/setPaused",
"index/forceReIndex",
"index/forceReIndexFiles",
"index/indexingProgressBarInitialized",
// Docs, etc.
"indexing/initStatuses",
"indexing/reindex",
"indexing/abort",
"indexing/setPaused",
//
"completeOnboarding",
"addAutocompleteModel",
"config/listProfiles",
@ -55,7 +63,8 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] =
[
"configUpdate",
"getDefaultModelTitle",
"indexProgress",
"indexProgress", // Codebase
"indexing/statusUpdate", // Docs, etc.
"addContextItem",
"refreshSubmenuItems",
"isContinueInputFocused",

View file

@ -1,12 +1,17 @@
import { ConfigValidationError } from "../config/validation.js";
import type { ContextItemWithId, IndexingProgressUpdate } from "../index.js";
import type {
ContextItemWithId,
IndexingProgressUpdate,
IndexingStatus,
} from "../index.js";
export type ToWebviewFromIdeOrCoreProtocol = {
configUpdate: [undefined, void];
configError: [ConfigValidationError[] | undefined, void];
getDefaultModelTitle: [undefined, string];
indexProgress: [IndexingProgressUpdate, void];
indexProgress: [IndexingProgressUpdate, void]; // Codebase
"indexing/statusUpdate": [IndexingStatus, void]; // Docs, etc.
refreshSubmenuItems: [undefined, void];
isContinueInputFocused: [undefined, boolean];
addContextItem: [

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, SymbolWithRange } from "..";
export enum LanguageName {
CPP = "cpp",
@ -205,3 +206,93 @@ 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<SymbolWithRange[] | 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: 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}`);
// });
// Empirically, the actual name is the last identifier in the node
// Especially with languages where return type is declared before the name
// 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" ||
node.children[i].type === "property_identifier"
) {
identifier = node.children[i];
break;
}
}
if (identifier?.text) {
symbols.push({
filepath,
type: node.type,
name: identifier.text,
range: {
start: {
character: node.startPosition.column,
line: node.startPosition.row,
},
end: {
character: node.endPosition.column + 1,
line: node.endPosition.row + 1,
},
},
});
}
}
node.children.forEach(findNamedNodesRecursive);
}
findNamedNodesRecursive(tree.rootNode);
return symbols;
}
export async function getSymbolsForManyFiles(
uris: string[],
ide: IDE,
): Promise<FileSymbolMap> {
const filesAndSymbols = await Promise.all(
uris.map(async (uri): Promise<[string, SymbolWithRange[]]> => {
const contents = await ide.readFile(uri);
const symbols = await getSymbolsForFile(uri, contents);
return [uri, symbols ?? []];
}),
);
return Object.fromEntries(filesAndSymbols);
}

View file

@ -2356,7 +2356,7 @@
"type": "integer",
"description": "The maximum depth to crawl the documentation site"
},
"favicon": {
"faviconUrl": {
"type": "string",
"description": "The URL path to a favicon for the site - by default, it will be `/favicon.ico` path from the Start URL"
}

View file

@ -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("/");
}}
>

View file

@ -93,6 +93,7 @@ export default function StepContainer(props: StepContainerProps) {
<StyledMarkdownPreview
isRenderingInStepContainer
source={stripImages(props.item.message.content)}
itemIndex={props.index}
/>
)}
</ContentDiv>

View file

@ -1,11 +1,20 @@
import { ChevronDownIcon, ChevronUpIcon } from "@heroicons/react/24/outline";
import {
CheckCircleIcon,
ChevronDownIcon,
ChevronUpIcon,
} from "@heroicons/react/24/outline";
import { SiteIndexingConfig } from "core";
import { usePostHog } from "posthog-js/react";
import { useContext, useLayoutEffect, useRef, useState } from "react";
import { useDispatch } from "react-redux";
import { Button, HelperText, Input, lightGray } from "..";
import { useDispatch, useSelector } from "react-redux";
import { Button, HelperText, Input, lightGray, SecondaryButton } from "..";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { setShowDialog } from "../../redux/slices/uiStateSlice";
import {
setDialogMessage,
setShowDialog,
} from "../../redux/slices/uiStateSlice";
import { RootState } from "../../redux/store";
import IndexingStatusViewer from "../indexing/IndexingStatus";
function AddDocsDialog() {
const posthog = usePostHog();
@ -18,7 +27,12 @@ function AddDocsDialog() {
const [faviconUrl, setFaviconUrl] = useState("");
const [isOpen, setIsOpen] = useState(false);
const [submittedConfig, setSubmittedConfig] = useState<SiteIndexingConfig>();
const ideMessenger = useContext(IdeMessengerContext);
const indexingStatuses = useSelector(
(store: RootState) => store.state.indexing.statuses,
);
const isFormValid = startUrl && title;
@ -41,15 +55,66 @@ function AddDocsDialog() {
ideMessenger.post("context/addDocs", siteIndexingConfig);
setSubmittedConfig(siteIndexingConfig);
setTitle("");
setStartUrl("");
setFaviconUrl("");
dispatch(setShowDialog(false));
posthog.capture("add_docs_gui", { url: startUrl });
}
if (submittedConfig) {
const status = indexingStatuses[submittedConfig.startUrl];
return (
<div className="flex flex-col p-4">
<div className="flex flex-row items-center gap-2">
<CheckCircleIcon className="h-8 w-8" />
<h1>{`Docs added`}</h1>
</div>
<div className="flex flex-col gap-1 text-stone-500">
<p className="m-0 p-0">Title: {submittedConfig.title}</p>
<p className="m-0 p-0">Start URL: {submittedConfig.startUrl}</p>
{submittedConfig.rootUrl && (
<p className="m-0 p-0">Root URL: {submittedConfig.rootUrl}</p>
)}
{submittedConfig.maxDepth && (
<p className="m-0 p-0">Max depth: {submittedConfig.maxDepth}</p>
)}
{submittedConfig.faviconUrl && (
<p className="m-0 p-0">Favicon URL: {submittedConfig.faviconUrl}</p>
)}
</div>
{!!status && (
<div className="mt-4 flex flex-col divide-x-0 divide-y-2 divide-solid divide-zinc-700">
<p className="m-0 mb-5 p-0 leading-snug">{`Type "@docs" and select ${submittedConfig.title} to reference these docs once indexing is complete. Check indexing status from the "More" page.`}</p>
<div className="pt-1">
<IndexingStatusViewer status={status} />
</div>
</div>
)}
<div className="mt-4 flex flex-row items-center justify-end gap-4">
<SecondaryButton
className=""
onClick={() => {
setSubmittedConfig(undefined);
}}
>
Add another
</SecondaryButton>
<Button
className=""
onClick={() => {
dispatch(setDialogMessage(undefined));
dispatch(setShowDialog(false));
}}
>
Done
</Button>
</div>
</div>
);
}
return (
<div className="p-4">
<div className="mb-8">

View file

@ -34,7 +34,6 @@ const DialogContainer = styled.div`
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 75%;
`;
const Dialog = styled.div`
@ -72,6 +71,7 @@ const TextDialog = (props: TextDialogProps) => {
return (
<ScreenCover onClick={props.onClose} hidden={!props.showDialog}>
<DialogContainer
className="xs:w-[85%] w-[92%] sm:w-[75%]"
onClick={(e) => {
e.stopPropagation();
}}

View file

@ -154,7 +154,6 @@ export const Button = styled.button`
export const SecondaryButton = styled.button`
padding: 10px 12px;
margin: 8px 0;
height: 2.5rem;
border-radius: ${defaultBorderRadius};
border: 1px solid ${vscForeground};

View file

@ -0,0 +1,113 @@
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "../../redux/store";
import { IndexingStatus } from "core";
import { useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import { ArrowPathIcon, EyeSlashIcon } from "@heroicons/react/24/outline";
import { setIndexingChatPeekHidden } from "../../redux/slices/stateSlice";
interface MergedIndexingState {
displayName: string;
type: IndexingStatus["type"];
titles: IndexingStatus["title"][];
progressPercentage: number;
}
const mergeProgress = (states: IndexingStatus[]): number => {
const progress =
states.reduce((acc, state) => acc + state.progress, 0) / states.length;
return Math.min(100, Math.max(0, progress * 100));
};
export interface ChatIndexingPeekProps {
state: MergedIndexingState;
}
function ChatIndexingPeek({ state }: ChatIndexingPeekProps) {
const navigate = useNavigate();
const dispatch = useDispatch();
const hiddenPeeks = useSelector(
(store: RootState) => store.state.indexing.hiddenChatPeekTypes,
);
if (hiddenPeeks[state.type]) return null;
return (
<div
className="flex flex-row items-center border-0 border-t border-solid border-t-zinc-700 px-3 py-0.5"
onClick={() => {
navigate("/more");
}}
>
<div className="group flex flex-1 cursor-pointer flex-row items-center gap-2">
<div className={`flex flex-row items-center gap-2`}>
<p className="m-0 p-0 text-stone-500 group-hover:underline">
{state.displayName}
</p>
{/* <p className="no-underline lines lines-1 m-0 max-w-20 p-0 text-xs text-stone-500">
{state.titles.join(", ")}
</p> */}
</div>
<div className="my-2 h-1.5 flex-1 rounded-md border border-solid border-gray-400">
<div
className={`h-full rounded-lg bg-stone-500 transition-all duration-200 ease-in-out`}
style={{
width: `${state.progressPercentage}%`,
}}
/>
</div>
<div className="xs:flex hidden flex-row items-center gap-1 text-stone-500">
<span className="text-xs no-underline">
{state.progressPercentage.toFixed(0)}%
</span>
<ArrowPathIcon
className={`animate-spin-slow inline-block h-4 w-4 text-stone-500`}
></ArrowPathIcon>
</div>
</div>
<EyeSlashIcon
className="ml-2 h-4 w-4 cursor-pointer text-stone-500 hover:opacity-80"
onClick={(e) => {
dispatch(
setIndexingChatPeekHidden({ type: state.type, hidden: true }),
);
e.stopPropagation();
}}
/>
</div>
);
}
function ChatIndexingPeeks() {
const indexingStatuses = useSelector(
(store: RootState) => store.state.indexing.statuses,
);
const mergedIndexingStates: MergedIndexingState[] = useMemo(() => {
const mergedStates: MergedIndexingState[] = [];
const docsStates = Object.values(indexingStatuses).filter(
(status) => status.type === "docs" && status.status === "indexing",
);
if (docsStates.length > 0) {
mergedStates.push({
displayName: "Docs indexing",
type: "docs",
titles: docsStates.map((state) => state.title),
progressPercentage: mergeProgress(docsStates),
});
}
return mergedStates;
}, [indexingStatuses]);
if (!mergedIndexingStates.length) return null;
return (
<div className="flex flex-col gap-1">
{mergedIndexingStates.map((state) => {
return <ChatIndexingPeek state={state} />;
})}
</div>
);
}
export default ChatIndexingPeeks;

View file

@ -0,0 +1,147 @@
import { IndexingStatus } from "core";
import { PropsWithChildren, useContext, useMemo } from "react";
import { useDispatch } from "react-redux";
import { usePostHog } from "posthog-js/react";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import {
ArrowPathIcon,
ArrowRightStartOnRectangleIcon,
ArrowTopRightOnSquareIcon,
CheckCircleIcon,
PauseCircleIcon,
XMarkIcon,
} from "@heroicons/react/24/outline";
import { updateIndexingStatus } from "../../redux/slices/stateSlice";
interface IndexingStatusViewerProps {
status: IndexingStatus;
}
const STATUS_TO_ICON: Record<IndexingStatus["status"], any> = {
indexing: ArrowPathIcon,
paused: PauseCircleIcon,
complete: CheckCircleIcon,
aborted: null,
deleted: null,
pending: null,
failed: XMarkIcon, // Since we show an erorr message below
};
function IndexingStatusViewer({ status }: IndexingStatusViewerProps) {
const ideMessenger = useContext(IdeMessengerContext);
const posthog = usePostHog();
const dispatch = useDispatch();
const reIndex = () =>
ideMessenger.post("indexing/reindex", {
type: status.type,
id: status.id,
});
const abort = () => {
ideMessenger.post("indexing/abort", {
type: status.type,
id: status.id,
});
// Optimistic abort status
dispatch(
updateIndexingStatus({ ...status, status: "aborted", progress: 0 }),
);
};
const progressPercentage = useMemo(() => {
return Math.min(100, Math.max(0, status.progress * 100));
}, [status.progress]);
const Icon = STATUS_TO_ICON[status.status];
return (
<div className="mt-2 flex w-full flex-col">
{/* {`${status.type} - ${status.id} - ${status.status} - ${status.progress} - ${status.description} - ${status.icon}`} */}
<div
className={`flex flex-row items-center justify-between gap-2 text-sm`}
>
<div
className={`flex flex-row items-center gap-2 ${status.url ? "cursor-pointer hover:underline" : ""}`}
onClick={() => {
if (status.url) {
ideMessenger.post("openUrl", status.url);
}
}}
>
{status.icon ? (
<img src={status.icon} alt="doc icon" className="h-4 w-4" />
) : null}
<p className="lines lines-1 m-0 p-0 text-left">
{status.title ?? status.id}
</p>
{!!status.url && (
<ArrowTopRightOnSquareIcon className="mb-0.5 h-3 w-3 text-stone-500" />
)}
</div>
{status.status === "pending" ? (
<div className="text-xs text-stone-500">Pending...</div>
) : (
<div className="flex flex-row items-center gap-1 text-stone-500">
<span className="text-xs">{progressPercentage.toFixed(0)}%</span>
{Icon ? (
<Icon
className={`inline-block h-4 w-4 text-stone-500 ${
status.status === "indexing" ? "animate-spin-slow" : ""
}`}
></Icon>
) : null}
</div>
)}
</div>
<div className="my-2 h-1.5 w-full rounded-md border border-solid border-gray-400">
<div
className={`h-full rounded-lg transition-all duration-200 ease-in-out ${
status.status === "failed" ? "bg-red-600" : "bg-stone-500"
}`}
style={{
width: `${progressPercentage}%`,
}}
/>
</div>
<div className="flex flex-row items-center justify-between gap-4">
<span
className={`cursor-pointer whitespace-nowrap text-xs text-stone-500 underline`}
onClick={
{
complete: reIndex,
indexing: abort,
failed: reIndex,
aborted: reIndex,
paused: () => {},
deleted: () => {},
pending: () => {},
}[status.status]
}
>
{
{
complete: "Click to re-index",
indexing: "Cancel indexing",
failed: "Click to retry",
aborted: "Click to index",
paused: "",
deleted: "",
pending: "",
}[status.status]
}
</span>
{/* {status.status === "indexing" && ( */}
<span className="lines lines-1 text-right text-xs text-stone-500">
{status.description}
</span>
{/* )} */}
</div>
</div>
);
}
export default IndexingStatusViewer;

View file

@ -0,0 +1,56 @@
import { useMemo } from "react";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "../../redux/store";
import IndexingStatusViewer from "./IndexingStatus";
import { Button, SecondaryButton } from "..";
import {
setDialogMessage,
setShowDialog,
} from "../../redux/slices/uiStateSlice";
import AddDocsDialog from "../dialogs/AddDocsDialog";
function IndexingStatuses() {
const indexingStatuses = useSelector(
(store: RootState) => store.state.indexing.statuses,
);
const docsStatuses = useMemo(() => {
const docs = Object.values(indexingStatuses).filter(
(status) => status.type === "docs" && status.status !== "deleted",
);
return docs;
}, [indexingStatuses]);
const dispatch = useDispatch();
return (
<div className="flex flex-col gap-1">
<div className="flex flex-row items-center justify-between">
<h3 className="mb-1 mt-0 text-xl">@docs indexes</h3>
{/* <div className="border-1 rounded-full border">
<ChevronUpIcon className="h-8 w-8" />
</div> */}
{/* TODO add some way to hide, scroll, etc. */}
</div>
<span className="text-xs text-stone-500">
Manage your documentation sources
</span>
{/* <div className="flex max-h-[170px] flex-col gap-1 overflow-x-hidden overflow-y-scroll pr-2"> */}
{docsStatuses.length ? (
docsStatuses.map((status) => {
return <IndexingStatusViewer key={status.id} status={status} />;
})
) : (
<SecondaryButton
onClick={() => {
dispatch(setShowDialog(true));
dispatch(setDialogMessage(<AddDocsDialog />));
}}
>
Add Docs
</SecondaryButton>
)}
</div>
// </div>
);
}
export default IndexingStatuses;

View file

@ -0,0 +1,16 @@
import {
ArrowPathIcon,
CheckCircleIcon,
PauseCircleIcon,
} from "@heroicons/react/24/outline";
import { IndexingStatus } from "core";
export const STATUS_TO_ICON: Record<IndexingStatus["status"], any> = {
indexing: ArrowPathIcon,
paused: PauseCircleIcon,
complete: CheckCircleIcon,
aborted: null,
deleted: null,
pending: null,
failed: null, // XMarkIcon, // Since we show an error message below
};

View file

@ -2,8 +2,6 @@ import { NodeViewWrapper } from "@tiptap/react";
import { ContextItemWithId } from "core";
import { vscBadgeBackground } from "..";
import CodeSnippetPreview from "../markdown/CodeSnippetPreview";
import { useSelector } from "react-redux";
import { RootState } from "../../redux/store";
export const CodeBlockComponent = (props: any) => {
const { node, deleteNode, selected, editor, updateAttributes } = props;
@ -13,7 +11,7 @@ export const CodeBlockComponent = (props: any) => {
// store.state.history[store.state.history.length - 1].contextItems,
// );
// const isFirstContextItem = item.id === contextItems[0]?.id;
const isFirstContextItem = false;
const isFirstContextItem = false; // TODO: fix this, decided not worth the insane renders for now
return (
<NodeViewWrapper className="code-block-with-content" as="p">

View file

@ -9,10 +9,12 @@ import SafeImg from "../SafeImg";
import { INSTRUCTIONS_BASE_ITEM } from "core/context/providers/utils";
import { getIconFromDropdownItem } from "./MentionList";
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 {
@ -118,7 +120,7 @@ function ContextItemsPeekItem({ contextItem }: ContextItemsPeekItemProps) {
function ContextItemsPeek({
contextItems,
isGatheringContext,
isCurrentContextPeek,
}: ContextItemsPeekProps) {
const [open, setOpen] = useState(false);
@ -126,7 +128,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;
}
@ -151,7 +162,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 "..";
@ -69,12 +68,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);
useWebviewListener(
"newSessionWithPrompt",
@ -92,22 +85,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" : ""}`}>
<div className={`relative flex px-2`}>
@ -135,7 +112,7 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
</div>
<ContextItemsPeek
contextItems={props.contextItems}
isGatheringContext={isGatheringContext && props.isLastUserInput}
isCurrentContextPeek={props.isLastUserInput}
/>
</div>
);

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) {
@ -172,6 +185,15 @@ async function resolveEditorContent(
}
}
if (shouldGatherContext) {
dispatch(
setIsGatheringContext({
isGathering: false,
gatheringMessage: "Gathering context",
}),
);
}
return [contextItems, selectedCode, parts];
}

View file

@ -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]}
/>
</div>

View file

@ -20,15 +20,15 @@ function FilenameLink({ rif }: FilenameLinkProps) {
}
return (
<div
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"
<span
className="mx-[0.1em] mb-[0.15em] inline-flex cursor-pointer items-center gap-0.5 rounded-md pr-[0.2em] align-middle hover:ring-1"
onClick={onClick}
>
<FileIcon filename={rif.filepath} height="20px" width="20px" />
<span className="align-middle underline decoration-gray-600 underline-offset-2">
<span className="align-middle underline underline-offset-2">
{getBasename(rif.filepath)}
</span>
</div>
</span>
);
}

View file

@ -1,4 +1,4 @@
import { memo, useEffect } 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,10 @@ import StepContainerPreToolbar from "./StepContainerPreToolbar";
import { SyntaxHighlightedPre } from "./SyntaxHighlightedPre";
import StepContainerPreActionButtons from "./StepContainerPreActionButtons";
import { patchNestedMarkdown } from "./utils/patchNestedMarkdown";
import { ContextItemWithId } from "core";
import { RootState } from "../../redux/store";
import { ContextItemWithId, SymbolWithRange } from "core";
import SymbolLink from "./SymbolLink";
import { useSelector } from "react-redux";
const StyledMarkdown = styled.div<{
fontSize?: number;
@ -93,7 +96,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-";
@ -117,12 +120,10 @@ function getCodeChildrenContent(children: any) {
} else if (
Array.isArray(children) &&
children.length > 0 &&
typeof children[0] === "string" &&
children[0] !== ""
typeof children[0] === "string"
) {
return children[0];
}
return undefined;
}
@ -154,6 +155,28 @@ function processCodeBlocks(tree: any) {
const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
props: StyledMarkdownPreviewProps,
) {
const contextItems = useSelector(
(state: RootState) =>
state.state.history[props.itemIndex - 1]?.contextItems,
);
const symbols = useSelector((state: RootState) => state.state.symbols);
// The refs are a workaround because rehype options are stored on initiation
// So they won't use the most up-to-date state values
// So in this case we just put them in refs
const symbolsRef = useRef<SymbolWithRange[]>([]);
const contextItemsRef = useRef<ContextItemWithId[]>([]);
useEffect(() => {
contextItemsRef.current = contextItems || [];
}, [contextItems]);
useEffect(() => {
// Note, before I was only looking for symbols that matched
// Context item files on current history item
// 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],
rehypePlugins: [
@ -236,16 +259,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 && contextItemsRef.current) {
const ctxItem = contextItemsRef.current.find((ctxItem) =>
ctxItem.uri?.value.includes(content),
);
if (ctxItem) {
const rif = ctxItemToRifWithContents(ctxItem);
return <FilenameLink rif={rif} />;
}
}
const exactSymbol = symbolsRef.current.find(
(s) => s.name === content,
);
if (exactSymbol) {
return <SymbolLink content={content} symbol={exactSymbol} />;
}
// PARTIAL - this is the case where the llm returns e.g. `subtract(number)` instead of `subtract`
const partialSymbol = symbolsRef.current.find((s) =>
content.startsWith(s.name),
);
if (partialSymbol) {
return <SymbolLink content={content} symbol={partialSymbol} />;
}
}
return <code {...codeProps}>{codeProps.children}</code>;
},
},

View file

@ -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 (
<span
className="mx-[0.1em] mb-[0.15em] inline-flex cursor-pointer flex-row items-center gap-[0.2rem] rounded-md align-middle hover:ring-1"
onClick={onClick}
>
<code className="align-middle underline underline-offset-2">
{content}
</code>
</span>
);
}
export default SymbolLink;

View file

@ -38,6 +38,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();
@ -70,22 +71,18 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) {
}, [active]);
async function _streamNormalInput(messages: ChatMessage[]) {
<<<<<<< HEAD
const abortController = new AbortController();
const cancelToken = abortController.signal;
if (!defaultModel) {
throw new Error("Default model not defined");
}
const gen = ideMessenger.llmStreamChat(
defaultModel.title,
cancelToken,
streamAborter.signal,
messages,
);
let next = await gen.next();
while (!next.done) {
if (!activeRef.current) {
abortController.abort();
dispatch(abortStream());
break;
}
dispatch(streamUpdate(stripImages((next.value as ChatMessage).content)));
@ -95,37 +92,6 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) {
let returnVal = next.value as PromptLog;
if (returnVal) {
dispatch(addPromptCompletionPair([returnVal]));
=======
try {
if (!defaultModel) {
throw new Error("Default model not defined");
}
const gen = ideMessenger.llmStreamChat(
defaultModel.title,
streamAborter.signal,
messages,
);
let next = await gen.next();
while (!next.done) {
if (!activeRef.current) {
dispatch(abortStream());
break;
}
dispatch(
streamUpdate(stripImages((next.value as ChatMessage).content)),
);
next = await gen.next();
}
let returnVal = next.value as PromptLog;
if (returnVal) {
dispatch(addPromptCompletionPair([returnVal]));
}
} catch (e) {
// If there's an error, we should clear the response so there aren't two input boxes
dispatch(clearLastResponse());
>>>>>>> e60341647fcf9834844ad7ef4d5aa44fe1edf801
}
}
@ -230,7 +196,12 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) {
modifiers.useCodebase || hasSlashCommandOrContextProvider(editorState);
if (shouldGatherContext) {
dispatch(setIsGatheringContext(true));
dispatch(
setIsGatheringContext({
isGathering: true,
gatheringMessage: "Gathering Context",
}),
);
}
// Resolve context providers and construct new history
@ -240,10 +211,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";
@ -283,6 +253,12 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) {
}
}
await updateFileSymbolsFromContextItems(
selectedContextItems,
ideMessenger,
dispatch,
);
const message: ChatMessage = {
role: "user",
content,

View file

@ -6,7 +6,6 @@ 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 } from "../redux/slices/stateSlice";
import { RootState } from "../redux/store";
import { getLocalStorage, setLocalStorage } from "../util/localStorage";
@ -22,7 +21,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,6 +120,7 @@ function useHistory(dispatch: Dispatch) {
if (result.status === "error") {
throw new Error(result.error);
}
const sessionContent = result.content;
dispatch(newSession(sessionContent));
return sessionContent;

View file

@ -11,6 +11,7 @@ import {
setInactive,
setSelectedProfileId,
setTTSActive,
updateIndexingStatus,
} from "../redux/slices/stateSlice";
import { RootState } from "../redux/store";
@ -19,9 +20,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<any>) {
function useSetup(dispatch: Dispatch) {
const ideMessenger = useContext(IdeMessengerContext);
const history = useSelector((store: RootState) => store.state.history);
const initialConfigLoad = useRef(false);
const loadConfig = useCallback(async () => {
@ -50,14 +53,34 @@ function useSetup(dispatch: Dispatch<any>) {
loadConfig();
const interval = setInterval(() => {
if (initialConfigLoad.current) {
// This triggers sending pending status to the GUI for relevant docs indexes
clearInterval(interval);
ideMessenger.post("indexing/initStatuses", undefined);
return;
}
loadConfig();
}, 2_000);
return () => clearInterval(interval);
}, [initialConfigLoad, loadConfig]);
}, [initialConfigLoad, loadConfig, ideMessenger]);
useWebviewListener("configUpdate", async () => {
await loadConfig();
});
// Load symbols for chat on any session change
const sessionId = useSelector((store: RootState) => store.state.sessionId);
const sessionIdRef = useRef("");
useEffect(() => {
if (sessionIdRef.current !== sessionId) {
updateFileSymbolsFromContextItems(
history.flatMap((item) => item.contextItems),
ideMessenger,
dispatch,
);
}
sessionIdRef.current = sessionId;
}, [sessionId, history, ideMessenger, dispatch]);
useEffect(() => {
// Override persisted state
@ -86,7 +109,6 @@ function useSetup(dispatch: Dispatch<any>) {
);
// IDE event listeners
const history = useSelector((store: RootState) => store.state.history);
useWebviewListener(
"getWebviewHistoryLength",
async () => {
@ -110,18 +132,6 @@ function useSetup(dispatch: Dispatch<any>) {
});
});
const debouncedIndexDocs = debounce(() => {
ideMessenger.post("context/indexDocs", { reIndex: false });
}, 1000);
useWebviewListener("configUpdate", async () => {
await loadConfig();
if (!isJetBrains && !getLocalStorage("disableIndexing")) {
debouncedIndexDocs();
}
});
useWebviewListener("configError", async (error) => {
dispatch(setConfigError(error));
});
@ -144,6 +154,10 @@ function useSetup(dispatch: Dispatch<any>) {
);
});
useWebviewListener("indexing/statusUpdate", async (data) => {
dispatch(updateIndexingStatus(data));
});
useWebviewListener(
"getDefaultModelTitle",
async () => {

View file

@ -13,6 +13,7 @@ import { IdeMessengerContext } from "../context/IdeMessenger";
import { selectContextProviderDescriptions } from "../redux/selectors";
import { getLocalStorage } from "../util/localStorage";
import { useWebviewListener } from "./useWebviewListener";
import { RootState } from "../redux/store";
const MINISEARCH_OPTIONS = {
prefix: true,
@ -38,6 +39,8 @@ function useSubmenuContextProviders() {
const [isLoading, setIsLoading] = useState(false);
const [autoLoadTriggered, setAutoLoadTriggered] = useState(false);
const config = useSelector((store: RootState) => store.state.config);
const ideMessenger = useContext(IdeMessengerContext);
const memoizedGetOpenFileItems = useMemo(() => {
@ -213,12 +216,10 @@ function useSubmenuContextProviders() {
const loadSubmenuItems = async () => {
try {
const disableIndexing = getLocalStorage("disableIndexing") ?? false;
await Promise.all(
contextProviderDescriptions.map(async (description) => {
const shouldSkipProvider =
description.dependsOnIndexing && disableIndexing;
description.dependsOnIndexing && config.disableIndexing;
if (shouldSkipProvider) {
console.debug(

View file

@ -72,3 +72,22 @@ a:focus {
-ms-overflow-style: none; /* IE and Edge */
scrollbar-width: none; /* Firefox */
}
.lines {
/* white-space: pre-wrap; */
word-break: break-word;
overflow: hidden;
line-height: 1.375;
}
.lines-3 {
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
}
.lines-1 {
display: -webkit-box;
-webkit-line-clamp: 1;
-webkit-box-orient: vertical;
}

View file

@ -15,6 +15,7 @@ import { setOnboardingCard } from "../../redux/slices/uiStateSlice";
import useHistory from "../../hooks/useHistory";
import MoreHelpRow from "./MoreHelpRow";
import IndexingProgress from "./IndexingProgress";
import IndexingStatuses from "../../components/indexing/IndexingStatuses";
function MorePage() {
useNavigationListener();
@ -50,6 +51,9 @@ function MorePage() {
</div>
<IndexingProgress />
</div>
<div className="flex flex-col py-5">
<IndexingStatuses />
</div>
<div className="py-5">
<h3 className="mb-4 mt-0 text-xl">Help center</h3>

View file

@ -174,8 +174,11 @@ function Edit() {
},
ideMessenger,
[],
dispatch,
);
// Note, not currently updating file symbols in edit mode
const prompt = [
...contextItems.map((item) => item.content),
stripImages(userInstructions),

View file

@ -59,6 +59,7 @@ import {
} from "../../util";
import { FREE_TRIAL_LIMIT_REQUESTS } from "../../util/freeTrial";
import { getLocalStorage, setLocalStorage } from "../../util/localStorage";
import ChatIndexingPeeks from "../../components/indexing/ChatIndexingPeeks";
import { useFindWidget } from "../../components/find/FindWidget";
const StopButton = styled.div`
@ -317,7 +318,7 @@ export function Chat() {
{widget}
<StepsDiv
ref={stepsDivRef}
className={`overflow-y-scroll pt-[8px] ${showScrollbar ? "thin-scrollbar" : "no-scrollbar"} ${state.history.length > 0 ? "h-full" : ""}`}
className={`overflow-y-scroll pt-[8px] ${showScrollbar ? "thin-scrollbar" : "no-scrollbar"} ${state.history.length > 0 ? "flex-1" : ""}`}
onScroll={handleScroll}
>
{highlights}
@ -464,6 +465,11 @@ export function Chat() {
)}
</div>
</div>
<div
className={`${state.history.length === 0 ? "h-full" : ""} flex flex-col justify-end`}
>
<ChatIndexingPeeks />
</div>
</>
);
}

View file

@ -5,14 +5,16 @@ import {
ChatMessage,
Checkpoint,
ContextItemWithId,
FileSymbolMap,
IndexingStatus,
PersistedSessionInfo,
PromptLog,
} from "core";
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.
@ -21,9 +23,13 @@ type ChatHistoryItemWithMessageId = ChatHistoryItem & {
};
type State = {
history: ChatHistoryItemWithMessageId[];
symbols: FileSymbolMap;
context: {
isGathering: boolean;
gatheringMessage: string;
};
ttsActive: boolean;
active: boolean;
isGatheringContext: boolean;
config: BrowserSerializedContinueConfig;
title: string;
sessionId: string;
@ -35,15 +41,23 @@ type State = {
curCheckpointIndex: number;
applyStates: ApplyState[];
nextCodeBlockToApplyIndex: number;
indexing: {
hiddenChatPeekTypes: Record<IndexingStatus["type"], boolean>;
statuses: Record<string, IndexingStatus>;
};
streamAborter: AbortController;
isMultifileEdit: boolean;
};
const initialState: State = {
history: [],
symbols: {},
context: {
isGathering: false,
gatheringMessage: "Gathering Context",
},
ttsActive: false,
active: false,
isGatheringContext: false,
configError: undefined,
config: {
slashCommands: [
@ -68,6 +82,12 @@ const initialState: State = {
curCheckpointIndex: 0,
nextCodeBlockToApplyIndex: 0,
applyStates: [],
indexing: {
statuses: {},
hiddenChatPeekTypes: {
docs: false,
},
},
streamAborter: new AbortController(),
};
@ -112,8 +132,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;
},
clearLastEmptyResponse: (state) => {
if (state.history.length < 2) {
@ -129,6 +158,12 @@ export const stateSlice = createSlice({
consumeMainEditorContent: (state) => {
state.mainEditorContent = undefined;
},
updateFileSymbols: (state, action: PayloadAction<FileSymbolMap>) => {
state.symbols = {
...state.symbols,
...action.payload,
};
},
setContextItemsAtIndex: (
state,
{
@ -245,10 +280,13 @@ export const stateSlice = createSlice({
if (!historyItem) {
return;
}
historyItem.contextItems.push(...payload.contextItems);
historyItem.contextItems = [
...historyItem.contextItems,
...payload.contextItems,
];
},
setInactive: (state) => {
state.isGatheringContext = false;
state.context.isGathering = false;
state.active = false;
},
abortStream: (state) => {
@ -269,8 +307,9 @@ export const stateSlice = createSlice({
state.streamAborter = new AbortController();
state.active = false;
state.isGatheringContext = false;
state.context.isGathering = false;
state.isMultifileEdit = false;
state.symbols = {};
if (payload) {
state.history = payload.history as any;
state.title = payload.title;
@ -372,10 +411,47 @@ export const stateSlice = createSlice({
resetNextCodeBlockToApplyIndex: (state) => {
state.nextCodeBlockToApplyIndex = 0;
},
updateIndexingStatus: (
state,
{ payload }: PayloadAction<IndexingStatus>,
) => {
state.indexing.statuses = {
...state.indexing.statuses,
[payload.id]: payload,
};
// This check is so that if all indexing is stopped for e.g. docs
// The next time docs indexing starts the peek will show again
const indexingThisType = Object.values(state.indexing.statuses).filter(
(status) =>
status.type === payload.type && status.status === "indexing",
);
if (indexingThisType.length === 0) {
state.indexing.hiddenChatPeekTypes = {
...state.indexing.hiddenChatPeekTypes,
[payload.type]: false,
};
}
},
setIndexingChatPeekHidden: (
state,
{
payload,
}: PayloadAction<{
type: IndexingStatus["type"];
hidden: boolean;
}>,
) => {
state.indexing.hiddenChatPeekTypes = {
...state.indexing.hiddenChatPeekTypes,
[payload.type]: payload.hidden,
};
},
},
});
export const {
updateFileSymbols,
setContextItemsAtIndex,
addContextItemsAtIndex,
setInactive,
@ -401,6 +477,8 @@ export const {
setCurCheckpointIndex,
resetNextCodeBlockToApplyIndex,
updateApplyState,
updateIndexingStatus,
setIndexingChatPeekHidden,
abortStream,
} = stateSlice.actions;

35
gui/src/util/symbols.ts Normal file
View file

@ -0,0 +1,35 @@
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) {
// Catch all - don't want file symbols to break the chat experience for now
console.error("Error updating file symbols from context items", e);
}
}