Compare commits

...
Author SHA1 Message Date
Cursor AgentandJulius Marminge 487295d5bf Optimize chat composer context updates
Co-authored-by: Julius Marminge <[email protected]>
2026-06-17 16:18:20 +00:00
5 changed files with 211 additions and 25 deletions

No files matched your search

+3 -2
View File
@@ -4903,7 +4903,9 @@ function ChatViewContent(props: ChatViewProps) {
draftId={draftId}
activeThreadId={activeThreadId}
activeThreadEnvironmentId={activeThread?.environmentId}
activeThread={activeThread}
activeThreadSessionProviderInstanceId={
activeThread?.session?.providerInstanceId
}
isServerThread={isServerThread}
isLocalDraftThread={isLocalDraftThread}
phase={phase}
@@ -4932,7 +4934,6 @@ function ChatViewContent(props: ChatViewProps) {
providerStatuses={providerStatuses as ServerProvider[]}
activeProjectDefaultModelSelection={activeProject?.defaultModelSelection}
activeThreadModelSelection={activeThread?.modelSelection}
activeThreadActivities={activeThread?.activities}
resolvedTheme={resolvedTheme}
settings={settings}
keybindings={keybindings}
+20 -23
View File
@@ -111,14 +111,13 @@ import type { UnifiedSettings } from "@t3tools/contracts/settings";
import type { SessionPhase, Thread } from "../../types";
import type { PendingUserInputDraftAnswer } from "../../pendingUserInput";
import type { PendingApproval, PendingUserInput } from "../../session-logic";
import {
deriveLatestContextWindowSnapshot,
formatProviderDisplayName,
} from "../../lib/contextWindow";
import { type ContextWindowSnapshot, formatProviderDisplayName } from "../../lib/contextWindow";
import { formatProviderSkillDisplayName } from "../../providerSkillPresentation";
import { searchProviderSkills } from "../../providerSkillSearch";
import { useMediaQuery } from "../../hooks/useMediaQuery";
import type { ReviewCommentContext } from "../../reviewCommentContext";
import { useStore } from "../../store";
import { createContextWindowSnapshotSelectorByRef } from "../../storeSelectors";
const IMAGE_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / (1024 * 1024))}MB`;
@@ -323,7 +322,7 @@ const ComposerFooterModeControls = memo(function ComposerFooterModeControls(prop
const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(props: {
compact: boolean;
activeContextWindow: ReturnType<typeof deriveLatestContextWindowSnapshot>;
activeContextWindow: ContextWindowSnapshot | null;
activeThreadProviderDisplayName: string | null;
isPreparingWorktree: boolean;
pendingAction: {
@@ -432,7 +431,7 @@ export interface ChatComposerProps {
// Thread context
activeThreadId: ThreadId | null;
activeThreadEnvironmentId: EnvironmentId | undefined;
activeThread: Thread | undefined;
activeThreadSessionProviderInstanceId: ProviderInstanceId | undefined;
isServerThread: boolean;
isLocalDraftThread: boolean;
@@ -481,9 +480,6 @@ export interface ChatComposerProps {
activeProjectDefaultModelSelection: ModelSelection | null | undefined;
activeThreadModelSelection: ModelSelection | null | undefined;
// Context window
activeThreadActivities: Thread["activities"] | undefined;
// Misc
resolvedTheme: "light" | "dark";
settings: UnifiedSettings;
@@ -547,7 +543,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
draftId,
activeThreadId,
activeThreadEnvironmentId: _activeThreadEnvironmentId,
activeThread,
activeThreadSessionProviderInstanceId,
isServerThread: _isServerThread,
isLocalDraftThread: _isLocalDraftThread,
phase,
@@ -576,7 +572,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
providerStatuses,
activeProjectDefaultModelSelection,
activeThreadModelSelection,
activeThreadActivities,
resolvedTheme,
settings,
keybindings,
@@ -663,7 +658,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
);
const selectedProviderByThreadId = composerDraft.activeProvider ?? null;
const threadProvider =
activeThread?.session?.providerInstanceId ??
activeThreadSessionProviderInstanceId ??
activeThreadModelSelection?.instanceId ??
activeProjectDefaultModelSelection?.instanceId ??
null;
@@ -677,16 +672,17 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
) ?? ProviderDriverKind.make("codex");
const selectedProvider: ProviderDriverKind = lockedProvider ?? unlockedSelectedProvider;
const lockedContinuationGroupKey = useMemo((): string | null => {
if (!lockedProvider || !activeThread) return null;
if (!lockedProvider || !activeThreadId) return null;
const lockedInstanceId =
activeThread.session?.providerInstanceId ?? activeThreadModelSelection?.instanceId;
activeThreadSessionProviderInstanceId ?? activeThreadModelSelection?.instanceId;
if (!lockedInstanceId) return null;
return (
providerInstanceEntries.find((entry) => entry.instanceId === lockedInstanceId)
?.continuationGroupKey ?? null
);
}, [
activeThread,
activeThreadId,
activeThreadSessionProviderInstanceId,
activeThreadModelSelection?.instanceId,
lockedProvider,
providerInstanceEntries,
@@ -705,7 +701,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const selectedInstanceId = useMemo<ProviderInstanceId>(() => {
const candidates: Array<string | null | undefined> = [
composerDraft.activeProvider,
activeThread?.session?.providerInstanceId,
activeThreadSessionProviderInstanceId,
activeThreadModelSelection?.instanceId,
activeProjectDefaultModelSelection?.instanceId,
];
@@ -747,7 +743,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
);
}, [
activeProjectDefaultModelSelection?.instanceId,
activeThread?.session?.providerInstanceId,
activeThreadSessionProviderInstanceId,
activeThreadModelSelection?.instanceId,
composerDraft.activeProvider,
explicitSelectedInstanceId,
@@ -841,10 +837,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
// ------------------------------------------------------------------
// Context window
// ------------------------------------------------------------------
const activeContextWindow = useMemo(
() => deriveLatestContextWindowSnapshot(activeThreadActivities ?? []),
[activeThreadActivities],
const contextWindowSelector = useMemo(
() => createContextWindowSnapshotSelectorByRef(routeThreadRef),
[routeThreadRef],
);
const activeContextWindow = useStore(contextWindowSelector);
const activeThreadProviderDisplayName = useMemo(() => {
if (!activeThreadModelSelection) return null;
const entry = providerStatuses.find(
@@ -1969,7 +1966,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
);
},
addTerminalContext: (selection: TerminalContextSelection) => {
if (!activeThread) return;
if (!activeThreadId) return;
const snapshot = composerEditorRef.current?.readSnapshot() ?? {
value: promptRef.current,
cursor: composerCursor,
@@ -1989,7 +1986,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
insertion.prompt,
{
id: randomUUID(),
threadId: activeThread.id,
threadId: activeThreadId,
createdAt: new Date().toISOString(),
...selection,
},
@@ -2019,7 +2016,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
}),
}),
[
activeThread,
activeThreadId,
composerDraftTarget,
composerCursor,
composerTerminalContexts,
+29
View File
@@ -95,6 +95,35 @@ export function deriveLatestContextWindowSnapshot(
return null;
}
export function contextWindowSnapshotsEqual(
left: ContextWindowSnapshot | null,
right: ContextWindowSnapshot | null,
): boolean {
if (left === right) return true;
if (left === null || right === null) return false;
return (
left.usedTokens === right.usedTokens &&
left.totalProcessedTokens === right.totalProcessedTokens &&
left.maxTokens === right.maxTokens &&
left.remainingTokens === right.remainingTokens &&
left.usedPercentage === right.usedPercentage &&
left.remainingPercentage === right.remainingPercentage &&
left.inputTokens === right.inputTokens &&
left.cachedInputTokens === right.cachedInputTokens &&
left.outputTokens === right.outputTokens &&
left.reasoningOutputTokens === right.reasoningOutputTokens &&
left.lastUsedTokens === right.lastUsedTokens &&
left.lastInputTokens === right.lastInputTokens &&
left.lastCachedInputTokens === right.lastCachedInputTokens &&
left.lastOutputTokens === right.lastOutputTokens &&
left.lastReasoningOutputTokens === right.lastReasoningOutputTokens &&
left.toolUses === right.toolUses &&
left.durationMs === right.durationMs &&
left.compactsAutomatically === right.compactsAutomatically &&
left.updatedAt === right.updatedAt
);
}
export function formatContextWindowTokens(value: number | null): string {
if (value === null || !Number.isFinite(value)) {
return "0";
+108
View File
@@ -0,0 +1,108 @@
import {
EnvironmentId,
EventId,
type OrchestrationThreadActivity,
ThreadId,
TurnId,
} from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { type AppState, type EnvironmentState } from "./store";
import { createContextWindowSnapshotSelectorByRef } from "./storeSelectors";
const environmentId = EnvironmentId.make("environment-local");
const threadId = ThreadId.make("thread-1");
const threadRef = { environmentId, threadId };
function makeActivity(id: string, kind: string, payload: unknown): OrchestrationThreadActivity {
return {
id: EventId.make(id),
tone: "info",
kind,
summary: kind,
payload,
turnId: TurnId.make("turn-1"),
createdAt: `2026-06-17T16:00:${id.padStart(2, "0")}.000Z`,
};
}
function makeState(activities: ReadonlyArray<OrchestrationThreadActivity>): AppState {
const environmentState: EnvironmentState = {
projectIds: [],
projectById: {},
threadIds: [threadId],
threadIdsByProjectId: {},
threadShellById: {},
threadSessionById: {},
threadTurnStateById: {},
messageIdsByThreadId: {},
messageByThreadId: {},
activityIdsByThreadId: {
[threadId]: activities.map((activity) => activity.id),
},
activityByThreadId: {
[threadId]: Object.fromEntries(
activities.map((activity) => [activity.id, activity] as const),
) as Record<string, OrchestrationThreadActivity>,
},
proposedPlanIdsByThreadId: {},
proposedPlanByThreadId: {},
turnDiffIdsByThreadId: {},
turnDiffSummaryByThreadId: {},
sidebarThreadSummaryById: {},
bootstrapComplete: true,
};
return {
activeEnvironmentId: environmentId,
environmentStateById: {
[environmentId]: environmentState,
},
};
}
describe("storeSelectors", () => {
it("reuses the context window snapshot when unrelated activities append", () => {
const contextActivity = makeActivity("1", "context-window.updated", {
usedTokens: 42_000,
maxTokens: 258_000,
totalProcessedTokens: 90_000,
});
const selector = createContextWindowSnapshotSelectorByRef(threadRef);
const first = selector(makeState([contextActivity]));
const second = selector(
makeState([contextActivity, makeActivity("2", "tool.completed", { toolName: "profile" })]),
);
expect(first).not.toBeNull();
expect(second).toBe(first);
});
it("returns a new context window snapshot when context usage changes", () => {
const selector = createContextWindowSnapshotSelectorByRef(threadRef);
const first = selector(
makeState([
makeActivity("1", "context-window.updated", {
usedTokens: 42_000,
maxTokens: 258_000,
}),
]),
);
const second = selector(
makeState([
makeActivity("1", "context-window.updated", {
usedTokens: 42_000,
maxTokens: 258_000,
}),
makeActivity("2", "context-window.updated", {
usedTokens: 43_000,
maxTokens: 258_000,
}),
]),
);
expect(first).not.toBeNull();
expect(second).not.toBe(first);
expect(second?.usedTokens).toBe(43_000);
});
});
+51
View File
@@ -1,4 +1,9 @@
import { type ScopedProjectRef, type ScopedThreadRef, type ThreadId } from "@t3tools/contracts";
import {
contextWindowSnapshotsEqual,
deriveLatestContextWindowSnapshot,
type ContextWindowSnapshot,
} from "./lib/contextWindow";
import { selectEnvironmentState, type AppState, type EnvironmentState } from "./store";
import { type Project, type Thread } from "./types";
import { getThreadFromEnvironmentState } from "./threadDerivation";
@@ -45,6 +50,52 @@ export function createThreadSelectorByRef(
return createScopedThreadSelector(() => ref);
}
export function createContextWindowSnapshotSelectorByRef(
ref: ScopedThreadRef | null | undefined,
): (state: AppState) => ContextWindowSnapshot | null {
let previousEnvironmentState: EnvironmentState | undefined;
let previousThreadId: ThreadId | undefined;
let previousActivityIds: readonly string[] | undefined;
let previousSnapshot: ContextWindowSnapshot | null = null;
return (state) => {
if (!ref) {
previousEnvironmentState = undefined;
previousThreadId = undefined;
previousActivityIds = undefined;
previousSnapshot = null;
return null;
}
const environmentState = selectEnvironmentState(state, ref.environmentId);
const activityIds = environmentState.activityIdsByThreadId[ref.threadId];
if (
previousEnvironmentState === environmentState &&
previousThreadId === ref.threadId &&
previousActivityIds === activityIds
) {
return previousSnapshot;
}
const activities =
activityIds?.flatMap((activityId) => {
const activity = environmentState.activityByThreadId[ref.threadId]?.[activityId];
return activity ? [activity] : [];
}) ?? [];
const nextSnapshot = deriveLatestContextWindowSnapshot(activities);
previousEnvironmentState = environmentState;
previousThreadId = ref.threadId;
previousActivityIds = activityIds;
if (contextWindowSnapshotsEqual(previousSnapshot, nextSnapshot)) {
return previousSnapshot;
}
previousSnapshot = nextSnapshot;
return nextSnapshot;
};
}
export function createThreadSelectorAcrossEnvironments(
threadId: ThreadId | null | undefined,
): (state: AppState) => Thread | undefined {