From f312596f6b1700be3919b2a240fdede8a72c84c8 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 16 Jul 2025 20:30:07 +0200 Subject: [PATCH 01/10] updates to extra pruning step --- core/index.d.ts | 1 + core/llm/countTokens.ts | 7 ++++++- core/llm/index.ts | 2 +- gui/src/components/StepContainer/StepContainer.tsx | 3 --- gui/src/context/MockIdeMessenger.ts | 1 + 5 files changed, 9 insertions(+), 5 deletions(-) diff --git a/core/index.d.ts b/core/index.d.ts index 92ad04dfb..6e128e920 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1694,6 +1694,7 @@ export type PruningStatus = "deleted-last-input" | "pruned" | "not-pruned"; export interface CompiledMessagesResult { compiledChatMessages: ChatMessage[]; pruningStatus: PruningStatus; + contextPercentage: number; } export interface MessageOption { diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index add0b983b..97bd336d5 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -538,7 +538,12 @@ function compileChatMessages({ } reassembled.push(...historyWithTokens.map(({ tokens, ...rest }) => rest)); - return { compiledChatMessages: reassembled, pruningStatus }; + const contextPercentage = currentTotal / contextLength; + return { + compiledChatMessages: reassembled, + pruningStatus, + contextPercentage, + }; } export { diff --git a/core/llm/index.ts b/core/llm/index.ts index 9a727d1a4..d32331c12 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -923,7 +923,7 @@ export abstract class BaseLLM implements ILLM { let messages = _messages; // If not precompiled, compile the chat messages - if (!messageOptions || messageOptions.precompiled === false) { + if (!messageOptions?.precompiled) { const { compiledChatMessages } = compileChatMessages({ modelName: completionOptions.model, msgs: _messages, diff --git a/gui/src/components/StepContainer/StepContainer.tsx b/gui/src/components/StepContainer/StepContainer.tsx index 9522c3717..e235ae2a2 100644 --- a/gui/src/components/StepContainer/StepContainer.tsx +++ b/gui/src/components/StepContainer/StepContainer.tsx @@ -23,9 +23,6 @@ export default function StepContainer(props: StepContainerProps) { const historyItemAfterThis = useAppSelector( (state) => state.session.history[props.index + 1], ); - const warningMessage = useAppSelector( - (state) => state.session.warningMessage, - ); const uiConfig = useAppSelector(selectUIConfig); const isNextMsgAssistantOrThinking = diff --git a/gui/src/context/MockIdeMessenger.ts b/gui/src/context/MockIdeMessenger.ts index e6f144b6d..55bc4cab6 100644 --- a/gui/src/context/MockIdeMessenger.ts +++ b/gui/src/context/MockIdeMessenger.ts @@ -87,6 +87,7 @@ const DEFAULT_MOCK_CORE_RESPONSES: MockResponses = { "llm/compileChat": { compiledChatMessages: [], pruningStatus: "not-pruned", + contextPercentage: 0.5, }, }; From 9431872c7ccb09468e28c0b33f91938e5f178a24 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 17 Jul 2025 00:35:13 +0200 Subject: [PATCH 02/10] didPrune instead of pruning status --- core/index.d.ts | 4 +- core/llm/countTokens.ts | 48 ++++++++++------------- gui/src/context/MockIdeMessenger.ts | 2 +- gui/src/pages/gui/Chat.tsx | 3 -- gui/src/redux/thunks/streamNormalInput.ts | 32 +++++++-------- 5 files changed, 38 insertions(+), 51 deletions(-) diff --git a/core/index.d.ts b/core/index.d.ts index 6e128e920..e1516a970 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1689,11 +1689,9 @@ export interface CompleteOnboardingPayload { apiKey?: string; } -export type PruningStatus = "deleted-last-input" | "pruned" | "not-pruned"; - export interface CompiledMessagesResult { compiledChatMessages: ChatMessage[]; - pruningStatus: PruningStatus; + didPrune: boolean; contextPercentage: number; } diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 97bd336d5..e83a6acd9 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -5,7 +5,6 @@ import { CompiledMessagesResult, MessageContent, MessagePart, - PruningStatus, Tool, } from "../index.js"; import { autodetectTemplateType } from "./autodetect.js"; @@ -363,9 +362,6 @@ function getTokenCountingBufferSafety(contextLength: number) { } const MIN_RESPONSE_TOKENS = 1000; -function getMinResponseTokens(maxTokens: number) { - return Math.min(MIN_RESPONSE_TOKENS, maxTokens); -} function pruneRawPromptFromTop( modelName: string, @@ -425,6 +421,8 @@ function compileChatMessages({ supportsImages: boolean; tools?: Tool[]; }): CompiledMessagesResult { + let didPrune = false; + let msgsCopy: ChatMessage[] = msgs.map((m) => ({ ...m })); // If images not supported, convert MessagePart[] to string @@ -453,14 +451,14 @@ function compileChatMessages({ msgsCopy.pop(); } - // // Extract the tool sequence from the end of the message array - // const toolSequence = extractToolSequence(msgsCopy); + // Extract the tool sequence from the end of the message array + const toolSequence = extractToolSequence(msgsCopy); - // // Count tokens for all messages in the tool sequence - // let lastMessagesTokens = 0; - // for (const msg of toolSequence) { - // lastMessagesTokens += countChatMessageTokens(modelName, msg); - // } + // Count tokens for all messages in the tool sequence + let lastMessagesTokens = 0; + for (const msg of toolSequence) { + lastMessagesTokens += countChatMessageTokens(modelName, msg); + } // System message let systemMsgTokens = 0; @@ -475,7 +473,7 @@ function compileChatMessages({ } const countingSafetyBuffer = getTokenCountingBufferSafety(contextLength); - const minOutputTokens = getMinResponseTokens(maxTokens); + const minOutputTokens = Math.min(MIN_RESPONSE_TOKENS, maxTokens); let inputTokensAvailable = contextLength; @@ -486,19 +484,19 @@ function compileChatMessages({ // Non-negotiable messages inputTokensAvailable -= toolTokens; inputTokensAvailable -= systemMsgTokens; - // inputTokensAvailable -= lastMessagesTokens; + inputTokensAvailable -= lastMessagesTokens; // Make sure there's enough context for the non-excludable items if (inputTokensAvailable < 0) { throw new Error( `Not enough context available to include the system message, last user message, and tools. - There must be at least ${minOutputTokens} tokens remaining for output. - Request had the following token counts: - - contextLength: ${contextLength} - - counting safety buffer: ${countingSafetyBuffer} - - tools: ~${toolTokens} - - system message: ~${systemMsgTokens} - - max output tokens: ${maxTokens}`, + There must be at least ${minOutputTokens} tokens remaining for output. + Request had the following token counts: + - contextLength: ${contextLength} + - counting safety buffer: ${countingSafetyBuffer} + - tools: ~${toolTokens} + - system message: ~${systemMsgTokens} + - max output tokens: ${maxTokens}`, ); } @@ -513,12 +511,10 @@ function compileChatMessages({ }; }); - let pruningStatus: PruningStatus = "not-pruned"; - while (historyWithTokens.length > 0 && currentTotal > inputTokensAvailable) { const message = historyWithTokens.shift()!; currentTotal -= message.tokens; - pruningStatus = "pruned"; + didPrune = true; // At this point make sure no latent tool response without corresponding call while (historyWithTokens[0]?.role === "tool") { @@ -527,10 +523,6 @@ function compileChatMessages({ } } - if (historyWithTokens.length === 0) { - pruningStatus = "deleted-last-input"; - } - // Now reassemble const reassembled: ChatMessage[] = []; if (systemMsg) { @@ -541,7 +533,7 @@ function compileChatMessages({ const contextPercentage = currentTotal / contextLength; return { compiledChatMessages: reassembled, - pruningStatus, + didPrune, contextPercentage, }; } diff --git a/gui/src/context/MockIdeMessenger.ts b/gui/src/context/MockIdeMessenger.ts index 55bc4cab6..1cd305539 100644 --- a/gui/src/context/MockIdeMessenger.ts +++ b/gui/src/context/MockIdeMessenger.ts @@ -86,7 +86,7 @@ const DEFAULT_MOCK_CORE_RESPONSES: MockResponses = { }, "llm/compileChat": { compiledChatMessages: [], - pruningStatus: "not-pruned", + didPrune: false, contextPercentage: 0.5, }, }; diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 7f2fea420..383f18241 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -113,9 +113,6 @@ export function Chat() { const jetbrains = useMemo(() => { return isJetBrains(); }, []); - const warningMessage = useAppSelector( - (state) => state.session.warningMessage, - ); useAutoScroll(stepsDivRef, history); diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index 3f56f4bbd..0e1b99a34 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -192,22 +192,7 @@ export const streamNormalInput = createAsyncThunk< }); if (precompiledRes.status === "error") { - throw new Error(precompiledRes.error); - } - - const { compiledChatMessages, pruningStatus } = precompiledRes.content; - - switch (pruningStatus) { - case "pruned": - dispatch( - setWarningMessage({ - message: `Chat history exceeds model's context length (${state.config.config.selectedModelByRole.chat?.contextLength} tokens). Old messages will not be included.`, - level: "warning", - category: "exceeded-context-length", - }), - ); - break; - case "deleted-last-input": + if (precompiledRes.error.includes("Not enough context ")) { dispatch( setWarningMessage({ message: @@ -218,6 +203,21 @@ export const streamNormalInput = createAsyncThunk< ); dispatch(setInactive()); return; + } else { + throw new Error(precompiledRes.error); + } + } + + const { compiledChatMessages, didPrune } = precompiledRes.content; + + if (didPrune) { + dispatch( + setWarningMessage({ + message: `Chat history exceeds model's context length (${state.config.config.selectedModelByRole.chat?.contextLength} tokens). Old messages will not be included.`, + level: "warning", + category: "exceeded-context-length", + }), + ); } // Send request and stream response From 7e6c974e4d2cd1fced3f32dc755f97eb2c6814b3 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 17 Jul 2025 03:12:50 +0200 Subject: [PATCH 03/10] context filled text, pruning warning --- core/index.d.ts | 10 ---- core/llm/countTokens.ts | 1 + .../components/mainInput/ContextStatus.tsx | 54 ++++++++++++++++++ .../components/mainInput/ContinueInputBox.tsx | 21 +------ .../mainInput/InlineErrorMessage.tsx | 48 ++++++++++++++++ .../Actions/EditConfigAction.tsx | 15 ----- .../Actions/NewSessionAction.tsx | 10 ---- .../WarningMessageBox/ExpendableBox.tsx | 41 -------------- .../mainInput/WarningMessageBox/index.tsx | 55 ------------------- gui/src/pages/gui/Chat.tsx | 32 ++++++----- gui/src/redux/slices/sessionSlice.ts | 34 +++++++++--- gui/src/redux/thunks/streamNormalInput.ts | 33 ++++------- 12 files changed, 160 insertions(+), 194 deletions(-) create mode 100644 gui/src/components/mainInput/ContextStatus.tsx create mode 100644 gui/src/components/mainInput/InlineErrorMessage.tsx delete mode 100644 gui/src/components/mainInput/WarningMessageBox/Actions/EditConfigAction.tsx delete mode 100644 gui/src/components/mainInput/WarningMessageBox/Actions/NewSessionAction.tsx delete mode 100644 gui/src/components/mainInput/WarningMessageBox/ExpendableBox.tsx delete mode 100644 gui/src/components/mainInput/WarningMessageBox/index.tsx diff --git a/core/index.d.ts b/core/index.d.ts index e1516a970..589b96ac0 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1698,13 +1698,3 @@ export interface CompiledMessagesResult { export interface MessageOption { precompiled: boolean; } - -export type WarningMessageLevel = "warning" | "fatal"; - -export type WarningCategory = "exceeded-context-length" | "deleted-last-input"; - -export interface WarningMessage { - message: string; - level: WarningMessageLevel; - category: WarningCategory; -} diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index e83a6acd9..65a7cca1f 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -529,6 +529,7 @@ function compileChatMessages({ reassembled.push(systemMsg); } reassembled.push(...historyWithTokens.map(({ tokens, ...rest }) => rest)); + reassembled.push(...toolSequence); const contextPercentage = currentTotal / contextLength; return { diff --git a/gui/src/components/mainInput/ContextStatus.tsx b/gui/src/components/mainInput/ContextStatus.tsx new file mode 100644 index 000000000..8366acc99 --- /dev/null +++ b/gui/src/components/mainInput/ContextStatus.tsx @@ -0,0 +1,54 @@ +import { useAppDispatch, useAppSelector } from "../../redux/hooks"; +import { saveCurrentSession } from "../../redux/thunks/session"; +import { ToolTip } from "../gui/Tooltip"; + +const ContextStatus = () => { + const dispatch = useAppDispatch(); + const contextPercentage = useAppSelector( + (state) => state.session.contextPercentage, + ); + const percent = Math.round((contextPercentage ?? 0) * 100); + const isPruned = useAppSelector((state) => state.session.isPruned); + if (!isPruned && percent < 0.6) { + return null; + } + return ( +
+ { + dispatch( + saveCurrentSession({ + openNewSession: true, + generateTitle: false, + }), + ); + }} + > + New Session + + {contextPercentage !== undefined && ( + <> + {percent}% + + {`${percent}% of context is filled`} + + + )} + + {isPruned && ( + <> +
+ + Chat history exceeds context limit, old messages are being removed + + + )} +
+ ); +}; + +export default ContextStatus; diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index d95a0a118..7234fa03c 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -7,12 +7,10 @@ import { selectSlashCommandComboBoxInputs } from "../../redux/selectors"; import { ContextItemsPeek } from "./belowMainInput/ContextItemsPeek"; import { RulesPeek } from "./belowMainInput/RulesPeek"; import { GradientBorder } from "./GradientBorder"; +import InlineErrorMessage from "./InlineErrorMessage"; import { ToolbarOptions } from "./InputToolbar"; import { Lump } from "./Lump"; import { TipTapEditor } from "./TipTapEditor"; -import WarningMessageBox from "./WarningMessageBox"; -import EditConfigAction from "./WarningMessageBox/Actions/EditConfigAction"; -import NewSessionAction from "./WarningMessageBox/Actions/NewSessionAction"; interface ContinueInputBoxProps { isLastUserInput: boolean; @@ -43,9 +41,6 @@ const EDIT_DISALLOWED_CONTEXT_PROVIDERS = [ function ContinueInputBox(props: ContinueInputBoxProps) { const isStreaming = useAppSelector((state) => state.session.isStreaming); - const warningMessage = useAppSelector( - (state) => state.session.warningMessage, - ); const availableSlashCommands = useAppSelector( selectSlashCommandComboBoxInputs, ); @@ -125,19 +120,7 @@ function ContinueInputBox(props: ContinueInputBoxProps) { /> )} - {props.isLastUserInput && - warningMessage && - (warningMessage.category === "exceeded-context-length" ? ( - - ) : ( - - ))} + {props.isLastUserInput && } ); } diff --git a/gui/src/components/mainInput/InlineErrorMessage.tsx b/gui/src/components/mainInput/InlineErrorMessage.tsx new file mode 100644 index 000000000..631b939c1 --- /dev/null +++ b/gui/src/components/mainInput/InlineErrorMessage.tsx @@ -0,0 +1,48 @@ +import { useContext } from "react"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { useAppSelector } from "../../redux/hooks"; + +export type InlineErrorMessageType = "out-of-context"; + +export default function InlineErrorMessage() { + const ideMessenger = useContext(IdeMessengerContext); + const inlineErrorMessage = useAppSelector( + (state) => state.session.inlineErrorMessage, + ); + if (inlineErrorMessage === "out-of-context") { + return ( +
+

+ {`Message exceeds context limit.`} +

+
+
{ + ideMessenger.post("config/openProfile", { + profileId: undefined, + }); + }} + > + Open config + Config +
+ | + { + ideMessenger.post("config/openProfile", { + profileId: undefined, + }); + }} + > + Hide + +
+
+ ); + } + return null; +} diff --git a/gui/src/components/mainInput/WarningMessageBox/Actions/EditConfigAction.tsx b/gui/src/components/mainInput/WarningMessageBox/Actions/EditConfigAction.tsx deleted file mode 100644 index 6ff98bf61..000000000 --- a/gui/src/components/mainInput/WarningMessageBox/Actions/EditConfigAction.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import { useContext } from "react"; -import { IdeMessengerContext } from "../../../../context/IdeMessenger"; -export default function EditConfigAction() { - const ideMessenger = useContext(IdeMessengerContext); - return ( - - ideMessenger.post("config/openProfile", { profileId: undefined }) - } - className="hover:underline" - > - Open configuration file - - ); -} diff --git a/gui/src/components/mainInput/WarningMessageBox/Actions/NewSessionAction.tsx b/gui/src/components/mainInput/WarningMessageBox/Actions/NewSessionAction.tsx deleted file mode 100644 index 2f397e7a2..000000000 --- a/gui/src/components/mainInput/WarningMessageBox/Actions/NewSessionAction.tsx +++ /dev/null @@ -1,10 +0,0 @@ -import { useAppDispatch } from "../../../../redux/hooks"; -import { newSession } from "../../../../redux/slices/sessionSlice"; -export default function NewSessionAction() { - const dispatch = useAppDispatch(); - return ( - dispatch(newSession())} className="hover:underline"> - Start a new session - - ); -} diff --git a/gui/src/components/mainInput/WarningMessageBox/ExpendableBox.tsx b/gui/src/components/mainInput/WarningMessageBox/ExpendableBox.tsx deleted file mode 100644 index dbcbf21a9..000000000 --- a/gui/src/components/mainInput/WarningMessageBox/ExpendableBox.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import { ReactNode, useEffect, useRef, useState } from "react"; -export default function ExpendableBox({ children }: { children: ReactNode }) { - const [isExpended, setIsExpended] = useState(false); - const [showTrigger, setShowTrigger] = useState(true); - const expendableDivRef = useRef(null); - const toggleExpendable = () => { - setIsExpended((pre) => !pre); - }; - - useEffect(() => { - if (expendableDivRef.current) { - expendableDivRef.current.style.maxHeight = isExpended ? "600px" : "0px"; - } - - if (isExpended) { - setShowTrigger(false); - } else { - setTimeout(() => setShowTrigger(true), 200); - } - }, [isExpended]); - - return ( -
-
- -
- {children} -
-
- ); -} diff --git a/gui/src/components/mainInput/WarningMessageBox/index.tsx b/gui/src/components/mainInput/WarningMessageBox/index.tsx deleted file mode 100644 index 2b14a3457..000000000 --- a/gui/src/components/mainInput/WarningMessageBox/index.tsx +++ /dev/null @@ -1,55 +0,0 @@ -import { WarningMessage } from "core"; -import { ReactElement } from "react"; -import ExpendableBox from "./ExpendableBox"; - -function MessageBox({ - warningMessage, - actions, -}: { - warningMessage: WarningMessage; - actions?: (() => ReactElement)[]; -}) { - const warningMessageTextColor = - warningMessage.level === "fatal" ? "text-error" : "text-warning"; - const warningMessageBorderColor = - warningMessage.level === "fatal" ? "border-error" : "border-warning"; - return ( -
-

- Warning: - {`${warningMessage.message}`} -

- {actions && ( -
-

{`Recommended Action${actions.length > 1 ? "s" : ""}:`}

-
    - {actions.map((action, ind) => { - return
  • {action()}
  • ; - })} -
-
- )} -
- ); -} - -export default function WarningMessageBox({ - warningMessage, - actions, -}: { - warningMessage: WarningMessage; - actions?: (() => ReactElement)[]; -}) { - if (warningMessage.category === "exceeded-context-length") { - return ( - - } - /> - ); - } - return ; -} diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 383f18241..46377e094 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -43,6 +43,7 @@ import { streamResponseThunk } from "../../redux/thunks/streamResponse"; import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util"; import { ToolCallDiv } from "./ToolCallDiv"; +import ContextStatus from "../../components/mainInput/ContextStatus"; import { cancelStream } from "../../redux/thunks/cancelStream"; import { EmptyChatBody } from "./EmptyChatBody"; import { ExploreDialogWatcher } from "./ExploreDialogWatcher"; @@ -409,23 +410,24 @@ export function Chat() {
{history.length === 0 && lastSessionId && !isInEdit && ( -
- { - await dispatch( - loadLastSession({ - saveCurrentSession: true, - }), - ); - }} - className="flex items-center gap-2" - > - - Last Session - -
+ { + await dispatch( + loadLastSession({ + saveCurrentSession: true, + }), + ); + }} + className="flex items-center gap-2" + > + + Last Session + )}
+
+ +
{!hasDismissedExploreDialog && } {history.length === 0 && ( diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index ddecb6c19..0c40ed2eb 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -23,7 +23,6 @@ import { Tool, ToolCallDelta, ToolCallState, - WarningMessage, } from "core"; import { BuiltInToolNames } from "core/tools/builtIn"; import { NEW_SESSION_TITLE } from "core/util/constants"; @@ -34,6 +33,7 @@ import { import { findUriInDirs, getUriPathBasename } from "core/util/uri"; import { findLastIndex } from "lodash"; import { v4 as uuidv4 } from "uuid"; +import { type InlineErrorMessageType } from "../../components/mainInput/InlineErrorMessage"; import { toolCallCtxItemToCtxItemWithId } from "../../pages/gui/ToolCallDiv/utils"; import { addToolCallDeltaToState } from "../../util/toolCallState"; import { RootState } from "../store"; @@ -224,7 +224,9 @@ type SessionState = { }; newestToolbarPreviewForInput: Record; hasReasoningEnabled?: boolean; - warningMessage?: WarningMessage; + isPruned?: boolean; + contextPercentage?: number; + inlineErrorMessage?: InlineErrorMessageType; }; const initialState: SessionState = { @@ -244,6 +246,7 @@ const initialState: SessionState = { }, lastSessionId: undefined, newestToolbarPreviewForInput: {}, + isPruned: false, }; export const sessionSlice = createSlice({ @@ -421,12 +424,17 @@ export const sessionSlice = createSlice({ }, contextItems: [], }); + state.inlineErrorMessage = undefined; + state.isPruned = false; + state.contextPercentage = undefined; } }, deleteMessage: (state, action: PayloadAction) => { // Deletes the current assistant message and the previous user message state.history.splice(action.payload - 1, 2); - state.warningMessage = undefined; + state.inlineErrorMessage = undefined; + state.isPruned = false; + state.contextPercentage = undefined; }, updateHistoryItemAtIndex: ( state, @@ -637,6 +645,10 @@ export const sessionSlice = createSlice({ state.isStreaming = false; state.symbols = {}; + state.inlineErrorMessage = undefined; + state.isPruned = false; + state.contextPercentage = undefined; + if (payload) { state.history = payload.history as any; state.title = payload.title; @@ -892,11 +904,17 @@ export const sessionSlice = createSlice({ state.newestToolbarPreviewForInput[payload.inputId] = payload.contextItemId; }, - setWarningMessage: ( + setInlineErrorMessage: ( state, - action: PayloadAction, + action: PayloadAction, ) => { - state.warningMessage = action.payload; + state.inlineErrorMessage = action.payload; + }, + setIsPruned: (state, action: PayloadAction) => { + state.isPruned = action.payload; + }, + setContextPercentage: (state, action: PayloadAction) => { + state.contextPercentage = action.payload; }, }, selectors: { @@ -981,7 +999,9 @@ export const { setNewestToolbarPreviewForInput, setIsInEdit, setHasReasoningEnabled, - setWarningMessage, + setInlineErrorMessage, + setIsPruned, + setContextPercentage, } = sessionSlice.actions; export const { selectIsGatheringContext } = sessionSlice.selectors; diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index 0e1b99a34..6c722817b 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -11,9 +11,11 @@ import { addPromptCompletionPair, setActive, setAppliedRulesAtIndex, + setContextPercentage, setInactive, + setInlineErrorMessage, + setIsPruned, setToolGenerated, - setWarningMessage, streamUpdate, } from "../slices/sessionSlice"; import { AppThunkDispatch, RootState, ThunkApiType } from "../store"; @@ -184,23 +186,16 @@ export const streamNormalInput = createAsyncThunk< ); dispatch(setActive()); - // Remove the warning message before each compileChat call - dispatch(setWarningMessage(undefined)); + dispatch(setInlineErrorMessage(undefined)); + const precompiledRes = await extra.ideMessenger.request("llm/compileChat", { messages, options: completionOptions, }); if (precompiledRes.status === "error") { - if (precompiledRes.error.includes("Not enough context ")) { - dispatch( - setWarningMessage({ - message: - "The provided context items are too large. Please trim the context item to fit the model's context length or increase the model's context length by editing the configuration.", - level: "fatal", - category: "deleted-last-input", - }), - ); + if (precompiledRes.error.includes("Not enough context")) { + dispatch(setInlineErrorMessage("out-of-context")); dispatch(setInactive()); return; } else { @@ -208,17 +203,11 @@ export const streamNormalInput = createAsyncThunk< } } - const { compiledChatMessages, didPrune } = precompiledRes.content; + const { compiledChatMessages, didPrune, contextPercentage } = + precompiledRes.content; - if (didPrune) { - dispatch( - setWarningMessage({ - message: `Chat history exceeds model's context length (${state.config.config.selectedModelByRole.chat?.contextLength} tokens). Old messages will not be included.`, - level: "warning", - category: "exceeded-context-length", - }), - ); - } + dispatch(setIsPruned(didPrune)); + dispatch(setContextPercentage(contextPercentage)); // Send request and stream response const streamAborter = state.session.streamAborter; From 9ad19f9a56a18cedca405dfb0c8040f4d363f251 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 17 Jul 2025 03:14:31 +0200 Subject: [PATCH 04/10] fix context status percentage --- gui/src/components/mainInput/ContextStatus.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/components/mainInput/ContextStatus.tsx b/gui/src/components/mainInput/ContextStatus.tsx index 8366acc99..3ee97cbab 100644 --- a/gui/src/components/mainInput/ContextStatus.tsx +++ b/gui/src/components/mainInput/ContextStatus.tsx @@ -9,7 +9,7 @@ const ContextStatus = () => { ); const percent = Math.round((contextPercentage ?? 0) * 100); const isPruned = useAppSelector((state) => state.session.isPruned); - if (!isPruned && percent < 0.6) { + if (!isPruned && percent < 60) { return null; } return ( From 6177ba3fc40b9a7290a2eca37f50c2f32754cf06 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 17 Jul 2025 03:39:08 +0200 Subject: [PATCH 05/10] fix hide inline error and position --- core/llm/countTokens.ts | 13 +++++-------- gui/src/components/mainInput/ContinueInputBox.tsx | 2 -- gui/src/components/mainInput/InlineErrorMessage.tsx | 8 ++++---- gui/src/pages/gui/Chat.tsx | 2 ++ 4 files changed, 11 insertions(+), 14 deletions(-) diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 65a7cca1f..852638d1c 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -444,13 +444,6 @@ function compileChatMessages({ msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy); - while (msgsCopy.length > 1) { - if (isUserOrToolMsg(msgsCopy.at(-1))) { - break; - } - msgsCopy.pop(); - } - // Extract the tool sequence from the end of the message array const toolSequence = extractToolSequence(msgsCopy); @@ -531,7 +524,11 @@ function compileChatMessages({ reassembled.push(...historyWithTokens.map(({ tokens, ...rest }) => rest)); reassembled.push(...toolSequence); - const contextPercentage = currentTotal / contextLength; + const inputTokens = + currentTotal + systemMsgTokens + toolTokens + lastMessagesTokens; + const availableTokens = + contextLength - countingSafetyBuffer - minOutputTokens; + const contextPercentage = inputTokens / availableTokens; return { compiledChatMessages: reassembled, didPrune, diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index 7234fa03c..c731b761b 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -7,7 +7,6 @@ import { selectSlashCommandComboBoxInputs } from "../../redux/selectors"; import { ContextItemsPeek } from "./belowMainInput/ContextItemsPeek"; import { RulesPeek } from "./belowMainInput/RulesPeek"; import { GradientBorder } from "./GradientBorder"; -import InlineErrorMessage from "./InlineErrorMessage"; import { ToolbarOptions } from "./InputToolbar"; import { Lump } from "./Lump"; import { TipTapEditor } from "./TipTapEditor"; @@ -120,7 +119,6 @@ function ContinueInputBox(props: ContinueInputBoxProps) { /> )} - {props.isLastUserInput && } ); } diff --git a/gui/src/components/mainInput/InlineErrorMessage.tsx b/gui/src/components/mainInput/InlineErrorMessage.tsx index 631b939c1..d23fc7813 100644 --- a/gui/src/components/mainInput/InlineErrorMessage.tsx +++ b/gui/src/components/mainInput/InlineErrorMessage.tsx @@ -1,10 +1,12 @@ import { useContext } from "react"; import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { useAppSelector } from "../../redux/hooks"; +import { useAppDispatch, useAppSelector } from "../../redux/hooks"; +import { setInlineErrorMessage } from "../../redux/slices/sessionSlice"; export type InlineErrorMessageType = "out-of-context"; export default function InlineErrorMessage() { + const dispatch = useAppDispatch(); const ideMessenger = useContext(IdeMessengerContext); const inlineErrorMessage = useAppSelector( (state) => state.session.inlineErrorMessage, @@ -33,9 +35,7 @@ export default function InlineErrorMessage() { { - ideMessenger.post("config/openProfile", { - profileId: undefined, - }); + dispatch(setInlineErrorMessage(undefined)); }} > Hide diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 46377e094..93d51cc2e 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -44,6 +44,7 @@ import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util"; import { ToolCallDiv } from "./ToolCallDiv"; import ContextStatus from "../../components/mainInput/ContextStatus"; +import InlineErrorMessage from "../../components/mainInput/InlineErrorMessage"; import { cancelStream } from "../../redux/thunks/cancelStream"; import { EmptyChatBody } from "./EmptyChatBody"; import { ExploreDialogWatcher } from "./ExploreDialogWatcher"; @@ -389,6 +390,7 @@ export function Chat() { > {renderChatHistoryItem(item, index)} + {index === history.length - 1 && } ))} From 99eeec38061aee214a78e7aacd9878fdf66e4b83 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 18 Jul 2025 02:42:51 +0200 Subject: [PATCH 06/10] move context status to input toolbar --- .../components/mainInput/ContextStatus.tsx | 81 +++++++++++-------- gui/src/components/mainInput/InputToolbar.tsx | 3 +- .../components/modelSelection/ModelSelect.tsx | 2 +- gui/src/pages/gui/Chat.tsx | 4 - 4 files changed, 49 insertions(+), 41 deletions(-) diff --git a/gui/src/components/mainInput/ContextStatus.tsx b/gui/src/components/mainInput/ContextStatus.tsx index 3ee97cbab..2d5c1f5cb 100644 --- a/gui/src/components/mainInput/ContextStatus.tsx +++ b/gui/src/components/mainInput/ContextStatus.tsx @@ -1,52 +1,63 @@ +import { Tooltip } from "react-tooltip"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { saveCurrentSession } from "../../redux/thunks/session"; -import { ToolTip } from "../gui/Tooltip"; const ContextStatus = () => { const dispatch = useAppDispatch(); const contextPercentage = useAppSelector( (state) => state.session.contextPercentage, ); + const history = useAppSelector((state) => state.session.history); const percent = Math.round((contextPercentage ?? 0) * 100); const isPruned = useAppSelector((state) => state.session.isPruned); if (!isPruned && percent < 60) { return null; } - return ( -
- { - dispatch( - saveCurrentSession({ - openNewSession: true, - generateTitle: false, - }), - ); - }} - > - New Session - - {contextPercentage !== undefined && ( - <> - {percent}% - - {`${percent}% of context is filled`} - - - )} - {isPruned && ( - <> -
- - Chat history exceeds context limit, old messages are being removed - - - )} + const barColorClass = percent > 80 ? "bg-warning" : "bg-description"; + + return ( +
+ +
+ {`${percent}% of context filled`} + {isPruned && Old messages are being removed} + {history.length > 0 && ( + { + dispatch( + saveCurrentSession({ + openNewSession: true, + generateTitle: false, + }), + ); + }} + > + New Session + + )} +
+
+
+ {/*
*/} +
+
); }; diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index 4967c9d90..9be9f25d9 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -19,6 +19,7 @@ import ModelSelect from "../modelSelection/ModelSelect"; import { ModeSelect } from "../ModeSelect"; import { Button } from "../ui"; import { useFontSize } from "../ui/font"; +import ContextStatus from "./ContextStatus"; import HoverItem from "./InputToolbar/HoverItem"; export interface ToolbarOptions { @@ -170,6 +171,7 @@ function InputToolbar(props: InputToolbarProps) { fontSize: tinyFont, }} > + {!isInEdit && } {!props.toolbarOptions?.hideUseCodebase && !isInEdit && ( -
- -
{!hasDismissedExploreDialog && } {history.length === 0 && ( From 9555defca5e5e2d049783b6f24821bde781fcb62 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 18 Jul 2025 02:46:20 +0200 Subject: [PATCH 07/10] update colors for context status --- gui/src/components/mainInput/ContextStatus.tsx | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/gui/src/components/mainInput/ContextStatus.tsx b/gui/src/components/mainInput/ContextStatus.tsx index 2d5c1f5cb..13a030a9f 100644 --- a/gui/src/components/mainInput/ContextStatus.tsx +++ b/gui/src/components/mainInput/ContextStatus.tsx @@ -14,7 +14,11 @@ const ContextStatus = () => { return null; } - const barColorClass = percent > 80 ? "bg-warning" : "bg-description"; + const barColorClass = isPruned + ? "bg-error" + : percent > 80 + ? "bg-warning" + : "bg-description"; return (
From 9967ca78c5c8e2c8fc1940168c66830aee9d0bbe Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 18 Jul 2025 09:51:15 +0200 Subject: [PATCH 08/10] update context status copy --- .../components/mainInput/ContextStatus.tsx | 40 +++++++++++-------- 1 file changed, 24 insertions(+), 16 deletions(-) diff --git a/gui/src/components/mainInput/ContextStatus.tsx b/gui/src/components/mainInput/ContextStatus.tsx index 13a030a9f..f4c88b5b3 100644 --- a/gui/src/components/mainInput/ContextStatus.tsx +++ b/gui/src/components/mainInput/ContextStatus.tsx @@ -33,30 +33,38 @@ const ContextStatus = () => { clickable >
- {`${percent}% of context filled`} - {isPruned && Old messages are being removed} - {history.length > 0 && ( - { - dispatch( - saveCurrentSession({ - openNewSession: true, - generateTitle: false, - }), - ); - }} - > - New Session + + {`${percent}% of context filled`} + + {isPruned && ( + + {`Oldest messages are being removed`} )} + {history.length > 0 && ( +
+ Start a{" "} + { + dispatch( + saveCurrentSession({ + openNewSession: true, + generateTitle: false, + }), + ); + }} + > + New Session + +
+ )}
- {/*
*/}
Date: Fri, 18 Jul 2025 18:55:26 +0200 Subject: [PATCH 09/10] feat: tweak styling on context status --- gui/src/components/mainInput/ContextStatus.tsx | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/gui/src/components/mainInput/ContextStatus.tsx b/gui/src/components/mainInput/ContextStatus.tsx index f4c88b5b3..3b73fa36a 100644 --- a/gui/src/components/mainInput/ContextStatus.tsx +++ b/gui/src/components/mainInput/ContextStatus.tsx @@ -1,6 +1,6 @@ -import { Tooltip } from "react-tooltip"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { saveCurrentSession } from "../../redux/thunks/session"; +import { ToolTip } from "../gui/Tooltip"; const ContextStatus = () => { const dispatch = useAppDispatch(); @@ -22,7 +22,7 @@ const ContextStatus = () => { return (
- { { - dispatch( + void dispatch( saveCurrentSession({ openNewSession: true, generateTitle: false, @@ -60,10 +60,10 @@ const ContextStatus = () => {
)}
- +
Date: Fri, 18 Jul 2025 19:20:13 +0200 Subject: [PATCH 10/10] fix prettier --- packages/shared-release.config.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/shared-release.config.js b/packages/shared-release.config.js index 8063d6937..49373804c 100644 --- a/packages/shared-release.config.js +++ b/packages/shared-release.config.js @@ -25,4 +25,4 @@ export default function createReleaseConfig(packageName) { "@semantic-release/github", ], }; -} \ No newline at end of file +}