All files / src/store chatStore.ts

49.62% Statements 263/530
66.25% Branches 53/80
78.57% Functions 22/28
49.62% Lines 263/530

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 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 7261x                                                                                                                                                                                                         7x 7x 7x   7x 7x 7x 7x 7x 7x       1x 1x 1x 1x 1x 1x 1x 1x   1x 4x 4x 4x 4x 4x 4x 4x 4x 4x   7x 7x 7x 7x       2x 2x 2x 2x       1x 1x 1x 1x   1x   8x 8x 8x 8x 8x 1x 1x   7x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x   8x         7x 7x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 26x   1x 5x 5x 5x 5x 5x   1x   1x 2x 2x         2x     2x   2x                         2x 2x 2x 2x 2x 2x 2x 2x 2x   1x 2x 2x 2x         2x 2x   2x 2x   1x   1x 5x 5x   5x 5x 5x 5x 5x 5x 5x 5x   1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 2x 2x 2x 1x 1x 1x 1x 2x   1x 2x 2x 2x 2x     2x                                                   2x 2x 2x 2x                                         2x         2x 2x 2x 2x 2x 2x 2x 2x 2x   2x 2x 2x     2x         2x 2x 2x 2x 2x 2x 2x     2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   2x   2x     2x   2x   2x 2x                                                                                                                                                                                                       2x                           2x   2x 2x 2x 2x 4x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   1x 2x 2x 2x 2x 2x     2x         2x   2x     2x 2x 2x 2x 2x 2x 2x   2x 2x       2x   1x 1x 1x 1x 1x 1x 1x 1x   1x 2x     2x         2x                                                                                                                                                                           2x   2x 2x 1x 1x 1x 1x 90x 90x 90x 90x 90x 1x   1x 1x               1x     1x             1x 1x 1x 1x     1x 1x 1x 1x  
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import type { AgentStreamDelta } from '../lib/gateway-client';
import { getClient } from './connectionStore';
import { intelligenceClient } from '../lib/intelligence-client';
import { getMemoryExtractor } from '../lib/memory-extractor';
import { getAgentSwarm } from '../lib/agent-swarm';
import { getSkillDiscovery } from '../lib/skill-discovery';
import { useOfflineStore, isOffline } from './offlineStore';
import { useConnectionStore } from './connectionStore';
 
export interface MessageFile {
  name: string;
  path?: string;
  size?: number;
  type?: string;
}
 
export interface CodeBlock {
  language?: string;
  filename?: string;
  content?: string;
}
 
export interface Message {
  id: string;
  role: 'user' | 'assistant' | 'tool' | 'hand' | 'workflow' | 'system';
  content: string;
  timestamp: Date;
  runId?: string;
  streaming?: boolean;
  toolName?: string;
  toolInput?: string;
  toolOutput?: string;
  error?: string;
  // Hand event fields
  handName?: string;
  handStatus?: string;
  handResult?: unknown;
  // Workflow event fields
  workflowId?: string;
  workflowStep?: string;
  workflowStatus?: string;
  workflowResult?: unknown;
  // Output files and code blocks
  files?: MessageFile[];
  codeBlocks?: CodeBlock[];
}
 
export interface Conversation {
  id: string;
  title: string;
  messages: Message[];
  sessionKey: string | null;
  agentId: string | null;
  createdAt: Date;
  updatedAt: Date;
}
 
export interface Agent {
  id: string;
  name: string;
  icon: string;
  color: string;
  lastMessage: string;
  time: string;
}
 
export interface AgentProfileLike {
  id: string;
  name: string;
  nickname?: string;
  role?: string;
}
 
interface ChatState {
  messages: Message[];
  conversations: Conversation[];
  currentConversationId: string | null;
  agents: Agent[];
  currentAgent: Agent | null;
  isStreaming: boolean;
  isLoading: boolean;
  currentModel: string;
  sessionKey: string | null;
 
  addMessage: (message: Message) => void;
  updateMessage: (id: string, updates: Partial<Message>) => void;
  setIsLoading: (loading: boolean) => void;
  setCurrentAgent: (agent: Agent) => void;
  syncAgents: (profiles: AgentProfileLike[]) => void;
  setCurrentModel: (model: string) => void;
  sendMessage: (content: string) => Promise<void>;
  initStreamListener: () => () => void;
  newConversation: () => void;
  switchConversation: (id: string) => void;
  deleteConversation: (id: string) => void;
  dispatchSwarmTask: (description: string, style?: 'sequential' | 'parallel' | 'debate') => Promise<string | null>;
  searchSkills: (query: string) => { results: Array<{ id: string; name: string; description: string }>; totalAvailable: number };
}
 
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 '新对话';
}
 
const DEFAULT_AGENT: Agent = {
  id: '1',
  name: 'ZCLAW',
  icon: '🦞',
  color: 'bg-gradient-to-br from-orange-500 to-red-500',
  lastMessage: '发送消息开始对话',
  time: '',
};
 
export function toChatAgent(profile: AgentProfileLike): Agent {
  return {
    id: profile.id,
    name: profile.name,
    icon: profile.nickname?.slice(0, 1) || '🦞',
    color: 'bg-gradient-to-br from-orange-500 to-red-500',
    lastMessage: profile.role || '新分身',
    time: '',
  };
}
 
function resolveConversationAgentId(agent: Agent | null): string | null {
  if (!agent || agent.id === DEFAULT_AGENT.id) {
    return null;
  }
  return agent.id;
}
 
function resolveGatewayAgentId(agent: Agent | null): string | undefined {
  if (!agent || agent.id === DEFAULT_AGENT.id || agent.id.startsWith('clone_')) {
    return undefined;
  }
  return agent.id;
}
 
function resolveAgentForConversation(agentId: string | null, agents: Agent[]): Agent {
  if (!agentId) {
    return DEFAULT_AGENT;
  }
  return agents.find((agent) => agent.id === agentId) || DEFAULT_AGENT;
}
 
function upsertActiveConversation(
  conversations: Conversation[],
  state: Pick<ChatState, 'messages' | 'sessionKey' | 'currentConversationId' | 'currentAgent'>
): Conversation[] {
  if (state.messages.length === 0) {
    return conversations;
  }
 
  const currentId = state.currentConversationId || generateConvId();
  const existingIdx = conversations.findIndex((conversation) => conversation.id === currentId);
  const nextConversation: Conversation = {
    id: currentId,
    title: deriveTitle(state.messages),
    messages: [...state.messages],
    sessionKey: state.sessionKey,
    agentId: resolveConversationAgentId(state.currentAgent),
    createdAt: existingIdx >= 0 ? conversations[existingIdx].createdAt : new Date(),
    updatedAt: new Date(),
  };
 
  if (existingIdx >= 0) {
    conversations[existingIdx] = nextConversation;
    return conversations;
  }
 
  return [nextConversation, ...conversations];
}
 
export const useChatStore = create<ChatState>()(
  persist(
    (set, get) => ({
  messages: [],
  conversations: [],
  currentConversationId: null,
  agents: [DEFAULT_AGENT],
  currentAgent: DEFAULT_AGENT,
  isStreaming: false,
  isLoading: false,
  currentModel: 'glm-4-flash',
  sessionKey: null,
 
  addMessage: (message) =>
    set((state) => ({ messages: [...state.messages, message] })),
 
  updateMessage: (id, updates) =>
    set((state) => ({
      messages: state.messages.map((m) =>
        m.id === id ? { ...m, ...updates } : m
      ),
    })),
 
  setIsLoading: (loading) => set({ isLoading: loading }),
 
  setCurrentAgent: (agent) =>
    set((state) => {
      if (state.currentAgent?.id === agent.id) {
        return { currentAgent: agent };
      }
 
      // Save current conversation before switching
      const conversations = upsertActiveConversation([...state.conversations], state);
 
      // Try to find existing conversation for this agent
      const agentConversation = conversations.find(c => c.agentId === agent.id);
 
      if (agentConversation) {
        // Restore the agent's previous conversation
        return {
          conversations,
          currentAgent: agent,
          messages: [...agentConversation.messages],
          sessionKey: agentConversation.sessionKey,
          isStreaming: false,
          currentConversationId: agentConversation.id,
        };
      }
 
      // No existing conversation, start fresh
      return {
        conversations,
        currentAgent: agent,
        messages: [],
        sessionKey: null,
        isStreaming: false,
        currentConversationId: null,
      };
    }),
 
  syncAgents: (profiles) =>
    set((state) => {
      const agents = profiles.length > 0 ? profiles.map(toChatAgent) : [DEFAULT_AGENT];
      const currentAgent = state.currentConversationId
        ? resolveAgentForConversation(
            state.conversations.find((conversation) => conversation.id === state.currentConversationId)?.agentId || null,
            agents
          )
        : state.currentAgent
          ? agents.find((agent) => agent.id === state.currentAgent?.id) || agents[0]
          : agents[0];
      return { agents, currentAgent };
    }),
 
  setCurrentModel: (model) => set({ currentModel: model }),
 
  newConversation: () => {
    const state = get();
    const conversations = upsertActiveConversation([...state.conversations], state);
 
    set({
      conversations,
      messages: [],
      sessionKey: null,
      isStreaming: false,
      currentConversationId: null,
    });
  },
 
  switchConversation: (id: string) => {
    const state = get();
    const conversations = upsertActiveConversation([...state.conversations], state);
 
    const target = conversations.find(c => c.id === id);
    if (target) {
      set({
        conversations,
        messages: [...target.messages],
        sessionKey: target.sessionKey,
        currentAgent: resolveAgentForConversation(target.agentId, state.agents),
        currentConversationId: target.id,
        isStreaming: false,
      });
    }
  },
 
  deleteConversation: (id: string) => {
    const state = get();
    const conversations = state.conversations.filter(c => c.id !== id);
    if (state.currentConversationId === id) {
      set({ conversations, messages: [], sessionKey: null, currentConversationId: null, isStreaming: false });
    } else {
      set({ conversations });
    }
  },
 
  sendMessage: async (content: string) => {
    const { addMessage, currentAgent, sessionKey } = get();
    const effectiveSessionKey = sessionKey || `session_${Date.now()}`;
    const effectiveAgentId = resolveGatewayAgentId(currentAgent);
    const agentId = currentAgent?.id || 'zclaw-main';
 
    // Check if offline - queue message instead of sending
    if (isOffline()) {
      const { queueMessage } = useOfflineStore.getState();
      const queueId = queueMessage(content, effectiveAgentId, effectiveSessionKey);
      console.log(`[Chat] Offline - message queued: ${queueId}`);
 
      // Show a system message about offline queueing
      const systemMsg: Message = {
        id: `system_${Date.now()}`,
        role: 'system',
        content: `后端服务不可用,消息已保存到本地队列。恢复连接后将自动发送。`,
        timestamp: new Date(),
      };
      addMessage(systemMsg);
 
      // Add user message for display
      const userMsg: Message = {
        id: `user_${Date.now()}`,
        role: 'user',
        content,
        timestamp: new Date(),
      };
      addMessage(userMsg);
      return;
    }
 
    // Check context compaction threshold before adding new message
    try {
      const messages = get().messages.map(m => ({ role: m.role, content: m.content }));
      const check = await intelligenceClient.compactor.checkThreshold(messages);
      if (check.should_compact) {
        console.log(`[Chat] Context compaction triggered (${check.urgency}): ${check.current_tokens} tokens`);
        const result = await intelligenceClient.compactor.compact(
          get().messages.map(m => ({
            role: m.role,
            content: m.content,
            id: m.id,
            timestamp: m.timestamp instanceof Date ? m.timestamp.toISOString() : m.timestamp
          })),
          agentId,
          get().currentConversationId ?? undefined
        );
        // Replace messages with compacted version
        const compactedMsgs: Message[] = result.compacted_messages.map((m, i) => ({
          id: m.id || `compacted_${i}_${Date.now()}`,
          role: m.role as Message['role'],
          content: m.content,
          timestamp: m.timestamp ? new Date(m.timestamp) : new Date(),
        }));
        set({ messages: compactedMsgs });
      }
    } catch (err) {
      console.warn('[Chat] Context compaction check failed:', err);
    }
 
    // Build memory-enhanced content
    let enhancedContent = content;
    try {
      const relevantMemories = await intelligenceClient.memory.search({
        agentId,
        query: content,
        limit: 8,
        minImportance: 3,
      });
      const memoryContext = relevantMemories.length > 0
        ? `\n\n## 相关记忆\n${relevantMemories.map(m => `- [${m.type}] ${m.content}`).join('\n')}`
        : '';
      const systemPrompt = await intelligenceClient.identity.buildPrompt(agentId, memoryContext);
      if (systemPrompt) {
        enhancedContent = `<context>\n${systemPrompt}\n</context>\n\n${content}`;
      }
    } catch (err) {
      console.warn('[Chat] Memory enhancement failed, proceeding without:', err);
    }
 
    // Add user message (original content for display)
    const userMsg: Message = {
      id: `user_${Date.now()}`,
      role: 'user',
      content,
      timestamp: new Date(),
    };
    addMessage(userMsg);
 
    // Create placeholder assistant message for streaming
    const assistantId = `assistant_${Date.now()}`;
    const assistantMsg: Message = {
      id: assistantId,
      role: 'assistant',
      content: '',
      timestamp: new Date(),
      streaming: true,
    };
    addMessage(assistantMsg);
    set({ isStreaming: true });
 
    try {
      // Use the connected client from connectionStore (supports both GatewayClient and KernelClient)
      const client = getClient();
 
      // Check connection state first
      const connectionState = useConnectionStore.getState().connectionState;
 
      if (connectionState !== 'connected') {
        // Connection lost during send - update error
        throw new Error(`Not connected (state: ${connectionState})`);
      }
 
      // Declare runId before chatStream so callbacks can access it
      let runId = `run_${Date.now()}`;
 
      // Try streaming first (OpenFang WebSocket)
      const result = await client.chatStream(
        enhancedContent,
        {
          onDelta: (delta: string) => {
            // Update message content directly (works for both KernelClient and GatewayClient)
            set((s) => ({
              messages: s.messages.map((m) =>
                m.id === assistantId
                  ? { ...m, content: m.content + delta }
                  : m
              ),
            }));
          },
          onTool: (tool: string, input: string, output: string) => {
            const toolMsg: Message = {
              id: `tool_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`,
              role: 'tool',
              content: output || input,
              timestamp: new Date(),
              runId,
              toolName: tool,
              toolInput: input,
              toolOutput: output,
            };
            set((state) => ({ messages: [...state.messages, toolMsg] }));
          },
          onHand: (name: string, status: string, result?: unknown) => {
            const handMsg: Message = {
              id: `hand_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`,
              role: 'hand',
              content: result
                ? (typeof result === 'string' ? result : JSON.stringify(result, null, 2))
                : `Hand: ${name} - ${status}`,
              timestamp: new Date(),
              runId,
              handName: name,
              handStatus: status,
              handResult: result,
            };
            set((state) => ({ messages: [...state.messages, handMsg] }));
          },
          onComplete: () => {
            const state = get();
 
            // Save conversation to persist across refresh
            const conversations = upsertActiveConversation([...state.conversations], state);
            const currentConvId = state.currentConversationId || conversations[0]?.id;
 
            set({
              isStreaming: false,
              conversations,
              currentConversationId: currentConvId,
              messages: state.messages.map((m) =>
                m.id === assistantId ? { ...m, streaming: false, runId } : m
              ),
            });
 
            // Async memory extraction after stream completes
            const msgs = get().messages
              .filter(m => m.role === 'user' || m.role === 'assistant')
              .map(m => ({ role: m.role, content: m.content }));
            getMemoryExtractor().extractFromConversation(msgs, agentId, get().currentConversationId ?? undefined).catch(err => {
              console.warn('[Chat] Memory extraction failed:', err);
            });
            // Track conversation for reflection trigger
            intelligenceClient.reflection.recordConversation().catch(err => {
              console.warn('[Chat] Recording conversation failed:', err);
            });
            intelligenceClient.reflection.shouldReflect().then(shouldReflect => {
              if (shouldReflect) {
                intelligenceClient.reflection.reflect(agentId, []).catch(err => {
                  console.warn('[Chat] Reflection failed:', err);
                });
              }
            });
          },
          onError: (error: string) => {
            set((state) => ({
              isStreaming: false,
              messages: state.messages.map((m) =>
                m.id === assistantId
                  ? { ...m, content: `⚠️ ${error}`, streaming: false, error }
                  : m
              ),
            }));
          },
        },
        {
          sessionKey: effectiveSessionKey,
          agentId: effectiveAgentId,
        }
      );
 
      // Update runId from the result if available
      if (result?.runId) {
        runId = result.runId;
      }
 
      if (!sessionKey) {
        set({ sessionKey: effectiveSessionKey });
      }
 
      // Store runId on the message for correlation
      set((state) => ({
        messages: state.messages.map((m) =>
          m.id === assistantId ? { ...m, runId } : m
        ),
      }));
    } catch (err: unknown) {
      // Gateway not connected — show error in the assistant bubble
      const errorMessage = err instanceof Error ? err.message : '无法连接 Gateway';
      set((state) => ({
        isStreaming: false,
        messages: state.messages.map((m) =>
          m.id === assistantId
            ? {
                ...m,
                content: `⚠️ ${errorMessage}`,
                streaming: false,
                error: errorMessage,
              }
            : m
        ),
      }));
    }
  },
 
  dispatchSwarmTask: async (description: string, style?: 'sequential' | 'parallel' | 'debate') => {
    try {
      const swarm = getAgentSwarm();
      const task = swarm.createTask(description, {
        communicationStyle: style || 'parallel',
      });
 
      // Set up executor that uses the connected client
      swarm.setExecutor(async (agentId: string, prompt: string, context?: string) => {
        const client = getClient();
        const fullPrompt = context ? `${context}\n\n${prompt}` : prompt;
        const result = await client.chat(fullPrompt, { agentId: agentId.startsWith('clone_') ? undefined : agentId });
        return result?.response || '(无响应)';
      });
 
      const result = await swarm.execute(task);
 
      // Add swarm result as assistant message
      const swarmMsg: Message = {
        id: `swarm_${Date.now()}`,
        role: 'assistant',
        content: result.summary || '协作任务完成',
        timestamp: new Date(),
      };
      get().addMessage(swarmMsg);
 
      return result.task.id;
    } catch (err) {
      console.warn('[Chat] Swarm dispatch failed:', err);
      return null;
    }
  },
 
  searchSkills: (query: string) => {
    const discovery = getSkillDiscovery();
    const result = discovery.searchSkills(query);
    return {
      results: result.results.map(s => ({ id: s.id, name: s.name, description: s.description })),
      totalAvailable: result.totalAvailable,
    };
  },
 
  initStreamListener: () => {
    const client = getClient();
 
    // Check if client supports onAgentStream (GatewayClient does, KernelClient doesn't)
    if (!('onAgentStream' in client)) {
      // KernelClient handles streaming via chatStream callbacks, no separate listener needed
      return () => {};
    }
 
    const unsubscribe = client.onAgentStream((delta: AgentStreamDelta) => {
      const state = get();
 
      const streamingMsg = [...state.messages]
        .reverse()
        .find((m) => (
          m.role === 'assistant'
          && m.streaming
          && (
            (delta.runId && m.runId === delta.runId)
            || (!delta.runId && m.runId == null)
          )
        ))
        || [...state.messages]
          .reverse()
          .find((m) => m.role === 'assistant' && m.streaming);
 
      if (!streamingMsg) return;
 
      if (delta.stream === 'assistant' && (delta.delta || delta.content)) {
        set((s) => ({
          messages: s.messages.map((m) =>
            m.id === streamingMsg.id
              ? { ...m, content: m.content + (delta.delta || delta.content || '') }
              : m
          ),
        }));
      } else if (delta.stream === 'tool') {
        const toolMsg: Message = {
          id: `tool_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`,
          role: 'tool',
          content: delta.toolOutput || '',
          timestamp: new Date(),
          runId: delta.runId,
          toolName: delta.tool,
          toolInput: delta.toolInput,
          toolOutput: delta.toolOutput,
        };
        set((s) => ({ messages: [...s.messages, toolMsg] }));
      } else if (delta.stream === 'lifecycle') {
        if (delta.phase === 'end' || delta.phase === 'error') {
          set((s) => ({
            isStreaming: false,
            messages: s.messages.map((m) =>
              m.id === streamingMsg.id
                ? {
                    ...m,
                    streaming: false,
                    error: delta.phase === 'error' ? delta.error : undefined,
                  }
                : m
            ),
          }));
        }
      } else if (delta.stream === 'hand') {
        // Handle Hand trigger events from OpenFang
        const handMsg: Message = {
          id: `hand_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`,
          role: 'hand',
          content: delta.handResult
            ? (typeof delta.handResult === 'string' ? delta.handResult : JSON.stringify(delta.handResult, null, 2))
            : `Hand: ${delta.handName || 'unknown'} - ${delta.handStatus || 'triggered'}`,
          timestamp: new Date(),
          runId: delta.runId,
          handName: delta.handName,
          handStatus: delta.handStatus,
          handResult: delta.handResult,
        };
        set((s) => ({ messages: [...s.messages, handMsg] }));
      } else if (delta.stream === 'workflow') {
        // Handle Workflow execution events from OpenFang
        const workflowMsg: Message = {
          id: `workflow_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`,
          role: 'workflow',
          content: delta.workflowResult
            ? (typeof delta.workflowResult === 'string' ? delta.workflowResult : JSON.stringify(delta.workflowResult, null, 2))
            : `Workflow: ${delta.workflowId || 'unknown'} step ${delta.workflowStep || '?'} - ${delta.workflowStatus || 'running'}`,
          timestamp: new Date(),
          runId: delta.runId,
          workflowId: delta.workflowId,
          workflowStep: delta.workflowStep,
          workflowStatus: delta.workflowStatus,
          workflowResult: delta.workflowResult,
        };
        set((s) => ({ messages: [...s.messages, workflowMsg] }));
      }
    });
 
    return unsubscribe;
  },
}),
    {
      name: 'zclaw-chat-storage',
      partialize: (state) => ({
        conversations: state.conversations,
        currentModel: state.currentModel,
        currentAgentId: state.currentAgent?.id,
        currentConversationId: state.currentConversationId,
      }),
      onRehydrateStorage: () => (state) => {
        // Rehydrate Date objects from JSON strings
        if (state?.conversations) {
          for (const conv of state.conversations) {
            conv.createdAt = new Date(conv.createdAt);
            conv.updatedAt = new Date(conv.updatedAt);
            for (const msg of conv.messages) {
              msg.timestamp = new Date(msg.timestamp);
              msg.streaming = false; // Never restore streaming state
            }
          }
        }
 
        // Restore messages from current conversation if exists
        if (state?.currentConversationId && state.conversations) {
          const currentConv = state.conversations.find(c => c.id === state.currentConversationId);
          if (currentConv) {
            state.messages = [...currentConv.messages];
            state.sessionKey = currentConv.sessionKey;
          }
        }
      },
    },
  ),
);
 
// Dev-only: Expose chatStore to window for E2E testing
if (import.meta.env.DEV && typeof window !== 'undefined') {
  (window as any).__ZCLAW_STORES__ = (window as any).__ZCLAW_STORES__ || {};
  (window as any).__ZCLAW_STORES__.chat = useChatStore;
}