aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/packages/ui/src/stores/assistant-store.ts
blob: 180031bcc656c065deb40c4c6f09b7e426f9ef9f (plain) (blame)
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
import { invoke } from "@tauri-apps/api/core";
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
import { create } from "zustand";
import type { GenerationStats, StreamChunk } from "@/types/bindings/assistant";

export interface Message {
  role: "user" | "assistant" | "system";
  content: string;
  stats?: GenerationStats;
}

interface AssistantState {
  // State
  messages: Message[];
  isProcessing: boolean;
  isProviderHealthy: boolean | undefined;
  streamingContent: string;
  initialized: boolean;
  streamUnlisten: UnlistenFn | null;

  // Actions
  init: () => Promise<void>;
  checkHealth: () => Promise<void>;
  sendMessage: (
    content: string,
    isEnabled: boolean,
    provider: string,
    endpoint: string,
  ) => Promise<void>;
  finishStreaming: () => void;
  clearHistory: () => void;
  setMessages: (messages: Message[]) => void;
  setIsProcessing: (isProcessing: boolean) => void;
  setIsProviderHealthy: (isProviderHealthy: boolean | undefined) => void;
  setStreamingContent: (streamingContent: string) => void;
}

export const useAssistantStore = create<AssistantState>((set, get) => ({
  // Initial state
  messages: [],
  isProcessing: false,
  isProviderHealthy: false,
  streamingContent: "",
  initialized: false,
  streamUnlisten: null,

  // Actions
  init: async () => {
    const { initialized } = get();
    if (initialized) return;
    set({ initialized: true });
    await get().checkHealth();
  },

  checkHealth: async () => {
    try {
      const isHealthy = await invoke<boolean>("assistant_check_health");
      set({ isProviderHealthy: isHealthy });
    } catch (e) {
      console.error("Failed to check provider health:", e);
      set({ isProviderHealthy: false });
    }
  },

  finishStreaming: () => {
    const { streamUnlisten } = get();
    set({ isProcessing: false, streamingContent: "" });

    if (streamUnlisten) {
      streamUnlisten();
      set({ streamUnlisten: null });
    }
  },

  sendMessage: async (content, isEnabled, provider, endpoint) => {
    if (!content.trim()) return;

    const { messages } = get();

    if (!isEnabled) {
      const newMessage: Message = {
        role: "assistant",
        content: "Assistant is disabled. Enable it in Settings > AI Assistant.",
      };
      set({ messages: [...messages, { role: "user", content }, newMessage] });
      return;
    }

    // Add user message
    const userMessage: Message = { role: "user", content };
    const updatedMessages = [...messages, userMessage];
    set({
      messages: updatedMessages,
      isProcessing: true,
      streamingContent: "",
    });

    // Add empty assistant message for streaming
    const assistantMessage: Message = { role: "assistant", content: "" };
    const withAssistantMessage = [...updatedMessages, assistantMessage];
    set({ messages: withAssistantMessage });

    try {
      // Set up stream listener
      const unlisten = await listen<StreamChunk>(
        "assistant-stream",
        (event) => {
          const chunk = event.payload;
          const currentState = get();

          if (chunk.content) {
            const newStreamingContent =
              currentState.streamingContent + chunk.content;
            const currentMessages = [...currentState.messages];
            const lastIdx = currentMessages.length - 1;

            if (lastIdx >= 0 && currentMessages[lastIdx].role === "assistant") {
              currentMessages[lastIdx] = {
                ...currentMessages[lastIdx],
                content: newStreamingContent,
              };
              set({
                streamingContent: newStreamingContent,
                messages: currentMessages,
              });
            }
          }

          if (chunk.done) {
            const finalMessages = [...currentState.messages];
            const lastIdx = finalMessages.length - 1;

            if (
              chunk.stats &&
              lastIdx >= 0 &&
              finalMessages[lastIdx].role === "assistant"
            ) {
              finalMessages[lastIdx] = {
                ...finalMessages[lastIdx],
                stats: chunk.stats,
              };
              set({ messages: finalMessages });
            }

            get().finishStreaming();
          }
        },
      );

      set({ streamUnlisten: unlisten });

      // Start streaming chat
      await invoke<string>("assistant_chat_stream", {
        messages: withAssistantMessage.slice(0, -1), // Exclude the empty assistant message
      });
    } catch (e) {
      console.error("Failed to send message:", e);
      const errorMessage = e instanceof Error ? e.message : String(e);

      let helpText = "";
      if (provider === "ollama") {
        helpText = `\n\nPlease ensure Ollama is running at ${endpoint}.`;
      } else if (provider === "openai") {
        helpText = "\n\nPlease check your OpenAI API key in Settings.";
      }

      // Update the last message with error
      const currentMessages = [...get().messages];
      const lastIdx = currentMessages.length - 1;
      if (lastIdx >= 0 && currentMessages[lastIdx].role === "assistant") {
        currentMessages[lastIdx] = {
          role: "assistant",
          content: `Error: ${errorMessage}${helpText}`,
        };
        set({ messages: currentMessages });
      }

      get().finishStreaming();
    }
  },

  clearHistory: () => {
    set({ messages: [], streamingContent: "" });
  },

  setMessages: (messages) => {
    set({ messages });
  },

  setIsProcessing: (isProcessing) => {
    set({ isProcessing });
  },

  setIsProviderHealthy: (isProviderHealthy) => {
    set({ isProviderHealthy });
  },

  setStreamingContent: (streamingContent) => {
    set({ streamingContent });
  },
}));