feature: channels and skills (#2)

Co-authored-by: paisley <8197966+su8su@users.noreply.github.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Felix
2026-02-06 18:26:06 +08:00
committed by GitHub
Unverified
parent f9845023c3
commit fa6c23b82a
23 changed files with 4315 additions and 802 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -16,6 +16,8 @@ import {
RefreshCw,
CheckCircle2,
XCircle,
ExternalLink,
BookOpen,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
@@ -24,6 +26,13 @@ import { cn } from '@/lib/utils';
import { useGatewayStore } from '@/stores/gateway';
import { useSettingsStore } from '@/stores/settings';
import { toast } from 'sonner';
import {
CHANNEL_META,
getPrimaryChannels,
type ChannelType,
type ChannelMeta,
type ChannelConfigField,
} from '@/types/channel';
interface SetupStep {
id: string;
@@ -31,6 +40,15 @@ interface SetupStep {
description: string;
}
const STEP = {
WELCOME: 0,
RUNTIME: 1,
PROVIDER: 2,
CHANNEL: 3,
INSTALLING: 4,
COMPLETE: 5,
} as const;
const steps: SetupStep[] = [
{
id: 'welcome',
@@ -47,7 +65,11 @@ const steps: SetupStep[] = [
title: 'AI Provider',
description: 'Configure your AI service',
},
// Skills selection removed - auto-install essential components
{
id: 'channel',
title: 'Connect a Channel',
description: 'Connect a messaging platform (optional)',
},
{
id: 'installing',
title: 'Setting Up',
@@ -143,19 +165,23 @@ export function Setup() {
// Update canProceed based on current step
useEffect(() => {
switch (currentStep) {
case 0: // Welcome
case STEP.WELCOME:
setCanProceed(true);
break;
case 1: // Runtime
case STEP.RUNTIME:
// Will be managed by RuntimeContent
break;
case 2: // Provider
case STEP.PROVIDER:
setCanProceed(selectedProvider !== null && apiKey.length > 0);
break;
case 3: // Installing
case STEP.CHANNEL:
// Always allow proceeding — channel step is optional
setCanProceed(true);
break;
case STEP.INSTALLING:
setCanProceed(false); // Cannot manually proceed, auto-proceeds when done
break;
case 4: // Complete
case STEP.COMPLETE:
setCanProceed(true);
break;
}
@@ -213,9 +239,9 @@ export function Setup() {
{/* Step-specific content */}
<div className="rounded-xl bg-white/10 backdrop-blur p-8 mb-8">
{currentStep === 0 && <WelcomeContent />}
{currentStep === 1 && <RuntimeContent onStatusChange={setCanProceed} />}
{currentStep === 2 && (
{currentStep === STEP.WELCOME && <WelcomeContent />}
{currentStep === STEP.RUNTIME && <RuntimeContent onStatusChange={setCanProceed} />}
{currentStep === STEP.PROVIDER && (
<ProviderContent
providers={providers}
selectedProvider={selectedProvider}
@@ -224,13 +250,15 @@ export function Setup() {
onApiKeyChange={setApiKey}
/>
)}
{currentStep === 3 && (
{currentStep === STEP.CHANNEL && <SetupChannelContent />}
{currentStep === STEP.INSTALLING && (
<InstallingContent
skills={defaultSkills}
onComplete={handleInstallationComplete}
onSkip={() => setCurrentStep((i) => i + 1)}
/>
)}
{currentStep === 4 && (
{currentStep === STEP.COMPLETE && (
<CompleteContent
selectedProvider={selectedProvider}
installedSkills={installedSkills}
@@ -239,7 +267,7 @@ export function Setup() {
</div>
{/* Navigation - hidden during installation step */}
{currentStep !== 3 && (
{currentStep !== STEP.INSTALLING && (
<div className="flex justify-between">
<div>
{!isFirstStep && (
@@ -250,7 +278,12 @@ export function Setup() {
)}
</div>
<div className="flex gap-2">
{!isLastStep && currentStep !== 1 && (
{currentStep === STEP.CHANNEL && (
<Button variant="ghost" onClick={handleNext}>
Skip this step
</Button>
)}
{!isLastStep && currentStep !== STEP.RUNTIME && currentStep !== STEP.CHANNEL && (
<Button variant="ghost" onClick={handleSkip}>
Skip Setup
</Button>
@@ -531,6 +564,45 @@ function ProviderContent({
const [showKey, setShowKey] = useState(false);
const [validating, setValidating] = useState(false);
const [keyValid, setKeyValid] = useState<boolean | null>(null);
useEffect(() => {
let cancelled = false;
(async () => {
try {
const list = await window.electron.ipcRenderer.invoke('provider:list') as Array<{ id: string; hasKey: boolean }>;
const defaultId = await window.electron.ipcRenderer.invoke('provider:getDefault') as string | null;
const preferred = (defaultId && list.find((p) => p.id === defaultId && p.hasKey)) || list.find((p) => p.hasKey);
if (preferred && !cancelled) {
onSelectProvider(preferred.id);
const storedKey = await window.electron.ipcRenderer.invoke('provider:getApiKey', preferred.id) as string | null;
if (storedKey) {
onApiKeyChange(storedKey);
}
}
} catch (error) {
if (!cancelled) {
console.error('Failed to load provider list:', error);
}
}
})();
return () => { cancelled = true; };
}, [onApiKeyChange, onSelectProvider]);
useEffect(() => {
let cancelled = false;
(async () => {
if (!selectedProvider) return;
try {
const storedKey = await window.electron.ipcRenderer.invoke('provider:getApiKey', selectedProvider) as string | null;
if (!cancelled && storedKey) {
onApiKeyChange(storedKey);
}
} catch (error) {
if (!cancelled) {
console.error('Failed to load provider key:', error);
}
}
})();
return () => { cancelled = true; };
}, [onApiKeyChange, selectedProvider]);
const selectedProviderData = providers.find((p) => p.id === selectedProvider);
@@ -628,6 +700,7 @@ function ProviderContent({
onApiKeyChange(e.target.value);
setKeyValid(null);
}}
autoComplete="off"
className="pr-10 bg-white/5 border-white/10"
/>
<button
@@ -666,7 +739,257 @@ function ProviderContent({
);
}
// NOTE: ChannelContent component moved to Settings > Channels page
// ==================== Setup Channel Content ====================
function SetupChannelContent() {
const [selectedChannel, setSelectedChannel] = useState<ChannelType | null>(null);
const [configValues, setConfigValues] = useState<Record<string, string>>({});
const [showSecrets, setShowSecrets] = useState<Record<string, boolean>>({});
const [saving, setSaving] = useState(false);
const [saved, setSaved] = useState(false);
const [validationError, setValidationError] = useState<string | null>(null);
const meta: ChannelMeta | null = selectedChannel ? CHANNEL_META[selectedChannel] : null;
const primaryChannels = getPrimaryChannels();
useEffect(() => {
let cancelled = false;
(async () => {
if (!selectedChannel) return;
try {
const result = await window.electron.ipcRenderer.invoke(
'channel:getFormValues',
selectedChannel
) as { success: boolean; values?: Record<string, string> };
if (cancelled) return;
if (result.success && result.values) {
setConfigValues(result.values);
} else {
setConfigValues({});
}
} catch {
if (!cancelled) {
setConfigValues({});
}
}
})();
return () => { cancelled = true; };
}, [selectedChannel]);
const isFormValid = () => {
if (!meta) return false;
return meta.configFields
.filter((f: ChannelConfigField) => f.required)
.every((f: ChannelConfigField) => configValues[f.key]?.trim());
};
const handleSave = async () => {
if (!selectedChannel || !meta || !isFormValid()) return;
setSaving(true);
setValidationError(null);
try {
// Validate credentials first
const validation = await window.electron.ipcRenderer.invoke(
'channel:validateCredentials',
selectedChannel,
configValues
) as { success: boolean; valid?: boolean; errors?: string[]; details?: Record<string, string> };
if (!validation.valid) {
setValidationError((validation.errors || ['Validation failed']).join(', '));
setSaving(false);
return;
}
// Save config
await window.electron.ipcRenderer.invoke('channel:saveConfig', selectedChannel, { ...configValues });
const botName = validation.details?.botUsername ? ` (@${validation.details.botUsername})` : '';
toast.success(`${meta.name} configured${botName}`);
setSaved(true);
} catch (error) {
setValidationError(String(error));
} finally {
setSaving(false);
}
};
// Already saved — show success
if (saved) {
return (
<div className="text-center space-y-4">
<div className="text-5xl"></div>
<h2 className="text-xl font-semibold">
{meta?.name || 'Channel'} Connected
</h2>
<p className="text-slate-300">
Your channel has been configured. It will connect when the Gateway starts.
</p>
<Button
variant="ghost"
className="text-slate-400"
onClick={() => {
setSaved(false);
setSelectedChannel(null);
setConfigValues({});
}}
>
Configure another channel
</Button>
</div>
);
}
// Channel type not selected — show picker
if (!selectedChannel) {
return (
<div className="space-y-4">
<div className="text-center mb-2">
<div className="text-4xl mb-3">📡</div>
<h2 className="text-xl font-semibold">Connect a Messaging Channel</h2>
<p className="text-slate-300 text-sm mt-1">
Choose a platform to connect your AI assistant to. You can add more channels later in Settings.
</p>
</div>
<div className="grid grid-cols-2 gap-3">
{primaryChannels.map((type) => {
const channelMeta = CHANNEL_META[type];
if (channelMeta.connectionType !== 'token') return null;
return (
<button
key={type}
onClick={() => setSelectedChannel(type)}
className="p-4 rounded-lg bg-white/5 hover:bg-white/10 transition-all text-left"
>
<span className="text-3xl">{channelMeta.icon}</span>
<p className="font-medium mt-2">{channelMeta.name}</p>
<p className="text-xs text-slate-400 mt-1 line-clamp-2">
{channelMeta.description}
</p>
</button>
);
})}
</div>
</div>
);
}
// Channel selected — show config form
return (
<div className="space-y-4">
<div className="flex items-center gap-3 mb-2">
<button
onClick={() => { setSelectedChannel(null); setConfigValues({}); setValidationError(null); }}
className="text-slate-400 hover:text-white transition-colors"
>
<ChevronLeft className="h-5 w-5" />
</button>
<div>
<h2 className="text-xl font-semibold flex items-center gap-2">
<span>{meta?.icon}</span> Configure {meta?.name}
</h2>
<p className="text-slate-400 text-sm">{meta?.description}</p>
</div>
</div>
{/* Instructions */}
<div className="p-3 rounded-lg bg-white/5 text-sm">
<div className="flex items-center justify-between mb-2">
<p className="font-medium text-slate-200">How to connect:</p>
{meta?.docsUrl && (
<button
onClick={() => {
try {
window.electron?.openExternal?.(meta.docsUrl!);
} catch {
window.open(meta.docsUrl, '_blank');
}
}}
className="flex items-center gap-1 text-xs text-blue-400 hover:text-blue-300 transition-colors"
>
<BookOpen className="h-3 w-3" />
View docs
<ExternalLink className="h-3 w-3" />
</button>
)}
</div>
<ol className="list-decimal list-inside text-slate-400 space-y-1">
{meta?.instructions.map((inst, i) => (
<li key={i}>{inst}</li>
))}
</ol>
</div>
{/* Config fields */}
{meta?.configFields.map((field: ChannelConfigField) => {
const isPassword = field.type === 'password';
return (
<div key={field.key} className="space-y-1.5">
<Label htmlFor={`setup-${field.key}`} className="text-slate-200">
{field.label}
{field.required && <span className="text-red-400 ml-1">*</span>}
</Label>
<div className="flex gap-2">
<Input
id={`setup-${field.key}`}
type={isPassword && !showSecrets[field.key] ? 'password' : 'text'}
placeholder={field.placeholder}
value={configValues[field.key] || ''}
onChange={(e) => setConfigValues((prev) => ({ ...prev, [field.key]: e.target.value }))}
autoComplete="off"
className="font-mono text-sm bg-white/5 border-white/10"
/>
{isPassword && (
<Button
type="button"
variant="outline"
size="icon"
className="shrink-0"
onClick={() => setShowSecrets((prev) => ({ ...prev, [field.key]: !prev[field.key] }))}
>
{showSecrets[field.key] ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
</Button>
)}
</div>
{field.description && (
<p className="text-xs text-slate-500">{field.description}</p>
)}
</div>
);
})}
{/* Validation error */}
{validationError && (
<div className="p-3 rounded-lg bg-red-900/30 border border-red-500/30 text-sm text-red-300 flex items-start gap-2">
<XCircle className="h-4 w-4 mt-0.5 shrink-0" />
<span>{validationError}</span>
</div>
)}
{/* Save button */}
<Button
className="w-full"
onClick={handleSave}
disabled={!isFormValid() || saving}
>
{saving ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Validating & Saving...
</>
) : (
<>
<Check className="h-4 w-4 mr-2" />
Validate & Save
</>
)}
</Button>
</div>
);
}
// NOTE: SkillsContent component removed - auto-install essential skills
// Installation status for each skill
@@ -682,55 +1005,55 @@ interface SkillInstallState {
interface InstallingContentProps {
skills: DefaultSkill[];
onComplete: (installedSkills: string[]) => void;
onSkip: () => void;
}
function InstallingContent({ skills, onComplete }: InstallingContentProps) {
function InstallingContent({ skills, onComplete, onSkip }: InstallingContentProps) {
const [skillStates, setSkillStates] = useState<SkillInstallState[]>(
skills.map((s) => ({ ...s, status: 'pending' as InstallStatus }))
);
const [overallProgress, setOverallProgress] = useState(0);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const installStarted = useRef(false);
// Simulate installation process
// Real installation process
useEffect(() => {
if (installStarted.current) return;
installStarted.current = true;
const installSkills = async () => {
const installedIds: string[] = [];
for (let i = 0; i < skills.length; i++) {
// Set current skill to installing
setSkillStates((prev) =>
prev.map((s, idx) =>
idx === i ? { ...s, status: 'installing' } : s
)
);
// Simulate installation time (1-2 seconds per skill)
const installTime = 1000 + Math.random() * 1000;
await new Promise((resolve) => setTimeout(resolve, installTime));
// Mark as completed
setSkillStates((prev) =>
prev.map((s, idx) =>
idx === i ? { ...s, status: 'completed' } : s
)
);
installedIds.push(skills[i].id);
// Update overall progress
setOverallProgress(Math.round(((i + 1) / skills.length) * 100));
const runRealInstall = async () => {
try {
// Step 1: Initialize all skills to 'installing' state for UI
setSkillStates(prev => prev.map(s => ({ ...s, status: 'installing' })));
setOverallProgress(10);
// Step 2: Call the backend to install uv and setup Python
const result = await window.electron.ipcRenderer.invoke('uv:install-all') as {
success: boolean;
error?: string
};
if (result.success) {
setSkillStates(prev => prev.map(s => ({ ...s, status: 'completed' })));
setOverallProgress(100);
await new Promise((resolve) => setTimeout(resolve, 800));
onComplete(skills.map(s => s.id));
} else {
setSkillStates(prev => prev.map(s => ({ ...s, status: 'failed' })));
setErrorMessage(result.error || 'Unknown error during installation');
toast.error('Environment setup failed');
}
} catch (err) {
setSkillStates(prev => prev.map(s => ({ ...s, status: 'failed' })));
setErrorMessage(String(err));
toast.error('Installation error');
}
// Small delay before completing
await new Promise((resolve) => setTimeout(resolve, 500));
onComplete(installedIds);
};
installSkills();
runRealInstall();
}, [skills, onComplete]);
const getStatusIcon = (status: InstallStatus) => {
switch (status) {
case 'pending':
@@ -784,7 +1107,7 @@ function InstallingContent({ skills, onComplete }: InstallingContentProps) {
</div>
{/* Skill list */}
<div className="space-y-2 max-h-64 overflow-y-auto">
<div className="space-y-2 max-h-48 overflow-y-auto">
{skillStates.map((skill) => (
<motion.div
key={skill.id}
@@ -806,14 +1129,50 @@ function InstallingContent({ skills, onComplete }: InstallingContentProps) {
</motion.div>
))}
</div>
{/* Error Message Display */}
{errorMessage && (
<motion.div
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
className="p-4 rounded-lg bg-red-900/30 border border-red-500/50 text-red-200 text-sm"
>
<div className="flex items-start gap-2">
<AlertCircle className="h-5 w-5 text-red-400 shrink-0 mt-0.5" />
<div className="space-y-1">
<p className="font-semibold">Setup Error:</p>
<pre className="text-xs bg-black/30 p-2 rounded overflow-x-auto whitespace-pre-wrap font-monospace">
{errorMessage}
</pre>
<Button
variant="link"
className="text-red-400 p-0 h-auto text-xs underline"
onClick={() => window.location.reload()}
>
Try restarting the app
</Button>
</div>
</div>
</motion.div>
)}
<p className="text-sm text-slate-400 text-center">
This may take a few moments...
</p>
{!errorMessage && (
<p className="text-sm text-slate-400 text-center">
This may take a few moments...
</p>
)}
<div className="flex justify-end">
<Button
variant="ghost"
className="text-slate-400"
onClick={onSkip}
>
Skip this step
</Button>
</div>
</div>
);
}
interface CompleteContentProps {
selectedProvider: string | null;
installedSkills: string[];

File diff suppressed because it is too large Load Diff

View File

@@ -34,10 +34,107 @@ export const useChannelsStore = create<ChannelsState>((set, get) => ({
error: null,
fetchChannels: async () => {
// channels.status returns a complex nested object, not a simple array.
// Channel management is deferred to Settings > Channels page.
// For now, just use empty list - channels will be added later.
set({ channels: [], loading: false });
set({ loading: true, error: null });
try {
const result = await window.electron.ipcRenderer.invoke(
'gateway:rpc',
'channels.status',
{ probe: true }
) as {
success: boolean;
result?: {
channelOrder?: string[];
channels?: Record<string, unknown>;
channelAccounts?: Record<string, Array<{
accountId?: string;
configured?: boolean;
connected?: boolean;
running?: boolean;
lastError?: string;
name?: string;
linked?: boolean;
lastConnectedAt?: number | null;
lastInboundAt?: number | null;
lastOutboundAt?: number | null;
}>>;
channelDefaultAccountId?: Record<string, string>;
};
error?: string;
};
if (result.success && result.result) {
const data = result.result;
const channels: Channel[] = [];
// Parse the complex channels.status response into simple Channel objects
const channelOrder = data.channelOrder || Object.keys(data.channels || {});
for (const channelId of channelOrder) {
const summary = (data.channels as Record<string, unknown> | undefined)?.[channelId] as Record<string, unknown> | undefined;
const configured =
typeof summary?.configured === 'boolean'
? summary.configured
: typeof (summary as { running?: boolean })?.running === 'boolean'
? true
: false;
if (!configured) continue;
const accounts = data.channelAccounts?.[channelId] || [];
const defaultAccountId = data.channelDefaultAccountId?.[channelId];
const primaryAccount =
(defaultAccountId ? accounts.find((a) => a.accountId === defaultAccountId) : undefined) ||
accounts.find((a) => a.connected === true || a.linked === true) ||
accounts[0];
// Map gateway status to our status format
let status: Channel['status'] = 'disconnected';
const now = Date.now();
const RECENT_MS = 10 * 60 * 1000;
const hasRecentActivity = (a: { lastInboundAt?: number | null; lastOutboundAt?: number | null; lastConnectedAt?: number | null }) =>
(typeof a.lastInboundAt === 'number' && now - a.lastInboundAt < RECENT_MS) ||
(typeof a.lastOutboundAt === 'number' && now - a.lastOutboundAt < RECENT_MS) ||
(typeof a.lastConnectedAt === 'number' && now - a.lastConnectedAt < RECENT_MS);
const anyConnected = accounts.some((a) => a.connected === true || a.linked === true || hasRecentActivity(a));
const anyRunning = accounts.some((a) => a.running === true);
const summaryError =
typeof (summary as { error?: string })?.error === 'string'
? (summary as { error?: string }).error
: typeof (summary as { lastError?: string })?.lastError === 'string'
? (summary as { lastError?: string }).lastError
: undefined;
const anyError =
accounts.some((a) => typeof a.lastError === 'string' && a.lastError) || Boolean(summaryError);
if (anyConnected) {
status = 'connected';
} else if (anyRunning && !anyError) {
status = 'connected';
} else if (anyError) {
status = 'error';
} else if (anyRunning) {
status = 'connecting';
}
channels.push({
id: `${channelId}-${primaryAccount?.accountId || 'default'}`,
type: channelId as ChannelType,
name: primaryAccount?.name || channelId,
status,
accountId: primaryAccount?.accountId,
error:
(typeof primaryAccount?.lastError === 'string' ? primaryAccount.lastError : undefined) ||
(typeof summaryError === 'string' ? summaryError : undefined),
});
}
set({ channels, loading: false });
} else {
// Gateway not available - try to show channels from local config
set({ channels: [], loading: false });
}
} catch {
// Gateway not connected, show empty
set({ channels: [], loading: false });
}
},
addChannel: async (params) => {

View File

@@ -242,17 +242,31 @@ export const useChatStore = create<ChatState>((set, get) => ({
// Message complete - add to history and clear streaming
const finalMsg = event.message as RawMessage | undefined;
if (finalMsg) {
set((s) => ({
messages: [...s.messages, {
...finalMsg,
role: finalMsg.role || 'assistant',
id: finalMsg.id || `run-${runId}`,
}],
streamingText: '',
streamingMessage: null,
sending: false,
activeRunId: null,
}));
const msgId = finalMsg.id || `run-${runId}`;
set((s) => {
// Check if message already exists (prevent duplicates)
const alreadyExists = s.messages.some(m => m.id === msgId);
if (alreadyExists) {
// Just clear streaming state, don't add duplicate
return {
streamingText: '',
streamingMessage: null,
sending: false,
activeRunId: null,
};
}
return {
messages: [...s.messages, {
...finalMsg,
role: finalMsg.role || 'assistant',
id: msgId,
}],
streamingText: '',
streamingMessage: null,
sending: false,
activeRunId: null,
};
});
} else {
// No message in final event - reload history to get complete data
set({ streamingText: '', streamingMessage: null, sending: false, activeRunId: null });

View File

@@ -16,7 +16,7 @@ interface GatewayState {
health: GatewayHealth | null;
isInitialized: boolean;
lastError: string | null;
// Actions
init: () => Promise<void>;
start: () => Promise<void>;
@@ -36,37 +36,37 @@ export const useGatewayStore = create<GatewayState>((set, get) => ({
health: null,
isInitialized: false,
lastError: null,
init: async () => {
if (get().isInitialized) return;
try {
// Get initial status
const status = await window.electron.ipcRenderer.invoke('gateway:status') as GatewayStatus;
set({ status, isInitialized: true });
// Listen for status changes
window.electron.ipcRenderer.on('gateway:status-changed', (newStatus) => {
set({ status: newStatus as GatewayStatus });
});
// Listen for errors
window.electron.ipcRenderer.on('gateway:error', (error) => {
set({ lastError: String(error) });
});
// Listen for notifications
window.electron.ipcRenderer.on('gateway:notification', (notification) => {
console.log('Gateway notification:', notification);
});
// Listen for chat events from the gateway and forward to chat store
window.electron.ipcRenderer.on('gateway:chat-message', (data) => {
try {
// Dynamic import to avoid circular dependency
import('./chat').then(({ useChatStore }) => {
const chatData = data as { message?: Record<string, unknown> } | Record<string, unknown>;
const event = ('message' in chatData && typeof chatData.message === 'object')
const event = ('message' in chatData && typeof chatData.message === 'object')
? chatData.message as Record<string, unknown>
: chatData as Record<string, unknown>;
useChatStore.getState().handleChatEvent(event);
@@ -75,32 +75,32 @@ export const useGatewayStore = create<GatewayState>((set, get) => ({
console.warn('Failed to forward chat event:', err);
}
});
} catch (error) {
console.error('Failed to initialize Gateway:', error);
set({ lastError: String(error) });
}
},
start: async () => {
try {
set({ status: { ...get().status, state: 'starting' }, lastError: null });
const result = await window.electron.ipcRenderer.invoke('gateway:start') as { success: boolean; error?: string };
if (!result.success) {
set({
set({
status: { ...get().status, state: 'error', error: result.error },
lastError: result.error || 'Failed to start Gateway'
});
}
} catch (error) {
set({
set({
status: { ...get().status, state: 'error', error: String(error) },
lastError: String(error)
});
}
},
stop: async () => {
try {
await window.electron.ipcRenderer.invoke('gateway:stop');
@@ -110,41 +110,41 @@ export const useGatewayStore = create<GatewayState>((set, get) => ({
set({ lastError: String(error) });
}
},
restart: async () => {
try {
set({ status: { ...get().status, state: 'starting' }, lastError: null });
const result = await window.electron.ipcRenderer.invoke('gateway:restart') as { success: boolean; error?: string };
if (!result.success) {
set({
set({
status: { ...get().status, state: 'error', error: result.error },
lastError: result.error || 'Failed to restart Gateway'
});
}
} catch (error) {
set({
set({
status: { ...get().status, state: 'error', error: String(error) },
lastError: String(error)
});
}
},
checkHealth: async () => {
try {
const result = await window.electron.ipcRenderer.invoke('gateway:health') as {
success: boolean;
ok: boolean;
error?: string;
uptime?: number
const result = await window.electron.ipcRenderer.invoke('gateway:health') as {
success: boolean;
ok: boolean;
error?: string;
uptime?: number
};
const health: GatewayHealth = {
ok: result.ok,
error: result.error,
uptime: result.uptime,
};
set({ health });
return health;
} catch (error) {
@@ -153,22 +153,22 @@ export const useGatewayStore = create<GatewayState>((set, get) => ({
return health;
}
},
rpc: async <T>(method: string, params?: unknown, timeoutMs?: number): Promise<T> => {
const result = await window.electron.ipcRenderer.invoke('gateway:rpc', method, params, timeoutMs) as {
success: boolean;
result?: T;
error?: string;
};
if (!result.success) {
throw new Error(result.error || `RPC call failed: ${method}`);
}
return result.result as T;
},
setStatus: (status) => set({ status }),
clearError: () => set({ lastError: null }),
}));

View File

@@ -3,15 +3,50 @@
* Manages skill/plugin state
*/
import { create } from 'zustand';
import type { Skill } from '../types/skill';
import type { Skill, MarketplaceSkill } from '../types/skill';
type GatewaySkillStatus = {
skillKey: string;
slug?: string;
name?: string;
description?: string;
disabled?: boolean;
emoji?: string;
version?: string;
author?: string;
config?: Record<string, unknown>;
bundled?: boolean;
always?: boolean;
};
type GatewaySkillsStatusResult = {
skills?: GatewaySkillStatus[];
};
type GatewayRpcResponse<T> = {
success: boolean;
result?: T;
error?: string;
};
type ClawHubListResult = {
slug: string;
version?: string;
};
interface SkillsState {
skills: Skill[];
searchResults: MarketplaceSkill[];
loading: boolean;
searching: boolean;
installing: Record<string, boolean>; // slug -> boolean
error: string | null;
// Actions
fetchSkills: () => Promise<void>;
searchSkills: (query: string) => Promise<void>;
installSkill: (slug: string, version?: string) => Promise<void>;
uninstallSkill: (slug: string) => Promise<void>;
enableSkill: (skillId: string) => Promise<void>;
disableSkill: (skillId: string) => Promise<void>;
setSkills: (skills: Skill[]) => void;
@@ -20,26 +55,163 @@ interface SkillsState {
export const useSkillsStore = create<SkillsState>((set, get) => ({
skills: [],
searchResults: [],
loading: false,
searching: false,
installing: {},
error: null,
fetchSkills: async () => {
// skills.status returns a complex nested object, not a simple Skill[] array.
// Skill management is handled in the Skills page.
// For now, use empty list - will be properly integrated later.
set({ skills: [], loading: false });
// Only show loading state if we have no skills yet (initial load)
if (get().skills.length === 0) {
set({ loading: true, error: null });
}
try {
// 1. Fetch from Gateway (running skills)
const gatewayResult = await window.electron.ipcRenderer.invoke(
'gateway:rpc',
'skills.status'
) as GatewayRpcResponse<GatewaySkillsStatusResult>;
// 2. Fetch from ClawHub (installed on disk)
const clawhubResult = await window.electron.ipcRenderer.invoke(
'clawhub:list'
) as { success: boolean; results?: ClawHubListResult[]; error?: string };
// 3. Fetch configurations directly from Electron (since Gateway doesn't return them)
const configResult = await window.electron.ipcRenderer.invoke(
'skill:getAllConfigs'
) as Record<string, { apiKey?: string; env?: Record<string, string> }>;
let combinedSkills: Skill[] = [];
const currentSkills = get().skills;
// Map gateway skills info
if (gatewayResult.success && gatewayResult.result?.skills) {
combinedSkills = gatewayResult.result.skills.map((s: GatewaySkillStatus) => {
// Merge with direct config if available
const directConfig = configResult[s.skillKey] || {};
return {
id: s.skillKey,
slug: s.slug || s.skillKey,
name: s.name || s.skillKey,
description: s.description || '',
enabled: !s.disabled,
icon: s.emoji || '📦',
version: s.version || '1.0.0',
author: s.author,
config: {
...(s.config || {}),
...directConfig,
},
isCore: s.bundled && s.always,
isBundled: s.bundled,
};
});
} else if (currentSkills.length > 0) {
// ... if gateway down ...
combinedSkills = [...currentSkills];
}
// Merge with ClawHub results
if (clawhubResult.success && clawhubResult.results) {
clawhubResult.results.forEach((cs: ClawHubListResult) => {
const existing = combinedSkills.find(s => s.id === cs.slug);
if (!existing) {
const directConfig = configResult[cs.slug] || {};
combinedSkills.push({
id: cs.slug,
slug: cs.slug,
name: cs.slug,
description: 'Recently installed, initializing...',
enabled: false,
icon: '⌛',
version: cs.version || 'unknown',
author: undefined,
config: directConfig,
isCore: false,
isBundled: false,
});
}
});
}
set({ skills: combinedSkills, loading: false });
} catch (error) {
console.error('Failed to fetch skills:', error);
set({ loading: false });
}
},
searchSkills: async (query: string) => {
set({ searching: true, error: null });
try {
const result = await window.electron.ipcRenderer.invoke('clawhub:search', { query }) as { success: boolean; results?: MarketplaceSkill[]; error?: string };
if (result.success) {
set({ searchResults: result.results || [] });
} else {
throw new Error(result.error || 'Search failed');
}
} catch (error) {
set({ error: String(error) });
} finally {
set({ searching: false });
}
},
installSkill: async (slug: string, version?: string) => {
set((state) => ({ installing: { ...state.installing, [slug]: true } }));
try {
const result = await window.electron.ipcRenderer.invoke('clawhub:install', { slug, version }) as { success: boolean; error?: string };
if (!result.success) {
throw new Error(result.error || 'Install failed');
}
// Refresh skills after install
await get().fetchSkills();
} catch (error) {
console.error('Install error:', error);
throw error;
} finally {
set((state) => {
const newInstalling = { ...state.installing };
delete newInstalling[slug];
return { installing: newInstalling };
});
}
},
uninstallSkill: async (slug: string) => {
set((state) => ({ installing: { ...state.installing, [slug]: true } }));
try {
const result = await window.electron.ipcRenderer.invoke('clawhub:uninstall', { slug }) as { success: boolean; error?: string };
if (!result.success) {
throw new Error(result.error || 'Uninstall failed');
}
// Refresh skills after uninstall
await get().fetchSkills();
} catch (error) {
console.error('Uninstall error:', error);
throw error;
} finally {
set((state) => {
const newInstalling = { ...state.installing };
delete newInstalling[slug];
return { installing: newInstalling };
});
}
},
enableSkill: async (skillId) => {
const { updateSkill } = get();
try {
const result = await window.electron.ipcRenderer.invoke(
'gateway:rpc',
'skills.enable',
{ skillId }
) as { success: boolean; error?: string };
'skills.update',
{ skillKey: skillId, enabled: true }
) as GatewayRpcResponse<unknown>;
if (result.success) {
updateSkill(skillId, { enabled: true });
} else {
@@ -50,23 +222,22 @@ export const useSkillsStore = create<SkillsState>((set, get) => ({
throw error;
}
},
disableSkill: async (skillId) => {
const { updateSkill, skills } = get();
// Check if skill is a core skill
const skill = skills.find((s) => s.id === skillId);
if (skill?.isCore) {
throw new Error('Cannot disable core skill');
}
try {
const result = await window.electron.ipcRenderer.invoke(
'gateway:rpc',
'skills.disable',
{ skillId }
) as { success: boolean; error?: string };
'skills.update',
{ skillKey: skillId, enabled: false }
) as GatewayRpcResponse<unknown>;
if (result.success) {
updateSkill(skillId, { enabled: false });
} else {
@@ -77,9 +248,9 @@ export const useSkillsStore = create<SkillsState>((set, get) => ({
throw error;
}
},
setSkills: (skills) => set({ skills }),
updateSkill: (skillId, updates) => {
set((state) => ({
skills: state.skills.map((skill) =>

View File

@@ -6,13 +6,30 @@
/**
* Supported channel types
*/
export type ChannelType = 'whatsapp' | 'telegram' | 'discord' | 'slack' | 'wechat';
export type ChannelType =
| 'whatsapp'
| 'telegram'
| 'discord'
| 'slack'
| 'signal'
| 'feishu'
| 'imessage'
| 'matrix'
| 'line'
| 'msteams'
| 'googlechat'
| 'mattermost';
/**
* Channel connection status
*/
export type ChannelStatus = 'connected' | 'disconnected' | 'connecting' | 'error';
/**
* Channel connection type
*/
export type ChannelConnectionType = 'token' | 'qr' | 'oauth' | 'webhook';
/**
* Channel data structure
*/
@@ -21,6 +38,7 @@ export interface Channel {
type: ChannelType;
name: string;
status: ChannelStatus;
accountId?: string;
lastActivity?: string;
error?: string;
avatar?: string;
@@ -28,27 +46,32 @@ export interface Channel {
}
/**
* Channel configuration for each type
* Channel configuration field definition
*/
export interface ChannelConfig {
whatsapp: {
phoneNumber?: string;
};
telegram: {
botToken?: string;
chatId?: string;
};
discord: {
botToken?: string;
guildId?: string;
};
slack: {
botToken?: string;
appToken?: string;
};
wechat: {
appId?: string;
};
export interface ChannelConfigField {
key: string;
label: string;
type: 'text' | 'password' | 'select';
placeholder?: string;
required?: boolean;
envVar?: string;
description?: string;
options?: { value: string; label: string }[];
}
/**
* Channel metadata with configuration info
*/
export interface ChannelMeta {
id: ChannelType;
name: string;
icon: string;
description: string;
connectionType: ChannelConnectionType;
docsUrl: string;
configFields: ChannelConfigField[];
instructions: string[];
isPlugin?: boolean;
}
/**
@@ -59,7 +82,14 @@ export const CHANNEL_ICONS: Record<ChannelType, string> = {
telegram: '✈️',
discord: '🎮',
slack: '💼',
wechat: '💬',
signal: '🔒',
feishu: '🐦',
imessage: '💬',
matrix: '🔗',
line: '🟢',
msteams: '👔',
googlechat: '💭',
mattermost: '💠',
};
/**
@@ -70,5 +100,377 @@ export const CHANNEL_NAMES: Record<ChannelType, string> = {
telegram: 'Telegram',
discord: 'Discord',
slack: 'Slack',
wechat: 'WeChat',
signal: 'Signal',
feishu: 'Feishu / Lark',
imessage: 'iMessage',
matrix: 'Matrix',
line: 'LINE',
msteams: 'Microsoft Teams',
googlechat: 'Google Chat',
mattermost: 'Mattermost',
};
/**
* Channel metadata with configuration information
*/
export const CHANNEL_META: Record<ChannelType, ChannelMeta> = {
telegram: {
id: 'telegram',
name: 'Telegram',
icon: '✈️',
description: 'Connect Telegram using a bot token from @BotFather',
connectionType: 'token',
docsUrl: 'https://docs.openclaw.ai/channels/telegram',
configFields: [
{
key: 'botToken',
label: 'Bot Token',
type: 'password',
placeholder: '123456:ABC-DEF...',
required: true,
envVar: 'TELEGRAM_BOT_TOKEN',
},
],
instructions: [
'Open Telegram and search for @BotFather',
'Send /newbot and follow the instructions',
'Copy the bot token provided',
'Paste the token below',
],
},
discord: {
id: 'discord',
name: 'Discord',
icon: '🎮',
description: 'Connect Discord using a bot token from Developer Portal',
connectionType: 'token',
docsUrl: 'https://docs.openclaw.ai/channels/discord',
configFields: [
{
key: 'token',
label: 'Bot Token',
type: 'password',
placeholder: 'Your Discord bot token',
required: true,
envVar: 'DISCORD_BOT_TOKEN',
},
{
key: 'guildId',
label: 'Guild/Server ID (optional)',
type: 'text',
placeholder: 'e.g., 123456789012345678',
required: false,
description: 'Limit bot to a specific server. Right-click server → Copy Server ID.',
},
{
key: 'channelId',
label: 'Channel ID (optional)',
type: 'text',
placeholder: 'e.g., 123456789012345678',
required: false,
description: 'Limit bot to a specific channel. Right-click channel → Copy Channel ID.',
},
],
instructions: [
'Go to Discord Developer Portal → Applications → New Application',
'In Bot section: Add Bot, then copy the Bot Token',
'Enable Message Content Intent + Server Members Intent in Bot → Privileged Gateway Intents',
'In OAuth2 → URL Generator: select "bot" + "applications.commands", add message permissions',
'Invite the bot to your server using the generated URL',
'Paste the bot token below',
],
},
slack: {
id: 'slack',
name: 'Slack',
icon: '💼',
description: 'Connect Slack using bot and app tokens',
connectionType: 'token',
docsUrl: 'https://docs.openclaw.ai/channels/slack',
configFields: [
{
key: 'botToken',
label: 'Bot Token (xoxb-...)',
type: 'password',
placeholder: 'xoxb-...',
required: true,
envVar: 'SLACK_BOT_TOKEN',
},
{
key: 'appToken',
label: 'App Token (xapp-...)',
type: 'password',
placeholder: 'xapp-...',
required: false,
envVar: 'SLACK_APP_TOKEN',
},
],
instructions: [
'Go to api.slack.com/apps',
'Create a new app from scratch',
'Add required OAuth scopes',
'Install to workspace and copy tokens',
],
},
whatsapp: {
id: 'whatsapp',
name: 'WhatsApp',
icon: '📱',
description: 'Connect WhatsApp by scanning a QR code',
connectionType: 'qr',
docsUrl: 'https://docs.openclaw.ai/channels/whatsapp',
configFields: [],
instructions: [
'Open WhatsApp on your phone',
'Go to Settings > Linked Devices',
'Tap "Link a Device"',
'Scan the QR code shown below',
],
},
signal: {
id: 'signal',
name: 'Signal',
icon: '🔒',
description: 'Connect Signal using signal-cli',
connectionType: 'token',
docsUrl: 'https://docs.openclaw.ai/channels/signal',
configFields: [
{
key: 'phoneNumber',
label: 'Phone Number',
type: 'text',
placeholder: '+1234567890',
required: true,
},
],
instructions: [
'Install signal-cli on your system',
'Register or link your phone number',
'Enter your phone number below',
],
},
feishu: {
id: 'feishu',
name: 'Feishu / Lark',
icon: '🐦',
description: 'Connect Feishu/Lark bot via WebSocket',
connectionType: 'token',
docsUrl: 'https://docs.openclaw.ai/channels/feishu',
configFields: [
{
key: 'appId',
label: 'App ID',
type: 'text',
placeholder: 'cli_xxxxxx',
required: true,
envVar: 'FEISHU_APP_ID',
},
{
key: 'appSecret',
label: 'App Secret',
type: 'password',
placeholder: 'Your app secret',
required: true,
envVar: 'FEISHU_APP_SECRET',
},
],
instructions: [
'Go to Feishu Open Platform',
'Create a new application',
'Get App ID and App Secret',
'Configure event subscription',
],
isPlugin: true,
},
imessage: {
id: 'imessage',
name: 'iMessage',
icon: '💬',
description: 'Connect iMessage via BlueBubbles (macOS)',
connectionType: 'token',
docsUrl: 'https://docs.openclaw.ai/channels/bluebubbles',
configFields: [
{
key: 'serverUrl',
label: 'BlueBubbles Server URL',
type: 'text',
placeholder: 'http://localhost:1234',
required: true,
},
{
key: 'password',
label: 'Server Password',
type: 'password',
placeholder: 'Your server password',
required: true,
},
],
instructions: [
'Install BlueBubbles server on your Mac',
'Note the server URL and password',
'Enter the connection details below',
],
},
matrix: {
id: 'matrix',
name: 'Matrix',
icon: '🔗',
description: 'Connect to Matrix protocol',
connectionType: 'token',
docsUrl: 'https://docs.openclaw.ai/channels/matrix',
configFields: [
{
key: 'homeserver',
label: 'Homeserver URL',
type: 'text',
placeholder: 'https://matrix.org',
required: true,
},
{
key: 'accessToken',
label: 'Access Token',
type: 'password',
placeholder: 'Your access token',
required: true,
},
],
instructions: [
'Create a Matrix account or use existing',
'Get an access token from your client',
'Enter the homeserver and token below',
],
isPlugin: true,
},
line: {
id: 'line',
name: 'LINE',
icon: '🟢',
description: 'Connect LINE Messaging API',
connectionType: 'token',
docsUrl: 'https://docs.openclaw.ai/channels/line',
configFields: [
{
key: 'channelAccessToken',
label: 'Channel Access Token',
type: 'password',
placeholder: 'Your LINE channel access token',
required: true,
envVar: 'LINE_CHANNEL_ACCESS_TOKEN',
},
{
key: 'channelSecret',
label: 'Channel Secret',
type: 'password',
placeholder: 'Your LINE channel secret',
required: true,
envVar: 'LINE_CHANNEL_SECRET',
},
],
instructions: [
'Go to LINE Developers Console',
'Create a Messaging API channel',
'Get Channel Access Token and Secret',
],
isPlugin: true,
},
msteams: {
id: 'msteams',
name: 'Microsoft Teams',
icon: '👔',
description: 'Connect Microsoft Teams via Bot Framework',
connectionType: 'token',
docsUrl: 'https://docs.openclaw.ai/channels/msteams',
configFields: [
{
key: 'appId',
label: 'App ID',
type: 'text',
placeholder: 'Your Microsoft App ID',
required: true,
envVar: 'MSTEAMS_APP_ID',
},
{
key: 'appPassword',
label: 'App Password',
type: 'password',
placeholder: 'Your Microsoft App Password',
required: true,
envVar: 'MSTEAMS_APP_PASSWORD',
},
],
instructions: [
'Go to Azure Portal',
'Register a new Bot application',
'Get App ID and create a password',
'Configure Teams channel',
],
isPlugin: true,
},
googlechat: {
id: 'googlechat',
name: 'Google Chat',
icon: '💭',
description: 'Connect Google Chat via webhook',
connectionType: 'webhook',
docsUrl: 'https://docs.openclaw.ai/channels/googlechat',
configFields: [
{
key: 'serviceAccountKey',
label: 'Service Account JSON Path',
type: 'text',
placeholder: '/path/to/service-account.json',
required: true,
},
],
instructions: [
'Create a Google Cloud project',
'Enable Google Chat API',
'Create a service account',
'Download the JSON key file',
],
},
mattermost: {
id: 'mattermost',
name: 'Mattermost',
icon: '💠',
description: 'Connect Mattermost via Bot API',
connectionType: 'token',
docsUrl: 'https://docs.openclaw.ai/channels/mattermost',
configFields: [
{
key: 'serverUrl',
label: 'Server URL',
type: 'text',
placeholder: 'https://your-mattermost.com',
required: true,
},
{
key: 'botToken',
label: 'Bot Access Token',
type: 'password',
placeholder: 'Your bot access token',
required: true,
},
],
instructions: [
'Go to Mattermost Integrations',
'Create a new Bot Account',
'Copy the access token',
],
isPlugin: true,
},
};
/**
* Get primary supported channels (non-plugin, commonly used)
*/
export function getPrimaryChannels(): ChannelType[] {
return ['telegram', 'discord', 'slack', 'whatsapp', 'feishu'];
}
/**
* Get all available channels including plugins
*/
export function getAllChannels(): ChannelType[] {
return Object.keys(CHANNEL_META) as ChannelType[];
}

View File

@@ -3,34 +3,22 @@
* Types for skills/plugins
*/
/**
* Skill category
*/
export type SkillCategory =
| 'productivity'
| 'developer'
| 'smart-home'
| 'media'
| 'communication'
| 'security'
| 'information'
| 'utility'
| 'custom';
/**
* Skill data structure
*/
export interface Skill {
id: string;
slug?: string;
name: string;
description: string;
enabled: boolean;
category: SkillCategory;
icon?: string;
version?: string;
author?: string;
configurable?: boolean;
config?: Record<string, unknown>;
isCore?: boolean;
isBundled?: boolean;
dependencies?: string[];
}
@@ -48,6 +36,20 @@ export interface SkillBundle {
recommended?: boolean;
}
/**
* Marketplace skill data
*/
export interface MarketplaceSkill {
slug: string;
name: string;
description: string;
version: string;
author?: string;
downloads?: number;
stars?: number;
}
/**
* Skill configuration schema
*/