Skip to content

Commit 71e887d

Browse files
shivamhwpclaude
andcommitted
fix(chat): a pick matching the old model waits for earlier picks in flight
Picking B then A again showed A over the pending B, and A also matched the durable model, so value-only reconciliation cleared the A draft before its own reply. If B then landed and A was rejected, the thread showed B with no trace of the A pick. Reconciliation now skips a thread while it has optimistic updates in flight, read from the thread lifecycle's pending list, on web and mobile. Once they settle it compares the draft with the durable model as before, so hydrated drafts and delivered queued picks still reconcile. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent aac0988 commit 71e887d

9 files changed

Lines changed: 77 additions & 4 deletions

File tree

‎apps/mobile/src/App.tsx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ import {
4848
import { RootStack, rootPathnameFromState, workspaceLocationFromState } from "./Stack";
4949
import { appAtomRegistry } from "./state/atom-registry";
5050
import { subscribeComposerDraftModelReconciliation } from "./state/use-composer-drafts";
51-
import { environmentThreadShells } from "./state/threads";
51+
import { environmentThreadShells, threadEnvironment } from "./state/threads";
5252
import { environmentShell } from "./state/shell";
5353
import { OverlayPortalHost } from "./components/ui/OverlayPortal";
5454
import { shouldHandleAppLink, restoreDraftLinkState } from "./lib/appLinking";
@@ -186,6 +186,7 @@ const appServiceDisposers = [
186186
threadShellAtom: environmentThreadShells.threadShellAtom,
187187
threadRefsAtom: environmentThreadShells.threadRefsAtom,
188188
shellStateAtom: environmentShell.stateAtom,
189+
pendingThreadIdsAtom: threadEnvironment.pendingThreadIdsAtom,
189190
}),
190191
installAppearanceRuntime(),
191192
installSubscriptionUsageRefresh(),

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -334,6 +334,7 @@ function modelReconciliationHarness(
334334
],
335335
]),
336336
});
337+
const noPendingThreadIdsAtom = Atom.make((): ReadonlySet<ThreadId> => new Set());
337338
const shells = createEnvironmentThreadShellAtoms({
338339
catalogValueAtom,
339340
snapshotAtom: () => snapshotAtom,
@@ -347,6 +348,7 @@ function modelReconciliationHarness(
347348
threadShellAtom: shells.threadShellAtom,
348349
threadRefsAtom: shells.threadRefsAtom,
349350
shellStateAtom: () => shellResultAtom,
351+
pendingThreadIdsAtom: () => noPendingThreadIdsAtom,
350352
}),
351353
);
352354
flush();

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import {
1919
type ProviderOptionSelection,
2020
type RuntimeMode,
2121
type ScopedThreadRef,
22+
type ThreadId,
2223
} from "@t3tools/contracts";
2324
import * as Schema from "effect/Schema";
2425
import { useEffect, useState } from "react";
@@ -1571,6 +1572,7 @@ export function subscribeComposerDraftModelReconciliation(input: {
15711572
readonly shellStateAtom: (
15721573
environmentId: EnvironmentId,
15731574
) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentShellState, unknown>>;
1575+
readonly pendingThreadIdsAtom: (environmentId: EnvironmentId) => Atom.Atom<ReadonlySet<ThreadId>>;
15741576
}): () => void {
15751577
const draftsAtom = Atom.make(appAtomRegistry.get(composerDraftsAtom));
15761578
const unsubscribeDrafts = appAtomRegistry.subscribe(composerDraftsAtom, (drafts) =>
@@ -1590,6 +1592,8 @@ export function subscribeComposerDraftModelReconciliation(input: {
15901592
const thread = get(input.threadShellAtom(ref));
15911593
if (!thread || !draftModelPickMatchesThread(draft.modelSelection, thread.modelSelection))
15921594
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;
15931597
// Status and selection must come from the same emission; derived atoms can update apart.
15941598
const shell = AsyncResult.getOrElse(get(input.shellStateAtom(ref.environmentId)), () => null);
15951599
if (shell?.status !== "live") continue;

‎apps/web/src/appInit.tsx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ import { installChatRouteCommands } from "./shortcuts/chatRouteCommands";
5353
import { startWorkspaceFocus } from "./lib/workspaceFocus";
5454
import { installCommandPaletteCommands } from "./shortcuts/commandPaletteCommands";
5555
import { registerOpenFavoriteEditorCommand } from "./components/chat/OpenInPickerShortcut";
56-
import { environmentThreadShells } from "./state/threads";
56+
import { environmentThreadShells, threadEnvironment } from "./state/threads";
5757
import { resolveThreadRouteTarget } from "./threadRoutes";
5858

5959
/** Writes appearance settings onto the document, touching only the groups that changed. */
@@ -203,6 +203,7 @@ export function startAppServices(): AppRouter {
203203
threadShellAtom: environmentThreadShells.threadShellAtom,
204204
threadRefsAtom: environmentThreadShells.threadRefsAtom,
205205
shellStateAtom: environmentShell.stateAtom,
206+
pendingThreadIdsAtom: threadEnvironment.pendingThreadIdsAtom,
206207
});
207208
startMainAppLocationTracking(router);
208209
startWorkspaceFocus(router);

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

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1332,9 +1332,26 @@ function modelReconciliationHarness(
13321332
],
13331333
]),
13341334
});
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+
);
13351352
const shells = createEnvironmentThreadShellAtoms({
13361353
catalogValueAtom,
1337-
snapshotAtom: () => snapshotAtom,
1354+
snapshotAtom: () => visibleSnapshotAtom,
13381355
hiddenThreadTagsAtom: () => Atom.make(null),
13391356
});
13401357
const selectedShell = shells.threadShellAtom({ environmentId, threadId: selectedThreadId });
@@ -1345,11 +1362,16 @@ function modelReconciliationHarness(
13451362
threadShellAtom: shells.threadShellAtom,
13461363
threadRefsAtom: shells.threadRefsAtom,
13471364
shellStateAtom: () => shellResultAtom,
1365+
pendingThreadIdsAtom: () => pendingThreadIdsAtom,
13481366
}),
13491367
);
13501368
flush();
13511369
return {
13521370
flush,
1371+
showInFlightPick(pick: ModelSelection | null) {
1372+
registry.set(inFlightPickAtom, pick);
1373+
flush();
1374+
},
13531375
setStatus(status: EnvironmentShellStatus) {
13541376
registry.set(shellStateAtom, { ...registry.get(shellStateAtom), status });
13551377
flush();
@@ -1560,6 +1582,34 @@ describe("composerDraftStore modelSelection", () => {
15601582
expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toBeUndefined();
15611583
});
15621584

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.setPrompt(threadRef, "keep this unsent follow-up");
1591+
store.setModelSelection(threadRef, other, { explicit: true });
1592+
h.showInFlightPick(other);
1593+
store.setModelSelection(threadRef, original, { explicit: true });
1594+
h.showInFlightPick(original);
1595+
const latest = draftFor(threadId, TEST_ENVIRONMENT_ID);
1596+
expect(latest?.modelSelectionByProvider[original.instanceId]).toEqual(original);
1597+
1598+
// The earlier pick lands, then the latest one is rejected.
1599+
h.update({ modelSelection: other });
1600+
h.showInFlightPick(null);
1601+
expect(h.model()).toEqual(other);
1602+
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+
15631613
it("releases an accepted pick only while it is still the draft's latest choice", () => {
15641614
const store = useComposerDraftStore.getState();
15651615
store.setPrompt(threadRef, "keep this unsent follow-up");

‎apps/web/src/composerDraftStore.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4271,6 +4271,7 @@ export function subscribeComposerDraftModelReconciliation(input: {
42714271
readonly shellStateAtom: (
42724272
environmentId: EnvironmentId,
42734273
) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentShellState, unknown>>;
4274+
readonly pendingThreadIdsAtom: (environmentId: EnvironmentId) => Atom.Atom<ReadonlySet<ThreadId>>;
42744275
}): () => void {
42754276
const draftsAtom = Atom.make(composerDraftStore.getState());
42764277
const unsubscribeDrafts = composerDraftStore.subscribe((state) =>
@@ -4292,6 +4293,8 @@ export function subscribeComposerDraftModelReconciliation(input: {
42924293
if (!ref || !pick || !threadKeys.has(key)) continue;
42934294
const thread = get(input.threadShellAtom(ref));
42944295
if (!thread || !draftModelPickMatchesThread(pick, thread.modelSelection)) continue;
4296+
// The pick can match an old model while an earlier pick in flight still replaces it.
4297+
if (get(input.pendingThreadIdsAtom(ref.environmentId)).has(ref.threadId)) continue;
42954298
// Status and selection must come from the same emission; derived atoms can update apart.
42964299
const shell = AsyncResult.getOrElse(get(input.shellStateAtom(ref.environmentId)), () => null);
42974300
if (shell?.status !== "live") continue;

‎packages/client-runtime/src/state/threadCommands.test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -312,11 +312,14 @@ describe("remote thread lifecycle commands", () => {
312312
},
313313
});
314314
expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(expected);
315+
const pending = h.commands.pendingThreadIdsAtom(ENVIRONMENT_ID);
316+
expect(h.registry.get(pending)).toEqual(new Set([THREAD_ID]));
315317
const request = yield* Queue.take(h.requests);
316318
expect(h.registry.get(source)).toBe(initial);
317319
yield* Deferred.fail(request.reply, new Error("Remote rejected the action"));
318320
expect((yield* Effect.promise(() => result))._tag).toBe("Failure");
319321
expect(h.registry.get(h.visibleAtom)).toBe(initial);
322+
expect(h.registry.get(pending)).toEqual(new Set());
320323
}),
321324
);
322325

‎packages/client-runtime/src/state/threadCommands.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -386,6 +386,7 @@ export function createThreadEnvironmentAtoms<R, E>(
386386
return {
387387
...commands,
388388
snapshotAtom: optimistic.snapshotAtom,
389+
pendingThreadIdsAtom: optimistic.pendingThreadIdsAtom,
389390
settle: optimistic.wrap(commands.settle, (thread, _input, now, accepted) =>
390391
!accepted &&
391392
(thread.pendingRuntimeRequest !== null ||

‎packages/client-runtime/src/state/threadLifecycle.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,14 @@ export function createOptimisticThreadLifecycle(
4848
}),
4949
);
5050

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+
5159
function wrap<Input extends { readonly threadId: ThreadId }, E>(
5260
command: AtomCommand<
5361
{ readonly environmentId: EnvironmentId; readonly input: Input },
@@ -98,5 +106,5 @@ export function createOptimisticThreadLifecycle(
98106
};
99107
}
100108

101-
return { snapshotAtom, wrap };
109+
return { snapshotAtom, pendingThreadIdsAtom, wrap };
102110
}

0 commit comments

Comments
 (0)