File size: 9,792 Bytes
48eafa7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df790cc
 
 
48eafa7
 
df790cc
 
 
48eafa7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e6ed1f4
 
 
 
 
48eafa7
 
 
 
 
 
df790cc
48eafa7
 
 
df790cc
48eafa7
 
 
 
 
 
 
 
e6ed1f4
 
 
 
 
 
 
 
48eafa7
 
 
 
 
 
 
df790cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48eafa7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e6ed1f4
 
 
48eafa7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df790cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48eafa7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e6ed1f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48eafa7
 
 
 
 
 
 
 
 
 
 
 
 
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
"use client";

import { create } from "zustand";
import { persist, createJSONStorage } from "zustand/middleware";
import type { AskSmartRequest, AskSmartResponse } from "./types";

export type ChatTurn = {
  id: string;
  question: string;
  response?: AskSmartResponse;
  error?: { status: number; message: string };
  pending?: boolean;
  timestamp: number;
};

export type Conversation = {
  id: string;
  title: string;
  turns: ChatTurn[];
  createdAt: number;
  updatedAt: number;
  /** When set, follow-up questions go to /ask scoped to this doc instead of /ask_smart. */
  pinnedDocId?: string | null;
  pinnedDocName?: string | null;
};

export type Settings = Required<
  Omit<AskSmartRequest, "question" | "history" | "stream">
>;

export const DEFAULT_SETTINGS: Settings = {
  top_k: 1,
  max_new_tokens: 200,
  similarity_threshold: 0.45,
  rerank_threshold: 0.6,
  anchor_threshold: 0.2,
  use_grounding: true,
  repetition_penalty: 1.15,
  no_repeat_ngram_size: 4,
  scaler: 1.0,
  bias_scaler: 1.0,
};

type ChatStore = {
  conversations: Record<string, Conversation>;
  activeId: string | null;
  settings: Settings;
  sidebarOpen: boolean;

  // sync state
  hydrated: boolean;
  syncStatus: "idle" | "saving" | "error";
  lastSavedAt: number;

  // selectors
  active: () => Conversation | null;
  list: () => Conversation[];

  // mutations
  newConversation: () => string;
  newConversationPinned: (doc_id: string, doc_name: string) => string;
  openConversation: (id: string) => void;
  deleteConversation: (id: string) => void;
  renameConversation: (id: string, title: string) => void;
  pinDoc: (id: string, doc_id: string | null, doc_name?: string | null) => void;
  appendTurn: (turn: ChatTurn) => void;
  patchTurn: (id: string, patch: Partial<ChatTurn>) => void;
  clearActive: () => void;

  setSettings: (next: Settings) => void;
  resetSettings: () => void;
  toggleSidebar: () => void;
  setSidebarOpen: (open: boolean) => void;

  // sync helpers (used by useBackendSync hook)
  _setHydrated: (v: boolean) => void;
  _setSyncStatus: (v: "idle" | "saving" | "error") => void;
  _hydrateFromRemote: (payload: {
    conversations: Record<string, Conversation>;
    activeId: string | null;
  }) => void;
};

const newId = () =>
  (typeof crypto !== "undefined" && crypto.randomUUID
    ? crypto.randomUUID()
    : Math.random().toString(36).slice(2, 12));

/**
 * Build a multi-turn history payload for the backend from a conversation.
 * Excludes pending and errored turns; caps to last `max` Q→A pairs.
 */
export function buildHistory(
  conv: Conversation | null | undefined,
  max = 5
): { question: string; answer: string }[] {
  if (!conv) return [];
  const pairs: { question: string; answer: string }[] = [];
  for (const t of conv.turns) {
    if (t.pending || t.error || !t.response) continue;
    pairs.push({ question: t.question, answer: t.response.answer });
  }
  return pairs.slice(-max);
}

const seedConversation = (): Conversation => ({
  id: newId(),
  title: "New conversation",
  turns: [],
  createdAt: Date.now(),
  updatedAt: Date.now(),
});

export const useChatStore = create<ChatStore>()(
  persist(
    (set, get) => ({
      conversations: {},
      activeId: null,
      settings: DEFAULT_SETTINGS,
      sidebarOpen: true,
      hydrated: false,
      syncStatus: "idle",
      lastSavedAt: 0,

      active: () => {
        const { activeId, conversations } = get();
        return activeId ? conversations[activeId] ?? null : null;
      },

      list: () =>
        Object.values(get().conversations).sort(
          (a, b) => b.updatedAt - a.updatedAt
        ),

      newConversation: () => {
        const c = seedConversation();
        set((s) => ({
          conversations: { ...s.conversations, [c.id]: c },
          activeId: c.id,
        }));
        return c.id;
      },

      newConversationPinned: (doc_id, doc_name) => {
        const c: Conversation = {
          ...seedConversation(),
          title: doc_name ? `Scoped: ${doc_name}` : "Scoped conversation",
          pinnedDocId: doc_id,
          pinnedDocName: doc_name ?? null,
        };
        set((s) => ({
          conversations: { ...s.conversations, [c.id]: c },
          activeId: c.id,
        }));
        return c.id;
      },

      pinDoc: (id, doc_id, doc_name) =>
        set((s) => {
          const conv = s.conversations[id];
          if (!conv) return s;
          return {
            conversations: {
              ...s.conversations,
              [id]: {
                ...conv,
                pinnedDocId: doc_id,
                pinnedDocName: doc_name ?? conv.pinnedDocName ?? null,
                updatedAt: Date.now(),
              },
            },
          };
        }),

      openConversation: (id) => set({ activeId: id }),

      deleteConversation: (id) =>
        set((s) => {
          const next = { ...s.conversations };
          delete next[id];
          const remainingIds = Object.keys(next);
          return {
            conversations: next,
            activeId:
              s.activeId === id
                ? remainingIds[0] ?? null
                : s.activeId,
          };
        }),

      renameConversation: (id, title) =>
        set((s) => ({
          conversations: {
            ...s.conversations,
            [id]: s.conversations[id]
              ? { ...s.conversations[id], title, updatedAt: Date.now() }
              : s.conversations[id],
          },
        })),

      appendTurn: (turn) =>
        set((s) => {
          let { activeId } = s;
          let conversations = s.conversations;
          if (!activeId || !conversations[activeId]) {
            const c = seedConversation();
            activeId = c.id;
            conversations = { ...conversations, [c.id]: c };
          }
          const conv = conversations[activeId];
          const isFirstTurn = conv.turns.length === 0;
          const updated: Conversation = {
            ...conv,
            title: isFirstTurn
              ? turn.question.slice(0, 60).trim() || conv.title
              : conv.title,
            turns: [...conv.turns, turn],
            updatedAt: Date.now(),
          };
          return {
            activeId,
            conversations: { ...conversations, [activeId]: updated },
          };
        }),

      patchTurn: (id, patch) =>
        set((s) => {
          if (!s.activeId) return s;
          const conv = s.conversations[s.activeId];
          if (!conv) return s;
          const turns = conv.turns.map((t) =>
            t.id === id ? { ...t, ...patch } : t
          );
          return {
            conversations: {
              ...s.conversations,
              [s.activeId]: { ...conv, turns, updatedAt: Date.now() },
            },
          };
        }),

      clearActive: () =>
        set((s) => {
          if (!s.activeId) return s;
          const conv = s.conversations[s.activeId];
          if (!conv) return s;
          return {
            conversations: {
              ...s.conversations,
              [s.activeId]: { ...conv, turns: [], updatedAt: Date.now() },
            },
          };
        }),

      setSettings: (next) => set({ settings: next }),
      resetSettings: () => set({ settings: DEFAULT_SETTINGS }),
      toggleSidebar: () => set((s) => ({ sidebarOpen: !s.sidebarOpen })),
      setSidebarOpen: (open) => set({ sidebarOpen: open }),

      // ── sync helpers ─────────────────────────────────────────────
      _setHydrated: (v) => set({ hydrated: v }),
      _setSyncStatus: (v) => set({ syncStatus: v }),
      _hydrateFromRemote: ({ conversations, activeId }) =>
        set((s) => {
          // Merge remote into local: remote wins per-id (server is the
          // source of truth on hydrate). If remote is empty but local has
          // pending in-flight turns, keep local β€” avoids losing a turn
          // that's mid-flight when hydration races with the request.
          const remoteIds = Object.keys(conversations);
          if (remoteIds.length === 0) {
            // Server is empty β€” keep local; the next save will populate it.
            return { hydrated: true };
          }
          // Preserve any locally-pending turns that aren't yet on server.
          const merged: Record<string, Conversation> = { ...conversations };
          for (const [id, local] of Object.entries(s.conversations)) {
            if (!merged[id]) {
              merged[id] = local;
              continue;
            }
            const localPending = local.turns.filter((t) => t.pending);
            if (localPending.length === 0) continue;
            const serverTurnIds = new Set(merged[id].turns.map((t) => t.id));
            const extras = localPending.filter(
              (t) => !serverTurnIds.has(t.id)
            );
            if (extras.length > 0) {
              merged[id] = {
                ...merged[id],
                turns: [...merged[id].turns, ...extras],
              };
            }
          }
          const nextActive =
            activeId && merged[activeId]
              ? activeId
              : s.activeId && merged[s.activeId]
              ? s.activeId
              : Object.keys(merged)[0] ?? null;
          return {
            conversations: merged,
            activeId: nextActive,
            hydrated: true,
          };
        }),
    }),
    {
      name: "etiya-d2l-chat",
      storage: createJSONStorage(() => localStorage),
      partialize: (state) => ({
        conversations: state.conversations,
        activeId: state.activeId,
        settings: state.settings,
        sidebarOpen: state.sidebarOpen,
      }),
    }
  )
);