🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(skills): import private repositories through the GitHub connector (#23510)
AmAzing-057ee369701b
diff --git a/.agents/ux/lobe-design-rules.md b/.agents/ux/lobe-design-rules.mdindex 36f9027a48a..750fc87ea9e 100644--- a/.agents/ux/lobe-design-rules.md+++ b/.agents/ux/lobe-design-rules.md@@ -201,3 +201,9 @@ Enforcement: the picker metadata excludes always-on identifiers; builtin selectoThe profile library picker and chat Tools menu are two views of the same agent configuration. Share the tool inventory, translated names, state and agent-scoped write path, **not the popup**. The profile keeps its searchable checklist; chat keeps its loading-policy filters. Derive profile counts from the same unfiltered options. Agent-owned connector provisioning and the Skills invocation picker are separate tasks.Enforcement: both surfaces use the same tool controls; regression tests cover the profile summary, runtime-backed settings and fixed-loader exclusions.++## LOBE-UX-028 — Recover GitHub skill imports in the import dialog++Show GitHub authorization guidance when an import encounters an access error. Keep the source URL in the dialog while the user connects. Offer technical details only when they add diagnostic information beyond the recovery message.++Enforcement: `useGithubSkillImport.test.ts` covers the single access message, retrying discovery after authorization, and retaining the user's selection when an import needs reconnection.diff --git a/apps/server/src/modules/GitHub/index.ts b/apps/server/src/modules/GitHub/index.tsindex 8e6340f23b1..b2d9c53d525 100644--- a/apps/server/src/modules/GitHub/index.ts+++ b/apps/server/src/modules/GitHub/index.ts@@ -157,7 +157,7 @@ export class GitHub {});// A missing repository answers 404, a missing ref answers 422.if (response.status === 404 || response.status === 422)- throw new GitHubNotFoundError('GitHub repository or ref not found');+ throw new GitHubNotFoundError('GitHub repository or ref not found', response.status);if (response.status === 429 ||(response.status === 403 &&@@ -165,6 +165,8 @@ export class GitHub {response.headers.get('x-ratelimit-remaining') === '0')))throw new GitHubRateLimitError('GitHub rate limit reached');+ if (response.status === 403)+ throw new GitHubNotFoundError('GitHub repository is inaccessible', 403);if (!response.ok)throw new GitHubDownloadError(`Could not resolve GitHub revision (HTTP ${response.status})`);const commit = (await response.text()).trim();@@ -175,7 +177,10 @@ export class GitHub {async downloadCommitZip(info: GitHubRepoInfo, commit: string) {if (!/^[a-f0-9]{40}$/.test(commit)) throw new GitHubParseError('Invalid commit SHA');const url = `https://codeload.github.com/${encodeURIComponent(info.owner)}/${encodeURIComponent(info.repo)}/zip/${commit}`;- return this.readArchive(await fetch(url, { signal: AbortSignal.timeout(30_000) }));+ const response = await fetch(url, { signal: AbortSignal.timeout(30_000) });+ if (response.status === 404 || response.status === 403)+ throw new GitHubNotFoundError('GitHub repository or commit is inaccessible');+ return this.readArchive(response);}/**@@ -197,6 +202,32 @@ export class GitHub {return { buffer, commit };}+ /** A private commit's signed archive URL is short-lived and must never be logged. */+ async downloadSnapshotZip(location: string) {+ const signal = AbortSignal.timeout(30_000);+ for (let redirects = 0; redirects <= 3; redirects++) {+ const url = new URL(location);+ if (+ !['https://github.com', 'https://api.github.com', 'https://codeload.github.com'].includes(+ url.origin,+ ) ||+ url.username ||+ url.password+ )+ throw new GitHubDownloadError('Invalid GitHub archive location');+ const response = await fetch(url.href, { redirect: 'manual', signal });+ if (response.status >= 300 && response.status < 400) {+ await response.body?.cancel();+ const next = response.headers.get('location');+ if (!next) throw new GitHubDownloadError('Missing GitHub archive location');+ location = new URL(next, url).href;+ continue;+ }+ return this.readArchive(response);+ }+ throw new GitHubDownloadError('Too many GitHub archive redirects');+ }+private async readArchive(response: Response) {if (!response.ok || !response.body)throw new GitHubDownloadError(`Could not download repository (HTTP ${response.status})`);@@ -319,7 +350,10 @@ export class GitHubParseError extends GitHubError {}export class GitHubNotFoundError extends GitHubError {- constructor(message: string) {+ constructor(+ message: string,+ readonly status?: number,+ ) {super(message);this.name = 'GitHubNotFoundError';}diff --git a/apps/server/src/routers/lambda/agentSkills.ensure.test.ts b/apps/server/src/routers/lambda/agentSkills.ensure.test.tsindex 3ee0fb61c4c..1a17db06a34 100644--- a/apps/server/src/routers/lambda/agentSkills.ensure.test.ts+++ b/apps/server/src/routers/lambda/agentSkills.ensure.test.ts@@ -94,6 +94,7 @@ describe('agentSkills.ensureFromMarket', () => {]);expect(mocks.modelConstructor).toHaveBeenCalledWith({}, 'user', 'workspace');expect(mocks.importerConstructor).toHaveBeenLastCalledWith({}, 'user', 'workspace', {+ githubProxy: expect.any(Function),workspaceRole: 'member',});expect(mocks.importFromUrl).toHaveBeenCalledWith(diff --git a/apps/server/src/routers/lambda/agentSkills.ts b/apps/server/src/routers/lambda/agentSkills.tsindex 646f7425178..53f069a72e1 100644--- a/apps/server/src/routers/lambda/agentSkills.ts+++ b/apps/server/src/routers/lambda/agentSkills.ts@@ -8,7 +8,7 @@ import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAimport { AgentSkillModel } from '@/database/models/agentSkill';import { FileModel } from '@/database/models/file';import { router } from '@/libs/trpc/lambda';-import { serverDatabase } from '@/libs/trpc/lambda/middleware';+import { resolveMarketUserContext, serverDatabase } from '@/libs/trpc/lambda/middleware';import { FileService } from '@/server/services/file';import { MarketService } from '@/server/services/market';import {@@ -26,8 +26,24 @@ import { assertWorkspaceRowManageable } from './_helpers/assertWorkspaceRowManagconst skillImportErrorToTRPCCode = (code: SkillImportError['code'],-): 'CONFLICT' | 'BAD_REQUEST' | 'NOT_FOUND' | 'BAD_GATEWAY' | 'FORBIDDEN' => {+):+ | 'CONFLICT'+ | 'BAD_REQUEST'+ | 'NOT_FOUND'+ | 'BAD_GATEWAY'+ | 'FORBIDDEN'+ | 'PRECONDITION_FAILED' => {switch (code) {+ case 'CONNECT_GITHUB': {+ return 'PRECONDITION_FAILED';+ }++ case 'GITHUB_ACCESS':+ case 'NOT_FOUND':+ case 'FILE_NOT_FOUND': {+ return 'NOT_FOUND';+ }+case 'CONFLICT': {return 'CONFLICT';}@@ -36,11 +52,6 @@ const skillImportErrorToTRPCCode = (return 'FORBIDDEN';}- case 'NOT_FOUND':- case 'FILE_NOT_FOUND': {- return 'NOT_FOUND';- }-case 'DOWNLOAD_FAILED': {return 'BAD_GATEWAY';}@@ -70,12 +81,23 @@ const skillProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =>const workspaceId = ctx.workspaceId ?? undefined;const skillModel = new AgentSkillModel(ctx.serverDB, ctx.userId, workspaceId);+ const githubProxy: MarketService['proxyOAuthRequest'] = async (request) => {+ const { marketAccessToken, marketUserInfo } = await resolveMarketUserContext(ctx);+ const market = new MarketService({+ // Keep the workspace claim on trusted requests and personal bearer tokens in personal mode.+ accessToken: workspaceId ? undefined : (marketAccessToken ?? ctx.marketAccessToken),+ userInfo: marketUserInfo,+ });+ return market.proxyOAuthRequest(request);+ };+return opts.next({ctx: {+ githubProxy,fileModel: new FileModel(ctx.serverDB, ctx.userId, workspaceId),fileService: new FileService(ctx.serverDB, ctx.userId, workspaceId),marketService: new MarketService({ userInfo: { userId: ctx.userId } }),- skillImporter: new SkillImporter(ctx.serverDB, ctx.userId, workspaceId),+ skillImporter: new SkillImporter(ctx.serverDB, ctx.userId, workspaceId, { githubProxy }),skillModel,},});@@ -97,6 +119,7 @@ const skillWriteProcedure = skillProcedurereturn opts.next({ctx: {skillImporter: new SkillImporter(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined, {+ githubProxy: ctx.githubProxy,workspaceRole: (ctx as { workspaceRole?: string }).workspaceRole,}),},@@ -225,7 +248,9 @@ export const agentSkillsRouter = router({discoverGitHubSkills: skillWriteProcedure.input(z.object({ gitUrl: z.string().url() }))- .mutation(({ ctx, input }) => ctx.skillImporter.discoverGitHubSkills(input.gitUrl)),+ .mutation(({ ctx, input }) =>+ ctx.skillImporter.discoverGitHubSkills(input.gitUrl).catch(handleSkillImportError),+ ),importGitHubSkills: skillWriteProcedure.input(@@ -239,7 +264,9 @@ export const agentSkillsRouter = router({.max(200),}),)- .mutation(({ ctx, input }) => ctx.skillImporter.importGitHubSkills(input)),+ .mutation(({ ctx, input }) =>+ ctx.skillImporter.importGitHubSkills(input).catch(handleSkillImportError),+ ),importFromGitHub: skillWriteProcedure.input(diff --git a/apps/server/src/services/market/index.ts b/apps/server/src/services/market/index.tsindex d17eaa506a3..e882e764401 100644--- a/apps/server/src/services/market/index.ts+++ b/apps/server/src/services/market/index.ts@@ -100,6 +100,7 @@ export interface MarketOAuthProxyRequest {parameters?: MarketOAuthProxyParameter[];/** Market OAuth provider identifier. */provider: string;+ signal?: AbortSignal;}/** Provider response returned through the Market OAuth proxy. */@@ -241,6 +242,7 @@ export class MarketService {method,parameters,provider,+ signal,}: MarketOAuthProxyRequest): Promise<MarketOAuthProxyResponse> => {const normalizedEndpoint = endpoint.startsWith('/') ? endpoint : `/${endpoint}`;const url = new URL(@@ -286,6 +288,7 @@ export class MarketService {body: body === undefined ? undefined : JSON.stringify(body),headers: forwardedHeaders,method,+ signal,});return { data: (await response.json()) as unknown, status: response.status };diff --git a/apps/server/src/services/skill/errors.ts b/apps/server/src/services/skill/errors.tsindex 9adb68f19a0..a5d543c2c83 100644--- a/apps/server/src/services/skill/errors.ts+++ b/apps/server/src/services/skill/errors.ts@@ -28,16 +28,19 @@ export class SkillResourceError extends Error {}export class SkillImportError extends Error {- code:- 'CONFLICT' | 'INVALID_URL' | 'NOT_FOUND' | 'DOWNLOAD_FAILED' | 'FILE_NOT_FOUND' | 'FORBIDDEN';-constructor(message: string,- code:- 'CONFLICT' | 'INVALID_URL' | 'NOT_FOUND' | 'DOWNLOAD_FAILED' | 'FILE_NOT_FOUND' | 'FORBIDDEN',+ readonly code:+ | 'CONFLICT'+ | 'INVALID_URL'+ | 'NOT_FOUND'+ | 'DOWNLOAD_FAILED'+ | 'FILE_NOT_FOUND'+ | 'FORBIDDEN'+ | 'CONNECT_GITHUB'+ | 'GITHUB_ACCESS',) {super(message);this.name = 'SkillImportError';- this.code = code;}}diff --git a/apps/server/src/services/skill/githubRepository.test.ts b/apps/server/src/services/skill/githubRepository.test.tsnew file mode 100644index 00000000000..15235356740--- /dev/null+++ b/apps/server/src/services/skill/githubRepository.test.ts@@ -0,0 +1,89 @@+// @vitest-environment node+import { afterEach, expect, it, vi } from 'vitest';++import { GitHub } from '@/server/modules/GitHub';+import { redisService } from '@/server/services/redis';++import { GitHubSkillRepository } from './githubRepository';++const info = { branch: 'HEAD', owner: 'owner', repo: 'private' };+const commit = 'a'.repeat(40);+const signed = 'https://codeload.github.com/owner/private/zip/' + commit + '?token=temporary';+const snapshot = { data: { repository: { object: { oid: commit, zipballUrl: signed } } } };+const proxy = vi.fn();+const source = () => new GitHubSkillRepository(new GitHub(), proxy);+const missing = () => new Response(null, { status: 404 });++afterEach(() => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ proxy.mockReset();+});++it('resolves a private HEAD with the connector and downloads the pinned archive without credentials', async () => {+ const fetch = vi.fn().mockResolvedValueOnce(missing()).mockResolvedValueOnce(new Response('zip'));+ vi.stubGlobal('fetch', fetch);+ const record = vi.spyOn(redisService.gitHubRefs, 'record');+ proxy.mockResolvedValue({ data: snapshot, status: 200 });+ const repo = source();+ expect(await repo.resolveCommit(info)).toEqual({ commit, public: false });+ expect(await repo.downloadCommitZip(info, commit)).toEqual(Buffer.from('zip'));+ expect(record).not.toHaveBeenCalled();+ expect(proxy).toHaveBeenCalledWith(+ expect.objectContaining({+ body: expect.objectContaining({+ variables: { owner: 'owner', repo: 'private', ref: 'HEAD' },+ }),+ endpoint: '/graphql',+ provider: 'github',+ }),+ );+ expect(fetch.mock.calls[1]).toEqual([+ signed,+ { redirect: 'manual', signal: expect.any(AbortSignal) },+ ]);+});++it('checks connector access again on a new pinned batch request', async () => {+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(missing()));+ proxy.mockResolvedValue({ data: { error: { code: 'NOT_CONNECTED' } }, status: 403 });+ await expect(source().downloadCommitZip(info, commit)).rejects.toMatchObject({+ code: 'CONNECT_GITHUB',+ });+});++it('distinguishes an inaccessible repository from an unconnected account', async () => {+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(missing()));+ proxy.mockResolvedValue({ data: { errors: [{ type: 'NOT_FOUND' }] }, status: 200 });+ await expect(source().resolveCommit(info)).rejects.toMatchObject({ code: 'GITHUB_ACCESS' });+});++it('does not consult the connector for a public commit', async () => {+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(commit)));+ vi.spyOn(redisService.gitHubRefs, 'record').mockResolvedValue();+ expect(await source().resolveCommit(info)).toEqual({ commit, public: true });+ expect(proxy).not.toHaveBeenCalled();+});++it('rejects an archive redirect outside GitHub before issuing another request', async () => {+ const fetch = vi+ .fn()+ .mockResolvedValueOnce(missing())+ .mockResolvedValueOnce(+ new Response(null, { headers: { location: 'https://example.org/archive' }, status: 302 }),+ );+ vi.stubGlobal('fetch', fetch);+ proxy.mockResolvedValue({ data: snapshot, status: 200 });+ await expect(source().downloadCommitZip(info, commit)).rejects.toThrow(+ 'Invalid GitHub archive location',+ );+ expect(fetch).toHaveBeenCalledTimes(2);+});++it('rejects a connector snapshot that does not match the selected commit', async () => {+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(missing()));+ proxy.mockResolvedValue({ data: snapshot, status: 200 });+ await expect(source().downloadCommitZip(info, 'b'.repeat(40))).rejects.toThrow(+ 'different commit',+ );+});diff --git a/apps/server/src/services/skill/githubRepository.ts b/apps/server/src/services/skill/githubRepository.tsnew file mode 100644index 00000000000..e80184c8811--- /dev/null+++ b/apps/server/src/services/skill/githubRepository.ts@@ -0,0 +1,127 @@+import { z } from 'zod';++import {+ type GitHub,+ GitHubNotFoundError,+ GitHubRateLimitError,+ type GitHubRepoInfo,+} from '@/server/modules/GitHub';+import type { MarketService } from '@/server/services/market';+import { redisService } from '@/server/services/redis';++import { SkillImportError } from './errors';++type GitHubProxy = MarketService['proxyOAuthRequest'];++const snapshotQuery = `query SkillArchive($owner: String!, $repo: String!, $ref: String!) {+ repository(owner: $owner, name: $repo) {+ object(expression: $ref) { ... on Commit { oid zipballUrl } }+ }+}`;+const snapshotSchema = z.object({+ oid: z.string().regex(/^[a-f0-9]{40}$/),+ zipballUrl: z.string().url(),+});+const envelopeSchema = z.object({+ data: z+ .object({ repository: z.object({ object: snapshotSchema.nullable() }).nullable() })+ .nullable()+ .optional(),+ errors: z.array(z.object({ type: z.string().optional() })).optional(),+ error: z.object({ code: z.string().optional() }).optional(),+});++const connectorRequired = () =>+ new SkillImportError(+ 'Check the repository URL. For a private repository, connect GitHub in Settings → Connectors and retry.',+ 'CONNECT_GITHUB',+ );+const unavailable = () =>+ new SkillImportError(+ 'Check the repository URL and branch, and confirm your GitHub connector can read the repository.',+ 'GITHUB_ACCESS',+ );++/** Request-scoped. Only anonymous ref lookups may enter the shared Redis cache. */+export class GitHubSkillRepository {+ private archiveUrls = new Map<string, string>();++ constructor(+ private readonly github: GitHub,+ private readonly proxy?: GitHubProxy,+ ) {}++ private key(info: GitHubRepoInfo, commit: string) {+ return JSON.stringify([info.owner, info.repo, commit]);+ }++ private async connectedSnapshot(info: GitHubRepoInfo, ref: string, cause: unknown) {+ if (+ !this.proxy ||+ !(cause instanceof GitHubNotFoundError || cause instanceof GitHubRateLimitError)+ )+ throw cause;+ if (cause instanceof GitHubNotFoundError && cause.status === 422) throw cause;+ const { data, status } = await this.proxy({+ body: { query: snapshotQuery, variables: { owner: info.owner, repo: info.repo, ref } },+ endpoint: '/graphql',+ method: 'POST',+ provider: 'github',+ signal: AbortSignal.timeout(15_000),+ });+ const envelope = envelopeSchema.safeParse(data).data;+ const code = envelope?.error?.code;+ if (status === 401 || code === 'NOT_CONNECTED' || code === 'TOKEN_EXPIRED') {+ throw connectorRequired();+ }+ const errors = envelope?.errors ?? [];+ if (status === 429 || errors.some((e) => e.type === 'RATE_LIMITED'))+ throw new GitHubRateLimitError('GitHub rate limit reached');+ if (+ status === 403 ||+ status === 404 ||+ errors.some((e) => e.type === 'NOT_FOUND' || e.type === 'FORBIDDEN')+ )+ throw unavailable();+ if (status !== 200 || errors.length || !envelope?.data)+ throw new SkillImportError('GitHub connector request failed. Try again.', 'DOWNLOAD_FAILED');+ const snapshot = envelope.data.repository?.object;+ if (!snapshot) throw unavailable();+ this.archiveUrls.set(this.key(info, snapshot.oid), snapshot.zipballUrl);+ return snapshot;+ }++ async resolveCommit(info: GitHubRepoInfo, cached = false) {+ try {+ const resolve = () => this.github.resolveCommit(info);+ const commit = cached+ ? await redisService.gitHubRefs.remember(info, resolve)+ : await resolve();+ if (!cached) await redisService.gitHubRefs.record(info, commit);+ return { commit, public: true };+ } catch (error) {+ const snapshot = await this.connectedSnapshot(info, info.branch, error).catch((failure) => {+ // Preserve the anonymous ref-archive fallback when the public API is+ // rate limited and the connector cannot supply a snapshot.+ if (error instanceof GitHubRateLimitError) throw error;+ throw failure;+ });+ return { commit: snapshot.oid, public: false };+ }+ }++ async downloadCommitZip(info: GitHubRepoInfo, commit: string) {+ let url = this.archiveUrls.get(this.key(info, commit));+ if (!url) {+ try {+ return await this.github.downloadCommitZip(info, commit);+ } catch (error) {+ const snapshot = await this.connectedSnapshot(info, commit, error);+ if (snapshot.oid !== commit)+ throw new SkillImportError('GitHub returned a different commit', 'DOWNLOAD_FAILED');+ url = snapshot.zipballUrl;+ }+ }+ return this.github.downloadSnapshotZip(url);+ }+}diff --git a/apps/server/src/services/skill/githubUpdates.ts b/apps/server/src/services/skill/githubUpdates.tsindex fe4ef887131..658f7d70ccc 100644--- a/apps/server/src/services/skill/githubUpdates.ts+++ b/apps/server/src/services/skill/githubUpdates.ts@@ -3,10 +3,10 @@ import { createHash } from 'node:crypto';import type { GitHubSkillCheck, SkillItem } from '@lobechat/types';import pMap from 'p-map';-import { type GitHub, GitHubRateLimitError, type GitHubRepoInfo } from '@/server/modules/GitHub';-import { redisService } from '@/server/services/redis';+import { GitHubRateLimitError, type GitHubRepoInfo } from '@/server/modules/GitHub';import { readGitHubArchive } from './githubArchive';+import type { GitHubSkillRepository } from './githubRepository';import type { SkillParser } from './parser';export const isCommit = (ref: string) => /^[a-f0-9]{40}$/i.test(ref);@@ -43,18 +43,19 @@ type TrackedRow = { info: GitHubRepoInfo; skill: SkillItem };const packageHashes = new Map<string, string | null>();async function readPackageHashes(- github: GitHub,+ github: GitHubSkillRepository,parser: SkillParser,info: GitHubRepoInfo,commit: string,paths: Set<string>,+ isPublic: boolean,) {const hashes = new Map<string, string | null>();const pending = [];const key = (path: string) =>JSON.stringify([info.owner.toLowerCase(), info.repo.toLowerCase(), commit, path]);for (const path of paths) {- const cached = packageHashes.get(key(path));+ const cached = isPublic ? packageHashes.get(key(path)) : undefined;if (cached === undefined) pending.push(path);else hashes.set(path, cached);}@@ -70,6 +71,7 @@ async function readPackageHashes(: null;if (hash === undefined) continue;hashes.set(path, hash);+ if (!isPublic) continue;if (packageHashes.size >= 2048) {const oldest = packageHashes.keys().next();if (!oldest.done) packageHashes.delete(oldest.value);@@ -82,7 +84,11 @@ async function readPackageHashes(return hashes;}-export async function checkGitHubRows(rows: TrackedRow[], github: GitHub, parser: SkillParser) {+export async function checkGitHubRows(+ rows: TrackedRow[],+ github: GitHubSkillRepository,+ parser: SkillParser,+) {const results: Record<string, GitHubSkillCheck> = {};const groups = new Map<string, TrackedRow[]>();for (const row of rows) {@@ -110,16 +116,14 @@ export async function checkGitHubRows(rows: TrackedRow[], github: GitHub, parserreturn;}const { info } = group[0];- const commit = await redisService.gitHubRefs.remember(info, () =>- github.resolveCommit(info),- );+ const { commit, public: isPublic } = await github.resolveCommit(info, true);const changed = group.filter(({ skill }) => {if (skill.upstream?.installedCommit !== commit) return true;results[skill.id] = { status: 'current' };return false;});const paths = new Set(changed.map(({ info }) => info.path ?? ''));- const hashes = await readPackageHashes(github, parser, info, commit, paths);+ const hashes = await readPackageHashes(github, parser, info, commit, paths, isPublic);for (const { info: source, skill } of changed) {const hash = hashes.get(source.path ?? '');if (hash === undefined) results[skill.id] = { status: 'unavailable' };diff --git a/apps/server/src/services/skill/importer.githubCollection.test.ts b/apps/server/src/services/skill/importer.githubCollection.test.tsindex 7e1375a4e48..75e83c1315f 100644--- a/apps/server/src/services/skill/importer.githubCollection.test.ts+++ b/apps/server/src/services/skill/importer.githubCollection.test.ts@@ -85,6 +85,56 @@ describe('GitHub skill collection import', () => {expect((await model.findAll()).total).toBe(1);});+ it('imports only the selected skill from a private snapshot and rechecks access on each batch', async () => {+ const hidden = new GitHubNotFoundError('Repository is inaccessible', 404);+ vi.mocked(GitHub.prototype.resolveCommit).mockRejectedValue(hidden);+ vi.mocked(GitHub.prototype.downloadCommitZip).mockRejectedValue(hidden);+ const archive = vi.spyOn(GitHub.prototype, 'downloadSnapshotZip').mockResolvedValue(zip);+ const url = 'https://codeload.github.com/owner/collection/zip/' + commit + '?token=test';+ const githubProxy = vi.fn().mockResolvedValue({+ data: { data: { repository: { object: { oid: commit, zipballUrl: url } } } },+ status: 200,+ });+ const request = () => new SkillImporter(db, userId, undefined, { githubProxy });+ const scan = await request().discoverGitHubSkills(repo);+ expect(scan.candidates.map(({ path }) => path)).toContain(review);+ expect(scan.commit).toBe(commit);+ const batch = { ...scan, gitUrl: repo, selections: [{ path: review, revision: null }] };+ githubProxy.mockResolvedValueOnce({ data: { error: { code: 'NOT_CONNECTED' } }, status: 403 });+ await expect(request().importGitHubSkills(batch)).rejects.toMatchObject({+ code: 'CONNECT_GITHUB',+ });+ expect((await model.findAll()).total).toBe(0);+ expect(archive).toHaveBeenCalledTimes(1);++ expect(await request().importGitHubSkills(batch)).toEqual([+ { path: review, status: 'created' },+ ]);+ expect(githubProxy).toHaveBeenLastCalledWith(+ expect.objectContaining({+ body: expect.objectContaining({+ variables: { owner: 'owner', repo: 'collection', ref: commit },+ }),+ }),+ );+ expect((await model.findAll()).total).toBe(1);+ const skill = await model.findByName('review');+ expect(skill?.upstream?.installedCommit).toBe(commit);+ expect(JSON.stringify({ skill, scan })).not.toContain('token=test');+ });++ it('returns a typed not-found error when GitHub cannot resolve a ref during discovery', async () => {+ const proxy = vi.fn();+ vi.mocked(GitHub.prototype.resolveCommit).mockRejectedValue(+ new GitHubNotFoundError('GitHub repository or ref not found', 422),+ );+ const importer = new SkillImporter(db, userId, undefined, { githubProxy: proxy });+ await expect(importer.discoverGitHubSkills(repo + '/tree/missing')).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ expect(proxy).not.toHaveBeenCalled();+ });+it('coalesces concurrent submissions of the same selection', async () => {const scan = await importer.discoverGitHubSkills(repo);const batch = { ...scan, gitUrl: repo, selections: [{ path: review, revision: null }] };diff --git a/apps/server/src/services/skill/importer.ts b/apps/server/src/services/skill/importer.tsindex 30bd941e839..820b3946e21 100644--- a/apps/server/src/services/skill/importer.ts+++ b/apps/server/src/services/skill/importer.ts@@ -30,10 +30,12 @@ import {type GitHubRepoInfo,} from '@/server/modules/GitHub';import { FileService } from '@/server/services/file';+import type { MarketService } from '@/server/services/market';import { redisService } from '@/server/services/redis';import { SkillImportError, SkillManifestError, SkillParseError } from './errors';import { readGitHubArchive } from './githubArchive';+import { GitHubSkillRepository } from './githubRepository';import {checkGitHubRows,installedFingerprint,@@ -60,6 +62,7 @@ const log = debug('lobe-chat:service:skill-importer');/** GitHub and package failures reach the client as import errors, not as a 500. */const asImportError = (error: unknown): never => {if (error instanceof GitHubNotFoundError) throw new SkillImportError(error.message, 'NOT_FOUND');+ if (error instanceof GitHubParseError) throw new SkillImportError(error.message, 'INVALID_URL');if (error instanceof GitHubError ||error instanceof SkillParseError ||@@ -75,6 +78,7 @@ export class SkillImporter {private resourceService: SkillResourceService;private fileService: FileService;private github: GitHub;+ private repository: GitHubSkillRepository;private userId: string;private workspaceId?: string;private workspaceRole?: string;@@ -83,13 +87,14 @@ export class SkillImporter {db: LobeChatDatabase,userId: string,workspaceId?: string,- options?: { workspaceRole?: string },+ options?: { githubProxy?: MarketService['proxyOAuthRequest']; workspaceRole?: string },) {this.skillModel = new AgentSkillModel(db, userId, workspaceId);this.parser = new SkillParser();this.resourceService = new SkillResourceService(db, userId, workspaceId);this.fileService = new FileService(db, userId, workspaceId);this.github = new GitHub({ userAgent: 'LobeHub-Skill-Importer' });+ this.repository = new GitHubSkillRepository(this.github, options?.githubProxy);this.userId = userId;this.workspaceId = workspaceId;this.workspaceRole = options?.workspaceRole;@@ -236,6 +241,7 @@ export class SkillImporter {log('importFromGitHub: downloaded ZIP size=%d bytes', zipBuffer.length);} catch (error) {log('importFromGitHub: download failed, error=%s', (error as Error).message);+ if (error instanceof SkillImportError) throw error;if (error instanceof GitHubNotFoundError) {throw new SkillImportError(error.message, 'NOT_FOUND');}@@ -260,15 +266,13 @@ export class SkillImporter {* older commit than the one this import is about to install.*/private async resolveCommit(info: GitHubRepoInfo) {- const commit = await this.github.resolveCommit(info);- await redisService.gitHubRefs.record(info, commit);- return commit;+ return (await this.repository.resolveCommit(info)).commit;}private async downloadRef(info: GitHubRepoInfo) {try {const commit = await this.resolveCommit(info);- return { buffer: await this.github.downloadCommitZip(info, commit), commit };+ return { buffer: await this.repository.downloadCommitZip(info, commit), commit };} catch (error) {if (!(error instanceof GitHubRateLimitError)) throw error;// The REST quota is shared by everyone behind this server's address. The@@ -313,7 +317,7 @@ export class SkillImporter {const info = this.installedSource(skill);return info ? [{ info, skill }] : [];}),- this.github,+ this.repository,this.parser,);}@@ -339,7 +343,7 @@ export class SkillImporter {const tracking = { ...info, branch: ref };const archive = await this.resolveCommit(tracking).then(async (commit) =>- readGitHubArchive(await this.github.downloadCommitZip(info, commit), info.path),+ readGitHubArchive(await this.repository.downloadCommitZip(info, commit), info.path),).catch(asImportError);if (!archive.get(info.path ?? ''))@@ -373,7 +377,7 @@ export class SkillImporter {skill.upstream?.installedFingerprint !== installedFingerprint(skill))throw new SkillImportError('Confirm replacement of local changes', 'CONFLICT');- const parsed = await this.github+ const parsed = await this.repository.downloadCommitZip(info, input.commit).then((buffer) =>this.parser.parseZipPackage(buffer, {@@ -545,7 +549,7 @@ export class SkillImporter {const commit = pinnedCommit ?? (await this.resolveCommit(info));const base = info.path ?? '';const archive = await readGitHubArchive(- await this.github.downloadCommitZip(info, commit),+ await this.repository.downloadCommitZip(info, commit),base,);const exact = url.pathname.split('/')[3] === 'blob' || (!!base && archive.has(base));@@ -556,7 +560,7 @@ export class SkillImporter {}async discoverGitHubSkills(gitUrl: string): Promise<GitHubSkillDiscovery> {- const { commit, directories, info } = await this.gitHubCollection(gitUrl);+ const { commit, directories, info } = await this.gitHubCollection(gitUrl).catch(asImportError);const entries = directories.map(([path, directory]) => {const fallbackName = path.split('/').at(-1) || info.repo;const source = { ...info, path };@@ -628,7 +632,9 @@ export class SkillImporter {async importGitHubSkills(input: GitHubSkillBatchInput): Promise<GitHubSkillOutcome[]> {if (this.importScope !== input.scope)throw new SkillImportError('The active library changed. Find skills again.', 'CONFLICT');- const { directories, info } = await this.gitHubCollection(input.gitUrl, input.commit);+ const { directories, info } = await this.gitHubCollection(input.gitUrl, input.commit).catch(+ asImportError,+ );const available = new Map(directories);const results: GitHubSkillOutcome[] = [];for (const { path, revision } of input.selections) {diff --git a/locales/en-US/error.json b/locales/en-US/error.jsonindex 61c9cf9f8c4..d52665a412a 100644--- a/locales/en-US/error.json+++ b/locales/en-US/error.json@@ -20,6 +20,8 @@"forbidden.backHome": "Back to Home","forbidden.desc": "You don't have permission to view this page. Please contact a workspace owner if you need access.","forbidden.title": "Access denied",+ "import.github.access": "Couldn’t open this repository or branch. Check the link and your GitHub account’s access.",+ "import.github.connect": "Private repositories need a GitHub account with read access.","import.importConfigFile.description": "Error reason: {{reason}}","import.importConfigFile.title": "Import Failed","import.incompatible.description": "This file was exported from a higher version. Please try upgrading to the latest version and then re-importing.",diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex 10a98784443..642a8068311 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -210,13 +210,13 @@"agentSkillModal.github.clearSearch": "Clear search","agentSkillModal.github.complete_one": "{{count}} skill is ready to use","agentSkillModal.github.complete_other": "{{count}} skills are ready to use",- "agentSkillModal.github.desc": "Paste the URL of a skill directory from a public GitHub repository. The directory must contain a SKILL.md file.",+ "agentSkillModal.github.connectionSettings": "Open GitHub connection settings",+ "agentSkillModal.github.desc": "Choose a GitHub repository or folder containing a SKILL.md file.","agentSkillModal.github.empty": "No SKILL.md found at this URL. Try another repository or directory.","agentSkillModal.github.example": "https://github.com/owner/repository",- "agentSkillModal.github.find": "Find skills",+ "agentSkillModal.github.find": "Parse skills","agentSkillModal.github.findFailed": "Couldn’t read this GitHub link. Check the URL and try again.",- "agentSkillModal.github.finding": "Finding skills…",- "agentSkillModal.github.hint": "Find skills in a public repository, then choose which to import.",+ "agentSkillModal.github.finding": "Parsing skills…","agentSkillModal.github.importFailed": "Couldn’t import the selected skills. Find skills again, then retry.","agentSkillModal.github.importSelected_one": "Import {{count}} skill","agentSkillModal.github.importSelected_other": "Import {{count}} skills",@@ -2469,7 +2469,7 @@"tab.hotkey": "Hotkeys","tab.image": "Image Generation","tab.importFromGithub": "Import from GitHub",- "tab.importFromGithub.desc": "Import from a public GitHub repository",+ "tab.importFromGithub.desc": "Import from a GitHub repository","tab.importFromUrl": "Import from URL","tab.importFromUrl.desc": "Import via a direct link to SKILL.md","tab.integrations": "Integrations",diff --git a/locales/zh-CN/error.json b/locales/zh-CN/error.jsonindex 0b9ebef6a8e..c1765db6c9c 100644--- a/locales/zh-CN/error.json+++ b/locales/zh-CN/error.json@@ -20,6 +20,8 @@"forbidden.backHome": "返回首页","forbidden.desc": "你没有权限访问该页面。如需访问,请联系空间所有者","forbidden.title": "无权访问",+ "import.github.access": "无法访问这个仓库或分支。请确认链接正确,且 GitHub 账号有读取权限。",+ "import.github.connect": "导入私有仓库需要有读取权限的 GitHub 账号。","import.importConfigFile.description": "原因:{{reason}}","import.importConfigFile.title": "导入遇到了问题","import.incompatible.description": "该文件由更高版本导出。请升级到最新版后再导入",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex 25e0379461a..1bb905a8c2a 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -210,13 +210,13 @@"agentSkillModal.github.clearSearch": "清除搜索","agentSkillModal.github.complete_one": "{{count}} 个技能已就绪","agentSkillModal.github.complete_other": "{{count}} 个技能已就绪",- "agentSkillModal.github.desc": "粘贴公开 GitHub 仓库中技能目录的 URL,该目录下需包含 SKILL.md 文件。",+ "agentSkillModal.github.connectionSettings": "查看 GitHub 连接设置",+ "agentSkillModal.github.desc": "选择包含 SKILL.md 的 GitHub 仓库或目录。","agentSkillModal.github.empty": "此链接下没有找到 SKILL.md,请尝试其他仓库或目录。","agentSkillModal.github.example": "https://github.com/owner/repository",- "agentSkillModal.github.find": "查找技能",+ "agentSkillModal.github.find": "解析技能","agentSkillModal.github.findFailed": "无法读取这个 GitHub 链接,请检查链接后重试。",- "agentSkillModal.github.finding": "正在查找技能…",- "agentSkillModal.github.hint": "查找公开仓库中的技能,然后选择要导入的项目。",+ "agentSkillModal.github.finding": "正在解析技能…","agentSkillModal.github.importFailed": "未能导入所选技能,请重新查找后再试。","agentSkillModal.github.importSelected_one": "导入 {{count}} 个技能","agentSkillModal.github.importSelected_other": "导入 {{count}} 个技能",@@ -2469,7 +2469,7 @@"tab.hotkey": "快捷键","tab.image": "绘画服务","tab.importFromGithub": "从 GitHub 导入",- "tab.importFromGithub.desc": "从公开的 GitHub 仓库导入",+ "tab.importFromGithub.desc": "从 GitHub 仓库导入","tab.importFromUrl": "从 URL 导入","tab.importFromUrl.desc": "通过 SKILL.md 的直接链接导入","tab.integrations": "集成",diff --git a/packages/locales/src/default/error.ts b/packages/locales/src/default/error.tsindex ce1de1a220a..b6bd18ed6e2 100644--- a/packages/locales/src/default/error.ts+++ b/packages/locales/src/default/error.ts@@ -21,6 +21,9 @@ export default {'error.title': 'Oops, something went wrong..','fetchError.detail': 'Error details','fetchError.title': 'Request failed',+ 'import.github.access':+ 'Couldn’t open this repository or branch. Check the link and your GitHub account’s access.',+ 'import.github.connect': 'Private repositories need a GitHub account with read access.','import.importConfigFile.description': 'Error reason: {{reason}}','import.importConfigFile.title': 'Import Failed','import.incompatible.description':diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex 1f16716214d..69754d8b812 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -360,16 +360,15 @@ export default {'agentSkillModal.github.clearSearch': 'Clear search','agentSkillModal.github.complete_one': '{{count}} skill is ready to use','agentSkillModal.github.complete_other': '{{count}} skills are ready to use',- 'agentSkillModal.github.desc':- 'Paste the URL of a skill directory from a public GitHub repository. The directory must contain a SKILL.md file.',+ 'agentSkillModal.github.connectionSettings': 'Open GitHub connection settings',+ 'agentSkillModal.github.desc': 'Choose a GitHub repository or folder containing a SKILL.md file.','agentSkillModal.github.empty':'No SKILL.md found at this URL. Try another repository or directory.','agentSkillModal.github.example': 'https://github.com/owner/repository',- 'agentSkillModal.github.find': 'Find skills',+ 'agentSkillModal.github.find': 'Parse skills','agentSkillModal.github.findFailed':'Couldn’t read this GitHub link. Check the URL and try again.',- 'agentSkillModal.github.finding': 'Finding skills…',- 'agentSkillModal.github.hint': 'Find skills in a public repository, then choose which to import.',+ 'agentSkillModal.github.finding': 'Parsing skills…','agentSkillModal.github.importFailed':'Couldn’t import the selected skills. Find skills again, then retry.','agentSkillModal.github.importSelected_one': 'Import {{count}} skill',@@ -2325,7 +2324,7 @@ When I am ___, I need ___'tab.hotkey': 'Hotkeys','tab.image': 'Image Generation','tab.importFromGithub': 'Import from GitHub',- 'tab.importFromGithub.desc': 'Import from a public GitHub repository',+ 'tab.importFromGithub.desc': 'Import from a GitHub repository','tab.importFromUrl': 'Import from URL','tab.importFromUrl.desc': 'Import via a direct link to SKILL.md','tab.labels': 'Labels',diff --git a/src/features/SkillStore/SkillImportModal/GithubImport.tsx b/src/features/SkillStore/SkillImportModal/GithubImport.tsxindex dfe6eec9b25..52f2014116c 100644--- a/src/features/SkillStore/SkillImportModal/GithubImport.tsx+++ b/src/features/SkillStore/SkillImportModal/GithubImport.tsx@@ -3,12 +3,12 @@ import { GithubIcon } from '@lobehub/ui/icons';import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';import * as stylex from '@stylexjs/stylex';import { CheckCircle2, CircleAlert } from 'lucide-react';-import { useId } from 'react';import { useTranslation } from 'react-i18next';import AsyncError from '@/components/AsyncError';import { densityTokens } from '@/styles/density.stylex';+import { GithubImportRecovery } from './GithubImportRecovery';import { GithubSkillPicker } from './GithubSkillPicker';import { canImportCandidate } from './githubSkillSelection';import type { useGithubSkillImport } from './useGithubSkillImport';@@ -35,7 +35,6 @@ const styles = stylex.create({export const GithubImport = ({ state }: { state: ReturnType<typeof useGithubSkillImport> }) => {const { t } = useTranslation(['setting', 'common']);const { close } = useModalContext();- const inputId = useId();const {canCreate,candidates,@@ -62,52 +61,47 @@ export const GithubImport = ({ state }: { state: ReturnType<typeof useGithubSkilconst failureCount = results.filter((item) =>['failed', 'conflict', 'forbidden'].includes(item.status),).length;- const error = failure && (- <AsyncError- align="start"- details={failure.details}- retrying={loading}- variant="inline"- action={- scan && failure.stage !== 'refresh' ? (- <Button disabled={loading || !canCreate} size="small" type="text" onClick={discover}>- {t('agentSkillModal.github.rescan')}- </Button>- ) : undefined- }- title={t(- failure.stage === 'import'- ? 'agentSkillModal.github.batchFailed'- : `agentSkillModal.github.${failure.stage}Failed`,- )}- onRetry={failure.stage === 'refresh' ? refreshLibrary : undefined}- />+ const error = failure?.recovery ? (+ <GithubImportRecovery recovery={failure.recovery} onConnected={state.resumeAfterConnect} />+ ) : (+ failure && (+ <AsyncError+ align="start"+ details={failure.details}+ retrying={loading}+ variant="inline"+ action={+ scan && failure.stage !== 'refresh' ? (+ <Button disabled={loading || !canCreate} size="small" type="text" onClick={discover}>+ {t('agentSkillModal.github.rescan')}+ </Button>+ ) : undefined+ }+ title={t(+ failure.stage === 'import'+ ? 'agentSkillModal.github.batchFailed'+ : `agentSkillModal.github.${failure.stage}Failed`,+ )}+ onRetry={failure.stage === 'refresh' ? refreshLibrary : undefined}+ />+ ));if (!scan)return (<Flexbox gap={20}><Flexbox gap={8}>- <label htmlFor={inputId}>- <Text strong as="span">- {t('agentSkillModal.github.label')}- </Text>- </label><Input- aria-describedby={inputId + '-hint'}+ aria-label={t('agentSkillModal.github.label')}disabled={loading || !canCreate}- id={inputId}placeholder={t('agentSkillModal.github.example')}prefix={<Icon icon={GithubIcon} />}value={url}onChange={(event) => setUrl(event.target.value)}onPressEnter={discover}/>- <Text fontSize={13} id={inputId + '-hint'} type="secondary">- {t('agentSkillModal.github.hint')}- </Text>+ {error}</Flexbox>- {error}<Flexbox horizontal justify="flex-end"><Buttondisabled={!canCreate || !url.trim()}diff --git a/src/features/SkillStore/SkillImportModal/GithubImportRecovery.tsx b/src/features/SkillStore/SkillImportModal/GithubImportRecovery.tsxnew file mode 100644index 00000000000..db5c6e4c0ac--- /dev/null+++ b/src/features/SkillStore/SkillImportModal/GithubImportRecovery.tsx@@ -0,0 +1,85 @@+import type { TaskTemplateConnectorReference } from '@lobechat/const';+import { Alert, Button, Flexbox, Icon, toast, Tooltip } from '@lobehub/ui';+import { ArrowUpRight, LockKeyhole } from 'lucide-react';+import { useEffect, useRef } from 'react';+import { useTranslation } from 'react-i18next';++import {+ ConnectorConnectionMarketAuthRequiredError,+ ConnectorConnectionPopupBlockedError,+ useConnectorConnection,+} from '@/features/RecommendTaskTemplates/useConnectorConnection';+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';+import { usePermission } from '@/hooks/usePermission';++const github: TaskTemplateConnectorReference[] = [{ identifier: 'github', source: 'lobehub' }];++interface GithubImportRecoveryProps {+ onConnected: () => void;+ recovery: 'access' | 'connect';+}++export const GithubImportRecovery = ({ recovery, onConnected }: GithubImportRecoveryProps) => {+ const { t } = useTranslation(['setting', 'common', 'error']);+ const create = usePermission('create_content');+ const edit = usePermission('edit_own_content');+ const { connect, isConnecting, isAllConnected } = useConnectorConnection(github);+ const startedHere = useRef(false);++ useEffect(() => {+ if (startedHere.current && isAllConnected) {+ startedHere.current = false;+ onConnected();+ }+ }, [isAllConnected, onConnected]);++ const authorize = async () => {+ startedHere.current = true;+ try {+ await connect();+ } catch (error) {+ startedHere.current = false;+ if (error instanceof ConnectorConnectionMarketAuthRequiredError) return;+ toast.error(+ t(+ error instanceof ConnectorConnectionPopupBlockedError+ ? 'common:taskTemplate.action.connect.popupBlocked'+ : 'common:taskTemplate.action.connect.error',+ ),+ );+ }+ };++ const showSettings = recovery === 'access' || isAllConnected;+ return (+ <Alert+ icon={LockKeyhole}+ title={t(showSettings ? 'error:import.github.access' : 'error:import.github.connect')}+ type="warning"+ action={+ showSettings ? (+ <WorkspaceLink+ rel="noopener noreferrer"+ target="_blank"+ to="/settings/connector?open=lobehub-connector%3Agithub"+ >+ <Flexbox horizontal align="center" as="span" gap={4}>+ {t('agentSkillModal.github.connectionSettings')}+ <Icon icon={ArrowUpRight} size={14} />+ </Flexbox>+ </WorkspaceLink>+ ) : (+ <Tooltip title={create.reason ?? edit.reason}>+ <Button+ disabled={!create.allowed || !edit.allowed}+ loading={isConnecting}+ onClick={authorize}+ >+ {t('environments.github.connect')}+ </Button>+ </Tooltip>+ )+ }+ />+ );+};diff --git a/src/features/SkillStore/SkillImportModal/SingleSkillImport.tsx b/src/features/SkillStore/SkillImportModal/SingleSkillImport.tsxindex 9da28e15b33..20eb40ab169 100644--- a/src/features/SkillStore/SkillImportModal/SingleSkillImport.tsx+++ b/src/features/SkillStore/SkillImportModal/SingleSkillImport.tsx@@ -43,7 +43,7 @@ export const SingleSkillImport = ({}: SingleSkillImportProps) => {const { t } = useTranslation('setting');const { close } = useModalContext();- const inputId = useId();+ const hintId = useId();const [url, setUrl] = useState('');const [file, setFile] = useState<File>();const [fileId, setFileId] = useState<string>();@@ -103,16 +103,11 @@ export const SingleSkillImport = ({<Flexbox gap={20}>{isLink ? (<Flexbox gap={8}>- <label htmlFor={inputId}>- <Text strong as="span">- {t('agentSkillModal.url.label')}- </Text>- </label><Input- aria-describedby={inputId + '-hint'}+ aria-describedby={hintId}aria-invalid={invalidUrl}+ aria-label={t('agentSkillModal.url.label')}disabled={loading || !canCreate}- id={inputId}placeholder={t('agentSkillModal.url.urlPlaceholder')}prefix={<Icon icon={Link} />}value={url}@@ -125,7 +120,7 @@ export const SingleSkillImport = ({/><TextfontSize={13}- id={inputId + '-hint'}+ id={hintId}role={invalidUrl ? 'alert' : undefined}type={invalidUrl ? 'danger' : 'secondary'}>@@ -134,10 +129,10 @@ export const SingleSkillImport = ({</Flexbox>) : (<Flexbox gap={8}>- <Text strong>{t('agentSkillModal.upload.label')}</Text><Uploaddraggeraccept=".zip,.skill"+ aria-describedby={hintId}disabled={loading || !canCreate}maxCount={1}onDropCapture={(event) => checkFileTypes(event.dataTransfer.files)}@@ -165,6 +160,7 @@ export const SingleSkillImport = ({</Upload><TextfontSize={13}+ id={hintId}role={invalidFile ? 'alert' : undefined}type={invalidFile ? 'danger' : 'secondary'}>diff --git a/src/features/SkillStore/SkillImportModal/useGithubSkillImport.test.ts b/src/features/SkillStore/SkillImportModal/useGithubSkillImport.test.tsindex 2cc4fe06405..1da5654a1c5 100644--- a/src/features/SkillStore/SkillImportModal/useGithubSkillImport.test.ts+++ b/src/features/SkillStore/SkillImportModal/useGithubSkillImport.test.ts@@ -62,6 +62,68 @@ describe('useGithubSkillImport', () => {expect(result.current.selected).toEqual(['skills/demo']);});+ it.each([+ ['PRECONDITION_FAILED', 'connect'],+ ['NOT_FOUND', 'access'],+ ])('keeps the source URL and exposes recovery for %s', async (code, recovery) => {+ mocks.discoverGitHubSkills.mockRejectedValueOnce(+ Object.assign(new Error('GitHub access failed'), { data: { code } }),+ );+ const { result } = await scanned();+ expect(result.current.failure).toEqual({ recovery, stage: 'find' });+ expect(result.current.url.trim()).toBe('https://github.com/lobehub/skills');+ });++ it('offers repository access guidance for the unclassified error from older servers', async () => {+ const details = 'GitHub repository or ref not found';+ mocks.discoverGitHubSkills.mockRejectedValueOnce(+ Object.assign(new Error(details), { data: { code: 'INTERNAL_SERVER_ERROR' } }),+ );+ const { result } = await scanned();+ expect(result.current.failure).toEqual({ recovery: 'access', stage: 'find' });+ });++ it('rescans the original link after connecting without installing a skill', async () => {+ mocks.discoverGitHubSkills+ .mockRejectedValueOnce(+ Object.assign(new Error('Connect GitHub'), { data: { code: 'PRECONDITION_FAILED' } }),+ )+ .mockResolvedValueOnce({ candidates: [demo], commit, scope: 'scope' });+ const { result } = await scanned();++ await act(() => result.current.resumeAfterConnect());++ expect(mocks.discoverGitHubSkills.mock.calls).toEqual([+ ['https://github.com/lobehub/skills'],+ ['https://github.com/lobehub/skills'],+ ]);+ expect(result.current.selected).toEqual([demo.path]);+ expect(result.current.failure).toBeUndefined();+ expect(mocks.importGitHubSkills).not.toHaveBeenCalled();+ });++ it('keeps the pinned preview and selection when reconnecting after a batch error', async () => {+ mocks.discoverGitHubSkills.mockResolvedValueOnce({+ candidates: [demo],+ commit,+ scope: 'scope',+ });+ mocks.importGitHubSkills.mockRejectedValueOnce(+ Object.assign(new Error('Connect GitHub'), { data: { code: 'PRECONDITION_FAILED' } }),+ );+ const { result } = await scanned();+ await act(() => result.current.install([demo.path]));++ expect(result.current.failure).toEqual({ recovery: 'connect', stage: 'import' });+ await act(() => result.current.resumeAfterConnect());++ expect(result.current.scan?.commit).toBe(commit);+ expect(result.current.selected).toEqual([demo.path]);+ expect(result.current.failure).toBeUndefined();+ expect(mocks.importGitHubSkills).toHaveBeenCalledTimes(1);+ expect(mocks.discoverGitHubSkills).toHaveBeenCalledTimes(1);+ });+it('records a failed scan with its raw message as details', async () => {mocks.discoverGitHubSkills.mockRejectedValue(new Error('[{"code":"invalid_format"}]'));diff --git a/src/features/SkillStore/SkillImportModal/useGithubSkillImport.ts b/src/features/SkillStore/SkillImportModal/useGithubSkillImport.tsindex c10092fcb84..215024d3b8b 100644--- a/src/features/SkillStore/SkillImportModal/useGithubSkillImport.ts+++ b/src/features/SkillStore/SkillImportModal/useGithubSkillImport.ts@@ -2,17 +2,32 @@ import type { GitHubSkillDiscovery, GitHubSkillOutcome } from '@lobechat/types';import { useState } from 'react';import { usePermission } from '@/hooks/usePermission';+import { normalizeAsyncError } from '@/libs/swr/normalizeError';import { agentSkillService } from '@/services/skill';import { useToolStore } from '@/store/tool';export interface GithubSkillImportFailure {/** Raw message from the server, folded behind "Show details". */- details: string;+ details?: string;+ recovery?: 'access' | 'connect';stage: 'find' | 'import' | 'refresh';}const detailsOf = (err: unknown) => (err instanceof Error ? err.message : String(err));+const importFailure = (error: unknown, stage: 'find' | 'import'): GithubSkillImportFailure => {+ const { code } = normalizeAsyncError(error);+ if (code === 'PRECONDITION_FAILED') return { recovery: 'connect', stage };+ const details = detailsOf(error);+ // Older discovery endpoints return this GitHub error as an internal error.+ if (+ code === 'NOT_FOUND' ||+ (stage === 'find' && details === 'GitHub repository or ref not found')+ )+ return { recovery: 'access', stage };+ return { details, stage };+};+/*** The scan → select → import state of the GitHub import modal: one request at* a time, and a failure kept apart from the per-skill outcomes of a batch.@@ -52,12 +67,18 @@ export const useGithubSkillImport = () => {setResults([]);setSelected(found.length === 1 && found[0].status === 'new' ? [found[0].path] : []);} catch (err) {- setFailure({ details: detailsOf(err), stage: 'find' });+ setFailure(importFailure(err, 'find'));} finally {setPending(undefined);}};+ const resumeAfterConnect = () => {+ if (failure?.stage === 'find') return discover();+ // A batch still needs an explicit import. Keep its pinned commit and selection.+ setFailure(undefined);+ };+const refreshLibrary = async () => {setPending('refresh');setFailure(undefined);@@ -86,7 +107,7 @@ export const useGithubSkillImport = () => {setResults((prev) => [...prev.filter((item) => !paths.includes(item.path)), ...batch]);setQuery('');} catch (err) {- setFailure({ details: detailsOf(err), stage: 'import' });+ setFailure(importFailure(err, 'import'));setPending(undefined);return;}@@ -104,6 +125,7 @@ export const useGithubSkillImport = () => {query,refreshLibrary,results,+ resumeAfterConnect,scan,selected,setQuery,