Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(skill): install the Market skills an agent references when it is added (#21059)

Mochae7ce0bf50047
diff --git a/apps/server/src/routers/lambda/agentSkills.ensure.test.ts b/apps/server/src/routers/lambda/agentSkills.ensure.test.ts
new file mode 100644
index 00000000000..3ee0fb61c4c
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentSkills.ensure.test.ts
@@ -0,0 +1,158 @@
+// @vitest-environment node
+import { MarketAPIError } from '@lobehub/market-sdk';
+import { TRPCError } from '@trpc/server';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { SkillImportError } from '@/server/services/skill/errors';
+
+import { agentSkillsRouter } from './agentSkills';
+
+const mocks = vi.hoisted(() => ({
+ detail: vi.fn(),
+ findByIdentifier: vi.fn(),
+ importerConstructor: vi.fn(),
+ importFromUrl: vi.fn(),
+ modelConstructor: vi.fn(),
+}));
+vi.mock('@/libs/trpc/lambda', async () => {
+ const { trpc } = await import('@/libs/trpc/lambda/init');
+ return { router: trpc.router };
+});
+vi.mock('@/libs/trpc/lambda/middleware', async () => {
+ const { trpc } = await import('@/libs/trpc/lambda/init');
+ return { serverDatabase: trpc.middleware(({ next }) => next({ ctx: { serverDB: {} } })) };
+});
+vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async () => {
+ const { trpc } = await import('@/libs/trpc/lambda/init');
+ return { wsCompatProcedure: trpc.procedure };
+});
+vi.mock('@/business/server/trpc-middlewares/rbacPermission', async () => {
+ const { trpc } = await import('@/libs/trpc/lambda/init');
+ return {
+ withScopedPermission: (action: string) =>
+ trpc.middleware(({ ctx, next }) => {
+ if (
+ action !== 'agent:update' ||
+ (ctx as { workspaceRole?: string }).workspaceRole === 'viewer'
+ ) {
+ throw new TRPCError({ code: 'FORBIDDEN' });
+ }
+ return next({ ctx: { workspaceRole: 'member' } });
+ }),
+ };
+});
+vi.mock('@/database/models/agentSkill', () => ({
+ AgentSkillModel: class {
+ constructor(...args: unknown[]) {
+ mocks.modelConstructor(...args);
+ }
+ findByIdentifier = mocks.findByIdentifier;
+ },
+}));
+vi.mock('@/database/models/file', () => ({ FileModel: class {} }));
+vi.mock('@/server/services/file', () => ({ FileService: class {} }));
+vi.mock('@/server/services/market', () => ({
+ MarketService: class {
+ getSkillDetail = mocks.detail;
+ getSkillDownloadUrl = (id: string) => `https://market.example/${id}/download`;
+ },
+}));
+vi.mock('@/server/services/skill', async () => ({
+ ...(await import('@/server/services/skill/ensure')),
+ ...(await import('@/server/services/skill/errors')),
+ SkillImporter: class {
+ constructor(...args: unknown[]) {
+ mocks.importerConstructor(...args);
+ }
+ importFromUrl = mocks.importFromUrl;
+ },
+ SkillResourceService: class {},
+}));
+vi.mock('@lobechat/builtin-skills/manifests', () => ({ builtinSkillManifests: [] }));
+vi.mock('@lobechat/builtin-tools/identifiers', () => ({
+ builtinToolIdentifiers: ['builtin-tool'],
+}));
+
+const caller = (workspaceRole = 'member') =>
+ agentSkillsRouter.createCaller({
+ userId: 'user',
+ workspaceId: 'workspace',
+ workspaceRole,
+ } as Parameters<typeof agentSkillsRouter.createCaller>[0]);
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ mocks.detail.mockResolvedValue({});
+ mocks.findByIdentifier.mockResolvedValue(undefined);
+ mocks.importFromUrl.mockResolvedValue({ status: 'created' });
+});
+
+describe('agentSkills.ensureFromMarket', () => {
+ it('normalizes identifiers and imports using the RBAC-resolved workspace importer', async () => {
+ await expect(caller().ensureFromMarket({ identifiers: [' a ', '', 'a'] })).resolves.toEqual([
+ { identifier: 'a', status: 'installed' },
+ ]);
+ expect(mocks.modelConstructor).toHaveBeenCalledWith({}, 'user', 'workspace');
+ expect(mocks.importerConstructor).toHaveBeenLastCalledWith({}, 'user', 'workspace', {
+ workspaceRole: 'member',
+ });
+ expect(mocks.importFromUrl).toHaveBeenCalledWith(
+ { url: 'https://market.example/a/download' },
+ { identifier: 'a', overwrite: false, source: 'market' },
+ );
+ });
+
+ it('applies the write gate before any market request or import', async () => {
+ await expect(caller('viewer').ensureFromMarket({ identifiers: ['a'] })).rejects.toMatchObject({
+ code: 'FORBIDDEN',
+ });
+ expect(mocks.detail).not.toHaveBeenCalled();
+ expect(mocks.importFromUrl).not.toHaveBeenCalled();
+ });
+
+ it('rejects more than fifty distinct identifiers without importing', async () => {
+ await expect(
+ caller().ensureFromMarket({ identifiers: Array.from({ length: 51 }, (_, i) => `${i}`) }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ expect(mocks.detail).not.toHaveBeenCalled();
+ });
+
+ it('returns mixed states without failing the entire batch', async () => {
+ mocks.findByIdentifier.mockImplementation(async (id) =>
+ id === 'already' ? { source: 'market' } : undefined,
+ );
+ mocks.detail.mockImplementation(async (id) => {
+ if (id === 'missing') throw new MarketAPIError(404, 'Not Found');
+ if (id === 'forbidden') throw new MarketAPIError(403, 'Forbidden');
+ return {};
+ });
+ mocks.importFromUrl.mockImplementation(async (_input, options) => {
+ if (options.identifier === 'download-404')
+ throw new SkillImportError('Download missing', 'NOT_FOUND');
+ if (options.identifier === 'conflict')
+ throw new SkillImportError('Name conflict', 'CONFLICT');
+ return { status: 'created' };
+ });
+ await expect(
+ caller().ensureFromMarket({
+ identifiers: [
+ 'already',
+ 'builtin-tool',
+ 'missing',
+ 'forbidden',
+ 'download-404',
+ 'conflict',
+ 'new',
+ ],
+ }),
+ ).resolves.toEqual([
+ { identifier: 'already', status: 'installed' },
+ { identifier: 'builtin-tool', status: 'skipped' },
+ { identifier: 'missing', status: 'notSkill' },
+ { identifier: 'forbidden', reason: 'unavailable', status: 'failed' },
+ { identifier: 'download-404', reason: 'download', status: 'failed' },
+ { identifier: 'conflict', reason: 'conflict', status: 'failed' },
+ { identifier: 'new', status: 'installed' },
+ ]);
+ });
+});
diff --git a/apps/server/src/routers/lambda/agentSkills.ts b/apps/server/src/routers/lambda/agentSkills.ts
index db47c81a320..b241fdd4216 100644
--- a/apps/server/src/routers/lambda/agentSkills.ts
+++ b/apps/server/src/routers/lambda/agentSkills.ts
@@ -12,6 +12,8 @@ import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { FileService } from '@/server/services/file';
import { MarketService } from '@/server/services/market';
import {
+ ensureMarketSkills,
+ ensureMarketSkillsInputSchema,
SkillImporter,
SkillImportError,
SkillResourceError,
@@ -155,6 +157,10 @@ export const agentSkillsRouter = router({
return ctx.skillModel.delete(input.id);
}),
+ ensureFromMarket: skillWriteProcedure
+ .input(ensureMarketSkillsInputSchema)
+ .mutation(async ({ ctx, input }) => ensureMarketSkills(input.identifiers, ctx)),
+
// ===== Query =====
getById: skillProcedure.input(z.object({ id: z.string() })).query(async ({ ctx, input }) => {
diff --git a/apps/server/src/services/skill/ensure.test.ts b/apps/server/src/services/skill/ensure.test.ts
new file mode 100644
index 00000000000..d2f4a692856
--- /dev/null
+++ b/apps/server/src/services/skill/ensure.test.ts
@@ -0,0 +1,188 @@
+// @vitest-environment node
+import { MarketAPIError } from '@lobehub/market-sdk';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ensureMarketSkills, ensureMarketSkillsInputSchema } from './ensure';
+import { SkillImportError } from './errors';
+
+vi.mock('@lobechat/builtin-skills/manifests', () => ({
+ builtinSkillManifests: [{ identifier: 'builtin-skill' }],
+}));
+vi.mock('@lobechat/builtin-tools/identifiers', () => ({
+ builtinToolIdentifiers: ['builtin-tool'],
+}));
+
+const deps = {
+ marketService: {
+ getSkillDetail: vi.fn(),
+ getSkillDownloadUrl: vi.fn((id: string) => `https://market.example/skills/${id}/download`),
+ },
+ skillImporter: { importFromUrl: vi.fn() },
+ skillModel: { findByIdentifier: vi.fn() },
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ deps.marketService.getSkillDetail.mockResolvedValue({ name: 'Market Skill' });
+ deps.skillModel.findByIdentifier.mockResolvedValue(undefined);
+ deps.skillImporter.importFromUrl.mockResolvedValue({ status: 'created' });
+});
+
+describe('ensureMarketSkills', () => {
+ it('normalizes identifiers before applying the batch limit', () => {
+ expect(
+ ensureMarketSkillsInputSchema.parse({ identifiers: [' a ', '', ' ', 'a', 'b'] }),
+ ).toEqual({ identifiers: ['a', 'b'] });
+ expect(
+ ensureMarketSkillsInputSchema.safeParse({
+ identifiers: Array.from({ length: 51 }, (_, i) => `${i}`),
+ }).success,
+ ).toBe(false);
+ expect(
+ ensureMarketSkillsInputSchema.parse({ identifiers: Array.from({ length: 60 }, () => 'a') }),
+ ).toEqual({ identifiers: ['a'] });
+ });
+
+ it('skips builtins without querying or importing them', async () => {
+ expect(await ensureMarketSkills(['builtin-tool', 'builtin-skill'], deps)).toEqual([
+ { identifier: 'builtin-tool', status: 'skipped' },
+ { identifier: 'builtin-skill', status: 'skipped' },
+ ]);
+ expect(deps.skillModel.findByIdentifier).not.toHaveBeenCalled();
+ expect(deps.marketService.getSkillDetail).not.toHaveBeenCalled();
+ expect(deps.skillImporter.importFromUrl).not.toHaveBeenCalled();
+ });
+
+ it('preserves existing market skills and rejects other sources, even with the same source URL', async () => {
+ deps.skillModel.findByIdentifier.mockImplementation(async (identifier) => ({
+ identifier,
+ manifest: { sourceUrl: `https://market.example/skills/${identifier}/download` },
+ source: identifier === 'installed' ? 'market' : 'user',
+ }));
+ expect(await ensureMarketSkills(['installed', 'conflicting'], deps)).toEqual([
+ { identifier: 'installed', status: 'installed' },
+ { identifier: 'conflicting', reason: 'conflict', status: 'failed' },
+ ]);
+ expect(deps.marketService.getSkillDetail).not.toHaveBeenCalled();
+ expect(deps.skillImporter.importFromUrl).not.toHaveBeenCalled();
+ });
+
+ it('imports through the scoped importer without allowing overwrite', async () => {
+ expect(await ensureMarketSkills(['new'], deps)).toEqual([
+ { identifier: 'new', status: 'installed' },
+ ]);
+ expect(deps.skillImporter.importFromUrl).toHaveBeenCalledWith(
+ { url: 'https://market.example/skills/new/download' },
+ { identifier: 'new', overwrite: false, source: 'market' },
+ );
+ });
+
+ it.each([
+ [new MarketAPIError(404, 'Not Found'), 'notSkill'],
+ [new MarketAPIError(403, 'Forbidden'), 'failed'],
+ [new MarketAPIError(503, 'Unavailable'), 'failed'],
+ [new Error('404 Not Found'), 'failed'],
+ [Object.assign(new Error('Not Found'), { status: 404 }), 'failed'],
+ [new TypeError('Network failed'), 'failed'],
+ ])('classifies only typed detail 404 as notSkill (%s)', async (error, status) => {
+ deps.marketService.getSkillDetail.mockRejectedValue(error);
+ expect(await ensureMarketSkills(['missing'], deps)).toEqual([
+ expect.objectContaining({
+ identifier: 'missing',
+ status,
+ ...(status === 'failed' && { reason: 'unavailable' }),
+ }),
+ ]);
+ expect(deps.skillImporter.importFromUrl).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ [new SkillImportError('Download 404', 'NOT_FOUND'), 'download'],
+ [new Error('Invalid manifest'), 'download'],
+ [new SkillImportError('Same name exists', 'CONFLICT'), 'conflict'],
+ ])('keeps download failures and source conflicts distinct (%s)', async (error, reason) => {
+ deps.skillImporter.importFromUrl.mockRejectedValue(error);
+ expect(await ensureMarketSkills(['new'], deps)).toEqual([
+ expect.objectContaining({ identifier: 'new', reason, status: 'failed' }),
+ ]);
+ });
+
+ describe('when the import fails', () => {
+ // The unique constraint rejects the loser of two concurrent installs.
+ const uniqueViolation = Object.assign(new Error('duplicate key value'), { code: '23505' });
+
+ it('reports installed when a concurrent request already installed the Market skill', async () => {
+ deps.skillModel.findByIdentifier
+ .mockResolvedValueOnce(undefined)
+ .mockResolvedValueOnce({ identifier: 'new', source: 'market' });
+ deps.skillImporter.importFromUrl.mockRejectedValue(uniqueViolation);
+
+ expect(await ensureMarketSkills(['new'], deps)).toEqual([
+ { identifier: 'new', status: 'installed' },
+ ]);
+ });
+
+ it('keeps the download failure when nothing was installed meanwhile', async () => {
+ deps.skillImporter.importFromUrl.mockRejectedValue(uniqueViolation);
+
+ expect(await ensureMarketSkills(['new'], deps)).toEqual([
+ { identifier: 'new', reason: 'download', status: 'failed' },
+ ]);
+ });
+
+ it('reports a conflict when the identifier is now taken by another source', async () => {
+ deps.skillModel.findByIdentifier
+ .mockResolvedValueOnce(undefined)
+ .mockResolvedValueOnce({ identifier: 'new', source: 'user' });
+ deps.skillImporter.importFromUrl.mockRejectedValue(uniqueViolation);
+
+ expect(await ensureMarketSkills(['new'], deps)).toEqual([
+ { identifier: 'new', reason: 'conflict', status: 'failed' },
+ ]);
+ });
+
+ it('keeps the original classification when the re-check itself fails', async () => {
+ deps.skillModel.findByIdentifier
+ .mockResolvedValueOnce(undefined)
+ .mockRejectedValueOnce(new Error('DB unavailable'));
+ deps.skillImporter.importFromUrl.mockRejectedValue(new Error('Invalid manifest'));
+
+ expect(await ensureMarketSkills(['new'], deps)).toEqual([
+ { identifier: 'new', reason: 'download', status: 'failed' },
+ ]);
+ });
+ });
+
+ it('isolates per-item storage lookup errors', async () => {
+ deps.skillModel.findByIdentifier.mockRejectedValueOnce(new Error('DB unavailable'));
+ const result = await ensureMarketSkills(['broken', 'new'], deps);
+ expect(result[0]).toMatchObject({ reason: 'unavailable', status: 'failed' });
+ expect(result[1]).toEqual({ identifier: 'new', status: 'installed' });
+ });
+
+ it('limits concurrent work to four and preserves input order', async () => {
+ const identifiers = Array.from({ length: 9 }, (_, i) => `skill-${i}`);
+ let active = 0;
+ let peak = 0;
+ const release: Array<() => void> = [];
+ deps.marketService.getSkillDetail.mockImplementation(async () => {
+ active++;
+ peak = Math.max(peak, active);
+ await new Promise<void>((resolve) => release.push(resolve));
+ active--;
+ return {};
+ });
+ const pending = ensureMarketSkills(identifiers, deps);
+ while (deps.marketService.getSkillDetail.mock.calls.length < 4)
+ await new Promise((resolve) => setImmediate(resolve));
+ expect(active).toBe(4);
+ while (release.length || active) {
+ release.splice(0).forEach((resolve) => resolve());
+ await new Promise((resolve) => setImmediate(resolve));
+ }
+ expect(await pending).toEqual(
+ identifiers.map((identifier) => ({ identifier, status: 'installed' })),
+ );
+ expect(peak).toBe(4);
+ });
+});
diff --git a/apps/server/src/services/skill/ensure.ts b/apps/server/src/services/skill/ensure.ts
new file mode 100644
index 00000000000..a69eb743f9e
--- /dev/null
+++ b/apps/server/src/services/skill/ensure.ts
@@ -0,0 +1,132 @@
+import { builtinSkillManifests } from '@lobechat/builtin-skills/manifests';
+import { builtinToolIdentifiers } from '@lobechat/builtin-tools/identifiers';
+import { MarketAPIError } from '@lobehub/market-sdk';
+import debug from 'debug';
+import pMap from 'p-map';
+import { z } from 'zod';
+
+import type { AgentSkillModel } from '@/database/models/agentSkill';
+import type { MarketService } from '@/server/services/market';
+
+import { SkillImportError } from './errors';
+import type { SkillImporter } from './importer';
+
+const log = debug('lobe-chat:service:skill-ensure');
+
+const logEnsureFailure = (
+ identifier: string,
+ stage: 'lookup' | 'detail' | 'import',
+ error: unknown,
+) => {
+ log('ensureFromMarket failed: %o', {
+ identifier,
+ stage,
+ ...(error instanceof MarketAPIError && { status: error.status }),
+ ...(error instanceof SkillImportError && { code: error.code }),
+ });
+};
+
+export type EnsureMarketSkillResult =
+ | { identifier: string; status: 'installed' | 'skipped' | 'notSkill' }
+ | {
+ identifier: string;
+ message?: string;
+ reason: 'conflict' | 'download' | 'unavailable';
+ status: 'failed';
+ };
+
+export const ensureMarketSkillsInputSchema = z.object({
+ identifiers: z
+ .array(z.string())
+ .transform((identifiers) => [...new Set(identifiers.map((id) => id.trim()).filter(Boolean))])
+ .pipe(z.array(z.string()).max(50)),
+});
+
+const builtinIdentifiers = new Set([
+ ...builtinToolIdentifiers,
+ ...builtinSkillManifests.map((skill) => skill.identifier),
+]);
+
+interface EnsureMarketSkillsDependencies {
+ marketService: Pick<MarketService, 'getSkillDetail' | 'getSkillDownloadUrl'>;
+ skillImporter: Pick<SkillImporter, 'importFromUrl'>;
+ skillModel: Pick<AgentSkillModel, 'findByIdentifier'>;
+}
+
+/** The scope's record for `identifier` after a failed import; a failed lookup counts as none. */
+const findAfterFailedImport = async (
+ identifier: string,
+ skillModel: EnsureMarketSkillsDependencies['skillModel'],
+) => {
+ try {
+ return await skillModel.findByIdentifier(identifier);
+ } catch (error) {
+ logEnsureFailure(identifier, 'lookup', error);
+ return undefined;
+ }
+};
+
+/** Ensure dependencies without replacing any skill already in the caller's scope. */
+export const ensureMarketSkills = async (
+ identifiers: string[],
+ { marketService, skillImporter, skillModel }: EnsureMarketSkillsDependencies,
+): Promise<EnsureMarketSkillResult[]> =>
+ pMap(
+ identifiers,
+ async (identifier): Promise<EnsureMarketSkillResult> => {
+ if (builtinIdentifiers.has(identifier)) return { identifier, status: 'skipped' };
+
+ try {
+ const existing = await skillModel.findByIdentifier(identifier);
+ if (existing) {
+ return existing.source === 'market'
+ ? { identifier, status: 'installed' }
+ : { identifier, reason: 'conflict', status: 'failed' };
+ }
+ } catch (error) {
+ logEnsureFailure(identifier, 'lookup', error);
+ return { identifier, reason: 'unavailable', status: 'failed' };
+ }
+
+ // Only a typed 404 from the detail endpoint proves this is not a skill.
+ // Download 404s after a successful detail request remain install failures.
+ try {
+ await marketService.getSkillDetail(identifier);
+ } catch (error) {
+ logEnsureFailure(identifier, 'detail', error);
+ return error instanceof MarketAPIError && error.status === 404
+ ? { identifier, status: 'notSkill' }
+ : { identifier, reason: 'unavailable', status: 'failed' };
+ }
+
+ try {
+ await skillImporter.importFromUrl(
+ { url: marketService.getSkillDownloadUrl(identifier) },
+ { identifier, overwrite: false, source: 'market' },
+ );
+ return { identifier, status: 'installed' };
+ } catch (error) {
+ logEnsureFailure(identifier, 'import', error);
+
+ // A concurrent request may have installed the same skill between our
+ // lookup and the insert, which the per-scope unique constraint rejects.
+ // Whatever the error was, the scope's current state decides the result.
+ const raced = await findAfterFailedImport(identifier, skillModel);
+ if (raced) {
+ return raced.source === 'market'
+ ? { identifier, status: 'installed' }
+ : { identifier, reason: 'conflict', status: 'failed' };
+ }
+
+ return {
+ identifier,
+ reason:
+ error instanceof SkillImportError && error.code === 'CONFLICT'
+ ? 'conflict'
+ : 'download',
+ status: 'failed',
+ };
+ }
+ },
+ { concurrency: 4 },
+ );
diff --git a/apps/server/src/services/skill/importer.ensure.test.ts b/apps/server/src/services/skill/importer.ensure.test.ts
new file mode 100644
index 00000000000..16726b11f8e
--- /dev/null
+++ b/apps/server/src/services/skill/importer.ensure.test.ts
@@ -0,0 +1,110 @@
+// @vitest-environment node
+import type { LobeChatDatabase } from '@lobechat/database';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { SkillImporter } from './importer';
+
+const mocks = vi.hoisted(() => ({
+ create: vi.fn(),
+ findByIdentifier: vi.fn(),
+ findByName: vi.fn(),
+ parseSkillMd: vi.fn(),
+ ssrfSafeFetch: vi.fn(),
+ update: vi.fn(),
+}));
+vi.mock('@/database/models/agentSkill', () => ({
+ AgentSkillModel: class {
+ create = mocks.create;
+ findByIdentifier = mocks.findByIdentifier;
+ findByName = mocks.findByName;
+ update = mocks.update;
+ },
+}));
+vi.mock('@/server/modules/GitHub', () => ({
+ GitHub: class {},
+ GitHubNotFoundError: class extends Error {},
+ GitHubParseError: class extends Error {},
+}));
+vi.mock('@/server/services/file', () => ({ FileService: class {} }));
+vi.mock('./resource', () => ({ SkillResourceService: class {} }));
+vi.mock('./parser', () => ({
+ SkillParser: class {
+ parseSkillMd = mocks.parseSkillMd;
+ },
+}));
+vi.mock('@lobechat/ssrf-safe-fetch', () => ({ ssrfSafeFetch: mocks.ssrfSafeFetch }));
+
+const url = 'https://market.example/skills/new/SKILL.md';
+const options = { identifier: 'new', overwrite: false, source: 'market' as const };
+const importer = () => new SkillImporter({} as LobeChatDatabase, 'owner', 'scope');
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ mocks.ssrfSafeFetch.mockResolvedValue({ ok: true, text: async () => 'skill content' });
+ mocks.parseSkillMd.mockReturnValue({ content: 'new content', manifest: { name: 'Shared Name' } });
+ mocks.findByIdentifier.mockResolvedValue(undefined);
+ mocks.findByName.mockResolvedValue(undefined);
+ mocks.create.mockResolvedValue({ id: 'created' });
+ mocks.update.mockResolvedValue({ id: 'overwritten' });
+});
+
+describe('SkillImporter ensure mode', () => {
+ it('rejects a user identifier even when its source URL matches', async () => {
+ mocks.findByIdentifier.mockResolvedValue({
+ content: 'old content',
+ id: 'existing',
+ identifier: 'new',
+ manifest: { sourceUrl: url },
+ source: 'user',
+ userId: 'owner',
+ });
+ await expect(importer().importFromUrl({ url }, options)).rejects.toMatchObject({
+ code: 'CONFLICT',
+ });
+ expect(mocks.update).not.toHaveBeenCalled();
+ expect(mocks.create).not.toHaveBeenCalled();
+ });
+
+ it('rejects a same-name user skill even when it was fetched from the same URL', async () => {
+ mocks.findByName.mockResolvedValue({
+ content: 'old content',
+ id: 'existing',
+ identifier: 'user.name',
+ manifest: { sourceUrl: url },
+ source: 'user',
+ userId: 'owner',
+ });
+ await expect(importer().importFromUrl({ url }, options)).rejects.toMatchObject({
+ code: 'CONFLICT',
+ });
+ expect(mocks.update).not.toHaveBeenCalled();
+ });
+
+ it('does not update an already installed market skill found during import', async () => {
+ const existing = {
+ content: 'old content',
+ id: 'existing',
+ identifier: 'new',
+ source: 'market',
+ };
+ mocks.findByIdentifier.mockResolvedValue(existing);
+ await expect(importer().importFromUrl({ url }, options)).resolves.toEqual({
+ skill: existing,
+ status: 'unchanged',
+ });
+ expect(mocks.update).not.toHaveBeenCalled();
+ });
+
+ it('creates a missing market skill through the SSRF safe downloader', async () => {
+ await expect(importer().importFromUrl({ url }, options)).resolves.toMatchObject({
+ status: 'created',
+ });
+ expect(mocks.ssrfSafeFetch).toHaveBeenCalledWith(
+ url,
+ expect.objectContaining({ signal: expect.any(AbortSignal) }),
+ );
+ expect(mocks.create).toHaveBeenCalledWith(
+ expect.objectContaining({ identifier: 'new', source: 'market' }),
+ );
+ });
+});
diff --git a/apps/server/src/services/skill/importer.ts b/apps/server/src/services/skill/importer.ts
index 275a3e5adcc..6944ee7226b 100644
--- a/apps/server/src/services/skill/importer.ts
+++ b/apps/server/src/services/skill/importer.ts
@@ -309,7 +309,7 @@ export class SkillImporter {
*/
async importFromUrl(
input: ImportUrlInput,
- options?: { identifier?: string; source?: 'market' | 'user' },
+ options?: { identifier?: string; overwrite?: boolean; source?: 'market' | 'user' },
): Promise<SkillImportResult> {
log('importFromUrl: starting with url=%s', input.url);
@@ -424,6 +424,17 @@ export class SkillImporter {
// 5. Check for existing skill
let existing = await this.skillModel.findByIdentifier(identifier);
+ // Dependency installation never updates an installed row, including user
+ // imports that happen to carry the same source URL. Recheck here after the
+ // download as another request may have installed the skill in the meantime.
+ if (existing && options?.overwrite === false) {
+ if (existing.source === 'market') return { skill: existing, status: 'unchanged' };
+ throw new SkillImportError(
+ `A skill with identifier "${identifier}" is already installed from another source`,
+ 'CONFLICT',
+ );
+ }
+
// A user may have authored a skill under this very identifier. Only treat
// the row as this import when it came from the market or from this same
// URL; otherwise updating it would overwrite the user's own skill.
@@ -439,7 +450,7 @@ export class SkillImporter {
// since then is still updated in place rather than installed twice. Only
// take it when it was fetched from this same URL: a user skill may carry
// that identifier explicitly and must not be overwritten.
- if (!existing && identifier !== urlIdentifier) {
+ if (!existing && identifier !== urlIdentifier && options?.overwrite !== false) {
const legacy = await this.skillModel.findByIdentifier(urlIdentifier);
if (legacy?.manifest?.sourceUrl === input.url) existing = legacy;
}
@@ -451,7 +462,7 @@ export class SkillImporter {
if (!existing) {
const sameName = await this.skillModel.findByName(manifest.name);
if (sameName) {
- if (sameName.manifest?.sourceUrl !== input.url) {
+ if (options?.overwrite === false || sameName.manifest?.sourceUrl !== input.url) {
throw new SkillImportError(
`A skill named "${manifest.name}" is already installed (identifier: ${sameName.identifier}). Use the installed skill, or delete it before importing this one.`,
'CONFLICT',
diff --git a/apps/server/src/services/skill/index.ts b/apps/server/src/services/skill/index.ts
index 9d495a90847..9d2760f343a 100644
--- a/apps/server/src/services/skill/index.ts
+++ b/apps/server/src/services/skill/index.ts
@@ -1,3 +1,4 @@
+export * from './ensure';
export * from './errors';
export * from './importer';
export * from './parser';
diff --git a/locales/en-US/common.json b/locales/en-US/common.json
index 3416c0ad3b5..03dd52b7dcd 100644
--- a/locales/en-US/common.json
+++ b/locales/en-US/common.json
@@ -5,6 +5,7 @@
"agentLabel.create": "New label",
"agentLabel.manage": "Manage labels",
"agentLabel.menuTitle": "Labels",
+ "agentSkills.ensureFailed": "Some skills this agent relies on could not be installed automatically: {{skills}}. You can add them manually in the Skill Store.",
"agentViewAll.addToSidebar": "Show in my sidebar",
"agentViewAll.empty": "No agents yet",
"agentViewAll.form.grouping": "Grouping",
diff --git a/locales/zh-CN/common.json b/locales/zh-CN/common.json
index 4cdc32dd9da..8f71bfe53ba 100644
--- a/locales/zh-CN/common.json
+++ b/locales/zh-CN/common.json
@@ -5,6 +5,7 @@
"agentLabel.create": "新建标签",
"agentLabel.manage": "管理标签",
"agentLabel.menuTitle": "标签",
+ "agentSkills.ensureFailed": "该助理依赖的部分技能未能自动安装:{{skills}}。可在技能商店中手动添加。",
"agentViewAll.addToSidebar": "在我的侧边栏显示",
"agentViewAll.empty": "暂无助理",
"agentViewAll.form.grouping": "分组",
diff --git a/packages/locales/src/default/common.ts b/packages/locales/src/default/common.ts
index 5694f28e198..112c0d7b74d 100644
--- a/packages/locales/src/default/common.ts
+++ b/packages/locales/src/default/common.ts
@@ -15,6 +15,8 @@ export default {
'agentLabel.create': 'New label',
'agentLabel.manage': 'Manage labels',
'agentLabel.menuTitle': 'Labels',
+ 'agentSkills.ensureFailed':
+ 'Some skills this agent relies on could not be installed automatically: {{skills}}. You can add them manually in the Skill Store.',
'agentViewAll.groupBy.author': 'Author',
'agentViewAll.groupBy.label': 'Label',
'agentViewAll.groupBy.noLabel': 'No label',
diff --git a/src/features/ProfileEditor/AgentTool.tsx b/src/features/ProfileEditor/AgentTool.tsx
index e788d64802c..0a4a3203de7 100644
--- a/src/features/ProfileEditor/AgentTool.tsx
+++ b/src/features/ProfileEditor/AgentTool.tsx
@@ -7,7 +7,7 @@ import { Avatar, Button, cssVar, Flexbox, Icon } from '@lobehub/ui';
import { McpIcon, SkillsIcon } from '@lobehub/ui/icons';
import isEqual from 'fast-deep-equal';
import { PlusIcon } from 'lucide-react';
-import React, { memo, Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import React, { memo, Suspense, useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import ActionDropdown from '@/features/ChatInput/ActionBar/components/ActionDropdown';
@@ -36,13 +36,14 @@ import {
composioStoreSelectors,
pluginSelectors,
} from '@/store/tool/selectors';
+import { agentSkillListResource } from '@/store/tool/slices/agentSkills/projection';
import type { LobeToolMetaWithAvailability } from '@/store/tool/slices/builtin/selectors';
import { connectorSelectors } from '@/store/tool/slices/connector';
import PluginTag from './PluginTag';
import PopoverContent from './PopoverContent';
import { getVisibleProfileToolIds } from './profileToolVisibility';
-import { resolveStalePluginCleanup, selectProfileToolCatalogsSynced } from './staleProfilePlugins';
+import { selectProfileToolCatalogsSynced, useStalePluginAutoResolve } from './staleProfilePlugins';
export interface AgentToolProps {
/**
@@ -785,50 +786,28 @@ const AgentTool = memo<AgentToolProps>(
customConnectors,
]);
- // Track whether initial cleanup has been performed
- const cleanupDoneRef = useRef(false);
-
- // Auto-remove stale plugin IDs from the agent config. The catalog gates
- // decide when the data is complete; the debounce only coalesces the burst
- // of catalog updates that arrive together.
- useEffect(() => {
- if (cleanupDoneRef.current) return;
-
- const timer = setTimeout(() => {
- const cleanedPlugins = resolveStalePluginCleanup({
- canEditContent: canEdit,
- canEditResource,
- isAccessResolved,
- isConnectorsInit,
- isToolCatalogSynced,
- plugins: config?.plugins,
- validIdentifiers,
- });
-
- if (cleanedPlugins && effectiveAgentId) {
- // Best-effort self-healing the user never asked for, so a rejection
- // (edit lock held by another member, resource access revoked between
- // render and write) must not claim "your change was not applied" —
- // there was no change to apply. It retries on the next open.
- updateAgentConfigById(
- effectiveAgentId,
- { plugins: cleanedPlugins },
- { showErrorMessage: false },
- );
- cleanupDoneRef.current = true;
- }
- }, 500);
-
- return () => clearTimeout(timer);
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [
- validIdentifiers,
- canEdit,
+ // Self-heal unresolved plugin entries once the catalogs are complete. They
+ // may be Market skills that are not installed yet, so the server is asked
+ // first and only entries it says are not skills are removed.
+ useStalePluginAutoResolve({
+ agentId: effectiveAgentId,
+ canEditContent: canEdit,
canEditResource,
+ getScope: () => agentSkillListResource.scope.get(),
+ getCurrentPlugins: () =>
+ agentSelectors.getAgentConfigById(effectiveAgentId)(useAgentStore.getState())?.plugins,
isAccessResolved,
isConnectorsInit,
isToolCatalogSynced,
- ]);
+ plugins: config?.plugins,
+ scope: agentSkillListResource.scope.use(),
+ // Best-effort: the user never asked for this, so a rejection (edit lock
+ // held by another member, access revoked between render and write) must
+ // not claim "your change was not applied". It retries on the next open.
+ updatePlugins: (id, nextPlugins) =>
+ updateAgentConfigById(id, { plugins: nextPlugins }, { showErrorMessage: false }),
+ validIdentifiers,
+ });
// Only display tools that this profile surface actually manages. Runtime-
// managed entries remain untouched in config for compatibility with other
diff --git a/src/features/ProfileEditor/staleProfilePlugins.test.ts b/src/features/ProfileEditor/staleProfilePlugins.test.ts
index 4f0a1c6c9eb..08cc39acc15 100644
--- a/src/features/ProfileEditor/staleProfilePlugins.test.ts
+++ b/src/features/ProfileEditor/staleProfilePlugins.test.ts
@@ -1,5 +1,11 @@
-import { describe, expect, it } from 'vitest';
+/**
+ * @vitest-environment happy-dom
+ */
+import type { AgentPluginEntry } from '@lobechat/types';
+import { renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { EnsureMarketSkillResult } from '@/services/skill';
import { initialState, type ToolStoreState } from '@/store/tool/initialState';
import { AGENT_SKILL_LIST_KEY } from '@/store/tool/slices/agentSkills/projection';
import { UNINSTALLED_BUILTIN_TOOLS_KEY } from '@/store/tool/slices/builtin/projection';
@@ -8,10 +14,19 @@ import { INSTALLED_PLUGINS_KEY } from '@/store/tool/slices/plugin/projection';
import {
resolveStalePluginCleanup,
+ resolveUnresolvedPluginIds,
selectProfileToolCatalogsSynced,
+ type StalePluginAutoResolveInput,
type StalePluginCleanupInput,
+ useStalePluginAutoResolve,
} from './staleProfilePlugins';
+const ensureMock = vi.hoisted(() => vi.fn());
+vi.mock('@/services/ensureAgentMarketSkills', () => ({ ensureAgentMarketSkills: ensureMock }));
+
+const notSkill = (...ids: string[]): EnsureMarketSkillResult[] =>
+ ids.map((identifier) => ({ identifier, status: 'notSkill' }));
+
const baseInput = (overrides: Partial<StalePluginCleanupInput> = {}): StalePluginCleanupInput => ({
canEditContent: true,
canEditResource: true,
@@ -25,7 +40,7 @@ const baseInput = (overrides: Partial<StalePluginCleanupInput> = {}): StalePlugi
describe('resolveStalePluginCleanup', () => {
it('drops entries whose identifier no longer resolves', () => {
- expect(resolveStalePluginCleanup(baseInput())).toEqual(['web-search']);
+ expect(resolveStalePluginCleanup(baseInput(), notSkill('ghost-tool'))).toEqual(['web-search']);
});
it('keeps the original entry shape for surviving entries', () => {
@@ -33,6 +48,7 @@ describe('resolveStalePluginCleanup', () => {
baseInput({
plugins: [{ identifier: 'web-search', mode: 'disabled' }, 'ghost-tool'],
}),
+ notSkill('ghost-tool'),
);
expect(result).toEqual([{ identifier: 'web-search', mode: 'disabled' }]);
@@ -42,12 +58,64 @@ describe('resolveStalePluginCleanup', () => {
expect(
resolveStalePluginCleanup(
baseInput({ plugins: ['web-search'], validIdentifiers: new Set(['web-search']) }),
+ notSkill('web-search'),
+ ),
+ ).toBeNull();
+ });
+
+ // The server could not say the entry is not a skill, so it may still be a
+ // valid Market skill that failed to download: keep it for the next open.
+ it.each<[string, EnsureMarketSkillResult[]]>([
+ ['installed', [{ identifier: 'ghost-tool', status: 'installed' }]],
+ ['skipped', [{ identifier: 'ghost-tool', status: 'skipped' }]],
+ ['failed', [{ identifier: 'ghost-tool', reason: 'download', status: 'failed' }]],
+ ['unavailable', [{ identifier: 'ghost-tool', reason: 'unavailable', status: 'failed' }]],
+ ['not reported', []],
+ ])('keeps an unresolved entry whose ensure result is %s', (_, results) => {
+ expect(resolveStalePluginCleanup(baseInput(), results)).toBeNull();
+ });
+
+ it('removes nothing without ensure results', () => {
+ expect(resolveStalePluginCleanup(baseInput())).toBeNull();
+ });
+
+ it('only removes not-a-skill entries and leaves the rest untouched in place', () => {
+ const plugins = [
+ 'web-search',
+ { identifier: 'ghost-a', mode: 'disabled' as const },
+ 'market-skill',
+ { identifier: 'ghost-b' },
+ { identifier: 'kept-disabled', mode: 'disabled' as const },
+ ];
+
+ expect(
+ resolveStalePluginCleanup(
+ baseInput({
+ plugins,
+ validIdentifiers: new Set(['web-search', 'kept-disabled']),
+ }),
+ [
+ { identifier: 'ghost-a', status: 'notSkill' },
+ { identifier: 'market-skill', status: 'installed' },
+ { identifier: 'ghost-b', status: 'notSkill' },
+ ],
+ ),
+ ).toEqual(['web-search', 'market-skill', { identifier: 'kept-disabled', mode: 'disabled' }]);
+ });
+
+ it('does not remove a now-resolved entry even if the server called it not-a-skill', () => {
+ expect(
+ resolveStalePluginCleanup(
+ baseInput({ plugins: ['web-search'], validIdentifiers: new Set(['web-search']) }),
+ notSkill('web-search'),
),
).toBeNull();
});
it('returns null before the connector store has loaded', () => {
- expect(resolveStalePluginCleanup(baseInput({ isConnectorsInit: false }))).toBeNull();
+ expect(
+ resolveStalePluginCleanup(baseInput({ isConnectorsInit: false }), notSkill('ghost-tool')),
+ ).toBeNull();
});
// https://github.com/lobehub/lobehub/issues/18856 — on a cold start the
@@ -61,17 +129,20 @@ describe('resolveStalePluginCleanup', () => {
plugins: ['web-search', 'my-custom-tool'],
validIdentifiers: new Set(['web-search']),
}),
+ notSkill('my-custom-tool'),
),
).toBeNull();
});
it('returns null when no identifiers are known yet', () => {
- expect(resolveStalePluginCleanup(baseInput({ validIdentifiers: new Set() }))).toBeNull();
+ expect(
+ resolveStalePluginCleanup(baseInput({ validIdentifiers: new Set() }), notSkill('ghost-tool')),
+ ).toBeNull();
});
it('returns null for an agent with no plugins', () => {
- expect(resolveStalePluginCleanup(baseInput({ plugins: undefined }))).toBeNull();
- expect(resolveStalePluginCleanup(baseInput({ plugins: [] }))).toBeNull();
+ expect(resolveStalePluginCleanup(baseInput({ plugins: undefined }), [])).toBeNull();
+ expect(resolveStalePluginCleanup(baseInput({ plugins: [] }), [])).toBeNull();
});
// automatic corrections must not trigger phantom save-error toasts: the cleanup is automatic, so firing it without edit access made
@@ -80,11 +151,15 @@ describe('resolveStalePluginCleanup', () => {
// agent settings" on an agent the member had only opened.
describe('permission gate (automatic corrections must not trigger phantom save-error toasts)', () => {
it('does not clean up when the workspace role cannot edit content', () => {
- expect(resolveStalePluginCleanup(baseInput({ canEditContent: false }))).toBeNull();
+ expect(
+ resolveStalePluginCleanup(baseInput({ canEditContent: false }), notSkill('ghost-tool')),
+ ).toBeNull();
});
it('does not clean up when General access on this agent is below edit', () => {
- expect(resolveStalePluginCleanup(baseInput({ canEditResource: false }))).toBeNull();
+ expect(
+ resolveStalePluginCleanup(baseInput({ canEditResource: false }), notSkill('ghost-tool')),
+ ).toBeNull();
});
it('fails closed while workspace access is still resolving', () => {
@@ -93,12 +168,263 @@ describe('resolveStalePluginCleanup', () => {
// `canEditResource` defaults permissive during loading, so the
// resolved flag is what keeps the doomed write from being fired.
baseInput({ canEditResource: true, isAccessResolved: false }),
+ notSkill('ghost-tool'),
),
).toBeNull();
});
});
});
+describe('resolveUnresolvedPluginIds', () => {
+ it('lists each unresolved identifier once, whatever the entry shape or mode', () => {
+ expect(
+ resolveUnresolvedPluginIds(
+ baseInput({
+ plugins: [
+ 'web-search',
+ 'ghost-a',
+ { identifier: 'ghost-a', mode: 'disabled' },
+ { identifier: 'ghost-b' },
+ ],
+ }),
+ ),
+ ).toEqual(['ghost-a', 'ghost-b']);
+ });
+
+ it.each([
+ ['canEditContent', { canEditContent: false }],
+ ['canEditResource', { canEditResource: false }],
+ ['isAccessResolved', { isAccessResolved: false }],
+ ['isConnectorsInit', { isConnectorsInit: false }],
+ ['isToolCatalogSynced', { isToolCatalogSynced: false }],
+ ['validIdentifiers', { validIdentifiers: new Set<string>() }],
+ ])('lists nothing while the %s gate is not satisfied', (_, overrides) => {
+ expect(resolveUnresolvedPluginIds(baseInput(overrides))).toEqual([]);
+ });
+
+ it('lists nothing when every entry resolves', () => {
+ expect(resolveUnresolvedPluginIds(baseInput({ plugins: ['web-search'] }))).toEqual([]);
+ });
+});
+
+describe('useStalePluginAutoResolve', () => {
+ const update = vi.fn();
+ let live: AgentPluginEntry[] | undefined;
+ let liveScope = 'user-1:personal';
+
+ const deferred = () => {
+ let resolve!: (value: EnsureMarketSkillResult[]) => void;
+ const promise = new Promise<EnsureMarketSkillResult[]>((r) => (resolve = r));
+ return { promise, resolve };
+ };
+
+ const hookInput = (
+ overrides: Partial<StalePluginAutoResolveInput> = {},
+ ): StalePluginAutoResolveInput => {
+ const base = baseInput(overrides);
+ live = base.plugins;
+ liveScope = overrides.scope ?? 'user-1:personal';
+ return {
+ ...base,
+ agentId: 'agent-1',
+ getCurrentPlugins: () => live,
+ getScope: () => liveScope,
+ scope: 'user-1:personal',
+ updatePlugins: update,
+ ...overrides,
+ };
+ };
+
+ const settle = (ms = 500) => vi.advanceTimersByTimeAsync(ms);
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ update.mockReset();
+ ensureMock.mockReset();
+ ensureMock.mockImplementation(async () => notSkill('ghost-tool'));
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it.each([
+ ['canEditContent', { canEditContent: false }],
+ ['canEditResource', { canEditResource: false }],
+ ['isAccessResolved', { isAccessResolved: false }],
+ ['isConnectorsInit', { isConnectorsInit: false }],
+ ['isToolCatalogSynced', { isToolCatalogSynced: false }],
+ ])('sends no write request while the %s gate is not satisfied', async (_, overrides) => {
+ renderHook(() => useStalePluginAutoResolve(hookInput(overrides)));
+ await settle();
+
+ expect(ensureMock).not.toHaveBeenCalled();
+ expect(update).not.toHaveBeenCalled();
+ });
+
+ it('asks about the unresolved identifiers only, then drops the not-a-skill ones', async () => {
+ renderHook(() => useStalePluginAutoResolve(hookInput()));
+ await settle();
+
+ expect(ensureMock).toHaveBeenCalledTimes(1);
+ expect(ensureMock).toHaveBeenCalledWith(['ghost-tool']);
+ expect(update).toHaveBeenCalledWith('agent-1', ['web-search']);
+ });
+
+ it.each<[string, () => Promise<EnsureMarketSkillResult[]>]>([
+ ['installed', async () => [{ identifier: 'ghost-tool', status: 'installed' }]],
+ ['failed', async () => [{ identifier: 'ghost-tool', reason: 'download', status: 'failed' }]],
+ [
+ 'rejected',
+ async () => {
+ throw new Error('network down');
+ },
+ ],
+ ])('keeps every entry when ensure is %s', async (_, outcome) => {
+ ensureMock.mockImplementation(outcome);
+ renderHook(() => useStalePluginAutoResolve(hookInput()));
+ await settle();
+
+ expect(ensureMock).toHaveBeenCalledTimes(1);
+ expect(update).not.toHaveBeenCalled();
+ });
+
+ it('does not repeat the request while one is in flight or after it settled', async () => {
+ const pending = deferred();
+ ensureMock.mockImplementation(() => pending.promise);
+ const { rerender } = renderHook((input) => useStalePluginAutoResolve(input), {
+ initialProps: hookInput(),
+ });
+ await settle();
+
+ rerender(hookInput({ validIdentifiers: new Set(['web-search']) }));
+ await settle();
+ expect(ensureMock).toHaveBeenCalledTimes(1);
+
+ pending.resolve(notSkill('ghost-tool'));
+ await settle();
+ rerender(hookInput({ validIdentifiers: new Set(['web-search']) }));
+ await settle();
+
+ expect(ensureMock).toHaveBeenCalledTimes(1);
+ expect(update).toHaveBeenCalledTimes(1);
+ });
+
+ it('tracks attempts per scope and agent', async () => {
+ const { rerender } = renderHook((input) => useStalePluginAutoResolve(input), {
+ initialProps: hookInput(),
+ });
+ await settle();
+ rerender(hookInput({ agentId: 'agent-2' }));
+ await settle();
+ rerender(hookInput({ agentId: 'agent-2', scope: 'user-1:workspace-1' }));
+ await settle();
+
+ expect(ensureMock).toHaveBeenCalledTimes(3);
+ expect(update.mock.calls.map(([agentId]) => agentId)).toEqual([
+ 'agent-1',
+ 'agent-2',
+ 'agent-2',
+ ]);
+ });
+
+ it('abandons the write when the plugins changed meanwhile, then retries on the new snapshot', async () => {
+ const pending = deferred();
+ ensureMock.mockImplementationOnce(() => pending.promise);
+ const { rerender } = renderHook((input) => useStalePluginAutoResolve(input), {
+ initialProps: hookInput(),
+ });
+ await settle();
+
+ // the user edits the tool list while the request is in flight
+ const edited = ['web-search', 'ghost-tool', 'added-by-user'];
+ live = edited;
+ rerender(
+ hookInput({ plugins: edited, validIdentifiers: new Set(['web-search', 'added-by-user']) }),
+ );
+ live = edited;
+ pending.resolve(notSkill('ghost-tool'));
+ await settle();
+
+ // nothing is written from the old snapshot; the new one is resolved on its own
+ expect(update).toHaveBeenCalledTimes(1);
+ expect(update).toHaveBeenCalledWith('agent-1', ['web-search', 'added-by-user']);
+ expect(ensureMock).toHaveBeenCalledTimes(2);
+ });
+
+ it('abandons the write when the scope switched meanwhile', async () => {
+ const pending = deferred();
+ ensureMock.mockImplementationOnce(() => pending.promise);
+ // the new scope gets its own attempt, which has nothing to remove
+ ensureMock.mockImplementation(async () => []);
+ const { rerender } = renderHook((input) => useStalePluginAutoResolve(input), {
+ initialProps: hookInput(),
+ });
+ await settle();
+
+ rerender(hookInput({ plugins: live, scope: 'user-1:workspace-1' }));
+ pending.resolve(notSkill('ghost-tool'));
+ await settle();
+
+ expect(update).not.toHaveBeenCalled();
+ });
+
+ // Same workspace (here: personal mode), another signed-in user: the cache
+ // scope carries the user id, so the old response must not land.
+ it.each([
+ ['rendered', true],
+ ['not rendered yet', false],
+ ])(
+ 'abandons the write when another user signed in on the same workspace (%s)',
+ async (_, rendered) => {
+ const pending = deferred();
+ ensureMock.mockImplementationOnce(() => pending.promise);
+ // the new scope gets its own attempt, which has nothing to remove
+ ensureMock.mockImplementation(async () => []);
+ const { rerender } = renderHook((input) => useStalePluginAutoResolve(input), {
+ initialProps: hookInput(),
+ });
+ await settle();
+
+ const plugins = live;
+ if (rendered) rerender(hookInput({ plugins, scope: 'user-2:personal' }));
+ else liveScope = 'user-2:personal';
+ pending.resolve(notSkill('ghost-tool'));
+ await settle();
+
+ expect(update).not.toHaveBeenCalled();
+ },
+ );
+
+ it('abandons the write when edit permission is lost meanwhile', async () => {
+ const pending = deferred();
+ ensureMock.mockImplementationOnce(() => pending.promise);
+ const { rerender } = renderHook((input) => useStalePluginAutoResolve(input), {
+ initialProps: hookInput(),
+ });
+ await settle();
+
+ rerender(hookInput({ canEditResource: false, plugins: live }));
+ pending.resolve(notSkill('ghost-tool'));
+ await settle();
+
+ expect(update).not.toHaveBeenCalled();
+ });
+
+ it('abandons the write when the profile is closed meanwhile', async () => {
+ const pending = deferred();
+ ensureMock.mockImplementationOnce(() => pending.promise);
+ const { unmount } = renderHook(() => useStalePluginAutoResolve(hookInput()));
+ await settle();
+
+ unmount();
+ pending.resolve(notSkill('ghost-tool'));
+ await settle();
+
+ expect(update).not.toHaveBeenCalled();
+ });
+});
+
describe('selectProfileToolCatalogsSynced', () => {
type Source = 'local' | 'server' | 'storage';
diff --git a/src/features/ProfileEditor/staleProfilePlugins.ts b/src/features/ProfileEditor/staleProfilePlugins.ts
index 6741d023077..e13132aaa1b 100644
--- a/src/features/ProfileEditor/staleProfilePlugins.ts
+++ b/src/features/ProfileEditor/staleProfilePlugins.ts
@@ -1,7 +1,12 @@
import { type AgentPluginEntry, parsePluginEntry } from '@lobechat/types';
+import isEqual from 'fast-deep-equal';
+import { useEffect, useRef } from 'react';
+import { useSingleton } from '@/hooks/useSingleton';
+import { ensureAgentMarketSkills } from '@/services/ensureAgentMarketSkills';
+import type { EnsureMarketSkillResult } from '@/services/skill';
import type { ToolStoreState } from '@/store/tool/initialState';
-import { AGENT_SKILL_LIST_KEY } from '@/store/tool/slices/agentSkills/projection';
+import { agentSkillsSelectors } from '@/store/tool/slices/agentSkills/selectors';
import { UNINSTALLED_BUILTIN_TOOLS_KEY } from '@/store/tool/slices/builtin/projection';
import { CONNECTOR_LIST_KEY } from '@/store/tool/slices/connector/projection';
import { INSTALLED_PLUGINS_KEY } from '@/store/tool/slices/plugin/projection';
@@ -20,7 +25,7 @@ export const selectProfileToolCatalogsSynced = (s: ToolStoreState): boolean =>
s.installedPluginsReplica.entries[INSTALLED_PLUGINS_KEY]?.source === 'server' &&
s.connectorsReplica.entries[CONNECTOR_LIST_KEY]?.source === 'server' &&
s.uninstalledBuiltinToolsReplica.entries[UNINSTALLED_BUILTIN_TOOLS_KEY]?.source === 'server' &&
- s.agentSkillListReplica.entries[AGENT_SKILL_LIST_KEY]?.source === 'server';
+ agentSkillsSelectors.isAgentSkillListSynced(s);
export interface StalePluginCleanupInput {
/**
@@ -57,20 +62,16 @@ export interface StalePluginCleanupInput {
}
/**
- * Decide whether the agent profile should silently drop plugin entries whose
- * identifier no longer resolves to any known tool, and to what.
- *
- * Returns the cleaned list when a write is warranted, or `null` to leave the
- * config alone.
- *
- * The permission inputs matter as much as the staleness ones (automatic corrections must not trigger phantom save-error toasts): this
- * cleanup is automatic, so in a workspace a caller without resource edit access
- * would fire an `agent.updateAgentConfig` the server rejects — and because the
- * rejected write never persists, it would fire and fail again on *every* open,
- * surfacing "Failed to save agent settings" on an agent the user only viewed.
- * Fail closed while access is still resolving.
+ * Whether the automatic cleanup may touch this agent's plugins at all. The
+ * permission inputs matter as much as the staleness ones (automatic corrections
+ * must not trigger phantom save-error toasts): this cleanup is automatic, so in
+ * a workspace a caller without resource edit access would fire an
+ * `agent.updateAgentConfig` the server rejects — and because the rejected write
+ * never persists, it would fire and fail again on *every* open, surfacing
+ * "Failed to save agent settings" on an agent the user only viewed. Fail closed
+ * while access is still resolving.
*/
-export const resolveStalePluginCleanup = ({
+const isCleanupAllowed = ({
canEditContent,
canEditResource,
isAccessResolved,
@@ -78,22 +79,159 @@ export const resolveStalePluginCleanup = ({
isToolCatalogSynced,
plugins,
validIdentifiers,
-}: StalePluginCleanupInput): AgentPluginEntry[] | null => {
- if (!canEditContent || !isAccessResolved || !canEditResource) return null;
- if (!isConnectorsInit || !isToolCatalogSynced) return null;
- if (validIdentifiers.size === 0) return null;
+}: StalePluginCleanupInput): boolean => {
+ if (!canEditContent || !isAccessResolved || !canEditResource) return false;
+ if (!isConnectorsInit || !isToolCatalogSynced) return false;
+ if (validIdentifiers.size === 0) return false;
+ return (plugins ?? []).length > 0;
+};
+
+/**
+ * Identifiers of the plugin entries that do not resolve to any known tool, or
+ * `[]` when the gates in `isCleanupAllowed` are not all satisfied. Entries are
+ * checked by identifier regardless of shape or mode, so a disabled or pinned
+ * object entry counts like a legacy string one.
+ *
+ * These are what the server is asked about before anything is removed: an
+ * unresolved identifier may be a Market skill the agent references that is not
+ * installed yet.
+ */
+export const resolveUnresolvedPluginIds = (input: StalePluginCleanupInput): string[] => {
+ if (!isCleanupAllowed(input)) return [];
+
+ const unresolved = new Set<string>();
+ for (const entry of input.plugins ?? []) {
+ const { identifier } = parsePluginEntry(entry);
+ if (!input.validIdentifiers.has(identifier)) unresolved.add(identifier);
+ }
+ return [...unresolved];
+};
+
+/**
+ * Decide whether the agent profile should drop plugin entries, and to what.
+ *
+ * An unresolved entry is removed only when the server positively said it is not
+ * a Market skill (`notSkill`). Installed, skipped, failed and unreported
+ * entries stay: a failed download must not delete a valid skill binding.
+ * Surviving entries keep their original shape, mode and order (lazy per-item
+ * upgrade; a disabled entry is never re-enabled).
+ *
+ * Returns the cleaned list when a write is warranted, or `null` to leave the
+ * config alone. The same gates are re-checked here, so a caller that evaluates
+ * this after an `await` also fails closed on a permission lost meanwhile.
+ */
+export const resolveStalePluginCleanup = (
+ input: StalePluginCleanupInput,
+ ensureResults: readonly EnsureMarketSkillResult[] = [],
+): AgentPluginEntry[] | null => {
+ if (!isCleanupAllowed(input)) return null;
+
+ const notSkill = new Set(
+ ensureResults.filter((result) => result.status === 'notSkill').map((r) => r.identifier),
+ );
+ if (notSkill.size === 0) return null;
+
+ const rawPlugins = input.plugins ?? [];
+ const isRemoved = (entry: AgentPluginEntry) => {
+ const { identifier } = parsePluginEntry(entry);
+ return notSkill.has(identifier) && !input.validIdentifiers.has(identifier);
+ };
+
+ if (!rawPlugins.some(isRemoved)) return null;
+
+ return rawPlugins.filter((entry) => !isRemoved(entry));
+};
+
+export interface StalePluginAutoResolveInput extends StalePluginCleanupInput {
+ agentId: string;
+ /** The agent's plugins as stored right now, read when a response comes back. */
+ getCurrentPlugins: () => AgentPluginEntry[] | undefined;
+ /**
+ * The active cache scope (user + workspace) as rendered, and as it is right
+ * now; attempts and results never cross it.
+ */
+ getScope: () => string;
+ scope: string;
+ updatePlugins: (agentId: string, plugins: AgentPluginEntry[]) => unknown;
+}
+
+/** Coalesces the burst of catalog updates that arrive together. */
+const AUTO_RESOLVE_DEBOUNCE_MS = 500;
+
+/**
+ * Self-heal an agent's plugins once the tool catalogs are complete: ask the
+ * server about unresolved identifiers (they may be uninstalled Market skills),
+ * then drop only those it says are not skills.
+ *
+ * One attempt per scope + agent, also while it is in flight. A response is
+ * applied only if the scope, agent, permissions and the plugins it was started
+ * from are all unchanged; otherwise the write is abandoned and the attempt is
+ * released so the new state gets its own.
+ */
+export const useStalePluginAutoResolve = (input: StalePluginAutoResolveInput): void => {
+ const latest = useRef(input);
+ latest.current = input;
+ const attempted = useSingleton(() => new Set<string>());
+ const mounted = useRef(true);
+
+ useEffect(() => {
+ mounted.current = true;
+ return () => {
+ mounted.current = false;
+ };
+ }, []);
+
+ const run = async () => {
+ const snapshot = latest.current;
+ const { agentId, scope } = snapshot;
+ const key = `${scope}\u0000${agentId}`;
+ if (!agentId || attempted.has(key)) return;
+
+ const unresolved = resolveUnresolvedPluginIds(snapshot);
+ if (unresolved.length === 0) return;
- const rawPlugins = plugins ?? [];
- if (rawPlugins.length === 0) return null;
+ attempted.add(key);
+ let results: EnsureMarketSkillResult[] = [];
+ try {
+ results = await ensureAgentMarketSkills(unresolved);
+ } catch {
+ // The helper does not throw; keep every entry if it somehow does.
+ }
- // Checked (and filtered) by identifier regardless of entry shape, so a stale
- // disabled/pinned object entry is pruned exactly like a stale legacy string
- // one — untouched valid entries keep their original shape (lazy per-item
- // upgrade).
- const isValid = (entry: AgentPluginEntry) =>
- validIdentifiers.has(parsePluginEntry(entry).identifier);
+ const current = latest.current;
+ const unchanged =
+ mounted.current &&
+ current.agentId === agentId &&
+ current.scope === scope &&
+ snapshot.getScope() === scope &&
+ isEqual(snapshot.getCurrentPlugins(), snapshot.plugins);
+ if (!unchanged) {
+ attempted.delete(key);
+ return;
+ }
- if (rawPlugins.every(isValid)) return null;
+ const cleaned = resolveStalePluginCleanup({ ...current, plugins: snapshot.plugins }, results);
+ if (!cleaned) return;
+ try {
+ await current.updatePlugins(agentId, cleaned);
+ } catch {
+ // Best-effort self-healing; a rejected write is retried on the next open.
+ }
+ };
- return rawPlugins.filter(isValid);
+ useEffect(() => {
+ const timer = setTimeout(() => void run(), AUTO_RESOLVE_DEBOUNCE_MS);
+ return () => clearTimeout(timer);
+ // `run` only reads refs; the inputs below are what should re-evaluate it.
+ }, [
+ input.agentId,
+ input.scope,
+ input.plugins,
+ input.validIdentifiers,
+ input.canEditContent,
+ input.canEditResource,
+ input.isAccessResolved,
+ input.isConnectorsInit,
+ input.isToolCatalogSynced,
+ ]);
};
diff --git a/src/routes/(main)/community/(detail)/agent/features/Sidebar/ActionButton/ForkAndChat.test.tsx b/src/routes/(main)/community/(detail)/agent/features/Sidebar/ActionButton/ForkAndChat.test.tsx
new file mode 100644
index 00000000000..842d8f42e32
--- /dev/null
+++ b/src/routes/(main)/community/(detail)/agent/features/Sidebar/ActionButton/ForkAndChat.test.tsx
@@ -0,0 +1,130 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import type * as I18nextModule from 'i18next';
+import type { ReactNode } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { agentService } from '@/services/agent';
+import { marketApiService } from '@/services/marketApi';
+import { agentSkillService } from '@/services/skill';
+import { useToolStore } from '@/store/tool';
+
+import ForkAndChat from './ForkAndChat';
+
+const mocks = vi.hoisted(() => ({
+ createAgent: vi.fn(),
+ navigate: vi.fn(),
+ refreshAgentList: vi.fn(),
+ toast: { error: vi.fn(), info: vi.fn(), success: vi.fn(), warning: vi.fn() },
+}));
+
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+vi.mock('i18next', async (importOriginal) => ({
+ ...(await importOriginal<typeof I18nextModule>()),
+ t: (key: string, options?: { skills?: string }) => `${key}: ${options?.skills}`,
+}));
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ Button: ({ children, onClick }: { children: ReactNode; onClick?: () => void }) => (
+ <button onClick={onClick}>{children}</button>
+ ),
+ createStaticStyles: () => ({}),
+ Flexbox: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ Select: () => null,
+ toast: mocks.toast,
+}));
+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
+ getActiveWorkspaceId: () => null,
+ useActiveWorkspaceId: () => null,
+}));
+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
+ useWorkspaceAwareNavigate: () => mocks.navigate,
+}));
+vi.mock('@/hooks/usePermission', () => ({ usePermission: () => ({ allowed: true }) }));
+vi.mock('@/layout/AuthProvider/MarketAuth', () => ({
+ useMarketAuth: () => ({ isAuthenticated: true, signIn: vi.fn() }),
+}));
+vi.mock('@/services/discover', () => ({ discoverService: { reportAgentEvent: vi.fn() } }));
+vi.mock('@/store/agent', () => ({
+ useAgentStore: (selector: (s: object) => unknown) => selector({ createAgent: mocks.createAgent }),
+}));
+vi.mock('@/store/home', () => ({
+ useHomeStore: (selector: (s: object) => unknown) =>
+ selector({ refreshAgentList: mocks.refreshAgentList }),
+}));
+vi.mock('../../DetailProvider', () => ({
+ useDetailContext: () => ({
+ config: { params: {}, plugins: ['skill-a', { identifier: 'skill-b', mode: 'disabled' }] },
+ identifier: 'source-agent',
+ title: 'Source Agent',
+ }),
+}));
+
+describe('ForkAndChat market skills', () => {
+ beforeEach(() => {
+ vi.restoreAllMocks();
+ Object.values(mocks.toast).forEach((fn) => fn.mockReset());
+ mocks.navigate.mockReset();
+ mocks.createAgent.mockReset().mockResolvedValue({ agentId: 'new-agent' });
+ mocks.refreshAgentList.mockReset().mockResolvedValue(undefined);
+ vi.spyOn(agentService, 'getAgentByForkedFromIdentifier').mockResolvedValue(null);
+ vi.spyOn(marketApiService, 'forkAgent').mockResolvedValue([
+ { data: { agent: { identifier: 'forked', name: 'Forked' } }, success: true },
+ ] as any);
+ vi.spyOn(useToolStore, 'getState').mockReturnValue({
+ ...useToolStore.getState(),
+ refreshAgentSkills: vi.fn().mockResolvedValue(undefined),
+ });
+ });
+
+ const fork = async () => {
+ render(<ForkAndChat />);
+ fireEvent.click(screen.getByText('fork.forkAndChat'));
+ await waitFor(() => expect(mocks.navigate).toHaveBeenCalled());
+ };
+
+ it('installs the referenced skills after creating the agent, without warning on success', async () => {
+ const ensure = vi.spyOn(agentSkillService, 'ensureFromMarket').mockResolvedValue([
+ { identifier: 'skill-a', status: 'installed' },
+ { identifier: 'skill-b', status: 'notSkill' },
+ ]);
+
+ await fork();
+
+ expect(ensure).toHaveBeenCalledWith(['skill-a', 'skill-b']);
+ expect(ensure.mock.invocationCallOrder[0]).toBeGreaterThan(
+ mocks.createAgent.mock.invocationCallOrder[0],
+ );
+ expect(mocks.toast.warning).not.toHaveBeenCalled();
+ expect(mocks.toast.success).toHaveBeenCalledWith('fork.success');
+ });
+
+ it('still reports success and navigates when installing skills fails outright', async () => {
+ vi.spyOn(agentSkillService, 'ensureFromMarket').mockRejectedValue(new Error('network down'));
+
+ await fork();
+
+ expect(mocks.navigate).toHaveBeenCalledWith(expect.stringContaining('new-agent'));
+ expect(mocks.toast.success).toHaveBeenCalledWith('fork.success');
+ expect(mocks.toast.error).not.toHaveBeenCalled();
+ expect(mocks.toast.warning).toHaveBeenCalledTimes(1);
+ expect(mocks.toast.warning.mock.calls[0][0]).toContain('skill-a');
+ });
+
+ it('warns only about failed skills, not about notSkill ones', async () => {
+ vi.spyOn(agentSkillService, 'ensureFromMarket').mockResolvedValue([
+ { identifier: 'skill-a', reason: 'download', status: 'failed' },
+ { identifier: 'skill-b', status: 'notSkill' },
+ ]);
+
+ await fork();
+
+ expect(mocks.toast.warning).toHaveBeenCalledTimes(1);
+ const message = mocks.toast.warning.mock.calls[0][0] as string;
+ expect(message).toContain('skill-a');
+ expect(message).not.toContain('skill-b');
+ expect(mocks.toast.error).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/routes/(main)/community/(detail)/agent/features/Sidebar/ActionButton/ForkAndChat.tsx b/src/routes/(main)/community/(detail)/agent/features/Sidebar/ActionButton/ForkAndChat.tsx
index b23ed77b550..416d5319aa7 100644
--- a/src/routes/(main)/community/(detail)/agent/features/Sidebar/ActionButton/ForkAndChat.tsx
+++ b/src/routes/(main)/community/(detail)/agent/features/Sidebar/ActionButton/ForkAndChat.tsx
@@ -13,6 +13,7 @@ import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';
import { lambdaClient } from '@/libs/trpc/client';
import { agentService } from '@/services/agent';
import { discoverService } from '@/services/discover';
+import { ensureAgentMarketSkillsAndWarn } from '@/services/ensureAgentMarketSkills';
import { marketApiService } from '@/services/marketApi';
import { useAgentStore } from '@/store/agent';
import { useHomeStore } from '@/store/home';
@@ -200,7 +201,11 @@ const ForkAndChat = memo<{ mobile?: boolean }>(({ mobile }) => {
toast.success(t('fork.success'));
- // Step 6: Navigate to chat
+ // Step 6: Install the Market skills the agent references. The agent already
+ // exists, so this never throws and only ever adds a non-blocking warning.
+ await ensureAgentMarketSkillsAndWarn(config.plugins);
+
+ // Step 7: Navigate to chat
navigate(AGENT_CHAT_URL(result!.agentId, mobile));
} catch (error: any) {
console.error('Fork failed:', error);
diff --git a/src/services/chat/mecha/skillEngineering.test.ts b/src/services/chat/mecha/skillEngineering.test.ts
index afa803b0138..822ed3645c5 100644
--- a/src/services/chat/mecha/skillEngineering.test.ts
+++ b/src/services/chat/mecha/skillEngineering.test.ts
@@ -43,6 +43,7 @@ const setToolState = (state: any) => {
),
agentSkillListMap: { all: agentSkills },
builtinSkills: [],
+ ensureAgentSkillsLoaded: vi.fn(),
...rest,
} as any);
};
@@ -215,6 +216,36 @@ describe('resolveClientSkills', () => {
expect(findSkill(result.skills, 'lobehub')).toMatchObject({ activated: false });
});
+ describe('agent skill list loading', () => {
+ const dbSkill = { description: 'Bound', id: 'db-1', identifier: 'bound-skill', name: 'Bound' };
+
+ it('loads the skill list before assembling the pool, so a send right after a page load sees DB skills', async () => {
+ const state: any = { agentSkillListMap: {}, agentSkillDetailMap: {}, builtinSkills: [] };
+ state.ensureAgentSkillsLoaded = vi.fn(async () => {
+ state.agentSkillListMap = { all: [dbSkill] };
+ });
+ mockedGetToolStoreState.mockReturnValue(state);
+
+ const result = await resolveClientSkills();
+
+ expect(state.ensureAgentSkillsLoaded).toHaveBeenCalledTimes(1);
+ expect(findSkill(result.skills, 'bound-skill')).toMatchObject({ name: 'Bound' });
+ });
+
+ it('still assembles the pool when the skill list fails to load', async () => {
+ setToolState({
+ builtinSkills: [
+ { content: 'guide', description: 'd', identifier: 'artifacts', name: 'Artifacts' },
+ ],
+ ensureAgentSkillsLoaded: vi.fn().mockRejectedValue(new Error('network down')),
+ });
+
+ const result = await resolveClientSkills();
+
+ expect(findSkill(result.skills, 'artifacts')).toBeDefined();
+ });
+ });
+
describe('disabled skills', () => {
it('excludes a disabled DB skill entirely, not just from the pinned set', async () => {
setToolState({
diff --git a/src/services/chat/mecha/skillEngineering.ts b/src/services/chat/mecha/skillEngineering.ts
index f91840ad731..eb6dcb0ebd6 100644
--- a/src/services/chat/mecha/skillEngineering.ts
+++ b/src/services/chat/mecha/skillEngineering.ts
@@ -49,6 +49,15 @@ export const resolveClientSkills = async (
/** Selectable for this turn even in manual mode, without being pinned. */
turnSkillIds?: string[],
): Promise<OperationSkillSet> => {
+ // The list is only fetched by mounted views (tool popover, side panel), so a
+ // send right after a page load would otherwise see no DB skills. A failed
+ // load must not block the send; fall back to whatever the store holds.
+ try {
+ await getToolStoreState().ensureAgentSkillsLoaded();
+ } catch (error) {
+ log('Failed to load agent skills before building the skill pool: %O', error);
+ }
+
const toolState = getToolStoreState();
const pinnedIds = new Set(pluginIds ?? []);
const disabledIdSet = new Set(disabledIds ?? []);
diff --git a/src/services/ensureAgentMarketSkills.test.ts b/src/services/ensureAgentMarketSkills.test.ts
new file mode 100644
index 00000000000..df311bafb98
--- /dev/null
+++ b/src/services/ensureAgentMarketSkills.test.ts
@@ -0,0 +1,282 @@
+import { getConnectorCatalog } from '@lobechat/const';
+import { toast } from '@lobehub/ui';
+import type * as I18nextModule from 'i18next';
+import { beforeEach, describe, expect, it, type MockInstance, vi } from 'vitest';
+
+import { agentSkillService, type EnsureMarketSkillResult } from '@/services/skill';
+import { initialState } from '@/store/tool/initialState';
+import { builtinToolSelectors } from '@/store/tool/selectors';
+import {
+ AGENT_SKILL_LIST_KEY,
+ agentSkillListResource,
+} from '@/store/tool/slices/agentSkills/projection';
+import { useToolStore } from '@/store/tool/store';
+
+import {
+ ensureAgentMarketSkills,
+ ensureAgentMarketSkillsAndWarn,
+ MARKET_SKILL_ENSURE_BATCH_SIZE,
+} from './ensureAgentMarketSkills';
+
+vi.mock('i18next', async (importOriginal) => ({
+ ...(await importOriginal<typeof I18nextModule>()),
+ t: (key: string, options?: { skills?: string }) => `${key}: ${options?.skills}`,
+}));
+
+const installedAll = (ids: string[]): EnsureMarketSkillResult[] =>
+ ids.map((identifier) => ({ identifier, status: 'installed' }));
+
+const builtinToolId = builtinToolSelectors.installedAllMetaList(initialState)[0].identifier;
+const connectorItem = getConnectorCatalog({ composio: true, lobehub: true })[0];
+const connectorId =
+ connectorItem.type === 'lobehub'
+ ? connectorItem.provider.id
+ : connectorItem.serverType.identifier;
+
+describe('ensureAgentMarketSkills', () => {
+ const refreshAgentSkills = vi.fn();
+ let ensureFromMarket: MockInstance<typeof agentSkillService.ensureFromMarket>;
+
+ /** `listSource` is where the skills list came from: the server, or the persisted copy. */
+ const mockCatalog = (
+ skills: { identifier: string; source: 'market' | 'user' }[] = [],
+ listSource: 'server' | 'storage' = 'server',
+ ) => {
+ vi.spyOn(useToolStore, 'getState').mockReturnValue({
+ ...initialState,
+ agentSkillListMap: { [AGENT_SKILL_LIST_KEY]: skills },
+ agentSkillListReplica: {
+ ...initialState.agentSkillListReplica,
+ entries: {
+ [AGENT_SKILL_LIST_KEY]: { pending: [], source: listSource, updatedAt: 1 },
+ },
+ },
+ refreshAgentSkills,
+ } as unknown as ReturnType<typeof useToolStore.getState>);
+ };
+
+ beforeEach(() => {
+ vi.restoreAllMocks();
+ refreshAgentSkills.mockReset();
+ refreshAgentSkills.mockResolvedValue(undefined);
+ ensureFromMarket = vi
+ .spyOn(agentSkillService, 'ensureFromMarket')
+ .mockImplementation(async (ids) => installedAll(ids));
+ mockCatalog();
+ });
+
+ it('sends no request for empty input', async () => {
+ expect(await ensureAgentMarketSkills(undefined)).toEqual([]);
+ expect(await ensureAgentMarketSkills([])).toEqual([]);
+ expect(await ensureAgentMarketSkills([[], undefined as any])).toEqual([]);
+ expect(ensureFromMarket).not.toHaveBeenCalled();
+ expect(refreshAgentSkills).not.toHaveBeenCalled();
+ });
+
+ it('reads identifiers from string and object entries, including disabled ones', async () => {
+ await ensureAgentMarketSkills([
+ 'skill-a',
+ { identifier: 'skill-b', mode: 'disabled' },
+ { identifier: 'skill-c' },
+ ]);
+
+ expect(ensureFromMarket).toHaveBeenCalledWith(['skill-a', 'skill-b', 'skill-c']);
+ });
+
+ it('merges and dedupes plugins across several agents into one request', async () => {
+ await ensureAgentMarketSkills([
+ ['skill-a', 'skill-b'],
+ [{ identifier: 'skill-a' }, 'skill-c'],
+ ]);
+
+ expect(ensureFromMarket).toHaveBeenCalledTimes(1);
+ expect(ensureFromMarket).toHaveBeenCalledWith(['skill-a', 'skill-b', 'skill-c']);
+ });
+
+ it('leaves out what the local catalog already resolves', async () => {
+ mockCatalog([
+ { identifier: 'installed-market', source: 'market' },
+ { identifier: 'my-own-skill', source: 'user' },
+ ]);
+
+ await ensureAgentMarketSkills([
+ builtinToolId,
+ connectorId,
+ 'installed-market',
+ 'my-own-skill',
+ 'fresh-skill',
+ ]);
+
+ // a same-named skill from another source still goes to the server, which
+ // reports the conflict instead of silently overwriting it
+ expect(ensureFromMarket).toHaveBeenCalledWith(['my-own-skill', 'fresh-skill']);
+ });
+
+ it('still asks the server about installed Market skills while the list is only the persisted copy', async () => {
+ // A hydrated list can predate a skill installed elsewhere; the server is
+ // idempotent and answers `installed` for the ones already there.
+ mockCatalog([{ identifier: 'installed-market', source: 'market' }], 'storage');
+
+ await ensureAgentMarketSkills(['installed-market', 'fresh-skill']);
+
+ expect(ensureFromMarket).toHaveBeenCalledWith(['installed-market', 'fresh-skill']);
+ });
+
+ it('sends nothing when every identifier is already resolved locally', async () => {
+ expect(await ensureAgentMarketSkills([builtinToolId, connectorId])).toEqual([]);
+ expect(ensureFromMarket).not.toHaveBeenCalled();
+ });
+
+ it('splits more than 50 identifiers into ordered batches', async () => {
+ const ids = Array.from({ length: MARKET_SKILL_ENSURE_BATCH_SIZE * 2 + 20 }, (_, i) => `s-${i}`);
+
+ const results = await ensureAgentMarketSkills(ids);
+
+ expect(ensureFromMarket.mock.calls.map(([batch]) => batch.length)).toEqual([50, 50, 20]);
+ expect(results.map((r) => r.identifier)).toEqual(ids);
+ });
+
+ it('stops sending batches once the scope changed, and does not refresh the new scope', async () => {
+ let scope = 'user-1:personal';
+ vi.spyOn(agentSkillListResource.scope, 'get').mockImplementation(() => scope);
+ ensureFromMarket.mockImplementationOnce(async (ids) => {
+ // the user switches workspace while the first batch is in flight
+ scope = 'user-1:workspace-2';
+ return installedAll(ids);
+ });
+ const ids = Array.from({ length: 120 }, (_, i) => `s-${i}`);
+
+ const results = await ensureAgentMarketSkills(ids);
+
+ expect(ensureFromMarket).toHaveBeenCalledTimes(1);
+ expect(results.slice(0, 50).every((r) => r.status === 'installed')).toBe(true);
+ expect(results.slice(50)).toHaveLength(70);
+ expect(
+ results.slice(50).every((r) => r.status === 'failed' && r.reason === 'unavailable'),
+ ).toBe(true);
+ expect(refreshAgentSkills).not.toHaveBeenCalled();
+ });
+
+ it('refreshes the list when the scope never changed', async () => {
+ vi.spyOn(agentSkillListResource.scope, 'get').mockReturnValue('user-1:personal');
+
+ await ensureAgentMarketSkills(['skill-a']);
+
+ expect(refreshAgentSkills).toHaveBeenCalledTimes(1);
+ });
+
+ it('turns a rejected request into unavailable results without throwing', async () => {
+ ensureFromMarket.mockRejectedValueOnce(new Error('network down'));
+
+ const results = await ensureAgentMarketSkills(['skill-a', 'skill-b']);
+
+ expect(results).toEqual([
+ { identifier: 'skill-a', message: 'network down', reason: 'unavailable', status: 'failed' },
+ { identifier: 'skill-b', message: 'network down', reason: 'unavailable', status: 'failed' },
+ ]);
+ expect(refreshAgentSkills).not.toHaveBeenCalled();
+ });
+
+ it('keeps later batches running when an earlier batch fails', async () => {
+ ensureFromMarket.mockRejectedValueOnce(new Error('boom'));
+ const ids = Array.from({ length: 51 }, (_, i) => `s-${i}`);
+
+ const results = await ensureAgentMarketSkills(ids);
+
+ expect(results.filter((r) => r.status === 'failed')).toHaveLength(50);
+ expect(results[50]).toEqual({ identifier: 's-50', status: 'installed' });
+ });
+
+ it('reports identifiers the server left out of its answer as unavailable', async () => {
+ ensureFromMarket.mockResolvedValueOnce(installedAll(['skill-a']));
+
+ const results = await ensureAgentMarketSkills(['skill-a', 'skill-b']);
+
+ expect(results[1]).toMatchObject({
+ identifier: 'skill-b',
+ reason: 'unavailable',
+ status: 'failed',
+ });
+ });
+
+ it('treats a malformed response as unavailable', async () => {
+ ensureFromMarket.mockResolvedValueOnce(undefined as any);
+
+ const results = await ensureAgentMarketSkills(['skill-a']);
+
+ expect(results).toMatchObject([{ identifier: 'skill-a', reason: 'unavailable' }]);
+ });
+
+ it('refreshes the skill list once after installs, whatever the batch count', async () => {
+ await ensureAgentMarketSkills(Array.from({ length: 70 }, (_, i) => `s-${i}`));
+
+ expect(refreshAgentSkills).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not refresh when nothing got installed', async () => {
+ ensureFromMarket.mockResolvedValueOnce([{ identifier: 'skill-a', status: 'notSkill' }]);
+
+ await ensureAgentMarketSkills(['skill-a']);
+
+ expect(refreshAgentSkills).not.toHaveBeenCalled();
+ });
+
+ it('keeps the install results when refreshing the list fails', async () => {
+ refreshAgentSkills.mockRejectedValue(new Error('list failed'));
+
+ expect(await ensureAgentMarketSkills(['skill-a'])).toEqual([
+ { identifier: 'skill-a', status: 'installed' },
+ ]);
+ });
+
+ it('never throws, even when reading the local catalog fails', async () => {
+ vi.spyOn(useToolStore, 'getState').mockImplementation(() => {
+ throw new Error('store broken');
+ });
+
+ expect(await ensureAgentMarketSkills(['skill-a'])).toEqual([
+ expect.objectContaining({ identifier: 'skill-a', reason: 'unavailable', status: 'failed' }),
+ ]);
+ });
+});
+
+describe('ensureAgentMarketSkillsAndWarn', () => {
+ let warning: MockInstance<typeof toast.warning>;
+
+ beforeEach(() => {
+ vi.restoreAllMocks();
+ warning = vi.spyOn(toast, 'warning').mockImplementation(() => '' as any);
+ vi.spyOn(useToolStore, 'getState').mockReturnValue({
+ ...initialState,
+ refreshAgentSkills: vi.fn().mockResolvedValue(undefined),
+ } as unknown as ReturnType<typeof useToolStore.getState>);
+ });
+
+ it('shows one merged warning listing only the failed identifiers', async () => {
+ vi.spyOn(agentSkillService, 'ensureFromMarket').mockResolvedValue([
+ { identifier: 'ok', status: 'installed' },
+ { identifier: 'tool-id', status: 'notSkill' },
+ { identifier: 'bad-1', reason: 'download', status: 'failed' },
+ { identifier: 'bad-2', reason: 'conflict', status: 'failed' },
+ ]);
+
+ await ensureAgentMarketSkillsAndWarn(['ok', 'tool-id', 'bad-1', 'bad-2']);
+
+ expect(warning).toHaveBeenCalledTimes(1);
+ const message = String(warning.mock.calls[0][0]);
+ expect(message).toContain('bad-1');
+ expect(message).toContain('bad-2');
+ expect(message).not.toContain('tool-id');
+ });
+
+ it('stays quiet when nothing failed', async () => {
+ vi.spyOn(agentSkillService, 'ensureFromMarket').mockResolvedValue([
+ { identifier: 'a', status: 'installed' },
+ { identifier: 'b', status: 'notSkill' },
+ ]);
+
+ await ensureAgentMarketSkillsAndWarn(['a', 'b']);
+
+ expect(warning).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/services/ensureAgentMarketSkills.ts b/src/services/ensureAgentMarketSkills.ts
new file mode 100644
index 00000000000..e813ad3518a
--- /dev/null
+++ b/src/services/ensureAgentMarketSkills.ts
@@ -0,0 +1,169 @@
+import { getConnectorCatalog } from '@lobechat/const';
+import { type AgentPluginEntry, parsePluginEntry } from '@lobechat/types';
+import { toast } from '@lobehub/ui';
+import { t } from 'i18next';
+
+import { agentSkillService, type EnsureMarketSkillResult } from '@/services/skill';
+import { useToolStore } from '@/store/tool';
+import {
+ agentSkillsSelectors,
+ builtinToolSelectors,
+ pluginSelectors,
+} from '@/store/tool/selectors';
+import { agentSkillListResource } from '@/store/tool/slices/agentSkills/projection';
+import { connectorSelectors } from '@/store/tool/slices/connector';
+
+/** The server accepts at most this many identifiers per `ensureFromMarket` call. */
+export const MARKET_SKILL_ENSURE_BATCH_SIZE = 50;
+
+type EnsureFailure = Extract<EnsureMarketSkillResult, { status: 'failed' }>;
+
+export type AgentPluginsInput = AgentPluginEntry[] | AgentPluginEntry[][] | null | undefined;
+
+const unavailable = (identifier: string, error?: unknown): EnsureFailure => ({
+ identifier,
+ ...(error instanceof Error && error.message ? { message: error.message } : {}),
+ reason: 'unavailable',
+ status: 'failed',
+});
+
+/** Identifiers of every agent's plugin entries (any mode), first-seen order, deduped. */
+const collectIdentifiers = (input: AgentPluginsInput): string[] => {
+ const identifiers = new Set<string>();
+ const visit = (entry: AgentPluginEntry | AgentPluginsInput) => {
+ if (Array.isArray(entry)) return entry.forEach(visit);
+ if (!entry) return;
+ const { identifier } = parsePluginEntry(entry);
+ const trimmed = identifier?.trim();
+ if (trimmed) identifiers.add(trimmed);
+ };
+ visit(input);
+ return [...identifiers];
+};
+
+/**
+ * Identifiers the local catalog already resolves to something that is not a
+ * Market skill to install: builtin tools and skills, installed plugins,
+ * connectors and, once the skills list is server-confirmed, installed Market
+ * skills (a list hydrated from the persisted copy can miss what was installed
+ * elsewhere, and the server answers `installed` for those anyway). A same-named skill from another
+ * source is deliberately not listed — the server reports it as a conflict.
+ */
+const getResolvedIdentifiers = (): Set<string> => {
+ const state = useToolStore.getState();
+ const resolved = new Set<string>();
+
+ for (const tool of builtinToolSelectors.installedAllMetaList(state))
+ resolved.add(tool.identifier);
+ for (const skill of builtinToolSelectors.installedBuiltinSkills(state)) {
+ resolved.add(skill.identifier);
+ }
+ for (const plugin of pluginSelectors.installedPluginMetaList(state)) {
+ resolved.add(plugin.identifier);
+ }
+ for (const connector of connectorSelectors.customConnectors(state)) {
+ resolved.add(connector.identifier);
+ }
+ // Catalog membership does not depend on which providers this deployment enables.
+ for (const item of getConnectorCatalog({ composio: true, lobehub: true })) {
+ resolved.add(item.type === 'lobehub' ? item.provider.id : item.serverType.identifier);
+ }
+ if (agentSkillsSelectors.isAgentSkillListSynced(state)) {
+ for (const skill of agentSkillsSelectors.getMarketAgentSkills(state)) {
+ resolved.add(skill.identifier);
+ }
+ }
+
+ return resolved;
+};
+
+const ensureBatch = async (identifiers: string[]): Promise<EnsureMarketSkillResult[]> => {
+ try {
+ const response = await agentSkillService.ensureFromMarket(identifiers);
+ if (!Array.isArray(response)) return identifiers.map((id) => unavailable(id));
+
+ const byIdentifier = new Map(response.map((result) => [result.identifier, result]));
+ return identifiers.map((id) => byIdentifier.get(id) ?? unavailable(id));
+ } catch (error) {
+ return identifiers.map((id) => unavailable(id, error));
+ }
+};
+
+/**
+ * Install the Market skills referenced by agent `plugins` into the active
+ * scope. Accepts one agent's plugins or several agents' (merged and deduped),
+ * and reports one result per identifier it asked the server about.
+ *
+ * It never throws: any failure becomes a `failed`/`unavailable` result, and a
+ * failed list refresh does not change the install results.
+ */
+export const ensureAgentMarketSkills = async (
+ input: AgentPluginsInput,
+): Promise<EnsureMarketSkillResult[]> => {
+ let identifiers: string[];
+ try {
+ const resolved = getResolvedIdentifiers();
+ identifiers = collectIdentifiers(input).filter((id) => !resolved.has(id));
+ } catch (error) {
+ // Without the local catalog we cannot tell what to send; report the whole set.
+ return collectIdentifiers(input).map((id) => unavailable(id, error));
+ }
+ if (identifiers.length === 0) return [];
+
+ // Every request is written into whichever scope is active when it is sent
+ // (`lambdaClient` reads the workspace per call), so the whole run stays in the
+ // scope it started under: once the identity switched, later batches are not
+ // sent and the list refresh is skipped.
+ const scope = agentSkillListResource.scope.get();
+ const isCurrentScope = () => agentSkillListResource.scope.get() === scope;
+
+ const results: EnsureMarketSkillResult[] = [];
+ for (let i = 0; i < identifiers.length; i += MARKET_SKILL_ENSURE_BATCH_SIZE) {
+ const batch = identifiers.slice(i, i + MARKET_SKILL_ENSURE_BATCH_SIZE);
+ results.push(
+ ...(isCurrentScope()
+ ? await ensureBatch(batch)
+ : batch.map((id) => unavailable(id, new Error('Workspace changed before install')))),
+ );
+ }
+
+ if (isCurrentScope() && results.some((result) => result.status === 'installed')) {
+ try {
+ await useToolStore.getState().refreshAgentSkills();
+ } catch (error) {
+ console.warn('Failed to refresh agent skills after ensuring market skills:', error);
+ }
+ }
+
+ return results;
+};
+
+/** One merged warning for the skills that could not be installed. `notSkill` is not a failure. */
+export const warnMarketSkillFailures = (results: EnsureMarketSkillResult[]): void => {
+ const failed = results.filter((result) => result.status === 'failed');
+ if (failed.length === 0) return;
+
+ toast.warning(
+ t('agentSkills.ensureFailed', {
+ ns: 'common',
+ skills: failed.map((result) => result.identifier).join(', '),
+ }),
+ );
+};
+
+/**
+ * Ensure, then warn about failures. The agent was already created by the
+ * caller, so nothing here may fail the caller.
+ */
+export const ensureAgentMarketSkillsAndWarn = async (
+ input: AgentPluginsInput,
+): Promise<EnsureMarketSkillResult[]> => {
+ try {
+ const results = await ensureAgentMarketSkills(input);
+ warnMarketSkillFailures(results);
+ return results;
+ } catch (error) {
+ console.warn('Failed to ensure market skills:', error);
+ return [];
+ }
+};
diff --git a/src/services/installMarketplaceAgents.test.ts b/src/services/installMarketplaceAgents.test.ts
index 272d8971b26..f941d3396d1 100644
--- a/src/services/installMarketplaceAgents.test.ts
+++ b/src/services/installMarketplaceAgents.test.ts
@@ -1,10 +1,13 @@
+import { toast } from '@lobehub/ui';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { agentService } from '@/services/agent';
import { discoverService } from '@/services/discover';
import { marketApiService } from '@/services/marketApi';
+import { agentSkillService } from '@/services/skill';
import { useAgentStore } from '@/store/agent';
import { useHomeStore } from '@/store/home';
+import { useToolStore } from '@/store/tool';
import { installMarketplaceAgents } from './installMarketplaceAgents';
@@ -136,4 +139,82 @@ describe('installMarketplaceAgents', () => {
expect(result.skippedAgentIds).toEqual(['src-b', 'src-c']);
expect(result.installedAgentIds).toEqual(['agent-src-a']);
});
+
+ describe('market skills referenced by the installed agents', () => {
+ const pluginsBySource: Record<string, any[]> = {
+ 'src-a': ['skill-a', { identifier: 'skill-shared', mode: 'disabled' }],
+ 'src-b': ['skill-b'],
+ 'src-c': ['skill-shared', 'skill-c'],
+ };
+
+ const arrange = (failCreateFor?: string) => {
+ vi.spyOn(agentService, 'getAgentByForkedFromIdentifier').mockResolvedValue(null);
+ vi.spyOn(discoverService, 'getAssistantDetail').mockImplementation(
+ async ({ identifier }) =>
+ ({
+ config: { params: {}, plugins: pluginsBySource[identifier] } as any,
+ identifier,
+ title: identifier,
+ }) as any,
+ );
+ vi.spyOn(marketApiService, 'forkAgent').mockImplementation(async (items) =>
+ items.map((item) => ({
+ data: { agent: { identifier: item.identifier, name: item.name ?? '' } } as any,
+ sourceIdentifier: item.sourceIdentifier,
+ success: true as const,
+ })),
+ );
+ createAgent.mockImplementation(async ({ config }: any) => {
+ if (config.params.forkedFromIdentifier === failCreateFor) throw new Error('create failed');
+ return { agentId: `agent-${config.params.forkedFromIdentifier}` };
+ });
+ vi.spyOn(useToolStore, 'getState').mockReturnValue({
+ ...useToolStore.getState(),
+ refreshAgentSkills: vi.fn().mockResolvedValue(undefined),
+ });
+ };
+
+ it('ensures once, after every createAgent settled, for the created agents only', async () => {
+ arrange('src-b');
+ const ensure = vi
+ .spyOn(agentSkillService, 'ensureFromMarket')
+ .mockImplementation(async (ids) =>
+ ids.map((id) => ({ identifier: id, status: 'installed' })),
+ );
+
+ const result = await installMarketplaceAgents(['src-a', 'src-b', 'src-c']);
+
+ expect(ensure).toHaveBeenCalledTimes(1);
+ expect(ensure).toHaveBeenCalledWith(['skill-a', 'skill-shared', 'skill-c']);
+ expect(Math.min(...ensure.mock.invocationCallOrder)).toBeGreaterThan(
+ Math.max(...createAgent.mock.invocationCallOrder),
+ );
+ expect(result.installedAgentIds).toEqual(['agent-src-a', 'agent-src-c']);
+ });
+
+ it('does not ask for skills when no agent could be created', async () => {
+ arrange('src-a');
+ const ensure = vi.spyOn(agentSkillService, 'ensureFromMarket');
+
+ await installMarketplaceAgents(['src-a']);
+
+ expect(ensure).not.toHaveBeenCalled();
+ });
+
+ it('keeps the install result and summaries when ensuring skills fails', async () => {
+ arrange();
+ vi.spyOn(agentSkillService, 'ensureFromMarket').mockRejectedValue(new Error('network down'));
+ const warning = vi.spyOn(toast, 'warning').mockImplementation(() => '' as any);
+
+ const result = await installMarketplaceAgents(['src-a', 'src-b']);
+
+ expect(result.installedAgentIds).toEqual(['agent-src-a', 'agent-src-b']);
+ expect(result.summaries.map((s) => s.installedAgentId)).toEqual([
+ 'agent-src-a',
+ 'agent-src-b',
+ ]);
+ expect(refreshAgentList).toHaveBeenCalledTimes(1);
+ expect(warning).toHaveBeenCalledTimes(1);
+ });
+ });
});
diff --git a/src/services/installMarketplaceAgents.ts b/src/services/installMarketplaceAgents.ts
index 4c652e0ba54..8f2feb096df 100644
--- a/src/services/installMarketplaceAgents.ts
+++ b/src/services/installMarketplaceAgents.ts
@@ -5,6 +5,7 @@ import { getActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspace
import { lambdaClient } from '@/libs/trpc/client';
import { agentService } from '@/services/agent';
import { discoverService } from '@/services/discover';
+import { ensureAgentMarketSkillsAndWarn } from '@/services/ensureAgentMarketSkills';
import { marketApiService } from '@/services/marketApi';
import { useAgentStore } from '@/store/agent';
import { useHomeStore } from '@/store/home';
@@ -208,6 +209,14 @@ export const installMarketplaceAgents = async (
const installedAgentIds = Array.from(installedBySource.values());
if (installedAgentIds.length > 0) {
+ // Once every createAgent has settled, install the Market skills the created
+ // agents reference in one pass. Already non-throwing, and the agents exist
+ // either way, so nothing here may change the result below.
+ await ensureAgentMarketSkillsAndWarn(
+ prepared
+ .filter((p) => installedBySource.has(p.sourceId))
+ .map((p) => p.detail.config.plugins ?? []),
+ );
await refreshAgentList();
}
diff --git a/src/services/skill/index.ts b/src/services/skill/index.ts
index 7ca6b68ed2e..331e8373dfd 100644
--- a/src/services/skill/index.ts
+++ b/src/services/skill/index.ts
@@ -39,6 +39,14 @@ class AgentSkillService {
return lambdaClient.agentSkills.importFromMarket.mutate({ identifier });
}
+ /**
+ * Make sure the Market skills an agent references are installed in the active
+ * scope. Per-identifier outcomes; a failed one never throws.
+ */
+ async ensureFromMarket(identifiers: string[]) {
+ return lambdaClient.agentSkills.ensureFromMarket.mutate({ identifiers });
+ }
+
// ===== Query =====
async getById(id: string): Promise<SkillItem | undefined> {
@@ -93,4 +101,8 @@ class AgentSkillService {
}
}
+export type EnsureMarketSkillResult = Awaited<
+ ReturnType<AgentSkillService['ensureFromMarket']>
+>[number];
+
export const agentSkillService = new AgentSkillService();
diff --git a/src/store/tool/slices/agentSkills/action.test.ts b/src/store/tool/slices/agentSkills/action.test.ts
index 30fe1583352..6940973824d 100644
--- a/src/store/tool/slices/agentSkills/action.test.ts
+++ b/src/store/tool/slices/agentSkills/action.test.ts
@@ -298,6 +298,74 @@ describe('agentSkills replicas', () => {
expect(useToolStore.getState().agentSkillListMap[AGENT_SKILL_LIST_KEY]?.[0]?.id).toBe('db-9');
});
+ describe('ensureAgentSkillsLoaded', () => {
+ it('fetches the list when it has not been loaded', async () => {
+ vi.mocked(agentSkillService.list).mockResolvedValue({ data: [skill('db-1')], total: 1 });
+
+ await act(() => useToolStore.getState().ensureAgentSkillsLoaded());
+
+ expect(agentSkillService.list).toHaveBeenCalledTimes(1);
+ expect(useToolStore.getState().agentSkillListMap[AGENT_SKILL_LIST_KEY]?.[0]?.id).toBe(
+ 'db-1',
+ );
+ });
+
+ it('does not request again once the list is loaded', async () => {
+ await seed();
+ vi.mocked(agentSkillService.list).mockClear();
+
+ await act(() => useToolStore.getState().ensureAgentSkillsLoaded());
+
+ expect(agentSkillService.list).not.toHaveBeenCalled();
+ });
+
+ it('still requests when the list only came from the persisted copy', async () => {
+ // A hydrated list can predate a skill installed on another device.
+ await agentSkillListResource.storage!.set(
+ { queryKey: LIST_STORAGE_KEY, scope },
+ { data: [skill('db-1', 'Cached')], updatedAt: 1 },
+ );
+ // The confirming request fails, so the persisted copy stays the only data.
+ vi.mocked(agentSkillService.list).mockRejectedValue(new Error('offline'));
+ const sync = renderHook(() => useToolStore((s) => s.useFetchAgentSkills)(true), {
+ wrapper,
+ });
+ await waitFor(() => expect(agentSkillService.list).toHaveBeenCalled());
+ await waitFor(() => expect(sync.result.current.isValidating).toBe(false));
+ expect(useToolStore.getState().agentSkillListMap[AGENT_SKILL_LIST_KEY]).toHaveLength(1);
+ sync.unmount();
+ vi.mocked(agentSkillService.list).mockClear();
+ vi.mocked(agentSkillService.list).mockResolvedValue({
+ data: [skill('db-1'), skill('db-2')],
+ total: 2,
+ });
+
+ await act(() => useToolStore.getState().ensureAgentSkillsLoaded());
+
+ expect(agentSkillService.list).toHaveBeenCalledTimes(1);
+ expect(useToolStore.getState().agentSkillListMap[AGENT_SKILL_LIST_KEY]).toHaveLength(2);
+ });
+
+ it('shares one request between concurrent callers', async () => {
+ vi.mocked(agentSkillService.list).mockResolvedValue({ data: [skill('db-1')], total: 1 });
+
+ await act(() =>
+ Promise.all([
+ useToolStore.getState().ensureAgentSkillsLoaded(),
+ useToolStore.getState().ensureAgentSkillsLoaded(),
+ ]),
+ );
+
+ expect(agentSkillService.list).toHaveBeenCalledTimes(1);
+ });
+
+ it('rejects when the request fails so the caller can degrade', async () => {
+ vi.mocked(agentSkillService.list).mockRejectedValue(new Error('boom'));
+
+ await expect(useToolStore.getState().ensureAgentSkillsLoaded()).rejects.toThrow('boom');
+ });
+ });
+
it('drops a refresh response that resolves after the scope switched', async () => {
let resolveList!: (value: unknown) => void;
vi.mocked(agentSkillService.list).mockImplementation(
diff --git a/src/store/tool/slices/agentSkills/action.ts b/src/store/tool/slices/agentSkills/action.ts
index 460806dc7b2..eade22da925 100644
--- a/src/store/tool/slices/agentSkills/action.ts
+++ b/src/store/tool/slices/agentSkills/action.ts
@@ -28,6 +28,7 @@ import {
type AgentSkillListItem,
agentSkillListResource,
} from './projection';
+import { agentSkillsSelectors } from './selectors';
/** The skills list has a single entry; its params carry no filter. */
const LIST_PARAMS = {} as Record<string, never>;
@@ -57,12 +58,14 @@ export const createAgentSkillsSlice = (set: Setter, get: () => ToolStore, _api?:
export class AgentSkillsActionImpl {
readonly #detail;
+ readonly #get: () => ToolStore;
readonly #list;
/** One skill lives in the list row and in every loaded detail entry. */
readonly #skill;
constructor(set: Setter, get: () => ToolStore, _api?: unknown) {
void _api;
+ this.#get = get;
this.#list = createReplicaSlice(agentSkillListResource, {
actionPrefix: 'agentSkillList',
entity: agentSkillListEntity,
@@ -162,6 +165,19 @@ export class AgentSkillsActionImpl {
return result;
};
+ /**
+ * Make sure the installed skills list is in the store, for callers that need
+ * it while no list view is mounted (assembling a chat request right after a
+ * page load). A list the server has confirmed is not requested again, while
+ * one hydrated from the persisted copy is: it can miss a skill installed on
+ * another device. A request in flight is joined. Rejects when the fetch fails; callers decide whether that is
+ * fatal.
+ */
+ ensureAgentSkillsLoaded = async (): Promise<void> => {
+ if (agentSkillsSelectors.isAgentSkillListSynced(this.#get())) return;
+ await this.#list.fetch(LIST_PARAMS);
+ };
+
refreshAgentSkills = async (): Promise<void> => {
await this.#refreshList();
};
diff --git a/src/store/tool/slices/agentSkills/selectors.ts b/src/store/tool/slices/agentSkills/selectors.ts
index 0c4329c183f..ad37a4d4564 100644
--- a/src/store/tool/slices/agentSkills/selectors.ts
+++ b/src/store/tool/slices/agentSkills/selectors.ts
@@ -10,6 +10,14 @@ import {
const getAgentSkills = (s: ToolStoreState): AgentSkillListItem[] =>
s.agentSkillListMap?.[AGENT_SKILL_LIST_KEY] || [];
+/**
+ * Whether the installed skills list holds the server's answer. The replica also
+ * hydrates from IndexedDB, and that copy can predate a skill installed on
+ * another device, so a populated list alone is not proof it is current.
+ */
+const isAgentSkillListSynced = (s: ToolStoreState): boolean =>
+ s.agentSkillListReplica?.entries[AGENT_SKILL_LIST_KEY]?.source === 'server';
+
const getMarketAgentSkills = (s: ToolStoreState): AgentSkillListItem[] =>
getAgentSkills(s).filter((skill) => skill.source === 'market');
@@ -56,4 +64,5 @@ export const agentSkillsSelectors = {
getMarketAgentSkills,
getUserAgentSkills,
isAgentSkill,
+ isAgentSkillListSynced,
};