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

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) =>