Skip to content

Commit f3a19b4

Browse files
committed
fix(app-shell): the assistant's picked model survives the first send's pane remount (#32994)
The chat hosts key ChatPane on the conversation id and the first send mints it, so the pane remounts mid-send. The composer's model pick was pane state and died there: the replayed first message sent the default model and the picker snapped back. The hosts (AiChatPage, the console dock, the Studio copilot) now own the pick and pass it to the pane. Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016WV4czLbpetCrYUqeRsq85
1 parent ee9ad83 commit f3a19b4

5 files changed

Lines changed: 277 additions & 1 deletion

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
---
4+
5+
fix(app-shell): the model picked in the AI assistant composer is the model the chat request sends, from the first message of a new conversation on, and the picker keeps showing it
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
Every chat host (the full-page `/ai/build` and `/ai/ask` surfaces, the console dock, the Studio copilot) keys its chat pane on the conversation id, and the first send creates that conversation, so the pane remounts mid-send. The pick lived inside the pane and was dropped there: the first message went out with the environment's default model and the picker snapped back to it. The hosts now hold the pick, so it survives the remount.

‎ui/packages/app-shell/src/console/ai/AiChatPage.tsx‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1218,6 +1218,10 @@ export function AiChatPage({ apiBase: apiBaseProp, defaultAgent: defaultAgentPro
12181218
// remount that the id-resolution triggers; the freshly-mounted pane replays it
12191219
// via useDeferredFirstSend. See that hook for the full race.
12201220
const pendingFirstMessageRef = useRef<PendingFirstMessage | null>(null);
1221+
// ADR-0028 — the composer's picked model, owned by the PAGE for the same
1222+
// reason: it must survive the keyed <ChatPane> remount, or the pane that
1223+
// replays the first message sends (and shows) the default instead.
1224+
const [selectedModelId, setSelectedModelId] = useState<string | undefined>(undefined);
12211225
// Bumped whenever the pending ref is set OUT OF BAND (the handoff seed below).
12221226
// ChatPane's deferred-send replay lists this in its deps, so it re-runs and
12231227
// fires the seed even when the conversation id was ALREADY minted. Without it a
@@ -1659,6 +1663,8 @@ export function AiChatPage({ apiBase: apiBaseProp, defaultAgent: defaultAgentPro
16591663
pendingFirstMessageRef={pendingFirstMessageRef}
16601664
pendingFirstMessageSeq={pendingFirstMessageSeq}
16611665
ensureConversation={ensureConversation}
1666+
selectedModelId={selectedModelId}
1667+
onSelectedModelChange={setSelectedModelId}
16621668
onSent={handleSent}
16631669
onShare={() => setShareOpen(true)}
16641670
onDebug={() => setDebugOpen(true)}
@@ -1733,6 +1739,17 @@ interface ChatPaneProps {
17331739
* `useChatConversation().ensureConversation`); no row exists before it.
17341740
* See {@link useDeferredFirstSend}. */
17351741
ensureConversation?: () => unknown;
1742+
/**
1743+
* ADR-0028 — the model the user picked in the composer, held by the HOST.
1744+
* The pane is keyed on the conversation id and remounts when the first send
1745+
* mints it, so a pick kept inside the pane would be dropped right then: the
1746+
* replayed first message and every later turn would go out with the default
1747+
* while the picker had shown the pick. A host that keys the pane passes this
1748+
* pair; absent, the pane holds the pick itself for its own lifetime.
1749+
*/
1750+
selectedModelId?: string;
1751+
/** ADR-0028 — records a pick; paired with {@link ChatPaneProps.selectedModelId}. */
1752+
onSelectedModelChange?: (modelId: string) => void;
17361753
onSent: (firstUserMessage?: string) => void;
17371754
onShare: () => void;
17381755
/** Opens the Build Doctor drawer (build agent only). */
@@ -1762,6 +1779,8 @@ export function ChatPane({
17621779
pendingFirstMessageRef,
17631780
pendingFirstMessageSeq,
17641781
ensureConversation,
1782+
selectedModelId: hostSelectedModelId,
1783+
onSelectedModelChange,
17651784
onSent,
17661785
onShare,
17671786
onDebug,
@@ -2016,7 +2035,12 @@ export function ChatPane({
20162035
// AI service answers that catalog empty and `/models` with a 501.
20172036
const { models: aiModels, defaultModelId } = useAiModels({ apiBase, enabled: agents.length > 0 });
20182037
const selectedApp = activeAppPackageId || editPackageId || undefined;
2019-
const [selectedModelId, setSelectedModelId] = useState<string | undefined>(undefined);
2038+
// The pick outlives this pane only when the host holds it (see the props).
2039+
const [paneSelectedModelId, setPaneSelectedModelId] = useState<string | undefined>(undefined);
2040+
const hostHoldsModel = onSelectedModelChange !== undefined;
2041+
const selectedModelId = hostHoldsModel ? hostSelectedModelId : paneSelectedModelId;
2042+
const setSelectedModelId = hostHoldsModel ? onSelectedModelChange : setPaneSelectedModelId;
2043+
// The one value both the picker shows and the request sends.
20202044
const effectiveModelId = selectedModelId ?? defaultModelId;
20212045

20222046
const {
Lines changed: 232 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,232 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* objectstack#32994 — the model a user picks in the composer is the model the
5+
* chat request sends, on the first turn of a new conversation and after it.
6+
*
7+
* Every chat host keys `ChatPane` on the conversation id, and the first send
8+
* mints that id (objectstack#32031), so the pane remounts mid-send. A pick held
9+
* inside the pane died with it: the replayed first message went out with the
10+
* environment default and the picker snapped back to it.
11+
*
12+
* ## Real subjects
13+
*
14+
* The full-page build surface (`AiChatPage` at `/ai/build`) and the console
15+
* dock body (`ChatDockConversation`), each with the REAL `ChatPane`, the REAL
16+
* `useChatConversation` and the REAL `useObjectChat` transport. What is pinned
17+
* is the `model` of the JSON body of each POST to the agent's chat route
18+
* (captured off a `fetch` stub), and the `selectedModelId` the pane hands the
19+
* composer, which is the value its model picker shows. The stand-ins: the agent
20+
* catalog, the model allowlist (three models, Haiku the default), and
21+
* `ChatbotEnhanced` (a recorder exposing the composer's send and pick).
22+
*
23+
* Pins, on both surfaces:
24+
* - a pick made before the first message rides that message, and the next one;
25+
* - after each send the picker still shows the pick;
26+
* - CONTROL: with no pick the default model is sent and shown, as before.
27+
*/
28+
29+
import '@testing-library/jest-dom/vitest';
30+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
31+
import { act, cleanup, render, waitFor } from '@testing-library/react';
32+
import { MemoryRouter, Route, Routes } from 'react-router-dom';
33+
import React from 'react';
34+
35+
const HAIKU = 'anthropic/claude-haiku-5.5';
36+
const SONNET = 'anthropic/claude-sonnet-5.5';
37+
const MODELS = [
38+
{ id: 'openai/gpt-5.6-luna', label: 'Standard' },
39+
{ id: HAIKU, label: 'Fast' },
40+
{ id: SONNET, label: 'Advanced' },
41+
];
42+
43+
const state = {
44+
/** The latest props `ChatPane` handed the composer. */
45+
pane: undefined as
46+
| {
47+
onSendMessage?: (text: string) => void;
48+
onModelChange?: (modelId: string) => void;
49+
selectedModelId?: string;
50+
}
51+
| undefined,
52+
/** The JSON body of every chat POST, in order. */
53+
sent: [] as Array<{ model?: string }>,
54+
minted: 0,
55+
};
56+
57+
vi.mock('@object-ui/plugin-chatbot', async (importOriginal) => {
58+
const actual = await importOriginal<Record<string, unknown>>();
59+
return {
60+
...actual,
61+
useAiModels: () => ({ models: MODELS, defaultModelId: HAIKU }),
62+
useHitlInChat: () => ({ decide: vi.fn(), decisions: {} }),
63+
ChatbotEnhanced: (props: typeof state.pane) => {
64+
state.pane = props;
65+
return <div data-testid="pane" />;
66+
},
67+
};
68+
});
69+
vi.mock('@object-ui/plugin-chatbot/core', async (importOriginal) => ({
70+
...(await importOriginal<typeof import('@object-ui/plugin-chatbot/core')>()),
71+
useAgents: () => ({
72+
agents: [{ name: 'build', label: 'Build', capabilities: ['build'] }],
73+
isLoading: false,
74+
loading: false,
75+
error: undefined,
76+
refetch: vi.fn(),
77+
}),
78+
}));
79+
vi.mock('@object-ui/auth', async (importOriginal) => ({
80+
...(await importOriginal<Record<string, unknown>>()),
81+
useAuth: () => ({ user: { id: 'u1' } }),
82+
}));
83+
vi.mock('../../../providers/MetadataProvider', async (importOriginal) => ({
84+
...(await importOriginal<Record<string, unknown>>()),
85+
useMetadata: () => ({ apps: [] }),
86+
}));
87+
vi.mock('../../../providers/AdapterProvider', async (importOriginal) => ({
88+
...(await importOriginal<Record<string, unknown>>()),
89+
useAdapter: () => null,
90+
}));
91+
vi.mock('../../../hooks/useCanAuthorMetadata', () => ({ useCanAuthorMetadata: () => true }));
92+
vi.mock('../ConversationsSidebar', () => ({ ConversationsSidebar: () => null }));
93+
vi.mock('../LiveCanvas', () => ({ LiveCanvas: () => null }));
94+
vi.mock('../PendingDraftsBar', () => ({ PendingDraftsBar: () => null }));
95+
96+
import { I18nProvider } from '@object-ui/i18n';
97+
import { AiChatPage } from '../AiChatPage';
98+
import { ChatDockConversation } from '../../../layout/ChatDockConversation';
99+
100+
window.matchMedia = ((query: string) => ({
101+
matches: false,
102+
media: query,
103+
onchange: null,
104+
addEventListener: () => {},
105+
removeEventListener: () => {},
106+
addListener: () => {},
107+
removeListener: () => {},
108+
dispatchEvent: () => false,
109+
})) as unknown as typeof window.matchMedia;
110+
111+
/** A minimal, well-formed UI-message stream so a send completes. */
112+
function dataStreamResponse(): Response {
113+
return new Response('data: {"type":"start"}\n\ndata: {"type":"finish"}\n\ndata: [DONE]\n\n', {
114+
status: 200,
115+
headers: { 'Content-Type': 'text/event-stream', 'x-vercel-ai-ui-message-stream': 'v1' },
116+
});
117+
}
118+
119+
function installFetch(): void {
120+
vi.stubGlobal(
121+
'fetch',
122+
vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
123+
const url = String(input);
124+
const method = init?.method ?? 'GET';
125+
const json = (body: unknown) =>
126+
new Response(JSON.stringify(body), { status: 200, headers: { 'Content-Type': 'application/json' } });
127+
if (/\/agents\/[^/]+\/chat$/.test(url) && method === 'POST') {
128+
state.sent.push(JSON.parse(String(init?.body ?? '{}')));
129+
return dataStreamResponse();
130+
}
131+
if (/\/conversations$/.test(url) && method === 'POST') {
132+
state.minted += 1;
133+
return json({ id: `conv-${state.minted}`, messages: [] });
134+
}
135+
const one = /\/conversations\/([^/?]+)$/.exec(url);
136+
if (one && method === 'GET') return json({ id: decodeURIComponent(one[1]), messages: [] });
137+
return json({ success: true, data: [] });
138+
}),
139+
);
140+
}
141+
142+
function mountPage(): void {
143+
render(
144+
<I18nProvider config={{ defaultLanguage: 'en', detectBrowserLanguage: false }}>
145+
<MemoryRouter initialEntries={['/ai/build']}>
146+
<Routes>
147+
<Route path="/ai/:agent/:conversationId" element={<AiChatPage />} />
148+
<Route path="/ai/:agent" element={<AiChatPage />} />
149+
</Routes>
150+
</MemoryRouter>
151+
</I18nProvider>,
152+
);
153+
}
154+
155+
function mountDock(): void {
156+
render(
157+
<I18nProvider config={{ defaultLanguage: 'en', detectBrowserLanguage: false }}>
158+
<MemoryRouter initialEntries={['/apps/crm_app/account']}>
159+
<ChatDockConversation userId="u1" apiBase="/api/v1/ai" />
160+
</MemoryRouter>
161+
</I18nProvider>,
162+
);
163+
}
164+
165+
async function composerReady(): Promise<void> {
166+
await waitFor(() => expect(state.pane?.onSendMessage).toBeTypeOf('function'), { timeout: 4000 });
167+
}
168+
169+
/** Picks a model in the composer, the way the picker's `onPick` does. */
170+
function pick(modelId: string): void {
171+
act(() => state.pane!.onModelChange!(modelId));
172+
}
173+
174+
/** Sends one message through the composer, and returns the request body that left. */
175+
async function send(text: string): Promise<{ model?: string }> {
176+
const before = state.sent.length;
177+
await act(async () => {
178+
state.pane!.onSendMessage!(text);
179+
});
180+
await waitFor(() => expect(state.sent.length).toBe(before + 1), { timeout: 4000 });
181+
// Let the remount the first send causes, and the turn's stream, settle.
182+
await act(async () => {
183+
await new Promise((resolve) => setTimeout(resolve, 50));
184+
});
185+
return state.sent[before];
186+
}
187+
188+
beforeEach(() => {
189+
state.pane = undefined;
190+
state.sent = [];
191+
state.minted = 0;
192+
window.localStorage.clear();
193+
window.sessionStorage.clear();
194+
installFetch();
195+
});
196+
197+
afterEach(() => {
198+
cleanup();
199+
vi.unstubAllGlobals();
200+
});
201+
202+
describe.each([
203+
['the full-page build composer (/ai/build)', mountPage],
204+
['the console dock', mountDock],
205+
])('%s — the picked model is the model sent (objectstack#32994)', (_surface, mount) => {
206+
it('a pick before the first message rides it and the next turn, and the picker keeps showing it', async () => {
207+
mount();
208+
await composerReady();
209+
expect(state.pane?.selectedModelId).toBe(HAIKU);
210+
211+
pick(SONNET);
212+
expect(state.pane?.selectedModelId).toBe(SONNET);
213+
214+
expect((await send('first')).model).toBe(SONNET);
215+
// The first send minted the conversation and remounted the pane.
216+
expect(state.minted).toBe(1);
217+
expect(state.pane?.selectedModelId).toBe(SONNET);
218+
219+
expect((await send('second')).model).toBe(SONNET);
220+
expect(state.pane?.selectedModelId).toBe(SONNET);
221+
});
222+
223+
it('CONTROL: with no pick the default model is sent and shown', async () => {
224+
mount();
225+
await composerReady();
226+
227+
expect((await send('first')).model).toBe(HAIKU);
228+
expect(state.minted).toBe(1);
229+
expect(state.pane?.selectedModelId).toBe(HAIKU);
230+
expect((await send('second')).model).toBe(HAIKU);
231+
});
232+
});

‎ui/packages/app-shell/src/layout/ChatDockConversation.tsx‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,9 @@ export function ChatDockConversation({
140140
onBoundPackageChange?.(editPackageId);
141141
}, [editPackageId, onBoundPackageChange]);
142142
const pendingFirstMessageRef = React.useRef<PendingFirstMessage | null>(null);
143+
// ADR-0028 — the composer's picked model, held here so it outlives the keyed
144+
// pane's remount when the first send mints the conversation.
145+
const [selectedModelId, setSelectedModelId] = React.useState<string | undefined>(undefined);
143146

144147
// OSS / no AI seat → the whole dock body is inert (the launcher is gated too).
145148
if (!isLoading && agents.length === 0) return null;
@@ -163,6 +166,8 @@ export function ChatDockConversation({
163166
initialMessages={paneInitialMessages}
164167
pendingFirstMessageRef={pendingFirstMessageRef}
165168
ensureConversation={ensureConversation}
169+
selectedModelId={selectedModelId}
170+
onSelectedModelChange={setSelectedModelId}
166171
onSent={() => {}}
167172
onShare={() => {}}
168173
showDebug={false}

‎ui/packages/app-shell/src/views/studio-design/StudioAiCopilot.tsx‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,9 @@ export function StudioCopilotConversation({
113113
});
114114

115115
const pendingFirstMessageRef = React.useRef<PendingFirstMessage | null>(null);
116+
// ADR-0028 — the composer's picked model, held here so it outlives the keyed
117+
// pane's remount when the first send mints the conversation.
118+
const [selectedModelId, setSelectedModelId] = React.useState<string | undefined>(undefined);
116119

117120
// No agent served (community edition / misconfigured) → no copilot, plain surface.
118121
if (!agentsLoading && agents.length === 0) return null;
@@ -133,6 +136,8 @@ export function StudioCopilotConversation({
133136
initialMessages={initialMessages}
134137
pendingFirstMessageRef={pendingFirstMessageRef}
135138
ensureConversation={ensureConversation}
139+
selectedModelId={selectedModelId}
140+
onSelectedModelChange={setSelectedModelId}
136141
onSent={() => {}}
137142
onShare={() => {}}
138143
showDebug={false}

0 commit comments

Comments
 (0)