diff --git a/ui/apps/chat/README.md b/ui/apps/chat/README.md index ef8230b33324..88fba341fd0a 100644 --- a/ui/apps/chat/README.md +++ b/ui/apps/chat/README.md @@ -161,7 +161,7 @@ An extension is a feature the app is composed with and that can be switched off. A prompt is one kind of item whatever it comes from. The library (`promptsStore`, the Library page) is the app's own source of prompts, and an extension adds another through `promptSources`: MCP lists the prompts of its servers. `/prompt` and the System message list in the chat form's + menu show the prompts of every source together, each with where it comes from, and either sends a prompt with a message or makes it the chat's system message. -Skills are listed the same way, to browse and read: the Library's Skills tab shows the skills found in `~/.agents/skills` and `~/.claude/skills` on the machine llama-server runs on, read through llama-server's file tools (`skillsStore`, `LocalSkillsService`), and an extension adds another source through `skillSources`: MCP lists the skills its servers publish. +Skills are listed the same way: the Library's Skills tab shows the skills found in `~/.agents/skills` and `~/.claude/skills` on the machine llama-server runs on, read through llama-server's file tools (`skillsStore`, `LocalSkillsService`), and an extension adds another source through `skillSources`: MCP lists the skills its servers publish. A chat uses every source the same way: `/skill` attaches a skill to the message, and the model lists and loads skills through the app's own `list_skills` and `load_skill` tools (`SkillToolsService`). A load asks the user for the skill, in the tool permission card, and the source keeps the answer bound to the skill's content: a local skill's SKILL.md digest, an MCP skill's digest set. The core never imports an extension's own code; an extension may import the core. ESLint enforces this: a file outside `src/lib/extensions//` cannot import from that folder. diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte index 1ae3fd3278eb..7505002bc048 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte @@ -13,6 +13,7 @@ ChatFormInputFileInputInvisible, ChatFormPickerPrompts, ChatFormPickers, + ChatFormPickerSkills, ChatFormSystemMessageAttachment, ChatFormSystemMessageChip } from '#lib/components/app/index.ts'; @@ -23,6 +24,7 @@ OPEN_OVERLAY_SELECTOR, PROMPTS_PICKER_ID, SETTING_CONFIG_DEFAULT, + SKILLS_PICKER_ID, SYSTEM_MESSAGE_PLACEHOLDER, VOICE_EDITOR_SELECTOR } from '#lib/constants/index.ts'; @@ -53,6 +55,7 @@ modelsStore, serverStore, settingsStore, + skillsStore, toolsStore, uiStore, voiceTranscriptsStore @@ -186,12 +189,18 @@ component: ChatFormPickerPrompts, id: PROMPTS_PICKER_ID }; + // so is the skill picker, over every source of skills + const SKILLS_PICKER: ComposerPicker = { + component: ChatFormPickerSkills, + id: SKILLS_PICKER_ID + }; // what extensions add to the form: slash commands, the pickers they open, and // attachments that wait outside the form's files let contributedCommands = $derived(extensions.contributions('composerCommands')); let contributedPickers = $derived([ PROMPTS_PICKER, + SKILLS_PICKER, ...extensions.contributions('composerPickers') ]); let contributedAttachments = $derived(extensions.contributions('composerAttachments')); @@ -226,6 +235,7 @@ getShowModelSelector: () => isModelSelectorShown, getValue: () => value, hasCwdTools: () => conversationsStore.preferences.hasEnabledCwdTools(), + hasSkills: () => skillsStore.hasAvailableSources, onCompact: () => chatStore.compactConversation(), onSystemMessage: () => onSystemPromptClick?.({ files: uploadedFiles, message: value }), openModelSelector: () => chatFormActionsRef?.openModelSelector(), diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormPickers/ChatFormPickerPromptOrigin.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormPickers/ChatFormPickerPromptOrigin.svelte index 341645d24a20..1c94d643d879 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormPickers/ChatFormPickerPromptOrigin.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormPickers/ChatFormPickerPromptOrigin.svelte @@ -1,16 +1,17 @@ - + {#if entry.iconUrl} + import ChatFormPickerPromptOrigin from './ChatFormPickerPromptOrigin.svelte'; + import { Badge } from '@ggml-org/llama-ui/ui/badge'; + import { + ChatFormPickerList, + ChatFormPickerListItem, + ChatFormPickerListItemSkeleton, + ChatFormPickerPopover + } from '#lib/components/app/chat/index.ts'; + import { SKILL_SEARCH_MIN_ITEMS } from '#lib/constants/index.ts'; + import type { ComposerPickerProps } from '#lib/extensions/index.ts'; + import { usePickerNavigation } from '#lib/hooks/use-picker-navigation.svelte.ts'; + import { SkillToolsService, type SourcedSkill } from '#lib/services/skill-tools.service.ts'; + import { untrack } from 'svelte'; + + /** + * The skill picker `/skill` opens: the skills of the machine's folders and the + * ones extensions offer, such as an MCP server's, each with where it comes + * from. Picking one attaches it to the message being written. + */ + let { anchor, composer, isOpen, onClose, query }: ComposerPickerProps = $props(); + + let skills = $state.raw([]); + let isLoading = $state(false); + let searchQuery = $state(''); + + let items = $derived.by(() => { + const search = searchQuery.trim().toLowerCase(); + + if (!search) return skills; + + return skills.filter( + ({ entry }) => + entry.name.toLowerCase().includes(search) || + entry.description.toLowerCase().includes(search) || + entry.origin.toLowerCase().includes(search) + ); + }); + + const nav = usePickerNavigation({ + count: () => items.length, + isOpen: () => isOpen, + onClose: () => onClose(), + onSelect: (index) => pick(items[index]) + }); + + // opening the picker is the need for the listings + $effect(() => { + if (!isOpen) return; + + untrack(() => { + nav.reset(0); + void load(); + }); + }); + + // what is typed after `/skill` searches the list, like its own search field does + $effect(() => { + if (isOpen) searchQuery = query; + }); + + $effect(() => { + if (nav.hoveredIndex >= items.length) nav.reset(0); + }); + + async function load() { + isLoading = true; + // in the order of the sources; one that fails to list leaves the others' skills + skills = (await SkillToolsService.listings()).flatMap((listing) => listing.skills); + isLoading = false; + } + + function pick({ entry, source }: SourcedSkill) { + onClose(); + void source.attach(entry, composer); + } + + export function handleKeydown(event: KeyboardEvent): boolean { + return nav.handleKeydown(event); + } + + + + `${source.id}:${entry.id}`} + {items} + scrollTrigger={nav.scrollTrigger} + searchPlaceholder="Search skills..." + selectedIndex={nav.hoveredIndex} + showSearchInput={skills.length >= SKILL_SEARCH_MIN_ITEMS} + > + {#snippet item(skill, index, isSelected)} + pick(skill)} + onhover={() => nav.setHover(index)} + > +
+ + +
+ {skill.entry.name} + + {#if skill.entry.isUnverified} + Cannot be verified + {/if} +
+ + {#if skill.entry.description} +

+ {skill.entry.description} +

+ {/if} +
+
+ {/snippet} + + {#snippet skeleton()} + + {/snippet} +
+
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardSkillDetail.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardSkillDetail.svelte new file mode 100644 index 000000000000..1f4533ddb7b2 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardSkillDetail.svelte @@ -0,0 +1,26 @@ + + +
+ {#if hasChanged} +

This skill changed since you allowed it.

+ {/if} + +

Its instructions go to the model, which can act on them with the tools you allow.

+ + {#if description} +

{description}

+ {/if} + +

{path}

+
diff --git a/ui/apps/chat/src/lib/components/app/chat/index.ts b/ui/apps/chat/src/lib/components/app/chat/index.ts index 2651f72f2adf..6038ee7fb2bb 100644 --- a/ui/apps/chat/src/lib/components/app/chat/index.ts +++ b/ui/apps/chat/src/lib/components/app/chat/index.ts @@ -298,7 +298,7 @@ export { default as ChatFormPickerMention } from './ChatForm/ChatFormPickers/Cha /** * `/`-triggered slash-command picker. Lists the available slash commands - * (`/prompt`, `/cwd`, `/model`) filtered by the typed query; selection + * (`/prompt`, `/skill`, `/cwd`, `/model`) filtered by the typed query; selection * hands the command to the parent for dispatch. */ export { default as ChatFormPickerCommand } from './ChatForm/ChatFormPickers/ChatFormPickerCommand.svelte'; @@ -310,6 +310,12 @@ export { default as ChatFormPickerCommand } from './ChatForm/ChatFormPickers/Cha */ export { default as ChatFormPickerPrompts } from './ChatForm/ChatFormPickers/ChatFormPickerPrompts.svelte'; +/** + * The skill picker `/skill` opens: the skills of the machine's folders and the ones + * extensions offer, such as an MCP server's, each with where it comes from. + */ +export { default as ChatFormPickerSkills } from './ChatForm/ChatFormPickers/ChatFormPickerSkills.svelte'; + /** * Where a prompt comes from, on its row in a list: the origin's icon and name. */ diff --git a/ui/apps/chat/src/lib/constants/skills.constants.ts b/ui/apps/chat/src/lib/constants/skills.constants.ts index 75f3d40b8412..29e488da069c 100644 --- a/ui/apps/chat/src/lib/constants/skills.constants.ts +++ b/ui/apps/chat/src/lib/constants/skills.constants.ts @@ -1,3 +1,5 @@ +import { STORAGE_APP_NAME } from './storage.constants'; + /** The file that names, describes and holds a skill. */ export const SKILL_MANIFEST_NAME = 'SKILL.md'; @@ -23,3 +25,18 @@ export const LOCAL_SKILL_FRONTMATTER_LINES = 40; /** Id of the machine's folders as a source of skills. */ export const LOCAL_SKILLS_SOURCE_ID = 'local'; + +/** What one of the local source's origins is, in the model's listing of skills. */ +export const LOCAL_SKILLS_ORIGIN_KIND = 'folder'; + +/** Where the local skills the user always allows are remembered, in localStorage. */ +export const LOCAL_SKILL_APPROVALS_LOCALSTORAGE_KEY = `${STORAGE_APP_NAME}.localSkillApprovals`; + +/** Id of the chat form's skill picker, which `/skill` opens. */ +export const SKILLS_PICKER_ID = 'skills'; + +/** A skill list this long gets a search field. */ +export const SKILL_SEARCH_MIN_ITEMS = 4; + +/** What the chip of a skill attached to a message reads, before the skill's name. */ +export const SKILL_ATTACHMENT_TITLE_PREFIX = 'Skill: '; diff --git a/ui/apps/chat/src/lib/constants/tool-ui.constants.ts b/ui/apps/chat/src/lib/constants/tool-ui.constants.ts index dce125262e3e..2e7a5b0bba1c 100644 --- a/ui/apps/chat/src/lib/constants/tool-ui.constants.ts +++ b/ui/apps/chat/src/lib/constants/tool-ui.constants.ts @@ -7,6 +7,7 @@ // (see ChatMessageToolCallBlockGetDatetime and // ChatMessageToolCallBlockSearchResults for prior art). +import { SKILL_ICON } from './icons.constants'; import Braces from '@lucide/svelte/icons/braces'; import Clock from '@lucide/svelte/icons/clock'; import Eye from '@lucide/svelte/icons/eye'; @@ -27,6 +28,16 @@ export const TOOL_UI: Readonly> = { label: 'Current time', source: ToolSource.BROWSER }, + [BuiltInTool.BROWSER_LIST_SKILLS]: { + icon: SKILL_ICON, + label: 'List skills', + source: ToolSource.BROWSER + }, + [BuiltInTool.BROWSER_LOAD_SKILL]: { + icon: SKILL_ICON, + label: 'Load skill', + source: ToolSource.BROWSER + }, [BuiltInTool.BROWSER_READ_MEDIA]: { icon: Eye, label: 'Read media', source: ToolSource.BROWSER }, [BuiltInTool.BROWSER_RUN_JAVASCRIPT]: { icon: Braces, diff --git a/ui/apps/chat/src/lib/enums/chat.enums.ts b/ui/apps/chat/src/lib/enums/chat.enums.ts index 2043a5830769..0500b5988f25 100644 --- a/ui/apps/chat/src/lib/enums/chat.enums.ts +++ b/ui/apps/chat/src/lib/enums/chat.enums.ts @@ -86,6 +86,7 @@ export enum ChatFormCommandAction { CWD = 'cwd', MODEL = 'model', PROMPT = 'prompt', + SKILL = 'skill', SYSTEM_MESSAGE = 'system-message' } diff --git a/ui/apps/chat/src/lib/enums/index.ts b/ui/apps/chat/src/lib/enums/index.ts index 83f14498f53e..5284097538af 100644 --- a/ui/apps/chat/src/lib/enums/index.ts +++ b/ui/apps/chat/src/lib/enums/index.ts @@ -125,6 +125,7 @@ export { SearchChatsMessageSelection, SearchChatsOrder, ServerToolType, + SkillToolArgument, ToolSource, ToolPermissionDecision, ToolResponseField diff --git a/ui/apps/chat/src/lib/enums/tools.enums.ts b/ui/apps/chat/src/lib/enums/tools.enums.ts index d46d7af83407..596afd933c7d 100644 --- a/ui/apps/chat/src/lib/enums/tools.enums.ts +++ b/ui/apps/chat/src/lib/enums/tools.enums.ts @@ -50,6 +50,8 @@ export enum GlobSearchType { */ export enum BuiltInTool { BROWSER_GET_DATETIME = 'get_datetime', + BROWSER_LIST_SKILLS = 'list_skills', + BROWSER_LOAD_SKILL = 'load_skill', BROWSER_READ_MEDIA = 'read_media', BROWSER_RUN_JAVASCRIPT = 'run_javascript', BROWSER_SEARCH_CHATS = 'search_chats', @@ -62,6 +64,13 @@ export enum BuiltInTool { SERVER_WRITE_FILE = 'write_file' } +/** The arguments of {@link BuiltInTool.BROWSER_LOAD_SKILL}. */ +export enum SkillToolArgument { + FILE = 'file', + FROM = 'from', + NAME = 'name' +} + /** Wire values of the `search_chats` `message_selection` parameter */ export enum SearchChatsMessageSelection { EARLIEST = 'earliest', diff --git a/ui/apps/chat/src/lib/extensions/index.ts b/ui/apps/chat/src/lib/extensions/index.ts index 3912d7fb827a..736eed68c7d7 100644 --- a/ui/apps/chat/src/lib/extensions/index.ts +++ b/ui/apps/chat/src/lib/extensions/index.ts @@ -24,7 +24,7 @@ export type { MessageRendererProps } from './points/renderers'; export type { SettingsAction, SettingsActionDialog } from './points/settings'; -export type { SkillEntry, SkillSource } from './points/skills'; +export type { SkillEntry, SkillPermission, SkillSource } from './points/skills'; export type { FlowHook, FlowInfo, diff --git a/ui/apps/chat/src/lib/extensions/mcp/components/contributions/ComposerMcpSkills.svelte b/ui/apps/chat/src/lib/extensions/mcp/components/contributions/ComposerMcpSkills.svelte deleted file mode 100644 index b6e48bb2a685..000000000000 --- a/ui/apps/chat/src/lib/extensions/mcp/components/contributions/ComposerMcpSkills.svelte +++ /dev/null @@ -1,159 +0,0 @@ - - - - `${serverId}${ITEM_KEY_SEPARATOR}${skill.uri}`} - items={filteredSkills} - {scrollTrigger} - searchPlaceholder="Search skills..." - {selectedIndex} - showSearchInput={skills.length >= SEARCH_INPUT_MIN_ITEMS} - > - {#snippet item(pickable, index, isSelected)} - pick(pickable)}> - - {#snippet titleExtra()} - {#if pickable.skill.resources === MCP_SKILL_DYNAMIC_RESOURCES} - Cannot be verified - {/if} - {/snippet} - - - {/snippet} - - {#snippet skeleton()} - - {/snippet} - - diff --git a/ui/apps/chat/src/lib/extensions/mcp/components/contributions/McpToolGroupIdentity.svelte b/ui/apps/chat/src/lib/extensions/mcp/components/contributions/McpToolGroupIdentity.svelte index c84c9536b9df..5fa334d721fb 100644 --- a/ui/apps/chat/src/lib/extensions/mcp/components/contributions/McpToolGroupIdentity.svelte +++ b/ui/apps/chat/src/lib/extensions/mcp/components/contributions/McpToolGroupIdentity.svelte @@ -1,8 +1,6 @@ @@ -65,7 +80,16 @@ {onDecision} permission={skillPermission} serverLabel={skillPermission.source} - toolName="load_skill" + toolName={BuiltInTool.BROWSER_LOAD_SKILL} + /> + + + + diff --git a/ui/apps/chat/tests/unit/chat-commands.test.ts b/ui/apps/chat/tests/unit/chat-commands.test.ts index a392d5205a92..5b9ea5d9fe1a 100644 --- a/ui/apps/chat/tests/unit/chat-commands.test.ts +++ b/ui/apps/chat/tests/unit/chat-commands.test.ts @@ -9,6 +9,7 @@ const OPTIONS = { canCompact: () => true, canEditSystemMessage: () => true, hasCwdTools: () => true, + hasSkills: () => true, showModelSelector: true }; @@ -27,14 +28,25 @@ const names = (contributed?: ComposerCommand[]) => describe('getChatCommands', () => { it('lists only the built-in commands without contributions', () => { - expect(names()).toEqual(['prompt', 'cwd', 'model', 'compact', 'system-message']); - expect(names([])).toEqual(['prompt', 'cwd', 'model', 'compact', 'system-message']); + expect(names()).toEqual(['prompt', 'skill', 'cwd', 'model', 'compact', 'system-message']); + expect(names([])).toEqual(['prompt', 'skill', 'cwd', 'model', 'compact', 'system-message']); }); - it('sorts a command with an order below zero right after /prompt, before the other built-in ones', () => { - expect(names([makeCommand({ name: 'skill', order: -1 })])).toEqual([ + it('greys out /skill while no source offers skills', () => { + const skill = (hasSkills: boolean) => + getChatCommands({ ...OPTIONS, hasSkills: () => hasSkills }).find( + (command) => command.name === 'skill' + ); + + expect(skill(true)?.disabled).toBe(false); + expect(skill(false)?.disabled).toBe(true); + }); + + it('sorts a command with an order below zero right after /prompt and /skill, before the other built-in ones', () => { + expect(names([makeCommand({ name: 'early', order: -1 })])).toEqual([ 'prompt', 'skill', + 'early', 'cwd', 'model', 'compact', @@ -45,6 +57,7 @@ describe('getChatCommands', () => { it('sorts a command without an order after the built-in ones', () => { expect(names([makeCommand()])).toEqual([ 'prompt', + 'skill', 'cwd', 'model', 'compact', @@ -63,6 +76,7 @@ describe('getChatCommands', () => { expect(names(contributed)).toEqual([ 'prompt', + 'skill', 'first', 'second', 'cwd', @@ -88,8 +102,8 @@ describe('getChatCommands', () => { it('carries what a contributed command shows and does', () => { const run = vi.fn(); - // right after /prompt - const [, command] = getChatCommands(OPTIONS, [ + // right after /prompt and /skill + const [, , command] = getChatCommands(OPTIONS, [ makeCommand({ keywords: ['more'], order: -1, run }) ]); const composer = {} as ComposerHandle; diff --git a/ui/apps/chat/tests/unit/mcp-skill-source.test.ts b/ui/apps/chat/tests/unit/mcp-skill-source.test.ts index 995b2c26e656..49ec06db1d68 100644 --- a/ui/apps/chat/tests/unit/mcp-skill-source.test.ts +++ b/ui/apps/chat/tests/unit/mcp-skill-source.test.ts @@ -1,6 +1,7 @@ // MCP servers are a source of skills through the skillSources extension point: the // skills they publish are listed with their server, and one's SKILL.md is read -// verified, without loading it for the model. +// verified, without loading it for the model. A chat attaches one, and the core's +// skill tools ask for one and load it, through the same source. import { beforeEach, describe, expect, it, vi } from 'vitest'; @@ -8,14 +9,20 @@ vi.mock('#lib/extensions/mcp/stores/index.svelte.ts', () => ({ mcpStore: { ensureInitialized: vi.fn(), getServerDisplayName: vi.fn(), - skills: { list: vi.fn(), read: vi.fn() } + getServerFavicon: vi.fn(), + skills: { allow: vi.fn(), list: vi.fn(), load: vi.fn(), permissionFor: vi.fn(), read: vi.fn() } } })); vi.mock('#lib/extensions/mcp/tools.ts', () => ({ skillServersInUse: vi.fn() })); vi.mock('#lib/extensions/mcp/components/McpLogo.svelte', () => ({ default: () => {} })); +vi.mock('#lib/extensions/mcp/components/skills/McpSkillPermissionDetail.svelte', () => ({ + default: () => {} +})); +vi.mock('#lib/extensions/mcp/composer-skills.ts', () => ({ attachSkill: vi.fn() })); import type { Skill } from '@modelcontextprotocol/client/ext/skills'; import type { ExtensionContext, SkillSource } from '#lib/extensions/index.ts'; +import { attachSkill } from '#lib/extensions/mcp/composer-skills.ts'; import { contributeSkillSource } from '#lib/extensions/mcp/skills/source.ts'; import { mcpStore } from '#lib/extensions/mcp/stores/index.svelte.ts'; import { skillServersInUse } from '#lib/extensions/mcp/tools.ts'; @@ -26,6 +33,8 @@ function skill(name: string, uri: string): Skill { const HF_MEM = skill('hf-mem', 'skill://hf-mem'); const HF_CLI = skill('hf-cli', 'skill://hf-cli'); +// its files are made on demand: listed, but not offered to the model +const DAILY = { ...skill('daily', 'skill://daily'), resources: 'dynamic' } as Skill; // the same URI on another server is another skill const OTHER = skill('hf-mem', 'skill://hf-mem'); @@ -59,23 +68,90 @@ describe('MCP as a source of skills', () => { ); }); + it('is on offer while a server in use publishes skills', () => { + const source = activate(); + + expect(source.isAvailable()).toBe(true); + + vi.mocked(skillServersInUse).mockReturnValue([]); + + expect(source.isAvailable()).toBe(false); + }); + + it('marks a skill whose files are made on demand as one that cannot be verified', async () => { + vi.mocked(mcpStore.skills.list).mockResolvedValue([DAILY]); + + expect((await activate().list()).map((entry) => entry.isUnverified)).toEqual([true, true]); + }); + + it('attaches a picked skill from its own server', async () => { + const source = activate(); + const entries = await source.list(); + + await source.attach(entries[2], {} as Parameters[1]); + + expect(attachSkill).toHaveBeenCalledWith('docs', OTHER); + }); + + it('asks for a skill as its server knows it now, and keeps the answer there', async () => { + vi.mocked(mcpStore.skills.permissionFor).mockResolvedValue({ + hasChanged: true, + isAllowed: false, + skill: HF_MEM + }); + + const source = activate(); + const [hfMem] = await source.list(); + const permission = await source.permission(hfMem); + + expect(mcpStore.skills.permissionFor).toHaveBeenCalledWith('hf', 'skill://hf-mem'); + expect(permission).toMatchObject({ hasChanged: true, isAllowed: false }); + expect(permission.detail?.props).toEqual({ hasChanged: true, serverId: 'hf', skill: HF_MEM }); + + permission.allow(true); + + expect(mcpStore.skills.allow).toHaveBeenCalledWith('hf', HF_MEM, true); + }); + + it('loads a file of a skill from its own server, under a line that names the server', async () => { + vi.mocked(mcpStore.skills.load).mockResolvedValue({ + file: { body: 'Measure first.', text: '---\nname: hf-mem\n---\nMeasure first.' }, + skill: HF_MEM + } as Awaited>); + + const source = activate(); + const entries = await source.list(); + const text = await source.load(entries[2], 'references/guide.md'); + + expect(mcpStore.skills.load).toHaveBeenCalledWith( + 'docs', + 'skill://hf-mem', + 'references/guide.md' + ); + expect(text).toContain('Skill "hf-mem" from the MCP server "Docs"'); + expect(text).toContain('Measure first.'); + }); + it('lists the skills of the servers in use, in their order, each under its server', async () => { expect(await activate().list()).toEqual([ { description: 'What hf-mem is for', id: 'hf skill://hf-mem', + isUnverified: false, name: 'hf-mem', origin: 'Hugging Face' }, { description: 'What hf-cli is for', id: 'hf skill://hf-cli', + isUnverified: false, name: 'hf-cli', origin: 'Hugging Face' }, { description: 'What hf-mem is for', id: 'docs skill://hf-mem', + isUnverified: false, name: 'hf-mem', origin: 'Docs' } diff --git a/ui/apps/chat/tests/unit/mcp-skill-tools.test.ts b/ui/apps/chat/tests/unit/mcp-skill-tools.test.ts deleted file mode 100644 index 51b627475fd1..000000000000 --- a/ui/apps/chat/tests/unit/mcp-skill-tools.test.ts +++ /dev/null @@ -1,309 +0,0 @@ -// The model reaches skills through two tools of the MCP tool provider: one -// lists the skills of the servers in use, under each server's name, and one -// loads a skill from the server the model names. A load asks the user for the -// skill, through the permission every tool call goes through. - -import { beforeEach, describe, expect, it, vi } from 'vitest'; - -vi.mock('#lib/services/database.service.ts', () => ({ - DatabaseService: {} -})); -// the component draws on the app's component barrel, which needs a browser -vi.mock('#lib/extensions/mcp/components/contributions/McpToolGroupIdentity.svelte', () => ({ - default: () => {} -})); -vi.mock('#lib/extensions/mcp/components/skills/McpSkillPermissionDetail.svelte', () => ({ - default: () => {} -})); - -import type { Skill, SkillFile } from '@modelcontextprotocol/client/ext/skills'; -import { SETTINGS_KEYS } from '#lib/constants/index.ts'; -import { ToolPermissionDecision } from '#lib/enums/index.ts'; -import type { ExtensionContext, ToolProvider } from '#lib/extensions/index.ts'; -import { extensions } from '#lib/extensions/index.ts'; -import { MCP_SKILLS_TOOL_GROUP_ID, McpSkillTool } from '#lib/extensions/mcp/skills/constants.ts'; -import { mcpStore } from '#lib/extensions/mcp/stores/index.svelte.ts'; -import { contributeTools } from '#lib/extensions/mcp/tools.ts'; -import { AgenticGates } from '#lib/stores/agentic/gates.svelte.ts'; -import { agenticMode } from '#lib/stores/agentic-mode.svelte.ts'; -import { permissionsStore } from '#lib/stores/permissions.svelte.ts'; -import { settingsStore } from '#lib/stores/settings/index.svelte.ts'; -import type { MCPServerSettingsEntry } from '#lib/types/index.ts'; - -const SERVERS: MCPServerSettingsEntry[] = [ - { enabled: true, id: 'srv-billing', name: 'Billing', url: 'https://billing.example.com/mcp' }, - { enabled: true, id: 'srv-support', name: 'Support', url: 'https://support.example.com/mcp' }, - { enabled: true, id: 'srv-plain', name: 'Plain', url: 'https://plain.example.com/mcp' } -]; -const SKILL_URI = 'skill://refunds/SKILL.md'; - -function skill(description: string, resources: Skill['resources']): Skill { - return { frontmatter: { description, name: 'refunds' }, resources, uri: SKILL_URI }; -} - -const FILES = [ - { digest: `sha256:${'a'.repeat(64)}`, size: 120, uri: SKILL_URI }, - { digest: `sha256:${'b'.repeat(64)}`, size: 40, uri: 'skill://refunds/references/guide.md' } -]; -const LISTINGS: Record = { - 'srv-billing': [skill('Refunds, by\n billing', FILES)], - 'srv-support': [ - skill('Refunds, by support', FILES), - { ...skill('Made on demand', 'dynamic'), uri: 'skill://daily/SKILL.md' } - ] -}; - -function provider(): ToolProvider { - let made: ToolProvider | undefined; - - const ctx: ExtensionContext = { - contribute: (point, contribution) => { - if (point === 'tools') made = contribution as ToolProvider; - }, - onDeactivate: () => {} - }; - - contributeTools(ctx); - - return made!; -} - -function call(name: McpSkillTool, args: Record = {}) { - return { arguments: JSON.stringify(args), id: 'call-1', name }; -} - -beforeEach(() => { - // as against a llama-server started with --agent, with Enable MCP on - agenticMode.serverHasTools = true; - settingsStore.updateConfig(SETTINGS_KEYS.ENABLE_MCP, true); - vi.restoreAllMocks(); - vi.spyOn(mcpStore, 'getServers').mockReturnValue(SERVERS); - vi.spyOn(mcpStore, 'getConnections').mockReturnValue(new Map()); - vi.spyOn(mcpStore, 'publishesSkills').mockImplementation((serverId) => serverId in LISTINGS); - vi.spyOn(mcpStore.skills, 'list').mockImplementation(async (serverId) => LISTINGS[serverId]); -}); - -describe('skill tools', () => { - it('are not on offer while no server in use publishes skills', () => { - vi.spyOn(mcpStore, 'publishesSkills').mockReturnValue(false); - - expect(provider().entries()).toEqual([]); - }); - - it('are one group of two tools, and only the load asks for what it loads', () => { - const [list, load] = provider().entries(); - - expect(list).toMatchObject({ groupId: MCP_SKILLS_TOOL_GROUP_ID }); - expect(list.definition.function.name).toBe(McpSkillTool.LIST); - expect(list.callPermission).toBeUndefined(); - expect(load).toMatchObject({ groupId: MCP_SKILLS_TOOL_GROUP_ID }); - expect(load.definition.function.name).toBe(McpSkillTool.LOAD); - expect(load.callPermission).toBeTypeOf('function'); - }); - - describe('permission of a load', () => { - const [refunds] = LISTINGS['srv-support']; - - function gates() { - const made = provider(); - - vi.spyOn(extensions, 'contributions').mockImplementation(((point: string) => - point === 'tools' ? [made] : []) as typeof extensions.contributions); - - return new AgenticGates(); - } - - function permissionFor(isAllowed: boolean, hasChanged = false) { - return vi - .spyOn(mcpStore.skills, 'permissionFor') - .mockResolvedValue({ hasChanged, isAllowed, skill: refunds }); - } - - it('asks for the skill and its server, not for the tool', async () => { - const lookup = permissionFor(false, true); - const asked = gates(); - const decision = asked.requestPermission( - 'conv-1', - call(McpSkillTool.LOAD, { server: 'Support', uri: SKILL_URI }), - 'MCP Skills' - ); - - await vi.waitFor(() => expect(asked.getPendingPermissionRequest('conv-1')).not.toBeNull()); - - const pending = asked.getPendingPermissionRequest('conv-1')!; - - expect(lookup).toHaveBeenCalledWith('srv-support', SKILL_URI); - expect(pending).toMatchObject({ - permission: { alwaysLabel: 'Always allow this skill', subject: 'the skill refunds' }, - serverLabel: 'Support', - toolName: McpSkillTool.LOAD - }); - expect(pending.permission?.detail?.props).toEqual({ - hasChanged: true, - serverId: 'srv-support', - skill: refunds - }); - - asked.resolvePermission('conv-1', ToolPermissionDecision.DENY); - await expect(decision).resolves.toBe(ToolPermissionDecision.DENY); - }); - - it.each([ - [ToolPermissionDecision.ONCE, false], - [ToolPermissionDecision.ALWAYS, true] - ])('keeps the answer %s with the skills, never with the tool', async (answer, always) => { - const allow = vi.spyOn(mcpStore.skills, 'allow').mockImplementation(() => {}); - const allowTool = vi.spyOn(permissionsStore, 'allowTool'); - - permissionFor(false); - - const asked = gates(); - const decision = asked.requestPermission( - 'conv-1', - call(McpSkillTool.LOAD, { server: 'Support', uri: SKILL_URI }), - 'MCP Skills' - ); - - await vi.waitFor(() => expect(asked.getPendingPermissionRequest('conv-1')).not.toBeNull()); - asked.resolvePermission('conv-1', answer); - - await expect(decision).resolves.toBe(answer); - expect(allow).toHaveBeenCalledWith('srv-support', refunds, always); - expect(allowTool).not.toHaveBeenCalled(); - }); - - it('does not ask for a skill the user allowed', async () => { - permissionFor(true); - - await expect( - gates().requestPermission( - 'conv-1', - call(McpSkillTool.LOAD, { server: 'Support', uri: SKILL_URI }), - 'MCP Skills' - ) - ).resolves.toBe(ToolPermissionDecision.ONCE); - }); - - it('asks nothing for a call that names no skill: the call fails saying why', async () => { - const lookup = vi.spyOn(mcpStore.skills, 'permissionFor'); - const asked = gates(); - - await expect( - asked.requestPermission('conv-1', call(McpSkillTool.LOAD, { server: 'Plain' }), '') - ).resolves.toBe(ToolPermissionDecision.ONCE); - expect(lookup).not.toHaveBeenCalled(); - await expect( - provider().execute(call(McpSkillTool.LOAD, { server: 'Plain' })) - ).rejects.toThrow('"uri" is missing'); - }); - - it('refuses a load the user did not allow, whoever let the call through', async () => { - await expect( - provider().execute(call(McpSkillTool.LOAD, { server: 'Support', uri: SKILL_URI })) - ).rejects.toThrow('has not allowed the skill "refunds"'); - }); - }); - - it('list every server skills under its name, a same-named skill once per server', async () => { - const { content } = await provider().execute(call(McpSkillTool.LIST)); - - expect(content).toContain( - ['Server: Billing', `- refunds (${SKILL_URI}): Refunds, by billing`].join('\n') - ); - expect(content).toContain( - ['Server: Support', `- refunds (${SKILL_URI}): Refunds, by support`].join('\n') - ); - // a server without skills is not asked, a skill that cannot be verified is not offered - expect(content).not.toContain('Plain'); - expect(content).not.toContain('Made on demand'); - }); - - it('leave a call to the server that has a tool of the same name', async () => { - const executeTool = vi - .spyOn(mcpStore, 'executeTool') - .mockResolvedValue({ content: 'from the server', isError: false }); - const load = vi.spyOn(mcpStore.skills, 'load'); - - vi.spyOn(mcpStore, 'hasTool').mockImplementation((name) => name === McpSkillTool.LOAD); - - await expect( - provider().execute(call(McpSkillTool.LOAD, { server: 'Support', uri: SKILL_URI })) - ).resolves.toEqual({ content: 'from the server', isError: false }); - expect(executeTool).toHaveBeenCalledTimes(1); - expect(load).not.toHaveBeenCalled(); - }); - - it('say which server could not list, and still list the others', async () => { - vi.spyOn(mcpStore.skills, 'list').mockImplementation(async (serverId) => { - if (serverId === 'srv-billing') throw new Error('server is down'); - - return LISTINGS[serverId]; - }); - - const { content } = await provider().execute(call(McpSkillTool.LIST)); - - expect(content).toContain('Server: Billing\n(its skills could not be listed: server is down)'); - expect(content).toContain('Refunds, by support'); - }); - - it('load a skill from the server the model names, under a line that names it', async () => { - const [loaded] = LISTINGS['srv-support']; - const load = vi.spyOn(mcpStore.skills, 'load').mockResolvedValue({ - file: { - body: '# Refunds\n\nAsk for the order number.\n', - bytes: new Uint8Array(), - text: '---\nname: refunds\nallowed-tools: Bash\n---\n# Refunds\n', - uri: SKILL_URI, - verified: true - } as SkillFile, - skill: loaded - }); - const { content } = await provider().execute( - call(McpSkillTool.LOAD, { server: 'Support', uri: SKILL_URI }) - ); - - expect(load).toHaveBeenCalledWith('srv-support', SKILL_URI, undefined); - expect(content).toMatch(/^Skill "refunds" from the MCP server "Support"/); - expect(content).toContain('written by that server, not by the user'); - expect(content).toContain('Ask for the order number.'); - // the frontmatter stays out: nothing in it changes what the model may do - expect(content).not.toContain('allowed-tools'); - expect(content).toContain('- references/guide.md'); - }); - - it('load one of the other files of a skill', async () => { - const load = vi.spyOn(mcpStore.skills, 'load').mockResolvedValue({ - file: { - bytes: new Uint8Array(), - text: 'The guide.', - uri: 'skill://refunds/references/guide.md', - verified: true - } as SkillFile, - skill: LISTINGS['srv-billing'][0] - }); - const { content } = await provider().execute( - call(McpSkillTool.LOAD, { - file: 'references/guide.md', - server: 'srv-billing', - uri: SKILL_URI - }) - ); - - expect(load).toHaveBeenCalledWith('srv-billing', SKILL_URI, 'references/guide.md'); - expect(content).toContain('from the MCP server "Billing"'); - expect(content).toContain('The guide.'); - expect(content).not.toContain('Other files'); - }); - - it('refuse a server that publishes no skills here, and never pick another one', async () => { - const load = vi.spyOn(mcpStore.skills, 'load'); - - await expect( - provider().execute(call(McpSkillTool.LOAD, { server: 'Plain', uri: SKILL_URI })) - ).rejects.toThrow('Servers with skills: "Billing", "Support".'); - await expect( - provider().execute(call(McpSkillTool.LOAD, { server: 'Billing' })) - ).rejects.toThrow('"uri" is missing'); - expect(load).not.toHaveBeenCalled(); - }); -}); diff --git a/ui/apps/chat/tests/unit/skill-tools.test.ts b/ui/apps/chat/tests/unit/skill-tools.test.ts new file mode 100644 index 000000000000..fe9f67e8c0bf --- /dev/null +++ b/ui/apps/chat/tests/unit/skill-tools.test.ts @@ -0,0 +1,304 @@ +// The model reaches skills through two of the app's own tools, over every source +// of skills on offer: one lists them under where each is from (a folder of the +// machine, an MCP server), one loads the skill a call names. A load asks the +// user for the skill, through the permission card every tool call goes through, +// and the source keeps the answer. + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('#lib/services/database.service.ts', () => ({ + DatabaseService: {} +})); + +import { ToolPermissionDecision } from '#lib/enums/index.ts'; +import { BuiltInTool } from '#lib/enums/index.ts'; +import type { SkillEntry, SkillPermission, SkillSource } from '#lib/extensions/index.ts'; +import { SkillToolsService } from '#lib/services/skill-tools.service.ts'; +import { AgenticGates } from '#lib/stores/agentic/gates.svelte.ts'; +import { agenticMode } from '#lib/stores/agentic-mode.svelte.ts'; +import { permissionsStore } from '#lib/stores/permissions.svelte.ts'; +import { skillsStore } from '#lib/stores/skills.svelte.ts'; +import { toolsStore } from '#lib/stores/tools.svelte.ts'; + +function entry(name: string, origin: string, extra: Partial = {}): SkillEntry { + return { description: `What ${name}\n is for`, id: `${origin}/${name}`, name, origin, ...extra }; +} + +const ANIMATE = entry('animate', '~/.agents/skills'); +const SWIFT = entry('write-swift', '~/.claude/skills'); +const REFUNDS = entry('refunds', 'Support'); +const DAILY = entry('daily', 'Support', { isUnverified: true }); +// the same name on a server as in a folder +const ANIMATE_ON_SERVER = entry('animate', 'Design'); + +function source(id: string, originKind: string, entries: SkillEntry[]) { + const permission: SkillPermission = { + allow: vi.fn(), + hasChanged: false, + isAllowed: false + }; + + return { + attach: vi.fn(), + icon: (() => {}) as unknown as SkillSource['icon'], + id, + isAvailable: vi.fn(() => true), + list: vi.fn(async () => entries), + load: vi.fn( + async (picked: SkillEntry, file?: string) => `${picked.name}:${file ?? 'SKILL.md'}` + ), + originKind, + permission: vi.fn(async () => permission), + read: vi.fn() + } satisfies SkillSource; +} + +let local: ReturnType; +let mcp: ReturnType; + +function call(name: BuiltInTool, args: Record = {}) { + return { arguments: JSON.stringify(args), id: 'call-1', name }; +} + +beforeEach(() => { + local = source('local', 'folder', [ANIMATE, SWIFT]); + mcp = source('mcp', 'MCP server', [REFUNDS, DAILY, ANIMATE_ON_SERVER]); + vi.spyOn(skillsStore, 'sources', 'get').mockReturnValue([local, mcp]); +}); + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe('list_skills', () => { + it('lists the skills of every source under where each is from, the unverifiable left out', async () => { + const { content, isError } = await SkillToolsService.execute( + call(BuiltInTool.BROWSER_LIST_SKILLS) + ); + + expect(isError).toBe(false); + expect(content).toContain( + [ + 'From the folder "~/.agents/skills":', + '- animate: What animate is for', + '', + 'From the folder "~/.claude/skills":', + '- write-swift: What write-swift is for', + '', + 'From the MCP server "Support":', + '- refunds: What refunds is for', + '', + 'From the MCP server "Design":', + '- animate: What animate is for' + ].join('\n') + ); + expect(content).not.toContain('daily'); + }); + + it('leaves out a source that offers nothing now, such as the folders with tools off', async () => { + local.isAvailable.mockReturnValue(false); + + const { content } = await SkillToolsService.execute(call(BuiltInTool.BROWSER_LIST_SKILLS)); + + expect(local.list).not.toHaveBeenCalled(); + expect(content).not.toContain('From the folder'); + expect(content).toContain('From the MCP server "Support"'); + }); + + it('keeps the other sources when one fails to list, and says so', async () => { + mcp.list.mockRejectedValue(new Error('server went away')); + + const { content } = await SkillToolsService.execute(call(BuiltInTool.BROWSER_LIST_SKILLS)); + + expect(content).toContain('- animate: What animate is for'); + expect(content).toContain('(the MCP server skills could not be listed: server went away)'); + }); + + it('says there are none when no source has any', async () => { + local.list.mockResolvedValue([]); + mcp.list.mockResolvedValue([]); + + const { content } = await SkillToolsService.execute(call(BuiltInTool.BROWSER_LIST_SKILLS)); + + expect(content).toMatch(/\(no skills\)$/); + }); +}); + +describe('load_skill', () => { + it('loads the skill a call names, by its name and where it is from', async () => { + const { content } = await SkillToolsService.execute( + call(BuiltInTool.BROWSER_LOAD_SKILL, { from: 'Design', name: 'animate' }) + ); + + expect(content).toBe('animate:SKILL.md'); + expect(mcp.load).toHaveBeenCalledWith(ANIMATE_ON_SERVER, undefined); + expect(local.load).not.toHaveBeenCalled(); + }); + + it('passes the file a call names to the source', async () => { + await SkillToolsService.execute( + call(BuiltInTool.BROWSER_LOAD_SKILL, { + file: 'references/guide.md', + from: 'Support', + name: 'refunds' + }) + ); + + expect(mcp.load).toHaveBeenCalledWith(REFUNDS, 'references/guide.md'); + }); + + it('takes a name only one place has, whatever it is said to be from, and never guesses between two', async () => { + await SkillToolsService.execute(call(BuiltInTool.BROWSER_LOAD_SKILL, { name: 'write-swift' })); + // as a small model writes it: the name where the place goes + await SkillToolsService.execute( + call(BuiltInTool.BROWSER_LOAD_SKILL, { from: 'refunds', name: 'refunds' }) + ); + + expect(local.load).toHaveBeenCalledWith(SWIFT, undefined); + expect(mcp.load).toHaveBeenCalledWith(REFUNDS, undefined); + await expect( + SkillToolsService.execute(call(BuiltInTool.BROWSER_LOAD_SKILL, { name: 'animate' })) + ).rejects.toThrow( + 'More than one skill is named "animate": give "from", one of "~/.agents/skills", "Design".' + ); + await expect( + SkillToolsService.execute( + call(BuiltInTool.BROWSER_LOAD_SKILL, { from: 'Billing', name: 'animate' }) + ) + ).rejects.toThrow('More than one skill is named "animate"'); + await expect( + SkillToolsService.execute(call(BuiltInTool.BROWSER_LOAD_SKILL, { from: 'Support' })) + ).rejects.toThrow('"name" is missing'); + }); + + it('does not load a skill whose files cannot be verified', async () => { + await expect( + SkillToolsService.execute( + call(BuiltInTool.BROWSER_LOAD_SKILL, { from: 'Support', name: 'daily' }) + ) + ).rejects.toThrow('No skill "daily"'); + expect(mcp.load).not.toHaveBeenCalled(); + }); + + it('passes on the refusal of a source the user did not allow the skill in', async () => { + local.load.mockRejectedValue(new Error('The user has not allowed the skill "animate".')); + + await expect( + SkillToolsService.execute( + call(BuiltInTool.BROWSER_LOAD_SKILL, { from: '~/.agents/skills', name: 'animate' }) + ) + ).rejects.toThrow('has not allowed'); + }); +}); + +describe('the tools in the tool list', () => { + beforeEach(() => { + // as against a llama-server started with --agent + agenticMode.serverHasTools = true; + }); + + const names = () => toolsStore.allTools.map((tool) => tool.definition.function.name); + + it('are on offer while a source offers skills, as the app own browser tools', () => { + local.isAvailable.mockReturnValue(false); + + expect(names()).toEqual( + expect.arrayContaining([BuiltInTool.BROWSER_LIST_SKILLS, BuiltInTool.BROWSER_LOAD_SKILL]) + ); + + const load = toolsStore.allTools.find( + (tool) => tool.definition.function.name === BuiltInTool.BROWSER_LOAD_SKILL + ); + const list = toolsStore.allTools.find( + (tool) => tool.definition.function.name === BuiltInTool.BROWSER_LIST_SKILLS + ); + + expect(load?.callPermission).toBeTypeOf('function'); + expect(list?.callPermission).toBeUndefined(); + }); + + it('are not on offer while no source offers skills, e.g. tools off and no server with skills', () => { + local.isAvailable.mockReturnValue(false); + mcp.isAvailable.mockReturnValue(false); + + expect(names()).not.toContain(BuiltInTool.BROWSER_LIST_SKILLS); + expect(names()).not.toContain(BuiltInTool.BROWSER_LOAD_SKILL); + }); +}); + +describe('permission of a load', () => { + const LOAD_ANIMATE = call(BuiltInTool.BROWSER_LOAD_SKILL, { + from: '~/.agents/skills', + name: 'animate' + }); + + beforeEach(() => { + agenticMode.serverHasTools = true; + }); + + it('asks for the skill and where it is from, not for the tool', async () => { + local.permission.mockResolvedValue({ + allow: vi.fn(), + detail: { component: (() => {}) as never, props: { path: '~/.agents/skills/animate' } }, + hasChanged: true, + isAllowed: false + }); + + const gates = new AgenticGates(); + const decision = gates.requestPermission('conv-1', LOAD_ANIMATE, 'Browser Tools'); + + await vi.waitFor(() => expect(gates.getPendingPermissionRequest('conv-1')).not.toBeNull()); + + const pending = gates.getPendingPermissionRequest('conv-1')!; + + expect(local.permission).toHaveBeenCalledWith(ANIMATE); + expect(pending).toMatchObject({ + permission: { alwaysLabel: 'Always allow this skill', subject: 'the skill animate' }, + serverLabel: '~/.agents/skills', + toolName: BuiltInTool.BROWSER_LOAD_SKILL + }); + expect(pending.permission?.detail?.props).toEqual({ path: '~/.agents/skills/animate' }); + + gates.resolvePermission('conv-1', ToolPermissionDecision.DENY); + await expect(decision).resolves.toBe(ToolPermissionDecision.DENY); + }); + + it.each([ + [ToolPermissionDecision.ONCE, false], + [ToolPermissionDecision.ALWAYS, true] + ])('keeps the answer %s with the source, never with the tool', async (answer, always) => { + const allow = vi.fn(); + const allowTool = vi.spyOn(permissionsStore, 'allowTool'); + + local.permission.mockResolvedValue({ allow, hasChanged: false, isAllowed: false }); + + const gates = new AgenticGates(); + const decision = gates.requestPermission('conv-1', LOAD_ANIMATE, ''); + + await vi.waitFor(() => expect(gates.getPendingPermissionRequest('conv-1')).not.toBeNull()); + gates.resolvePermission('conv-1', answer); + + await expect(decision).resolves.toBe(answer); + expect(allow).toHaveBeenCalledWith(always); + expect(allowTool).not.toHaveBeenCalled(); + }); + + it('does not ask for a skill the user allowed', async () => { + local.permission.mockResolvedValue({ allow: vi.fn(), hasChanged: false, isAllowed: true }); + + await expect(new AgenticGates().requestPermission('conv-1', LOAD_ANIMATE, '')).resolves.toBe( + ToolPermissionDecision.ONCE + ); + }); + + it('asks nothing for a call that names no skill: the call fails saying why', async () => { + const unknown = call(BuiltInTool.BROWSER_LOAD_SKILL, { name: 'unknown' }); + + await expect(new AgenticGates().requestPermission('conv-1', unknown, '')).resolves.toBe( + ToolPermissionDecision.ONCE + ); + expect(local.permission).not.toHaveBeenCalled(); + expect(mcp.permission).not.toHaveBeenCalled(); + await expect(SkillToolsService.execute(unknown)).rejects.toThrow('No skill "unknown"'); + }); +}); diff --git a/ui/apps/chat/tests/unit/skills-store.test.ts b/ui/apps/chat/tests/unit/skills-store.test.ts index e7795f4ca8b9..b77553862bec 100644 --- a/ui/apps/chat/tests/unit/skills-store.test.ts +++ b/ui/apps/chat/tests/unit/skills-store.test.ts @@ -1,12 +1,21 @@ // The machine's skills folders are one source of skills, listed before the ones // extensions add: read only when llama-server offers its file tools, one skill per -// name, the first folder's when two folders hold the same name. +// name, the first folder's when two folders hold the same name. In a chat a skill +// is attached, or loaded for the model only with the text the user allowed. import { beforeEach, describe, expect, it, vi } from 'vitest'; -vi.mock('#lib/services/local-skills.service.ts', () => ({ - LocalSkillsService: { list: vi.fn(), read: vi.fn() } -})); +vi.mock('#lib/services/local-skills.service.ts', async (importOriginal) => { + const actual = await importOriginal(); + + return { + LocalSkillsService: { format: actual.LocalSkillsService.format, list: vi.fn(), read: vi.fn() } + }; +}); +vi.mock( + '#lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardSkillDetail.svelte', + () => ({ default: () => {} }) +); const offeredTools = vi.hoisted(() => ({ names: [] as string[] })); @@ -18,10 +27,16 @@ vi.mock('#lib/stores/tools.svelte.ts', () => ({ } })); -import { LOCAL_SKILL_FOLDERS, LOCAL_SKILLS_SOURCE_ID } from '#lib/constants/index.ts'; +import { + LOCAL_SKILL_APPROVALS_LOCALSTORAGE_KEY, + LOCAL_SKILL_FOLDERS, + LOCAL_SKILLS_SOURCE_ID +} from '#lib/constants/index.ts'; import { BuiltInTool } from '#lib/enums/index.ts'; +import type { ComposerHandle } from '#lib/extensions/index.ts'; import { type LocalSkill, LocalSkillsService } from '#lib/services/local-skills.service.ts'; import { skillsStore } from '#lib/stores/skills.svelte.ts'; +import type { ChatUploadedFile } from '#lib/types/index.ts'; const list = vi.mocked(LocalSkillsService.list); const read = vi.mocked(LocalSkillsService.read); @@ -97,3 +112,146 @@ describe('skillsStore', () => { expect(read).not.toHaveBeenCalled(); }); }); + +describe('a skill of a folder in a chat', () => { + const SKILL_TEXT = '---\nname: animate\ndescription: Motion\n---\n\n# Animate\nEase out.'; + + let stored: Map; + + /** A fresh store: what was allowed is kept per page, so each case starts with none. */ + async function freshLocal() { + vi.resetModules(); + + const { skillsStore: fresh } = await import('#lib/stores/skills.svelte.ts'); + const [source] = fresh.sources; + + return { entries: await source.list(), fresh, source }; + } + + function composer() { + let files: ChatUploadedFile[] = []; + + const handle: ComposerHandle = { + addUploadedFile: (file) => (files = [...files, file]), + closePicker: () => {}, + focusInput: () => {}, + openPicker: () => {}, + updateUploadedFile: (id, update) => + (files = files.map((file) => (file.id === id ? update(file) : file))) + }; + + return { files: () => files, handle }; + } + + beforeEach(() => { + vi.clearAllMocks(); + stored = new Map(); + vi.stubGlobal('localStorage', { + getItem: (key: string) => stored.get(key) ?? null, + setItem: (key: string, value: string) => stored.set(key, value) + }); + offeredTools.names = [BuiltInTool.SERVER_FILE_GLOB_SEARCH, BuiltInTool.SERVER_READ_FILE]; + list.mockImplementation(async (folder) => + folder === AGENTS ? [skill('animate', AGENTS)] : [] + ); + read.mockResolvedValue(SKILL_TEXT); + }); + + it('is on offer only while llama-server offers its file tools', async () => { + const { source } = await freshLocal(); + + expect(source.isAvailable()).toBe(true); + + offeredTools.names = []; + + expect(source.isAvailable()).toBe(false); + }); + + it('asks before it is loaded, and loads under a line that names its folder once allowed', async () => { + const { entries, source } = await freshLocal(); + const permission = await source.permission(entries[0]); + + expect(permission).toMatchObject({ hasChanged: false, isAllowed: false }); + expect(permission.detail?.props).toEqual({ + description: 'animate of ~/.agents/skills', + hasChanged: false, + path: `${AGENTS}/animate/SKILL.md` + }); + await expect(source.load(entries[0])).rejects.toThrow( + 'The user has not allowed the skill "animate".' + ); + + permission.allow(false); + + const loaded = await source.load(entries[0]); + + expect(loaded).toBe( + `Skill "animate" from the folder "${AGENTS}" (${AGENTS}/animate/SKILL.md). The text below was written there, not by the user.\n\n# Animate\nEase out.` + ); + expect((await source.permission(entries[0])).isAllowed).toBe(true); + // allowed for now is not kept + expect(stored.has(LOCAL_SKILL_APPROVALS_LOCALSTORAGE_KEY)).toBe(false); + }); + + it('keeps an approval for good, bound to the text: a changed skill is asked for again', async () => { + const { entries, source } = await freshLocal(); + + (await source.permission(entries[0])).allow(true); + + expect(JSON.parse(stored.get(LOCAL_SKILL_APPROVALS_LOCALSTORAGE_KEY)!)).toEqual({ + [`${AGENTS}/animate/SKILL.md`]: expect.stringMatching(/^[0-9a-f]{64}$/) + }); + + // a new page reads it back + const reloaded = await freshLocal(); + + expect((await reloaded.source.permission(reloaded.entries[0])).isAllowed).toBe(true); + + read.mockResolvedValue(`${SKILL_TEXT}\nAnd also run rm -rf.`); + + expect(await reloaded.source.permission(reloaded.entries[0])).toMatchObject({ + hasChanged: true, + isAllowed: false + }); + await expect(reloaded.source.load(reloaded.entries[0])).rejects.toThrow('has not allowed'); + }); + + it('loads only its SKILL.md: an approval covers nothing else', async () => { + const { entries, source } = await freshLocal(); + + (await source.permission(entries[0])).allow(false); + + await expect(source.load(entries[0], 'references/guide.md')).rejects.toThrow( + 'Only the SKILL.md of a skill from a folder can be loaded' + ); + await expect(source.load(entries[0], 'SKILL.md')).resolves.toContain('# Animate'); + }); + + it('is attached as a chip that holds it as the model gets it, and picking it allows it', async () => { + const { entries, source } = await freshLocal(); + const form = composer(); + + await source.attach(entries[0], form.handle); + + expect(form.files()).toEqual([ + expect.objectContaining({ + isLoading: false, + name: 'Skill: animate', + textContent: expect.stringContaining('# Animate\nEase out.') + }) + ]); + expect((await source.permission(entries[0])).isAllowed).toBe(true); + }); + + it('keeps the chip of a skill that cannot be read, with the error on it', async () => { + const { entries, source } = await freshLocal(); + const form = composer(); + + read.mockRejectedValue(new Error('read_file failed')); + await source.attach(entries[0], form.handle); + + expect(form.files()).toEqual([ + expect.objectContaining({ isLoading: false, loadError: 'read_file failed' }) + ]); + }); +});