All files / src/domains/chat store.ts

0% Statements 0/145
0% Branches 0/1
0% Functions 0/1
0% Lines 0/145

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                                                                                                                                                                                                                                                                                                                                                                                                                                                             
/**
 * Chat Domain Store
 *
 * Valtio-based state management for chat.
 * Replaces Zustand for better performance with fine-grained reactivity.
 */
import { proxy, subscribe } from 'valtio';
import type { Message, Conversation, Agent, AgentProfileLike } from './types';
 
// === Constants ===
 
const DEFAULT_AGENT: Agent = {
  id: '1',
  name: 'ZCLAW',
  icon: '🦞',
  color: 'bg-gradient-to-br from-orange-500 to-red-500',
  lastMessage: '发送消息开始对话',
  time: '',
};
 
// === Helper Functions ===
 
function generateConvId(): string {
  return `conv_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
}
 
function deriveTitle(messages: Message[]): string {
  const firstUser = messages.find(m => m.role === 'user');
  if (firstUser) {
    const text = firstUser.content.trim();
    return text.length > 30 ? text.slice(0, 30) + '...' : text;
  }
  return '新对话';
}
 
export function toChatAgent(profile: AgentProfileLike): Agent {
  return {
    id: profile.id,
    name: profile.name,
    icon: profile.nickname?.slice(0, 1) || profile.name.slice(0, 1) || '🦞',
    color: 'bg-gradient-to-br from-orange-500 to-red-500',
    lastMessage: profile.role || '新分身',
    time: '',
  };
}
 
// === Store Interface ===
 
export interface ChatStore {
  // State
  messages: Message[];
  conversations: Conversation[];
  currentConversationId: string | null;
  agents: Agent[];
  currentAgent: Agent | null;
  isStreaming: boolean;
  currentModel: string;
  sessionKey: string | null;
 
  // Actions
  addMessage: (message: Message) => void;
  updateMessage: (id: string, updates: Partial<Message>) => void;
  deleteMessage: (id: string) => void;
  setCurrentAgent: (agent: Agent) => void;
  syncAgents: (profiles: AgentProfileLike[]) => void;
  setCurrentModel: (model: string) => void;
  setStreaming: (streaming: boolean) => void;
  setSessionKey: (key: string | null) => void;
  newConversation: () => void;
  switchConversation: (id: string) => void;
  deleteConversation: (id: string) => void;
  clearMessages: () => void;
}
 
// === Create Proxy State ===
 
export const chatStore = proxy<ChatStore>({
  // Initial state
  messages: [],
  conversations: [],
  currentConversationId: null,
  agents: [DEFAULT_AGENT],
  currentAgent: DEFAULT_AGENT,
  isStreaming: false,
  currentModel: 'glm-4-flash',
  sessionKey: null,
 
  // === Actions ===
 
  addMessage: (message: Message) => {
    chatStore.messages.push(message);
  },
 
  updateMessage: (id: string, updates: Partial<Message>) => {
    const msg = chatStore.messages.find(m => m.id === id);
    if (msg) {
      Object.assign(msg, updates);
    }
  },
 
  deleteMessage: (id: string) => {
    const index = chatStore.messages.findIndex(m => m.id === id);
    if (index >= 0) {
      chatStore.messages.splice(index, 1);
    }
  },
 
  setCurrentAgent: (agent: Agent) => {
    chatStore.currentAgent = agent;
  },
 
  syncAgents: (profiles: AgentProfileLike[]) => {
    if (profiles.length === 0) {
      chatStore.agents = [DEFAULT_AGENT];
    } else {
      chatStore.agents = profiles.map(toChatAgent);
    }
  },
 
  setCurrentModel: (model: string) => {
    chatStore.currentModel = model;
  },
 
  setStreaming: (streaming: boolean) => {
    chatStore.isStreaming = streaming;
  },
 
  setSessionKey: (key: string | null) => {
    chatStore.sessionKey = key;
  },
 
  newConversation: () => {
    // Save current conversation if has messages
    if (chatStore.messages.length > 0) {
      const conversation: Conversation = {
        id: chatStore.currentConversationId || generateConvId(),
        title: deriveTitle(chatStore.messages),
        messages: [...chatStore.messages],
        sessionKey: chatStore.sessionKey,
        agentId: chatStore.currentAgent?.id || null,
        createdAt: new Date(),
        updatedAt: new Date(),
      };
 
      // Check if conversation already exists
      const existingIndex = chatStore.conversations.findIndex(
        c => c.id === chatStore.currentConversationId
      );
 
      if (existingIndex >= 0) {
        chatStore.conversations[existingIndex] = conversation;
      } else {
        chatStore.conversations.unshift(conversation);
      }
    }
 
    // Reset for new conversation
    chatStore.messages = [];
    chatStore.sessionKey = null;
    chatStore.isStreaming = false;
    chatStore.currentConversationId = null;
  },
 
  switchConversation: (id: string) => {
    const conv = chatStore.conversations.find(c => c.id === id);
    if (conv) {
      // Save current first
      if (chatStore.messages.length > 0) {
        const currentConv: Conversation = {
          id: chatStore.currentConversationId || generateConvId(),
          title: deriveTitle(chatStore.messages),
          messages: [...chatStore.messages],
          sessionKey: chatStore.sessionKey,
          agentId: chatStore.currentAgent?.id || null,
          createdAt: new Date(),
          updatedAt: new Date(),
        };
 
        const existingIndex = chatStore.conversations.findIndex(
          c => c.id === chatStore.currentConversationId
        );
 
        if (existingIndex >= 0) {
          chatStore.conversations[existingIndex] = currentConv;
        } else {
          chatStore.conversations.unshift(currentConv);
        }
      }
 
      // Switch to new
      chatStore.messages = [...conv.messages];
      chatStore.sessionKey = conv.sessionKey;
      chatStore.currentConversationId = conv.id;
    }
  },
 
  deleteConversation: (id: string) => {
    const index = chatStore.conversations.findIndex(c => c.id === id);
    if (index >= 0) {
      chatStore.conversations.splice(index, 1);
 
      // If deleting current, clear messages
      if (chatStore.currentConversationId === id) {
        chatStore.messages = [];
        chatStore.sessionKey = null;
        chatStore.currentConversationId = null;
      }
    }
  },
 
  clearMessages: () => {
    chatStore.messages = [];
  },
});
 
// === Dev Mode Logging ===
 
if (import.meta.env.DEV) {
  subscribe(chatStore, (ops) => {
    console.log('[ChatStore] Changes:', ops);
  });
}