Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 | /** * Agent Store - Manages clones/agents, usage statistics, and plugin status * * Extracted from gatewayStore.ts for Phase 11 Store Refactoring. * This store focuses on agent/clone CRUD operations and related metadata. */ import { create } from 'zustand'; import type { GatewayClient } from '../lib/gateway-client'; // === Types === export interface Clone { id: string; name: string; role?: string; nickname?: string; scenarios?: string[]; model?: string; workspaceDir?: string; workspaceResolvedPath?: string; restrictFiles?: boolean; privacyOptIn?: boolean; userName?: string; userRole?: string; createdAt: string; bootstrapReady?: boolean; bootstrapFiles?: Array<{ name: string; path: string; exists: boolean }>; updatedAt?: string; // 人格相关字段 emoji?: string; // Agent emoji, e.g., "🦞", "🤖", "💻" personality?: string; // 人格风格: professional, friendly, creative, concise communicationStyle?: string; // 沟通风格描述 notes?: string; // 用户备注 onboardingCompleted?: boolean; // 是否完成首次引导 } export interface UsageStats { totalSessions: number; totalMessages: number; totalTokens: number; byModel: Record<string, { messages: number; inputTokens: number; outputTokens: number }>; } export interface PluginStatus { id: string; name?: string; status: 'active' | 'inactive' | 'error' | 'loading'; version?: string; description?: string; } export interface CloneCreateOptions { name: string; role?: string; nickname?: string; scenarios?: string[]; model?: string; workspaceDir?: string; restrictFiles?: boolean; privacyOptIn?: boolean; userName?: string; userRole?: string; // 人格相关字段 emoji?: string; personality?: string; communicationStyle?: string; notes?: string; } // === Store State === export interface AgentStateSlice { clones: Clone[]; usageStats: UsageStats | null; pluginStatus: PluginStatus[]; isLoading: boolean; error: string | null; } // === Store Actions === export interface AgentActionsSlice { loadClones: () => Promise<void>; createClone: (opts: CloneCreateOptions) => Promise<Clone | undefined>; updateClone: (id: string, updates: Partial<Clone>) => Promise<Clone | undefined>; deleteClone: (id: string) => Promise<void>; loadUsageStats: () => Promise<void>; loadPluginStatus: () => Promise<void>; setError: (error: string | null) => void; clearError: () => void; } // === Store Interface === export type AgentStore = AgentStateSlice & AgentActionsSlice; // === Client Injection === // For coordinator to inject client - avoids direct import coupling let _client: GatewayClient | null = null; /** * Sets the gateway client for the agent store. * Called by the coordinator during initialization. */ export const setAgentStoreClient = (client: unknown): void => { _client = client as GatewayClient; }; /** * Gets the gateway client. * Returns null if not set (coordinator must initialize first). */ const getClient = (): GatewayClient | null => _client; // === Store Implementation === export const useAgentStore = create<AgentStore>((set, get) => ({ // Initial state clones: [], usageStats: null, pluginStatus: [], isLoading: false, error: null, // Actions loadClones: async () => { const client = getClient(); if (!client) { console.warn('[AgentStore] Client not initialized, skipping loadClones'); return; } try { set({ isLoading: true, error: null }); const result = await client.listClones(); const clones = result?.clones || result?.agents || []; set({ clones, isLoading: false }); // Set default agent ID if we have agents and none is set if (clones.length > 0 && clones[0].id) { const currentDefault = client.getDefaultAgentId(); // Only set if the default doesn't exist in the list const defaultExists = clones.some((c: Clone) => c.id === currentDefault); if (!defaultExists) { client.setDefaultAgentId(clones[0].id); } } } catch (err: unknown) { const errorMessage = err instanceof Error ? err.message : String(err); set({ error: errorMessage, isLoading: false }); // Don't throw - clone loading is non-critical } }, createClone: async (opts: CloneCreateOptions) => { const client = getClient(); if (!client) { console.warn('[AgentStore] Client not initialized'); return undefined; } try { set({ isLoading: true, error: null }); const result = await client.createClone(opts); await get().loadClones(); // Refresh the list return result?.clone; } catch (err: unknown) { const errorMessage = err instanceof Error ? err.message : String(err); set({ error: errorMessage, isLoading: false }); return undefined; } }, updateClone: async (id: string, updates: Partial<Clone>) => { const client = getClient(); if (!client) { console.warn('[AgentStore] Client not initialized'); return undefined; } try { set({ isLoading: true, error: null }); const result = await client.updateClone(id, updates); await get().loadClones(); // Refresh the list return result?.clone; } catch (err: unknown) { const errorMessage = err instanceof Error ? err.message : String(err); set({ error: errorMessage, isLoading: false }); return undefined; } }, deleteClone: async (id: string) => { const client = getClient(); if (!client) { console.warn('[AgentStore] Client not initialized'); return; } try { set({ isLoading: true, error: null }); await client.deleteClone(id); await get().loadClones(); // Refresh the list } catch (err: unknown) { const errorMessage = err instanceof Error ? err.message : String(err); set({ error: errorMessage, isLoading: false }); } }, loadUsageStats: async () => { const client = getClient(); if (!client) { console.warn('[AgentStore] Client not initialized, skipping loadUsageStats'); return; } try { const stats = await client.getUsageStats(); set({ usageStats: stats }); } catch { // Usage stats are non-critical, ignore errors silently } }, loadPluginStatus: async () => { const client = getClient(); if (!client) { console.warn('[AgentStore] Client not initialized, skipping loadPluginStatus'); return; } try { const result = await client.getPluginStatus(); set({ pluginStatus: result?.plugins || [] }); } catch { // Plugin status is non-critical, ignore errors silently } }, setError: (error: string | null) => { set({ error }); }, clearError: () => { set({ error: null }); }, })); // === Selectors === /** * Get a clone by ID */ export const selectCloneById = (id: string) => (state: AgentStore): Clone | undefined => state.clones.find((clone) => clone.id === id); /** * Get all active plugins */ export const selectActivePlugins = (state: AgentStore): PluginStatus[] => state.pluginStatus.filter((plugin) => plugin.status === 'active'); /** * Check if any operation is in progress */ export const selectIsLoading = (state: AgentStore): boolean => state.isLoading; |