feat: Enhance Marketplace and Skill Management UI with improved error handling and user feedback
- Updated MarketplaceDrawer to include security notes and manual installation hints. - Refactored SkillDetailDrawer to display default icons for skills. - Simplified SkillListItem to use default icons for better readability. - Integrated gateway status checks and warnings in SkillsPage for improved user awareness. - Enhanced error handling for skill installation and fetching, providing clearer feedback to users. - Added new translations for error messages and gateway warnings to improve localization support.
This commit is contained in:
473
electron/gateway/clawhub.ts
Normal file
473
electron/gateway/clawhub.ts
Normal file
@@ -0,0 +1,473 @@
|
||||
/**
|
||||
* ClawHub Service
|
||||
* Manages interactions with the ClawHub CLI for skills management
|
||||
*/
|
||||
import { spawn } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import { shell } from 'electron';
|
||||
import { join } from 'node:path';
|
||||
import { getOpenClawConfigDir, ensureDir, getClawHubCliBinPath, getClawHubCliEntryPath } from '../utils/paths';
|
||||
|
||||
export interface ClawHubSearchParams {
|
||||
query: string;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export interface ClawHubInstallParams {
|
||||
slug: string;
|
||||
version?: string;
|
||||
force?: boolean;
|
||||
}
|
||||
|
||||
export interface ClawHubUninstallParams {
|
||||
slug: string;
|
||||
}
|
||||
|
||||
export interface ClawHubSkillResult {
|
||||
slug: string;
|
||||
name: string;
|
||||
description: string;
|
||||
version: string;
|
||||
author?: string;
|
||||
downloads?: number;
|
||||
stars?: number;
|
||||
}
|
||||
|
||||
export interface ClawHubInstalledSkillResult {
|
||||
slug: string;
|
||||
version: string;
|
||||
source?: string;
|
||||
baseDir?: string;
|
||||
}
|
||||
|
||||
export class ClawHubService {
|
||||
private workDir: string;
|
||||
private cliPath: string;
|
||||
private cliEntryPath: string;
|
||||
private useNodeRunner: boolean;
|
||||
private cliAvailable: boolean;
|
||||
private ansiRegex: RegExp;
|
||||
|
||||
constructor() {
|
||||
// Use the user's OpenClaw config directory (~/.openclaw) for skill management
|
||||
this.workDir = getOpenClawConfigDir();
|
||||
ensureDir(this.workDir);
|
||||
|
||||
const binPath = getClawHubCliBinPath();
|
||||
const entryPath = getClawHubCliEntryPath();
|
||||
|
||||
this.cliPath = binPath;
|
||||
this.cliEntryPath = entryPath;
|
||||
|
||||
// Detect if CLI is available
|
||||
const binExists = fs.existsSync(binPath);
|
||||
const entryExists = fs.existsSync(entryPath);
|
||||
this.cliAvailable = binExists || entryExists;
|
||||
|
||||
// If bin exists, use it directly; otherwise fall back to node runner
|
||||
this.useNodeRunner = !binExists;
|
||||
|
||||
const esc = String.fromCharCode(27);
|
||||
const csi = String.fromCharCode(155);
|
||||
const pattern = `(?:${esc}|${csi})[[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]`;
|
||||
this.ansiRegex = new RegExp(pattern, 'g');
|
||||
}
|
||||
|
||||
async getMarketplaceCapability(): Promise<{ mode: string; canSearch: boolean; canInstall: boolean; reason?: string }> {
|
||||
if (!this.cliAvailable) {
|
||||
return { mode: 'none', canSearch: false, canInstall: false, reason: 'ClawHub CLI not found' };
|
||||
}
|
||||
return { mode: 'clawhub', canSearch: true, canInstall: true };
|
||||
}
|
||||
|
||||
private stripAnsi(line: string): string {
|
||||
return line.replace(this.ansiRegex, '').trim();
|
||||
}
|
||||
|
||||
private extractFrontmatterName(skillManifestPath: string): string | null {
|
||||
try {
|
||||
const raw = fs.readFileSync(skillManifestPath, 'utf8');
|
||||
// Match the first frontmatter block and read `name: ...`
|
||||
const frontmatterMatch = raw.match(/^---\s*\n([\s\S]*?)\n---/);
|
||||
if (!frontmatterMatch) return null;
|
||||
const body = frontmatterMatch[1];
|
||||
const nameMatch = body.match(/^\s*name\s*:\s*["']?([^"'\n]+)["']?\s*$/m);
|
||||
if (!nameMatch) return null;
|
||||
const name = nameMatch[1].trim();
|
||||
return name || null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private resolveSkillDirByManifestName(candidates: string[]): string | null {
|
||||
const skillsRoot = join(this.workDir, 'skills');
|
||||
if (!fs.existsSync(skillsRoot)) return null;
|
||||
|
||||
const wanted = new Set(
|
||||
candidates
|
||||
.map((v) => v.trim().toLowerCase())
|
||||
.filter((v) => v.length > 0),
|
||||
);
|
||||
if (wanted.size === 0) return null;
|
||||
|
||||
let entries: fs.Dirent[];
|
||||
try {
|
||||
entries = fs.readdirSync(skillsRoot, { withFileTypes: true });
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
for (const entry of entries) {
|
||||
if (!entry.isDirectory()) continue;
|
||||
const skillDir = join(skillsRoot, entry.name);
|
||||
const skillManifestPath = join(skillDir, 'SKILL.md');
|
||||
if (!fs.existsSync(skillManifestPath)) continue;
|
||||
|
||||
const frontmatterName = this.extractFrontmatterName(skillManifestPath);
|
||||
if (!frontmatterName) continue;
|
||||
if (wanted.has(frontmatterName.toLowerCase())) {
|
||||
return skillDir;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run a ClawHub CLI command
|
||||
*/
|
||||
private async runCommand(args: string[]): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!this.cliAvailable) {
|
||||
reject(new Error('ClawHub CLI not found'));
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.useNodeRunner && !fs.existsSync(this.cliEntryPath)) {
|
||||
reject(new Error(`ClawHub CLI entry not found at: ${this.cliEntryPath}`));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.useNodeRunner && !fs.existsSync(this.cliPath)) {
|
||||
reject(new Error(`ClawHub CLI not found at: ${this.cliPath}`));
|
||||
return;
|
||||
}
|
||||
|
||||
const commandArgs = this.useNodeRunner ? [this.cliEntryPath, ...args] : args;
|
||||
const displayCommand = [this.cliPath, ...commandArgs].join(' ');
|
||||
console.log(`Running ClawHub command: ${displayCommand}`);
|
||||
|
||||
const { NODE_OPTIONS: _nodeOptions, ...baseEnv } = process.env;
|
||||
const env = {
|
||||
...baseEnv,
|
||||
CI: 'true',
|
||||
FORCE_COLOR: '0',
|
||||
};
|
||||
if (this.useNodeRunner) {
|
||||
env.ELECTRON_RUN_AS_NODE = '1';
|
||||
}
|
||||
|
||||
const child = spawn(this.cliPath, commandArgs, {
|
||||
cwd: this.workDir,
|
||||
env: {
|
||||
...env,
|
||||
CLAWHUB_WORKDIR: this.workDir,
|
||||
},
|
||||
windowsHide: true,
|
||||
});
|
||||
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
|
||||
child.stdout.on('data', (data) => {
|
||||
stdout += data.toString();
|
||||
});
|
||||
|
||||
child.stderr.on('data', (data) => {
|
||||
stderr += data.toString();
|
||||
});
|
||||
|
||||
child.on('error', (error) => {
|
||||
console.error('ClawHub process error:', error);
|
||||
reject(error);
|
||||
});
|
||||
|
||||
child.on('close', (code) => {
|
||||
if (code !== 0 && code !== null) {
|
||||
console.error(`ClawHub command failed with code ${code}`);
|
||||
console.error('Stderr:', stderr);
|
||||
reject(new Error(`Command failed: ${stderr || stdout}`));
|
||||
} else {
|
||||
resolve(stdout.trim());
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Search for skills
|
||||
*/
|
||||
async search(params: ClawHubSearchParams): Promise<ClawHubSkillResult[]> {
|
||||
if (!this.cliAvailable) {
|
||||
throw new Error('ClawHub CLI not found');
|
||||
}
|
||||
try {
|
||||
// If query is empty, use 'explore' to show trending skills
|
||||
if (!params.query || params.query.trim() === '') {
|
||||
return this.explore({ limit: params.limit });
|
||||
}
|
||||
|
||||
const args = ['search', params.query];
|
||||
if (params.limit) {
|
||||
args.push('--limit', String(params.limit));
|
||||
}
|
||||
|
||||
const output = await this.runCommand(args);
|
||||
if (!output || output.includes('No skills found')) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const lines = output.split('\n').filter((l) => l.trim());
|
||||
return lines
|
||||
.map((line) => {
|
||||
const cleanLine = this.stripAnsi(line);
|
||||
|
||||
// Format could be: slug vversion description (score)
|
||||
// Or sometimes: slug vversion description
|
||||
let match = cleanLine.match(/^(\S+)\s+v?(\d+\.\S+)\s+(.+)$/);
|
||||
if (match) {
|
||||
const slug = match[1];
|
||||
const version = match[2];
|
||||
let description = match[3];
|
||||
|
||||
// Clean up score if present at the end
|
||||
description = description.replace(/\(\d+\.\d+\)$/, '').trim();
|
||||
|
||||
return {
|
||||
slug,
|
||||
name: slug,
|
||||
version,
|
||||
description,
|
||||
};
|
||||
}
|
||||
|
||||
// Fallback for new clawhub search format without version:
|
||||
// slug name/description (score)
|
||||
match = cleanLine.match(/^(\S+)\s+(.+)$/);
|
||||
if (match) {
|
||||
const slug = match[1];
|
||||
let description = match[2];
|
||||
|
||||
// Clean up score if present at the end
|
||||
description = description.replace(/\(\d+\.\d+\)$/, '').trim();
|
||||
|
||||
return {
|
||||
slug,
|
||||
name: slug,
|
||||
version: 'latest', // Fallback version since it's not provided
|
||||
description,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
})
|
||||
.filter((s): s is ClawHubSkillResult => s !== null);
|
||||
} catch (error) {
|
||||
console.error('ClawHub search error:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Explore trending skills
|
||||
*/
|
||||
async explore(params: { limit?: number } = {}): Promise<ClawHubSkillResult[]> {
|
||||
if (!this.cliAvailable) {
|
||||
throw new Error('ClawHub CLI not found');
|
||||
}
|
||||
try {
|
||||
const args = ['explore'];
|
||||
if (params.limit) {
|
||||
args.push('--limit', String(params.limit));
|
||||
}
|
||||
|
||||
const output = await this.runCommand(args);
|
||||
if (!output) return [];
|
||||
|
||||
const lines = output.split('\n').filter((l) => l.trim());
|
||||
return lines
|
||||
.map((line) => {
|
||||
const cleanLine = this.stripAnsi(line);
|
||||
|
||||
// Format: slug vversion time description
|
||||
// Example: my-skill v1.0.0 2 hours ago A great skill
|
||||
const match = cleanLine.match(/^(\S+)\s+v?(\d+\.\S+)\s+(.+? ago|just now|yesterday)\s+(.+)$/i);
|
||||
if (match) {
|
||||
return {
|
||||
slug: match[1],
|
||||
name: match[1],
|
||||
version: match[2],
|
||||
description: match[4],
|
||||
};
|
||||
}
|
||||
return null;
|
||||
})
|
||||
.filter((s): s is ClawHubSkillResult => s !== null);
|
||||
} catch (error) {
|
||||
console.error('ClawHub explore error:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Install a skill
|
||||
*/
|
||||
async install(params: ClawHubInstallParams): Promise<void> {
|
||||
if (!this.cliAvailable) {
|
||||
throw new Error('ClawHub CLI not found');
|
||||
}
|
||||
const args = ['install', params.slug];
|
||||
|
||||
if (params.version) {
|
||||
args.push('--version', params.version);
|
||||
}
|
||||
|
||||
if (params.force) {
|
||||
args.push('--force');
|
||||
}
|
||||
|
||||
await this.runCommand(args);
|
||||
}
|
||||
|
||||
/**
|
||||
* Uninstall a skill
|
||||
*/
|
||||
async uninstall(params: ClawHubUninstallParams): Promise<void> {
|
||||
const fsPromises = fs.promises;
|
||||
|
||||
// 1. Delete the skill directory
|
||||
const skillDir = join(this.workDir, 'skills', params.slug);
|
||||
if (fs.existsSync(skillDir)) {
|
||||
console.log(`Deleting skill directory: ${skillDir}`);
|
||||
await fsPromises.rm(skillDir, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
// 2. Remove from lock.json
|
||||
const lockFile = join(this.workDir, '.clawhub', 'lock.json');
|
||||
if (fs.existsSync(lockFile)) {
|
||||
try {
|
||||
const lockData = JSON.parse(fs.readFileSync(lockFile, 'utf8'));
|
||||
if (lockData.skills && lockData.skills[params.slug]) {
|
||||
console.log(`Removing ${params.slug} from lock.json`);
|
||||
delete lockData.skills[params.slug];
|
||||
await fsPromises.writeFile(lockFile, JSON.stringify(lockData, null, 2));
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to update ClawHub lock file:', err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* List installed skills
|
||||
*/
|
||||
async listInstalled(): Promise<ClawHubInstalledSkillResult[]> {
|
||||
if (!this.cliAvailable) {
|
||||
throw new Error('ClawHub CLI not found');
|
||||
}
|
||||
try {
|
||||
const output = await this.runCommand(['list']);
|
||||
if (!output || output.includes('No installed skills')) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const lines = output.split('\n').filter((l) => l.trim());
|
||||
return lines
|
||||
.map((line) => {
|
||||
const cleanLine = this.stripAnsi(line);
|
||||
const match = cleanLine.match(/^(\S+)\s+v?(\d+\.\S+)/);
|
||||
if (match) {
|
||||
const slug = match[1];
|
||||
return {
|
||||
slug,
|
||||
version: match[2],
|
||||
source: 'openclaw-managed',
|
||||
baseDir: join(this.workDir, 'skills', slug),
|
||||
};
|
||||
}
|
||||
return null;
|
||||
})
|
||||
.filter((s): s is ClawHubInstalledSkillResult => s !== null);
|
||||
} catch (error) {
|
||||
console.error('ClawHub list error:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
private resolveSkillDir(skillKeyOrSlug: string, fallbackSlug?: string, preferredBaseDir?: string): string | null {
|
||||
const candidates = [skillKeyOrSlug, fallbackSlug]
|
||||
.filter((v): v is string => typeof v === 'string' && v.trim().length > 0)
|
||||
.map((v) => v.trim());
|
||||
const uniqueCandidates = [...new Set(candidates)];
|
||||
if (preferredBaseDir && preferredBaseDir.trim() && fs.existsSync(preferredBaseDir.trim())) {
|
||||
return preferredBaseDir.trim();
|
||||
}
|
||||
const directSkillDir = uniqueCandidates
|
||||
.map((id) => join(this.workDir, 'skills', id))
|
||||
.find((dir) => fs.existsSync(dir));
|
||||
return directSkillDir || this.resolveSkillDirByManifestName(uniqueCandidates);
|
||||
}
|
||||
|
||||
/**
|
||||
* Open skill README/manual in default editor
|
||||
*/
|
||||
async openSkillReadme(skillKeyOrSlug: string, fallbackSlug?: string, preferredBaseDir?: string): Promise<boolean> {
|
||||
const skillDir = this.resolveSkillDir(skillKeyOrSlug, fallbackSlug, preferredBaseDir);
|
||||
|
||||
// Try to find documentation file
|
||||
const possibleFiles = ['SKILL.md', 'README.md', 'skill.md', 'readme.md'];
|
||||
let targetFile = '';
|
||||
|
||||
if (skillDir) {
|
||||
for (const file of possibleFiles) {
|
||||
const filePath = join(skillDir, file);
|
||||
if (fs.existsSync(filePath)) {
|
||||
targetFile = filePath;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!targetFile) {
|
||||
// If no md file, just open the directory
|
||||
if (skillDir) {
|
||||
targetFile = skillDir;
|
||||
} else {
|
||||
throw new Error('Skill directory not found');
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
// Open file with default application
|
||||
await shell.openPath(targetFile);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Failed to open skill readme:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Open skill path in file explorer
|
||||
*/
|
||||
async openSkillPath(skillKeyOrSlug: string, fallbackSlug?: string, preferredBaseDir?: string): Promise<boolean> {
|
||||
const skillDir = this.resolveSkillDir(skillKeyOrSlug, fallbackSlug, preferredBaseDir);
|
||||
if (!skillDir) {
|
||||
throw new Error('Skill directory not found');
|
||||
}
|
||||
const openResult = await shell.openPath(skillDir);
|
||||
if (openResult) {
|
||||
throw new Error(openResult);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
45
electron/gateway/handlers/skills.ts
Normal file
45
electron/gateway/handlers/skills.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import { getAllSkillConfigs, updateSkillConfig } from '@electron/utils/skill-config';
|
||||
import type { GatewayRpcReturns } from '../types';
|
||||
|
||||
export async function handleSkillsStatus(): Promise<GatewayRpcReturns['skills.status']> {
|
||||
const configs = await getAllSkillConfigs();
|
||||
|
||||
return {
|
||||
skills: Object.entries(configs).map(([skillKey, config]) => ({
|
||||
skillKey,
|
||||
slug: config.slug || skillKey,
|
||||
name: config.name || skillKey,
|
||||
description: config.description || '',
|
||||
disabled: config.enabled === false,
|
||||
emoji: config.icon,
|
||||
version: config.version || '1.0.0',
|
||||
author: config.author,
|
||||
config: {
|
||||
...(config.config || {}),
|
||||
...(config.apiKey ? { apiKey: config.apiKey } : {}),
|
||||
...(config.env ? { env: config.env } : {}),
|
||||
},
|
||||
bundled: typeof config.isBundled === 'boolean' ? config.isBundled : config.source === 'openclaw-bundled',
|
||||
always: Boolean(config.isCore),
|
||||
source: config.source,
|
||||
baseDir: config.baseDir,
|
||||
filePath: config.filePath,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleSkillsUpdate(
|
||||
params: { skillKey: string; enabled?: boolean },
|
||||
): Promise<GatewayRpcReturns['skills.update']> {
|
||||
const { skillKey, enabled } = params;
|
||||
if (!skillKey || !String(skillKey).trim()) {
|
||||
throw new Error('skillKey is required');
|
||||
}
|
||||
|
||||
const result = await updateSkillConfig(String(skillKey).trim(), { enabled });
|
||||
if (!result.success) {
|
||||
throw new Error(result.error || 'Failed to update skill');
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import logManager from '@electron/service/logger';
|
||||
import type { GatewayEvent, RuntimeRefreshTopic } from './types';
|
||||
import * as chatHandlers from './handlers/chat';
|
||||
import * as providerHandlers from './handlers/provider';
|
||||
import * as skillHandlers from './handlers/skills';
|
||||
|
||||
type RuntimeChangeBroadcast = {
|
||||
topics: RuntimeRefreshTopic[];
|
||||
@@ -94,6 +95,10 @@ class GatewayManager {
|
||||
return providerHandlers.handleProviderList();
|
||||
case 'provider.getDefault':
|
||||
return providerHandlers.handleProviderGetDefault();
|
||||
case 'skills.status':
|
||||
return skillHandlers.handleSkillsStatus();
|
||||
case 'skills.update':
|
||||
return skillHandlers.handleSkillsUpdate(params);
|
||||
default:
|
||||
throw new Error(`Unknown gateway RPC method: ${method}`);
|
||||
}
|
||||
|
||||
@@ -68,6 +68,11 @@ export interface GatewayRpcParams {
|
||||
};
|
||||
'provider.list': Record<string, never>;
|
||||
'provider.getDefault': Record<string, never>;
|
||||
'skills.status': Record<string, never>;
|
||||
'skills.update': {
|
||||
skillKey: string;
|
||||
enabled?: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
/// Gateway RPC 方法返回值映射
|
||||
@@ -79,4 +84,23 @@ export interface GatewayRpcReturns {
|
||||
'session.delete': { success: boolean };
|
||||
'provider.list': { accounts: any[]; defaultAccountId: string | null };
|
||||
'provider.getDefault': { accountId: string | null };
|
||||
'skills.status': {
|
||||
skills: Array<{
|
||||
skillKey: string;
|
||||
slug?: string;
|
||||
name?: string;
|
||||
description?: string;
|
||||
disabled?: boolean;
|
||||
emoji?: string;
|
||||
version?: string;
|
||||
author?: string;
|
||||
config?: Record<string, unknown>;
|
||||
bundled?: boolean;
|
||||
always?: boolean;
|
||||
source?: string;
|
||||
baseDir?: string;
|
||||
filePath?: string;
|
||||
}>;
|
||||
};
|
||||
'skills.update': { success: boolean };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user