TypeScript
fix(composer): drafts follow model changes made on other clients (#20886)
Nick Anisimov276701299629
diff --git a/apps/mobile/src/App.tsx b/apps/mobile/src/App.tsxindex 7a729c76dfa..bfe5d1774a6 100644--- a/apps/mobile/src/App.tsx+++ b/apps/mobile/src/App.tsx@@ -20,6 +20,9 @@ import {} from "./features/settings/appearance/AppearancePreferencesProvider";import { RootStack } from "./Stack";import { appAtomRegistry } from "./state/atom-registry";+import { subscribeComposerDraftModelReconciliation } from "./state/use-composer-drafts";+import { environmentThreadShells } from "./state/threads";+import { environmentShell } from "./state/shell";import { OverlayPortalHost } from "./components/ui/OverlayPortal";import { shouldHandleAppLink } from "./lib/appLinking";import { useMobileNavigationTheme } from "./lib/useMobileNavigationTheme";@@ -57,6 +60,16 @@ function SplashScreenCoordinator() {export default function App() {useUiRuntimeMemoryWarningGc();+ useEffect(+ () =>+ subscribeComposerDraftModelReconciliation({+ registry: appAtomRegistry,+ threadShellAtom: environmentThreadShells.threadShellAtom,+ threadRefsAtom: environmentThreadShells.threadRefsAtom,+ shellStateAtom: environmentShell.stateAtom,+ }),+ [],+ );return (<RegistryContext.Provider value={appAtomRegistry}>diff --git a/apps/mobile/src/state/use-composer-drafts.test.ts b/apps/mobile/src/state/use-composer-drafts.test.tsindex 43e14f90ec7..ce99a6a7c25 100644--- a/apps/mobile/src/state/use-composer-drafts.test.ts+++ b/apps/mobile/src/state/use-composer-drafts.test.ts@@ -1,3 +1,17 @@+import { PrimaryConnectionTarget } from "@t3tools/client-runtime/connection";+import { createEnvironmentThreadShellAtoms } from "@t3tools/client-runtime/state/threads";+import {+ applyShellStreamEvent,+ createEnvironmentSnapshotAtom,+ type EnvironmentShellState,+ type EnvironmentShellStatus,+} from "@t3tools/client-runtime/state/shell";+import {+ v2ShellSnapshot,+ v2ThreadShell,+} from "../../../../packages/client-runtime/src/state/orchestrationV2TestFixtures";+import * as Option from "effect/Option";+import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";import { afterEach, describe, expect, it } from "@effect/vitest";import {CommandId,@@ -7,6 +21,9 @@ import {ProjectId,ProviderInstanceId,ThreadId,+ type OrchestrationV2ThreadShell,+ type OrchestrationV2ShellSnapshot,+ type ModelSelection,} from "@t3tools/contracts";import { onTestFinished, vi } from "vite-plus/test";@@ -162,6 +179,7 @@ import {archiveCloudComposerDrafts,clearComposerDraftContent,clearComposerDraftContentState,+ subscribeComposerDraftModelReconciliation,clearComposerDraftsEnvironment,ComposerDraftPersistenceError,composerDraftsAtom,@@ -196,6 +214,7 @@ import {stickyComposerModelSelectionAtom,undoComposerDraftMerge,undoComposerDraftMergeState,+ updateComposerDraftSettings,} from "./use-composer-drafts";import { retainComposerAttachmentFileForPreview } from "../lib/composerAttachmentPreviewRetention";@@ -242,6 +261,98 @@ function contextDraft(start: number, count: number): ComposerDraft {};}+function modelReconciliationHarness(+ environmentId: EnvironmentId,+ threadId: ThreadId,+ initialStatus: EnvironmentShellStatus = "live",+) {+ const tasks: Array<() => void> = [];+ const registry = AtomRegistry.make({+ scheduleTask: (task) => {+ tasks.push(task);+ return () => {};+ },+ });+ onTestFinished(() => registry.dispose());+ const flush = () => {+ for (let task = tasks.shift(); task !== undefined; task = tasks.shift()) task();+ };+ const selectedThreadId = ThreadId.make("another-selected-thread");+ const initialSnapshot: OrchestrationV2ShellSnapshot = {+ ...v2ShellSnapshot,+ threads: [+ { ...v2ThreadShell, id: threadId },+ { ...v2ThreadShell, id: selectedThreadId },+ ],+ };+ const shellStateAtom = Atom.make<EnvironmentShellState>({+ snapshot: Option.some(initialSnapshot),+ status: initialStatus,+ error: Option.none(),+ });+ const shellResultAtom = Atom.map(shellStateAtom, AsyncResult.success);+ const snapshotAtom = createEnvironmentSnapshotAtom(() => shellResultAtom)(environmentId);+ const catalogValueAtom = Atom.make({+ isReady: true,+ entries: new Map([+ [+ environmentId,+ {+ target: new PrimaryConnectionTarget({+ environmentId,+ label: "Environment",+ httpBaseUrl: "https://example.test",+ wsBaseUrl: "wss://example.test",+ }),+ profile: Option.none(),+ enabled: true,+ },+ ],+ ]),+ });+ const shells = createEnvironmentThreadShellAtoms({+ catalogValueAtom,+ snapshotAtom: () => snapshotAtom,+ });+ const selectedShell = shells.threadShellAtom({ environmentId, threadId: selectedThreadId });+ onTestFinished(registry.mount(selectedShell));+ onTestFinished(+ subscribeComposerDraftModelReconciliation({+ registry,+ threadShellAtom: shells.threadShellAtom,+ threadRefsAtom: shells.threadRefsAtom,+ shellStateAtom: () => shellResultAtom,+ }),+ );+ flush();+ return {+ flush,+ setStatus(status: EnvironmentShellStatus) {+ registry.set(shellStateAtom, { ...registry.get(shellStateAtom), status });+ flush();+ },+ update(changes: Partial<OrchestrationV2ThreadShell>, status?: EnvironmentShellStatus) {+ const state = registry.get(shellStateAtom);+ const snapshot = Option.getOrThrow(state.snapshot);+ registry.set(shellStateAtom, {+ ...state,+ status: status ?? state.status,+ snapshot: Option.some(+ applyShellStreamEvent(snapshot, {+ kind: "thread.updated",+ location: "active",+ sequence: snapshot.snapshotSequence + 1,+ thread: { ...snapshot.threads[0]!, ...changes },+ }),+ ),+ });+ flush();+ expect(registry.get(selectedShell)?.id).toBe(selectedThreadId);+ },+ model: () => registry.get(shells.threadShellAtom({ environmentId, threadId }))!.modelSelection,+ };+}+describe("mobile composer drafts", () => {it("restores a PR checkout source after restarting the composer", () => {const draft: ComposerDraft = {@@ -428,6 +539,114 @@ describe("mobile composer drafts", () => {expect(draft.text).toContain(String(record?.contextId));});+ it("retains a pick matching cached state until the live shell confirms it", () => {+ const environmentId = EnvironmentId.make("environment-1");+ const threadId = ThreadId.make("thread-1");+ const key = `${environmentId}:${threadId}`;+ const h = modelReconciliationHarness(environmentId, threadId, "cached");+ const pick = h.model();+ updateComposerDraftSettings(key, { modelSelection: pick });+ h.flush();+ const before = getComposerDraftSnapshot(key);+ expect(before.modelSelection).toEqual(pick);++ for (const status of ["empty", "synchronizing", "cached"] as const) {+ h.setStatus(status);+ expect(getComposerDraftSnapshot(key)).toEqual(before);+ }+ h.update({ modelSelection: { ...pick, model: "remote-model" } }, "live");+ expect(getComposerDraftSnapshot(key)).toEqual(before);+ h.update({ modelSelection: pick }, "synchronizing");+ expect(getComposerDraftSnapshot(key)).toEqual(before);+ h.setStatus("live");+ expect(appAtomRegistry.get(composerDraftsAtom)[key]).toBeUndefined();+ });++ it("releases an inactive thread pick only after its queued model becomes durable", () => {+ const environmentId = EnvironmentId.make("environment-1");+ const threadId = ThreadId.make("thread-1");+ const key = `${environmentId}:${threadId}`;+ const pick = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.5" };+ setComposerDraftText(key, "keep this unsent follow-up");+ appendComposerDraftAttachments(+ key,+ [+ {+ type: "file",+ id: "file",+ name: "notes.txt",+ mimeType: "text/plain",+ sizeBytes: 4,+ fileUri: "file:///notes.txt",+ },+ ],+ { appendReference: true },+ );+ updateComposerDraftSettings(key, {+ modelSelection: pick,+ runtimeMode: "approval-required",+ interactionMode: "plan",+ });+ const before = getComposerDraftSnapshot(key);+ const remoteKey = `environment-remote:${threadId}`;+ updateComposerDraftSettings(remoteKey, { modelSelection: pick });+ const remoteBefore = getComposerDraftSnapshot(remoteKey);+ const h = modelReconciliationHarness(environmentId, threadId);++ h.update({ status: "queued" });+ expect(getComposerDraftSnapshot(key)).toEqual(before);+ h.update({+ status: "running",+ modelSelection: { ...pick, options: [{ id: "fastMode", value: false }] },+ });+ expect(getComposerDraftSnapshot(key)).toEqual({ ...before, modelSelection: undefined });+ expect(getComposerDraftSnapshot(remoteKey)).toEqual(remoteBefore);++ h.update({+ modelSelection: {+ instanceId: ProviderInstanceId.make("claudeAgent"),+ model: "claude-opus-5-5",+ },+ });+ expect(getComposerDraftSnapshot(key).modelSelection ?? h.model()).toEqual(h.model());+ expect(getComposerDraftSnapshot(key)).toEqual({ ...before, modelSelection: undefined });+ });++ it("retains an unavailable provider pick through differing durable model updates", () => {+ const environmentId = EnvironmentId.make("environment-1");+ const threadId = ThreadId.make("thread-1");+ const key = `${environmentId}:${threadId}`;+ const pick: ModelSelection = {+ instanceId: ProviderInstanceId.make("codex-secondary"),+ model: "gpt-5.5",+ options: [+ { id: "reasoningEffort", value: "high" },+ { id: "fastMode", value: true },+ ],+ };+ updateComposerDraftSettings(key, { modelSelection: pick });+ const before = getComposerDraftSnapshot(key);+ const h = modelReconciliationHarness(environmentId, threadId);+ expect(getComposerDraftSnapshot(key)).toEqual(before);+ for (const modelSelection of [+ { ...pick, instanceId: ProviderInstanceId.make("codex") },+ { ...pick, model: "gpt-5.4" },+ { ...pick, options: [{ id: "reasoningEffort", value: "high" }] },+ {+ ...pick,+ options: [+ { id: "reasoningEffort", value: "low" },+ { id: "fastMode", value: true },+ ],+ },+ ]) {+ h.update({ modelSelection });+ expect(getComposerDraftSnapshot(key)).toEqual(before);+ }+ h.update({ modelSelection: { ...pick, options: pick.options!.toReversed() } });+ expect(appAtomRegistry.get(composerDraftsAtom)[key]).toBeUndefined();+ });+it("drops chips and records for attachments a replace no longer keeps", () => {const key = "new-task:draft-1";const kept = {diff --git a/apps/mobile/src/state/use-composer-drafts.ts b/apps/mobile/src/state/use-composer-drafts.tsindex b804bb1c926..2549cb276bc 100644--- a/apps/mobile/src/state/use-composer-drafts.ts+++ b/apps/mobile/src/state/use-composer-drafts.ts@@ -18,10 +18,18 @@ import {type ProviderInteractionMode,type ProviderOptionSelection,type RuntimeMode,+ type ScopedThreadRef,} from "@t3tools/contracts";import * as Schema from "effect/Schema";import { useEffect } from "react";-import { Atom } from "effect/reactivity";+import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";+import * as Option from "effect/Option";+import { parseScopedThreadKey, scopedThreadKey } from "@t3tools/client-runtime/environment";+import type {+ EnvironmentShellState,+ EnvironmentThreadShell,+} from "@t3tools/client-runtime/state/shell";+import { draftModelPickMatchesThread } from "@t3tools/shared/model";import { writeFileAtomically } from "../lib/atomic-file";import { createComposerContextHistory, referencedComposerContext } from "../lib/composerContext";@@ -1460,6 +1468,71 @@ export function updateComposerDraftSettings(});}+export function subscribeComposerDraftModelReconciliation(input: {+ readonly registry: AtomRegistry.AtomRegistry;+ readonly threadRefsAtom: Atom.Atom<ReadonlyArray<ScopedThreadRef>>;+ readonly threadShellAtom: (ref: ScopedThreadRef) => Atom.Atom<EnvironmentThreadShell | null>;+ readonly shellStateAtom: (+ environmentId: EnvironmentId,+ ) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentShellState, unknown>>;+}): () => void {+ const draftsAtom = Atom.make(appAtomRegistry.get(composerDraftsAtom));+ const unsubscribeDrafts = appAtomRegistry.subscribe(composerDraftsAtom, (drafts) =>+ input.registry.set(draftsAtom, drafts),+ );+ const threadKeysAtom = Atom.map(+ input.threadRefsAtom,+ (refs) => new Set(refs.map(scopedThreadKey)),+ );+ const matchesAtom = Atom.make((get) => {+ const threadKeys = get(threadKeysAtom);+ const matches: Array<readonly [string, ComposerDraft]> = [];+ for (const [key, draft] of Object.entries(get(draftsAtom))) {+ if (!draft.modelSelection || isNewTaskDraftKey(key) || isQueuedEditDraftKey(key)) continue;+ const ref = parseScopedThreadKey(key);+ if (!ref || !threadKeys.has(key)) continue;+ const thread = get(input.threadShellAtom(ref));+ if (!thread || !draftModelPickMatchesThread(draft.modelSelection, thread.modelSelection))+ continue;+ // Status and selection must come from the same emission; derived atoms can update apart.+ const shell = Option.getOrNull(+ AsyncResult.value(get(input.shellStateAtom(ref.environmentId))),+ );+ if (shell?.status !== "live") continue;+ const authoritativeThread = Option.getOrNull(shell.snapshot)?.threads.find(+ (candidate) => candidate.id === ref.threadId,+ );+ if (+ authoritativeThread &&+ draftModelPickMatchesThread(draft.modelSelection, authoritativeThread.modelSelection)+ ) {+ matches.push([key, draft]);+ }+ }+ return matches;+ });+ const unsubscribeMatches = input.registry.subscribe(+ matchesAtom,+ (matches) => {+ if (matches.length === 0) return;+ updateComposerDrafts((current) => {+ let next = current;+ for (const [key, matchedDraft] of matches) {+ if (next[key] !== matchedDraft) continue;+ const { modelSelection: _modelSelection, ...draft } = matchedDraft;+ next = withComposerDraft(next, key, draft);+ }+ return next;+ });+ },+ { immediate: true },+ );+ return () => {+ unsubscribeMatches();+ unsubscribeDrafts();+ };+}+export function clearComposerDraftContentState(current: Record<string, ComposerDraft>,draftKey: string,diff --git a/apps/web/src/AppRoot.tsx b/apps/web/src/AppRoot.tsxindex df610d8e1ab..cc3b9e5d3b4 100644--- a/apps/web/src/AppRoot.tsx+++ b/apps/web/src/AppRoot.tsx@@ -1,9 +1,14 @@import { RouterProvider } from "@tanstack/react-router";+import { useEffect } from "react";++import { subscribeComposerDraftModelReconciliation } from "./composerDraftStore";+import { environmentThreadShells } from "./state/threads";+import { environmentShell } from "./state/shell";import { BrowserProfileReporter } from "./browser/BrowserProfileReporter";import { ElectronBrowserHost } from "./browser/ElectronBrowserHost";import { QuitHoldOverlay } from "./components/QuitHoldOverlay";-import { AppAtomRegistryProvider } from "./rpc/atomRegistry";+import { appAtomRegistry, AppAtomRegistryProvider } from "./rpc/atomRegistry";import type { AppRouter } from "./router";/**@@ -12,6 +17,16 @@ import type { AppRouter } from "./router";* as routed UI.*/export function AppRoot({ router }: { readonly router: AppRouter }) {+ useEffect(+ () =>+ subscribeComposerDraftModelReconciliation({+ registry: appAtomRegistry,+ threadShellAtom: environmentThreadShells.threadShellAtom,+ threadRefsAtom: environmentThreadShells.threadRefsAtom,+ shellStateAtom: environmentShell.stateAtom,+ }),+ [],+ );return (<AppAtomRegistryProvider><RouterProvider router={router} />diff --git a/apps/web/src/composerDraftStore.test.ts b/apps/web/src/composerDraftStore.test.tsindex 5a03c81a8f6..7f992c95b09 100644--- a/apps/web/src/composerDraftStore.test.ts+++ b/apps/web/src/composerDraftStore.test.ts@@ -1,3 +1,14 @@+import { PrimaryConnectionTarget } from "@t3tools/client-runtime/connection";+import { createEnvironmentThreadShellAtoms } from "@t3tools/client-runtime/state/threads";+import {+ applyShellStreamEvent,+ createEnvironmentSnapshotAtom,+ type EnvironmentShellState,+ type EnvironmentShellStatus,+} from "@t3tools/client-runtime/state/shell";+import { makeThreadProjectionFixture } from "./test-fixtures";+import * as Option from "effect/Option";+import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";import {scopedProjectKey,scopedThreadKey,@@ -5,8 +16,11 @@ import {scopeThreadRef,} from "@t3tools/client-runtime/environment";import * as Schema from "effect/Schema";+import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";import {defaultInstanceIdForDriver,+ DEFAULT_MODEL,+ DEFAULT_MODEL_BY_PROVIDER,EnvironmentId,MessageId,ProjectId,@@ -14,6 +28,8 @@ import {ProviderInstanceId,PROVIDER_SEND_TURN_MAX_ATTACHMENTS,ThreadId,+ type OrchestrationV2ThreadShell,+ type OrchestrationV2ShellSnapshot,type ModelSelection,type PreviewAnnotationPayload,type ProviderOptionSelection,@@ -59,10 +75,12 @@ function selectionsByProvider(}return result;}-import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";+import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from "vite-plus/test";import {COMPOSER_DRAFT_STORAGE_KEY,+ subscribeComposerDraftModelReconciliation,+ deriveEffectiveComposerModelState,clearComposerDraftsEnvironment,composerDraftHasUserContent,beginBackgroundDraftSubmissionByRef,@@ -1971,6 +1989,113 @@ describe("composerDraftStore project draft thread mapping", () => {});});+function modelReconciliationHarness(+ environmentId: EnvironmentId,+ threadId: ThreadId,+ initialStatus: EnvironmentShellStatus = "live",+) {+ const tasks: Array<() => void> = [];+ const registry = AtomRegistry.make({+ scheduleTask: (task) => {+ tasks.push(task);+ return () => {};+ },+ });+ onTestFinished(() => registry.dispose());+ const flush = () => {+ for (let task = tasks.shift(); task !== undefined; task = tasks.shift()) task();+ };+ const selectedThreadId = ThreadId.make("another-selected-thread");+ const thread: OrchestrationV2ThreadShell = {+ ...makeThreadProjectionFixture().thread,+ latestRunId: null,+ activeRunId: null,+ status: "idle",+ pendingRuntimeRequest: null,+ latestVisibleMessage: null,+ latestUserMessageAt: null,+ hasActionableProposedPlan: false,+ itemCount: 0,+ visibleItemCount: 0,+ };+ const initialSnapshot: OrchestrationV2ShellSnapshot = {+ schemaVersion: 1,+ snapshotSequence: 0,+ projects: [],+ archivedThreads: [],+ threads: [+ { ...thread, id: threadId },+ { ...thread, id: selectedThreadId },+ ],+ };+ const shellStateAtom = Atom.make<EnvironmentShellState>({+ snapshot: Option.some(initialSnapshot),+ status: initialStatus,+ error: Option.none(),+ });+ const shellResultAtom = Atom.map(shellStateAtom, AsyncResult.success);+ const snapshotAtom = createEnvironmentSnapshotAtom(() => shellResultAtom)(environmentId);+ const catalogValueAtom = Atom.make({+ isReady: true,+ entries: new Map([+ [+ environmentId,+ {+ target: new PrimaryConnectionTarget({+ environmentId,+ label: "Environment",+ httpBaseUrl: "https://example.test",+ wsBaseUrl: "wss://example.test",+ }),+ profile: Option.none(),+ enabled: true,+ },+ ],+ ]),+ });+ const shells = createEnvironmentThreadShellAtoms({+ catalogValueAtom,+ snapshotAtom: () => snapshotAtom,+ });+ const selectedShell = shells.threadShellAtom({ environmentId, threadId: selectedThreadId });+ onTestFinished(registry.mount(selectedShell));+ onTestFinished(+ subscribeComposerDraftModelReconciliation({+ registry,+ threadShellAtom: shells.threadShellAtom,+ threadRefsAtom: shells.threadRefsAtom,+ shellStateAtom: () => shellResultAtom,+ }),+ );+ flush();+ return {+ flush,+ setStatus(status: EnvironmentShellStatus) {+ registry.set(shellStateAtom, { ...registry.get(shellStateAtom), status });+ flush();+ },+ update(changes: Partial<OrchestrationV2ThreadShell>, status?: EnvironmentShellStatus) {+ const state = registry.get(shellStateAtom);+ const snapshot = Option.getOrThrow(state.snapshot);+ registry.set(shellStateAtom, {+ ...state,+ status: status ?? state.status,+ snapshot: Option.some(+ applyShellStreamEvent(snapshot, {+ kind: "thread.updated",+ location: "active",+ sequence: snapshot.snapshotSequence + 1,+ thread: { ...snapshot.threads[0]!, ...changes },+ }),+ ),+ });+ flush();+ expect(registry.get(selectedShell)?.id).toBe(selectedThreadId);+ },+ model: () => registry.get(shells.threadShellAtom({ environmentId, threadId }))!.modelSelection,+ };+}+describe("composerDraftStore modelSelection", () => {const threadId = ThreadId.make("thread-model-options");const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId);@@ -1999,6 +2124,125 @@ describe("composerDraftStore modelSelection", () => {);});+ it("retains a pick matching cached state until the live shell confirms it", () => {+ const h = modelReconciliationHarness(TEST_ENVIRONMENT_ID, threadId, "cached");+ const pick = h.model();+ useComposerDraftStore.getState().setModelSelection(threadRef, pick, { explicit: true });+ h.flush();+ const before = draftFor(threadId, TEST_ENVIRONMENT_ID);+ expect(before?.modelSelectionByProvider[pick.instanceId]).toEqual(pick);++ for (const status of ["empty", "synchronizing", "cached"] as const) {+ h.setStatus(status);+ expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toEqual(before);+ }+ h.update({ modelSelection: { ...pick, model: "remote-model" } }, "live");+ expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toEqual(before);+ h.update({ modelSelection: pick }, "synchronizing");+ expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toEqual(before);+ h.setStatus("live");+ expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toBeUndefined();+ });++ it("releases an inactive thread pick only after its queued model becomes durable", () => {+ const store = useComposerDraftStore.getState();+ const pick = modelSelection(CODEX_DRIVER, "gpt-5.5", { fastMode: false });+ store.setPrompt(threadRef, "keep this unsent follow-up");+ store.addImage(threadRef, makeImage({ id: "image", previewUrl: "blob:keep-image" }));+ store.setTerminalContexts(threadRef, [makeTerminalContext({ id: "terminal" })]);+ store.setRuntimeMode(threadRef, "approval-required");+ store.setInteractionMode(threadRef, "plan");+ store.setModelSelection(threadRef, pick, { explicit: true });+ const before = draftFor(threadId, TEST_ENVIRONMENT_ID)!;+ const remoteRef = scopeThreadRef(OTHER_TEST_ENVIRONMENT_ID, threadId);+ store.setModelSelection(remoteRef, pick, { explicit: true });+ const remoteBefore = draftFor(threadId, OTHER_TEST_ENVIRONMENT_ID);+ const h = modelReconciliationHarness(TEST_ENVIRONMENT_ID, threadId);++ h.update({ status: "queued" });+ expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toEqual(before);+ h.update({ status: "running", modelSelection: modelSelection(CODEX_DRIVER, "gpt-5.5") });+ expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toEqual({+ ...before,+ activeProvider: null,+ modelSelectionByProvider: {},+ modelSelectionExplicit: undefined,+ });+ expect(draftFor(threadId, OTHER_TEST_ENVIRONMENT_ID)).toEqual(remoteBefore);++ const remoteModel = DEFAULT_MODEL_BY_PROVIDER[CLAUDE_AGENT_DRIVER]!;+ h.update({ modelSelection: modelSelection(CLAUDE_AGENT_DRIVER, remoteModel) });+ const effective = deriveEffectiveComposerModelState({+ draft: draftFor(threadId, TEST_ENVIRONMENT_ID),+ providers: [+ {+ instanceId: CLAUDE_AGENT_INSTANCE,+ driver: CLAUDE_AGENT_DRIVER,+ enabled: true,+ installed: true,+ version: null,+ status: "ready",+ auth: { status: "authenticated" },+ checkedAt: "2026-01-01T00:00:00.000Z",+ models: [{ slug: remoteModel, name: remoteModel, isCustom: false, capabilities: {} }],+ slashCommands: [],+ skills: [],+ },+ ],+ selectedProvider: CLAUDE_AGENT_DRIVER,+ selectedInstanceId: CLAUDE_AGENT_INSTANCE,+ threadModelSelection: h.model(),+ projectModelSelection: null,+ settings: DEFAULT_UNIFIED_SETTINGS,+ });+ expect(effective.selectedModel).toBe(remoteModel);+ expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider).toEqual({});+ });++ it("retains an unavailable provider pick through differing durable model updates", () => {+ const store = useComposerDraftStore.getState();+ const pick = createModelSelection(CODEX_SECONDARY_INSTANCE, "gpt-5.5", [+ { id: "reasoningEffort", value: "high" },+ { id: "fastMode", value: true },+ ]);+ // A remembered primary pick is the visible fallback while the secondary is unavailable.+ const primary = modelSelection(CODEX_DRIVER, DEFAULT_MODEL);+ store.setModelSelection(threadRef, primary);+ store.setModelSelection(threadRef, pick, { explicit: true });+ const before = draftFor(threadId, TEST_ENVIRONMENT_ID);+ const h = modelReconciliationHarness(TEST_ENVIRONMENT_ID, threadId);+ h.update({ modelSelection: primary });+ const fallback = deriveEffectiveComposerModelState({+ draft: before,+ providers: [],+ selectedProvider: CODEX_DRIVER,+ selectedInstanceId: CODEX_INSTANCE,+ threadModelSelection: h.model(),+ projectModelSelection: null,+ settings: DEFAULT_UNIFIED_SETTINGS,+ });+ expect(fallback.selectedModel).toBe(h.model().model);+ expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toEqual(before);++ for (const modelSelection of [+ { ...pick, instanceId: CODEX_INSTANCE },+ { ...pick, model: "gpt-5.4" },+ { ...pick, options: [{ id: "reasoningEffort", value: "high" }] },+ {+ ...pick,+ options: [+ { id: "reasoningEffort", value: "low" },+ { id: "fastMode", value: true },+ ],+ },+ ]) {+ h.update({ modelSelection });+ expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toEqual(before);+ }+ h.update({ modelSelection: { ...pick, options: pick.options!.toReversed() } });+ expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toBeUndefined();+ });+it("keeps default-only model selections on the draft", () => {const store = useComposerDraftStore.getState();store.setModelSelection(threadRef, modelSelection(CODEX_DRIVER, "gpt-5.4"));diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.tsindex b93af955f32..57ffde65949 100644--- a/apps/web/src/composerDraftStore.ts+++ b/apps/web/src/composerDraftStore.ts@@ -37,7 +37,17 @@ import * as Schema from "effect/Schema";import * as Equal from "effect/Equal";import * as Effect from "effect/Effect";import { DeepMutable } from "effect/Types";-import { createModelSelection, normalizeModelSlug } from "@t3tools/shared/model";+import {+ createModelSelection,+ draftModelPickMatchesThread,+ normalizeModelSlug,+} from "@t3tools/shared/model";+import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";+import * as Option from "effect/Option";+import type {+ EnvironmentShellState,+ EnvironmentThreadShell,+} from "@t3tools/client-runtime/state/shell";import { getLocalStorageItem } from "./hooks/useLocalStorage";import { readThreadPreviewState } from "./previewStateStore";import { resolveAppModelSelection, resolveAppModelSelectionForInstance } from "./modelSelection";@@ -4139,6 +4149,75 @@ const composerDraftStore = create<ComposerDraftStoreState>()(export const useComposerDraftStore = composerDraftStore;+export function subscribeComposerDraftModelReconciliation(input: {+ readonly registry: AtomRegistry.AtomRegistry;+ readonly threadRefsAtom: Atom.Atom<ReadonlyArray<ScopedThreadRef>>;+ readonly threadShellAtom: (ref: ScopedThreadRef) => Atom.Atom<EnvironmentThreadShell | null>;+ readonly shellStateAtom: (+ environmentId: EnvironmentId,+ ) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentShellState, unknown>>;+}): () => void {+ const draftsAtom = Atom.make(composerDraftStore.getState());+ const unsubscribeDrafts = composerDraftStore.subscribe((state) =>+ input.registry.set(draftsAtom, state),+ );+ const threadKeysAtom = Atom.map(+ input.threadRefsAtom,+ (refs) => new Set(refs.map(scopedThreadKey)),+ );+ const matchesAtom = Atom.make((get) => {+ const state = get(draftsAtom);+ const threadKeys = get(threadKeysAtom);+ const matches: Array<readonly [string, ComposerThreadDraftState]> = [];+ for (const [key, draft] of Object.entries(state.draftsByThreadKey)) {+ // Local drafts can materialize a shell before their first turn is submitted.+ if (state.draftThreadsByThreadKey[key] || draft.activeProvider === null) continue;+ const ref = parseScopedThreadKey(key);+ const pick = draft.modelSelectionByProvider[draft.activeProvider];+ if (!ref || !pick || !threadKeys.has(key)) continue;+ const thread = get(input.threadShellAtom(ref));+ if (!thread || !draftModelPickMatchesThread(pick, thread.modelSelection)) continue;+ // Status and selection must come from the same emission; derived atoms can update apart.+ const shell = Option.getOrNull(+ AsyncResult.value(get(input.shellStateAtom(ref.environmentId))),+ );+ if (shell?.status !== "live") continue;+ const authoritativeThread = Option.getOrNull(shell.snapshot)?.threads.find(+ (candidate) => candidate.id === ref.threadId,+ );+ if (+ authoritativeThread &&+ draftModelPickMatchesThread(pick, authoritativeThread.modelSelection)+ ) {+ matches.push([key, draft]);+ }+ }+ return matches;+ });+ const unsubscribeMatches = input.registry.subscribe(+ matchesAtom,+ (matches) => {+ if (matches.length === 0) return;+ composerDraftStore.setState((state) => {+ const drafts = { ...state.draftsByThreadKey };+ for (const [key, matchedDraft] of matches) {+ if (drafts[key] !== matchedDraft) continue;+ const { modelSelectionExplicit: _explicit, ...retained } = matchedDraft;+ const draft = { ...retained, activeProvider: null, modelSelectionByProvider: {} };+ if (shouldRemoveDraft(draft)) delete drafts[key];+ else drafts[key] = draft;+ }+ return { draftsByThreadKey: drafts };+ });+ },+ { immediate: true },+ );+ return () => {+ unsubscribeMatches();+ unsubscribeDrafts();+ };+}+export function beginBackgroundDraftSubmissionByRef(threadRef: ScopedThreadRef): void {const threadKey = scopedThreadKey(threadRef);useComposerDraftStore.setState((state) => ({diff --git a/packages/shared/src/model.ts b/packages/shared/src/model.tsindex b1e7a7bd7cc..f382b6d4ecd 100644--- a/packages/shared/src/model.ts+++ b/packages/shared/src/model.ts@@ -116,6 +116,20 @@ export function modelSelectionsEqual(left: ModelSelection, right: ModelSelection);}+/**+ * Whether a composer's draft model pick is what the thread already runs. Web sends+ * `fastMode: false` for models with a fast toggle while mobile omits it, so off counts as unset.+ */+export function draftModelPickMatchesThread(pick: ModelSelection, thread: ModelSelection): boolean {+ const withoutFastModeOff = (selection: ModelSelection) =>+ createModelSelection(+ selection.instanceId,+ selection.model,+ selection.options?.filter((option) => option.id !== "fastMode" || option.value !== false),+ );+ return modelSelectionsEqual(withoutFastModeOff(pick), withoutFastModeOff(thread));+}+function resolveDescriptorChoiceValue(descriptor: Extract<ProviderOptionDescriptor, { type: "select" }>,raw: string | null | undefined,