feat: compaction (#6662)

* feat: compaction

* fix: type errors

* fix: prettier

* fix: type errrors

* Update gui/src/components/StepContainer/StepContainer.tsx

Co-authored-by: Patrick Erichsen <patrick.a.erichsen@gmail.com>

* Update gui/src/components/StepContainer/ResponseActions.tsx

Co-authored-by: Patrick Erichsen <patrick.a.erichsen@gmail.com>

* Update gui/src/components/StepContainer/ConversationSummary.tsx

Co-authored-by: Patrick Erichsen <patrick.a.erichsen@gmail.com>

* fix: compaction

* fix: type errors

* fix: type errors

* fix: add passthrough

---------

Co-authored-by: Patrick Erichsen <patrick.a.erichsen@gmail.com>
This commit is contained in:
Tomasz Stefaniak 2025-07-17 16:22:46 -07:00 • committed by GitHub
parent 6eaf4ed530
commit 25ebca018f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
24 changed files with 2527 additions and 2198 deletions

View file

@ -24,6 +24,7 @@ import { createNewPromptFileV2 } from "./promptFiles/createNewPromptFile";
import { callTool } from "./tools/callTool";
import { ChatDescriber } from "./util/chatDescriber";
import { clipboardCache } from "./util/clipboardCache";
import { compactConversation } from "./util/conversationCompaction";
import { GlobalContext } from "./util/GlobalContext";
import historyManager from "./util/history";
import { editConfigFile, migrateV1DevDataFiles } from "./util/paths";
@ -549,6 +550,28 @@ export class Core {
return await ChatDescriber.describe(currentModel, {}, msg.data.text);
});
on("conversation/compact", async (msg) => {
const currentModel = (await this.configHandler.loadConfig()).config
?.selectedModelByRole.chat;
if (!currentModel) {
throw new Error("No chat model selected");
}
try {
await compactConversation({
sessionId: msg.data.sessionId,
index: msg.data.index,
historyManager,
currentModel,
});
return undefined;
} catch (error) {
console.error("Error compacting conversation:", error);
return undefined;
}
});
// Autocomplete
on("autocomplete/complete", async (msg) => {
const outcome =

1
core/index.d.ts vendored
View file

@ -472,6 +472,7 @@ export interface ChatHistoryItem {
isGatheringContext?: boolean;
reasoning?: Reasoning;
appliedRules?: RuleWithSource[];
conversationSummary?: string;
}
export interface LLMFullCompletionOptions extends BaseCompletionOptions {

View file

@ -186,6 +186,13 @@ export type ToCoreFromIdeOrWebviewProtocol = {
},
string | undefined,
];
"conversation/compact": [
{
index: number;
sessionId: string;
},
string | undefined,
];
"stats/getTokensPerDay": [
undefined,
{ day: string; promptTokens: number; generatedTokens: number }[],

View file

@ -47,6 +47,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"llm/compileChat",
"streamDiffLines",
"chatDescriber/describe",
"conversation/compact",
"stats/getTokensPerDay",
"stats/getTokensPerModel",
// Codebase

View file

@ -0,0 +1,89 @@
import { ILLM } from "..";
import { HistoryManager } from "./history";
import { stripImages } from "./messageContent";
export interface CompactionParams {
sessionId: string;
index: number;
historyManager: HistoryManager;
currentModel: ILLM;
}
/**
* Compacts conversation history up to a specified index by generating a summary.
* This helper function extracts the compaction logic from the main core handler.
*
* @param params - Object containing sessionId, index, historyManager, and currentModel
* @returns Promise<void> - Updates the session with the conversation summary
*/
export async function compactConversation({
sessionId,
index,
historyManager,
currentModel,
}: CompactionParams): Promise<void> {
// Get the current session
const session = historyManager.load(sessionId);
const historyUpToIndex = session.history.slice(0, index + 1);
// Apply the same filtering logic as in constructMessages, but exclude the target message
// if it already has a summary (we're re-compacting)
let summaryContent = "";
let filteredHistory = historyUpToIndex;
// First, check if the target message already has a summary and ignore it
const targetMessageHasSummary = historyUpToIndex[index].conversationSummary;
const searchHistory = targetMessageHasSummary
? historyUpToIndex.slice(0, index)
: historyUpToIndex;
// Find the most recent conversation summary (excluding target if it has one)
for (let i = searchHistory.length - 1; i >= 0; i--) {
const summary = searchHistory[i].conversationSummary;
if (summary) {
summaryContent = summary;
// Only include messages that come AFTER the message with the summary
filteredHistory = historyUpToIndex.slice(i + 1);
break;
}
}
// Create messages from filtered history
const messages = filteredHistory.map((item: any) => item.message);
// If there's a previous summary, include it as a user message at the beginning
if (summaryContent) {
messages.unshift({
role: "user",
content: `Previous conversation summary:\n\n${summaryContent}`,
});
}
const compactionPrompt = {
role: "user" as const,
content:
"Create a comprehensive summary of this conversation that captures all essential information needed to continue the work seamlessly. Structure your response to preserve technical accuracy and context continuity.\n\nYour summary should include:\n\n1. **Conversation Overview**: Describe the main topic and progression of the discussion, including any shifts in focus or direction.\n\n2. **Active Development**: Detail what was being implemented, modified, or debugged most recently. Include specific technical approaches and methodologies used.\n\n3. **Technical Stack**: List all relevant technologies, frameworks, libraries, coding patterns, and architectural decisions discussed.\n\n4. **File Operations**: Document all files that were created, modified, or referenced, including their purposes and key changes. Include important code snippets and their locations.\n\n5. **Solutions & Troubleshooting**: Summarize problems encountered and how they were resolved, including any debugging steps or workarounds applied.\n\n6. **Outstanding Work**: Clearly identify any incomplete tasks, pending implementations, or next steps that were discussed. Include direct references to user requests and current progress.\n\nIf there's a previous summary in the conversation, integrate its relevant information while removing outdated details. Focus on technical precision and include specific identifiers (file paths, function names, class names, etc.) that would be essential for continuation. Write in third person and maintain an objective, technical tone.",
};
// Generate the summary using the current model
const response = await currentModel.chat(
[...messages, compactionPrompt],
new AbortController().signal,
{},
);
// Update the target message with the conversation summary
const updatedHistory = [...session.history];
updatedHistory[index] = {
...updatedHistory[index],
conversationSummary: stripImages(response.content),
};
// Update the session with the new history
const updatedSession = {
...session,
history: updatedHistory,
};
historyManager.save(updatedSession);
}

View file

@ -21,7 +21,7 @@ function safeParseArray<T>(
}
}
class HistoryManager {
export class HistoryManager {
list(options: ListHistoryOptions): SessionMetadata[] {
const filepath = getSessionsListPath();
if (!fs.existsSync(filepath)) {

View file

@ -113,6 +113,7 @@ class MessageTypes {
"llm/compileChat",
"streamDiffLines",
"chatDescriber/describe",
"conversation/compact",
"stats/getTokensPerDay",
"stats/getTokensPerModel",
// Codebase

View file

@ -38,4 +38,4 @@ All e2e tests are separated (by folder) into
### Quirks
- For non-macOS systems, `codesign` is not available. You should run `npm run e2e:all-non-mac` instead of `npm run e2e:all`.
- For non-macOS systems, `codesign` is not available. You should run `npm run e2e:all-non-mac` instead of `npm run e2e:all`.

View file

@ -1,15 +1,19 @@
import { expect } from "chai";
import { Key } from "vscode-extension-tester";
import { access, constants } from 'fs/promises';
import { access, constants } from "fs/promises";
import * as path from "path";
import { DEFAULT_TIMEOUT } from "./constants";
export class TestUtils {
public static CONTINUE_GLOBAL_DIR = process.env.CONTINUE_GLOBAL_DIR ?? "";
public static getGlobalContextFilePath(): string {
return path.join(TestUtils.CONTINUE_GLOBAL_DIR, "index", "globalContext.json");
return path.join(
TestUtils.CONTINUE_GLOBAL_DIR,
"index",
"globalContext.json",
);
}
public static async fileExists(path: string): Promise<boolean> {

View file

@ -12,12 +12,14 @@ export class NextEditActions {
public static async acceptNextEditSuggestion(editor: TextEditor) {
const hasDecoration = await NextEditActions.forceNextEdit(editor);
expect(hasDecoration).to.be.true;
await new Workbench().executeCommand("Continue: Accept Next Edit Suggestion");
await new Workbench().executeCommand(
"Continue: Accept Next Edit Suggestion",
);
// Check if HELLO is written into the editor.
const editorText = await editor.getTextAtLine(1);
return editorText === "HELLO";
}
@ -27,12 +29,12 @@ export class NextEditActions {
public static async rejectNextEditSuggestion(editor: TextEditor) {
const hasDecoration = await NextEditActions.forceNextEdit(editor);
expect(hasDecoration).to.be.true;
await new Workbench().executeCommand("Continue: Hide Next Edit Suggestion");
// Check if the editor text didn't change.
const editorText = await editor.getText();
return editorText === "def main():\n ";
}
@ -45,16 +47,16 @@ export class NextEditActions {
await new Workbench().executeCommand("Continue: Force Next Edit");
await TestUtils.waitForTimeout(DEFAULT_TIMEOUT.XL);
const svgDecoration = await TestUtils.waitForSuccess(
() => NextEditSelectors.getSvgDecoration(VSBrowser.instance.driver),
DEFAULT_TIMEOUT.XL
DEFAULT_TIMEOUT.XL,
);
return svgDecoration !== null;
}
public static async reload(): Promise<void> {
await new Workbench().executeCommand('workbench.action.reloadWindow');
await new Workbench().executeCommand("workbench.action.reloadWindow");
}
}

View file

@ -100,10 +100,7 @@ export class GUISelectors {
}
public static getNthMessageDeleteButton(view: WebView, index: number) {
return SelectorUtils.getElementByDataTestId(
view,
`delete-button-${index}`,
);
return SelectorUtils.getElementByDataTestId(view, `delete-button-${index}`);
}
public static getModelDropdownOption(view: WebView, option: string) {

View file

@ -8,7 +8,7 @@ export class NextEditSelectors {
try {
const decorations = await driver.findElement(
// By.xpath("//*[contains(@class, 'ced-') and matches(@class, 'ced-2-TextEditorDecorationType[0-9]+-4')]")
By.css("[class*='TextEditorDecorationType']")
By.css("[class*='TextEditorDecorationType']"),
);
return decorations ?? null;
} catch (error) {
@ -16,4 +16,4 @@ export class NextEditSelectors {
return null;
}
}
}
}

View file

@ -584,4 +584,4 @@ describe("GUI Test", () => {
);
}).timeout(DEFAULT_TIMEOUT.XL);
});
});
});

View file

@ -7,55 +7,59 @@ import { NextEditActions } from "../actions/NextEdit.actions";
import { DEFAULT_TIMEOUT } from "../constants";
import { TestUtils } from "../TestUtils";
describe("Next Edit", () => {
describe("Next Edit", () => {
let editor: TextEditor;
before(async function () {
// this.timeout(DEFAULT_TIMEOUT.XL);
const globalContextPath = TestUtils.getGlobalContextFilePath();
// Update config.json to add optInNextEditFeature.
// globalContext.json does not exist in CI before this test runs.
if (await TestUtils.fileExists(globalContextPath)) {
const globalContext = await fs.readFile(globalContextPath, "utf8");
const sharedConfig = JSON.parse(globalContext).sharedConfig;
const sharedConfigWithNextEditEnabled = {
...sharedConfig,
"optInNextEditFeature": true
optInNextEditFeature: true,
};
const globalContextWithNextEditEnabled = {
...JSON.parse(globalContext),
"sharedConfig": sharedConfigWithNextEditEnabled
sharedConfig: sharedConfigWithNextEditEnabled,
};
await fs.writeFile(globalContextPath, JSON.stringify(globalContextWithNextEditEnabled, null, 2), "utf8");
await fs.writeFile(
globalContextPath,
JSON.stringify(globalContextWithNextEditEnabled, null, 2),
"utf8",
);
} else {
await fs.writeFile(
globalContextPath,
JSON.stringify(
{
sharedConfig: {
optInNextEditFeature: true
},
selectedModelsByProfileId: {
local: {
chat: "TEST LLM",
edit: "TEST LLM",
apply: "TEST LLM",
embed: "Transformers.js (Built-In)",
autocomplete: "TEST LLM",
rerank: null,
summarize: null
}
}
},
null,
2,
),
);
globalContextPath,
JSON.stringify(
{
sharedConfig: {
optInNextEditFeature: true,
},
selectedModelsByProfileId: {
local: {
chat: "TEST LLM",
edit: "TEST LLM",
apply: "TEST LLM",
embed: "Transformers.js (Built-In)",
autocomplete: "TEST LLM",
rerank: null,
summarize: null,
},
},
},
null,
2,
),
);
}
await NextEditActions.reload();
@ -77,20 +81,27 @@ describe("Next Edit", () => {
after(async function () {
// this.timeout(DEFAULT_TIMEOUT.XL);
// Update config.json to delete optInNextEditFeature.
const globalContext = await fs.readFile(TestUtils.getGlobalContextFilePath(), "utf8");
const globalContext = await fs.readFile(
TestUtils.getGlobalContextFilePath(),
"utf8",
);
const sharedConfig = JSON.parse(globalContext).sharedConfig;
const sharedConfigWithoutNextEdit = { ...sharedConfig };
delete sharedConfigWithoutNextEdit.optInNextEditFeature;
const globalContextWithNextEditEnabled = {
...JSON.parse(globalContext),
"sharedConfig": sharedConfigWithoutNextEdit
sharedConfig: sharedConfigWithoutNextEdit,
};
await fs.writeFile(TestUtils.getGlobalContextFilePath(), JSON.stringify(globalContextWithNextEditEnabled, null, 2), "utf8");
await fs.writeFile(
TestUtils.getGlobalContextFilePath(),
JSON.stringify(globalContextWithNextEditEnabled, null, 2),
"utf8",
);
await NextEditActions.reload();
}).timeout(DEFAULT_TIMEOUT.XL);
@ -116,5 +127,4 @@ describe("Next Edit", () => {
const rejected = await NextEditActions.rejectNextEditSuggestion(editor);
expect(rejected).to.be.true;
}).timeout(DEFAULT_TIMEOUT.XXL);
});
});

View file

@ -47,6 +47,7 @@ const Layout = () => {
const dispatch = useAppDispatch();
const onboardingCard = useOnboardingCard();
const ideMessenger = useContext(IdeMessengerContext);
const currentSessionId = useAppSelector((state) => state.session.id);
const { mainEditor } = useMainEditor();
const dialogMessage = useAppSelector((state) => state.ui.dialogMessage);

View file

@ -0,0 +1,68 @@
import { ChevronDownIcon, ChevronUpIcon } from "@heroicons/react/24/solid";
import { ChatHistoryItem } from "core";
import { useState } from "react";
import { AnimatedEllipsis } from "../";
import { useAppSelector } from "../../redux/hooks";
import StyledMarkdownPreview from "../StyledMarkdownPreview";
interface ConversationSummaryProps {
item: ChatHistoryItem;
index: number;
}
export default function ConversationSummary(props: ConversationSummaryProps) {
const [open, setOpen] = useState(false);
const isLoading = useAppSelector(
(state) => state.session.compactionLoading[props.index] || false,
);
if (!props.item.conversationSummary && !isLoading) {
return null;
}
// Loading state - much simpler
if (isLoading) {
return (
<div className="mx-1.5 mb-4 mt-2">
<div className="bg-vsc-input-background rounded-md shadow-sm">
<div className="text-description flex items-center justify-start px-3 py-2 text-xs">
<span>Generating conversation summary</span>
<AnimatedEllipsis />
</div>
</div>
</div>
);
}
// Normal state with content
return (
<div className="mx-1.5 mb-4 mt-2">
<div className="bg-vsc-input-background rounded-md shadow-sm">
<div
className="text-description flex cursor-pointer items-center gap-2 px-3 py-2 text-xs transition-colors duration-200 hover:brightness-105"
onClick={() => setOpen(!open)}
>
{open ? (
<ChevronUpIcon className="h-3 w-3" />
) : (
<ChevronDownIcon className="h-3 w-3" />
)}
<span>Conversation Summary</span>
</div>
{open && (
<>
<div className="border-border border-0 border-t border-solid"></div>
<div className="max-h-[400px] overflow-y-auto px-3 pb-3 pt-2">
<StyledMarkdownPreview
isRenderingInStepContainer
source={props.item.conversationSummary}
itemIndex={props.index}
useParentBackgroundColor
/>
</div>
</>
)}
</div>
</div>
);
}

View file

@ -1,4 +1,5 @@
import {
ArrowsPointingInIcon,
BarsArrowDownIcon,
PencilSquareIcon,
TrashIcon,
@ -6,11 +7,13 @@ import {
import { ChatHistoryItem } from "core";
import { modelSupportsTools } from "core/llm/autodetect";
import { renderChatMessage } from "core/util/messageContent";
import { useMemo } from "react";
import { useDispatch } from "react-redux";
import { useAppSelector } from "../../redux/hooks";
import { useContext, useMemo } from "react";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { selectSelectedChatModel } from "../../redux/slices/configSlice";
import { setCompactionLoading } from "../../redux/slices/sessionSlice";
import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice";
import { loadSession } from "../../redux/thunks/session";
import { FeedbackButtons } from "../FeedbackButtons";
import { GenerateRuleDialog } from "../GenerateRuleDialog";
import { CopyIconButton } from "../gui/CopyIconButton";
@ -33,7 +36,9 @@ export default function ResponseActions({
onDelete,
isLast,
}: ResponseActionsProps) {
const dispatch = useDispatch();
const dispatch = useAppDispatch();
const ideMessenger = useContext(IdeMessengerContext);
const currentSessionId = useAppSelector((state) => state.session.id);
const selectedModel = useAppSelector(selectSelectedChatModel);
const ruleGenerationSupported = useMemo(() => {
return selectedModel && modelSupportsTools(selectedModel);
@ -44,6 +49,35 @@ export default function ResponseActions({
dispatch(setDialogMessage(<GenerateRuleDialog />));
};
const onCompactConversation = async () => {
if (!currentSessionId) {
return;
}
try {
// Set loading state
dispatch(setCompactionLoading({ index, loading: true }));
await ideMessenger.request("conversation/compact", {
index,
sessionId: currentSessionId,
});
// Reload the current session to refresh the conversation state
dispatch(
loadSession({
sessionId: currentSessionId,
saveCurrentSession: false,
}),
);
} catch (error) {
console.error("Error compacting conversation:", error);
} finally {
// Clear loading state
dispatch(setCompactionLoading({ index, loading: false }));
}
};
return (
<div className="text-description-muted mx-2 flex cursor-default items-center justify-end space-x-1 bg-transparent pb-0 text-xs">
{isLast && ruleGenerationSupported && (
@ -66,6 +100,15 @@ export default function ResponseActions({
</HeaderButtonWithToolTip>
)}
<HeaderButtonWithToolTip
testId={`compact-button-${index}`}
text="Compact conversation"
tabIndex={-1}
onClick={onCompactConversation}
>
<ArrowsPointingInIcon className="text-description-muted h-3.5 w-3.5" />
</HeaderButtonWithToolTip>
<HeaderButtonWithToolTip
testId={`delete-button-${index}`}
text="Delete"

View file

@ -6,6 +6,7 @@ import { useAppSelector } from "../../redux/hooks";
import { selectUIConfig } from "../../redux/slices/configSlice";
import { deleteMessage } from "../../redux/slices/sessionSlice";
import StyledMarkdownPreview from "../StyledMarkdownPreview";
import ConversationSummary from "./ConversationSummary";
import Reasoning from "./Reasoning";
import ResponseActions from "./ResponseActions";
import ThinkingIndicator from "./ThinkingIndicator";
@ -14,6 +15,7 @@ interface StepContainerProps {
item: ChatHistoryItem;
index: number;
isLast: boolean;
latestSummaryIndex?: number;
}
export default function StepContainer(props: StepContainerProps) {
@ -28,6 +30,13 @@ export default function StepContainer(props: StepContainerProps) {
);
const uiConfig = useAppSelector(selectUIConfig);
// Calculate dimming and indicator state based on latest summary index
const latestSummaryIndex = props.latestSummaryIndex ?? -1;
const isBeforeLatestSummary =
latestSummaryIndex !== -1 && props.index <= latestSummaryIndex;
const isLatestSummary =
latestSummaryIndex !== -1 && props.index === latestSummaryIndex;
const isNextMsgAssistantOrThinking =
historyItemAfterThis?.message.role === "assistant" ||
historyItemAfterThis?.message.role === "thinking" ||
@ -83,7 +92,9 @@ export default function StepContainer(props: StepContainerProps) {
return (
<div>
<div className="bg-background p-1 px-1.5">
<div
className={`bg-background p-1 px-1.5 ${isBeforeLatestSummary ? "opacity-35" : ""}`}
>
{uiConfig?.displayRawMarkdown ? (
<pre className="text-2xs max-w-full overflow-x-auto whitespace-pre-wrap break-words p-4">
{renderChatMessage(props.item.message)}
@ -101,9 +112,12 @@ export default function StepContainer(props: StepContainerProps) {
)}
{props.isLast && <ThinkingIndicator historyItem={props.item} />}
</div>
{shouldRenderResponseAction() && (
// We want to occupy space in the DOM regardless of whether the actions are visible to avoid jank on stream complete
<div className={`mt-2 h-7 transition-opacity duration-300 ease-in-out`}>
<div
className={`mt-2 h-7 transition-opacity duration-300 ease-in-out ${isBeforeLatestSummary ? "opacity-35" : ""}`}
>
{!isStreaming && (
<ResponseActions
isTruncated={isTruncated}
@ -116,6 +130,22 @@ export default function StepContainer(props: StepContainerProps) {
)}
</div>
)}
{/* Show compaction indicator for the latest summary */}
{isLatestSummary && (
<div className="mx-1.5 my-5">
<div className="flex items-center">
<div className="border-border flex-1 border-t border-solid"></div>
<span className="text-description mx-3 text-xs">
Previous Conversation Compacted
</span>
<div className="border-border flex-1 border-t border-solid"></div>
</div>
</div>
)}
{/* ConversationSummary is outside the dimmed container so it's always at full opacity */}
<ConversationSummary item={props.item} index={props.index} />
</div>
);
}

View file

@ -3,7 +3,7 @@ import {
ChatBubbleOvalLeftIcon,
} from "@heroicons/react/24/outline";
import { Editor, JSONContent } from "@tiptap/react";
import { InputModifiers } from "core";
import { InputModifiers, ChatHistoryItem } from "core";
import { renderChatMessage } from "core/util/messageContent";
import {
useCallback,
@ -48,6 +48,16 @@ import { EmptyChatBody } from "./EmptyChatBody";
import { ExploreDialogWatcher } from "./ExploreDialogWatcher";
import { useAutoScroll } from "./useAutoScroll";
// Helper function to find the index of the latest conversation summary
function findLatestSummaryIndex(history: ChatHistoryItem[]): number {
for (let i = history.length - 1; i >= 0; i--) {
if (history[i].conversationSummary) {
return i;
}
}
return -1; // No summary found
}
const StepsDiv = styled.div`
position: relative;
background-color: transparent;
@ -273,19 +283,26 @@ export function Chat() {
toolCallStates,
} = item;
// Calculate once for the entire function
const latestSummaryIndex = findLatestSummaryIndex(history);
const isBeforeLatestSummary =
latestSummaryIndex !== -1 && index < latestSummaryIndex;
if (message.role === "user") {
return (
<ContinueInputBox
onEnter={(editorState, modifiers) =>
sendInput(editorState, modifiers, index)
}
isLastUserInput={isLastUserInput(index)}
isMainInput={false}
editorState={editorState}
contextItems={contextItems}
appliedRules={appliedRules}
inputId={message.id}
/>
<div className={isBeforeLatestSummary ? "opacity-50" : ""}>
<ContinueInputBox
onEnter={(editorState, modifiers) =>
sendInput(editorState, modifiers, index)
}
isLastUserInput={isLastUserInput(index)}
isMainInput={false}
editorState={editorState}
contextItems={contextItems}
appliedRules={appliedRules}
inputId={message.id}
/>
</div>
);
}
@ -314,6 +331,7 @@ export function Chat() {
index={index}
isLast={index === history.length - 1}
item={item}
latestSummaryIndex={latestSummaryIndex}
/>
</TimelineItem>
</div>
@ -330,14 +348,16 @@ export function Chat() {
if (message.role === "thinking") {
return (
<ThinkingBlockPeek
content={renderChatMessage(message)}
redactedThinking={message.redactedThinking}
index={index}
prevItem={index > 0 ? history[index - 1] : null}
inProgress={index === history.length - 1}
signature={message.signature}
/>
<div className={isBeforeLatestSummary ? "opacity-50" : ""}>
<ThinkingBlockPeek
content={renderChatMessage(message)}
redactedThinking={message.redactedThinking}
index={index}
prevItem={index > 0 ? history[index - 1] : null}
inProgress={index === history.length - 1}
signature={message.signature}
/>
</div>
);
}
@ -356,6 +376,7 @@ export function Chat() {
index={index}
isLast={index === history.length - 1}
item={item}
latestSummaryIndex={latestSummaryIndex}
/>
</TimelineItem>
</div>

View file

@ -75,6 +75,7 @@ describe("sessionSlice streamUpdate", () => {
},
newestToolbarPreviewForInput: {},
isSessionMetadataLoading: false,
compactionLoading: {},
});
describe("Basic Chat Message", () => {

View file

@ -224,6 +224,7 @@ type SessionState = {
};
newestToolbarPreviewForInput: Record<string, string>;
hasReasoningEnabled?: boolean;
compactionLoading: Record<number, boolean>; // Track compaction loading by message index
warningMessage?: WarningMessage;
};
@ -244,6 +245,7 @@ const initialState: SessionState = {
},
lastSessionId: undefined,
newestToolbarPreviewForInput: {},
compactionLoading: {},
};
export const sessionSlice = createSlice({
@ -892,6 +894,17 @@ export const sessionSlice = createSlice({
state.newestToolbarPreviewForInput[payload.inputId] =
payload.contextItemId;
},
setCompactionLoading: (
state,
action: PayloadAction<{ index: number; loading: boolean }>,
) => {
const { index, loading } = action.payload;
if (loading) {
state.compactionLoading[index] = true;
} else {
delete state.compactionLoading[index];
}
},
setWarningMessage: (
state,
action: PayloadAction<WarningMessage | undefined>,
@ -981,6 +994,7 @@ export const {
setNewestToolbarPreviewForInput,
setIsInEdit,
setHasReasoningEnabled,
setCompactionLoading,
setWarningMessage,
} = sessionSlice.actions;

View file

@ -40,7 +40,21 @@ export function constructMessages(
appliedRules: RuleWithSource[];
appliedRuleIndex: number;
} {
const historyCopy = [...history];
// Find the most recent conversation summary and filter history accordingly
let summaryContent = "";
let filteredHistory = history;
for (let i = history.length - 1; i >= 0; i--) {
const summary = history[i].conversationSummary;
if (summary) {
summaryContent = summary;
// Only include messages that come AFTER the message with the summary
filteredHistory = history.slice(i + 1);
break;
}
}
const historyCopy = [...filteredHistory];
const msgs: MessageWithContextItems[] = [];
let appliedRuleIndex = -1;
@ -160,12 +174,20 @@ export function constructMessages(
rulePolicies,
});
if (systemMessage.trim()) {
// Append conversation summary to system message if it exists
let finalSystemMessage = systemMessage;
if (summaryContent) {
finalSystemMessage = systemMessage
? `${systemMessage}\n\nPrevious conversation summary:\n\n ${summaryContent}`
: `Previous conversation summary:\n\n ${summaryContent}`;
}
if (finalSystemMessage.trim()) {
msgs.unshift({
ctxItems: [],
message: {
role: "system",
content: systemMessage,
content: finalSystemMessage,
},
});
}

File diff suppressed because it is too large Load diff

View file

@ -71,7 +71,10 @@ export function createOpenAIClient({
);
}
if (!("apiKeyLocation" in modelConfig) && !("envSecretLocations" in modelConfig)) {
if (
!("apiKeyLocation" in modelConfig) &&
!("envSecretLocations" in modelConfig)
) {
throw new Error(
`Model ${modelName} does not have an apiKeyLocation or envSecretLocations defined`,
);