Skip to content

Commit 4837afc

Browse files
shivamhwpclaude
andcommitted
fix(composer): restore mobile import and drop receipt-based pick release
Draft reconciliation already releases a pick once the durable model matches and nothing is pending, so the receipt release and its tests are redundant. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 75e361e commit 4837afc

15 files changed

Lines changed: 39 additions & 207 deletions

‎apps/mobile/src/state/thread-model-selection.ts‎

Lines changed: 12 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -7,48 +7,42 @@ import {
77
type ServerProvider,
88
type ThreadId,
99
} from "@t3tools/contracts";
10-
import { threadModelPickAppliesNow } from "@t3tools/shared/model";
1110

1211
import { scopedThreadKey } from "../lib/scopedEntities";
1312
import { appAtomRegistry } from "./atom-registry";
1413
import { readEnvironmentScope } from "./session";
1514
import { environmentThreadShells, threadEnvironment } from "./threads";
16-
import {
17-
releaseComposerDraftModelSelection,
18-
updateComposerDraftSettings,
19-
} from "./use-composer-drafts";
15+
import { updateComposerDraftSettings } from "./use-composer-drafts";
2016

2117
/** Sets an existing thread's pick on the thread, so any next turn runs on it. */
2218
export function selectThreadModel(
2319
ref: { readonly environmentId: EnvironmentId; readonly threadId: ThreadId },
24-
value: ModelSelection,
20+
modelSelection: ModelSelection,
2521
providers: ReadonlyArray<ServerProvider>,
2622
): void {
27-
const threadKey = scopedThreadKey(ref.environmentId, ref.threadId);
28-
// Its own object, so an older reply for an equal pick cannot release this one.
29-
const pick = { ...value };
30-
const provider = providers.find((candidate) => candidate.instanceId === pick.instanceId);
23+
const provider = providers.find(
24+
(candidate) => candidate.instanceId === modelSelection.instanceId,
25+
);
3126
// A provider without the interaction-mode toggle runs in the default mode.
32-
updateComposerDraftSettings(threadKey, {
33-
modelSelection: pick,
27+
updateComposerDraftSettings(scopedThreadKey(ref.environmentId, ref.threadId), {
28+
modelSelection,
3429
...(provider?.showInteractionModeToggle === false
3530
? { interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE }
3631
: {}),
3732
});
3833
const thread = appAtomRegistry.get(environmentThreadShells.threadShellAtom(ref));
39-
if (!thread) return;
34+
// Another instance replaces the live session, which may hold an open question; that pick
35+
// still waits for a sent message.
4036
if (
41-
!threadModelPickAppliesNow(pick, thread.modelSelection) ||
37+
thread?.modelSelection.instanceId !== modelSelection.instanceId ||
4238
!readEnvironmentScope(ref.environmentId, AuthOrchestrationOperateScope)
4339
) {
4440
return;
4541
}
4642
void runAtomCommand(
4743
appAtomRegistry,
4844
threadEnvironment.setModelSelection,
49-
{ environmentId: ref.environmentId, input: { threadId: ref.threadId, modelSelection: pick } },
45+
{ environmentId: ref.environmentId, input: { threadId: ref.threadId, modelSelection } },
5046
{ label: "change model", reportFailure: true, reportDefect: true },
51-
).then((result) => {
52-
if (result._tag === "Success") releaseComposerDraftModelSelection(threadKey, pick);
53-
});
47+
);
5448
}

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

Lines changed: 14 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -129,10 +129,7 @@ const modelCommandMocks = vi.hoisted(() => ({
129129
setModelSelection: Symbol("set-model-selection"),
130130
canOperate: true,
131131
thread: null as unknown,
132-
runs: [] as Array<{
133-
readonly value: unknown;
134-
readonly settle: (result: { readonly _tag: "Success" | "Failure" }) => void;
135-
}>,
132+
runs: [] as Array<unknown>,
136133
}));
137134

138135
const incomingShareStorageMocks = vi.hoisted(() => ({
@@ -175,7 +172,8 @@ vi.mock("@t3tools/client-runtime/state/runtime", () => ({
175172
if (command !== modelCommandMocks.setModelSelection) {
176173
throw new Error("Unexpected network command in the inline read test");
177174
}
178-
return new Promise((settle) => modelCommandMocks.runs.push({ value, settle }));
175+
modelCommandMocks.runs.push(value);
176+
return Promise.resolve();
179177
},
180178
squashAtomCommandFailure: (result: { readonly error: unknown }) => result.error,
181179
}));
@@ -525,57 +523,33 @@ describe("mobile composer drafts", () => {
525523
expect(appAtomRegistry.get(composerDraftsAtom)[key]).toBeUndefined();
526524
});
527525

528-
it("applies an existing thread's pick now and releases only the latest accepted pick", async () => {
526+
it("sets an existing thread's pick on the thread only within its instance and with operate access", () => {
529527
const environmentId = EnvironmentId.make("environment-1");
530528
const threadId = ThreadId.make("thread-1");
531529
const key = `${environmentId}:${threadId}`;
532530
const codex = ProviderInstanceId.make("codex");
533531
modelCommandMocks.runs.length = 0;
534532
modelCommandMocks.canOperate = true;
535-
const initialThread = {
533+
modelCommandMocks.thread = {
536534
...v2ThreadShell,
537535
id: threadId,
538536
environmentId,
539537
modelSelection: { instanceId: codex, model: "gpt-5.4" },
540538
};
541-
modelCommandMocks.thread = initialThread;
542-
setComposerDraftText(key, "keep this unsent follow-up");
543-
const first = { instanceId: codex, model: "gpt-5.5" };
544-
const latest = { ...first };
545-
selectThreadModel({ environmentId, threadId }, first, []);
546-
modelCommandMocks.thread = { ...initialThread, modelSelection: first };
547-
selectThreadModel({ environmentId, threadId }, latest, []);
548-
expect(modelCommandMocks.runs.map((run) => run.value)).toEqual([
549-
{ environmentId, input: { threadId, modelSelection: first } },
550-
{ environmentId, input: { threadId, modelSelection: latest } },
539+
const pick = { instanceId: codex, model: "gpt-5.5" };
540+
selectThreadModel({ environmentId, threadId }, pick, []);
541+
expect(modelCommandMocks.runs).toEqual([
542+
{ environmentId, input: { threadId, modelSelection: pick } },
551543
]);
552544

553-
modelCommandMocks.runs[0]!.settle({ _tag: "Failure" });
554-
await Promise.resolve();
555-
expect(getComposerDraftSnapshot(key).modelSelection).toEqual(latest);
556-
modelCommandMocks.runs[1]!.settle({ _tag: "Success" });
557-
await Promise.resolve();
558-
expect(getComposerDraftSnapshot(key).text).toBe("keep this unsent follow-up");
559-
expect(getComposerDraftSnapshot(key).modelSelection).toBeUndefined();
560-
561-
// A rejected pick stays the composer's choice, as before.
562-
modelCommandMocks.thread = {
563-
...initialThread,
564-
modelSelection: { instanceId: codex, model: "gpt-5.4" },
565-
};
566-
selectThreadModel({ environmentId, threadId }, first, []);
567-
modelCommandMocks.runs[2]!.settle({ _tag: "Failure" });
568-
await Promise.resolve();
569-
expect(getComposerDraftSnapshot(key).modelSelection).toEqual(first);
570-
571-
// Another provider instance would replace the live session, and a read-only
572-
// connection cannot change the thread: both picks wait for a sent message.
545+
// Another instance would replace the live session, and a read-only connection cannot
546+
// change the thread: both picks wait for a sent message.
573547
const claude = { instanceId: ProviderInstanceId.make("claudeAgent"), model: "claude-opus-5-5" };
574548
selectThreadModel({ environmentId, threadId }, claude, []);
575549
modelCommandMocks.canOperate = false;
576-
selectThreadModel({ environmentId, threadId }, latest, []);
577-
expect(modelCommandMocks.runs).toHaveLength(3);
578-
expect(getComposerDraftSnapshot(key).modelSelection).toEqual(latest);
550+
selectThreadModel({ environmentId, threadId }, pick, []);
551+
expect(modelCommandMocks.runs).toHaveLength(1);
552+
expect(getComposerDraftSnapshot(key).modelSelection).toEqual(pick);
579553
});
580554

581555
it("releases an inactive thread pick only after its queued model becomes durable", () => {

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

Lines changed: 0 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1542,20 +1542,6 @@ export function updateComposerDraftSettings(
15421542
});
15431543
}
15441544

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-
15591545
export function setFreshSessionPending(draftKey: string, pending: boolean): void {
15601546
if ((getComposerDraftSnapshot(draftKey).freshContext === true) === pending) return;
15611547
updateComposerDraftSettings(draftKey, { freshContext: pending ? true : undefined });

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import {
2424
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
2525
orchestrationV2WorktreePending,
2626
type EnvironmentId,
27+
type ModelSelection,
2728
type ProviderInteractionMode,
2829
type RuntimeMode,
2930
type ScopedThreadRef,

‎apps/web/src/components/ChatView.modelPick.browser.test.tsx‎

Lines changed: 3 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import { createMemoryHistory } from "@tanstack/react-router";
2-
import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
32
import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
43
import type * as Context from "effect/Context";
54
import { expect, it, vi } from "vite-plus/test";
@@ -9,7 +8,6 @@ import { AppRoot } from "~/AppRoot";
98
// The route loads ChatView lazily, and its first transform (React Compiler over ~4k lines)
109
// takes 6-11s; importing it here keeps that out of the test's timeout.
1110
import "~/components/ChatView";
12-
import { useComposerDraftStore } from "~/composerDraftStore";
1311
import { __setClientSettingsForTests } from "~/hooks/useSettings";
1412
import { getRouter } from "~/router";
1513
import {
@@ -54,36 +52,16 @@ it("a model picked for an existing thread reaches the server before any message
5452
});
5553
await expect.element(page.getByText("Answer 0 for thread-model-pick.")).toBeVisible();
5654

57-
const threadKey = scopedThreadKey(scopeThreadRef(ENVIRONMENT_ID, thread.id));
58-
const modelSets = () =>
59-
dispatchedCommands().filter((command) => command.type === "thread.model-selection.set");
60-
61-
// Every explicit pick waits for acceptance, even when the optimistic shell already shows it.
6255
await page.getByRole("button", { name: "GPT-5.4", exact: true }).click();
63-
await page.getByRole("option", { name: /GPT-5\.4/ }).click();
64-
await vi.waitFor(() =>
65-
expect(useComposerDraftStore.getState().draftsByThreadKey[threadKey]).toBeUndefined(),
66-
);
67-
expect(modelSets()).toEqual([
68-
expect.objectContaining({
69-
threadId: thread.id,
70-
modelSelection: expect.objectContaining({ instanceId: "codex", model: "gpt-5.4" }),
71-
}),
72-
]);
73-
74-
// The picker stays open after a pick.
7556
await page.getByRole("option", { name: /GPT-5\.5/ }).click();
7657
await vi.waitFor(() =>
77-
expect(modelSets().slice(1)).toEqual([
58+
expect(
59+
dispatchedCommands().filter((command) => command.type === "thread.model-selection.set"),
60+
).toEqual([
7861
expect.objectContaining({
7962
threadId: thread.id,
8063
modelSelection: expect.objectContaining({ instanceId: "codex", model: "gpt-5.5" }),
8164
}),
8265
]),
8366
);
84-
// The accepted pick leaves the draft, and the thread shows it until its event arrives.
85-
await vi.waitFor(() =>
86-
expect(useComposerDraftStore.getState().draftsByThreadKey[threadKey]).toBeUndefined(),
87-
);
88-
await expect.element(page.getByRole("button", { name: "GPT-5.5", exact: true })).toBeVisible();
8967
});

‎apps/web/src/components/chat/ChatComposer.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2999,7 +2999,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
29992999
model: selectedModel,
30003000
persistSticky: true,
30013001
});
3002-
void applyThreadModelPick(composerDraftTarget);
3002+
applyThreadModelPick(composerDraftTarget);
30033003
if (change.prompt !== promptRef.current) {
30043004
applyPromptReplacementStable(0, promptRef.current.length, change.prompt, {
30053005
expandedCursorAfterReplace: change.cursor,

‎apps/web/src/components/chat/ComposerControlsBar.tsx‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -155,9 +155,7 @@ export function ComposerControlsBar(props: {
155155
});
156156
const controlSize = composerControlsCollapsed ? "xs" : "sm";
157157
const applyThreadModelPick = useApplyThreadModelPick();
158-
const applyRouteThreadModelPick = useStableCallback(
159-
() => void applyThreadModelPick(routeThreadRef),
160-
);
158+
const applyRouteThreadModelPick = useStableCallback(() => applyThreadModelPick(routeThreadRef));
161159
const traitsInput = resolveComposerTraitsInput({
162160
provider: selectedProvider,
163161
instanceId: selectedInstanceId,
Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import { RegistryContext } from "@effect/atom-react";
22
import { scopedThreadKey } from "@t3tools/client-runtime/environment";
3-
import { threadModelPickAppliesNow } from "@t3tools/shared/model";
43
import { useContext } from "react";
54

65
import { type ComposerThreadTarget, useComposerDraftStore } from "../../composerDraftStore";
@@ -13,21 +12,20 @@ export function useApplyThreadModelPick() {
1312
const setModelSelection = useOrchestrationCommand(threadEnvironment.setModelSelection, {
1413
label: "change model",
1514
});
16-
return async (target: ComposerThreadTarget) => {
15+
return (target: ComposerThreadTarget) => {
1716
if (typeof target === "string") return;
1817
const store = useComposerDraftStore.getState();
1918
const draft = store.draftsByThreadKey[scopedThreadKey(target)];
2019
if (!draft?.modelSelectionExplicit || !draft.activeProvider) return;
2120
const pick = draft.modelSelectionByProvider[draft.activeProvider];
2221
const thread = registry.get(environmentThreadShells.threadShellAtom(target));
2322
if (!pick || !thread || store.draftThreadsByThreadKey[scopedThreadKey(target)]) return;
24-
if (!threadModelPickAppliesNow(pick, thread.modelSelection)) return;
25-
const result = await setModelSelection({
23+
// Another instance replaces the live session, which may hold an open question; that pick
24+
// still waits for a sent message.
25+
if (pick.instanceId !== thread.modelSelection.instanceId) return;
26+
void setModelSelection({
2627
environmentId: target.environmentId,
2728
input: { threadId: target.threadId, modelSelection: pick },
2829
});
29-
if (result._tag === "Success") {
30-
useComposerDraftStore.getState().releaseModelSelection(target, pick);
31-
}
3230
};
3331
}

‎apps/web/src/components/chat/useComposerSelection.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -213,7 +213,7 @@ export function useComposerSelection(input: ComposerSelectionInput) {
213213
replaceOptions: true,
214214
});
215215
setStickyComposerModelSelection(nextModelSelection);
216-
if (!isLocalDraftThread) void applyThreadModelPick(threadRef);
216+
if (!isLocalDraftThread) applyThreadModelPick(threadRef);
217217
if (options?.focusComposer !== false) scheduleComposerFocus();
218218
};
219219
const onProviderModelSelectStable = useStableCallback(onProviderModelSelect);

‎apps/web/src/composerDraftStore.test.ts‎

Lines changed: 0 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1587,7 +1587,6 @@ describe("composerDraftStore modelSelection", () => {
15871587
const store = useComposerDraftStore.getState();
15881588
const original = h.model();
15891589
const other = { ...original, model: "remote-model" };
1590-
store.setPrompt(threadRef, "keep this unsent follow-up");
15911590
store.setModelSelection(threadRef, other, { explicit: true });
15921591
h.showInFlightPick(other);
15931592
store.setModelSelection(threadRef, original, { explicit: true });
@@ -1600,50 +1599,6 @@ describe("composerDraftStore modelSelection", () => {
16001599
h.showInFlightPick(null);
16011600
expect(h.model()).toEqual(other);
16021601
expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toBe(latest);
1603-
1604-
// With nothing in flight, a matching durable model still reconciles the pick.
1605-
h.update({ modelSelection: original });
1606-
expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toMatchObject({
1607-
prompt: "keep this unsent follow-up",
1608-
activeProvider: null,
1609-
modelSelectionByProvider: {},
1610-
});
1611-
});
1612-
1613-
it("releases an accepted pick only while it is still the draft's latest choice", () => {
1614-
const store = useComposerDraftStore.getState();
1615-
store.setPrompt(threadRef, "keep this unsent follow-up");
1616-
store.setRuntimeMode(threadRef, "approval-required");
1617-
store.setModelSelection(threadRef, modelSelection(CODEX_DRIVER, "gpt-5.5"), {
1618-
explicit: true,
1619-
});
1620-
const first = draftFor(threadId, TEST_ENVIRONMENT_ID)!.modelSelectionByProvider[
1621-
CODEX_INSTANCE
1622-
]!;
1623-
store.setModelSelection(threadRef, modelSelection(CODEX_DRIVER, "gpt-5.4"), {
1624-
explicit: true,
1625-
});
1626-
store.setModelSelection(threadRef, modelSelection(CODEX_DRIVER, "gpt-5.5"), {
1627-
explicit: true,
1628-
});
1629-
const latest = draftFor(threadId, TEST_ENVIRONMENT_ID)!;
1630-
1631-
// An older acknowledgement of the same model is not the latest pick.
1632-
store.releaseModelSelection(threadRef, first);
1633-
expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toBe(latest);
1634-
store.releaseModelSelection(
1635-
scopeThreadRef(OTHER_TEST_ENVIRONMENT_ID, threadId),
1636-
latest.modelSelectionByProvider[CODEX_INSTANCE]!,
1637-
);
1638-
expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toBe(latest);
1639-
1640-
store.releaseModelSelection(threadRef, latest.modelSelectionByProvider[CODEX_INSTANCE]!);
1641-
const { modelSelectionExplicit: _explicit, ...retained } = latest;
1642-
expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toEqual({
1643-
...retained,
1644-
activeProvider: null,
1645-
modelSelectionByProvider: {},
1646-
});
16471602
});
16481603

16491604
it("releases an inactive thread pick only after its queued model becomes durable", () => {

0 commit comments

Comments
 (0)