The best way to control Claude Code, Codex and more from any computer or phone
fix(composer): drafts follow model changes made on other clients (#20886)
Co-authored-by: Julius Marminge <julius0216@outlook.com>
Nick Anisimov committed
Oct 20, 2026 at 09:42 UTC
27670129962932046907cddffa4d2d932e905d90
7 files changed
+661
-4
apps/mobile/src/App.tsx
+13
@@ -20,6 +20,9 @@ import {
20
} from "./features/settings/appearance/AppearancePreferencesProvider";
21
import { RootStack } from "./Stack";
22
import { appAtomRegistry } from "./state/atom-registry";
23
+import { subscribeComposerDraftModelReconciliation } from "./state/use-composer-drafts";
24
+import { environmentThreadShells } from "./state/threads";
25
+import { environmentShell } from "./state/shell";
26
import { OverlayPortalHost } from "./components/ui/OverlayPortal";
27
import { shouldHandleAppLink } from "./lib/appLinking";
28
import { useMobileNavigationTheme } from "./lib/useMobileNavigationTheme";
@@ -57,6 +60,16 @@ function SplashScreenCoordinator() {
60
61
export default function App() {
62
useUiRuntimeMemoryWarningGc();
63
+ useEffect(
64
+ () =>
65
+ subscribeComposerDraftModelReconciliation({
66
+ registry: appAtomRegistry,
67
+ threadShellAtom: environmentThreadShells.threadShellAtom,
68
+ threadRefsAtom: environmentThreadShells.threadRefsAtom,
69
+ shellStateAtom: environmentShell.stateAtom,
70
+ }),
71
+ [],
72
+ );
73
74
return (
75
<RegistryContext.Provider value={appAtomRegistry}>
apps/mobile/src/state/use-composer-drafts.test.ts
+219
@@ -1,3 +1,17 @@
1
+import { PrimaryConnectionTarget } from "@t3tools/client-runtime/connection";
2
+import { createEnvironmentThreadShellAtoms } from "@t3tools/client-runtime/state/threads";
3
+import {
4
+ applyShellStreamEvent,
5
+ createEnvironmentSnapshotAtom,
6
+ type EnvironmentShellState,
7
+ type EnvironmentShellStatus,
8
+} from "@t3tools/client-runtime/state/shell";
9
+import {
10
+ v2ShellSnapshot,
11
+ v2ThreadShell,
12
+} from "../../../../packages/client-runtime/src/state/orchestrationV2TestFixtures";
13
+import * as Option from "effect/Option";
14
+import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
15
import { afterEach, describe, expect, it } from "@effect/vitest";
16
import {
17
CommandId,
@@ -7,6 +21,9 @@ import {
21
ProjectId,
22
ProviderInstanceId,
23
ThreadId,
24
+ type OrchestrationV2ThreadShell,
25
+ type OrchestrationV2ShellSnapshot,
26
+ type ModelSelection,
27
} from "@t3tools/contracts";
28
import { onTestFinished, vi } from "vite-plus/test";
29
@@ -162,6 +179,7 @@ import {
179
archiveCloudComposerDrafts,
180
clearComposerDraftContent,
181
clearComposerDraftContentState,
182
+ subscribeComposerDraftModelReconciliation,
183
clearComposerDraftsEnvironment,
184
ComposerDraftPersistenceError,
185
composerDraftsAtom,
@@ -196,6 +214,7 @@ import {
214
stickyComposerModelSelectionAtom,
215
undoComposerDraftMerge,
216
undoComposerDraftMergeState,
217
+ updateComposerDraftSettings,
218
} from "./use-composer-drafts";
219
import { retainComposerAttachmentFileForPreview } from "../lib/composerAttachmentPreviewRetention";
220
@@ -242,6 +261,98 @@ function contextDraft(start: number, count: number): ComposerDraft {
261
};
262
}
263
264
+function modelReconciliationHarness(
265
+ environmentId: EnvironmentId,
266
+ threadId: ThreadId,
267
+ initialStatus: EnvironmentShellStatus = "live",
268
+) {
269
+ const tasks: Array<() => void> = [];
270
+ const registry = AtomRegistry.make({
271
+ scheduleTask: (task) => {
272
+ tasks.push(task);
273
+ return () => {};
274
+ },
275
+ });
276
+ onTestFinished(() => registry.dispose());
277
+ const flush = () => {
278
+ for (let task = tasks.shift(); task !== undefined; task = tasks.shift()) task();
279
+ };
280
+ const selectedThreadId = ThreadId.make("another-selected-thread");
281
+ const initialSnapshot: OrchestrationV2ShellSnapshot = {
282
+ ...v2ShellSnapshot,
283
+ threads: [
284
+ { ...v2ThreadShell, id: threadId },
285
+ { ...v2ThreadShell, id: selectedThreadId },
286
+ ],
287
+ };
288
+ const shellStateAtom = Atom.make<EnvironmentShellState>({
289
+ snapshot: Option.some(initialSnapshot),
290
+ status: initialStatus,
291
+ error: Option.none(),
292
+ });
293
+ const shellResultAtom = Atom.map(shellStateAtom, AsyncResult.success);
294
+ const snapshotAtom = createEnvironmentSnapshotAtom(() => shellResultAtom)(environmentId);
295
+ const catalogValueAtom = Atom.make({
296
+ isReady: true,
297
+ entries: new Map([
298
+ [
299
+ environmentId,
300
+ {
301
+ target: new PrimaryConnectionTarget({
302
+ environmentId,
303
+ label: "Environment",
304
+ httpBaseUrl: "https://example.test",
305
+ wsBaseUrl: "wss://example.test",
306
+ }),
307
+ profile: Option.none(),
308
+ enabled: true,
309
+ },
310
+ ],
311
+ ]),
312
+ });
313
+ const shells = createEnvironmentThreadShellAtoms({
314
+ catalogValueAtom,
315
+ snapshotAtom: () => snapshotAtom,
316
+ });
317
+ const selectedShell = shells.threadShellAtom({ environmentId, threadId: selectedThreadId });
318
+ onTestFinished(registry.mount(selectedShell));
319
+ onTestFinished(
320
+ subscribeComposerDraftModelReconciliation({
321
+ registry,
322
+ threadShellAtom: shells.threadShellAtom,
323
+ threadRefsAtom: shells.threadRefsAtom,
324
+ shellStateAtom: () => shellResultAtom,
325
+ }),
326
+ );
327
+ flush();
328
+ return {
329
+ flush,
330
+ setStatus(status: EnvironmentShellStatus) {
331
+ registry.set(shellStateAtom, { ...registry.get(shellStateAtom), status });
332
+ flush();
333
+ },
334
+ update(changes: Partial<OrchestrationV2ThreadShell>, status?: EnvironmentShellStatus) {
335
+ const state = registry.get(shellStateAtom);
336
+ const snapshot = Option.getOrThrow(state.snapshot);
337
+ registry.set(shellStateAtom, {
338
+ ...state,
339
+ status: status ?? state.status,
340
+ snapshot: Option.some(
341
+ applyShellStreamEvent(snapshot, {
342
+ kind: "thread.updated",
343
+ location: "active",
344
+ sequence: snapshot.snapshotSequence + 1,
345
+ thread: { ...snapshot.threads[0]!, ...changes },
346
+ }),
347
+ ),
348
+ });
349
+ flush();
350
+ expect(registry.get(selectedShell)?.id).toBe(selectedThreadId);
351
+ },
352
+ model: () => registry.get(shells.threadShellAtom({ environmentId, threadId }))!.modelSelection,
353
+ };
354
+}
355
+
356
describe("mobile composer drafts", () => {
357
it("restores a PR checkout source after restarting the composer", () => {
358
const draft: ComposerDraft = {
@@ -428,6 +539,114 @@ describe("mobile composer drafts", () => {
539
expect(draft.text).toContain(String(record?.contextId));
540
});
541
542
+ it("retains a pick matching cached state until the live shell confirms it", () => {
543
+ const environmentId = EnvironmentId.make("environment-1");
544
+ const threadId = ThreadId.make("thread-1");
545
+ const key = `${environmentId}:${threadId}`;
546
+ const h = modelReconciliationHarness(environmentId, threadId, "cached");
547
+ const pick = h.model();
548
+ updateComposerDraftSettings(key, { modelSelection: pick });
549
+ h.flush();
550
+ const before = getComposerDraftSnapshot(key);
551
+ expect(before.modelSelection).toEqual(pick);
552
+
553
+ for (const status of ["empty", "synchronizing", "cached"] as const) {
554
+ h.setStatus(status);
555
+ expect(getComposerDraftSnapshot(key)).toEqual(before);
556
+ }
557
+ h.update({ modelSelection: { ...pick, model: "remote-model" } }, "live");
558
+ expect(getComposerDraftSnapshot(key)).toEqual(before);
559
+ h.update({ modelSelection: pick }, "synchronizing");
560
+ expect(getComposerDraftSnapshot(key)).toEqual(before);
561
+ h.setStatus("live");
562
+ expect(appAtomRegistry.get(composerDraftsAtom)[key]).toBeUndefined();
563
+ });
564
+
565
+ it("releases an inactive thread pick only after its queued model becomes durable", () => {
566
+ const environmentId = EnvironmentId.make("environment-1");
567
+ const threadId = ThreadId.make("thread-1");
568
+ const key = `${environmentId}:${threadId}`;
569
+ const pick = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.5" };
570
+ setComposerDraftText(key, "keep this unsent follow-up");
571
+ appendComposerDraftAttachments(
572
+ key,
573
+ [
574
+ {
575
+ type: "file",
576
+ id: "file",
577
+ name: "notes.txt",
578
+ mimeType: "text/plain",
579
+ sizeBytes: 4,
580
+ fileUri: "file:///notes.txt",
581
+ },
582
+ ],
583
+ { appendReference: true },
584
+ );
585
+ updateComposerDraftSettings(key, {
586
+ modelSelection: pick,
587
+ runtimeMode: "approval-required",
588
+ interactionMode: "plan",
589
+ });
590
+ const before = getComposerDraftSnapshot(key);
591
+ const remoteKey = `environment-remote:${threadId}`;
592
+ updateComposerDraftSettings(remoteKey, { modelSelection: pick });
593
+ const remoteBefore = getComposerDraftSnapshot(remoteKey);
594
+ const h = modelReconciliationHarness(environmentId, threadId);
595
+
596
+ h.update({ status: "queued" });
597
+ expect(getComposerDraftSnapshot(key)).toEqual(before);
598
+ h.update({
599
+ status: "running",
600
+ modelSelection: { ...pick, options: [{ id: "fastMode", value: false }] },
601
+ });
602
+ expect(getComposerDraftSnapshot(key)).toEqual({ ...before, modelSelection: undefined });
603
+ expect(getComposerDraftSnapshot(remoteKey)).toEqual(remoteBefore);
604
+
605
+ h.update({
606
+ modelSelection: {
607
+ instanceId: ProviderInstanceId.make("claudeAgent"),
608
+ model: "claude-opus-5-5",
609
+ },
610
+ });
611
+ expect(getComposerDraftSnapshot(key).modelSelection ?? h.model()).toEqual(h.model());
612
+ expect(getComposerDraftSnapshot(key)).toEqual({ ...before, modelSelection: undefined });
613
+ });
614
+
615
+ it("retains an unavailable provider pick through differing durable model updates", () => {
616
+ const environmentId = EnvironmentId.make("environment-1");
617
+ const threadId = ThreadId.make("thread-1");
618
+ const key = `${environmentId}:${threadId}`;
619
+ const pick: ModelSelection = {
620
+ instanceId: ProviderInstanceId.make("codex-secondary"),
621
+ model: "gpt-5.5",
622
+ options: [
623
+ { id: "reasoningEffort", value: "high" },
624
+ { id: "fastMode", value: true },
625
+ ],
626
+ };
627
+ updateComposerDraftSettings(key, { modelSelection: pick });
628
+ const before = getComposerDraftSnapshot(key);
629
+ const h = modelReconciliationHarness(environmentId, threadId);
630
+ expect(getComposerDraftSnapshot(key)).toEqual(before);
631
+ for (const modelSelection of [
632
+ { ...pick, instanceId: ProviderInstanceId.make("codex") },
633
+ { ...pick, model: "gpt-5.4" },
634
+ { ...pick, options: [{ id: "reasoningEffort", value: "high" }] },
635
+ {
636
+ ...pick,
637
+ options: [
638
+ { id: "reasoningEffort", value: "low" },
639
+ { id: "fastMode", value: true },
640
+ ],
641
+ },
642
+ ]) {
643
+ h.update({ modelSelection });
644
+ expect(getComposerDraftSnapshot(key)).toEqual(before);
645
+ }
646
+ h.update({ modelSelection: { ...pick, options: pick.options!.toReversed() } });
647
+ expect(appAtomRegistry.get(composerDraftsAtom)[key]).toBeUndefined();
648
+ });
649
+
650
it("drops chips and records for attachments a replace no longer keeps", () => {
651
const key = "new-task:draft-1";
652
const kept = {
apps/mobile/src/state/use-composer-drafts.ts
+74
-1
@@ -18,10 +18,18 @@ import {
18
type ProviderInteractionMode,
19
type ProviderOptionSelection,
20
type RuntimeMode,
21
+ type ScopedThreadRef,
22
} from "@t3tools/contracts";
23
import * as Schema from "effect/Schema";
24
import { useEffect } from "react";
24
-import { Atom } from "effect/reactivity";
25
+import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
26
+import * as Option from "effect/Option";
27
+import { parseScopedThreadKey, scopedThreadKey } from "@t3tools/client-runtime/environment";
28
+import type {
29
+ EnvironmentShellState,
30
+ EnvironmentThreadShell,
31
+} from "@t3tools/client-runtime/state/shell";
32
+import { draftModelPickMatchesThread } from "@t3tools/shared/model";
33
34
import { writeFileAtomically } from "../lib/atomic-file";
35
import { createComposerContextHistory, referencedComposerContext } from "../lib/composerContext";
@@ -1460,6 +1468,71 @@ export function updateComposerDraftSettings(
1468
});
1469
}
1470
1471
+export function subscribeComposerDraftModelReconciliation(input: {
1472
+ readonly registry: AtomRegistry.AtomRegistry;
1473
+ readonly threadRefsAtom: Atom.Atom<ReadonlyArray<ScopedThreadRef>>;
1474
+ readonly threadShellAtom: (ref: ScopedThreadRef) => Atom.Atom<EnvironmentThreadShell | null>;
1475
+ readonly shellStateAtom: (
1476
+ environmentId: EnvironmentId,
1477
+ ) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentShellState, unknown>>;
1478
+}): () => void {
1479
+ const draftsAtom = Atom.make(appAtomRegistry.get(composerDraftsAtom));
1480
+ const unsubscribeDrafts = appAtomRegistry.subscribe(composerDraftsAtom, (drafts) =>
1481
+ input.registry.set(draftsAtom, drafts),
1482
+ );
1483
+ const threadKeysAtom = Atom.map(
1484
+ input.threadRefsAtom,
1485
+ (refs) => new Set(refs.map(scopedThreadKey)),
1486
+ );
1487
+ const matchesAtom = Atom.make((get) => {
1488
+ const threadKeys = get(threadKeysAtom);
1489
+ const matches: Array<readonly [string, ComposerDraft]> = [];
1490
+ for (const [key, draft] of Object.entries(get(draftsAtom))) {
1491
+ if (!draft.modelSelection || isNewTaskDraftKey(key) || isQueuedEditDraftKey(key)) continue;
1492
+ const ref = parseScopedThreadKey(key);
1493
+ if (!ref || !threadKeys.has(key)) continue;
1494
+ const thread = get(input.threadShellAtom(ref));
1495
+ if (!thread || !draftModelPickMatchesThread(draft.modelSelection, thread.modelSelection))
1496
+ continue;
1497
+ // Status and selection must come from the same emission; derived atoms can update apart.
1498
+ const shell = Option.getOrNull(
1499
+ AsyncResult.value(get(input.shellStateAtom(ref.environmentId))),
1500
+ );
1501
+ if (shell?.status !== "live") continue;
1502
+ const authoritativeThread = Option.getOrNull(shell.snapshot)?.threads.find(
1503
+ (candidate) => candidate.id === ref.threadId,
1504
+ );
1505
+ if (
1506
+ authoritativeThread &&
1507
+ draftModelPickMatchesThread(draft.modelSelection, authoritativeThread.modelSelection)
1508
+ ) {
1509
+ matches.push([key, draft]);
1510
+ }
1511
+ }
1512
+ return matches;
1513
+ });
1514
+ const unsubscribeMatches = input.registry.subscribe(
1515
+ matchesAtom,
1516
+ (matches) => {
1517
+ if (matches.length === 0) return;
1518
+ updateComposerDrafts((current) => {
1519
+ let next = current;
1520
+ for (const [key, matchedDraft] of matches) {
1521
+ if (next[key] !== matchedDraft) continue;
1522
+ const { modelSelection: _modelSelection, ...draft } = matchedDraft;
1523
+ next = withComposerDraft(next, key, draft);
1524
+ }
1525
+ return next;
1526
+ });
1527
+ },
1528
+ { immediate: true },
1529
+ );
1530
+ return () => {
1531
+ unsubscribeMatches();
1532
+ unsubscribeDrafts();
1533
+ };
1534
+}
1535
+
1536
export function clearComposerDraftContentState(
1537
current: Record<string, ComposerDraft>,
1538
draftKey: string,
apps/web/src/AppRoot.tsx
+16
-1
@@ -1,9 +1,14 @@
1
import { RouterProvider } from "@tanstack/react-router";
2
+import { useEffect } from "react";
3
+
4
+import { subscribeComposerDraftModelReconciliation } from "./composerDraftStore";
5
+import { environmentThreadShells } from "./state/threads";
6
+import { environmentShell } from "./state/shell";
7
8
import { BrowserProfileReporter } from "./browser/BrowserProfileReporter";
9
import { ElectronBrowserHost } from "./browser/ElectronBrowserHost";
10
import { QuitHoldOverlay } from "./components/QuitHoldOverlay";
6
-import { AppAtomRegistryProvider } from "./rpc/atomRegistry";
11
+import { appAtomRegistry, AppAtomRegistryProvider } from "./rpc/atomRegistry";
12
import type { AppRouter } from "./router";
13
14
/**
@@ -12,6 +17,16 @@ import type { AppRouter } from "./router";
17
* as routed UI.
18
*/
19
export function AppRoot({ router }: { readonly router: AppRouter }) {
20
+ useEffect(
21
+ () =>
22
+ subscribeComposerDraftModelReconciliation({
23
+ registry: appAtomRegistry,
24
+ threadShellAtom: environmentThreadShells.threadShellAtom,
25
+ threadRefsAtom: environmentThreadShells.threadRefsAtom,
26
+ shellStateAtom: environmentShell.stateAtom,
27
+ }),
28
+ [],
29
+ );
30
return (
31
<AppAtomRegistryProvider>
32
<RouterProvider router={router} />
apps/web/src/composerDraftStore.test.ts
+245
-1
@@ -1,3 +1,14 @@
1
+import { PrimaryConnectionTarget } from "@t3tools/client-runtime/connection";
2
+import { createEnvironmentThreadShellAtoms } from "@t3tools/client-runtime/state/threads";
3
+import {
4
+ applyShellStreamEvent,
5
+ createEnvironmentSnapshotAtom,
6
+ type EnvironmentShellState,
7
+ type EnvironmentShellStatus,
8
+} from "@t3tools/client-runtime/state/shell";
9
+import { makeThreadProjectionFixture } from "./test-fixtures";
10
+import * as Option from "effect/Option";
11
+import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
12
import {
13
scopedProjectKey,
14
scopedThreadKey,
@@ -5,8 +16,11 @@ import {
16
scopeThreadRef,
17
} from "@t3tools/client-runtime/environment";
18
import * as Schema from "effect/Schema";
19
+import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
20
import {
21
defaultInstanceIdForDriver,
22
+ DEFAULT_MODEL,
23
+ DEFAULT_MODEL_BY_PROVIDER,
24
EnvironmentId,
25
MessageId,
26
ProjectId,
@@ -14,6 +28,8 @@ import {
28
ProviderInstanceId,
29
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
30
ThreadId,
31
+ type OrchestrationV2ThreadShell,
32
+ type OrchestrationV2ShellSnapshot,
33
type ModelSelection,
34
type PreviewAnnotationPayload,
35
type ProviderOptionSelection,
@@ -59,10 +75,12 @@ function selectionsByProvider(
75
}
76
return result;
77
}
62
-import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
78
+import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from "vite-plus/test";
79
80
import {
81
COMPOSER_DRAFT_STORAGE_KEY,
82
+ subscribeComposerDraftModelReconciliation,
83
+ deriveEffectiveComposerModelState,
84
clearComposerDraftsEnvironment,
85
composerDraftHasUserContent,
86
beginBackgroundDraftSubmissionByRef,
@@ -1971,6 +1989,113 @@ describe("composerDraftStore project draft thread mapping", () => {
1989
});
1990
});
1991
1992
+function modelReconciliationHarness(
1993
+ environmentId: EnvironmentId,
1994
+ threadId: ThreadId,
1995
+ initialStatus: EnvironmentShellStatus = "live",
1996
+) {
1997
+ const tasks: Array<() => void> = [];
1998
+ const registry = AtomRegistry.make({
1999
+ scheduleTask: (task) => {
2000
+ tasks.push(task);
2001
+ return () => {};
2002
+ },
2003
+ });
2004
+ onTestFinished(() => registry.dispose());
2005
+ const flush = () => {
2006
+ for (let task = tasks.shift(); task !== undefined; task = tasks.shift()) task();
2007
+ };
2008
+ const selectedThreadId = ThreadId.make("another-selected-thread");
2009
+ const thread: OrchestrationV2ThreadShell = {
2010
+ ...makeThreadProjectionFixture().thread,
2011
+ latestRunId: null,
2012
+ activeRunId: null,
2013
+ status: "idle",
2014
+ pendingRuntimeRequest: null,
2015
+ latestVisibleMessage: null,
2016
+ latestUserMessageAt: null,
2017
+ hasActionableProposedPlan: false,
2018
+ itemCount: 0,
2019
+ visibleItemCount: 0,
2020
+ };
2021
+ const initialSnapshot: OrchestrationV2ShellSnapshot = {
2022
+ schemaVersion: 1,
2023
+ snapshotSequence: 0,
2024
+ projects: [],
2025
+ archivedThreads: [],
2026
+ threads: [
2027
+ { ...thread, id: threadId },
2028
+ { ...thread, id: selectedThreadId },
2029
+ ],
2030
+ };
2031
+ const shellStateAtom = Atom.make<EnvironmentShellState>({
2032
+ snapshot: Option.some(initialSnapshot),
2033
+ status: initialStatus,
2034
+ error: Option.none(),
2035
+ });
2036
+ const shellResultAtom = Atom.map(shellStateAtom, AsyncResult.success);
2037
+ const snapshotAtom = createEnvironmentSnapshotAtom(() => shellResultAtom)(environmentId);
2038
+ const catalogValueAtom = Atom.make({
2039
+ isReady: true,
2040
+ entries: new Map([
2041
+ [
2042
+ environmentId,
2043
+ {
2044
+ target: new PrimaryConnectionTarget({
2045
+ environmentId,
2046
+ label: "Environment",
2047
+ httpBaseUrl: "https://example.test",
2048
+ wsBaseUrl: "wss://example.test",
2049
+ }),
2050
+ profile: Option.none(),
2051
+ enabled: true,
2052
+ },
2053
+ ],
2054
+ ]),
2055
+ });
2056
+ const shells = createEnvironmentThreadShellAtoms({
2057
+ catalogValueAtom,
2058
+ snapshotAtom: () => snapshotAtom,
2059
+ });
2060
+ const selectedShell = shells.threadShellAtom({ environmentId, threadId: selectedThreadId });
2061
+ onTestFinished(registry.mount(selectedShell));
2062
+ onTestFinished(
2063
+ subscribeComposerDraftModelReconciliation({
2064
+ registry,
2065
+ threadShellAtom: shells.threadShellAtom,
2066
+ threadRefsAtom: shells.threadRefsAtom,
2067
+ shellStateAtom: () => shellResultAtom,
2068
+ }),
2069
+ );
2070
+ flush();
2071
+ return {
2072
+ flush,
2073
+ setStatus(status: EnvironmentShellStatus) {
2074
+ registry.set(shellStateAtom, { ...registry.get(shellStateAtom), status });
2075
+ flush();
2076
+ },
2077
+ update(changes: Partial<OrchestrationV2ThreadShell>, status?: EnvironmentShellStatus) {
2078
+ const state = registry.get(shellStateAtom);
2079
+ const snapshot = Option.getOrThrow(state.snapshot);
2080
+ registry.set(shellStateAtom, {
2081
+ ...state,
2082
+ status: status ?? state.status,
2083
+ snapshot: Option.some(
2084
+ applyShellStreamEvent(snapshot, {
2085
+ kind: "thread.updated",
2086
+ location: "active",
2087
+ sequence: snapshot.snapshotSequence + 1,
2088
+ thread: { ...snapshot.threads[0]!, ...changes },
2089
+ }),
2090
+ ),
2091
+ });
2092
+ flush();
2093
+ expect(registry.get(selectedShell)?.id).toBe(selectedThreadId);
2094
+ },
2095
+ model: () => registry.get(shells.threadShellAtom({ environmentId, threadId }))!.modelSelection,
2096
+ };
2097
+}
2098
+
2099
describe("composerDraftStore modelSelection", () => {
2100
const threadId = ThreadId.make("thread-model-options");
2101
const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId);
@@ -1999,6 +2124,125 @@ describe("composerDraftStore modelSelection", () => {
2124
);
2125
});
2126
2127
+ it("retains a pick matching cached state until the live shell confirms it", () => {
2128
+ const h = modelReconciliationHarness(TEST_ENVIRONMENT_ID, threadId, "cached");
2129
+ const pick = h.model();
2130
+ useComposerDraftStore.getState().setModelSelection(threadRef, pick, { explicit: true });
2131
+ h.flush();
2132
+ const before = draftFor(threadId, TEST_ENVIRONMENT_ID);
2133
+ expect(before?.modelSelectionByProvider[pick.instanceId]).toEqual(pick);
2134
+
2135
+ for (const status of ["empty", "synchronizing", "cached"] as const) {
2136
+ h.setStatus(status);
2137
+ expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toEqual(before);
2138
+ }
2139
+ h.update({ modelSelection: { ...pick, model: "remote-model" } }, "live");
2140
+ expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toEqual(before);
2141
+ h.update({ modelSelection: pick }, "synchronizing");
2142
+ expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toEqual(before);
2143
+ h.setStatus("live");
2144
+ expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toBeUndefined();
2145
+ });
2146
+
2147
+ it("releases an inactive thread pick only after its queued model becomes durable", () => {
2148
+ const store = useComposerDraftStore.getState();
2149
+ const pick = modelSelection(CODEX_DRIVER, "gpt-5.5", { fastMode: false });
2150
+ store.setPrompt(threadRef, "keep this unsent follow-up");
2151
+ store.addImage(threadRef, makeImage({ id: "image", previewUrl: "blob:keep-image" }));
2152
+ store.setTerminalContexts(threadRef, [makeTerminalContext({ id: "terminal" })]);
2153
+ store.setRuntimeMode(threadRef, "approval-required");
2154
+ store.setInteractionMode(threadRef, "plan");
2155
+ store.setModelSelection(threadRef, pick, { explicit: true });
2156
+ const before = draftFor(threadId, TEST_ENVIRONMENT_ID)!;
2157
+ const remoteRef = scopeThreadRef(OTHER_TEST_ENVIRONMENT_ID, threadId);
2158
+ store.setModelSelection(remoteRef, pick, { explicit: true });
2159
+ const remoteBefore = draftFor(threadId, OTHER_TEST_ENVIRONMENT_ID);
2160
+ const h = modelReconciliationHarness(TEST_ENVIRONMENT_ID, threadId);
2161
+
2162
+ h.update({ status: "queued" });
2163
+ expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toEqual(before);
2164
+ h.update({ status: "running", modelSelection: modelSelection(CODEX_DRIVER, "gpt-5.5") });
2165
+ expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toEqual({
2166
+ ...before,
2167
+ activeProvider: null,
2168
+ modelSelectionByProvider: {},
2169
+ modelSelectionExplicit: undefined,
2170
+ });
2171
+ expect(draftFor(threadId, OTHER_TEST_ENVIRONMENT_ID)).toEqual(remoteBefore);
2172
+
2173
+ const remoteModel = DEFAULT_MODEL_BY_PROVIDER[CLAUDE_AGENT_DRIVER]!;
2174
+ h.update({ modelSelection: modelSelection(CLAUDE_AGENT_DRIVER, remoteModel) });
2175
+ const effective = deriveEffectiveComposerModelState({
2176
+ draft: draftFor(threadId, TEST_ENVIRONMENT_ID),
2177
+ providers: [
2178
+ {
2179
+ instanceId: CLAUDE_AGENT_INSTANCE,
2180
+ driver: CLAUDE_AGENT_DRIVER,
2181
+ enabled: true,
2182
+ installed: true,
2183
+ version: null,
2184
+ status: "ready",
2185
+ auth: { status: "authenticated" },
2186
+ checkedAt: "2026-01-01T00:00:00.000Z",
2187
+ models: [{ slug: remoteModel, name: remoteModel, isCustom: false, capabilities: {} }],
2188
+ slashCommands: [],
2189
+ skills: [],
2190
+ },
2191
+ ],
2192
+ selectedProvider: CLAUDE_AGENT_DRIVER,
2193
+ selectedInstanceId: CLAUDE_AGENT_INSTANCE,
2194
+ threadModelSelection: h.model(),
2195
+ projectModelSelection: null,
2196
+ settings: DEFAULT_UNIFIED_SETTINGS,
2197
+ });
2198
+ expect(effective.selectedModel).toBe(remoteModel);
2199
+ expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider).toEqual({});
2200
+ });
2201
+
2202
+ it("retains an unavailable provider pick through differing durable model updates", () => {
2203
+ const store = useComposerDraftStore.getState();
2204
+ const pick = createModelSelection(CODEX_SECONDARY_INSTANCE, "gpt-5.5", [
2205
+ { id: "reasoningEffort", value: "high" },
2206
+ { id: "fastMode", value: true },
2207
+ ]);
2208
+ // A remembered primary pick is the visible fallback while the secondary is unavailable.
2209
+ const primary = modelSelection(CODEX_DRIVER, DEFAULT_MODEL);
2210
+ store.setModelSelection(threadRef, primary);
2211
+ store.setModelSelection(threadRef, pick, { explicit: true });
2212
+ const before = draftFor(threadId, TEST_ENVIRONMENT_ID);
2213
+ const h = modelReconciliationHarness(TEST_ENVIRONMENT_ID, threadId);
2214
+ h.update({ modelSelection: primary });
2215
+ const fallback = deriveEffectiveComposerModelState({
2216
+ draft: before,
2217
+ providers: [],
2218
+ selectedProvider: CODEX_DRIVER,
2219
+ selectedInstanceId: CODEX_INSTANCE,
2220
+ threadModelSelection: h.model(),
2221
+ projectModelSelection: null,
2222
+ settings: DEFAULT_UNIFIED_SETTINGS,
2223
+ });
2224
+ expect(fallback.selectedModel).toBe(h.model().model);
2225
+ expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toEqual(before);
2226
+
2227
+ for (const modelSelection of [
2228
+ { ...pick, instanceId: CODEX_INSTANCE },
2229
+ { ...pick, model: "gpt-5.4" },
2230
+ { ...pick, options: [{ id: "reasoningEffort", value: "high" }] },
2231
+ {
2232
+ ...pick,
2233
+ options: [
2234
+ { id: "reasoningEffort", value: "low" },
2235
+ { id: "fastMode", value: true },
2236
+ ],
2237
+ },
2238
+ ]) {
2239
+ h.update({ modelSelection });
2240
+ expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toEqual(before);
2241
+ }
2242
+ h.update({ modelSelection: { ...pick, options: pick.options!.toReversed() } });
2243
+ expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toBeUndefined();
2244
+ });
2245
+
2246
it("keeps default-only model selections on the draft", () => {
2247
const store = useComposerDraftStore.getState();
2248
store.setModelSelection(threadRef, modelSelection(CODEX_DRIVER, "gpt-5.4"));
apps/web/src/composerDraftStore.ts
+80
-1
@@ -37,7 +37,17 @@ import * as Schema from "effect/Schema";
37
import * as Equal from "effect/Equal";
38
import * as Effect from "effect/Effect";
39
import { DeepMutable } from "effect/Types";
40
-import { createModelSelection, normalizeModelSlug } from "@t3tools/shared/model";
40
+import {
41
+ createModelSelection,
42
+ draftModelPickMatchesThread,
43
+ normalizeModelSlug,
44
+} from "@t3tools/shared/model";
45
+import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
46
+import * as Option from "effect/Option";
47
+import type {
48
+ EnvironmentShellState,
49
+ EnvironmentThreadShell,
50
+} from "@t3tools/client-runtime/state/shell";
51
import { getLocalStorageItem } from "./hooks/useLocalStorage";
52
import { readThreadPreviewState } from "./previewStateStore";
53
import { resolveAppModelSelection, resolveAppModelSelectionForInstance } from "./modelSelection";
@@ -4139,6 +4149,75 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
4149
4150
export const useComposerDraftStore = composerDraftStore;
4151
4152
+export function subscribeComposerDraftModelReconciliation(input: {
4153
+ readonly registry: AtomRegistry.AtomRegistry;
4154
+ readonly threadRefsAtom: Atom.Atom<ReadonlyArray<ScopedThreadRef>>;
4155
+ readonly threadShellAtom: (ref: ScopedThreadRef) => Atom.Atom<EnvironmentThreadShell | null>;
4156
+ readonly shellStateAtom: (
4157
+ environmentId: EnvironmentId,
4158
+ ) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentShellState, unknown>>;
4159
+}): () => void {
4160
+ const draftsAtom = Atom.make(composerDraftStore.getState());
4161
+ const unsubscribeDrafts = composerDraftStore.subscribe((state) =>
4162
+ input.registry.set(draftsAtom, state),
4163
+ );
4164
+ const threadKeysAtom = Atom.map(
4165
+ input.threadRefsAtom,
4166
+ (refs) => new Set(refs.map(scopedThreadKey)),
4167
+ );
4168
+ const matchesAtom = Atom.make((get) => {
4169
+ const state = get(draftsAtom);
4170
+ const threadKeys = get(threadKeysAtom);
4171
+ const matches: Array<readonly [string, ComposerThreadDraftState]> = [];
4172
+ for (const [key, draft] of Object.entries(state.draftsByThreadKey)) {
4173
+ // Local drafts can materialize a shell before their first turn is submitted.
4174
+ if (state.draftThreadsByThreadKey[key] || draft.activeProvider === null) continue;
4175
+ const ref = parseScopedThreadKey(key);
4176
+ const pick = draft.modelSelectionByProvider[draft.activeProvider];
4177
+ if (!ref || !pick || !threadKeys.has(key)) continue;
4178
+ const thread = get(input.threadShellAtom(ref));
4179
+ if (!thread || !draftModelPickMatchesThread(pick, thread.modelSelection)) continue;
4180
+ // Status and selection must come from the same emission; derived atoms can update apart.
4181
+ const shell = Option.getOrNull(
4182
+ AsyncResult.value(get(input.shellStateAtom(ref.environmentId))),
4183
+ );
4184
+ if (shell?.status !== "live") continue;
4185
+ const authoritativeThread = Option.getOrNull(shell.snapshot)?.threads.find(
4186
+ (candidate) => candidate.id === ref.threadId,
4187
+ );
4188
+ if (
4189
+ authoritativeThread &&
4190
+ draftModelPickMatchesThread(pick, authoritativeThread.modelSelection)
4191
+ ) {
4192
+ matches.push([key, draft]);
4193
+ }
4194
+ }
4195
+ return matches;
4196
+ });
4197
+ const unsubscribeMatches = input.registry.subscribe(
4198
+ matchesAtom,
4199
+ (matches) => {
4200
+ if (matches.length === 0) return;
4201
+ composerDraftStore.setState((state) => {
4202
+ const drafts = { ...state.draftsByThreadKey };
4203
+ for (const [key, matchedDraft] of matches) {
4204
+ if (drafts[key] !== matchedDraft) continue;
4205
+ const { modelSelectionExplicit: _explicit, ...retained } = matchedDraft;
4206
+ const draft = { ...retained, activeProvider: null, modelSelectionByProvider: {} };
4207
+ if (shouldRemoveDraft(draft)) delete drafts[key];
4208
+ else drafts[key] = draft;
4209
+ }
4210
+ return { draftsByThreadKey: drafts };
4211
+ });
4212
+ },
4213
+ { immediate: true },
4214
+ );
4215
+ return () => {
4216
+ unsubscribeMatches();
4217
+ unsubscribeDrafts();
4218
+ };
4219
+}
4220
+
4221
export function beginBackgroundDraftSubmissionByRef(threadRef: ScopedThreadRef): void {
4222
const threadKey = scopedThreadKey(threadRef);
4223
useComposerDraftStore.setState((state) => ({
packages/shared/src/model.ts
+14
@@ -116,6 +116,20 @@ export function modelSelectionsEqual(left: ModelSelection, right: ModelSelection
116
);
117
}
118
119
+/**
120
+ * Whether a composer's draft model pick is what the thread already runs. Web sends
121
+ * `fastMode: false` for models with a fast toggle while mobile omits it, so off counts as unset.
122
+ */
123
+export function draftModelPickMatchesThread(pick: ModelSelection, thread: ModelSelection): boolean {
124
+ const withoutFastModeOff = (selection: ModelSelection) =>
125
+ createModelSelection(
126
+ selection.instanceId,
127
+ selection.model,
128
+ selection.options?.filter((option) => option.id !== "fastMode" || option.value !== false),
129
+ );
130
+ return modelSelectionsEqual(withoutFastModeOff(pick), withoutFastModeOff(thread));
131
+}
132
+
133
function resolveDescriptorChoiceValue(
134
descriptor: Extract<ProviderOptionDescriptor, { type: "select" }>,
135
raw: string | null | undefined,