aboutsummaryrefslogtreecommitdiff
path: root/apps/browser-extension/entrypoints/background.ts
blob: 9d46a5e9830371df033db2695c2f381af99b38d5 (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
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
import { getDefaultProject, saveMemory, searchMemories } from "../utils/api"
import {
	CONTAINER_TAGS,
	CONTEXT_MENU_IDS,
	MESSAGE_TYPES,
	POSTHOG_EVENT_KEY,
} from "../utils/constants"
import { trackEvent } from "../utils/posthog"
import { captureTwitterTokens } from "../utils/twitter-auth"
import {
	type TwitterImportConfig,
	TwitterImporter,
} from "../utils/twitter-import"
import type {
	ExtensionMessage,
	MemoryData,
	MemoryPayload,
} from "../utils/types"

export default defineBackground(() => {
	let twitterImporter: TwitterImporter | null = null

	browser.runtime.onInstalled.addListener(async (details) => {
		browser.contextMenus.create({
			id: CONTEXT_MENU_IDS.SAVE_TO_SUPERMEMORY,
			title: "sync to supermemory",
			contexts: ["selection", "page", "link"],
		})

		if (details.reason === "install") {
			await trackEvent("extension_installed", {
				reason: details.reason,
				version: browser.runtime.getManifest().version,
			})
			browser.tabs.create({
				url: browser.runtime.getURL("/welcome.html"),
			})
		}
	})

	// Intercept Twitter requests to capture authentication headers.
	browser.webRequest.onBeforeSendHeaders.addListener(
		(details) => {
			captureTwitterTokens(details)
			return {}
		},
		{ urls: ["*://x.com/*", "*://twitter.com/*"] },
		["requestHeaders", "extraHeaders"],
	)

	// Handle context menu clicks.
	browser.contextMenus.onClicked.addListener(async (info, tab) => {
		if (info.menuItemId === CONTEXT_MENU_IDS.SAVE_TO_SUPERMEMORY) {
			if (tab?.id) {
				try {
					await browser.tabs.sendMessage(tab.id, {
						action: MESSAGE_TYPES.SAVE_MEMORY,
						actionSource: "context_menu",
					})
				} catch (error) {
					console.error("Failed to send message to content script:", error)
				}
			}
		}
	})

	// Send message to current active tab.
	const sendMessageToCurrentTab = async (message: string) => {
		const tabs = await browser.tabs.query({
			active: true,
			currentWindow: true,
		})
		if (tabs.length > 0 && tabs[0].id) {
			await browser.tabs.sendMessage(tabs[0].id, {
				type: MESSAGE_TYPES.IMPORT_UPDATE,
				importedMessage: message,
			})
		}
	}

	/**
	 * Send import completion message
	 */
	const sendImportDoneMessage = async (totalImported: number) => {
		const tabs = await browser.tabs.query({
			active: true,
			currentWindow: true,
		})
		if (tabs.length > 0 && tabs[0].id) {
			await browser.tabs.sendMessage(tabs[0].id, {
				type: MESSAGE_TYPES.IMPORT_DONE,
				totalImported,
			})
		}
	}

	/**
	 * Save memory to supermemory API
	 */
	const saveMemoryToSupermemory = async (
		data: MemoryData,
		actionSource: string,
	): Promise<{ success: boolean; data?: unknown; error?: string }> => {
		try {
			let containerTag: string = CONTAINER_TAGS.DEFAULT_PROJECT
			try {
				const defaultProject = await getDefaultProject()
				if (defaultProject?.containerTag) {
					containerTag = defaultProject.containerTag
				}
			} catch (error) {
				console.warn("Failed to get default project, using fallback:", error)
			}

			const payload: MemoryPayload = {
				containerTags: [containerTag],
				content:
					data.content ||
					`${data.highlightedText}\n\n${data.html}\n\n${data?.url}`,
				metadata: { sm_source: "consumer" },
			}

			const responseData = await saveMemory(payload)

			await trackEvent(POSTHOG_EVENT_KEY.SAVE_MEMORY_ATTEMPTED, {
				source: `${POSTHOG_EVENT_KEY.SOURCE}_${actionSource}`,
				has_highlight: !!data.highlightedText,
				url_domain: data.url ? new URL(data.url).hostname : undefined,
			})

			return { success: true, data: responseData }
		} catch (error) {
			return {
				success: false,
				error: error instanceof Error ? error.message : "Unknown error",
			}
		}
	}

	const getRelatedMemories = async (
		data: string,
		eventSource: string,
	): Promise<{ success: boolean; data?: unknown; error?: string }> => {
		try {
			const responseData = await searchMemories(data)
			const response = responseData as {
				results?: Array<{ memory?: string }>
			}
			const memories: string[] = []
			response.results?.forEach((result, index) => {
				memories.push(`${index + 1}. ${result.memory} \n`)
			})
			console.log("Memories:", memories)
			await trackEvent(eventSource)
			return { success: true, data: memories }
		} catch (error) {
			return {
				success: false,
				error: error instanceof Error ? error.message : "Unknown error",
			}
		}
	}

	/**
	 * Handle extension messages
	 */
	browser.runtime.onMessage.addListener(
		(message: ExtensionMessage, _sender, sendResponse) => {
			// Handle Twitter import request
			if (message.type === MESSAGE_TYPES.BATCH_IMPORT_ALL) {
				const importConfig: TwitterImportConfig = {
					onProgress: sendMessageToCurrentTab,
					onComplete: sendImportDoneMessage,
					onError: async (error: Error) => {
						await sendMessageToCurrentTab(`Error: ${error.message}`)
					},
				}

				twitterImporter = new TwitterImporter(importConfig)
				twitterImporter.startImport().catch(console.error)
				sendResponse({ success: true })
				return true
			}

			// Handle regular memory save request
			if (message.action === MESSAGE_TYPES.SAVE_MEMORY) {
				;(async () => {
					try {
						const result = await saveMemoryToSupermemory(
							message.data as MemoryData,
							message.actionSource || "unknown",
						)
						sendResponse(result)
					} catch (error) {
						sendResponse({
							success: false,
							error: error instanceof Error ? error.message : "Unknown error",
						})
					}
				})()
				return true
			}

			if (message.action === MESSAGE_TYPES.GET_RELATED_MEMORIES) {
				;(async () => {
					try {
						const result = await getRelatedMemories(
							message.data as string,
							message.actionSource || "unknown",
						)
						sendResponse(result)
					} catch (error) {
						sendResponse({
							success: false,
							error: error instanceof Error ? error.message : "Unknown error",
						})
					}
				})()
				return true
			}

			if (message.action === MESSAGE_TYPES.CAPTURE_PROMPT) {
				;(async () => {
					try {
						const messageData = message.data as {
							prompt: string
							platform: string
							source: string
						}
						console.log("=== PROMPT CAPTURED ===")
						console.log(messageData)
						console.log("========================")

						const memoryData: MemoryData = {
							content: messageData.prompt,
						}

						const result = await saveMemoryToSupermemory(
							memoryData,
							`prompt_capture_${messageData.platform}`,
						)
						sendResponse(result)
					} catch (error) {
						sendResponse({
							success: false,
							error: error instanceof Error ? error.message : "Unknown error",
						})
					}
				})()
				return true
			}
		},
	)
})