@devries-cameron20 / t3code-1 / commits / 402d0623d5
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(composer): persist model picks before the next message (#31739)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

shivam committed Nov 9, 2026 at 15:14 UTC 402d0623d5f4160859607e9b7c11fc829fbe3e18
19 files changed +382 -40
apps/mobile/src/App.tsx
+2 -1
@@ -49,7 +49,7 @@ import {
49 import { RootStack, rootPathnameFromState, workspaceLocationFromState } from "./Stack";
50 import { appAtomRegistry } from "./state/atom-registry";
51 import { subscribeComposerDraftModelReconciliation } from "./state/use-composer-drafts";
52 -import { environmentThreadShells } from "./state/threads";
52 +import { environmentThreadShells, threadEnvironment } from "./state/threads";
53 import { environmentShell } from "./state/shell";
54 import { OverlayPortalHost } from "./components/ui/OverlayPortal";
55 import { shouldHandleAppLink, restoreDraftLinkState } from "./lib/appLinking";
@@ -187,6 +187,7 @@ const appServiceDisposers = [
187 threadShellAtom: environmentThreadShells.threadShellAtom,
188 threadRefsAtom: environmentThreadShells.threadRefsAtom,
189 shellStateAtom: environmentShell.stateAtom,
190 + pendingThreadIdsAtom: threadEnvironment.pendingThreadIdsAtom,
191 }),
192 installAppearanceRuntime(),
193 installSubscriptionUsageRefresh(),
apps/mobile/src/features/threads/ThreadSettingsSheet.tsx
+2 -2
@@ -88,7 +88,7 @@ import {
88 } from "../../state/use-composer-drafts";
89 import { useQuietThreadStructure } from "../../state/use-thread-detail";
90 import { activeComposerDraftKey, useQueuedRunEdit } from "../../state/queued-run-edit";
91 -import { updateThreadDraftModelSelection } from "../../state/use-thread-composer-state";
91 +import { selectThreadModel } from "../../state/thread-model-selection";
92 import { useThreadSelection } from "../../state/use-thread-selection";
93 import { threadAllowsProviderSwitch } from "../../state/thread-provider-switching";
94 import { environmentServerConfigsAtom, serverEnvironment } from "../../state/server";
@@ -1338,7 +1338,7 @@ export function ExistingThreadSettingsRouteScreen({
1338 option.selection.model === modelSelection.model,
1339 ) ?? null;
1340 const updateModelSelection = (selection: ModelSelection) =>
1341 - updateThreadDraftModelSelection(threadKey, selection);
1341 + selectThreadModel(route.params, selection);
1342
1343 return (
1344 <ThreadSettingsPickerScreen
apps/mobile/src/state/thread-model-selection.ts new
+54
@@ -0,0 +1,54 @@
1 +import { runAtomCommand, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
2 +import {
3 + AuthOrchestrationOperateScope,
4 + type EnvironmentId,
5 + type ModelSelection,
6 + type ThreadId,
7 +} from "@t3tools/contracts";
8 +
9 +import { scopedThreadKey } from "../lib/scopedEntities";
10 +import * as Dialog from "../components/ui/Dialog";
11 +import { appAtomRegistry } from "./atom-registry";
12 +import { readEnvironmentScope } from "./session";
13 +import { environmentThreadShells, threadEnvironment } from "./threads";
14 +import {
15 + releaseComposerDraftModelSelection,
16 + updateComposerDraftSettings,
17 +} from "./use-composer-drafts";
18 +
19 +/** Sets an existing thread's pick on the thread, so any next turn runs on it. */
20 +export function selectThreadModel(
21 + ref: { readonly environmentId: EnvironmentId; readonly threadId: ThreadId },
22 + value: ModelSelection,
23 +): void {
24 + const threadKey = scopedThreadKey(ref.environmentId, ref.threadId);
25 + // Its own object, so an older reply for an equal pick cannot release this one.
26 + const modelSelection = { ...value };
27 + updateComposerDraftSettings(threadKey, { modelSelection });
28 + const thread = appAtomRegistry.get(environmentThreadShells.threadShellAtom(ref));
29 + // Another instance replaces the live session, which may hold an open question; that pick
30 + // still waits for a sent message.
31 + if (
32 + thread?.modelSelection.instanceId !== modelSelection.instanceId ||
33 + !readEnvironmentScope(ref.environmentId, AuthOrchestrationOperateScope)
34 + ) {
35 + return;
36 + }
37 + void runAtomCommand(
38 + appAtomRegistry,
39 + threadEnvironment.setModelSelection,
40 + { environmentId: ref.environmentId, input: { threadId: ref.threadId, modelSelection } },
41 + { label: "change model", reportFailure: true, reportDefect: true },
42 + ).then((result) => {
43 + // Released on the reply, so a later change from another client shows.
44 + if (result._tag === "Success") {
45 + releaseComposerDraftModelSelection(threadKey, modelSelection);
46 + } else {
47 + const error = squashAtomCommandFailure(result);
48 + Dialog.alert(
49 + "Could not apply model selection",
50 + `This model pick was not saved. ${error instanceof Error ? error.message : "Try again."}`,
51 + );
52 + }
53 + });
54 +}
apps/mobile/src/state/use-composer-drafts.test.ts
+2
@@ -310,6 +310,7 @@ function modelReconciliationHarness(
310 ],
311 ]),
312 });
313 + const noPendingThreadIdsAtom = Atom.make((): ReadonlySet<ThreadId> => new Set());
314 const shells = createEnvironmentThreadShellAtoms({
315 catalogValueAtom,
316 snapshotAtom: () => snapshotAtom,
@@ -323,6 +324,7 @@ function modelReconciliationHarness(
324 threadShellAtom: shells.threadShellAtom,
325 threadRefsAtom: shells.threadRefsAtom,
326 shellStateAtom: () => shellResultAtom,
327 + pendingThreadIdsAtom: () => noPendingThreadIdsAtom,
328 }),
329 );
330 flush();
apps/mobile/src/state/use-composer-drafts.ts
+18
@@ -19,6 +19,7 @@ import {
19 type ProviderOptionSelection,
20 type RuntimeMode,
21 type ScopedThreadRef,
22 + type ThreadId,
23 } from "@t3tools/contracts";
24 import * as Schema from "effect/Schema";
25 import { useEffect, useState } from "react";
@@ -1541,6 +1542,20 @@ export function updateComposerDraftSettings(
1542 });
1543 }
1544
1545 +/** Lets the thread's model show again once the server accepted this exact pick. */
1546 +export function releaseComposerDraftModelSelection(
1547 + draftKey: string,
1548 + modelSelection: ModelSelection,
1549 +): void {
1550 + updateComposerDrafts((current) => {
1551 + const existing = current[draftKey];
1552 + // A newer pick, even of the same model, is still waiting for its own reply.
1553 + if (existing?.modelSelection !== modelSelection) return current;
1554 + const { modelSelection: _modelSelection, ...draft } = existing;
1555 + return withComposerDraft(current, draftKey, draft);
1556 + });
1557 +}
1558 +
1559 export function setFreshSessionPending(draftKey: string, pending: boolean): void {
1560 if ((getComposerDraftSnapshot(draftKey).freshContext === true) === pending) return;
1561 updateComposerDraftSettings(draftKey, { freshContext: pending ? true : undefined });
@@ -1557,6 +1572,7 @@ export function subscribeComposerDraftModelReconciliation(input: {
1572 readonly shellStateAtom: (
1573 environmentId: EnvironmentId,
1574 ) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentShellState, unknown>>;
1575 + readonly pendingThreadIdsAtom: (environmentId: EnvironmentId) => Atom.Atom<ReadonlySet<ThreadId>>;
1576 }): () => void {
1577 const draftsAtom = Atom.make(appAtomRegistry.get(composerDraftsAtom));
1578 const unsubscribeDrafts = appAtomRegistry.subscribe(composerDraftsAtom, (drafts) =>
@@ -1576,6 +1592,8 @@ export function subscribeComposerDraftModelReconciliation(input: {
1592 const thread = get(input.threadShellAtom(ref));
1593 if (!thread || !draftModelPickMatchesThread(draft.modelSelection, thread.modelSelection))
1594 continue;
1595 + // The pick can match an old model while an earlier pick in flight still replaces it.
1596 + if (get(input.pendingThreadIdsAtom(ref.environmentId)).has(ref.threadId)) continue;
1597 // Status and selection must come from the same emission; derived atoms can update apart.
1598 const shell = AsyncResult.getOrElse(get(input.shellStateAtom(ref.environmentId)), () => null);
1599 if (shell?.status !== "live") continue;
apps/mobile/src/state/use-thread-composer-state.ts
-5
@@ -79,7 +79,6 @@ import {
79 scheduleUnusedComposerAttachmentCleanup,
80 setComposerDraftText,
81 setFreshSessionPending,
82 - updateComposerDraftSettings,
82 useComposerDraft,
83 useComposerDraftSettings,
84 } from "./use-composer-drafts";
@@ -178,10 +177,6 @@ export function useThreadDraftForThread(input: {
177 };
178 }
179
181 -export function updateThreadDraftModelSelection(threadKey: string, value: ModelSelection): void {
182 - updateComposerDraftSettings(threadKey, { modelSelection: value });
183 -}
184 -
180 export function useThreadComposerState(input: {
181 /** Forks the thread into a side chat that gets `prompt`; resolves false when it did not start. */
182 readonly startSideChat: (
apps/web/src/appInit.tsx
+2 -1
@@ -54,7 +54,7 @@ import { installChatRouteCommands } from "./shortcuts/chatRouteCommands";
54 import { startWorkspaceFocus } from "./lib/workspaceFocus";
55 import { installCommandPaletteCommands } from "./shortcuts/commandPaletteCommands";
56 import { registerOpenFavoriteEditorCommand } from "./components/chat/OpenInPickerShortcut";
57 -import { environmentThreadShells } from "./state/threads";
57 +import { environmentThreadShells, threadEnvironment } from "./state/threads";
58 import { resolveThreadRouteTarget } from "./threadRoutes";
59
60 /** Writes appearance settings onto the document, touching only the groups that changed. */
@@ -205,6 +205,7 @@ export function startAppServices(): AppRouter {
205 threadShellAtom: environmentThreadShells.threadShellAtom,
206 threadRefsAtom: environmentThreadShells.threadRefsAtom,
207 shellStateAtom: environmentShell.stateAtom,
208 + pendingThreadIdsAtom: threadEnvironment.pendingThreadIdsAtom,
209 });
210 startMainAppLocationTracking(router);
211 startWorkspaceFocus(router);
apps/web/src/components/ChatView.modelPick.browser.test.tsx new
+67
@@ -0,0 +1,67 @@
1 +import { createMemoryHistory } from "@tanstack/react-router";
2 +import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
3 +import type * as Context from "effect/Context";
4 +import { expect, it, vi } from "vite-plus/test";
5 +import { page } from "vite-plus/test/browser";
6 +
7 +import { AppRoot } from "~/AppRoot";
8 +// The route loads ChatView lazily, and its first transform (React Compiler over ~4k lines)
9 +// takes 6-11s; importing it here keeps that out of the test's timeout.
10 +import "~/components/ChatView";
11 +import { __setClientSettingsForTests } from "~/hooks/useSettings";
12 +import { getRouter } from "~/router";
13 +import {
14 + ENVIRONMENT_ID,
15 + dispatchedCommands,
16 + installFakeEnvironment,
17 + threadWithHistory,
18 + type FakeDriver,
19 +} from "../../test/fakeEnvironment";
20 +import { render } from "../../test/render";
21 +
22 +// The socket is the only fake layer; see test/appScenarios.renders.tsx.
23 +vi.mock("../../../../packages/client-runtime/src/connection/driver.ts", async (importOriginal) => {
24 + const [actual, { fakeDriver }, Layer] = await Promise.all([
25 + importOriginal<{ readonly ConnectionDriver: Context.Key<unknown, FakeDriver> }>(),
26 + import("../../test/fakeEnvironment"),
27 + import("effect/Layer"),
28 + ]);
29 + return { ...actual, layer: Layer.succeed(actual.ConnectionDriver, fakeDriver) };
30 +});
31 +
32 +vi.mock(import("~/rpc/requestLatencyState"), async (original) => ({
33 + ...(await original()),
34 + trackRpcRequestSent: () => {},
35 +}));
36 +
37 +// Its own file: the app's shell subscription outlives a test, and it must list this thread.
38 +it("a model picked for an existing thread reaches the server before any message is sent", async () => {
39 + const thread = threadWithHistory("thread-model-pick", 1);
40 + using _environment = installFakeEnvironment([thread], { acceptCommands: true });
41 + __setClientSettingsForTests({
42 + ...DEFAULT_CLIENT_SETTINGS,
43 + onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
44 + });
45 + const router = getRouter(
46 + createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
47 + );
48 + await router.load();
49 + await using _app = await render(<AppRoot router={router} />, {
50 + // AppRoot brings its own router.
51 + router: false,
52 + });
53 + await expect.element(page.getByText("Answer 0 for thread-model-pick.")).toBeVisible();
54 +
55 + await page.getByRole("button", { name: "GPT-5.4", exact: true }).click();
56 + await page.getByRole("option", { name: /GPT-5\.5/ }).click();
57 + await vi.waitFor(() =>
58 + expect(
59 + dispatchedCommands().filter((command) => command.type === "thread.model-selection.set"),
60 + ).toEqual([
61 + expect.objectContaining({
62 + threadId: thread.id,
63 + modelSelection: expect.objectContaining({ instanceId: "codex", model: "gpt-5.5" }),
64 + }),
65 + ]),
66 + );
67 +});
apps/web/src/components/chat/ChatComposer.tsx
+3
@@ -209,6 +209,7 @@ import { resolveComposerMenuActiveItemId } from "./composerMenuHighlight";
209 import { buildPullRequestReferenceContext } from "../pullRequest/pullRequestDetail.logic";
210 import { getComposerPromptInjectionState, getComposerReasoningStep } from "./composerProviderState";
211 import { readPromptUltrathink } from "./TraitsPicker";
212 +import { useApplyThreadModelPick } from "./useApplyThreadModelPick";
213 import {
214 buildAttachmentVideoPreview,
215 buildExpandedImagePreview,
@@ -598,6 +599,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
599 const activePendingIsResponding = !holdingUserInput && incomingPendingIsResponding;
600 const isLiteralPendingAnswer = activePendingProgress?.activeQuestion?.initialAnswer !== undefined;
601 const isEditingQueuedMessage = editingQueuedAttachments !== null;
602 + const applyThreadModelPick = useApplyThreadModelPick();
603 const composerDraft = useComposerThreadDraft(composerDraftTarget);
604 const composerDraftTargetKeyRef = useRef("");
605 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes the committed draft target key to a ref read by async handlers
@@ -2947,6 +2949,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
2949 model: selectedModel,
2950 persistSticky: true,
2951 });
2952 + applyThreadModelPick(composerDraftTarget);
2953 if (change.prompt !== promptRef.current) {
2954 applyPromptReplacementStable(0, promptRef.current.length, change.prompt, {
2955 expandedCursorAfterReplace: change.cursor,
apps/web/src/components/chat/ComposerControlsBar.tsx
+7 -1
@@ -21,6 +21,8 @@ import {
21 import type { EffortDisplay } from "@t3tools/contracts/settings";
22 import { cn } from "~/lib/utils";
23 import { resolveComposerTraitsInput } from "./composerProviderState";
24 +import { useApplyThreadModelPick } from "./useApplyThreadModelPick";
25 +import { useStableCallback } from "../../hooks/useStableCallback";
26 import {
27 ComposerEffortColumn,
28 ComposerPickerFooter,
@@ -142,10 +144,14 @@ export function ComposerControlsBar(props: {
144 measuredHiddenBlockCount,
145 });
146 const controlSize = composerControlsCollapsed ? "xs" : "sm";
147 + const applyThreadModelPick = useApplyThreadModelPick();
148 + const applyRouteThreadModelPick = useStableCallback(() => applyThreadModelPick(routeThreadRef));
149 const traitsInput = resolveComposerTraitsInput({
150 provider: selectedProvider,
151 instanceId: selectedInstanceId,
148 - ...(routeKind === "server" ? { threadRef: routeThreadRef } : {}),
152 + ...(routeKind === "server"
153 + ? { threadRef: routeThreadRef, onDraftModelOptionsChange: applyRouteThreadModelPick }
154 + : {}),
155 ...(routeKind === "draft" && draftId ? { draftId } : {}),
156 model: selectedModel,
157 models: selectedProviderModels,
apps/web/src/components/chat/TraitsPicker.tsx
+4
@@ -93,10 +93,13 @@ type TraitsPersistence =
93 | {
94 threadRef?: ScopedThreadRef;
95 draftId?: DraftId;
96 + /** Runs after a change is written to the draft. */
97 + onDraftModelOptionsChange?: () => void;
98 onModelOptionsChange?: never;
99 }
100 | {
101 threadRef?: undefined;
102 + onDraftModelOptionsChange?: never;
103 onModelOptionsChange: (nextOptions: ProviderOptions | undefined) => void;
104 };
105
@@ -328,6 +331,7 @@ export function useTraitsSelection({
331 model,
332 persistSticky: true,
333 });
334 + persistence.onDraftModelOptionsChange?.();
335 };
336 const selected = getTraitsSectionVisibility({
337 provider,
apps/web/src/components/chat/composerProviderState.tsx
+1
@@ -48,6 +48,7 @@ type ComposerTraitsTarget = {
48 instanceId: ProviderInstanceId;
49 threadRef?: ScopedThreadRef | undefined;
50 draftId?: DraftId | undefined;
51 + onDraftModelOptionsChange?: () => void;
52 model: string;
53 models: ReadonlyArray<ServerProviderModel>;
54 modelOptions: ReadonlyArray<ProviderOptionSelection> | undefined;
apps/web/src/components/chat/useApplyThreadModelPick.ts new
+48
@@ -0,0 +1,48 @@
1 +import { RegistryContext } from "@effect/atom-react";
2 +import { scopedThreadKey } from "@t3tools/client-runtime/environment";
3 +import {
4 + isAtomCommandInterrupted,
5 + squashAtomCommandFailure,
6 +} from "@t3tools/client-runtime/state/runtime";
7 +import { useContext } from "react";
8 +
9 +import { type ComposerThreadTarget, useComposerDraftStore } from "../../composerDraftStore";
10 +import { environmentThreadShells, threadEnvironment } from "../../state/threads";
11 +import { useOrchestrationCommand } from "../../state/use-orchestration-command";
12 +import { stackedThreadToast, toastManager } from "../ui/toast";
13 +
14 +/** Sets an existing thread's composer pick on the thread, so any next turn runs on it. */
15 +export function useApplyThreadModelPick() {
16 + const registry = useContext(RegistryContext);
17 + const setModelSelection = useOrchestrationCommand(threadEnvironment.setModelSelection, {
18 + label: "change model",
19 + });
20 + return async (target: ComposerThreadTarget) => {
21 + if (typeof target === "string") return;
22 + const store = useComposerDraftStore.getState();
23 + const draft = store.draftsByThreadKey[scopedThreadKey(target)];
24 + if (!draft?.modelSelectionExplicit || !draft.activeProvider) return;
25 + const pick = draft.modelSelectionByProvider[draft.activeProvider];
26 + const thread = registry.get(environmentThreadShells.threadShellAtom(target));
27 + if (!pick || !thread || store.draftThreadsByThreadKey[scopedThreadKey(target)]) return;
28 + // Another instance replaces the live session, which may hold an open question; that pick
29 + // still waits for a sent message.
30 + if (pick.instanceId !== thread.modelSelection.instanceId) return;
31 + const result = await setModelSelection({
32 + environmentId: target.environmentId,
33 + input: { threadId: target.threadId, modelSelection: pick },
34 + });
35 + if (result._tag === "Success") {
36 + useComposerDraftStore.getState().releaseModelSelection(target, pick);
37 + } else if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
38 + const error = squashAtomCommandFailure(result);
39 + toastManager.add(
40 + stackedThreadToast({
41 + type: "error",
42 + title: "Could not apply model selection",
43 + description: `This model pick was not saved. ${error instanceof Error ? error.message : "Try again."}`,
44 + }),
45 + );
46 + }
47 + };
48 +}
apps/web/src/components/chat/useComposerSelection.ts
+8 -5
@@ -3,6 +3,7 @@ import type { UnifiedSettings } from "@t3tools/contracts";
3 import type { Dispatch } from "react";
4 import type { ComposerThreadTarget, DraftSessionState } from "../../composerDraftStore";
5 import { useStableCallback } from "../../hooks/useStableCallback";
6 +import { useApplyThreadModelPick } from "./useApplyThreadModelPick";
7 import {
8 type EnvironmentId,
9 type ModelSelection,
@@ -81,6 +82,7 @@ export function useComposerSelection(input: ComposerSelectionInput) {
82 const setComposerDraftModelSelection = useComposerDraftStore((store) => store.setModelSelection);
83 const setComposerDraftRuntimeMode = useComposerDraftStore((store) => store.setRuntimeMode);
84 const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
85 + const applyThreadModelPick = useApplyThreadModelPick();
86
87 const handleRuntimeModeChange = (mode: RuntimeMode) => {
88 if (mode === runtimeMode) return;
@@ -182,12 +184,13 @@ export function useComposerSelection(input: ComposerSelectionInput) {
184 if (options?.focusComposer !== false) scheduleComposerFocus();
185 return;
186 }
185 - setComposerDraftModelSelection(
186 - scopeThreadRef(activeThread.environmentId, activeThread.id),
187 - nextModelSelection,
188 - { explicit: true, replaceOptions: true },
189 - );
187 + const threadRef = scopeThreadRef(activeThread.environmentId, activeThread.id);
188 + setComposerDraftModelSelection(threadRef, nextModelSelection, {
189 + explicit: true,
190 + replaceOptions: true,
191 + });
192 setStickyComposerModelSelection(nextModelSelection);
193 + if (!isLocalDraftThread) applyThreadModelPick(threadRef);
194 if (options?.focusComposer !== false) scheduleComposerFocus();
195 };
196 const onProviderModelSelectStable = useStableCallback(onProviderModelSelect);
apps/web/src/composerDraftStore.test.ts
+82 -1
@@ -1332,9 +1332,26 @@ function modelReconciliationHarness(
1332 ],
1333 ]),
1334 });
1335 + // A pick sent to the thread: shown over the durable snapshot until it settles.
1336 + const inFlightPickAtom = Atom.make<ModelSelection | null>(null);
1337 + const visibleSnapshotAtom = Atom.make((get) => {
1338 + const snapshot = get(snapshotAtom);
1339 + const pick = get(inFlightPickAtom);
1340 + if (!snapshot || !pick) return snapshot;
1341 + return {
1342 + ...snapshot,
1343 + threads: snapshot.threads.map((candidate) =>
1344 + candidate.id === threadId ? { ...candidate, modelSelection: pick } : candidate,
1345 + ),
1346 + };
1347 + });
1348 + const pendingThreadIdsAtom = Atom.map(
1349 + inFlightPickAtom,
1350 + (pick): ReadonlySet<ThreadId> => new Set(pick ? [threadId] : []),
1351 + );
1352 const shells = createEnvironmentThreadShellAtoms({
1353 catalogValueAtom,
1337 - snapshotAtom: () => snapshotAtom,
1354 + snapshotAtom: () => visibleSnapshotAtom,
1355 hiddenThreadTagsAtom: () => Atom.make(null),
1356 });
1357 const selectedShell = shells.threadShellAtom({ environmentId, threadId: selectedThreadId });
@@ -1345,11 +1362,16 @@ function modelReconciliationHarness(
1362 threadShellAtom: shells.threadShellAtom,
1363 threadRefsAtom: shells.threadRefsAtom,
1364 shellStateAtom: () => shellResultAtom,
1365 + pendingThreadIdsAtom: () => pendingThreadIdsAtom,
1366 }),
1367 );
1368 flush();
1369 return {
1370 flush,
1371 + showInFlightPick(pick: ModelSelection | null) {
1372 + registry.set(inFlightPickAtom, pick);
1373 + flush();
1374 + },
1375 setStatus(status: EnvironmentShellStatus) {
1376 registry.set(shellStateAtom, { ...registry.get(shellStateAtom), status });
1377 flush();
@@ -1560,6 +1582,65 @@ describe("composerDraftStore modelSelection", () => {
1582 expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toBeUndefined();
1583 });
1584
1585 + it("keeps a pick matching the old model while an earlier pick is still in flight", () => {
1586 + const h = modelReconciliationHarness(TEST_ENVIRONMENT_ID, threadId);
1587 + const store = useComposerDraftStore.getState();
1588 + const original = h.model();
1589 + const other = { ...original, model: "remote-model" };
1590 + store.setModelSelection(threadRef, other, { explicit: true });
1591 + h.showInFlightPick(other);
1592 + store.setModelSelection(threadRef, original, { explicit: true });
1593 + h.showInFlightPick(original);
1594 + const latest = draftFor(threadId, TEST_ENVIRONMENT_ID);
1595 + expect(latest?.modelSelectionByProvider[original.instanceId]).toEqual(original);
1596 +
1597 + // The earlier pick lands, then the latest one is rejected.
1598 + h.update({ modelSelection: other });
1599 + h.showInFlightPick(null);
1600 + expect(h.model()).toEqual(other);
1601 + expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toBe(latest);
1602 + });
1603 +
1604 + it.each(["consecutive model", "consecutive options", "returning model"] as const)(
1605 + "releases only the latest accepted pick after %s picks",
1606 + (kind) => {
1607 + const store = useComposerDraftStore.getState();
1608 + store.setPrompt(threadRef, "keep this follow-up");
1609 + const select = () => {
1610 + if (kind === "consecutive options") {
1611 + store.setProviderModelOptions(
1612 + threadRef,
1613 + CODEX_DRIVER,
1614 + toSelections({ reasoningEffort: "high" }),
1615 + { instanceId: CODEX_INSTANCE, model: "gpt-5.5" },
1616 + );
1617 + } else {
1618 + store.setModelSelection(threadRef, modelSelection(CODEX_DRIVER, "gpt-5.5"), {
1619 + explicit: true,
1620 + });
1621 + }
1622 + };
1623 + select();
1624 + const first = draftFor(threadId, TEST_ENVIRONMENT_ID)!.modelSelectionByProvider[
1625 + CODEX_INSTANCE
1626 + ]!;
1627 + if (kind === "returning model") {
1628 + store.setModelSelection(threadRef, modelSelection(CODEX_DRIVER, "gpt-5.4"), {
1629 + explicit: true,
1630 + });
1631 + }
1632 + select();
1633 + const latest = draftFor(threadId, TEST_ENVIRONMENT_ID)!;
1634 +
1635 + store.releaseModelSelection(threadRef, first);
1636 + expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toBe(latest);
1637 + store.releaseModelSelection(threadRef, latest.modelSelectionByProvider[CODEX_INSTANCE]!);
1638 + expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionExplicit).toBeUndefined();
1639 + expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider).toEqual({});
1640 + expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.prompt).toBe("keep this follow-up");
1641 + },
1642 + );
1643 +
1644 it("releases an inactive thread pick only after its queued model becomes durable", () => {
1645 const store = useComposerDraftStore.getState();
1646 const pick = modelSelection(CODEX_DRIVER, "gpt-5.5", { fastMode: false });
apps/web/src/composerDraftStore.ts
+31 -20
@@ -519,6 +519,8 @@ interface ComposerDraftStoreState {
519 replaceOptions?: boolean;
520 },
521 ) => void;
522 + /** Lets the thread's model show again once the server accepted this exact pick. */
523 + releaseModelSelection: (threadRef: ScopedThreadRef, modelSelection: ModelSelection) => void;
524 applyStickyState: (threadRef: ComposerThreadTarget) => void;
525 setProviderModelOptions: (
526 threadRef: ComposerThreadTarget,
@@ -3038,9 +3040,10 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
3040 }
3041 const nextActiveProvider = normalized?.instanceId ?? base.activeProvider;
3042 if (
3043 + opts?.explicit !== true &&
3044 Equal.equals(base.modelSelectionByProvider, nextMap) &&
3045 base.activeProvider === nextActiveProvider &&
3043 - (base.modelSelectionExplicit ?? false) === (opts?.explicit === true)
3046 + !base.modelSelectionExplicit
3047 ) {
3048 return state;
3049 }
@@ -3060,6 +3063,25 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
3063 return { draftsByThreadKey: nextDraftsByThreadKey };
3064 });
3065 },
3066 + releaseModelSelection: (threadRef, modelSelection) => {
3067 + const threadKey = scopedThreadKey(threadRef);
3068 + set((state) => {
3069 + const draft = state.draftsByThreadKey[threadKey];
3070 + // A newer pick, even of the same model, is still waiting for its own reply.
3071 + if (
3072 + !draft?.activeProvider ||
3073 + draft.modelSelectionByProvider[draft.activeProvider] !== modelSelection
3074 + ) {
3075 + return state;
3076 + }
3077 + const { modelSelectionExplicit: _explicit, ...retained } = draft;
3078 + const next = { ...retained, activeProvider: null, modelSelectionByProvider: {} };
3079 + const draftsByThreadKey = { ...state.draftsByThreadKey };
3080 + if (shouldRemoveDraft(next)) delete draftsByThreadKey[threadKey];
3081 + else draftsByThreadKey[threadKey] = next;
3082 + return { draftsByThreadKey };
3083 + });
3084 + },
3085 setProviderModelOptions: (threadRef, provider, nextProviderOptions, options) => {
3086 const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
3087 if (threadKey.length === 0) {
@@ -3083,16 +3105,11 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
3105
3106 const nextMap = { ...base.modelSelectionByProvider };
3107 const currentForProvider = nextMap[instanceKey];
3086 - if (providerOpts) {
3087 - nextMap[instanceKey] = createModelSelection(
3088 - instanceKey,
3089 - currentForProvider?.model ?? fallbackModel,
3090 - providerOpts,
3091 - );
3092 - } else if (currentForProvider && (currentForProvider.options?.length ?? 0) > 0) {
3093 - const { options: _, ...rest } = currentForProvider;
3094 - nextMap[instanceKey] = rest as ModelSelection;
3095 - }
3108 + nextMap[instanceKey] = createModelSelection(
3109 + instanceKey,
3110 + currentForProvider?.model ?? fallbackModel,
3111 + providerOpts,
3112 + );
3113
3114 let nextStickyMap = state.stickyModelSelectionByProvider;
3115 let nextOptionsByModel = state.stickyOptionsByModelByProvider;
@@ -3134,15 +3151,6 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
3151 : (base.activeProvider ?? instanceKey);
3152 }
3153
3137 - if (
3138 - Equal.equals(base.modelSelectionByProvider, nextMap) &&
3139 - Equal.equals(state.stickyModelSelectionByProvider, nextStickyMap) &&
3140 - Equal.equals(state.stickyOptionsByModelByProvider, nextOptionsByModel) &&
3141 - state.stickyActiveProvider === nextStickyActiveProvider
3142 - ) {
3143 - return state;
3144 - }
3145 -
3154 const { modelSelectionExplicit: _previousExplicit, ...restBase } = base;
3155 const nextDraft: ComposerThreadDraftState = {
3156 ...restBase,
@@ -4250,6 +4258,7 @@ export function subscribeComposerDraftModelReconciliation(input: {
4258 readonly shellStateAtom: (
4259 environmentId: EnvironmentId,
4260 ) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentShellState, unknown>>;
4261 + readonly pendingThreadIdsAtom: (environmentId: EnvironmentId) => Atom.Atom<ReadonlySet<ThreadId>>;
4262 }): () => void {
4263 const draftsAtom = Atom.make(composerDraftStore.getState());
4264 const unsubscribeDrafts = composerDraftStore.subscribe((state) =>
@@ -4271,6 +4280,8 @@ export function subscribeComposerDraftModelReconciliation(input: {
4280 if (!ref || !pick || !threadKeys.has(key)) continue;
4281 const thread = get(input.threadShellAtom(ref));
4282 if (!thread || !draftModelPickMatchesThread(pick, thread.modelSelection)) continue;
4283 + // The pick can match an old model while an earlier pick in flight still replaces it.
4284 + if (get(input.pendingThreadIdsAtom(ref.environmentId)).has(ref.threadId)) continue;
4285 // Status and selection must come from the same emission; derived atoms can update apart.
4286 const shell = AsyncResult.getOrElse(get(input.shellStateAtom(ref.environmentId)), () => null);
4287 if (shell?.status !== "live") continue;
apps/web/test/fakeEnvironment.ts
+27 -2
@@ -19,6 +19,7 @@ import {
19 WsRpcGroup,
20 type VcsStatusStreamEvent,
21 type OrchestrationProjectShell,
22 + type OrchestrationV2Command,
23 type OrchestrationV2ProjectedTurnItem,
24 type OrchestrationV2Run,
25 type OrchestrationV2ShellStreamItem,
@@ -85,7 +86,10 @@ const serverConfig: ServerConfig = {
86 status: "ready",
87 auth: { status: "authenticated" },
88 checkedAt: "2026-03-17T19:12:28.000Z",
88 - models: [{ slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, capabilities: null }],
89 + models: [
90 + { slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, capabilities: null },
91 + { slug: "gpt-5.5", name: "GPT-5.5", isCustom: false, capabilities: null },
92 + ],
93 },
94 ],
95 availableEditors: [],
@@ -318,6 +322,8 @@ const json = (body: unknown, status = 200) =>
322 const threadSubscribers = new Map<string, Queue.Queue<OrchestrationV2ThreadStreamItem>>();
323 let terminalMetadataSubscriber: Queue.Queue<TerminalMetadataStreamEvent> | null = null;
324 let threads: ReadonlyArray<FakeThread> = [];
325 +let dispatched: OrchestrationV2Command[] = [];
326 +let acceptCommands = false;
327 let sequence = 1;
328 let vcsStatusSubscriber: Queue.Queue<VcsStatusStreamEvent> | null = null;
329
@@ -335,6 +341,13 @@ const subscribe = <A>(first: ReadonlyArray<A>, register?: (queue: Queue.Queue<A>
341 );
342
343 const handlers: Record<string, (input: never) => unknown> = {
344 + // Recorded, and accepted only when the scenario asks, since a pending command holds every
345 + // later command on its thread. Accepted commands' events never arrive.
346 + [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command: OrchestrationV2Command) =>
347 + Effect.suspend(() => {
348 + dispatched.push(command);
349 + return acceptCommands ? Effect.succeed({ sequence: sequence + 1 }) : Effect.never;
350 + }),
351 [WS_METHODS.subscribeTerminalMetadata]: () =>
352 subscribe<TerminalMetadataStreamEvent>([{ type: "snapshot", terminals: [] }], (queue) => {
353 terminalMetadataSubscriber = queue;
@@ -433,8 +446,13 @@ const encodedDescriptor = Schema.encodeSync(ExecutionEnvironmentDescriptor)(
446 );
447
448 /** Serves the environment's HTTP API and these threads until disposed. */
436 -export function installFakeEnvironment(fixtures: ReadonlyArray<FakeThread>): Disposable {
449 +export function installFakeEnvironment(
450 + fixtures: ReadonlyArray<FakeThread>,
451 + options?: { readonly acceptCommands?: boolean },
452 +): Disposable {
453 threads = fixtures;
454 + dispatched = [];
455 + acceptCommands = options?.acceptCommands === true;
456 globalThis.fetch = async (input, init) => {
457 const url = new URL(input instanceof Request ? input.url : String(input), window.location.href);
458 if (url.origin !== window.location.origin) return realFetch(input, init);
@@ -456,10 +474,17 @@ export function installFakeEnvironment(fixtures: ReadonlyArray<FakeThread>): Dis
474 [Symbol.dispose]: () => {
475 globalThis.fetch = realFetch;
476 threads = [];
477 + dispatched = [];
478 + acceptCommands = false;
479 },
480 };
481 }
482
483 +/** Commands the app dispatched to the environment, oldest first. */
484 +export function dispatchedCommands(): ReadonlyArray<OrchestrationV2Command> {
485 + return dispatched;
486 +}
487 +
488 type ThreadEvent = Extract<OrchestrationV2ThreadStreamItem, { readonly kind: "event" }>["event"];
489
490 export async function emitTerminalMetadata(event: TerminalMetadataStreamEvent): Promise<void> {
packages/client-runtime/src/state/threadCommands.ts
+15 -1
@@ -1,4 +1,4 @@
1 -import type { ThreadId } from "@t3tools/contracts";
1 +import type { ModelSelection, ThreadId } from "@t3tools/contracts";
2 import * as SecureRandom from "effect/crypto/SecureRandom";
3 import * as Effect from "effect/Effect";
4 import * as Option from "effect/Option";
@@ -19,6 +19,7 @@ import {
19 } from "./runtime.ts";
20 import {
21 type InterruptThreadTurnInput,
22 + type UpdateThreadMetadataInput,
23 archiveThread,
24 closeGuestShare,
25 resolveGuestMessage,
@@ -245,6 +246,13 @@ export function createThreadEnvironmentAtoms<R, E>(
246 scheduler,
247 concurrency,
248 }),
249 + setModelSelection: createEnvironmentCommand(runtime, {
250 + label: "environment-data:commands:thread:set-model-selection",
251 + execute: (input: UpdateThreadMetadataInput & { readonly modelSelection: ModelSelection }) =>
252 + updateThreadMetadata(input),
253 + scheduler,
254 + concurrency,
255 + }),
256 setRuntimeMode: createEnvironmentCommand(runtime, {
257 label: "environment-data:commands:thread:set-runtime-mode",
258 execute: setThreadRuntimeMode,
@@ -378,6 +386,7 @@ export function createThreadEnvironmentAtoms<R, E>(
386 return {
387 ...commands,
388 snapshotAtom: optimistic.snapshotAtom,
389 + pendingThreadIdsAtom: optimistic.pendingThreadIdsAtom,
390 settle: optimistic.wrap(commands.settle, (thread, _input, now, accepted) =>
391 !accepted &&
392 (thread.pendingRuntimeRequest !== null ||
@@ -451,5 +460,10 @@ export function createThreadEnvironmentAtoms<R, E>(
460 ...thread,
461 activeOrderKey: input.orderKey,
462 })),
463 + // Shown at once, so a composer that releases its accepted pick keeps showing it.
464 + setModelSelection: optimistic.wrap(commands.setModelSelection, (thread, input) => ({
465 + ...thread,
466 + modelSelection: input.modelSelection,
467 + })),
468 };
469 }
packages/client-runtime/src/state/threadLifecycle.ts
+9 -1
@@ -48,6 +48,14 @@ export function createOptimisticThreadLifecycle(
48 }),
49 );
50
51 + // Until the durable snapshot catches up, an older pending update can still replace what shows.
52 + const pendingThreadIdsAtom = Atom.family((environmentId: EnvironmentId) =>
53 + Atom.make(
54 + (get): ReadonlySet<ThreadId> =>
55 + new Set(get(pendingAtom(environmentId)).map((update) => update.threadId)),
56 + ),
57 + );
58 +
59 function wrap<Input extends { readonly threadId: ThreadId }, E>(
60 command: AtomCommand<
61 { readonly environmentId: EnvironmentId; readonly input: Input },
@@ -98,5 +106,5 @@ export function createOptimisticThreadLifecycle(
106 };
107 }
108
101 - return { snapshotAtom, wrap };
109 + return { snapshotAtom, pendingThreadIdsAtom, wrap };
110 }