π OpenHands: AI-Driven Development
fix(agent-profiles): keep the profile on per-launch LLM picks and in /new (#18419)
simonrosenberg5958302c1c5d
diff --git a/__tests__/api/agent-server-adapter.test.ts b/__tests__/api/agent-server-adapter.test.tsindex 36357279a0..a458a316b1 100644--- a/__tests__/api/agent-server-adapter.test.ts+++ b/__tests__/api/agent-server-adapter.test.ts@@ -14,6 +14,7 @@ import {buildStartConversationRequest,buildStartConversationRequestWithEncryptedSettings,fetchBackendExecutionRuntime,+ backendSupportsLaunchLlmOverride,getDefaultConversationTitle,parseRuntimeServicesInfo,toAppConversation,@@ -1514,6 +1515,20 @@ describe("buildRuntimeServicesSystemSuffix", () => {expect(runtime).toBe("local");expect(mockGetServerInfo).toHaveBeenCalledOnce();});++ it("reports the per-launch LLM override from server capabilities", async () => {+ mockGetCachedAgentServerInfo.mockReturnValue({+ version: "1.54.0",+ capabilities: ["tool_catalog_v1"],+ });+ await expect(backendSupportsLaunchLlmOverride()).resolves.toBe(false);++ mockGetCachedAgentServerInfo.mockReturnValue({+ version: "1.54.0",+ capabilities: ["tool_catalog_v1", "agent_launch_pipeline_v1"],+ });+ await expect(backendSupportsLaunchLlmOverride()).resolves.toBe(true);+ });});describe("agent_settings runtime services suffix", () => {diff --git a/__tests__/api/use-create-conversation-metadata.test.ts b/__tests__/api/use-create-conversation-metadata.test.tsindex 4bd4dd75ab..542905025c 100644--- a/__tests__/api/use-create-conversation-metadata.test.ts+++ b/__tests__/api/use-create-conversation-metadata.test.ts@@ -8,6 +8,7 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import React from "react";import { useCreateConversation } from "#/hooks/mutation/use-create-conversation";import { getStoredConversationMetadata } from "#/api/conversation-metadata-store";+import ProfilesService from "#/api/profiles-service/profiles-service.api";const {mockHttpPost,@@ -141,6 +142,7 @@ describe("useCreateConversation persists selected repository metadata", () => {afterEach(() => {window.localStorage.clear();+ vi.restoreAllMocks();});it("stores the selected repo/branch/provider in the metadata store after a successful create", async () => {@@ -198,9 +200,10 @@ describe("useCreateConversation persists selected repository metadata", () => {});it("stamps the active LLM profile even when no repo or workspace is attached (#1082)", async () => {- mockUseLlmProfiles.mockReturnValue({- data: { active_profile: "team-default" },- });+ vi.spyOn(ProfilesService, "listProfiles").mockResolvedValue({+ profiles: [{ name: "team-default" }],+ active_profile: "team-default",+ } as never);const { result } = renderHook(() => useCreateConversation(), { wrapper });@@ -212,10 +215,7 @@ describe("useCreateConversation persists selected repository metadata", () => {selected_repository: null,selected_branch: null,git_provider: null,- selected_workspace: null,- workspace_mode: null,active_profile: "team-default",- plugins: null,});});diff --git a/__tests__/hooks/mutation/resolve-conversation-launch.test.ts b/__tests__/hooks/mutation/resolve-conversation-launch.test.tsnew file mode 100644index 0000000000..b10684e9d3--- /dev/null+++ b/__tests__/hooks/mutation/resolve-conversation-launch.test.ts@@ -0,0 +1,86 @@+import { QueryClient } from "@tanstack/react-query";+import { afterEach, describe, expect, it, vi } from "vitest";+import { resolveConversationLaunch } from "#/hooks/mutation/resolve-conversation-launch";++const { listAgentProfiles, listLlmProfiles, supportsOverride } = vi.hoisted(+ () => ({+ listAgentProfiles: vi.fn(),+ listLlmProfiles: vi.fn(),+ supportsOverride: vi.fn(),+ }),+);++vi.mock("#/api/agent-profiles-service/agent-profiles-service.api", () => ({+ __esModule: true,+ default: { listProfiles: listAgentProfiles, getProfile: vi.fn() },+ WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME: "default",+}));+vi.mock("#/api/profiles-service/profiles-service.api", () => ({+ __esModule: true,+ default: { listProfiles: listLlmProfiles },+}));+vi.mock("#/api/agent-server-adapter", () => ({+ backendSupportsLaunchLlmOverride: supportsOverride,+}));++const PARENT_PROFILE = {+ id: "profile-1",+ name: "reviewer",+ agent_kind: "openhands",+ revision: 1,+ llm_profile_ref: "slow",+ mcp_server_refs: null,+};++function launchWithParentModel() {+ return resolveConversationLaunch({+ queryClient: new QueryClient(),+ backendId: "local-1",+ orgId: null,+ isCloud: false,+ agentProfileId: "profile-1",+ llmProfile: "fast",+ });+}++describe("resolveConversationLaunch with a requested LLM profile", () => {+ afterEach(() => vi.resetAllMocks());++ it("runs the requested LLM on the picked profile", async () => {+ listAgentProfiles.mockResolvedValue({+ profiles: [PARENT_PROFILE],+ active_agent_profile_id: null,+ });+ listLlmProfiles.mockResolvedValue({+ profiles: [{ name: "slow" }, { name: "fast" }],+ active_profile: "slow",+ });+ supportsOverride.mockResolvedValue(true);++ await expect(launchWithParentModel()).resolves.toMatchObject({+ agentProfileId: "profile-1",+ llmProfileOverride: "fast",+ llmProfile: "fast",+ });+ });++ it("keeps the profile on its own LLM when the server has no override", async () => {+ listAgentProfiles.mockResolvedValue({+ profiles: [PARENT_PROFILE],+ active_agent_profile_id: null,+ });+ listLlmProfiles.mockResolvedValue({+ profiles: [{ name: "slow" }, { name: "fast" }],+ active_profile: "slow",+ });+ supportsOverride.mockResolvedValue(false);++ const launch = await launchWithParentModel();++ expect(launch).toMatchObject({+ agentProfileId: "profile-1",+ llmProfile: "slow",+ });+ expect(launch.llmProfileOverride).toBeUndefined();+ });+});diff --git a/__tests__/hooks/mutation/use-create-conversation.test.tsx b/__tests__/hooks/mutation/use-create-conversation.test.tsxindex 6159e71f49..195f35f6f1 100644--- a/__tests__/hooks/mutation/use-create-conversation.test.tsx+++ b/__tests__/hooks/mutation/use-create-conversation.test.tsx@@ -1,6 +1,6 @@import { renderHook, waitFor } from "@testing-library/react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import { afterEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";import { useCreateConversation } from "#/hooks/mutation/use-create-conversation";import { SuggestedTask } from "#/utils/types";@@ -86,6 +86,16 @@ vi.mock("#/api/profiles-service/profiles-service.api", () => ({}));listLlmProfilesMock.mockResolvedValue({ profiles: [], active_profile: null });+// Without `agent_launch_pipeline_v1` the launch keeps its agent_settings+// fallbacks; the override block below turns it on.+const { supportsLaunchLlmOverrideMock } = vi.hoisted(() => ({+ supportsLaunchLlmOverrideMock: vi.fn(async () => false),+}));+vi.mock("#/api/agent-server-adapter", async (importOriginal) => ({+ ...(await importOriginal<typeof import("#/api/agent-server-adapter")>()),+ backendSupportsLaunchLlmOverride: () => supportsLaunchLlmOverrideMock(),+}));+describe("useCreateConversation", () => {afterEach(() => {// Restore the default (no active AgentProfile) so the overrides below@@ -826,4 +836,150 @@ describe("useCreateConversation", () => {const call = createConversationSpy.mock.lastCall;expect(call?.[0]?.agentProfileId).toBe("profile-luna");});++ describe("on an agent-server with per-launch LLM overrides", () => {+ const luna = {+ id: "profile-luna",+ name: "openhands-luna",+ agent_kind: "openhands",+ revision: 1,+ llm_profile_ref: "pinned-model",+ mcp_server_refs: null,+ };++ async function launch(variables: { agentProfileId?: string } = {}) {+ const createConversationSpy = vi+ .spyOn(AgentServerConversationService, "createConversation")+ .mockResolvedValue({+ id: "task-id",+ app_conversation_id: "conv-dropdown-override",+ agent_server_url: "http://agent-server.local",+ } as never);+ const { result } = renderHook(() => useCreateConversation(), {+ wrapper: ({ children }) => (+ <QueryClientProvider client={new QueryClient()}>+ {children}+ </QueryClientProvider>+ ),+ });+ await result.current.mutateAsync({ query: "hello", ...variables });+ return createConversationSpy.mock.lastCall?.[0];+ }++ beforeEach(() => {+ supportsLaunchLlmOverrideMock.mockResolvedValue(true);+ });+ afterEach(() => {+ supportsLaunchLlmOverrideMock.mockResolvedValue(false);+ });++ it("keeps the named profile and runs the home LLM selection (#16539)", async () => {+ listAgentProfilesMock.mockResolvedValue({+ profiles: [luna],+ active_agent_profile_id: "profile-luna",+ });+ listLlmProfilesMock.mockResolvedValue({+ profiles: [{ name: "pinned-model" }, { name: "selected-model" }],+ active_profile: "selected-model",+ });++ const call = await launch();++ expect(call?.agentProfileId).toBe("profile-luna");+ expect(call?.agentLlmProfileOverride).toBe("selected-model");+ expect(call?.agentLlmProfileRef).toBe("selected-model");+ expect(getAgentProfileMock).not.toHaveBeenCalled();+ await waitFor(() =>+ expect(+ getStoredConversationMetadata("conv-dropdown-override")+ ?.active_profile,+ ).toBe("selected-model"),+ );+ });++ it("runs the active LLM profile when the profile's ref is missing", async () => {+ listAgentProfilesMock.mockResolvedValue({+ profiles: [luna],+ active_agent_profile_id: null,+ });+ listLlmProfilesMock.mockResolvedValue({+ profiles: [{ name: "selected-model" }],+ active_profile: "selected-model",+ });++ const call = await launch({ agentProfileId: "profile-luna" });++ expect(call?.agentProfileId).toBe("profile-luna");+ expect(call?.agentLlmProfileOverride).toBe("selected-model");+ });++ it("leaves a missing ref with no LLM selected for the server to report", async () => {+ listAgentProfilesMock.mockResolvedValue({+ profiles: [luna],+ active_agent_profile_id: "profile-luna",+ });+ listLlmProfilesMock.mockResolvedValue({+ profiles: [],+ active_profile: null,+ });++ const call = await launch();++ expect(call?.agentProfileId).toBe("profile-luna");+ expect(call).not.toHaveProperty("agentLlmProfileOverride");+ });++ it("keeps an explicit pick on its pinned ref", async () => {+ listAgentProfilesMock.mockResolvedValue({+ profiles: [luna],+ active_agent_profile_id: null,+ });+ listLlmProfilesMock.mockResolvedValue({+ profiles: [{ name: "pinned-model" }, { name: "selected-model" }],+ active_profile: "selected-model",+ });++ const call = await launch({ agentProfileId: "profile-luna" });++ expect(call?.agentProfileId).toBe("profile-luna");+ expect(call).not.toHaveProperty("agentLlmProfileOverride");+ expect(call?.agentLlmProfileRef).toBe("pinned-model");+ });++ it("still launches the OpenHands `default` via agent_settings", async () => {+ listAgentProfilesMock.mockResolvedValue({+ profiles: [{ ...luna, id: "profile-default", name: "default" }],+ active_agent_profile_id: "profile-default",+ });+ listLlmProfilesMock.mockResolvedValue({+ profiles: [{ name: "pinned-model" }, { name: "selected-model" }],+ active_profile: "selected-model",+ });++ const call = await launch();++ expect(call?.agentProfileId).toBeUndefined();+ expect(call).not.toHaveProperty("agentLlmProfileOverride");+ });++ it("sends no override to cloud", async () => {+ mockUseActiveBackend.mockReturnValue({+ backend: { id: "cloud-1", kind: "cloud" },+ orgId: null,+ });+ listAgentProfilesMock.mockResolvedValue({+ profiles: [luna],+ active_agent_profile_id: "profile-luna",+ });+ listLlmProfilesMock.mockResolvedValue({+ profiles: [{ name: "pinned-model" }, { name: "selected-model" }],+ active_profile: "selected-model",+ });++ const call = await launch();++ expect(call?.agentProfileId).toBe("profile-luna");+ expect(call).not.toHaveProperty("agentLlmProfileOverride");+ });+ });});diff --git a/__tests__/hooks/mutation/use-new-conversation-command.test.tsx b/__tests__/hooks/mutation/use-new-conversation-command.test.tsxindex b68c7636af..9927a3ba4c 100644--- a/__tests__/hooks/mutation/use-new-conversation-command.test.tsx+++ b/__tests__/hooks/mutation/use-new-conversation-command.test.tsx@@ -4,6 +4,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";import { useNewConversationCommand } from "#/hooks/mutation/use-new-conversation-command";import * as telemetry from "#/services/telemetry";+import AgentProfilesService from "#/api/agent-profiles-service/agent-profiles-service.api";+import ProfilesService from "#/api/profiles-service/profiles-service.api";+import {+ getStoredConversationMetadata,+ removeStoredConversationMetadata,+} from "#/api/conversation-metadata-store";const mockNavigate = vi.fn();@@ -105,7 +111,8 @@ describe("useNewConversationCommand", () => {});afterEach(() => {- captureMock.mockRestore();+ vi.restoreAllMocks();+ removeStoredConversationMetadata("new-conv-999");});const wrapper = ({ children }: { children: React.ReactNode }) => (@@ -222,6 +229,71 @@ describe("useNewConversationCommand", () => {});});+ it("launches the active agent profile rather than the global settings", async () => {+ vi.spyOn(AgentProfilesService, "listProfiles").mockResolvedValue({+ profiles: [+ {+ id: "acp-1",+ name: "claude",+ agent_kind: "acp",+ revision: 1,+ llm_profile_ref: null,+ mcp_server_refs: null,+ },+ ],+ active_agent_profile_id: "acp-1",+ } as never);+ const createSpy = vi+ .spyOn(AgentServerConversationService, "createConversation")+ .mockResolvedValue(makeStartTask() as never);++ const { result } = renderHook(() => useNewConversationCommand(), {+ wrapper,+ });+ await result.current.mutateAsync();++ expect(createSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ sandboxId: "sandbox-abc",+ agentProfileId: "acp-1",+ agentProfileKind: "acp",+ }),+ );+ });++ it("records the LLM profile the new conversation runs", async () => {+ vi.spyOn(AgentProfilesService, "listProfiles").mockResolvedValue({+ profiles: [+ {+ id: "oh-1",+ name: "reviewer",+ agent_kind: "openhands",+ revision: 1,+ llm_profile_ref: "pinned",+ mcp_server_refs: null,+ },+ ],+ active_agent_profile_id: "oh-1",+ } as never);+ vi.spyOn(ProfilesService, "listProfiles").mockResolvedValue({+ profiles: [{ name: "pinned" }],+ active_profile: "pinned",+ } as never);+ vi.spyOn(+ AgentServerConversationService,+ "createConversation",+ ).mockResolvedValue(makeStartTask() as never);++ const { result } = renderHook(() => useNewConversationCommand(), {+ wrapper,+ });+ await result.current.mutateAsync();++ expect(getStoredConversationMetadata("new-conv-999")?.active_profile).toBe(+ "pinned",+ );+ });+it("shows a loading toast and dismisses it on success", async () => {const readyTask = makeStartTask();diff --git a/__tests__/hooks/use-active-agent-profile.test.tsx b/__tests__/hooks/use-active-agent-profile.test.tsxnew file mode 100644index 0000000000..b57290d6d5--- /dev/null+++ b/__tests__/hooks/use-active-agent-profile.test.tsx@@ -0,0 +1,158 @@+import { act, renderHook, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import type { ReactNode } from "react";+import { afterEach, describe, expect, it, vi } from "vitest";+import { useActiveAgentProfile } from "#/hooks/use-active-agent-profile";+import { useAcpModelContext } from "#/hooks/use-acp-model-context";+import { resolveConversationLaunch } from "#/hooks/mutation/resolve-conversation-launch";+import { AGENT_PROFILES_QUERY_KEYS } from "#/hooks/query/query-keys";++const { listProfilesMock, settingsKind } = vi.hoisted(() => ({+ listProfilesMock: vi.fn(),+ settingsKind: { value: "openhands" as "openhands" | "acp" },+}));++vi.mock("#/api/agent-profiles-service/agent-profiles-service.api", () => ({+ __esModule: true,+ default: { listProfiles: listProfilesMock, getProfile: vi.fn() },+ WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME: "default",+}));+vi.mock("#/api/profiles-service/profiles-service.api", () => ({+ __esModule: true,+ default: {+ listProfiles: vi.fn().mockResolvedValue({+ profiles: [{ name: "mock-llm" }],+ active_profile: "mock-llm",+ }),+ },+}));+vi.mock("#/api/agent-server-adapter", () => ({+ backendSupportsLaunchLlmOverride: vi.fn().mockResolvedValue(true),+}));+vi.mock("#/contexts/active-backend-context", () => ({+ useActiveBackend: () => ({+ backend: { id: "local-1", kind: "local" },+ orgId: null,+ }),+}));+vi.mock("#/hooks/query/use-settings", () => ({+ useSettings: () => ({+ data: { agent_settings: { agent_kind: settingsKind.value } },+ }),+}));+vi.mock("#/hooks/query/use-active-conversation", () => ({+ useActiveConversation: () => ({ data: undefined }),+}));++const OPENHANDS = {+ id: "oh-1",+ name: "coder",+ agent_kind: "openhands",+ revision: 1,+ llm_profile_ref: "mock-llm",+ mcp_server_refs: null,+};+const ACP = {+ id: "acp-1",+ name: "claude",+ agent_kind: "acp",+ revision: 1,+ llm_profile_ref: null,+ mcp_server_refs: null,+};+const listWithActive = (id: string) => ({+ profiles: [OPENHANDS, ACP],+ active_agent_profile_id: id,+});++function renderActiveAgent(queryClient: QueryClient) {+ const wrapper = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ );+ return renderHook(+ () => ({ active: useActiveAgentProfile(), acp: useAcpModelContext() }),+ { wrapper },+ );+}++const launch = (queryClient: QueryClient) =>+ resolveConversationLaunch({+ queryClient,+ backendId: "local-1",+ orgId: null,+ isCloud: false,+ });++describe("active agent profile after a failed refetch", () => {+ afterEach(() => {+ listProfilesMock.mockReset();+ settingsKind.value = "openhands";+ });++ it("keeps cached data across a failed refetch, and the launch agrees", async () => {+ const queryClient = new QueryClient();+ listProfilesMock.mockResolvedValue(listWithActive("oh-1"));+ const { result } = renderActiveAgent(queryClient);+ await waitFor(() =>+ expect(result.current.active.activeProfile?.id).toBe("oh-1"),+ );++ // Activating ACP invalidates the list, and that refetch fails.+ settingsKind.value = "acp";+ listProfilesMock.mockRejectedValue(new Error("network down"));+ await act(() =>+ queryClient+ .refetchQueries({ queryKey: AGENT_PROFILES_QUERY_KEYS.all })+ .catch(() => undefined),+ );++ expect(result.current.active.isError).toBe(false);+ expect(result.current.active.agentKind).toBe("openhands");+ expect(result.current.acp.isHomeAcp).toBe(false);+ await expect(launch(queryClient)).resolves.toMatchObject({+ agentProfileId: "oh-1",+ agentProfileKind: "openhands",+ });++ listProfilesMock.mockResolvedValue(listWithActive("acp-1"));+ await act(() =>+ queryClient.refetchQueries({ queryKey: AGENT_PROFILES_QUERY_KEYS.all }),+ );+ expect(result.current.active.agentKind).toBe("acp");+ expect(result.current.acp.isHomeAcp).toBe(true);+ await expect(launch(queryClient)).resolves.toMatchObject({+ agentProfileId: "acp-1",+ agentProfileKind: "acp",+ });+ });++ it("does not fall back to global settings when nothing is cached", async () => {+ const queryClient = new QueryClient();+ settingsKind.value = "acp";+ listProfilesMock.mockRejectedValue(new Error("network down"));+ const { result } = renderActiveAgent(queryClient);++ await waitFor(() => expect(result.current.active.isError).toBe(true));+ expect(result.current.active.agentKind).toBeUndefined();+ expect(result.current.acp.isHomeAcp).toBe(false);+ await expect(launch(queryClient)).rejects.toThrow("network down");+ });++ it("uses global settings when no profile is active", async () => {+ const queryClient = new QueryClient();+ settingsKind.value = "acp";+ listProfilesMock.mockResolvedValue({+ profiles: [OPENHANDS],+ active_agent_profile_id: null,+ });+ const { result } = renderActiveAgent(queryClient);++ await waitFor(() => expect(listProfilesMock).toHaveBeenCalled());+ await waitFor(() => expect(result.current.active.isLoading).toBe(false));+ expect(result.current.active.agentKind).toBe("acp");+ expect(result.current.acp.isHomeAcp).toBe(true);+ await expect(launch(queryClient)).resolves.not.toHaveProperty(+ "agentProfileId",+ );+ });+});diff --git a/__tests__/hooks/use-llm-configured.test.tsx b/__tests__/hooks/use-llm-configured.test.tsxindex c6c18c4229..372220eb1b 100644--- a/__tests__/hooks/use-llm-configured.test.tsx+++ b/__tests__/hooks/use-llm-configured.test.tsx@@ -23,7 +23,14 @@ vi.mock("#/contexts/active-backend-context", () => ({useActiveBackend: () => useActiveBackendMock(),}));vi.mock("#/hooks/use-active-agent-profile", () => ({- useActiveAgentProfile: () => useActiveAgentProfileMock(),+ useActiveAgentProfile: () => {+ const value = useActiveAgentProfileMock();+ return {+ isError: false,+ agentKind: value.activeProfile?.agent_kind,+ ...value,+ };+ },}));function wrapper({ children }: { children: ReactNode }) {@@ -182,4 +189,26 @@ describe("useLlmConfigured (local, agent-profile-driven)", () => {const { result } = renderHook(() => useLlmConfigured(), { wrapper });expect(result.current.isConfigured).toBe(true);});++ it("stays indeterminate when the profile list failed with nothing cached", () => {+ useSettingsMock.mockReturnValue({+ data: {+ agent_settings: { agent_kind: "acp" },+ llm_api_key_set: false,+ },+ });+ useLlmProfilesMock.mockReturnValue(+ llmProfiles("default", [{ name: "default", api_key_set: false }]),+ );+ useActiveAgentProfileMock.mockReturnValue({+ activeProfile: null,+ agentKind: undefined,+ isLoading: false,+ isError: true,+ });++ const { result } = renderHook(() => useLlmConfigured(), { wrapper });+ expect(result.current.isLoading).toBe(true);+ expect(result.current.isConfigured).toBe(false);+ });});diff --git a/__tests__/services/child-conversation-launch.test.ts b/__tests__/services/child-conversation-launch.test.tsindex 42a33067b9..363c6400e6 100644--- a/__tests__/services/child-conversation-launch.test.ts+++ b/__tests__/services/child-conversation-launch.test.ts@@ -5,7 +5,11 @@ import {LAUNCH_CHILD_CONVERSATION_ACTION_KIND,LAUNCH_CHILD_CONVERSATION_TOOL_NAME,} from "#/constants/child-conversation";-import { setStoredConversationMetadata } from "#/api/conversation-metadata-store";+import {+ getStoredConversationMetadata,+ setStoredConversationMetadata,+} from "#/api/conversation-metadata-store";+import { getQueryClient } from "#/query-client-config";import { useGoalStore } from "#/stores/goal-store";import type { LaunchChildConversationAction } from "#/types/agent-server/core";import { isLaunchChildConversationActionEvent } from "#/types/agent-server/type-guards";@@ -25,6 +29,10 @@ const {mockGetCachedAgentServerVersion,mockGetSettings,mockListMetaProfiles,+ mockBatchGetAppConversations,+ mockListAgentProfiles,+ mockListLlmProfiles,+ mockSupportsLaunchLlmOverride,} = vi.hoisted(() => ({mockCreateConversation: vi.fn(),mockResolveWorkingDir: vi.fn(),@@ -36,6 +44,10 @@ const {mockGetCachedAgentServerVersion: vi.fn(),mockGetSettings: vi.fn(),mockListMetaProfiles: vi.fn(),+ mockBatchGetAppConversations: vi.fn(),+ mockListAgentProfiles: vi.fn(),+ mockListLlmProfiles: vi.fn(),+ mockSupportsLaunchLlmOverride: vi.fn(),}));vi.mock(@@ -46,10 +58,30 @@ vi.mock(resolveConversationWorkingDir: mockResolveWorkingDir,sendMessage: mockSendMessage,updateConversationTitle: mockUpdateTitle,+ batchGetAppConversations: mockBatchGetAppConversations,},}),);+vi.mock(+ "#/api/agent-profiles-service/agent-profiles-service.api",+ async (importOriginal) => ({+ ...(await importOriginal<+ typeof import("#/api/agent-profiles-service/agent-profiles-service.api")+ >()),+ default: { listProfiles: mockListAgentProfiles, getProfile: vi.fn() },+ }),+);++vi.mock("#/api/profiles-service/profiles-service.api", () => ({+ default: { listProfiles: mockListLlmProfiles },+}));++vi.mock("#/api/agent-server-adapter", async (importOriginal) => ({+ ...(await importOriginal<typeof import("#/api/agent-server-adapter")>()),+ backendSupportsLaunchLlmOverride: mockSupportsLaunchLlmOverride,+}));+vi.mock("#/api/cloud/conversation-service.api", () => ({createCloudAppConversation: mockCreateCloudAppConversation,getCloudAppConversationStartTask: mockGetCloudStartTask,@@ -152,6 +184,17 @@ describe("handleLaunchChildConversationAction", () => {meta_profiles: [],active_meta_profile: null,});+ mockBatchGetAppConversations.mockResolvedValue([]);+ getQueryClient().clear();+ mockListAgentProfiles.mockResolvedValue({+ profiles: [],+ active_agent_profile_id: null,+ });+ mockListLlmProfiles.mockResolvedValue({+ profiles: [],+ active_profile: null,+ });+ mockSupportsLaunchLlmOverride.mockResolvedValue(true);});describe("parameter validation", () => {@@ -229,6 +272,55 @@ describe("handleLaunchChildConversationAction", () => {});});+ it("launches the child from the parent's agent profile and current LLM", async () => {+ seedWorktreeCapableParent();+ mockBatchGetAppConversations.mockResolvedValue([+ {+ agent_kind: "openhands",+ active_profile: "fast",+ launched_agent_profile: {+ agent_profile_id: "profile-1",+ revision: 3,+ },+ },+ ]);+ mockListAgentProfiles.mockResolvedValue({+ profiles: [+ {+ id: "profile-1",+ name: "reviewer",+ agent_kind: "openhands",+ revision: 3,+ llm_profile_ref: "slow",+ mcp_server_refs: null,+ },+ ],+ active_agent_profile_id: null,+ });+ mockListLlmProfiles.mockResolvedValue({+ profiles: [{ name: "slow" }, { name: "fast" }],+ active_profile: "slow",+ });++ await handleLaunchChildConversationAction(+ action({}),+ PARENT_ID,+ nextToolCallId(),+ );++ expect(mockCreateConversation).toHaveBeenCalledWith(+ expect.objectContaining({+ agentProfileId: "profile-1",+ agentProfileKind: "openhands",+ agentLlmProfileOverride: "fast",+ parentConversationId: PARENT_ID,+ }),+ );+ expect(getStoredConversationMetadata("child-id")?.active_profile).toBe(+ "fast",+ );+ });+it("reports the child's id, url and status back to the agent", async () => {seedWorktreeCapableParent();diff --git a/src/api/agent-server-adapter.test.ts b/src/api/agent-server-adapter.test.tsindex 4abd64a6cc..d3cc048fe5 100644--- a/src/api/agent-server-adapter.test.ts+++ b/src/api/agent-server-adapter.test.ts@@ -751,6 +751,30 @@ describe("buildStartConversationRequest β agentProfileId path", () => {]);});+ it("carries a per-launch LLM override only on a profile launch", () => {+ const settings = makeSettings({+ agent_kind: "openhands",+ llm: { model: "litellm_proxy/openai/gpt-5.5", api_key: "sk-test" },+ });++ const profileLaunch = buildStartConversationRequest({+ settings,+ agentProfileId: "profile-xyz",+ agentProfileKind: "openhands",+ llmProfileOverride: "fast",+ });+ expect(profileLaunch.agent_launch_additions).toEqual({+ llm_profile_ref: "fast",+ });++ const settingsLaunch = buildStartConversationRequest({+ settings,+ llmProfileOverride: "fast",+ });+ expect(settingsLaunch.agent_launch_additions).toBeUndefined();+ expect(settingsLaunch.agent_settings).toBeDefined();+ });+it("suppresses the ACP server tag when launching from a profile", () => {const agentSettings = {agent_kind: "acp",diff --git a/src/api/agent-server-adapter.ts b/src/api/agent-server-adapter.tsindex 6726e8b9f7..8f3fbbb936 100644--- a/src/api/agent-server-adapter.ts+++ b/src/api/agent-server-adapter.ts@@ -241,6 +241,14 @@ async function fetchBackendServerInfo(): Promise<AgentServerInfo | null> {}}+/** Whether start requests accept `agent_launch_additions.llm_profile_ref`. */+export async function backendSupportsLaunchLlmOverride(): Promise<boolean> {+ const serverInfo = await fetchBackendServerInfo();+ return (+ serverInfo?.capabilities?.includes("agent_launch_pipeline_v1") ?? false+ );+}+export async function fetchBackendExecutionRuntime(): Promise<AgentServerInfo["execution_runtime"]> {@@ -1197,8 +1205,12 @@ type AgentSettingsStartConversationPayload = StartConversationPayloadBase & {// exclusive agent sources; the server resolves the profile server-side.agent_settings?: AgentSettingsPayload;agent_profile_id?: string;- // Appended to the profile-resolved agent's system-message suffix.- agent_launch_additions?: { system_message_suffix_append?: string };+ agent_launch_additions?: {+ // Appended to the profile-resolved agent's system-message suffix.+ system_message_suffix_append?: string;+ // Runs the profile with this LLM profile instead of its own.+ llm_profile_ref?: string;+ };agent?: never;};@@ -1234,6 +1246,8 @@ export interface StartConversationOptions {// server-side) instead of an inline ``agent_settings`` dump (#3727).agentProfileId?: string;agentProfileKind?: AgentKind;+ /** LLM profile the agent profile runs with instead of its own. */+ llmProfileOverride?: string;titleLlmProfile?: string;runtimeServicesInfo?: RuntimeServicesInfo | null;executionRuntime?: AgentServerInfo["execution_runtime"];@@ -1312,6 +1326,14 @@ export function buildStartConversationRequest(].filter((suffix): suffix is string => Boolean(suffix)).join("\n\n");+ const launchAdditions = {+ ...(profileLaunchSuffix+ ? { system_message_suffix_append: profileLaunchSuffix }+ : {}),+ ...(options.llmProfileOverride+ ? { llm_profile_ref: options.llmProfileOverride }+ : {}),+ };const acpServerTag = acpMode? getAcpServerTag(sourceAgentSettings): undefined;@@ -1359,12 +1381,8 @@ export function buildStartConversationRequest(...(options.agentProfileId? {agent_profile_id: options.agentProfileId,- ...(profileLaunchSuffix- ? {- agent_launch_additions: {- system_message_suffix_append: profileLaunchSuffix,- },- }+ ...(Object.keys(launchAdditions).length > 0+ ? { agent_launch_additions: launchAdditions }: {}),}: { agent_settings: agentSettings }),@@ -1759,6 +1777,7 @@ export async function buildStartConversationRequestWithEncryptedSettings(optionsworktree?: boolean;agentProfileId?: string;agentProfileKind?: AgentKind;+ llmProfileOverride?: string;titleLlmProfile?: string;}): Promise<Record<string, unknown>> {const [{ SecretsService }, { default: HooksService }] = await Promise.all([diff --git a/src/api/agent-server-compatibility.ts b/src/api/agent-server-compatibility.tsindex 7ad8a9e0d5..78f3682321 100644--- a/src/api/agent-server-compatibility.ts+++ b/src/api/agent-server-compatibility.ts@@ -36,6 +36,7 @@ export interface AgentServerInfo extends BaseServerInfo {sdk_version?: string;runtime_services?: unknown;execution_runtime?: "local" | "docker";+ capabilities?: string[];}let cachedAgentServerInfo: AgentServerInfo | null = null;diff --git a/src/api/conversation-service/agent-server-conversation-service.api.ts b/src/api/conversation-service/agent-server-conversation-service.api.tsindex 17b0dabcc2..dda3398f35 100644--- a/src/api/conversation-service/agent-server-conversation-service.api.ts+++ b/src/api/conversation-service/agent-server-conversation-service.api.ts@@ -463,11 +463,12 @@ export interface CreateConversationOptions {* by the caller from the warmed meta-profiles query.*/hasActiveMetaProfile?: boolean;- // The LLM profile pinned to the launched agent profile (llm_profile_ref).- // When set and no explicit title_llm_profile preference exists, title- // generation uses this profile so both the agent and its title use the- // same model.+ // The LLM profile the launched agent profile runs. When set and no explicit+ // title_llm_profile preference exists, title generation uses this profile so+ // both the agent and its title use the same model.agentLlmProfileRef?: string | null;+ /** Local only: run the agent profile with this LLM profile instead of its own. */+ agentLlmProfileOverride?: string;}class AgentServerConversationService {@@ -526,6 +527,7 @@ class AgentServerConversationService {agentProfileId,agentProfileKind,agentLlmProfileRef,+ agentLlmProfileOverride,} = options;if (getActiveBackend().backend.kind === "cloud") {@@ -622,6 +624,7 @@ class AgentServerConversationService {worktree: !isolated && resolvedWorkspaceMode === "new_worktree",agentProfileId,agentProfileKind,+ llmProfileOverride: agentLlmProfileOverride,titleLlmProfile,});diff --git a/src/hooks/mutation/resolve-conversation-launch.ts b/src/hooks/mutation/resolve-conversation-launch.tsnew file mode 100644index 0000000000..789d615f07--- /dev/null+++ b/src/hooks/mutation/resolve-conversation-launch.ts@@ -0,0 +1,219 @@+import type { QueryClient } from "@tanstack/react-query";+import type { AgentKind } from "@openhands/typescript-client";+import AgentProfilesService, {+ WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME,+ type AgentProfileListResponse,+} from "#/api/agent-profiles-service/agent-profiles-service.api";+import ProfilesService from "#/api/profiles-service/profiles-service.api";+import { backendSupportsLaunchLlmOverride } from "#/api/agent-server-adapter";+import AgentServerConversationService, {+ type CreateConversationOptions,+} from "#/api/conversation-service/agent-server-conversation-service.api";+import type { AppConversationStartTask } from "#/api/conversation-service/agent-server-conversation-service.types";+import { mergeStoredConversationMetadata } from "#/api/conversation-metadata-store";+import {+ AGENT_PROFILES_QUERY_KEYS,+ AGENT_PROFILES_RETRY_OPTIONS,+ LLM_PROFILES_QUERY_KEYS,+} from "#/hooks/query/query-keys";++export interface ConversationLaunch {+ /** Unset when the launch sends the global `agent_settings` instead. */+ agentProfileId?: string;+ agentProfileKind?: AgentKind;+ /** Runs the agent profile with this LLM profile instead of its own. */+ llmProfileOverride?: string;+ /** The LLM profile the launch runs, when Canvas can tell. */+ llmProfile?: string;+}++export interface ResolveConversationLaunchOptions {+ queryClient: QueryClient;+ backendId: string;+ orgId: string | null | undefined;+ isCloud: boolean;+ /** An explicit profile pick; omitted launches the active profile. */+ agentProfileId?: string;+ /** The LLM profile to run, such as a parent conversation's current model. */+ llmProfile?: string | null;+}++/** Decide which agent source and LLM a new conversation launches with. */+export async function resolveConversationLaunch({+ queryClient,+ backendId,+ orgId,+ isCloud,+ agentProfileId,+ llmProfile,+}: ResolveConversationLaunchOptions): Promise<ConversationLaunch> {+ // Await the list from the shared query cache: a send fired before the home+ // query resolves must still launch from the active profile. Do not fall back+ // to the global agent_settings when profile discovery fails: activation is+ // pointer-only, so those settings may describe a different agent.+ const agentProfiles: AgentProfileListResponse =+ await queryClient.ensureQueryData({+ queryKey: [...AGENT_PROFILES_QUERY_KEYS.all, backendId, orgId],+ queryFn: AgentProfilesService.listProfiles,+ ...AGENT_PROFILES_RETRY_OPTIONS,+ // A failure here rejects the launch, which reports it.+ meta: { disableToast: true },+ });++ // Await the list rather than a render snapshot: a send fired before the+ // LLM-profile query loads must still validate the ref.+ const readLlmProfiles = () =>+ queryClient+ .ensureQueryData({+ queryKey: [...LLM_PROFILES_QUERY_KEYS.all, backendId, orgId],+ queryFn: ProfilesService.listProfiles,+ retry: false,+ meta: { disableToast: true },+ })+ .catch(() => null);++ const requestedAgentProfileId =+ agentProfileId ?? agentProfiles.active_agent_profile_id ?? undefined;+ const profile = requestedAgentProfileId+ ? agentProfiles.profiles?.find((p) => p.id === requestedAgentProfileId)+ : undefined;++ let prefersAgentSettings = false;+ let activeLlmProfile: string | null = null;+ let llmProfileOverride: string | undefined;+ if (+ !isCloud &&+ profile?.name === WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME &&+ profile.agent_kind === "openhands"+ ) {+ // The seeded OpenHands `default` launches via agent_settings so the Skills+ // page selection (buildAgentContext) applies: a profile launch gets the+ // server's whole skill catalog minus a deny-list. Per-profile fields saved+ // on `default` therefore don't apply on local launches.+ //+ // Scoped to OpenHands: global agent_settings is stale when an ACP profile+ // is active. Scoped to local: cloud always resolves `default` server-side.+ prefersAgentSettings = true;+ } else if (profile?.agent_kind === "openhands" && profile.llm_profile_ref) {+ const llm = await readLlmProfiles();+ // An unreadable list leaves the ref unvalidated; handled below.+ const llmProfileExists =+ llm?.profiles.some((p) => p.name === profile.llm_profile_ref) ?? false;+ activeLlmProfile = llm?.active_profile ?? null;+ // The home LLM pill shows and activates the account-wide active LLM+ // profile, never the pinned ref (#16539), so an implicit launch runs that+ // selection. An explicit pick keeps its pinned ref unless the ref is gone.+ const preferredLlmProfile =+ llmProfile ||+ (!agentProfileId || !llmProfileExists ? activeLlmProfile : null);+ const selectedLlmProfile =+ !isCloud &&+ preferredLlmProfile &&+ preferredLlmProfile !== profile.llm_profile_ref+ ? preferredLlmProfile+ : undefined;+ if (!llmProfileExists || selectedLlmProfile) {+ if (!isCloud && (await backendSupportsLaunchLlmOverride())) {+ // A dangling ref with nothing selected reaches the server, which+ // rejects it with an error the user can act on.+ llmProfileOverride = selectedLlmProfile;+ } else if (!llmProfileExists || !llmProfile) {+ // No per-launch override on this server: run agent_settings at the+ // cost of the profile's other fields. A requested LLM is dropped+ // instead, keeping the profile.+ if (!llmProfileExists) {+ console.warn(+ `Agent profile "${profile.name}" references missing ` ++ `LLM profile "${profile.llm_profile_ref}"; ` ++ "launching from agent_settings instead.",+ );+ }+ prefersAgentSettings = true;+ }+ }+ }++ // A legacy agent_settings launch carries no profile identity, so Agent+ // Server cannot enforce that profile's secret allow-list. Keep restricted+ // profiles on the server-resolved path; if the detail cannot be read, fail+ // closed and let Agent Server report the underlying error.+ let profileAllowsAgentSettings = true;+ if (prefersAgentSettings && profile) {+ try {+ const detail = await queryClient.fetchQuery({+ queryKey: AGENT_PROFILES_QUERY_KEYS.detail(+ backendId,+ orgId,+ profile.name,+ ),+ queryFn: () => AgentProfilesService.getProfile(profile.name),+ ...AGENT_PROFILES_RETRY_OPTIONS,+ meta: { disableToast: true },+ });+ const secretRefs = (detail.profile as { secret_refs?: unknown })+ .secret_refs;+ profileAllowsAgentSettings = !Array.isArray(secretRefs);+ } catch {+ profileAllowsAgentSettings = false;+ }+ }++ if (+ !requestedAgentProfileId ||+ (prefersAgentSettings && profileAllowsAgentSettings)+ ) {+ // An agent_settings launch runs the active LLM profile.+ if (!activeLlmProfile && !isCloud) {+ activeLlmProfile = (await readLlmProfiles())?.active_profile ?? null;+ }+ return { llmProfile: activeLlmProfile ?? undefined };+ }+ return {+ agentProfileId: requestedAgentProfileId,+ agentProfileKind: profile?.agent_kind,+ llmProfileOverride,+ llmProfile:+ profile?.agent_kind === "openhands"+ ? (llmProfileOverride ?? profile.llm_profile_ref ?? undefined)+ : undefined,+ };+}++/** Create a conversation from the resolved launch and record the LLM it runs. */+export async function launchConversation(+ { agentProfileId, llmProfile, ...context }: ResolveConversationLaunchOptions,+ options: CreateConversationOptions,+): Promise<AppConversationStartTask> {+ const launch = await resolveConversationLaunch({+ ...context,+ agentProfileId,+ llmProfile,+ });+ const task = await AgentServerConversationService.createConversation({+ ...options,+ ...launchProfileOptions(launch),+ });+ // The chat LLM picker names this profile even when several share a model+ // (#1082). Cloud conversations don't use local LLM profiles.+ if (!context.isCloud && task.app_conversation_id && launch.llmProfile) {+ mergeStoredConversationMetadata(task.app_conversation_id, {+ active_profile: launch.llmProfile,+ });+ }+ return task;+}++function launchProfileOptions(+ launch: ConversationLaunch,+): Partial<CreateConversationOptions> {+ if (!launch.agentProfileId) return {};+ return {+ agentProfileId: launch.agentProfileId,+ agentProfileKind: launch.agentProfileKind,+ // Title generation uses the same LLM as the agent (#16885).+ agentLlmProfileRef: launch.llmProfile,+ ...(launch.llmProfileOverride+ ? { agentLlmProfileOverride: launch.llmProfileOverride }+ : {}),+ };+}diff --git a/src/hooks/mutation/use-create-conversation.ts b/src/hooks/mutation/use-create-conversation.tsindex 821eeec00b..bf7b8ed97c 100644--- a/src/hooks/mutation/use-create-conversation.ts+++ b/src/hooks/mutation/use-create-conversation.ts@@ -1,5 +1,4 @@import { useMutation, useQueryClient } from "@tanstack/react-query";-import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";import { PluginSpec } from "#/api/conversation-service/agent-server-conversation-service.types";import { SuggestedTask } from "#/utils/types";import { Provider } from "#/types/settings";@@ -9,24 +8,14 @@ import { useAgentProfiles } from "#/hooks/query/use-agent-profiles";import { useSettings } from "#/hooks/query/use-settings";import { useMetaProfiles } from "#/hooks/query/use-meta-profiles";import { useActiveBackend } from "#/contexts/active-backend-context";-import ProfilesService from "#/api/profiles-service/profiles-service.api";-import AgentProfilesService, {- WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME,- type AgentProfileListResponse,-} from "#/api/agent-profiles-service/agent-profiles-service.api";import PluginsManagementService, {type InstalledPluginInfo,} from "#/api/plugins-management-service";-import {- PLUGINS_QUERY_KEYS,- LLM_PROFILES_QUERY_KEYS,- AGENT_PROFILES_QUERY_KEYS,- AGENT_PROFILES_RETRY_OPTIONS,-} from "#/hooks/query/query-keys";+import { PLUGINS_QUERY_KEYS } from "#/hooks/query/query-keys";+import { launchConversation } from "#/hooks/mutation/resolve-conversation-launch";import { pluginReferenceKey } from "#/utils/plugin-display";import {- getStoredConversationMetadata,- setStoredConversationMetadata,+ mergeStoredConversationMetadata,toPluginCoordinates,type WorkspaceMode,} from "#/api/conversation-metadata-store";@@ -76,17 +65,13 @@ export const useCreateConversation = ({}: UseCreateConversationOptions = {}) => {const queryClient = useQueryClient();const { trackConversationCreated } = useTracking();- // Cache-warm on the home page (the profile picker reads the same query).- // Stamped onto the conversation at creation so the switcher can show the- // exact profile even when several profiles share a model (#1082).- const { data: llmProfiles } = useLlmProfiles();- // Warm the agent-profiles cache too β the launch path below awaits the same- // query via ensureQueryData, so a warm cache makes home-launch instant. The- // hook's maybe-unresolved data is deliberately NOT read at launch time:- // activation is pointer-only (it never writes agent_settings), so racing a- // cold cache into the agent_settings fallback would silently launch the- // wrong agent.+ // Warm the profile caches β the launch awaits the same queries via+ // ensureQueryData, so a warm cache makes home-launch instant. The hooks'+ // maybe-unresolved data is deliberately NOT read at launch time: activation+ // is pointer-only (it never writes agent_settings), so racing a cold cache+ // into the agent_settings fallback would silently launch the wrong agent.const { backend, orgId } = useActiveBackend();+ useLlmProfiles();useAgentProfiles();// Read the "Run on first message" toggle from the warmed settings// query so the cloud path can stamp the router instruction without a@@ -119,171 +104,17 @@ export const useCreateConversation = ({} = variables;// The active AgentProfile is the default launch profile for new- // conversations (#3727), on both local and cloud (cloud gained- // /api/agent-profiles in OpenHands #15060, #3730). Await the list from- // the shared query cache: a send fired before the home query resolves- // must still launch from the active profile. Do not fall back to the- // global agent_settings when profile discovery fails: activation is- // pointer-only, so those settings may describe a different agent.- const agentProfiles: AgentProfileListResponse =- await queryClient.ensureQueryData({- queryKey: [...AGENT_PROFILES_QUERY_KEYS.all, backend.id, orgId],- queryFn: AgentProfilesService.listProfiles,- ...AGENT_PROFILES_RETRY_OPTIONS,- // A failure here rejects the mutation, which reports it; a query- // toast on top would show the same error twice.- meta: { disableToast: true },- });-- const requestedAgentProfileId =- agentProfileId ?? agentProfiles.active_agent_profile_id ?? undefined;-- // Fall back to the legacy agent_settings launch when the resolved agent- // profile can't resolve its LLM. The agent-server seeds a `default`- // openhands profile whose `llm_profile_ref` can point at an LLM profile- // that doesn't exist (fresh store, or one configured with named profiles- // only); launching from it 404s ("LLM profile '<ref>' not found") and- // would brick home-launch. agent_settings reflects the active LLM, so the- // fallback degrades cleanly until the seed mirrors it (SDK #3933).- // ACP profiles carry no llm_profile_ref, so they're never gated here.- const resolvedAgentProfile = requestedAgentProfileId- ? agentProfiles?.profiles?.find(- (profile) => profile.id === requestedAgentProfileId,- )- : undefined;- // Cloud has no `agent_settings` payload to fall back to β the downgrade- // below only makes sense on local, where it exists and carries the- // canvas-only enrichments. Gating it here keeps cloud always launching- // from the resolved profile id, so the conversation gets- // `launched_agent_profile` stamped and the profile's config applied- // (#1571 review).- const isCloud = backend.kind === "cloud";- let prefersAgentSettingsFallback = false;- // The account-wide active LLM profile from the launch-path fetch below- // (null when that fetch didn't run or failed). Fresher than the- // `useLlmProfiles()` render snapshot, which a fast send can outrun.- let fetchedActiveLlmProfile: string | null = null;- if (- !isCloud &&- resolvedAgentProfile?.name === WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME &&- resolvedAgentProfile?.agent_kind === "openhands"- ) {- // The seeded OpenHands `default` profile is the enriched baseline, not a- // deliberate profile pick β it mirrors global agent_settings. Launch it- // via agent_settings so the global settings and the canvas skill- // selection (buildAgentContext) apply to the common home-launch; the- // profile path resolves skills server-side instead.- // Named profiles are deliberate custom configs and still use the profile- // path.- // Trade-off: per-profile fields set on `default` itself don't apply on- // home-launch β custom per-profile config belongs in a named profile.- //- // Scoped to OpenHands: an ACP `default` must keep the profile path.- // Activation is pointer-only, so global agent_settings is stale (often- // still OpenHands) when an ACP profile is active β launching it via- // agent_settings would start the wrong agent.- //- // Scoped to local: cloud never writes agent_settings, so it always- // resolves `default` server-side via agent_profile_id (validated below).- prefersAgentSettingsFallback = true;- } else if (- resolvedAgentProfile?.agent_kind === "openhands" &&- resolvedAgentProfile.llm_profile_ref- ) {- // Await the LLM-profile list rather than reading the maybe-unresolved- // `useLlmProfiles()` result: a send fired before that query loads (or- // after it errors) must still validate the ref, not launch blind.- let llmProfileExists = false;- try {- const llm = await queryClient.ensureQueryData({- queryKey: [...LLM_PROFILES_QUERY_KEYS.all, backend.id, orgId],- queryFn: ProfilesService.listProfiles,- // Match the agent-profiles fetch above: on a backend where this- // errors, fall back to agent_settings immediately rather than- // stalling the send through the default exponential backoff.- retry: false,- // Handled by the fallback below, so there is nothing to report.- meta: { disableToast: true },- });- llmProfileExists = llm.profiles.some(- (profile) => profile.name === resolvedAgentProfile.llm_profile_ref,- );- fetchedActiveLlmProfile = llm.active_profile ?? null;- } catch {- // List unavailable β can't validate β fall back to agent_settings.- }- if (!llmProfileExists) {- // Downgrade is silent in the UI; leave a diagnosable trace.- console.warn(- `Agent profile "${resolvedAgentProfile.name}" references missing ` +- `LLM profile "${resolvedAgentProfile.llm_profile_ref}"; ` +- "launching from agent_settings instead.",- );- prefersAgentSettingsFallback = true;- } else if (- !isCloud &&- !agentProfileId &&- fetchedActiveLlmProfile &&- fetchedActiveLlmProfile !== resolvedAgentProfile.llm_profile_ref- ) {- // The home LLM pill shows β and its dropdown activates β the- // account-wide active LLM profile, never the pinned ref- // (useChatInputLlmProfileState), so when the two differ the launch- // must run the selection or the UI advertises a model the- // conversation won't use (#16539). Launch via agent_settings, which- // the dropdown's profile activation syncs to the selection. Scoped- // to the implicit active-profile launch: an explicit `agentProfileId`- // (the in-conversation profile picker) is a deliberate profile pick,- // so its pinned ref stays authoritative. Local-only like the- // downgrades above β cloud has no agent_settings payload to fall- // back to. Trade-off: the named profile's non-LLM config doesn't- // apply to this launch; the start request has no per-launch LLM- // override that could preserve it (AgentLaunchAdditions carries only- // a system-message suffix).- prefersAgentSettingsFallback = true;- }- }-- // A legacy agent_settings launch carries no profile identity, so Agent- // Server cannot enforce that profile's secret allow-list. Keep restricted- // profiles on the server-resolved path even when one of the compatibility- // fallbacks above would otherwise apply. If the detail cannot be read,- // fail closed by preserving the profile id and letting Agent Server return- // the underlying profile-resolution error.- let profileAllowsAgentSettingsFallback = true;- if (prefersAgentSettingsFallback && resolvedAgentProfile) {- try {- // Revalidate stale cached details: policy may have changed since the- // profile editor or another client last populated this query.- const detail = await queryClient.fetchQuery({- queryKey: AGENT_PROFILES_QUERY_KEYS.detail(- backend.id,- orgId,- resolvedAgentProfile.name,- ),- queryFn: () =>- AgentProfilesService.getProfile(resolvedAgentProfile.name),- ...AGENT_PROFILES_RETRY_OPTIONS,- // Handled by failing closed below, so there is nothing to report.- meta: { disableToast: true },- });- const secretRefs = (detail.profile as { secret_refs?: unknown })- .secret_refs;- profileAllowsAgentSettingsFallback = !Array.isArray(secretRefs);- } catch {- profileAllowsAgentSettingsFallback = false;- }- }- const effectiveAgentProfileId =- prefersAgentSettingsFallback && profileAllowsAgentSettingsFallback- ? undefined- : requestedAgentProfileId;-- // Only extend the call with the profile fields when launching from a- // profile, so a plain create stays byte-identical to the legacy- // agent_settings path (#3727). sandboxId is unused here.- const conversation =- await AgentServerConversationService.createConversation({+ // conversations (#3727), on both local and cloud. sandboxId is unused+ // here.+ const conversation = await launchConversation(+ {+ queryClient,+ backendId: backend.id,+ orgId,+ isCloud: backend.kind === "cloud",+ agentProfileId,+ },+ {initialUserMsg: query,automationSetup,...(automationSetupTags ? { automationSetupTags } : {}),@@ -300,15 +131,6 @@ export const useCreateConversation = ({workspaceMode,parentConversationId,agentType,- ...(effectiveAgentProfileId- ? {- agentProfileId: effectiveAgentProfileId,- agentProfileKind: resolvedAgentProfile?.agent_kind,- // Let title generation use the same LLM as the agent profile- // so the title and the agent steps share a model (#16885).- agentLlmProfileRef: resolvedAgentProfile?.llm_profile_ref,- }- : {}),// Only stamp the toggle when it's on so the default path stays// byte-identical to the legacy launch (and the e2e snapshot tests// that assert the exact createConversation payload). The active@@ -320,13 +142,11 @@ export const useCreateConversation = ({hasActiveMetaProfile: !!metaProfiles?.active_meta_profile,}: {}),- });+ },+ );- // Stamp the active LLM profile onto the (local) conversation so the- // chat switcher shows the exact profile even when several profiles- // share a model (#1082). Cloud conversations don't use local profiles- // (app_conversation_id stays null until the sandbox is READY). Merge so- // the repo/workspace metadata the service just persisted is preserved.+ // Cloud conversations have no app_conversation_id until the sandbox is+ // READY.const localConversationId = conversation.app_conversation_id;// Snapshot the conversation's plugins into client-side metadata so the// in-conversation plugins view can show what's loaded (coordinates only@@ -364,32 +184,10 @@ export const useCreateConversation = ({.filter((plugin) => !seen.has(pluginReferenceKey(plugin)));attachedPlugins = [...explicitPlugins, ...enabledInstalled];}- // A launch from a named OpenHands profile runs that profile's- // `llm_profile_ref`, which can differ from the standalone active LLM- // profile β stamp the ref so the switcher pill names the exact profile- // the conversation runs (#1082). The agent_settings paths (the `default`- // baseline, a dangling ref, or a dropdown override (#16539) β where- // effectiveAgentProfileId is cleared) run the active LLM, so they stamp- // the active profile, preferring the launch-path fetch over the hook's- // render snapshot. ACP profiles carry no LLM profile, so they fall- // through to the active-profile stamp (unused by the ACP model chip).- const activeProfile =- effectiveAgentProfileId &&- resolvedAgentProfile?.agent_kind === "openhands"- ? resolvedAgentProfile.llm_profile_ref- : (fetchedActiveLlmProfile ?? llmProfiles?.active_profile ?? null);- if (localConversationId && (activeProfile || attachedPlugins.length)) {- const prev = getStoredConversationMetadata(localConversationId);- setStoredConversationMetadata(localConversationId, {- selected_repository: prev?.selected_repository ?? null,- selected_branch: prev?.selected_branch ?? null,- git_provider: prev?.git_provider ?? null,- selected_workspace: prev?.selected_workspace ?? null,- workspace_mode: prev?.workspace_mode ?? null,- active_profile: activeProfile ?? prev?.active_profile ?? null,- plugins: attachedPlugins.length- ? attachedPlugins- : (prev?.plugins ?? null),+ // Merge so the metadata the launch just persisted is preserved.+ if (localConversationId && attachedPlugins.length) {+ mergeStoredConversationMetadata(localConversationId, {+ plugins: attachedPlugins,});}diff --git a/src/hooks/mutation/use-new-conversation-command.ts b/src/hooks/mutation/use-new-conversation-command.tsindex 0f86bfe4c3..205c1fc896 100644--- a/src/hooks/mutation/use-new-conversation-command.ts+++ b/src/hooks/mutation/use-new-conversation-command.ts@@ -2,7 +2,6 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";import { useTranslation } from "react-i18next";import toast from "react-hot-toast";import { I18nKey } from "#/i18n/declaration";-import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";import {displayErrorToast,displaySuccessToast,@@ -13,6 +12,8 @@ import { useActiveConversation } from "#/hooks/query/use-active-conversation";import { useSettings } from "#/hooks/query/use-settings";import { useMetaProfiles } from "#/hooks/query/use-meta-profiles";import { useTracking } from "#/hooks/use-tracking";+import { useActiveBackend } from "#/contexts/active-backend-context";+import { launchConversation } from "#/hooks/mutation/resolve-conversation-launch";export const useNewConversationCommand = () => {const queryClient = useQueryClient();@@ -22,6 +23,7 @@ export const useNewConversationCommand = () => {const { data: settings } = useSettings();const { data: metaProfiles } = useMetaProfiles();const { trackConversationCreated } = useTracking();+ const { backend, orgId } = useActiveBackend();const mutation = useMutation({mutationFn: async () => {@@ -32,7 +34,13 @@ export const useNewConversationCommand = () => {// /new reuses the parent conversation's sandbox (matches OpenHands// cloud behavior); it is NOT a sub-conversation, so parent_conversation_id// and agent_type stay undefined.- const startTask = await AgentServerConversationService.createConversation(+ const startTask = await launchConversation(+ {+ queryClient,+ backendId: backend.id,+ orgId,+ isCloud: backend.kind === "cloud",+ },{sandboxId: conversation.sandbox_id ?? undefined,// Only stamp the toggle when it's on so the default /new pathdiff --git a/src/hooks/use-acp-model-context.ts b/src/hooks/use-acp-model-context.tsindex f50285c403..8cd7c8cd53 100644--- a/src/hooks/use-acp-model-context.ts+++ b/src/hooks/use-acp-model-context.ts@@ -1,7 +1,6 @@import { useTranslation } from "react-i18next";import { useActiveBackend } from "#/contexts/active-backend-context";import { useActiveConversation } from "#/hooks/query/use-active-conversation";-import { useSettings } from "#/hooks/query/use-settings";import { useActiveAgentKind } from "#/hooks/use-active-agent-profile";import { I18nKey } from "#/i18n/declaration";@@ -12,9 +11,8 @@ export interface AcpModelContext {/** The active conversation runs an ACP agent. */isActiveAcpConversation: boolean;/**- * No active conversation (home page) but the saved agent settings already- * select an ACP agent β the next conversation created here inherits it, so- * the model UI should reflect that now.+ * No active conversation (home page) and the next launch starts an ACP+ * agent, so the model UI should reflect that now.*/isHomeAcp: boolean;/** Either of the above: the model affordance should defer to the ACP picker. */@@ -35,16 +33,10 @@ export function useAcpModelContext(): AcpModelContext {const { t } = useTranslation("openhands");const { backend } = useActiveBackend();const { data: conversation } = useActiveConversation();- const { data: settings } = useSettings();const activeAgentKind = useActiveAgentKind();const isActiveAcpConversation = conversation?.agent_kind === "acp";- // On the home page the "current agent" is the active AgentProfile, not the- // global agent settings (activate never writes them). Fall back to settings- // only while the profile list is loading.- const isHomeAcp =- !conversation &&- (activeAgentKind ?? settings?.agent_settings?.agent_kind) === "acp";+ const isHomeAcp = !conversation && activeAgentKind === "acp";const isAcpContext = isActiveAcpConversation || isHomeAcp;const destinationPath = isAcpContextdiff --git a/src/hooks/use-active-agent-profile.ts b/src/hooks/use-active-agent-profile.tsindex e1bcd44916..cf9fbb635a 100644--- a/src/hooks/use-active-agent-profile.ts+++ b/src/hooks/use-active-agent-profile.ts@@ -1,6 +1,7 @@import type { AgentKind } from "@openhands/typescript-client";import type { AgentProfileSummary } from "#/api/agent-profiles-service/agent-profiles-service.api";import { useAgentProfiles } from "#/hooks/query/use-agent-profiles";+import { useSettings } from "#/hooks/query/use-settings";/*** The agent profile the user has activated β the authoritative "current agent"@@ -8,25 +9,33 @@ import { useAgentProfiles } from "#/hooks/query/use-agent-profiles";* pointer-only and never writes `settings.agent_settings`, so the active* profile β not the global agent settings β is the source of truth for what* kind of agent (OpenHands vs ACP) is in effect.+ *+ * Cached profile data survives a failed refetch; `isError` is set only when a+ * failed fetch left nothing to decide from, and `agentKind` is then+ * `undefined`. Without an active profile `agentKind` comes from the global+ * agent settings: briefly while the list loads, and for good when no profile+ * is active, the one case a launch sends them.*/export function useActiveAgentProfile(): {activeProfile: AgentProfileSummary | null;+ agentKind: AgentKind | undefined;isLoading: boolean;+ isError: boolean;} {- const { data, isLoading } = useAgentProfiles();+ const { data, isLoading, isError: queryError } = useAgentProfiles();+ const { data: settings } = useSettings();const activeId = data?.active_agent_profile_id ?? null;const activeProfile =data?.profiles?.find((p) => p.id != null && p.id === activeId) ?? null;- return { activeProfile, isLoading };+ const isError = queryError && !data;+ const settingsKind = settings?.agent_settings?.agent_kind;+ let agentKind: AgentKind | undefined;+ if (activeProfile) agentKind = activeProfile.agent_kind;+ else if (!isError && (settingsKind === "acp" || settingsKind === "openhands"))+ agentKind = settingsKind;+ return { activeProfile, agentKind, isLoading, isError };}-/**- * The effective agent kind from the active profile. `undefined` while the- * profile list is loading or when no profile is active β callers should fall- * back to `settings.agent_settings.agent_kind` in that window to avoid a flash- * of the wrong (OpenHands-default) UI.- */export function useActiveAgentKind(): AgentKind | undefined {- const { activeProfile } = useActiveAgentProfile();- return activeProfile?.agent_kind;+ return useActiveAgentProfile().agentKind;}diff --git a/src/hooks/use-llm-configured.ts b/src/hooks/use-llm-configured.tsindex 6a0346217a..fe1b886a13 100644--- a/src/hooks/use-llm-configured.ts+++ b/src/hooks/use-llm-configured.ts@@ -57,15 +57,14 @@ export function useLlmConfigured(): LlmConfiguredResult {const isLocal = backend.kind === "local";// The active AgentProfile is the current agent β an ACP profile owns its LLM- // via the subprocess and never needs an API key. Fall back to the global- // agent settings only while the profile list loads.+ // via the subprocess and never needs an API key.const {activeProfile: activeAgentProfile,+ agentKind: activeAgentKind,isLoading: activeAgentProfileLoading,+ isError: activeAgentProfileError,} = useActiveAgentProfile();- const activeAgentKind = activeAgentProfile?.agent_kind;- const isAcpAgent =- (activeAgentKind ?? settings?.agent_settings?.agent_kind) === "acp";+ const isAcpAgent = activeAgentKind === "acp";const hasApiKey = settings?.llm_api_key_set === true;// The LLM that will actually power the next conversation is the profile the// active AGENT profile references (`llm_profile_ref`) β conversations launch@@ -88,12 +87,8 @@ export function useLlmConfigured(): LlmConfiguredResult {: undefined;// Fall back to the active LLM profile when the ref is absent (list loading,// or an agent profile without a ref) OR stale (names a profile that no longer- // exists). This mirrors the launch-time fallback in `useCreateConversation`,- // which drops a stale-ref profile launch to an `agent_settings` launch on the- // active LLM. Without this fallback the two contradict each other: launch- // succeeds via the fallback, but this hook reports `isConfigured: false` and- // spuriously disables the composer + shows the banner β even inside a running- // conversation (VascoSch92 review, #1571).+ // exists): a launch runs the active LLM profile for a stale ref, so gating on+ // the ref would disable a composer whose launch succeeds.const activeProfile =referencedProfile ??profilesData?.profiles.find(@@ -148,10 +143,11 @@ export function useLlmConfigured(): LlmConfiguredResult {const settingsIndeterminate = settingsLoading || (settingsError && !settings);const configIndeterminate = configLoading || (configError && !config);// The active agent profile decides `isAcpAgent` and which LLM profile the- // next conversation runs; on a cold cache it's still loading, so decide- // nothing yet β otherwise an ACP agent (which needs no key) briefly reads as- // an unconfigured OpenHands agent and flashes the "LLM not set up" banner.- const agentProfileIndeterminate = activeAgentProfileLoading;+ // next conversation runs; until it is known, decide nothing β otherwise an+ // ACP agent (which needs no key) reads as an unconfigured OpenHands agent and+ // shows the "LLM not set up" banner.+ const agentProfileIndeterminate =+ activeAgentProfileLoading || activeAgentProfileError;const profilesIndeterminate =profilesLoading || (profilesError && !profilesData);const activeProfileDetailIndeterminate =diff --git a/src/services/child-conversation-launch.ts b/src/services/child-conversation-launch.tsindex 28bc4f18e0..1b74c8968e 100644--- a/src/services/child-conversation-launch.ts+++ b/src/services/child-conversation-launch.ts@@ -17,6 +17,9 @@ import {import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";import type { AppConversationStartTask } from "#/api/conversation-service/agent-server-conversation-service.types";import { buildRouterAtStartSystemSuffix } from "#/api/agent-server-adapter";+import { getActiveBackend } from "#/api/backend-registry/active-store";+import { launchConversation } from "#/hooks/mutation/resolve-conversation-launch";+import { getQueryClient } from "#/query-client-config";import SettingsService from "#/api/settings-service/settings-service.api";import MetaProfilesService from "#/api/meta-profiles-service/meta-profiles-service.api";import {@@ -241,6 +244,24 @@ const parentSupportsWorktree = (const SHARED_FALLBACK_CONSEQUENCE ="The child was launched in this conversation's directory instead, so it can see work in progress here and the two agents may conflict over the same files.";+/** The parent's Agent Profile and current LLM, so the child stays in its scope. */+async function parentProfileLaunch(parentConversationId: string) {+ const [parent] =+ await AgentServerConversationService.batchGetAppConversations([+ parentConversationId,+ ]);+ const { backend, orgId } = getActiveBackend();+ return {+ queryClient: getQueryClient(),+ backendId: backend.id,+ orgId,+ isCloud: false,+ agentProfileId: parent?.launched_agent_profile?.agent_profile_id,+ llmProfile:+ parent?.agent_kind === "openhands" ? parent.active_profile : null,+ };+}+async function launchLocalChild(params: ValidatedParams,parentConversationId: string,@@ -253,9 +274,10 @@ async function launchLocalChild(parentConversationId,);const parentMetadata = getStoredConversationMetadata(parentConversationId);+ const profileLaunch = await parentProfileLaunch(parentConversationId);const createChild = (isolation: ChildConversationIsolation) =>- AgentServerConversationService.createConversation({+ launchConversation(profileLaunch, {initialUserMsg: params.task,metadata: parentMetadata? {