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
9 changed files with 230 additions and 171 deletions

No files matched your search

+6 -130
View File
@@ -1,15 +1,10 @@
import { assert } from "@effect/vitest";
import * as Schema from "effect/Schema";
import { EnvironmentId, type OrchestrationShellSnapshot } from "@t3tools/contracts";
import { beforeEach, describe, it, vi } from "vite-plus/test";
import { EnvironmentId } from "@t3tools/contracts";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
const mocks = vi.hoisted(() => {
const values = new Map<string, string>();
const files = new Map<string, { text: string; deleted: boolean }>();
return {
clear: () => values.clear(),
clearFiles: () => files.clear(),
files,
getItemAsync: vi.fn((key: string) => Promise.resolve(values.get(key) ?? null)),
setItemAsync: vi.fn((key: string, value: string) => {
values.set(key, value);
@@ -18,57 +13,6 @@ const mocks = vi.hoisted(() => {
};
});
vi.mock("expo-file-system", () => ({
Directory: class {
readonly uri: string;
constructor(parent: string, name: string) {
this.uri = `${parent}/${name}`;
}
create(): void {
// Directory creation is idempotent for these storage tests.
}
},
File: class {
readonly uri: string;
constructor(directory: { readonly uri: string }, name: string) {
this.uri = `${directory.uri}/${name}`;
}
get exists(): boolean {
return mocks.files.has(this.uri) && mocks.files.get(this.uri)?.deleted === false;
}
create(): void {
mocks.files.set(this.uri, { text: "", deleted: false });
}
delete(): void {
const entry = mocks.files.get(this.uri);
if (entry) {
entry.deleted = true;
}
}
text(): string {
const entry = mocks.files.get(this.uri);
if (!entry || entry.deleted) {
throw new Error("missing file");
}
return entry.text;
}
write(text: string): void {
mocks.files.set(this.uri, { text, deleted: false });
}
},
Paths: {
document: "document",
},
}));
vi.mock("expo-secure-store", () => ({
getItemAsync: mocks.getItemAsync,
setItemAsync: mocks.setItemAsync,
@@ -86,18 +30,9 @@ vi.mock("./runtime", () => ({
},
}));
import {
loadCachedShellSnapshot,
loadSavedConnections,
saveCachedShellSnapshot,
saveConnection,
type CachedShellSnapshot,
} from "./storage";
import { loadSavedConnections, saveConnection } from "./storage";
import { toStableSavedRemoteConnection } from "./connection";
const decodeUnknownJsonString = Schema.decodeUnknownSync(Schema.UnknownFromJsonString);
const encodeUnknownJsonString = Schema.encodeUnknownSync(Schema.UnknownFromJsonString);
const managedConnection = {
environmentId: EnvironmentId.make("environment-1"),
environmentLabel: "Desktop",
@@ -111,30 +46,9 @@ const managedConnection = {
relayManaged: true,
} as const;
const cacheEnvironmentId = EnvironmentId.make("cache-environment-1");
const otherCacheEnvironmentId = EnvironmentId.make("cache-environment-2");
const cachedSnapshot: OrchestrationShellSnapshot = {
snapshotSequence: 1,
projects: [],
threads: [],
updatedAt: "2026-01-01T00:00:00.000Z",
};
const cacheFileUri = (environmentId: EnvironmentId) =>
`document/shell-snapshots/${encodeURIComponent(environmentId)}.json`;
const writeCachedSnapshotFile = (environmentId: EnvironmentId, document: unknown) => {
mocks.files.set(cacheFileUri(environmentId), {
text: typeof document === "string" ? document : encodeUnknownJsonString(document),
deleted: false,
});
};
describe("mobile connection storage", () => {
beforeEach(() => {
mocks.clear();
mocks.clearFiles();
vi.clearAllMocks();
});
@@ -142,8 +56,8 @@ describe("mobile connection storage", () => {
await saveConnection(managedConnection);
const savedValue = mocks.setItemAsync.mock.calls[0]?.[1];
assert.notEqual(savedValue, undefined);
assert.deepStrictEqual(decodeUnknownJsonString(savedValue ?? ""), {
expect(savedValue).toBeDefined();
expect(JSON.parse(savedValue ?? "")).toEqual({
connections: [toStableSavedRemoteConnection(managedConnection)],
});
});
@@ -151,46 +65,8 @@ describe("mobile connection storage", () => {
it("loads relay-managed connection metadata without a cached access token", async () => {
await saveConnection(managedConnection);
assert.deepStrictEqual(await loadSavedConnections(), [
await expect(loadSavedConnections()).resolves.toEqual([
toStableSavedRemoteConnection(managedConnection),
]);
});
it("loads cached shell snapshots through the schema JSON codec", async () => {
await saveCachedShellSnapshot(cacheEnvironmentId, cachedSnapshot);
const loaded = await loadCachedShellSnapshot(cacheEnvironmentId);
assert.deepStrictEqual(loaded?.snapshot, cachedSnapshot);
assert.equal(loaded?.environmentId, cacheEnvironmentId);
});
it("ignores malformed cached shell snapshot JSON", async () => {
writeCachedSnapshotFile(cacheEnvironmentId, "{");
assert.equal(await loadCachedShellSnapshot(cacheEnvironmentId), null);
});
it("ignores cached shell snapshots with an unsupported schema version", async () => {
writeCachedSnapshotFile(cacheEnvironmentId, {
schemaVersion: 2,
environmentId: cacheEnvironmentId,
snapshotReceivedAt: "2026-01-01T00:00:00.000Z",
snapshot: cachedSnapshot,
});
assert.equal(await loadCachedShellSnapshot(cacheEnvironmentId), null);
});
it("ignores cached shell snapshots written for a different environment", async () => {
const document: CachedShellSnapshot = {
schemaVersion: 1,
environmentId: otherCacheEnvironmentId,
snapshotReceivedAt: "2026-01-01T00:00:00.000Z",
snapshot: cachedSnapshot,
};
writeCachedSnapshotFile(cacheEnvironmentId, document);
assert.equal(await loadCachedShellSnapshot(cacheEnvironmentId), null);
});
});
+4 -9
View File
@@ -35,9 +35,7 @@ const CachedShellSnapshotSchema = Schema.Struct({
snapshotReceivedAt: Schema.String,
snapshot: OrchestrationShellSnapshot,
});
const CachedShellSnapshotJson = Schema.fromJsonString(CachedShellSnapshotSchema);
const decodeCachedShellSnapshotJson = Schema.decodeUnknownOption(CachedShellSnapshotJson);
const encodeCachedShellSnapshotJson = Schema.encodeOption(CachedShellSnapshotJson);
const decodeCachedShellSnapshot = Schema.decodeUnknownOption(CachedShellSnapshotSchema);
async function readStorageItem(key: string): Promise<string | null> {
return await SecureStore.getItemAsync(key);
@@ -82,7 +80,8 @@ export async function loadCachedShellSnapshot(
return null;
}
const decoded = decodeCachedShellSnapshotJson(await file.text());
const parsed = JSON.parse(await file.text()) as unknown;
const decoded = decodeCachedShellSnapshot(parsed);
if (Option.isNone(decoded) || decoded.value.environmentId !== environmentId) {
return null;
}
@@ -107,15 +106,11 @@ export async function saveCachedShellSnapshot(
snapshotReceivedAt: new Date().toISOString(),
snapshot,
};
const encoded = encodeCachedShellSnapshotJson(document);
if (Option.isNone(encoded)) {
return;
}
if (!file.exists) {
file.create({ intermediates: true, overwrite: true });
}
file.write(encoded.value);
file.write(JSON.stringify(document));
} catch {
// Cache persistence is best-effort and should never block live data.
}
+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 {
+4 -3
View File
@@ -1,4 +1,5 @@
import { assert, describe, it } from "@effect/vitest";
import { it } from "@effect/vitest";
import { describe, expect } from "vite-plus/test";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
@@ -44,12 +45,12 @@ describe("makeDrainableWorker", () => {
yield* Deferred.succeed(releaseFirst, undefined);
yield* Deferred.await(secondStarted);
assert.equal(yield* Deferred.isDone(drained), false);
expect(yield* Deferred.isDone(drained)).toBe(false);
yield* Deferred.succeed(releaseSecond, undefined);
yield* Deferred.await(drained);
assert.deepStrictEqual(processed, ["first", "second"]);
expect(processed).toEqual(["first", "second"]);
}),
),
);
@@ -1,4 +1,5 @@
import { assert, describe, it } from "@effect/vitest";
import { it } from "@effect/vitest";
import { describe, expect } from "vite-plus/test";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
@@ -46,12 +47,12 @@ describe("makeKeyedCoalescingWorker", () => {
yield* Deferred.succeed(releaseFirst, undefined);
yield* Deferred.await(secondStarted);
assert.equal(yield* Deferred.isDone(drained), false);
expect(yield* Deferred.isDone(drained)).toBe(false);
yield* Deferred.succeed(releaseSecond, undefined);
yield* Deferred.await(drained);
assert.deepStrictEqual(processed, ["terminal-1:first", "terminal-1:second"]);
expect(processed).toEqual(["terminal-1:first", "terminal-1:second"]);
}),
),
);
@@ -89,7 +90,7 @@ describe("makeKeyedCoalescingWorker", () => {
yield* Deferred.await(secondProcessed);
yield* worker.drainKey("terminal-1");
assert.deepStrictEqual(processed, ["terminal-1:first", "terminal-1:second"]);
expect(processed).toEqual(["terminal-1:first", "terminal-1:second"]);
}),
),
);