Skip to content

Commit 727d4f6

Browse files
committed
refactor(mobile): reuse composer persistence for model options
1 parent b40d567 commit 727d4f6

8 files changed

Lines changed: 105 additions & 297 deletions

File tree

‎apps/mobile/src/features/threads/new-task-flow-provider.tsx‎

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,6 @@ import {
6060
flushPendingTaskEditorWrite,
6161
} from "../../state/pending-task-editor-writes";
6262
import {
63-
ensureModelOptionMemoryLoaded,
6463
rememberModelOptions,
6564
withRememberedModelOptions,
6665
} from "../../state/use-model-option-memory";
@@ -209,9 +208,6 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
209208
const groupingSettings = useMobileProjectGroupingSettings();
210209
const { enabled: planModeEnabled, loaded: planModePreferenceLoaded } = useLegacyPlanModeState();
211210

212-
useEffect(() => {
213-
ensureModelOptionMemoryLoaded();
214-
}, []);
215211
const projectScopes = useMemo(
216212
() =>
217213
sortHomeProjectScopes({

‎apps/mobile/src/features/updates/app-updates.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -465,7 +465,6 @@ async function defaultFlushPendingWrites(): Promise<void> {
465465
// store cannot keep the others from landing.
466466
const results = await Promise.allSettled([
467467
import("../../state/use-composer-drafts").then((drafts) => drafts.flushComposerDrafts()),
468-
import("../../state/use-model-option-memory").then((memory) => memory.flushModelOptionMemory()),
469468
import("../../state/thread-outbox").then((outbox) => outbox.flushThreadOutbox()),
470469
]);
471470
const failed = results.find(

‎apps/mobile/src/state/use-composer-drafts.test.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,7 @@ import {
133133
flushComposerDrafts,
134134
getComposerDraftSnapshot,
135135
mergeComposerDraftContentState,
136+
modelOptionMemoryAtom,
136137
releaseUnusedComposerAttachmentFiles,
137138
removeComposerDraftsForEnvironment,
138139
resetComposerDraftsLoadState,
@@ -164,6 +165,7 @@ afterEach(() => {
164165
appAtomRegistry.set(composerDraftsAtom, {});
165166
appAtomRegistry.set(composerCloudDraftsAtom, { accountId: null, signedOut: {} });
166167
appAtomRegistry.set(stickyComposerModelSelectionAtom, null);
168+
appAtomRegistry.set(modelOptionMemoryAtom, {});
167169
appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, {});
168170
composerAttachmentCleanupMocks.remove.mockClear();
169171
composerAttachmentCleanupMocks.releaseUploads.mockReset();
@@ -958,6 +960,44 @@ describe("mobile composer drafts", () => {
958960
});
959961
});
960962

963+
it("decodes model option memory from the composer document", () => {
964+
expect(
965+
decodePersistedComposerState({
966+
schemaVersion: 1,
967+
drafts: {},
968+
modelOptionMemory: {
969+
pi: { "xai/grok-4.6": [{ id: "thinking", value: "xhigh" }] },
970+
},
971+
}).modelOptionMemory,
972+
).toEqual({ pi: { "xai/grok-4.6": [{ id: "thinking", value: "xhigh" }] } });
973+
});
974+
975+
it("merges persisted option memory without replacing newer choices", async () => {
976+
composerDraftFileMocks.setDocument({
977+
schemaVersion: 1,
978+
drafts: {},
979+
modelOptionMemory: {
980+
pi: {
981+
"xai/grok-4.6": [{ id: "thinking", value: "high" }],
982+
"openai/gpt-5.4": [{ id: "thinking", value: "medium" }],
983+
},
984+
},
985+
});
986+
appAtomRegistry.set(modelOptionMemoryAtom, {
987+
pi: { "xai/grok-4.6": [{ id: "thinking", value: "xhigh" }] },
988+
});
989+
990+
ensureComposerDraftsLoaded();
991+
await waitForComposerDraftsLoaded();
992+
993+
expect(appAtomRegistry.get(modelOptionMemoryAtom)).toEqual({
994+
pi: {
995+
"xai/grok-4.6": [{ id: "thinking", value: "xhigh" }],
996+
"openai/gpt-5.4": [{ id: "thinking", value: "medium" }],
997+
},
998+
});
999+
});
1000+
9611001
it("waits for hydration before persisting the latest composer state", async () => {
9621002
vi.useFakeTimers();
9631003
composerDraftFileMocks.setDocument({

‎apps/mobile/src/state/use-composer-drafts.ts‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,12 @@ import {
33
ModelSelection as ModelSelectionSchema,
44
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
55
ProviderInteractionMode as ProviderInteractionModeSchema,
6+
ProviderOptionSelection as ProviderOptionSelectionSchema,
67
RuntimeMode as RuntimeModeSchema,
78
type EnvironmentId,
89
type ModelSelection,
910
type ProviderInteractionMode,
11+
type ProviderOptionSelection,
1012
type RuntimeMode,
1113
} from "@t3tools/contracts";
1214
import * as Schema from "effect/Schema";
@@ -100,6 +102,12 @@ const PersistedComposerDraftsSchema = Schema.Struct({
100102
schemaVersion: Schema.Literal(COMPOSER_DRAFTS_SCHEMA_VERSION),
101103
drafts: Schema.Record(Schema.String, ComposerDraftSchema),
102104
stickyModelSelection: Schema.optional(ModelSelectionSchema),
105+
modelOptionMemory: Schema.optional(
106+
Schema.Record(
107+
Schema.String,
108+
Schema.Record(Schema.String, Schema.Array(ProviderOptionSelectionSchema)),
109+
),
110+
),
103111
cloudAccountId: Schema.optional(Schema.String),
104112
signedOutDrafts: Schema.optional(
105113
Schema.Record(
@@ -131,6 +139,15 @@ export const stickyComposerModelSelectionAtom = Atom.make<ModelSelection | null>
131139
Atom.withLabel("mobile:sticky-composer-model-selection"),
132140
);
133141

142+
export type ModelOptionMemoryState = Readonly<
143+
Record<string, Readonly<Record<string, ReadonlyArray<ProviderOptionSelection>>>>
144+
>;
145+
146+
export const modelOptionMemoryAtom = Atom.make<ModelOptionMemoryState>({}).pipe(
147+
Atom.keepAlive,
148+
Atom.withLabel("mobile:model-option-memory"),
149+
);
150+
134151
interface SignedOutDrafts {
135152
readonly drafts: Record<string, ComposerDraft>;
136153
readonly queuedMessages: ReadonlyArray<QueuedThreadMessage>;
@@ -188,6 +205,7 @@ function isEmptyDraft(draft: ComposerDraft): boolean {
188205
export function decodePersistedComposerState(value: unknown): {
189206
readonly drafts: Record<string, ComposerDraft>;
190207
readonly stickyModelSelection: ModelSelection | null;
208+
readonly modelOptionMemory: ModelOptionMemoryState;
191209
readonly cloudDrafts: ComposerCloudDraftState;
192210
} {
193211
const parsed = decodePersistedComposerDraftsDocument(value);
@@ -221,6 +239,7 @@ export function decodePersistedComposerState(value: unknown): {
221239
.filter(([, draft]) => !isEmptyDraft(draft) || (draft.importedShareIds?.length ?? 0) > 0),
222240
),
223241
stickyModelSelection: parsed.stickyModelSelection ?? null,
242+
modelOptionMemory: parsed.modelOptionMemory ?? {},
224243
cloudDrafts: {
225244
accountId: parsed.cloudAccountId ?? null,
226245
signedOut: Object.fromEntries(
@@ -257,6 +276,7 @@ async function loadPersistedComposerState(): Promise<
257276
return {
258277
drafts: {},
259278
stickyModelSelection: null,
279+
modelOptionMemory: {},
260280
cloudDrafts: { accountId: null, signedOut: {} },
261281
};
262282
}
@@ -277,6 +297,7 @@ async function loadPersistedComposerState(): Promise<
277297
return {
278298
drafts: {},
279299
stickyModelSelection: null,
300+
modelOptionMemory: {},
280301
cloudDrafts: { accountId: null, signedOut: {} },
281302
};
282303
}
@@ -298,6 +319,9 @@ async function writePersistedComposerState(
298319
schemaVersion: COMPOSER_DRAFTS_SCHEMA_VERSION,
299320
drafts: nonEmptyDrafts,
300321
...(stickyModelSelection ? { stickyModelSelection } : {}),
322+
...(Object.keys(appAtomRegistry.get(modelOptionMemoryAtom)).length > 0
323+
? { modelOptionMemory: appAtomRegistry.get(modelOptionMemoryAtom) }
324+
: {}),
301325
...(cloudDrafts.accountId ? { cloudAccountId: cloudDrafts.accountId } : {}),
302326
...(Object.keys(cloudDrafts.signedOut).length > 0
303327
? {
@@ -528,7 +552,7 @@ export function retainComposerAttachmentFileForPreview(
528552
});
529553
}
530554

531-
function schedulePersistComposerState(): void {
555+
export function schedulePersistComposerState(): void {
532556
if (persistTimer !== null) {
533557
clearTimeout(persistTimer);
534558
}
@@ -574,6 +598,18 @@ export function ensureComposerDraftsLoaded(): void {
574598
) {
575599
appAtomRegistry.set(stickyComposerModelSelectionAtom, persisted.stickyModelSelection);
576600
}
601+
if (Object.keys(persisted.modelOptionMemory).length > 0) {
602+
const current = appAtomRegistry.get(modelOptionMemoryAtom);
603+
appAtomRegistry.set(modelOptionMemoryAtom, {
604+
...persisted.modelOptionMemory,
605+
...Object.fromEntries(
606+
Object.entries(current).map(([instanceId, models]) => [
607+
instanceId,
608+
{ ...(persisted.modelOptionMemory[instanceId] ?? {}), ...models },
609+
]),
610+
),
611+
});
612+
}
577613
})
578614
.catch((cause) => {
579615
console.warn(
Lines changed: 16 additions & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,9 @@
1-
import { afterEach, describe, expect, it } from "@effect/vitest";
1+
import { afterEach, beforeEach, describe, expect, it } from "@effect/vitest";
22
import { vi } from "vite-plus/test";
33

4-
const memoryFileMocks = vi.hoisted(() => {
5-
let document = "";
6-
return {
7-
getDocument() {
8-
return document;
9-
},
10-
setDocument(value: unknown) {
11-
document = JSON.stringify(value);
12-
},
13-
Directory: class {
14-
create() {}
15-
},
16-
File: class {
17-
exists = true;
18-
parentDirectory = null;
19-
20-
create() {}
21-
22-
moveSync() {}
23-
24-
async text() {
25-
return document;
26-
}
27-
28-
write(value: string) {
29-
document = value;
30-
}
31-
},
32-
};
33-
});
34-
35-
vi.mock("expo-file-system", () => ({
36-
Directory: memoryFileMocks.Directory,
37-
File: memoryFileMocks.File,
38-
Paths: { document: "/documents" },
39-
}));
40-
414
import { appAtomRegistry } from "./atom-registry";
5+
import { modelOptionMemoryAtom } from "./use-composer-drafts";
426
import {
43-
flushModelOptionMemory,
44-
lookupModelOptionsInState,
45-
mergeModelOptionMemoryState,
46-
modelOptionMemoryAtom,
47-
recordModelOptionsInState,
487
rememberModelOptions,
498
rememberedModelOptions,
509
withRememberedModelOptions,
@@ -53,33 +12,28 @@ import {
5312
const XHIGH = [{ id: "thinking", value: "xhigh" }] as const;
5413
const HIGH = [{ id: "thinking", value: "high" }] as const;
5514

56-
afterEach(async () => {
57-
await flushModelOptionMemory();
15+
beforeEach(() => {
16+
vi.useFakeTimers();
17+
});
18+
19+
afterEach(() => {
20+
vi.clearAllTimers();
21+
vi.useRealTimers();
5822
appAtomRegistry.set(modelOptionMemoryAtom, {});
5923
});
6024

6125
describe("model option memory state", () => {
6226
it("records and looks up options per instance and model", () => {
63-
let state = recordModelOptionsInState({}, "codex", "gpt-5.3-codex", [...XHIGH]);
64-
state = recordModelOptionsInState(state, "codex", "gpt-5.4", [...HIGH]);
65-
expect(lookupModelOptionsInState(state, "codex", "gpt-5.3-codex")).toEqual(XHIGH);
66-
expect(lookupModelOptionsInState(state, "codex", "gpt-5.4")).toEqual(HIGH);
67-
expect(lookupModelOptionsInState(state, "pi", "gpt-5.3-codex")).toBeUndefined();
27+
rememberModelOptions("codex", "gpt-5.3-codex", [...XHIGH]);
28+
rememberModelOptions("codex", "gpt-5.4", [...HIGH]);
29+
expect(rememberedModelOptions("codex", "gpt-5.3-codex")).toEqual(XHIGH);
30+
expect(rememberedModelOptions("codex", "gpt-5.4")).toEqual(HIGH);
31+
expect(rememberedModelOptions("pi", "gpt-5.3-codex")).toBeUndefined();
6832
});
6933

7034
it("ignores empty option sets when recording", () => {
71-
const state = recordModelOptionsInState({}, "codex", "gpt-5.4", []);
72-
expect(state).toEqual({});
73-
expect(lookupModelOptionsInState(state, "codex", "gpt-5.4")).toBeUndefined();
74-
});
75-
76-
it("keeps persisted models when current choices share an instance", () => {
77-
expect(
78-
mergeModelOptionMemoryState(
79-
{ codex: { "gpt-5.3-codex": XHIGH, "gpt-5.4": HIGH } },
80-
{ codex: { "gpt-5.4": XHIGH } },
81-
),
82-
).toEqual({ codex: { "gpt-5.3-codex": XHIGH, "gpt-5.4": XHIGH } });
35+
rememberModelOptions("codex", "gpt-5.4", []);
36+
expect(rememberedModelOptions("codex", "gpt-5.4")).toBeUndefined();
8337
});
8438
});
8539

@@ -106,23 +60,3 @@ describe("withRememberedModelOptions", () => {
10660
expect(withRememberedModelOptions(selection)).toBe(selection);
10761
});
10862
});
109-
110-
describe("model option memory persistence", () => {
111-
it("round-trips recorded memory through the persisted document", async () => {
112-
memoryFileMocks.setDocument({ schemaVersion: 1, byInstance: {} });
113-
114-
rememberModelOptions("pi", "xai/grok-4.6", [...XHIGH]);
115-
await flushModelOptionMemory();
116-
117-
expect(JSON.parse(memoryFileMocks.getDocument())).toEqual({
118-
schemaVersion: 1,
119-
byInstance: { pi: { "xai/grok-4.6": XHIGH } },
120-
});
121-
122-
// Simulate an app restart: the loader sets the atom from the document.
123-
appAtomRegistry.set(modelOptionMemoryAtom, {});
124-
const parsed = JSON.parse(memoryFileMocks.getDocument());
125-
appAtomRegistry.set(modelOptionMemoryAtom, parsed.byInstance);
126-
expect(rememberedModelOptions("pi", "xai/grok-4.6")).toEqual(XHIGH);
127-
});
128-
});

0 commit comments

Comments
 (0)