File size: 8,372 Bytes
16b7924
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import Dexie, { type Table } from "dexie";
import { addLogEntry } from "./logEntries";

let currentSearchRunId: string | null = null;

function generateSearchRunId(): string {
  return `${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
}

export function getCurrentSearchRunId(): string {
  if (!currentSearchRunId) {
    currentSearchRunId = generateSearchRunId();
  }
  return currentSearchRunId;
}

export function setCurrentSearchRunId(id: string): void {
  currentSearchRunId = id;
}

export function resetSearchRunId(): void {
  currentSearchRunId = null;
}

function measurePerformance<T>(
  operation: string,
  fn: () => Promise<T>,
): Promise<T> {
  const startTime = performance.now();
  return fn().then(
    (result) => {
      const endTime = performance.now();
      const duration = endTime - startTime;
      if (duration > 100) {
        addLogEntry(`${operation} completed in ${duration.toFixed(2)}ms`);
      }
      return result;
    },
    (error) => {
      const endTime = performance.now();
      const duration = endTime - startTime;
      addLogEntry(
        `${operation} failed after ${duration.toFixed(2)}ms: ${error}`,
      );
      throw error;
    },
  );
}

export interface TextResults {
  type: "text";
  items: Array<{
    title: string;
    url: string;
    snippet: string;
  }>;
}

export interface ImageResults {
  type: "image";
  items: Array<{
    title: string;
    url: string;
    thumbnailUrl: string;
    sourceUrl: string;
  }>;
}

export interface SearchEntry {
  id?: number;
  searchRunId?: string;
  query: string;
  results: TextResults | ImageResults;
  textResults?: TextResults;
  imageResults?: ImageResults;
  timestamp: number;
  resultCount: number;
  source: "user" | "followup" | "suggestion";
  isPinned?: boolean;
  tags?: string[];
}

interface LLMResponse {
  id?: number;
  searchRunId?: string;
  prompt: string;
  response: string;
  model: string;
  timestamp: number;
  searchId?: number;
  quality?: number;
}

interface ChatHistoryMessage {
  id?: number;
  role: "user" | "assistant";
  content: string;
  timestamp: number;
  conversationId: string;
  metadata?: Record<string, unknown>;
}

class HistoryDatabase extends Dexie {
  searches!: Table<SearchEntry>;
  llmResponses!: Table<LLMResponse>;
  chatHistory!: Table<ChatHistoryMessage>;

  constructor() {
    super("History");

    this.version(1).stores({
      searches: "++id, searchRunId, query, timestamp, source, isPinned",
      llmResponses: "++id, searchId, searchRunId, timestamp, model",
      chatHistory:
        "++id, conversationId, timestamp, [conversationId+timestamp]",
    });

    this.searches.hook("creating", () => {
      this.performCleanup().catch((error) => {
        addLogEntry(`Cleanup hook error: ${error}`);
      });
    });
  }

  async performCleanup(): Promise<void> {
    try {
      const { getSettings } = await import("./pubSub");
      const globalSettings = getSettings();
      const settings = {
        autoCleanup: globalSettings.historyAutoCleanup,
        retentionDays: globalSettings.historyRetentionDays,
        maxEntries: globalSettings.historyMaxEntries,
      };
      if (!settings.autoCleanup) return;

      if (settings.retentionDays > 0) {
        const cutoffTime =
          Date.now() - settings.retentionDays * 24 * 60 * 60 * 1000;

        const oldSearches = await this.searches
          .where("timestamp")
          .below(cutoffTime)
          .and((search) => !search.isPinned)
          .limit(100)
          .toArray();

        if (oldSearches.length > 0) {
          await this.searches.bulkDelete(
            oldSearches
              .map((s) => s.id)
              .filter((id): id is number => id !== undefined),
          );
          addLogEntry(`Cleaned up ${oldSearches.length} old search entries`);
        }
      }

      const totalCount = await this.searches.count();
      if (totalCount > settings.maxEntries) {
        const excess = await this.searches
          .orderBy("timestamp")
          .reverse()
          .offset(settings.maxEntries)
          .filter((search) => !search.isPinned)
          .toArray();

        if (excess.length > 0) {
          await this.searches.bulkDelete(
            excess
              .map((s) => s.id)
              .filter((id): id is number => id !== undefined),
          );
          addLogEntry(`Removed ${excess.length} excess search entries`);
        }
      }
    } catch (error) {
      addLogEntry(`Cleanup error: ${error}`);
    }
  }
}

export const historyDatabase = new HistoryDatabase();

export async function updateSearchResults(
  searchRunId: string,
  results: Partial<SearchEntry>,
): Promise<void> {
  try {
    await historyDatabase.transaction(
      "rw",
      historyDatabase.searches,
      async () => {
        const latest = await historyDatabase.searches
          .where("searchRunId")
          .equals(searchRunId)
          .first();

        if (latest?.id !== undefined) {
          const updatedEntry = { ...latest, ...results };
          if (results.textResults) {
            updatedEntry.results = results.textResults;
          }
          await historyDatabase.searches.update(latest.id, updatedEntry);
        }
      },
    );
  } catch (error) {
    addLogEntry(`Error updating search results: ${error}`);
  }
}

export async function addSearchToHistory(
  query: string,
  results: TextResults | ImageResults,
  source: "user" | "followup" | "suggestion" = "user",
): Promise<number | undefined> {
  return measurePerformance("Add search to history", async () => {
    return await historyDatabase.searches.add({
      searchRunId: getCurrentSearchRunId(),
      query,
      results,
      timestamp: Date.now(),
      resultCount: results.items.length,
      source,
      isPinned: false,
    });
  }).catch((error) => {
    addLogEntry(`Error adding search to history: ${error}`);
    return undefined;
  });
}

export async function getRecentSearches(
  limit: number = 10,
): Promise<SearchEntry[]> {
  return measurePerformance("Get recent searches", async () => {
    return await historyDatabase.searches
      .orderBy("timestamp")
      .reverse()
      .limit(limit)
      .toArray();
  }).catch((error) => {
    addLogEntry(`Error fetching recent searches: ${error}`);
    return [];
  });
}

export async function saveLlmResponseForQuery(
  query: string,
  response: string,
  model: string = "",
): Promise<void> {
  try {
    const searchRunId = getCurrentSearchRunId();
    const latest = await historyDatabase.searches
      .where("searchRunId")
      .equals(searchRunId)
      .first();

    await historyDatabase.llmResponses.add({
      searchRunId,
      prompt: query,
      response,
      model,
      timestamp: Date.now(),
      searchId: latest?.id,
    });
  } catch (error) {
    addLogEntry(`Error saving LLM response: ${error}`);
  }
}

export async function getLatestLlmResponseForEntry(
  entry: SearchEntry,
): Promise<string | null> {
  try {
    const searchRunId = entry.searchRunId || entry.query;
    const records = await historyDatabase.llmResponses
      .where("searchRunId")
      .equals(searchRunId)
      .toArray();
    if (records.length > 0) {
      const latest = records.reduce((a, b) =>
        a.timestamp > b.timestamp ? a : b,
      );
      return latest.response;
    }
    return null;
  } catch (error) {
    addLogEntry(`Error getting latest LLM response: ${error}`);
    return null;
  }
}

export async function saveChatMessageForQuery(
  _query: string,
  role: "user" | "assistant",
  content: string,
): Promise<void> {
  try {
    const searchRunId = getCurrentSearchRunId();
    await historyDatabase.chatHistory.add({
      role,
      content,
      timestamp: Date.now(),
      conversationId: searchRunId,
    });
  } catch (error) {
    addLogEntry(`Error saving chat message: ${error}`);
  }
}

export async function getChatMessagesForQuery(
  searchRunId: string,
): Promise<Array<{ role: "user" | "assistant"; content: string }>> {
  try {
    const messages = await historyDatabase.chatHistory
      .where("conversationId")
      .equals(searchRunId)
      .sortBy("timestamp");
    return messages.map((msg) => ({ role: msg.role, content: msg.content }));
  } catch (error) {
    addLogEntry(`Error getting chat messages: ${error}`);
    return [];
  }
}