File size: 4,390 Bytes
6c3af4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import {
  getCurrentSearchRunId,
  type ImageResults,
  saveChatMessageForQuery,
  type TextResults,
  updateSearchResults,
} from "./history";
import { addLogEntry } from "./logEntries";
import {
  updateImageSearchResults,
  updateLlmTextSearchResults,
  updateTextSearchResults,
  updateTextSearchStale,
} from "./pubSub";
import { searchImages, searchText } from "./search";
import type { defaultSettings } from "./settings";
import { searchResultsToConsider } from "./textGenerationUtilities";
import type {
  ChatMessage,
  ImageSearchResults,
  TextSearchResults,
} from "./types";

type Settings = typeof defaultSettings;

/**
 * Fetches fresh text search results and merges them into existing results,
 * deduplicating by URL. Updates pubSub state for both LLM-visible and UI results.
 */
export async function refreshTextSearchResults(
  searchQuery: string,
  resultsLimit: number,
  existingResults: TextSearchResults,
): Promise<void> {
  const { results: freshResults, stale } = await searchText(
    searchQuery,
    resultsLimit,
  );

  if (freshResults.length === 0) return;

  updateTextSearchStale(stale);

  updateLlmTextSearchResults(freshResults.slice(0, searchResultsToConsider));

  const existingUrls = new Set(existingResults.map(([, , url]) => url));
  const uniqueFreshResults = freshResults.filter(
    ([, , url]) => !existingUrls.has(url),
  );

  if (uniqueFreshResults.length > 0) {
    const updatedResults: TextSearchResults = [
      ...existingResults,
      ...uniqueFreshResults,
    ];
    updateTextSearchResults(updatedResults);

    updateSearchResults(getCurrentSearchRunId(), {
      type: "text",
      items: updatedResults.map(([title, snippet, url]) => ({
        title,
        url,
        snippet,
      })),
    } satisfies TextResults);
  }
}

/**
 * Fetches fresh image search results and merges them into existing results,
 * deduplicating by URL. Fire-and-forget (returns Promise, caller catches errors).
 */
export async function refreshImageSearchResults(
  searchQuery: string,
  resultsLimit: number,
  existingResults: ImageSearchResults,
): Promise<void> {
  const { results: imageResults } = await searchImages(
    searchQuery,
    resultsLimit,
  );

  if (imageResults.length === 0) return;

  const existingUrls = new Set(existingResults.map(([, url]) => url));
  const uniqueFreshResults = imageResults.filter(
    ([, url]) => !existingUrls.has(url),
  );

  if (uniqueFreshResults.length > 0) {
    const updatedImageResults: ImageSearchResults = [
      ...uniqueFreshResults,
      ...existingResults,
    ];
    updateImageSearchResults(updatedImageResults);

    updateSearchResults(getCurrentSearchRunId(), {
      type: "image",
      items: updatedImageResults.map(
        ([title, url, thumbnailUrl, sourceUrl]) => ({
          title,
          url,
          thumbnail: thumbnailUrl,
          sourceUrl,
        }),
      ),
    } satisfies ImageResults);
  }
}

/**
 * Saves a user message and its assistant response to chat history.
 */
export async function persistChatMessages(
  query: string,
  userMessage: string,
  assistantMessage: string,
): Promise<void> {
  await saveChatMessageForQuery(query, "user", userMessage);
  await saveChatMessageForQuery(query, "assistant", assistantMessage);
}

/**
 * Runs the follow-up search phase: generates a related search query from chat
 * history, then refreshes text and image results with deduplication.
 */
export async function runFollowUpSearch(
  messages: ChatMessage[],
  currentInput: string,
  settings: Settings,
  existingTextResults: TextSearchResults,
  existingImageResults: ImageSearchResults,
): Promise<void> {
  const { generateRelatedSearchQuery } = await import("./relatedSearchQuery");
  const relatedQuery = await generateRelatedSearchQuery([...messages]);
  const searchQuery = relatedQuery || currentInput;

  if (settings.enableTextSearch) {
    try {
      await refreshTextSearchResults(
        searchQuery,
        settings.searchResultsLimit,
        existingTextResults,
      );
    } catch (error) {
      addLogEntry(`Error in follow-up search: ${error}`);
    }
  }

  if (settings.enableImageSearch) {
    refreshImageSearchResults(
      searchQuery,
      settings.searchResultsLimit,
      existingImageResults,
    ).catch((error) => {
      addLogEntry(`Error in follow-up image search: ${error}`);
    });
  }
}