Skip to content

Forbid file mentioning for large files #4790

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions core/core.ts
Original file line number Diff line number Diff line change
@@ -22,6 +22,7 @@ import { DataLogger } from "./data/log";
import { streamDiffLines } from "./edit/streamDiffLines";
import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer";
import DocsService from "./indexing/docs/DocsService";
import { countTokens } from "./llm/countTokens";
import Ollama from "./llm/llms/Ollama";
import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile";
import { callTool } from "./tools/callTool";
@@ -888,6 +889,26 @@ export class Core {

return { contextItems };
});

on("isItemTooBig", async ({ data: { item, selectedModelTitle } }) => {
const { config } = await this.configHandler.loadConfig();

if (!config) {
return false;
}

const llm = await this.configHandler.llmFromTitle(selectedModelTitle);

// Count the size of the file tokenwise
const tokens = countTokens(item.content);

// File exceeds context length of the model
if (tokens > llm.contextLength - llm.completionOptions!.maxTokens!) {
return true;
}

return false;
});
}

private indexingCancellationController: AbortController | undefined;
4 changes: 4 additions & 0 deletions core/protocol/core.ts
Original file line number Diff line number Diff line change
@@ -196,4 +196,8 @@ export type ToCoreFromIdeOrWebviewProtocol = {
];
"clipboardCache/add": [{ content: string }, void];
"controlPlane/openUrl": [{ path: string; orgSlug: string | undefined }, void];
isItemTooBig: [
{ item: ContextItemWithId; selectedModelTitle: string | undefined },
boolean,
];
};
1 change: 1 addition & 0 deletions core/protocol/passThrough.ts
Original file line number Diff line number Diff line change
@@ -59,6 +59,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"didChangeSelectedOrg",
"tools/call",
"controlPlane/openUrl",
"isItemTooBig",
];

// Message types to pass through from core to webview
Original file line number Diff line number Diff line change
@@ -126,6 +126,7 @@ class MessageTypes {
"didChangeSelectedOrg",
"tools/call",
"controlPlane/openUrl",
"isItemTooBig",
)
}
}
112 changes: 111 additions & 1 deletion gui/src/components/mainInput/AtMentionDropdown/index.tsx
Original file line number Diff line number Diff line change
@@ -5,6 +5,7 @@ import {
PlusIcon,
} from "@heroicons/react/24/outline";
import { Editor } from "@tiptap/react";
import { RangeInFile } from "core";
import {
forwardRef,
useContext,
@@ -24,6 +25,7 @@ import {
vscQuickInputBackground,
} from "../..";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
import { useAppSelector } from "../../../redux/hooks";
import { setDialogMessage, setShowDialog } from "../../../redux/slices/uiSlice";
import { fontSize } from "../../../util";
import FileIcon from "../../FileIcon";
@@ -138,11 +140,31 @@ interface AtMentionDropdownProps {
onClose: () => void;
}

const formatFileSize = (fileSize: number) => {
const KB = 1000;
const MB = 1000_000;
const GB = 1000_000_000;

if (fileSize > GB) {
return `${(fileSize / GB).toFixed(1)} GB`;
} else if (fileSize > MB) {
return `${(fileSize / MB).toFixed(1)} MB`;
} else if (fileSize > KB) {
return `${(fileSize / KB).toFixed(1)} KB`;
}

return `${fileSize} byte${fileSize > 1 ? "s" : ""}`;
};

const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => {
const dispatch = useDispatch();

const ideMessenger = useContext(IdeMessengerContext);

const selectedModelTitle = useAppSelector(
(store) => store.config.defaultModelTitle,
);

const [selectedIndex, setSelectedIndex] = useState(0);

const [subMenuTitle, setSubMenuTitle] = useState<string | undefined>(
@@ -157,6 +179,88 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => {

const [allItems, setAllItems] = useState<ComboBoxItem[]>([]);

async function isItemTooBig(
name: string,
query: string,
): Promise<[boolean, number]> {
const selectedCode: RangeInFile[] = [];
// Get context item from core
const contextResult = await ideMessenger.request(
"context/getContextItems",
{
name,
query,
fullInput: "",
selectedCode,
selectedModelTitle: selectedModelTitle ?? "",
},
);

if (contextResult.status === "error") {
return [false, -1];
}

const item = contextResult.content[0];

// Check if the context item exceeds the context length of the selected model
const result = await ideMessenger.request("isItemTooBig", {
item,
selectedModelTitle: selectedModelTitle,
});

if (result.status === "error") {
return [false, -1];
}

const size = new Blob([item.content]).size;

return [result.content, size];
}

function handleItemTooBig(
fileExceeds: boolean,
fileSize: number,
item: ComboBoxItem,
) {
if (fileExceeds) {
props.editor
.chain()
.focus()
.command(({ tr, state }) => {
const text = state.doc.textBetween(
0,
state.selection.from,
"\n",
"\n",
); // Get the text before the cursor
const lastAtIndex = text.lastIndexOf("@");

if (lastAtIndex !== -1) {
// Delete text after the last "@"
tr.delete(lastAtIndex + 1, state.selection.from);
return true;
}
return false;
})
.run();

// Trigger warning message
ideMessenger.ide.showToast(
"warning",
fileSize > 0 ? "File exceeds context length" : "Can't load the file",
{
modal: true,
detail:
fileSize > 0
? `'${item.title}' is ${formatFileSize(fileSize)} which exceeds the allowed context length and connot be processed by the model`
: `'${item.title}' could not be loaded. Please check if the file exists and has the correct permissions.`,
},
);
} else {
props.command({ ...item, itemType: item.type });
}
}

useEffect(() => {
const items = [...props.items];
if (subMenuTitle === "Type to search docs") {
@@ -243,7 +347,13 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => {
}

if (item) {
props.command({ ...item, itemType: item.type });
if (item.type === "file" && item.query) {
isItemTooBig(item.type, item.query).then(([fileExceeds, fileSize]) =>
handleItemTooBig(fileExceeds, fileSize, item),
);
} else {
props.command({ ...item, itemType: item.type });
}
}
};


Unchanged files with check annotations Beta

stopStatusBarLoading,
} from "./statusBar";
import type { IDE } from "core";

Check warning on line 26 in extensions/vscode/src/autocomplete/completionProvider.ts

GitHub Actions / vscode-checks

There should be at least one empty line between import groups
import { handleLLMError } from "../util/errorHandling";

Check warning on line 27 in extensions/vscode/src/autocomplete/completionProvider.ts

GitHub Actions / vscode-checks

`../util/errorHandling` import should occur before import of `../util/messages`
interface VsCodeCompletionInput {
document: vscode.TextDocument;
import * as vscode from "vscode";
import type { IDE, Range, RangeInFile, RangeInFileWithContents } from "core";
import type Parser from "web-tree-sitter";

Check warning on line 11 in extensions/vscode/src/autocomplete/lsp.ts

GitHub Actions / vscode-checks

There should be at least one empty line between import groups
import { GetLspDefinitionsFunction } from "core/autocomplete/types";

Check warning on line 12 in extensions/vscode/src/autocomplete/lsp.ts

GitHub Actions / vscode-checks

`core/autocomplete/types` import should occur before import of `core/autocomplete/util/ast`
import {

Check warning on line 13 in extensions/vscode/src/autocomplete/lsp.ts

GitHub Actions / vscode-checks

`core/autocomplete/snippets/types` import should occur before import of `core/autocomplete/util/ast`
AutocompleteCodeSnippet,
AutocompleteSnippetType,
} from "core/autocomplete/snippets/types";
import * as URI from "uri-js";

Check warning on line 17 in extensions/vscode/src/autocomplete/lsp.ts

GitHub Actions / vscode-checks

`uri-js` import should occur before import of `vscode`
type GotoProviderName =
| "vscode.executeDefinitionProvider"
setupStatusBar,
StatusBarStatus,
} from "./autocomplete/statusBar";
import { ContinueGUIWebviewViewProvider } from "./ContinueGUIWebviewViewProvider";

Check warning on line 30 in extensions/vscode/src/commands.ts

GitHub Actions / vscode-checks

There should be no empty line within import group
import { VerticalDiffManager } from "./diff/vertical/manager";
import EditDecorationManager from "./quickEdit/EditDecorationManager";
import { getMetaKeyLabel } from "./util/util";
import { VsCodeIde } from "./VsCodeIde";
import { LOCAL_DEV_DATA_VERSION } from "core/data/log";

Check warning on line 39 in extensions/vscode/src/commands.ts

GitHub Actions / vscode-checks

`core/data/log` import should occur before import of `core/indexing/walkDir`
import { isModelInstaller } from "core/llm";

Check warning on line 40 in extensions/vscode/src/commands.ts

GitHub Actions / vscode-checks

`core/llm` import should occur before import of `core/util/paths`
import { startLocalOllama } from "core/util/ollamaHelper";

Check warning on line 41 in extensions/vscode/src/commands.ts

GitHub Actions / vscode-checks

There should be at least one empty line between import groups
import type { VsCodeWebviewProtocol } from "./webviewProtocol";
let fullScreenPanel: vscode.WebviewPanel | undefined;