π OpenHands: AI-Driven Development
fix: list a cloud conversation own skills in show available skills (#17067)
Hiep Leb4428e1f8529
diff --git a/__tests__/api/cloud/skills-service.test.ts b/__tests__/api/cloud/skills-service.test.tsindex b54445def4..984873d4db 100644--- a/__tests__/api/cloud/skills-service.test.ts+++ b/__tests__/api/cloud/skills-service.test.ts@@ -80,3 +80,57 @@ describe("SkillsService.getSkills against cloud backend", () => {expect(skills[1]).toMatchObject({ triggers: ["foo"] });});});++describe("SkillsService.getConversationSkills against cloud backend", () => {+ it("reads the conversation's own skills route and maps entries to SkillInfo", async () => {+ // Arrange+ fetchMock.mockResolvedValueOnce(+ mockJsonResponse({+ skills: [+ {+ name: "release-notes",+ type: "agentskills",+ content: "# Release notes",+ triggers: ["/release-notes"],+ },+ {+ name: "repo",+ type: "repo",+ content: "Repository instructions",+ triggers: [],+ },+ ],+ }),+ );++ // Act+ const skills = await SkillsService.getConversationSkills("conv-1");++ // Assert+ expect(fetchMock).toHaveBeenCalledTimes(1);+ const [url, init] = getFetchCall(fetchMock, 0);+ expect(url).toBe(+ "https://app.all-hands.dev/api/v1/app-conversations/conv-1/skills",+ );+ expect(init).toMatchObject({+ method: "GET",+ headers: { Authorization: "Bearer bearer-token" },+ });+ expect(skills).toEqual([+ {+ name: "release-notes",+ type: "agentskills",+ content: "# Release notes",+ triggers: ["/release-notes"],+ source: null,+ },+ {+ name: "repo",+ type: "repo",+ content: "Repository instructions",+ triggers: [],+ source: null,+ },+ ]);+ });+});diff --git a/__tests__/hooks/query/use-conversation-skills.test.tsx b/__tests__/hooks/query/use-conversation-skills.test.tsxnew file mode 100644index 0000000000..39ceb31c5a--- /dev/null+++ b/__tests__/hooks/query/use-conversation-skills.test.tsx@@ -0,0 +1,199 @@+import React from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { renderHook, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";+import SkillsService from "#/api/skills-service";+import {+ __resetActiveStoreForTests,+ setActiveSelection,+ setRegisteredBackends,+} from "#/api/backend-registry/active-store";+import type { Backend } from "#/api/backend-registry/types";+import type { AppConversation } from "#/api/conversation-service/agent-server-conversation-service.types";+import { NavigationProvider } from "#/context/navigation-context";+import { ActiveBackendProvider } from "#/contexts/active-backend-context";+import { useConversationSkills } from "#/hooks/query/use-conversation-skills";+import type { SkillInfo } from "#/types/settings";++const localBackend: Backend = {+ id: "local-1",+ name: "Local",+ host: "http://localhost:8000",+ apiKey: "session-key",+ kind: "local",+};++const cloudBackend: Backend = {+ id: "cloud-1",+ name: "Production",+ host: "https://app.all-hands.dev",+ apiKey: "bearer-key",+ kind: "cloud",+};++const CONVERSATION_ID = "conv-1";+const WORKSPACE = "/workspace/project/demo";++function makeConversation(+ overrides: Partial<AppConversation> = {},+): AppConversation {+ return {+ id: CONVERSATION_ID,+ created_by_user_id: null,+ selected_repository: null,+ selected_branch: null,+ git_provider: null,+ title: "Test",+ trigger: null,+ pr_number: [],+ llm_model: null,+ metrics: null,+ created_at: "2024-01-01T00:00:00Z",+ updated_at: "2024-01-01T00:00:00Z",+ execution_status: null,+ sandbox_status: "RUNNING",+ conversation_url: "https://sandbox.example.com/api",+ session_api_key: null,+ sandbox_id: null,+ sub_conversation_ids: [],+ selected_workspace: WORKSPACE,+ ...overrides,+ };+}++function makeSkill(name: string): SkillInfo {+ return {+ name,+ type: "agentskills",+ source: null,+ content: `# ${name}`,+ triggers: [],+ };+}++function makeWrapper(conversationId: string | null) {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ function Wrapper({ children }: { children: React.ReactNode }) {+ return (+ <QueryClientProvider client={queryClient}>+ <ActiveBackendProvider>+ <NavigationProvider+ value={{+ currentPath: "/",+ conversationId,+ isNavigating: false,+ navigate: vi.fn(),+ }}+ >+ {children}+ </NavigationProvider>+ </ActiveBackendProvider>+ </QueryClientProvider>+ );+ }+ return { wrapper: Wrapper, queryClient };+}++beforeEach(() => {+ window.localStorage.clear();+ __resetActiveStoreForTests();+ setRegisteredBackends([localBackend, cloudBackend]);+ // Mock the services the hook depends on, not the hooks themselves.+ vi.spyOn(+ AgentServerConversationService,+ "batchGetAppConversations",+ ).mockResolvedValue([makeConversation()]);+ vi.spyOn(SkillsService, "getConversationSkills").mockResolvedValue([+ makeSkill("release-notes"),+ ]);+ vi.spyOn(SkillsService, "getSkills").mockResolvedValue([+ makeSkill("catalog-only"),+ ]);+});++afterEach(() => {+ vi.restoreAllMocks();+ window.localStorage.clear();+ __resetActiveStoreForTests();+});++describe("useConversationSkills", () => {+ it("lists the conversation's own skills on a cloud backend once its sandbox runs", async () => {+ // Arrange+ setActiveSelection({ backendId: cloudBackend.id });+ const { wrapper } = makeWrapper(CONVERSATION_ID);++ // Act+ const { result } = renderHook(() => useConversationSkills(), { wrapper });++ // Assert+ await waitFor(() =>+ expect(result.current.data).toEqual([makeSkill("release-notes")]),+ );+ expect(SkillsService.getConversationSkills).toHaveBeenCalledWith(+ CONVERSATION_ID,+ );+ expect(SkillsService.getSkills).not.toHaveBeenCalled();+ });++ it("does not request skills for a cloud conversation whose sandbox is not running yet", async () => {+ // Arrange+ setActiveSelection({ backendId: cloudBackend.id });+ vi.mocked(+ AgentServerConversationService.batchGetAppConversations,+ ).mockResolvedValue([makeConversation({ sandbox_status: "STARTING" })]);+ const { wrapper, queryClient } = makeWrapper(CONVERSATION_ID);++ // Act+ const { result } = renderHook(() => useConversationSkills(), { wrapper });++ // Assert β even once the conversation itself has loaded.+ await waitFor(() => {+ const [entry] = queryClient.getQueriesData<AppConversation | null>({+ queryKey: ["user", "conversation"],+ });+ expect(entry?.[1]?.sandbox_status).toBe("STARTING");+ });+ expect(result.current.fetchStatus).toBe("idle");+ expect(result.current.data).toBeUndefined();+ expect(SkillsService.getConversationSkills).not.toHaveBeenCalled();+ expect(SkillsService.getSkills).not.toHaveBeenCalled();+ });++ it("keeps the workspace-scoped catalog on a local backend", async () => {+ // Arrange+ setActiveSelection({ backendId: localBackend.id });+ const { wrapper } = makeWrapper(CONVERSATION_ID);++ // Act+ const { result } = renderHook(() => useConversationSkills(), { wrapper });++ // Assert+ await waitFor(() =>+ expect(SkillsService.getSkills).toHaveBeenCalledWith(WORKSPACE),+ );+ await waitFor(() =>+ expect(result.current.data).toEqual([makeSkill("catalog-only")]),+ );+ expect(SkillsService.getConversationSkills).not.toHaveBeenCalled();+ });++ it("falls back to the global catalog on a cloud backend without a conversation route", async () => {+ // Arrange+ setActiveSelection({ backendId: cloudBackend.id });+ const { wrapper } = makeWrapper(null);++ // Act+ const { result } = renderHook(() => useConversationSkills(), { wrapper });++ // Assert+ await waitFor(() =>+ expect(result.current.data).toEqual([makeSkill("catalog-only")]),+ );+ expect(SkillsService.getSkills).toHaveBeenCalledWith(undefined);+ expect(SkillsService.getConversationSkills).not.toHaveBeenCalled();+ });+});diff --git a/src/api/cloud/skills-service.api.ts b/src/api/cloud/skills-service.api.tsindex a1b45459cd..a6daec6b56 100644--- a/src/api/cloud/skills-service.api.ts+++ b/src/api/cloud/skills-service.api.ts@@ -47,3 +47,37 @@ export async function fetchCloudSkills(): Promise<SkillInfo[]> {return skills;}++interface CloudConversationSkill {+ name: string;+ type: SkillInfo["type"];+ content: string;+ triggers: string[];+}++interface CloudConversationSkillsResponse {+ skills: CloudConversationSkill[];+}++/**+ * Fetch the skills loaded into a running cloud conversation from the+ * per-conversation route (the one the OpenHands web UI's own "Show Available+ * Skills" modal uses). Unlike `/api/v1/skills/search`, which only scans the+ * API host's built-in skills directory, this resolves the conversation's+ * sandbox and asks its agent-server for the merged set: public catalog,+ * user/org repos, project skills and auto-loaded marketplace plugins. The+ * route reports no `source`, so it is `null`.+ */+export async function fetchCloudConversationSkills(+ conversationId: string,+): Promise<SkillInfo[]> {+ const backend = getActiveCloudBackend();++ const data = await callCloudProxy<CloudConversationSkillsResponse>({+ backend,+ method: "GET",+ path: `/api/v1/app-conversations/${conversationId}/skills`,+ });++ return (data?.skills ?? []).map((skill) => ({ ...skill, source: null }));+}diff --git a/src/api/skills-service.ts b/src/api/skills-service.tsindex 4b1ef8ba82..496ac4d19a 100644--- a/src/api/skills-service.ts+++ b/src/api/skills-service.ts@@ -6,7 +6,10 @@ import {import { SkillInfo } from "#/types/settings";import { getAgentServerWorkingDir } from "./agent-server-config";import { getActiveBackend } from "./backend-registry/active-store";-import { fetchCloudSkills } from "./cloud/skills-service.api";+import {+ fetchCloudConversationSkills,+ fetchCloudSkills,+} from "./cloud/skills-service.api";import { getAgentServerClientOptions } from "./agent-server-client-options";function catalogEntryToSkillInfo(entry: SkillCatalogEntry): SkillInfo {@@ -62,6 +65,16 @@ class SkillsService {return [...localSkills, ...PUBLIC_SKILLS];}++ /**+ * Skills loaded into a running cloud conversation (see+ * `fetchCloudConversationSkills`). Cloud-only: local conversations keep+ * using `getSkills(projectDir)`, whose agent-server call already scopes to+ * the conversation's workspace.+ */+ static getConversationSkills(conversationId: string): Promise<SkillInfo[]> {+ return fetchCloudConversationSkills(conversationId);+ }}export default SkillsService;diff --git a/src/hooks/query/use-conversation-skills.ts b/src/hooks/query/use-conversation-skills.tsindex 609e1db454..e716adf2f5 100644--- a/src/hooks/query/use-conversation-skills.ts+++ b/src/hooks/query/use-conversation-skills.ts@@ -1,13 +1,44 @@+import { useQuery } from "@tanstack/react-query";+import SkillsService from "#/api/skills-service";+import { useActiveBackend } from "#/contexts/active-backend-context";+import { useOptionalConversationId } from "#/hooks/use-conversation-id";+import { SkillInfo } from "#/types/settings";import { useActiveConversation } from "./use-active-conversation";-import { useSkills } from "./use-skills";/**- * Skills catalog scoped to the active conversation's attached workspace, so- * the slash-command menu and skills modal list the same project skills that- * were loaded into the conversation. Falls back to the global workspace dir- * for "No workspace" conversations (``selected_workspace`` is null).+ * Skills catalog scoped to the active conversation, so the slash-command menu+ * and skills modal list the same skills that were loaded into it.+ *+ * Cloud: the per-conversation route reports what the conversation's+ * agent-server actually loaded (public catalog, user/org repos, project+ * skills, auto-loaded marketplace plugins); the global `/api/v1/skills/search`+ * catalog only scans the API host's built-in skills directory. The route needs+ * a running sandbox, which `useActiveConversation` polls for.+ *+ * Local (and cloud with no conversation route, e.g. the home page): the+ * workspace-scoped catalog, falling back to the global workspace dir for+ * "No workspace" conversations (`selected_workspace` is null).*/export const useConversationSkills = () => {- const conversation = useActiveConversation();- return useSkills(conversation.data?.selected_workspace ?? undefined);+ const isCloud = useActiveBackend().backend.kind === "cloud";+ const { conversationId } = useOptionalConversationId();+ const { data: conversation } = useActiveConversation();+ const projectDir = conversation?.selected_workspace ?? undefined;+ // Keyed on the route id so a still-loading cloud conversation does not fall+ // back to the global catalog; only a missing route does.+ const cloudConversationId = isCloud ? conversationId : null;++ return useQuery<SkillInfo[]>({+ queryKey: cloudConversationId+ ? ["conversation", cloudConversationId, "skills"]+ : ["skills", projectDir ?? null],+ queryFn: () =>+ cloudConversationId+ ? SkillsService.getConversationSkills(cloudConversationId)+ : SkillsService.getSkills(projectDir),+ // The cloud route 404s until the sandbox runs.+ enabled: !cloudConversationId || conversation?.sandbox_status === "RUNNING",+ staleTime: 1000 * 60 * 10, // 10 minutes β skill list rarely changes+ refetchOnWindowFocus: false,+ });};