Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge 4966d418a8 Format mobile storage tests
Co-authored-by: Julius Marminge <[email protected]>
2026-06-17 16:09:21 +00:00
Cursor AgentandJulius Marminge d8a9e19c24 Use Effect schema JSON for mobile cache
Co-authored-by: Julius Marminge <[email protected]>
2026-06-17 16:06:23 +00:00
9 changed files with 171 additions and 230 deletions

No files matched your search

+130 -6
View File
@@ -1,10 +1,15 @@
import { EnvironmentId } from "@t3tools/contracts";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
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";
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);
@@ -13,6 +18,57 @@ 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,
@@ -30,9 +86,18 @@ vi.mock("./runtime", () => ({
},
}));
import { loadSavedConnections, saveConnection } from "./storage";
import {
loadCachedShellSnapshot,
loadSavedConnections,
saveCachedShellSnapshot,
saveConnection,
type CachedShellSnapshot,
} 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",
@@ -46,9 +111,30 @@ 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();
});
@@ -56,8 +142,8 @@ describe("mobile connection storage", () => {
await saveConnection(managedConnection);
const savedValue = mocks.setItemAsync.mock.calls[0]?.[1];
expect(savedValue).toBeDefined();
expect(JSON.parse(savedValue ?? "")).toEqual({
assert.notEqual(savedValue, undefined);
assert.deepStrictEqual(decodeUnknownJsonString(savedValue ?? ""), {
connections: [toStableSavedRemoteConnection(managedConnection)],
});
});
@@ -65,8 +151,46 @@ describe("mobile connection storage", () => {
it("loads relay-managed connection metadata without a cached access token", async () => {
await saveConnection(managedConnection);
await expect(loadSavedConnections()).resolves.toEqual([
assert.deepStrictEqual(await loadSavedConnections(), [
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);
});
});
+9 -4
View File
@@ -35,7 +35,9 @@ const CachedShellSnapshotSchema = Schema.Struct({
snapshotReceivedAt: Schema.String,
snapshot: OrchestrationShellSnapshot,
});
const decodeCachedShellSnapshot = Schema.decodeUnknownOption(CachedShellSnapshotSchema);
const CachedShellSnapshotJson = Schema.fromJsonString(CachedShellSnapshotSchema);
const decodeCachedShellSnapshotJson = Schema.decodeUnknownOption(CachedShellSnapshotJson);
const encodeCachedShellSnapshotJson = Schema.encodeOption(CachedShellSnapshotJson);
async function readStorageItem(key: string): Promise<string | null> {
return await SecureStore.getItemAsync(key);
@@ -80,8 +82,7 @@ export async function loadCachedShellSnapshot(
return null;
}
const parsed = JSON.parse(await file.text()) as unknown;
const decoded = decodeCachedShellSnapshot(parsed);
const decoded = decodeCachedShellSnapshotJson(await file.text());
if (Option.isNone(decoded) || decoded.value.environmentId !== environmentId) {
return null;
}
@@ -106,11 +107,15 @@ 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(JSON.stringify(document));
file.write(encoded.value);
} catch {
// Cache persistence is best-effort and should never block live data.
}
+2 -3
View File
@@ -4903,9 +4903,7 @@ function ChatViewContent(props: ChatViewProps) {
draftId={draftId}
activeThreadId={activeThreadId}
activeThreadEnvironmentId={activeThread?.environmentId}
activeThreadSessionProviderInstanceId={
activeThread?.session?.providerInstanceId
}
activeThread={activeThread}
isServerThread={isServerThread}
isLocalDraftThread={isLocalDraftThread}
phase={phase}
@@ -4934,6 +4932,7 @@ function ChatViewContent(props: ChatViewProps) {
providerStatuses={providerStatuses as ServerProvider[]}
activeProjectDefaultModelSelection={activeProject?.defaultModelSelection}
activeThreadModelSelection={activeThread?.modelSelection}
activeThreadActivities={activeThread?.activities}
resolvedTheme={resolvedTheme}
settings={settings}
keybindings={keybindings}
+23 -20
View File
@@ -111,13 +111,14 @@ 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 { type ContextWindowSnapshot, formatProviderDisplayName } from "../../lib/contextWindow";
import {
deriveLatestContextWindowSnapshot,
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`;
@@ -322,7 +323,7 @@ const ComposerFooterModeControls = memo(function ComposerFooterModeControls(prop
const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(props: {
compact: boolean;
activeContextWindow: ContextWindowSnapshot | null;
activeContextWindow: ReturnType<typeof deriveLatestContextWindowSnapshot>;
activeThreadProviderDisplayName: string | null;
isPreparingWorktree: boolean;
pendingAction: {
@@ -431,7 +432,7 @@ export interface ChatComposerProps {
// Thread context
activeThreadId: ThreadId | null;
activeThreadEnvironmentId: EnvironmentId | undefined;
activeThreadSessionProviderInstanceId: ProviderInstanceId | undefined;
activeThread: Thread | undefined;
isServerThread: boolean;
isLocalDraftThread: boolean;
@@ -480,6 +481,9 @@ export interface ChatComposerProps {
activeProjectDefaultModelSelection: ModelSelection | null | undefined;
activeThreadModelSelection: ModelSelection | null | undefined;
// Context window
activeThreadActivities: Thread["activities"] | undefined;
// Misc
resolvedTheme: "light" | "dark";
settings: UnifiedSettings;
@@ -543,7 +547,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
draftId,
activeThreadId,
activeThreadEnvironmentId: _activeThreadEnvironmentId,
activeThreadSessionProviderInstanceId,
activeThread,
isServerThread: _isServerThread,
isLocalDraftThread: _isLocalDraftThread,
phase,
@@ -572,6 +576,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
providerStatuses,
activeProjectDefaultModelSelection,
activeThreadModelSelection,
activeThreadActivities,
resolvedTheme,
settings,
keybindings,
@@ -658,7 +663,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
);
const selectedProviderByThreadId = composerDraft.activeProvider ?? null;
const threadProvider =
activeThreadSessionProviderInstanceId ??
activeThread?.session?.providerInstanceId ??
activeThreadModelSelection?.instanceId ??
activeProjectDefaultModelSelection?.instanceId ??
null;
@@ -672,17 +677,16 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
) ?? ProviderDriverKind.make("codex");
const selectedProvider: ProviderDriverKind = lockedProvider ?? unlockedSelectedProvider;
const lockedContinuationGroupKey = useMemo((): string | null => {
if (!lockedProvider || !activeThreadId) return null;
if (!lockedProvider || !activeThread) return null;
const lockedInstanceId =
activeThreadSessionProviderInstanceId ?? activeThreadModelSelection?.instanceId;
activeThread.session?.providerInstanceId ?? activeThreadModelSelection?.instanceId;
if (!lockedInstanceId) return null;
return (
providerInstanceEntries.find((entry) => entry.instanceId === lockedInstanceId)
?.continuationGroupKey ?? null
);
}, [
activeThreadId,
activeThreadSessionProviderInstanceId,
activeThread,
activeThreadModelSelection?.instanceId,
lockedProvider,
providerInstanceEntries,
@@ -701,7 +705,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const selectedInstanceId = useMemo<ProviderInstanceId>(() => {
const candidates: Array<string | null | undefined> = [
composerDraft.activeProvider,
activeThreadSessionProviderInstanceId,
activeThread?.session?.providerInstanceId,
activeThreadModelSelection?.instanceId,
activeProjectDefaultModelSelection?.instanceId,
];
@@ -743,7 +747,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
);
}, [
activeProjectDefaultModelSelection?.instanceId,
activeThreadSessionProviderInstanceId,
activeThread?.session?.providerInstanceId,
activeThreadModelSelection?.instanceId,
composerDraft.activeProvider,
explicitSelectedInstanceId,
@@ -837,11 +841,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
// ------------------------------------------------------------------
// Context window
// ------------------------------------------------------------------
const contextWindowSelector = useMemo(
() => createContextWindowSnapshotSelectorByRef(routeThreadRef),
[routeThreadRef],
const activeContextWindow = useMemo(
() => deriveLatestContextWindowSnapshot(activeThreadActivities ?? []),
[activeThreadActivities],
);
const activeContextWindow = useStore(contextWindowSelector);
const activeThreadProviderDisplayName = useMemo(() => {
if (!activeThreadModelSelection) return null;
const entry = providerStatuses.find(
@@ -1966,7 +1969,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
);
},
addTerminalContext: (selection: TerminalContextSelection) => {
if (!activeThreadId) return;
if (!activeThread) return;
const snapshot = composerEditorRef.current?.readSnapshot() ?? {
value: promptRef.current,
cursor: composerCursor,
@@ -1986,7 +1989,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
insertion.prompt,
{
id: randomUUID(),
threadId: activeThreadId,
threadId: activeThread.id,
createdAt: new Date().toISOString(),
...selection,
},
@@ -2016,7 +2019,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
}),
}),
[
activeThreadId,
activeThread,
composerDraftTarget,
composerCursor,
composerTerminalContexts,
-29
View File
@@ -95,35 +95,6 @@ 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
@@ -1,108 +0,0 @@
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,9 +1,4 @@
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";
@@ -50,52 +45,6 @@ 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 {
+3 -4
View File
@@ -1,5 +1,4 @@
import { it } from "@effect/vitest";
import { describe, expect } from "vite-plus/test";
import { assert, describe, it } from "@effect/vitest";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
@@ -45,12 +44,12 @@ describe("makeDrainableWorker", () => {
yield* Deferred.succeed(releaseFirst, undefined);
yield* Deferred.await(secondStarted);
expect(yield* Deferred.isDone(drained)).toBe(false);
assert.equal(yield* Deferred.isDone(drained), false);
yield* Deferred.succeed(releaseSecond, undefined);
yield* Deferred.await(drained);
expect(processed).toEqual(["first", "second"]);
assert.deepStrictEqual(processed, ["first", "second"]);
}),
),
);
@@ -1,5 +1,4 @@
import { it } from "@effect/vitest";
import { describe, expect } from "vite-plus/test";
import { assert, describe, it } from "@effect/vitest";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
@@ -47,12 +46,12 @@ describe("makeKeyedCoalescingWorker", () => {
yield* Deferred.succeed(releaseFirst, undefined);
yield* Deferred.await(secondStarted);
expect(yield* Deferred.isDone(drained)).toBe(false);
assert.equal(yield* Deferred.isDone(drained), false);
yield* Deferred.succeed(releaseSecond, undefined);
yield* Deferred.await(drained);
expect(processed).toEqual(["terminal-1:first", "terminal-1:second"]);
assert.deepStrictEqual(processed, ["terminal-1:first", "terminal-1:second"]);
}),
),
);
@@ -90,7 +89,7 @@ describe("makeKeyedCoalescingWorker", () => {
yield* Deferred.await(secondProcessed);
yield* worker.drainKey("terminal-1");
expect(processed).toEqual(["terminal-1:first", "terminal-1:second"]);
assert.deepStrictEqual(processed, ["terminal-1:first", "terminal-1:second"]);
}),
),
);