Skip to content
This repository was archived by the owner on Jul 27, 2026. It is now read-only.

Commit 65a429f

Browse files
fix(agent-profiles): self-heal LLM profile stream=true for profile-launched conversations
A profile-launched conversation (agent_profile_id) never sends agent_settings, so PR #1474's `llm.stream = true` (buildConfiguredOpenHands AgentSettings, agent-server-adapter.ts) never reaches it — the referenced LLM profile's stored `stream` field (SDK default: false) is used as-is by resolve_agent_profile/_build_openhands_settings, with no override, unlike the legacy path. The agent-server decides once, at conversation construction, whether to wire the `on_token` streaming callback — based on whether any of the agent's LLMs has stream=True at that moment — and never re-evaluates it afterward (confirmed by reading LocalConversation.switch_llm: it swaps the LLM but never touches _on_token). So a profile-launched conversation whose LLM profile was never saved with stream=true gets on_token=None for its entire lifetime. switchProfile's switch_llm call (unconditionally sending stream: true, unchanged by this fix) then crashes the next completion with "Streaming requires an on_token callback", since on_token can never be (re-)wired post-construction. Confirmed via real agent-server tracebacks in both mock-llm-e2e and mock-llm-docker-e2e CI runs. Streaming is a pre-existing, independently-shipped feature (PR #1474) that must not regress for legacy-launched conversations — ruling out simply dropping switch_llm's stream:true (would silently disable streaming after a switch for the one case that works today). And since existing users' LLM profiles predate this fix, defaulting stream:true only at future profile-save time (mirroring the skill_refs fix) would still crash on their first profile-launched conversation post-deploy. ensureLlmProfileStreams is a migration shim: at the one call site guaranteed to run for every profile-launched conversation (already fetching the LLM-profiles list to validate llm_profile_ref exists), check the referenced LLM profile's full config and, if stream isn't already true, save it with stream:true — self-healing both new and existing profiles on first use, memoized per profile name for the session so it's a no-op read on every subsequent launch. Mirrors the profile-duplicate flow's exact pattern for round-tripping the encrypted secret (getProfile(name, "encrypted") + saveProfile(..., include_secrets: true)) so the stored api_key is never clobbered. Touches neither the legacy agent_settings path nor switch_llm — both keep working exactly as before. Safe to delete once virtually all users are migrated, or once resolve_agent_profile forces stream=true for OpenHands profiles upstream (same category of fix as the skill_refs default — likely the same #3967 umbrella), whichever comes first. Verified: full unit suite green (3620 passed, +2 new tests exercising this exact self-heal/no-op branching), typecheck clean. Locally reproduced the fix: mock-llm-model-switch's on_token crash no longer occurs; preset-automation and image-upload remain passing. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent a30683a commit 65a429f

2 files changed

Lines changed: 214 additions & 1 deletion

File tree

‎__tests__/hooks/mutation/use-create-conversation.test.tsx‎

Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,23 @@ listAgentProfilesMock.mockResolvedValue({
4848
active_agent_profile_id: null,
4949
});
5050

51+
// LLM-profile service: real listProfiles/getProfile/saveProfile calls (the
52+
// llmProfileExists validation, and ensureLlmProfileStreams' self-heal —
53+
// see use-create-conversation.ts) so both can be asserted per-test.
54+
const listLlmProfilesMock = vi.fn();
55+
const getLlmProfileMock = vi.fn();
56+
const saveLlmProfileMock = vi.fn();
57+
vi.mock("#/api/profiles-service/profiles-service.api", () => ({
58+
__esModule: true,
59+
default: {
60+
listProfiles: (...args: unknown[]) => listLlmProfilesMock(...args),
61+
getProfile: (...args: unknown[]) => getLlmProfileMock(...args),
62+
saveProfile: (...args: unknown[]) => saveLlmProfileMock(...args),
63+
},
64+
}));
65+
listLlmProfilesMock.mockResolvedValue({ profiles: [], active_profile: null });
66+
saveLlmProfileMock.mockResolvedValue({ name: "x", message: "ok" });
67+
5168
describe("useCreateConversation", () => {
5269
afterEach(() => {
5370
// Restore the default (no active AgentProfile) so the overrides below
@@ -57,6 +74,14 @@ describe("useCreateConversation", () => {
5774
profiles: [],
5875
active_agent_profile_id: null,
5976
});
77+
listLlmProfilesMock.mockReset();
78+
listLlmProfilesMock.mockResolvedValue({
79+
profiles: [],
80+
active_profile: null,
81+
});
82+
getLlmProfileMock.mockReset();
83+
saveLlmProfileMock.mockReset();
84+
saveLlmProfileMock.mockResolvedValue({ name: "x", message: "ok" });
6085
removeStoredConversationMetadata("conv-with-plugins");
6186
});
6287

@@ -167,6 +192,123 @@ describe("useCreateConversation", () => {
167192
});
168193
});
169194

195+
it("self-heals a profile-launched conversation's LLM to stream=true when it isn't already (on_token migration shim)", async () => {
196+
listAgentProfilesMock.mockResolvedValue({
197+
profiles: [
198+
{
199+
id: "profile-abc",
200+
name: "default",
201+
revision: 1,
202+
agent_kind: "openhands",
203+
llm_profile_ref: "llm-needs-heal",
204+
mcp_server_refs: null,
205+
},
206+
],
207+
active_agent_profile_id: "profile-abc",
208+
});
209+
listLlmProfilesMock.mockResolvedValue({
210+
profiles: [{ name: "llm-needs-heal", model: "gpt-4", api_key_set: true }],
211+
active_profile: null,
212+
});
213+
getLlmProfileMock.mockResolvedValue({
214+
name: "llm-needs-heal",
215+
config: {
216+
model: "gpt-4",
217+
api_key: "fernet:encrypted-token",
218+
stream: false,
219+
},
220+
api_key_set: true,
221+
});
222+
const createConversationSpy = vi
223+
.spyOn(AgentServerConversationService, "createConversation")
224+
.mockResolvedValue({
225+
id: "task-id",
226+
app_conversation_id: "conv-1",
227+
agent_server_url: "http://agent-server.local",
228+
} as never);
229+
230+
const { result } = renderHook(() => useCreateConversation(), {
231+
wrapper: ({ children }) => (
232+
<QueryClientProvider client={new QueryClient()}>
233+
{children}
234+
</QueryClientProvider>
235+
),
236+
});
237+
238+
await result.current.mutateAsync({ query: "hello" });
239+
240+
await waitFor(() => {
241+
expect(getLlmProfileMock).toHaveBeenCalledWith(
242+
"llm-needs-heal",
243+
"encrypted",
244+
);
245+
// The encrypted secret must round-trip untouched, and the save must
246+
// opt in to persisting it (mirrors the profile-duplicate flow).
247+
expect(saveLlmProfileMock).toHaveBeenCalledWith("llm-needs-heal", {
248+
llm: {
249+
model: "gpt-4",
250+
api_key: "fernet:encrypted-token",
251+
stream: true,
252+
},
253+
include_secrets: true,
254+
});
255+
expect(createConversationSpy).toHaveBeenCalled();
256+
});
257+
});
258+
259+
it("does not re-save an LLM profile that already streams", async () => {
260+
listAgentProfilesMock.mockResolvedValue({
261+
profiles: [
262+
{
263+
id: "profile-abc",
264+
name: "default",
265+
revision: 1,
266+
agent_kind: "openhands",
267+
llm_profile_ref: "llm-already-streams",
268+
mcp_server_refs: null,
269+
},
270+
],
271+
active_agent_profile_id: "profile-abc",
272+
});
273+
listLlmProfilesMock.mockResolvedValue({
274+
profiles: [
275+
{ name: "llm-already-streams", model: "gpt-4", api_key_set: true },
276+
],
277+
active_profile: null,
278+
});
279+
getLlmProfileMock.mockResolvedValue({
280+
name: "llm-already-streams",
281+
config: { model: "gpt-4", stream: true },
282+
api_key_set: false,
283+
});
284+
vi.spyOn(
285+
AgentServerConversationService,
286+
"createConversation",
287+
).mockResolvedValue({
288+
id: "task-id",
289+
app_conversation_id: "conv-1",
290+
agent_server_url: "http://agent-server.local",
291+
} as never);
292+
293+
const { result } = renderHook(() => useCreateConversation(), {
294+
wrapper: ({ children }) => (
295+
<QueryClientProvider client={new QueryClient()}>
296+
{children}
297+
</QueryClientProvider>
298+
),
299+
});
300+
301+
await result.current.mutateAsync({ query: "hello" });
302+
303+
await waitFor(() => {
304+
expect(getLlmProfileMock).toHaveBeenCalledWith(
305+
"llm-already-streams",
306+
"encrypted",
307+
);
308+
});
309+
expect(saveLlmProfileMock).not.toHaveBeenCalled();
310+
});
311+
170312
it("awaits the profiles fetch so an early send still launches from the active profile", async () => {
171313
// A send fired before the home profiles query resolves must block on the
172314
// fetch, not fall through to the agent_settings path (#1571 review F2).

‎src/hooks/mutation/use-create-conversation.ts‎

Lines changed: 72 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,9 @@ import { useTracking } from "#/hooks/use-tracking";
77
import { useLlmProfiles } from "#/hooks/query/use-llm-profiles";
88
import { useAgentProfiles } from "#/hooks/query/use-agent-profiles";
99
import { useActiveBackend } from "#/contexts/active-backend-context";
10-
import ProfilesService from "#/api/profiles-service/profiles-service.api";
10+
import ProfilesService, {
11+
type SaveProfileRequest,
12+
} from "#/api/profiles-service/profiles-service.api";
1113
import AgentProfilesService, {
1214
type AgentProfileListResponse,
1315
} from "#/api/agent-profiles-service/agent-profiles-service.api";
@@ -53,6 +55,73 @@ interface CreateConversationResponse {
5355
task_id?: string;
5456
}
5557

58+
// One-time-per-session memo so ensureLlmProfileStreams only does real work
59+
// (a fetch, and — pre-migration — a save) once per LLM profile name; every
60+
// later profile-launched conversation in this session skips it entirely.
61+
const streamConfirmedLlmProfiles = new Set<string>();
62+
63+
/**
64+
* MIGRATION SHIM — self-heals an LLM profile's `stream` field to `true` the
65+
* first time it's used to launch a conversation via an agent profile.
66+
*
67+
* Conversations launched via `agentProfileId` never send `agent_settings`
68+
* (mutually exclusive with the profile path — see buildStartConversationRequest
69+
* in agent-server-adapter.ts), so `buildConfiguredOpenHandsAgentSettings`'s
70+
* `llm.stream = true` (PR #1474, "stream OpenHands agent responses") never
71+
* reaches them. The agent-server decides once, at conversation construction,
72+
* whether to wire the `on_token` streaming callback — based on whether any of
73+
* the agent's LLMs has `stream=True` at that moment — and never re-evaluates
74+
* it afterward. openhands-sdk's `resolve_agent_profile` uses the referenced
75+
* LLM profile's stored `stream` value as-is (no forced override, unlike the
76+
* agent_settings path), so a profile-launched conversation whose LLM profile
77+
* was never explicitly saved with `stream: true` gets `on_token=None` for its
78+
* entire lifetime. `switchProfile`'s `switch_llm` call (unconditionally
79+
* setting `stream: true`, unchanged by this fix — see its own comment) then
80+
* crashes the next completion with "Streaming requires an on_token callback",
81+
* since on_token can never be (re-)wired post-construction.
82+
*
83+
* This does NOT touch the legacy agent_settings path or switch_llm — both
84+
* keep working exactly as before. It only ensures the ONE thing profile
85+
* launches are missing: the underlying LLM profile has `stream: true`
86+
* persisted, so resolve_agent_profile picks it up correctly, matching what
87+
* agent_settings-launched conversations already guarantee.
88+
*
89+
* Safe to delete once either: (a) essentially every user's LLM profiles have
90+
* been touched by this at least once (self-limiting — becomes a no-op read
91+
* per profile once migrated), or (b) resolve_agent_profile/the profile model
92+
* itself forces stream=true for OpenHands profiles upstream (same category
93+
* of fix as the skill_refs default — likely the same #3967 umbrella), at
94+
* which point this is redundant regardless of migration state.
95+
*/
96+
async function ensureLlmProfileStreams(llmProfileName: string): Promise<void> {
97+
if (streamConfirmedLlmProfiles.has(llmProfileName)) return;
98+
try {
99+
const detail = await ProfilesService.getProfile(
100+
llmProfileName,
101+
"encrypted",
102+
);
103+
const config = detail.config as Record<string, unknown>;
104+
if (config.stream !== true) {
105+
await ProfilesService.saveProfile(llmProfileName, {
106+
llm: {
107+
...config,
108+
stream: true,
109+
} as unknown as SaveProfileRequest["llm"],
110+
include_secrets: true,
111+
});
112+
}
113+
streamConfirmedLlmProfiles.add(llmProfileName);
114+
} catch (error) {
115+
// Best-effort: never let this block conversation creation. A failed
116+
// self-heal just means the on_token crash risk (mid-conversation model
117+
// switch) remains for this profile until a later attempt succeeds.
118+
console.warn(
119+
`Failed to confirm streaming is enabled for LLM profile "${llmProfileName}":`,
120+
error,
121+
);
122+
}
123+
}
124+
56125
export const useCreateConversation = () => {
57126
const queryClient = useQueryClient();
58127
const { trackConversationCreated } = useTracking();
@@ -153,6 +222,8 @@ export const useCreateConversation = () => {
153222
"launching from agent_settings instead.",
154223
);
155224
effectiveAgentProfileId = undefined;
225+
} else {
226+
await ensureLlmProfileStreams(resolvedAgentProfile.llm_profile_ref);
156227
}
157228
}
158229

0 commit comments

Comments
 (0)