superbased 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (343) hide show
  1. package/LICENSE +31 -0
  2. package/README.md +84 -0
  3. package/SUPERBASED_SKILL.md +358 -0
  4. package/dist/electron/ai/ai-client.d.ts +45 -0
  5. package/dist/electron/ai/ai-client.d.ts.map +1 -0
  6. package/dist/electron/ai/ai-client.js +205 -0
  7. package/dist/electron/ai/ai-client.js.map +1 -0
  8. package/dist/electron/ai/context-builder.d.ts +8 -0
  9. package/dist/electron/ai/context-builder.d.ts.map +1 -0
  10. package/dist/electron/ai/context-builder.js +28 -0
  11. package/dist/electron/ai/context-builder.js.map +1 -0
  12. package/dist/electron/ai/instruction-parser.d.ts +11 -0
  13. package/dist/electron/ai/instruction-parser.d.ts.map +1 -0
  14. package/dist/electron/ai/instruction-parser.js +47 -0
  15. package/dist/electron/ai/instruction-parser.js.map +1 -0
  16. package/dist/electron/ai/orchestrator.d.ts +17 -0
  17. package/dist/electron/ai/orchestrator.d.ts.map +1 -0
  18. package/dist/electron/ai/orchestrator.js +53 -0
  19. package/dist/electron/ai/orchestrator.js.map +1 -0
  20. package/dist/electron/ai/providers/anthropic.d.ts +6 -0
  21. package/dist/electron/ai/providers/anthropic.d.ts.map +1 -0
  22. package/dist/electron/ai/providers/anthropic.js +67 -0
  23. package/dist/electron/ai/providers/anthropic.js.map +1 -0
  24. package/dist/electron/ai/providers/azure-openai.d.ts +12 -0
  25. package/dist/electron/ai/providers/azure-openai.d.ts.map +1 -0
  26. package/dist/electron/ai/providers/azure-openai.js +87 -0
  27. package/dist/electron/ai/providers/azure-openai.js.map +1 -0
  28. package/dist/electron/ai/providers/gemini.d.ts +6 -0
  29. package/dist/electron/ai/providers/gemini.d.ts.map +1 -0
  30. package/dist/electron/ai/providers/gemini.js +49 -0
  31. package/dist/electron/ai/providers/gemini.js.map +1 -0
  32. package/dist/electron/ai/providers/openai.d.ts +6 -0
  33. package/dist/electron/ai/providers/openai.d.ts.map +1 -0
  34. package/dist/electron/ai/providers/openai.js +68 -0
  35. package/dist/electron/ai/providers/openai.js.map +1 -0
  36. package/dist/electron/core/auth-store.d.ts +15 -0
  37. package/dist/electron/core/auth-store.d.ts.map +1 -0
  38. package/dist/electron/core/auth-store.js +86 -0
  39. package/dist/electron/core/auth-store.js.map +1 -0
  40. package/dist/electron/core/config.d.ts +6 -0
  41. package/dist/electron/core/config.d.ts.map +1 -0
  42. package/dist/electron/core/config.js +81 -0
  43. package/dist/electron/core/config.js.map +1 -0
  44. package/dist/electron/core/file-logger.d.ts +17 -0
  45. package/dist/electron/core/file-logger.d.ts.map +1 -0
  46. package/dist/electron/core/file-logger.js +74 -0
  47. package/dist/electron/core/file-logger.js.map +1 -0
  48. package/dist/electron/core/json-store.d.ts +4 -0
  49. package/dist/electron/core/json-store.d.ts.map +1 -0
  50. package/dist/electron/core/json-store.js +118 -0
  51. package/dist/electron/core/json-store.js.map +1 -0
  52. package/dist/electron/core/paths.d.ts +17 -0
  53. package/dist/electron/core/paths.d.ts.map +1 -0
  54. package/dist/electron/core/paths.js +117 -0
  55. package/dist/electron/core/paths.js.map +1 -0
  56. package/dist/electron/core/platform.d.ts +21 -0
  57. package/dist/electron/core/platform.d.ts.map +1 -0
  58. package/dist/electron/core/platform.js +18 -0
  59. package/dist/electron/core/platform.js.map +1 -0
  60. package/dist/electron/core/process-coord.d.ts +19 -0
  61. package/dist/electron/core/process-coord.d.ts.map +1 -0
  62. package/dist/electron/core/process-coord.js +124 -0
  63. package/dist/electron/core/process-coord.js.map +1 -0
  64. package/dist/electron/db/database.d.ts +154 -0
  65. package/dist/electron/db/database.d.ts.map +1 -0
  66. package/dist/electron/db/database.js +637 -0
  67. package/dist/electron/db/database.js.map +1 -0
  68. package/dist/electron/db/models.d.ts +26 -0
  69. package/dist/electron/db/models.d.ts.map +1 -0
  70. package/dist/electron/db/models.js +4 -0
  71. package/dist/electron/db/models.js.map +1 -0
  72. package/dist/electron/logger.d.ts +9 -0
  73. package/dist/electron/logger.d.ts.map +1 -0
  74. package/dist/electron/logger.js +18 -0
  75. package/dist/electron/logger.js.map +1 -0
  76. package/dist/electron/main.js +3286 -0
  77. package/dist/electron/modules/active-window.d.ts +6 -0
  78. package/dist/electron/modules/active-window.d.ts.map +1 -0
  79. package/dist/electron/modules/active-window.js +68 -0
  80. package/dist/electron/modules/active-window.js.map +1 -0
  81. package/dist/electron/modules/api-server.d.ts +8 -0
  82. package/dist/electron/modules/api-server.d.ts.map +1 -0
  83. package/dist/electron/modules/api-server.js +1324 -0
  84. package/dist/electron/modules/api-server.js.map +1 -0
  85. package/dist/electron/modules/auth.d.ts +28 -0
  86. package/dist/electron/modules/auth.d.ts.map +1 -0
  87. package/dist/electron/modules/auth.js +150 -0
  88. package/dist/electron/modules/auth.js.map +1 -0
  89. package/dist/electron/modules/azure-speech-realtime.d.ts +38 -0
  90. package/dist/electron/modules/azure-speech-realtime.d.ts.map +1 -0
  91. package/dist/electron/modules/azure-speech-realtime.js +354 -0
  92. package/dist/electron/modules/azure-speech-realtime.js.map +1 -0
  93. package/dist/electron/modules/capture-modes.d.ts +19 -0
  94. package/dist/electron/modules/capture-modes.d.ts.map +1 -0
  95. package/dist/electron/modules/capture-modes.js +100 -0
  96. package/dist/electron/modules/capture-modes.js.map +1 -0
  97. package/dist/electron/modules/capture.d.ts +16 -0
  98. package/dist/electron/modules/capture.d.ts.map +1 -0
  99. package/dist/electron/modules/capture.js +139 -0
  100. package/dist/electron/modules/capture.js.map +1 -0
  101. package/dist/electron/modules/clipboard.d.ts +6 -0
  102. package/dist/electron/modules/clipboard.d.ts.map +1 -0
  103. package/dist/electron/modules/clipboard.js +26 -0
  104. package/dist/electron/modules/clipboard.js.map +1 -0
  105. package/dist/electron/modules/color-picker.d.ts +4 -0
  106. package/dist/electron/modules/color-picker.d.ts.map +1 -0
  107. package/dist/electron/modules/color-picker.js +233 -0
  108. package/dist/electron/modules/color-picker.js.map +1 -0
  109. package/dist/electron/modules/dictation.d.ts +25 -0
  110. package/dist/electron/modules/dictation.d.ts.map +1 -0
  111. package/dist/electron/modules/dictation.js +1058 -0
  112. package/dist/electron/modules/dictation.js.map +1 -0
  113. package/dist/electron/modules/error-reporter.d.ts +7 -0
  114. package/dist/electron/modules/error-reporter.d.ts.map +1 -0
  115. package/dist/electron/modules/error-reporter.js +65 -0
  116. package/dist/electron/modules/error-reporter.js.map +1 -0
  117. package/dist/electron/modules/hotkeys.d.ts +4 -0
  118. package/dist/electron/modules/hotkeys.d.ts.map +1 -0
  119. package/dist/electron/modules/hotkeys.js +40 -0
  120. package/dist/electron/modules/hotkeys.js.map +1 -0
  121. package/dist/electron/modules/keystroke.d.ts +7 -0
  122. package/dist/electron/modules/keystroke.d.ts.map +1 -0
  123. package/dist/electron/modules/keystroke.js +53 -0
  124. package/dist/electron/modules/keystroke.js.map +1 -0
  125. package/dist/electron/modules/license.d.ts +25 -0
  126. package/dist/electron/modules/license.d.ts.map +1 -0
  127. package/dist/electron/modules/license.js +175 -0
  128. package/dist/electron/modules/license.js.map +1 -0
  129. package/dist/electron/modules/mcp-config.d.ts +16 -0
  130. package/dist/electron/modules/mcp-config.d.ts.map +1 -0
  131. package/dist/electron/modules/mcp-config.js +146 -0
  132. package/dist/electron/modules/mcp-config.js.map +1 -0
  133. package/dist/electron/modules/ocr.d.ts +3 -0
  134. package/dist/electron/modules/ocr.d.ts.map +1 -0
  135. package/dist/electron/modules/ocr.js +176 -0
  136. package/dist/electron/modules/ocr.js.map +1 -0
  137. package/dist/electron/modules/pin-window.d.ts +3 -0
  138. package/dist/electron/modules/pin-window.d.ts.map +1 -0
  139. package/dist/electron/modules/pin-window.js +63 -0
  140. package/dist/electron/modules/pin-window.js.map +1 -0
  141. package/dist/electron/modules/recording/ai-analysis.d.ts +8 -0
  142. package/dist/electron/modules/recording/ai-analysis.d.ts.map +1 -0
  143. package/dist/electron/modules/recording/ai-analysis.js +88 -0
  144. package/dist/electron/modules/recording/ai-analysis.js.map +1 -0
  145. package/dist/electron/modules/recording/capture-queue.d.ts +48 -0
  146. package/dist/electron/modules/recording/capture-queue.d.ts.map +1 -0
  147. package/dist/electron/modules/recording/capture-queue.js +376 -0
  148. package/dist/electron/modules/recording/capture-queue.js.map +1 -0
  149. package/dist/electron/modules/recording/cli.d.ts +13 -0
  150. package/dist/electron/modules/recording/cli.d.ts.map +1 -0
  151. package/dist/electron/modules/recording/cli.js +135 -0
  152. package/dist/electron/modules/recording/cli.js.map +1 -0
  153. package/dist/electron/modules/recording/http-api.d.ts +3 -0
  154. package/dist/electron/modules/recording/http-api.d.ts.map +1 -0
  155. package/dist/electron/modules/recording/http-api.js +236 -0
  156. package/dist/electron/modules/recording/http-api.js.map +1 -0
  157. package/dist/electron/modules/recording/index.d.ts +15 -0
  158. package/dist/electron/modules/recording/index.d.ts.map +1 -0
  159. package/dist/electron/modules/recording/index.js +148 -0
  160. package/dist/electron/modules/recording/index.js.map +1 -0
  161. package/dist/electron/modules/recording/input-hook-provider.d.ts +15 -0
  162. package/dist/electron/modules/recording/input-hook-provider.d.ts.map +1 -0
  163. package/dist/electron/modules/recording/input-hook-provider.js +5 -0
  164. package/dist/electron/modules/recording/input-hook-provider.js.map +1 -0
  165. package/dist/electron/modules/recording/mcp-tool.d.ts +13 -0
  166. package/dist/electron/modules/recording/mcp-tool.d.ts.map +1 -0
  167. package/dist/electron/modules/recording/mcp-tool.js +81 -0
  168. package/dist/electron/modules/recording/mcp-tool.js.map +1 -0
  169. package/dist/electron/modules/recording/providers/periodic-provider.d.ts +15 -0
  170. package/dist/electron/modules/recording/providers/periodic-provider.d.ts.map +1 -0
  171. package/dist/electron/modules/recording/providers/periodic-provider.js +55 -0
  172. package/dist/electron/modules/recording/providers/periodic-provider.js.map +1 -0
  173. package/dist/electron/modules/recording/providers/provider-factory.d.ts +9 -0
  174. package/dist/electron/modules/recording/providers/provider-factory.d.ts.map +1 -0
  175. package/dist/electron/modules/recording/providers/provider-factory.js +70 -0
  176. package/dist/electron/modules/recording/providers/provider-factory.js.map +1 -0
  177. package/dist/electron/modules/recording/providers/uiohook-provider.d.ts +19 -0
  178. package/dist/electron/modules/recording/providers/uiohook-provider.d.ts.map +1 -0
  179. package/dist/electron/modules/recording/providers/uiohook-provider.js +263 -0
  180. package/dist/electron/modules/recording/providers/uiohook-provider.js.map +1 -0
  181. package/dist/electron/modules/recording/recording-session.d.ts +25 -0
  182. package/dist/electron/modules/recording/recording-session.d.ts.map +1 -0
  183. package/dist/electron/modules/recording/recording-session.js +317 -0
  184. package/dist/electron/modules/recording/recording-session.js.map +1 -0
  185. package/dist/electron/modules/recording/session-alignment.d.ts +32 -0
  186. package/dist/electron/modules/recording/session-alignment.d.ts.map +1 -0
  187. package/dist/electron/modules/recording/session-alignment.js +103 -0
  188. package/dist/electron/modules/recording/session-alignment.js.map +1 -0
  189. package/dist/electron/modules/recording/session-export.d.ts +2 -0
  190. package/dist/electron/modules/recording/session-export.d.ts.map +1 -0
  191. package/dist/electron/modules/recording/session-export.js +287 -0
  192. package/dist/electron/modules/recording/session-export.js.map +1 -0
  193. package/dist/electron/modules/recording/trigger-engine.d.ts +62 -0
  194. package/dist/electron/modules/recording/trigger-engine.d.ts.map +1 -0
  195. package/dist/electron/modules/recording/trigger-engine.js +546 -0
  196. package/dist/electron/modules/recording/trigger-engine.js.map +1 -0
  197. package/dist/electron/modules/recording/visual-diff.d.ts +17 -0
  198. package/dist/electron/modules/recording/visual-diff.d.ts.map +1 -0
  199. package/dist/electron/modules/recording/visual-diff.js +109 -0
  200. package/dist/electron/modules/recording/visual-diff.js.map +1 -0
  201. package/dist/electron/modules/redact.d.ts +34 -0
  202. package/dist/electron/modules/redact.d.ts.map +1 -0
  203. package/dist/electron/modules/redact.js +583 -0
  204. package/dist/electron/modules/redact.js.map +1 -0
  205. package/dist/electron/modules/scroll-capture.d.ts +19 -0
  206. package/dist/electron/modules/scroll-capture.d.ts.map +1 -0
  207. package/dist/electron/modules/scroll-capture.js +185 -0
  208. package/dist/electron/modules/scroll-capture.js.map +1 -0
  209. package/dist/electron/modules/store.d.ts +59 -0
  210. package/dist/electron/modules/store.d.ts.map +1 -0
  211. package/dist/electron/modules/store.js +100 -0
  212. package/dist/electron/modules/store.js.map +1 -0
  213. package/dist/electron/modules/tce/content-analyzer.d.ts +20 -0
  214. package/dist/electron/modules/tce/content-analyzer.d.ts.map +1 -0
  215. package/dist/electron/modules/tce/content-analyzer.js +123 -0
  216. package/dist/electron/modules/tce/content-analyzer.js.map +1 -0
  217. package/dist/electron/modules/tce/index.d.ts +54 -0
  218. package/dist/electron/modules/tce/index.d.ts.map +1 -0
  219. package/dist/electron/modules/tce/index.js +174 -0
  220. package/dist/electron/modules/tce/index.js.map +1 -0
  221. package/dist/electron/modules/tce/layout-engine.d.ts +68 -0
  222. package/dist/electron/modules/tce/layout-engine.d.ts.map +1 -0
  223. package/dist/electron/modules/tce/layout-engine.js +313 -0
  224. package/dist/electron/modules/tce/layout-engine.js.map +1 -0
  225. package/dist/electron/modules/tce/renderer.d.ts +16 -0
  226. package/dist/electron/modules/tce/renderer.d.ts.map +1 -0
  227. package/dist/electron/modules/tce/renderer.js +196 -0
  228. package/dist/electron/modules/tce/renderer.js.map +1 -0
  229. package/dist/electron/modules/tce/themes.d.ts +14 -0
  230. package/dist/electron/modules/tce/themes.d.ts.map +1 -0
  231. package/dist/electron/modules/tce/themes.js +68 -0
  232. package/dist/electron/modules/tce/themes.js.map +1 -0
  233. package/dist/electron/modules/tce/token-estimator.d.ts +30 -0
  234. package/dist/electron/modules/tce/token-estimator.d.ts.map +1 -0
  235. package/dist/electron/modules/tce/token-estimator.js +59 -0
  236. package/dist/electron/modules/tce/token-estimator.js.map +1 -0
  237. package/dist/electron/modules/telemetry.d.ts +44 -0
  238. package/dist/electron/modules/telemetry.d.ts.map +1 -0
  239. package/dist/electron/modules/telemetry.js +316 -0
  240. package/dist/electron/modules/telemetry.js.map +1 -0
  241. package/dist/electron/modules/tray.d.ts +22 -0
  242. package/dist/electron/modules/tray.d.ts.map +1 -0
  243. package/dist/electron/modules/tray.js +221 -0
  244. package/dist/electron/modules/tray.js.map +1 -0
  245. package/dist/electron/modules/updater.d.ts +14 -0
  246. package/dist/electron/modules/updater.d.ts.map +1 -0
  247. package/dist/electron/modules/updater.js +102 -0
  248. package/dist/electron/modules/updater.js.map +1 -0
  249. package/dist/electron/modules/usage-link.d.ts +7 -0
  250. package/dist/electron/modules/usage-link.d.ts.map +1 -0
  251. package/dist/electron/modules/usage-link.js +63 -0
  252. package/dist/electron/modules/usage-link.js.map +1 -0
  253. package/dist/electron/modules/version-check.d.ts +3 -0
  254. package/dist/electron/modules/version-check.d.ts.map +1 -0
  255. package/dist/electron/modules/version-check.js +76 -0
  256. package/dist/electron/modules/version-check.js.map +1 -0
  257. package/dist/electron/modules/window-picker.d.ts +6 -0
  258. package/dist/electron/modules/window-picker.d.ts.map +1 -0
  259. package/dist/electron/modules/window-picker.js +192 -0
  260. package/dist/electron/modules/window-picker.js.map +1 -0
  261. package/dist/headless/electron/ai/ai-client.js +204 -0
  262. package/dist/headless/electron/ai/context-builder.js +27 -0
  263. package/dist/headless/electron/ai/instruction-parser.js +46 -0
  264. package/dist/headless/electron/core/auth-store.js +85 -0
  265. package/dist/headless/electron/core/config.js +80 -0
  266. package/dist/headless/electron/core/file-logger.js +73 -0
  267. package/dist/headless/electron/core/json-store.js +117 -0
  268. package/dist/headless/electron/core/paths.js +116 -0
  269. package/dist/headless/electron/core/platform.js +17 -0
  270. package/dist/headless/electron/core/process-coord.js +123 -0
  271. package/dist/headless/electron/db/database.js +636 -0
  272. package/dist/headless/electron/db/models.js +3 -0
  273. package/dist/headless/electron/logger.js +17 -0
  274. package/dist/headless/electron/modules/active-window.js +67 -0
  275. package/dist/headless/electron/modules/api-server.js +1323 -0
  276. package/dist/headless/electron/modules/auth.js +149 -0
  277. package/dist/headless/electron/modules/azure-speech-realtime.js +353 -0
  278. package/dist/headless/electron/modules/capture.js +138 -0
  279. package/dist/headless/electron/modules/clipboard.js +25 -0
  280. package/dist/headless/electron/modules/dictation.js +1057 -0
  281. package/dist/headless/electron/modules/keystroke.js +52 -0
  282. package/dist/headless/electron/modules/license.js +174 -0
  283. package/dist/headless/electron/modules/mcp-config.js +145 -0
  284. package/dist/headless/electron/modules/ocr.js +175 -0
  285. package/dist/headless/electron/modules/recording/ai-analysis.js +87 -0
  286. package/dist/headless/electron/modules/recording/capture-queue.js +375 -0
  287. package/dist/headless/electron/modules/recording/cli.js +134 -0
  288. package/dist/headless/electron/modules/recording/http-api.js +235 -0
  289. package/dist/headless/electron/modules/recording/index.js +147 -0
  290. package/dist/headless/electron/modules/recording/input-hook-provider.js +4 -0
  291. package/dist/headless/electron/modules/recording/mcp-tool.js +80 -0
  292. package/dist/headless/electron/modules/recording/providers/periodic-provider.js +54 -0
  293. package/dist/headless/electron/modules/recording/providers/provider-factory.js +69 -0
  294. package/dist/headless/electron/modules/recording/providers/uiohook-provider.js +262 -0
  295. package/dist/headless/electron/modules/recording/recording-session.js +316 -0
  296. package/dist/headless/electron/modules/recording/session-alignment.js +102 -0
  297. package/dist/headless/electron/modules/recording/session-export.js +286 -0
  298. package/dist/headless/electron/modules/recording/trigger-engine.js +545 -0
  299. package/dist/headless/electron/modules/recording/visual-diff.js +108 -0
  300. package/dist/headless/electron/modules/redact.js +582 -0
  301. package/dist/headless/electron/modules/store.js +99 -0
  302. package/dist/headless/electron/modules/tce/content-analyzer.js +122 -0
  303. package/dist/headless/electron/modules/tce/index.js +173 -0
  304. package/dist/headless/electron/modules/tce/layout-engine.js +312 -0
  305. package/dist/headless/electron/modules/tce/renderer.js +195 -0
  306. package/dist/headless/electron/modules/tce/themes.js +67 -0
  307. package/dist/headless/electron/modules/tce/token-estimator.js +58 -0
  308. package/dist/headless/electron/modules/telemetry.js +315 -0
  309. package/dist/headless/headless/capture-hotkey.js +155 -0
  310. package/dist/headless/headless/cli-auth.js +158 -0
  311. package/dist/headless/headless/cli.js +220 -0
  312. package/dist/headless/headless/dictation-hotkey.js +360 -0
  313. package/dist/headless/headless/mic-capture.js +312 -0
  314. package/dist/headless/headless/platform-headless.js +121 -0
  315. package/dist/headless/headless/server.js +159 -0
  316. package/dist/headless/mic-capture.d.ts +29 -0
  317. package/dist/headless/mic-capture.d.ts.map +1 -0
  318. package/dist/headless/mic-capture.js +313 -0
  319. package/dist/headless/mic-capture.js.map +1 -0
  320. package/dist/headless/shared/constants.js +63 -0
  321. package/dist/headless/shared/design-tokens.js +189 -0
  322. package/dist/headless/shared/recording-types.js +93 -0
  323. package/dist/headless/shared/types.js +3 -0
  324. package/dist/shared/constants.d.ts +98 -0
  325. package/dist/shared/constants.d.ts.map +1 -0
  326. package/dist/shared/constants.js +64 -0
  327. package/dist/shared/constants.js.map +1 -0
  328. package/dist/shared/design-tokens.d.ts +112 -0
  329. package/dist/shared/design-tokens.d.ts.map +1 -0
  330. package/dist/shared/design-tokens.js +190 -0
  331. package/dist/shared/design-tokens.js.map +1 -0
  332. package/dist/shared/recording-types.d.ts +174 -0
  333. package/dist/shared/recording-types.d.ts.map +1 -0
  334. package/dist/shared/recording-types.js +94 -0
  335. package/dist/shared/recording-types.js.map +1 -0
  336. package/dist/shared/types.d.ts +135 -0
  337. package/dist/shared/types.d.ts.map +1 -0
  338. package/dist/shared/types.js +4 -0
  339. package/dist/shared/types.js.map +1 -0
  340. package/mcp-server/dist/api-client.js +261 -0
  341. package/mcp-server/dist/index.js +824 -0
  342. package/mcp-server/package.json +16 -0
  343. package/package.json +125 -0
@@ -0,0 +1,3286 @@
1
+ "use strict";
2
+ // Main Electron process: app entry, window management, tray, IPC handlers
3
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
+ if (k2 === undefined) k2 = k;
5
+ var desc = Object.getOwnPropertyDescriptor(m, k);
6
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
+ desc = { enumerable: true, get: function() { return m[k]; } };
8
+ }
9
+ Object.defineProperty(o, k2, desc);
10
+ }) : (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ o[k2] = m[k];
13
+ }));
14
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
16
+ }) : function(o, v) {
17
+ o["default"] = v;
18
+ });
19
+ var __importStar = (this && this.__importStar) || (function () {
20
+ var ownKeys = function(o) {
21
+ ownKeys = Object.getOwnPropertyNames || function (o) {
22
+ var ar = [];
23
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
24
+ return ar;
25
+ };
26
+ return ownKeys(o);
27
+ };
28
+ return function (mod) {
29
+ if (mod && mod.__esModule) return mod;
30
+ var result = {};
31
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
32
+ __setModuleDefault(result, mod);
33
+ return result;
34
+ };
35
+ })();
36
+ var __importDefault = (this && this.__importDefault) || function (mod) {
37
+ return (mod && mod.__esModule) ? mod : { "default": mod };
38
+ };
39
+ Object.defineProperty(exports, "__esModule", { value: true });
40
+ const electron_1 = require("electron");
41
+ const platform_1 = require("./core/platform");
42
+ const platform_electron_1 = require("./platform-electron");
43
+ const config_1 = require("./core/config");
44
+ const paths_1 = require("./core/paths");
45
+ // Initialize platform adapter BEFORE any module that uses getPlatform()
46
+ (0, platform_1.setPlatform)(platform_electron_1.electronPlatform);
47
+ (0, config_1.setClientType)('desktop');
48
+ (0, paths_1.overrideDataDir)(electron_1.app.getPath('userData'));
49
+ const path = __importStar(require("path"));
50
+ const fs = __importStar(require("fs"));
51
+ const tray_1 = require("./modules/tray");
52
+ const hotkeys_1 = require("./modules/hotkeys");
53
+ const auth_1 = require("./modules/auth");
54
+ const capture_1 = require("./modules/capture");
55
+ const database_1 = require("./db/database");
56
+ const ai_client_1 = require("./ai/ai-client");
57
+ const instruction_parser_1 = require("./ai/instruction-parser");
58
+ const context_builder_1 = require("./ai/context-builder");
59
+ const store_1 = require("./modules/store");
60
+ const active_window_1 = require("./modules/active-window");
61
+ const keystroke_1 = require("./modules/keystroke");
62
+ const nut_js_1 = require("@nut-tree-fork/nut-js");
63
+ const clipboard_1 = require("./modules/clipboard");
64
+ const constants_1 = require("../shared/constants");
65
+ const capture_modes_1 = require("./modules/capture-modes");
66
+ const pin_window_1 = require("./modules/pin-window");
67
+ const color_picker_1 = require("./modules/color-picker");
68
+ const window_picker_1 = require("./modules/window-picker");
69
+ const updater_1 = require("./modules/updater");
70
+ const tray_2 = require("./modules/tray");
71
+ const version_check_1 = require("./modules/version-check");
72
+ const ocr_1 = require("./modules/ocr");
73
+ const redact_1 = require("./modules/redact");
74
+ const logger_1 = __importDefault(require("./logger"));
75
+ // --- Custom protocol: serves local files without holding Windows file locks ---
76
+ // Must be registered BEFORE app.whenReady() per Electron docs.
77
+ electron_1.protocol.registerSchemesAsPrivileged([
78
+ { scheme: 'sbfile', privileges: { standard: false, secure: true, supportFetchAPI: true, stream: true } },
79
+ ]);
80
+ // --- Crash reporting: log uncaught errors to disk ---
81
+ const crashLogDir = path.join(electron_1.app.getPath('userData'), 'crash-logs');
82
+ function ensureCrashLogDir() {
83
+ if (!fs.existsSync(crashLogDir)) {
84
+ fs.mkdirSync(crashLogDir, { recursive: true });
85
+ }
86
+ }
87
+ function writeCrashLog(type, error) {
88
+ try {
89
+ ensureCrashLogDir();
90
+ const timestamp = new Date().toISOString();
91
+ const filename = `crash-${timestamp.replace(/[:.]/g, '-')}.log`;
92
+ const message = error instanceof Error ? `${error.message}\n${error.stack || ''}` : String(error);
93
+ const content = `[${timestamp}] ${type}\n${message}\n`;
94
+ fs.writeFileSync(path.join(crashLogDir, filename), content);
95
+ }
96
+ catch {
97
+ // Avoid recursive failures in the crash handler
98
+ }
99
+ }
100
+ process.on('uncaughtException', (error) => {
101
+ logger_1.default.error('Uncaught exception:', error);
102
+ writeCrashLog('uncaughtException', error);
103
+ });
104
+ process.on('unhandledRejection', (reason) => {
105
+ logger_1.default.error('Unhandled rejection:', reason);
106
+ writeCrashLog('unhandledRejection', reason);
107
+ });
108
+ let selectionWindow = null;
109
+ let overlayWindow = null;
110
+ let galleryWindow = null;
111
+ let onboardingWindow = null;
112
+ let recordingBarWindow = null;
113
+ let timelineWindow = null;
114
+ let startRecordingWindow = null;
115
+ let mainPanelWindow = null;
116
+ let dictationIndicatorWindow = null;
117
+ // Track the last active window before we take over focus
118
+ let lastActiveWindow = { appName: null, windowTitle: null };
119
+ // Pending notes for the global "paste notes" shortcut
120
+ let pendingNotesText = null;
121
+ let notesPasteShortcutRegistered = false;
122
+ // Overlay pin & PIP state
123
+ let overlayPinned = false;
124
+ let overlayOriginalBounds = null;
125
+ // Flag: if true, next selection adds to existing overlay instead of creating new one
126
+ let addingToExistingOverlay = false;
127
+ // Flag: if true, next selection triggers scroll-capture mode
128
+ let scrollCaptureMode = false;
129
+ // Thumbnail cache — invalidated when screenshots are edited
130
+ const thumbnailCache = new Map();
131
+ const isMac = process.platform === 'darwin';
132
+ /** Load the app icon for use in BrowserWindow constructors (Windows taskbar) */
133
+ let _appIcon;
134
+ function getAppIcon() {
135
+ if (isMac)
136
+ return undefined; // macOS uses the app bundle icon automatically
137
+ if (_appIcon)
138
+ return _appIcon;
139
+ const assetsDir = electron_1.app.isPackaged
140
+ ? path.join(process.resourcesPath, 'assets')
141
+ : path.join(__dirname, '../../assets');
142
+ for (const name of ['icon.ico', 'icon-256.png', 'icon.png']) {
143
+ try {
144
+ const img = electron_1.nativeImage.createFromPath(path.join(assetsDir, name));
145
+ if (!img.isEmpty()) {
146
+ _appIcon = img;
147
+ return _appIcon;
148
+ }
149
+ }
150
+ catch {
151
+ // Try next
152
+ }
153
+ }
154
+ return undefined;
155
+ }
156
+ /** Returns platform-aware frame options for content windows (settings, gallery, etc.) */
157
+ function framelessWindowOptions() {
158
+ if (isMac) {
159
+ return {
160
+ titleBarStyle: 'hidden',
161
+ trafficLightPosition: { x: 12, y: 12 },
162
+ fullscreenable: false,
163
+ };
164
+ }
165
+ return { frame: false, icon: getAppIcon() };
166
+ }
167
+ function makeWindowFocusAware(win) {
168
+ // Set app icon on Windows (constructor icon can be ignored for transparent windows)
169
+ if (!isMac) {
170
+ const icon = getAppIcon();
171
+ if (icon)
172
+ win.setIcon(icon);
173
+ }
174
+ // Show the window above others initially, then drop to normal z-order
175
+ win.once('ready-to-show', () => {
176
+ win.show();
177
+ win.focus();
178
+ });
179
+ }
180
+ /**
181
+ * Dismiss the selection window before capturing.
182
+ * On macOS, exits simpleFullscreen first so the OS releases the screen properly.
183
+ */
184
+ async function dismissSelectionWindow() {
185
+ if (!selectionWindow || selectionWindow.isDestroyed())
186
+ return;
187
+ if (isMac && selectionWindow.isSimpleFullScreen()) {
188
+ selectionWindow.setSimpleFullScreen(false);
189
+ await new Promise((resolve) => setTimeout(resolve, 200));
190
+ }
191
+ if (!selectionWindow.isDestroyed()) {
192
+ selectionWindow.hide();
193
+ }
194
+ // Give the OS time to fully repaint the desktop before capturing
195
+ await new Promise((resolve) => setTimeout(resolve, isMac ? 200 : 100));
196
+ }
197
+ async function closeSelectionWindow() {
198
+ if (selectionWindow && !selectionWindow.isDestroyed()) {
199
+ selectionWindow.close();
200
+ }
201
+ }
202
+ /**
203
+ * Get a screen capture buffer for use after selection.
204
+ * On macOS, uses the pre-captured buffer (taken before the selection window appeared)
205
+ * because simpleFullscreen makes re-capturing unreliable.
206
+ * On Windows/Linux, captures fresh.
207
+ */
208
+ async function getCaptureBuffer() {
209
+ if (isMac) {
210
+ const pre = (0, capture_1.getPreCapture)();
211
+ if (pre && pre.length > 1000) {
212
+ logger_1.default.info(`[Capture] Using pre-capture buffer (${pre.length} bytes) on macOS`);
213
+ return pre;
214
+ }
215
+ logger_1.default.warn('[Capture] No pre-capture available on macOS, attempting live capture');
216
+ }
217
+ return (0, capture_1.captureScreen)();
218
+ }
219
+ function attachCrashHandlers(win, windowName) {
220
+ win.webContents.on('render-process-gone', (_event, details) => {
221
+ logger_1.default.error(`[Crash] Render process gone in ${windowName}: reason=${details.reason}`);
222
+ if (details.reason !== 'clean-exit') {
223
+ win.reload();
224
+ }
225
+ });
226
+ }
227
+ function isPathSafe(filePath) {
228
+ const resolved = path.resolve(filePath);
229
+ const capturesDir = getCapturesDir();
230
+ const userDataDir = electron_1.app.getPath('userData');
231
+ const tempDir = electron_1.app.getPath('temp');
232
+ return resolved.startsWith(capturesDir) || resolved.startsWith(userDataDir) || resolved.startsWith(tempDir);
233
+ }
234
+ function getCapturesDir() {
235
+ const custom = (0, store_1.getSetting)('screenshotFolder');
236
+ if (custom) {
237
+ logger_1.default.info('[Captures] Custom folder:', custom, 'exists:', fs.existsSync(custom));
238
+ if (fs.existsSync(custom))
239
+ return custom;
240
+ }
241
+ const defaultDir = path.join(electron_1.app.getPath('userData'), constants_1.CAPTURES_DIR);
242
+ logger_1.default.info('[Captures] Using default:', defaultDir);
243
+ return defaultDir;
244
+ }
245
+ function ensureCapturesDir() {
246
+ const dir = getCapturesDir();
247
+ if (!fs.existsSync(dir)) {
248
+ fs.mkdirSync(dir, { recursive: true });
249
+ }
250
+ }
251
+ /** Whether we've already shown the Screen Recording permission dialog this session */
252
+ let screenPermissionPromptShown = false;
253
+ /**
254
+ * One-time check at startup for macOS Screen Recording permission.
255
+ * Called once from app.whenReady() — does NOT block capture flow.
256
+ * getMediaAccessStatus('screen') can be unreliable (may report 'not-determined'
257
+ * even when granted), so we only show the prompt once per session.
258
+ */
259
+ function checkScreenRecordingPermissionOnce() {
260
+ if (!isMac || screenPermissionPromptShown)
261
+ return;
262
+ const status = electron_1.systemPreferences.getMediaAccessStatus('screen');
263
+ logger_1.default.info(`[Capture] Screen Recording permission status: ${status}`);
264
+ if (status === 'granted')
265
+ return;
266
+ // Only prompt once per session — the status API can be unreliable
267
+ screenPermissionPromptShown = true;
268
+ electron_1.dialog
269
+ .showMessageBox({
270
+ type: 'info',
271
+ title: 'Screen Recording Permission',
272
+ message: 'SuperBased needs Screen Recording permission to capture your screen.',
273
+ detail: 'If screenshots appear blank or show only your wallpaper, please open System Settings > Privacy & Security > Screen Recording and enable SuperBased.\n\n' +
274
+ 'You may need to restart the app after granting permission.',
275
+ buttons: ['Open System Settings', 'OK'],
276
+ defaultId: 1,
277
+ cancelId: 1,
278
+ })
279
+ .then((result) => {
280
+ if (result.response === 0) {
281
+ electron_1.shell.openExternal('x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture');
282
+ }
283
+ });
284
+ }
285
+ function createSelectionWindow() {
286
+ if (selectionWindow && !selectionWindow.isDestroyed()) {
287
+ selectionWindow.close();
288
+ }
289
+ createSelectionWindowInner();
290
+ }
291
+ async function createSelectionWindowInner() {
292
+ // Capture active window info BEFORE hiding any SuperBased windows.
293
+ // On macOS, hiding windows shifts focus and active-win would report "SuperBased".
294
+ try {
295
+ lastActiveWindow = await (0, active_window_1.getActiveWindowInfo)();
296
+ }
297
+ catch {
298
+ // Non-blocking — proceed with null values
299
+ }
300
+ // If overlay is already open, treat this as "add capture to existing overlay"
301
+ if (overlayWindow && !overlayWindow.isDestroyed()) {
302
+ addingToExistingOverlay = true;
303
+ overlayWindow.hide();
304
+ }
305
+ // Hide main panel window so it doesn't appear in the selection/capture
306
+ if (mainPanelWindow && !mainPanelWindow.isDestroyed()) {
307
+ mainPanelWindow.hide();
308
+ }
309
+ // Pre-capture the screen BEFORE the selection window appears.
310
+ // This buffer is used for: (1) magnifier in the selection UI, and
311
+ // (2) on macOS, as the actual capture buffer — because macOS simpleFullscreen
312
+ // makes it impossible to cleanly re-capture the desktop after selection.
313
+ (0, capture_1.clearPreCapture)();
314
+ let preCapture = null;
315
+ try {
316
+ // Eagerly attach .catch() to prevent "Unhandled rejection" warnings —
317
+ // the promise may reject before it's awaited in the did-finish-load handler
318
+ preCapture = (0, capture_1.captureScreen)().catch((err) => {
319
+ logger_1.default.warn('[Capture] Pre-capture failed:', err);
320
+ return null;
321
+ });
322
+ }
323
+ catch {
324
+ // Magnifier won't work but selection still functions
325
+ }
326
+ const primaryDisplay = electron_1.screen.getPrimaryDisplay();
327
+ const { width, height } = primaryDisplay.size;
328
+ selectionWindow = new electron_1.BrowserWindow({
329
+ x: 0,
330
+ y: 0,
331
+ width,
332
+ height,
333
+ frame: false,
334
+ transparent: true,
335
+ alwaysOnTop: true,
336
+ skipTaskbar: true,
337
+ resizable: false,
338
+ movable: false,
339
+ // Windows: native fullscreen covers everything.
340
+ // macOS: simpleFullscreen hides menu bar and dock while staying on current space.
341
+ fullscreen: !isMac,
342
+ simpleFullscreen: isMac,
343
+ webPreferences: {
344
+ preload: path.join(__dirname, 'preload.js'),
345
+ contextIsolation: true,
346
+ nodeIntegration: false,
347
+ navigateOnDragDrop: false,
348
+ },
349
+ });
350
+ if (isMac) {
351
+ selectionWindow.setSimpleFullScreen(true);
352
+ // Place above everything including menu bar and fullscreen apps.
353
+ // visibleOnAllWorkspaces + visibleOnFullScreen prevents Mission Control
354
+ // space switching when capturing from a native fullscreen app.
355
+ selectionWindow.setAlwaysOnTop(true, 'screen-saver');
356
+ selectionWindow.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true });
357
+ }
358
+ attachCrashHandlers(selectionWindow, 'selection');
359
+ selectionWindow.loadFile(path.join(__dirname, '../renderer/selection.html'));
360
+ selectionWindow.setIgnoreMouseEvents(false);
361
+ // Send the pre-captured screenshot for magnifier use after the window loads
362
+ // Also store it for use as the actual capture buffer on macOS
363
+ selectionWindow.webContents.once('did-finish-load', async () => {
364
+ try {
365
+ if (preCapture) {
366
+ const buf = await preCapture;
367
+ if (buf) {
368
+ (0, capture_1.storePreCapture)(buf);
369
+ logger_1.default.info(`[Capture] Pre-capture stored: ${buf.length} bytes`);
370
+ const dataUrl = `data:image/png;base64,${buf.toString('base64')}`;
371
+ if (selectionWindow && !selectionWindow.isDestroyed()) {
372
+ selectionWindow.webContents.send('selection:screen-image', dataUrl);
373
+ }
374
+ }
375
+ }
376
+ }
377
+ catch (err) {
378
+ logger_1.default.warn('[Capture] Pre-capture failed:', err);
379
+ }
380
+ });
381
+ selectionWindow.on('closed', () => {
382
+ selectionWindow = null;
383
+ });
384
+ }
385
+ function createOverlayWindow(initData, region) {
386
+ if (overlayWindow && !overlayWindow.isDestroyed()) {
387
+ overlayWindow.close();
388
+ }
389
+ const primaryDisplay = electron_1.screen.getPrimaryDisplay();
390
+ const { width: screenW, height: screenH } = primaryDisplay.size;
391
+ // Restore last saved overlay bounds, or use defaults
392
+ const savedBounds = (0, store_1.getSetting)('overlayBounds');
393
+ let overlayWidth = savedBounds?.width || 520;
394
+ let overlayHeight = savedBounds?.height || (initData.inlineEditMode ? 620 : 560);
395
+ let x, y;
396
+ if (savedBounds) {
397
+ x = savedBounds.x;
398
+ y = savedBounds.y;
399
+ }
400
+ else {
401
+ x = region.x + region.width + 16;
402
+ y = region.y;
403
+ }
404
+ if (x + overlayWidth > screenW)
405
+ x = region.x - overlayWidth - 16;
406
+ if (x < 0)
407
+ x = 16;
408
+ if (y + overlayHeight > screenH)
409
+ y = screenH - overlayHeight - 16;
410
+ if (y < 0)
411
+ y = 16;
412
+ // On macOS, use titleBarStyle: 'hidden' with native traffic lights visible
413
+ const overlayFrameOptions = isMac
414
+ ? { titleBarStyle: 'hidden', trafficLightPosition: { x: 12, y: 12 }, fullscreenable: false }
415
+ : { frame: false, icon: getAppIcon() };
416
+ overlayWindow = new electron_1.BrowserWindow({
417
+ x,
418
+ y,
419
+ width: overlayWidth,
420
+ height: overlayHeight,
421
+ minWidth: 320,
422
+ minHeight: 400,
423
+ ...overlayFrameOptions,
424
+ transparent: true,
425
+ alwaysOnTop: false,
426
+ skipTaskbar: false,
427
+ resizable: true,
428
+ minimizable: true,
429
+ maximizable: false,
430
+ webPreferences: {
431
+ preload: path.join(__dirname, 'preload.js'),
432
+ contextIsolation: true,
433
+ nodeIntegration: false,
434
+ navigateOnDragDrop: false,
435
+ },
436
+ });
437
+ const appIcon = getAppIcon();
438
+ if (appIcon && !isMac)
439
+ overlayWindow.setIcon(appIcon);
440
+ if (isMac) {
441
+ // Show on all workspaces so overlay appears on fullscreen app spaces
442
+ overlayWindow.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true });
443
+ }
444
+ makeWindowFocusAware(overlayWindow);
445
+ overlayWindow.loadFile(path.join(__dirname, '../renderer/overlay.html'));
446
+ overlayWindow.webContents.on('did-finish-load', () => {
447
+ logger_1.default.info(`[Overlay] did-finish-load, sending init: screenshotPath=${initData.screenshotPath}, regionScreenshots=${(initData.regionScreenshots || []).length}`);
448
+ overlayWindow?.webContents.send('overlay:init', initData);
449
+ });
450
+ attachCrashHandlers(overlayWindow, 'overlay');
451
+ // Save bounds on move/resize
452
+ const saveBounds = () => {
453
+ if (overlayWindow && !overlayWindow.isDestroyed()) {
454
+ const bounds = overlayWindow.getBounds();
455
+ (0, store_1.setSetting)('overlayBounds', bounds);
456
+ }
457
+ };
458
+ overlayWindow.on('moved', saveBounds);
459
+ overlayWindow.on('resized', saveBounds);
460
+ overlayWindow.on('closed', () => {
461
+ overlayWindow = null;
462
+ // Clear dictation callback when overlay closes
463
+ Promise.resolve().then(() => __importStar(require('./modules/dictation'))).then((mod) => mod.onDictationRecordingStart(null))
464
+ .catch(() => { });
465
+ });
466
+ // Set up dictation → overlay forwarding: when dictation starts recording
467
+ // while overlay is open, notify overlay to open the note editor
468
+ Promise.resolve().then(() => __importStar(require('./modules/dictation'))).then((mod) => {
469
+ mod.onDictationRecordingStart(() => {
470
+ if (overlayWindow && !overlayWindow.isDestroyed() && overlayWindow.isFocused()) {
471
+ overlayWindow.webContents.send('overlay:dictation-started');
472
+ }
473
+ });
474
+ })
475
+ .catch(() => { });
476
+ }
477
+ function openMainPanelSettings() {
478
+ createMainPanelWindow();
479
+ // Once the window is ready, tell it to navigate to settings
480
+ if (mainPanelWindow && !mainPanelWindow.isDestroyed()) {
481
+ if (mainPanelWindow.webContents.isLoading()) {
482
+ mainPanelWindow.webContents.once('did-finish-load', () => {
483
+ mainPanelWindow?.webContents.send('navigate', 'settings');
484
+ });
485
+ }
486
+ else {
487
+ mainPanelWindow.webContents.send('navigate', 'settings');
488
+ }
489
+ }
490
+ }
491
+ function createGalleryWindow() {
492
+ if (galleryWindow && !galleryWindow.isDestroyed()) {
493
+ galleryWindow.focus();
494
+ return;
495
+ }
496
+ galleryWindow = new electron_1.BrowserWindow({
497
+ width: 900,
498
+ height: 700,
499
+ ...framelessWindowOptions(),
500
+ webPreferences: {
501
+ preload: path.join(__dirname, 'preload.js'),
502
+ contextIsolation: true,
503
+ nodeIntegration: false,
504
+ navigateOnDragDrop: false,
505
+ },
506
+ });
507
+ makeWindowFocusAware(galleryWindow);
508
+ attachCrashHandlers(galleryWindow, 'gallery');
509
+ galleryWindow.loadFile(path.join(__dirname, '../renderer/gallery.html'));
510
+ galleryWindow.on('closed', () => {
511
+ galleryWindow = null;
512
+ });
513
+ }
514
+ function createRecordingBarWindow() {
515
+ logger_1.default.info('[RecordingBar] Creating recording bar window');
516
+ if (recordingBarWindow && !recordingBarWindow.isDestroyed()) {
517
+ recordingBarWindow.focus();
518
+ return;
519
+ }
520
+ const primaryDisplay = electron_1.screen.getPrimaryDisplay();
521
+ const { width: screenW } = primaryDisplay.size;
522
+ recordingBarWindow = new electron_1.BrowserWindow({
523
+ width: 300,
524
+ height: 50,
525
+ x: Math.round(screenW / 2 - 150),
526
+ y: 8,
527
+ frame: false,
528
+ transparent: true,
529
+ alwaysOnTop: true,
530
+ skipTaskbar: true,
531
+ resizable: false,
532
+ focusable: false,
533
+ webPreferences: {
534
+ preload: path.join(__dirname, 'preload.js'),
535
+ contextIsolation: true,
536
+ nodeIntegration: false,
537
+ navigateOnDragDrop: false,
538
+ },
539
+ });
540
+ attachCrashHandlers(recordingBarWindow, 'recording-bar');
541
+ recordingBarWindow.loadFile(path.join(__dirname, '../renderer/recording-bar.html'));
542
+ recordingBarWindow.setIgnoreMouseEvents(false);
543
+ recordingBarWindow.on('closed', () => {
544
+ recordingBarWindow = null;
545
+ });
546
+ }
547
+ function closeRecordingBarWindow() {
548
+ if (recordingBarWindow && !recordingBarWindow.isDestroyed()) {
549
+ recordingBarWindow.close();
550
+ recordingBarWindow = null;
551
+ }
552
+ }
553
+ // --- Dictation indicator window (floating push-to-talk indicator) ---
554
+ function createDictationIndicatorWindow() {
555
+ logger_1.default.info('[Dictation] Creating indicator window');
556
+ if (dictationIndicatorWindow && !dictationIndicatorWindow.isDestroyed())
557
+ return;
558
+ const primaryDisplay = electron_1.screen.getPrimaryDisplay();
559
+ const { width: screenW } = primaryDisplay.size;
560
+ dictationIndicatorWindow = new electron_1.BrowserWindow({
561
+ width: 420,
562
+ height: 48,
563
+ x: Math.round(screenW / 2 - 210),
564
+ y: 8,
565
+ frame: false,
566
+ transparent: true,
567
+ alwaysOnTop: true,
568
+ skipTaskbar: true,
569
+ resizable: false,
570
+ focusable: false,
571
+ show: false,
572
+ webPreferences: {
573
+ preload: path.join(__dirname, 'preload.js'),
574
+ contextIsolation: true,
575
+ nodeIntegration: false,
576
+ navigateOnDragDrop: false,
577
+ },
578
+ });
579
+ attachCrashHandlers(dictationIndicatorWindow, 'dictation-indicator');
580
+ dictationIndicatorWindow.loadFile(path.join(__dirname, '../renderer/dictation-indicator.html'));
581
+ dictationIndicatorWindow.on('closed', () => {
582
+ dictationIndicatorWindow = null;
583
+ });
584
+ }
585
+ function closeDictationIndicatorWindow() {
586
+ if (dictationIndicatorWindow && !dictationIndicatorWindow.isDestroyed()) {
587
+ dictationIndicatorWindow.close();
588
+ dictationIndicatorWindow = null;
589
+ }
590
+ }
591
+ // --- Timeline window ---
592
+ function createTimelineWindow(sessionId) {
593
+ logger_1.default.info('[Timeline] Creating timeline window, sessionId:', sessionId);
594
+ if (timelineWindow && !timelineWindow.isDestroyed()) {
595
+ timelineWindow.focus();
596
+ // If a sessionId is passed, tell it to navigate there
597
+ if (sessionId) {
598
+ timelineWindow.webContents.send('timeline:open-session', sessionId);
599
+ }
600
+ return;
601
+ }
602
+ timelineWindow = new electron_1.BrowserWindow({
603
+ width: 960,
604
+ height: 700,
605
+ ...framelessWindowOptions(),
606
+ webPreferences: {
607
+ preload: path.join(__dirname, 'preload.js'),
608
+ contextIsolation: true,
609
+ nodeIntegration: false,
610
+ navigateOnDragDrop: false,
611
+ },
612
+ });
613
+ makeWindowFocusAware(timelineWindow);
614
+ attachCrashHandlers(timelineWindow, 'timeline');
615
+ timelineWindow.loadFile(path.join(__dirname, '../renderer/timeline.html'));
616
+ if (sessionId) {
617
+ timelineWindow.webContents.once('did-finish-load', () => {
618
+ timelineWindow?.webContents.send('timeline:open-session', sessionId);
619
+ });
620
+ }
621
+ timelineWindow.on('closed', () => {
622
+ timelineWindow = null;
623
+ });
624
+ }
625
+ function createStartRecordingWindow() {
626
+ logger_1.default.info('[StartRecording] Creating start recording dialog window');
627
+ if (startRecordingWindow && !startRecordingWindow.isDestroyed()) {
628
+ startRecordingWindow.focus();
629
+ return;
630
+ }
631
+ startRecordingWindow = new electron_1.BrowserWindow({
632
+ width: 480,
633
+ height: 420,
634
+ ...framelessWindowOptions(),
635
+ resizable: false,
636
+ center: true,
637
+ alwaysOnTop: false,
638
+ webPreferences: {
639
+ preload: path.join(__dirname, 'preload.js'),
640
+ contextIsolation: true,
641
+ nodeIntegration: false,
642
+ navigateOnDragDrop: false,
643
+ },
644
+ });
645
+ attachCrashHandlers(startRecordingWindow, 'start-recording');
646
+ startRecordingWindow.loadFile(path.join(__dirname, '../renderer/start-recording.html'));
647
+ startRecordingWindow.on('closed', () => {
648
+ startRecordingWindow = null;
649
+ });
650
+ }
651
+ async function captureAndSaveRegion(fullScreenBuffer, region, suffix = '') {
652
+ let croppedBuffer = await (0, capture_1.cropRegion)(fullScreenBuffer, region);
653
+ // Auto-redact sensitive content if enabled
654
+ const redactSecrets = !!(0, store_1.getSetting)('autoRedactSecrets');
655
+ const redactPII = !!(0, store_1.getSetting)('autoRedactPII');
656
+ logger_1.default.info(`[Capture] Auto-redact check: secrets=${redactSecrets}, pii=${redactPII}`);
657
+ if (redactSecrets || redactPII) {
658
+ logger_1.default.info('[Capture] Running auto-redact on captured image...');
659
+ const result = await (0, redact_1.autoRedact)(croppedBuffer, { secrets: redactSecrets, pii: redactPII });
660
+ logger_1.default.info(`[Capture] Auto-redact result: ${result.regionsFound} regions found`);
661
+ croppedBuffer = result.buffer;
662
+ }
663
+ ensureCapturesDir();
664
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
665
+ const filename = `capture-${timestamp}${suffix}.png`;
666
+ const filepath = path.join(getCapturesDir(), filename);
667
+ fs.writeFileSync(filepath, croppedBuffer);
668
+ const captureId = (0, database_1.saveCapture)({
669
+ screenshotPath: filepath,
670
+ regionX: region.x,
671
+ regionY: region.y,
672
+ regionW: region.width,
673
+ regionH: region.height,
674
+ sourceApp: lastActiveWindow.appName,
675
+ windowTitle: lastActiveWindow.windowTitle,
676
+ });
677
+ // Store last capture region for repeat-capture
678
+ (0, capture_modes_1.setLastCaptureRegion)(region);
679
+ // Track analytics
680
+ (0, database_1.trackAnalytics)('capture', suffix === '' ? 'manual' : 'other', 1, 0, lastActiveWindow.appName || '');
681
+ return { filepath, captureId };
682
+ }
683
+ /**
684
+ * Draw a red circle click indicator on a nativeImage at the given physical pixel coordinates.
685
+ * Coordinates should already be in the screenshot's pixel space (converted at capture time
686
+ * on macOS; already physical on Windows).
687
+ */
688
+ function drawClickIndicator(image, physX, physY) {
689
+ const size = image.getSize();
690
+ const cx = Math.round(physX);
691
+ const cy = Math.round(physY);
692
+ // Scale circle size relative to image — 12px at 1920w, proportionally larger for higher res
693
+ const baseSize = Math.max(size.width, size.height);
694
+ const radius = Math.round(baseSize * 0.008); // ~15px at 1920w, ~30px at 3840w
695
+ const thickness = Math.max(2, Math.round(radius * 0.25));
696
+ const bitmap = image.toBitmap();
697
+ const w = size.width;
698
+ const h = size.height;
699
+ const bpp = 4; // BGRA
700
+ // Draw a red circle ring (not filled) at (cx, cy)
701
+ for (let dy = -radius - thickness; dy <= radius + thickness; dy++) {
702
+ for (let dx = -radius - thickness; dx <= radius + thickness; dx++) {
703
+ const dist = Math.sqrt(dx * dx + dy * dy);
704
+ if (dist >= radius - thickness / 2 && dist <= radius + thickness / 2) {
705
+ const px = cx + dx;
706
+ const py = cy + dy;
707
+ if (px >= 0 && px < w && py >= 0 && py < h) {
708
+ const offset = (py * w + px) * bpp;
709
+ bitmap[offset] = 68; // B
710
+ bitmap[offset + 1] = 68; // G
711
+ bitmap[offset + 2] = 239; // R (#EF4444)
712
+ bitmap[offset + 3] = 255; // A
713
+ }
714
+ }
715
+ }
716
+ }
717
+ return electron_1.nativeImage.createFromBitmap(bitmap, { width: w, height: h });
718
+ }
719
+ /** Load an image file into a nativeImage, handling WebP conversion via sharp */
720
+ async function loadImageForClipboard(filepath) {
721
+ let image = electron_1.nativeImage.createFromPath(filepath);
722
+ if (image.isEmpty()) {
723
+ const buf = fs.readFileSync(filepath);
724
+ image = electron_1.nativeImage.createFromBuffer(buf);
725
+ }
726
+ if (image.isEmpty()) {
727
+ try {
728
+ const sharp = require('sharp');
729
+ const pngBuf = await sharp(filepath).png().toBuffer();
730
+ image = electron_1.nativeImage.createFromBuffer(pngBuf);
731
+ }
732
+ catch {
733
+ logger_1.default.warn('[Copy] Cannot convert unsupported format:', filepath);
734
+ }
735
+ }
736
+ return image;
737
+ }
738
+ // Overlay note text as a subtle banner at the bottom of an image (for clipboard copy).
739
+ // Returns a new PNG buffer with the note rendered. Original file is not modified.
740
+ async function overlayNoteOnImage(inputBuffer, noteText, imgWidth) {
741
+ const sharp = require('sharp');
742
+ const escXml = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
743
+ const fontSize = Math.max(12, Math.min(16, Math.floor(imgWidth / 55)));
744
+ const padding = 8;
745
+ const lineHeight = fontSize + 6;
746
+ const maxChars = Math.floor((imgWidth - padding * 2) / (fontSize * 0.52));
747
+ // Word-wrap
748
+ const words = noteText.split(' ');
749
+ const lines = [];
750
+ let cur = '';
751
+ for (const w of words) {
752
+ if (cur && (cur + ' ' + w).length > maxChars) {
753
+ lines.push(cur);
754
+ cur = w;
755
+ }
756
+ else {
757
+ cur = cur ? cur + ' ' + w : w;
758
+ }
759
+ }
760
+ if (cur)
761
+ lines.push(cur);
762
+ if (lines.length > 4) {
763
+ lines.length = 4;
764
+ lines[3] = lines[3].slice(0, -3) + '...';
765
+ }
766
+ const bannerH = lines.length * lineHeight + padding * 2;
767
+ const textEls = lines
768
+ .map((ln, i) => `<text x="${padding}" y="${padding + (i + 1) * lineHeight - 4}" fill="#e0e0e0" font-size="${fontSize}" font-family="Segoe UI, Inter, system-ui, sans-serif">${escXml(ln)}</text>`)
769
+ .join('');
770
+ const svg = Buffer.from(`<svg width="${imgWidth}" height="${bannerH}"><rect width="${imgWidth}" height="${bannerH}" fill="#1a1a1a" rx="0"/>${textEls}</svg>`);
771
+ return sharp(inputBuffer)
772
+ .extend({ bottom: bannerH, background: { r: 26, g: 26, b: 26, alpha: 255 } })
773
+ .composite([{ input: svg, gravity: 'south' }])
774
+ .png()
775
+ .toBuffer();
776
+ }
777
+ // Store notes and register/manage the global paste shortcut
778
+ function setPendingNotes(text) {
779
+ pendingNotesText = text;
780
+ const shortcut = (0, store_1.getSetting)('notePasteShortcut') || 'CommandOrControl+Shift+N';
781
+ if (text && !notesPasteShortcutRegistered) {
782
+ try {
783
+ const ok = electron_1.globalShortcut.register(shortcut, async () => {
784
+ if (!pendingNotesText)
785
+ return;
786
+ const notes = pendingNotesText;
787
+ // Write notes to clipboard and simulate paste (same pattern as dictation)
788
+ const { saveClipboardState, writeClipboardText, restoreClipboardState } = await Promise.resolve().then(() => __importStar(require('./modules/clipboard')));
789
+ const { simulatePaste } = await Promise.resolve().then(() => __importStar(require('./modules/keystroke')));
790
+ saveClipboardState();
791
+ writeClipboardText(notes);
792
+ await simulatePaste();
793
+ setTimeout(() => restoreClipboardState(), 200);
794
+ logger_1.default.info('[Notes] Pasted notes via shortcut (' + shortcut + ')');
795
+ });
796
+ if (ok) {
797
+ notesPasteShortcutRegistered = true;
798
+ logger_1.default.info('[Notes] Shortcut registered:', shortcut);
799
+ // Auto-clear after 5 minutes
800
+ setTimeout(() => {
801
+ if (pendingNotesText === text) {
802
+ setPendingNotes(null);
803
+ }
804
+ }, 5 * 60 * 1000);
805
+ }
806
+ }
807
+ catch (err) {
808
+ logger_1.default.warn('[Notes] Failed to register shortcut:', err);
809
+ }
810
+ }
811
+ else if (!text && notesPasteShortcutRegistered) {
812
+ try {
813
+ const shortcutToUnregister = (0, store_1.getSetting)('notePasteShortcut') || 'CommandOrControl+Shift+N';
814
+ electron_1.globalShortcut.unregister(shortcutToUnregister);
815
+ }
816
+ catch { }
817
+ notesPasteShortcutRegistered = false;
818
+ logger_1.default.info('[Notes] Shortcut unregistered');
819
+ }
820
+ }
821
+ function setupIpcHandlers() {
822
+ // Single selection completed
823
+ electron_1.ipcMain.handle('capture:selection-complete', async (_event, region) => {
824
+ try {
825
+ // If adding to existing overlay, just capture and send the path back
826
+ if (addingToExistingOverlay) {
827
+ addingToExistingOverlay = false;
828
+ await dismissSelectionWindow();
829
+ const fullScreenBuffer = await getCaptureBuffer();
830
+ await closeSelectionWindow();
831
+ const { filepath } = await captureAndSaveRegion(fullScreenBuffer, region);
832
+ // Show overlay again and notify it of the new screenshot
833
+ if (overlayWindow && !overlayWindow.isDestroyed()) {
834
+ overlayWindow.show();
835
+ overlayWindow.webContents.send('capture:screenshot-added', filepath);
836
+ }
837
+ return { success: true, filepath };
838
+ }
839
+ // Scroll-capture mode: capture the region, then auto-scroll and capture more
840
+ if (scrollCaptureMode) {
841
+ scrollCaptureMode = false;
842
+ await dismissSelectionWindow();
843
+ await closeSelectionWindow();
844
+ const scrollSettings = (0, store_1.getSetting)('scrollCapture') || {};
845
+ const maxScreenshots = scrollSettings.maxScreenshots || 10;
846
+ const overlapPercent = scrollSettings.overlapPercent || 15;
847
+ const scrollDelayMs = scrollSettings.scrollDelayMs || 600;
848
+ let pixelsPerScroll = scrollSettings.pixelsPerScroll || 0;
849
+ const { performScrollCapture, calibrateScroll } = require('./modules/scroll-capture');
850
+ // Auto-calibrate if not done yet
851
+ if (pixelsPerScroll <= 0) {
852
+ logger_1.default.info('[ScrollCapture] No calibration found, auto-calibrating...');
853
+ pixelsPerScroll = await calibrateScroll(region);
854
+ const current = (0, store_1.getSetting)('scrollCapture') || {};
855
+ (0, store_1.setSetting)('scrollCapture', { ...current, pixelsPerScroll });
856
+ }
857
+ const screenshotPaths = [];
858
+ let primaryCaptureId = 0;
859
+ const captures = await performScrollCapture({
860
+ region,
861
+ maxScreenshots,
862
+ overlapPercent,
863
+ scrollDelayMs,
864
+ pixelsPerScroll,
865
+ onProgress: () => { },
866
+ });
867
+ // Save all captures
868
+ ensureCapturesDir();
869
+ for (let i = 0; i < captures.length; i++) {
870
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
871
+ const filename = `scroll-${timestamp}-${i + 1}.png`;
872
+ const filepath = path.join(getCapturesDir(), filename);
873
+ fs.writeFileSync(filepath, captures[i]);
874
+ screenshotPaths.push(filepath);
875
+ if (i === 0) {
876
+ primaryCaptureId = (0, database_1.saveCapture)({
877
+ screenshotPath: filepath,
878
+ regionX: region.x,
879
+ regionY: region.y,
880
+ regionW: region.width,
881
+ regionH: region.height,
882
+ sourceApp: lastActiveWindow.appName,
883
+ windowTitle: lastActiveWindow.windowTitle,
884
+ });
885
+ }
886
+ }
887
+ // Open overlay with all captured screenshots
888
+ createOverlayWindow({
889
+ screenshotPath: screenshotPaths[0],
890
+ captureId: primaryCaptureId,
891
+ hasApiKey: (0, auth_1.isAuthenticated)(),
892
+ voiceMode: false,
893
+ inlineEditMode: false,
894
+ originalText: null,
895
+ multiRegion: true,
896
+ regionScreenshots: screenshotPaths,
897
+ }, region);
898
+ return { success: true, captureId: primaryCaptureId, count: captures.length };
899
+ }
900
+ // Normal flow: create new overlay
901
+ const isInlineEdit = !!region.altHeld;
902
+ let originalText = null;
903
+ if (isInlineEdit) {
904
+ (0, clipboard_1.saveClipboardState)();
905
+ await dismissSelectionWindow();
906
+ await (0, keystroke_1.simulateCopy)();
907
+ await new Promise((resolve) => setTimeout(resolve, 150));
908
+ originalText = (0, clipboard_1.readClipboardText)();
909
+ // originalText captured above for inline-edit undo
910
+ }
911
+ else {
912
+ await dismissSelectionWindow();
913
+ }
914
+ const fullScreenBuffer = await getCaptureBuffer();
915
+ await closeSelectionWindow();
916
+ const { filepath, captureId } = await captureAndSaveRegion(fullScreenBuffer, region);
917
+ createOverlayWindow({
918
+ screenshotPath: filepath,
919
+ captureId,
920
+ hasApiKey: (0, auth_1.isAuthenticated)(),
921
+ voiceMode: !!region.shiftHeld,
922
+ inlineEditMode: isInlineEdit,
923
+ originalText,
924
+ multiRegion: false,
925
+ regionScreenshots: [],
926
+ }, region);
927
+ return { success: true, captureId, filepath };
928
+ }
929
+ catch (error) {
930
+ logger_1.default.error('Capture failed:', error);
931
+ addingToExistingOverlay = false;
932
+ return { success: false, error: String(error) };
933
+ }
934
+ });
935
+ // Multi-selection completed
936
+ electron_1.ipcMain.handle('capture:multi-selection-complete', async (_event, data) => {
937
+ try {
938
+ await dismissSelectionWindow();
939
+ const fullScreenBuffer = await getCaptureBuffer();
940
+ await closeSelectionWindow();
941
+ // Capture each region separately
942
+ const regionScreenshots = [];
943
+ let primaryCaptureId = 0;
944
+ let primaryFilepath = '';
945
+ for (let i = 0; i < data.regions.length; i++) {
946
+ const { filepath, captureId } = await captureAndSaveRegion(fullScreenBuffer, data.regions[i], `-region${i + 1}`);
947
+ regionScreenshots.push(filepath);
948
+ if (i === 0) {
949
+ primaryCaptureId = captureId;
950
+ primaryFilepath = filepath;
951
+ }
952
+ }
953
+ createOverlayWindow({
954
+ screenshotPath: primaryFilepath,
955
+ captureId: primaryCaptureId,
956
+ hasApiKey: (0, auth_1.isAuthenticated)(),
957
+ voiceMode: !!data.shiftHeld,
958
+ inlineEditMode: false,
959
+ originalText: null,
960
+ multiRegion: true,
961
+ regionScreenshots,
962
+ }, data.regions[0]);
963
+ return { success: true, captureId: primaryCaptureId };
964
+ }
965
+ catch (error) {
966
+ logger_1.default.error('Multi-capture failed:', error);
967
+ return { success: false, error: String(error) };
968
+ }
969
+ });
970
+ electron_1.ipcMain.handle('capture:cancel', async () => {
971
+ if (isMac && selectionWindow && !selectionWindow.isDestroyed() && selectionWindow.isSimpleFullScreen()) {
972
+ selectionWindow.setSimpleFullScreen(false);
973
+ await new Promise((resolve) => setTimeout(resolve, 100));
974
+ }
975
+ await closeSelectionWindow();
976
+ addingToExistingOverlay = false;
977
+ // Restore hidden windows after cancellation
978
+ if (overlayWindow && !overlayWindow.isDestroyed()) {
979
+ overlayWindow.show();
980
+ }
981
+ if (mainPanelWindow && !mainPanelWindow.isDestroyed()) {
982
+ mainPanelWindow.show();
983
+ }
984
+ return { success: true };
985
+ });
986
+ // AI: process screenshot with instruction
987
+ // Add more screenshots to existing overlay
988
+ electron_1.ipcMain.handle('capture:add-screenshot', async () => {
989
+ if (!overlayWindow || overlayWindow.isDestroyed())
990
+ return { success: false };
991
+ addingToExistingOverlay = true;
992
+ overlayWindow.hide();
993
+ await new Promise((resolve) => setTimeout(resolve, 100));
994
+ createSelectionWindow();
995
+ return { success: true };
996
+ });
997
+ electron_1.ipcMain.handle('ai:process', async (_event, data) => {
998
+ // Require authentication for AI features
999
+ if (!(0, auth_1.isAuthenticated)()) {
1000
+ return { success: false, error: 'Please sign in to use AI features.' };
1001
+ }
1002
+ try {
1003
+ // Support both single and multiple screenshot paths
1004
+ const paths = data.screenshotPaths || (data.screenshotPath ? [data.screenshotPath] : []);
1005
+ for (const p of paths) {
1006
+ if (!isPathSafe(p)) {
1007
+ return { success: false, error: 'Invalid file path' };
1008
+ }
1009
+ }
1010
+ // Vision optimization: resize images to max 1568px longest edge before sending to backend
1011
+ const sharp = require('sharp');
1012
+ const imagesBase64 = [];
1013
+ for (const p of paths) {
1014
+ const buf = fs.readFileSync(p);
1015
+ const meta = await sharp(buf).metadata();
1016
+ const maxDim = Math.max(meta.width || 0, meta.height || 0);
1017
+ if (maxDim > 1568) {
1018
+ const resized = await sharp(buf)
1019
+ .resize({
1020
+ width: maxDim === meta.width ? 1568 : undefined,
1021
+ height: maxDim === meta.height ? 1568 : undefined,
1022
+ fit: 'inside',
1023
+ })
1024
+ .png()
1025
+ .toBuffer();
1026
+ imagesBase64.push(resized.toString('base64'));
1027
+ }
1028
+ else {
1029
+ imagesBase64.push(buf.toString('base64'));
1030
+ }
1031
+ }
1032
+ // Estimate token usage for multi-image and warn if near limit
1033
+ if (imagesBase64.length > 1) {
1034
+ let totalEstTokens = 0;
1035
+ for (const b64 of imagesBase64) {
1036
+ const sizeBytes = b64.length * 0.75;
1037
+ const megapixels = sizeBytes / (3 * 1024 * 1024);
1038
+ totalEstTokens += Math.max(1600, Math.round(megapixels * 1600));
1039
+ }
1040
+ if (totalEstTokens > 80000 && overlayWindow && !overlayWindow.isDestroyed()) {
1041
+ overlayWindow.webContents.send('ai:token-warning', {
1042
+ estimatedTokens: totalEstTokens,
1043
+ imageCount: imagesBase64.length,
1044
+ });
1045
+ }
1046
+ }
1047
+ const { instruction } = (0, instruction_parser_1.parseInstruction)(data.instruction);
1048
+ const systemPrompt = (0, store_1.getSetting)('systemPrompt') || '';
1049
+ const contexts = imagesBase64.map((imageBase64, i) => ({
1050
+ imageBase64,
1051
+ sourceApp: lastActiveWindow.appName,
1052
+ windowTitle: lastActiveWindow.windowTitle,
1053
+ regionIndex: i,
1054
+ }));
1055
+ const fullPrompt = (systemPrompt ? systemPrompt + '\n\n' : '') + (0, context_builder_1.buildPrompt)(instruction, contexts);
1056
+ let fullResponse = '';
1057
+ logger_1.default.info(`[AI] Starting stream via backend proxy, images=${imagesBase64.length}`);
1058
+ let chunksSent = 0;
1059
+ for await (const chunk of (0, ai_client_1.streamAIFromBackend)({
1060
+ imagesBase64,
1061
+ instruction: fullPrompt,
1062
+ conversationHistory: data.conversationHistory,
1063
+ })) {
1064
+ fullResponse += chunk;
1065
+ chunksSent++;
1066
+ if (overlayWindow && !overlayWindow.isDestroyed()) {
1067
+ overlayWindow.webContents.send('ai:stream-chunk', chunk);
1068
+ }
1069
+ }
1070
+ logger_1.default.info(`[AI] Stream finished. Chunks sent: ${chunksSent}, Response length: ${fullResponse.length}`);
1071
+ logger_1.default.info(`[AI] First 200 chars: ${fullResponse.slice(0, 200)}`);
1072
+ if (overlayWindow && !overlayWindow.isDestroyed()) {
1073
+ overlayWindow.webContents.send('ai:stream-complete');
1074
+ logger_1.default.info('[AI] Sent stream-complete to overlay');
1075
+ }
1076
+ (0, database_1.updateCapture)(data.captureId, {
1077
+ aiResponse: fullResponse,
1078
+ instruction: data.instruction,
1079
+ });
1080
+ // Track AI query analytics
1081
+ (0, database_1.trackAnalytics)('ai_query', '', 1, fullResponse.length);
1082
+ return { success: true, response: fullResponse };
1083
+ }
1084
+ catch (error) {
1085
+ const errorMsg = error instanceof Error ? error.message : String(error);
1086
+ if (overlayWindow && !overlayWindow.isDestroyed()) {
1087
+ overlayWindow.webContents.send('ai:stream-error', errorMsg);
1088
+ }
1089
+ return { success: false, error: errorMsg };
1090
+ }
1091
+ });
1092
+ // Screenshot classification — heuristic-based, cached per path
1093
+ const classificationCache = new Map();
1094
+ electron_1.ipcMain.handle('ai:classify-screenshot', async (_event, screenshotPath) => {
1095
+ if (classificationCache.has(screenshotPath)) {
1096
+ return { success: true, type: classificationCache.get(screenshotPath) };
1097
+ }
1098
+ try {
1099
+ // Use window title/app name for heuristic classification
1100
+ const appName = (lastActiveWindow.appName || '').toLowerCase();
1101
+ const title = (lastActiveWindow.windowTitle || '').toLowerCase();
1102
+ let type = 'general';
1103
+ if (/code|vs\s?code|visual studio|intellij|webstorm|sublime|vim|neovim|terminal|cmd|powershell|bash/.test(appName + ' ' + title)) {
1104
+ type = 'code';
1105
+ }
1106
+ else if (/error|exception|crash|fail|stack trace|traceback/.test(title)) {
1107
+ type = 'error';
1108
+ }
1109
+ else if (/chrome|firefox|edge|safari|opera|brave|browser/.test(appName)) {
1110
+ type = 'ui';
1111
+ }
1112
+ else if (/word|docs|notion|obsidian|notepad|txt|pdf|reader/.test(appName + ' ' + title)) {
1113
+ type = 'text';
1114
+ }
1115
+ else if (/excel|sheets|csv|table|data|sql|database/.test(appName + ' ' + title)) {
1116
+ type = 'data';
1117
+ }
1118
+ classificationCache.set(screenshotPath, type);
1119
+ return { success: true, type };
1120
+ }
1121
+ catch {
1122
+ return { success: true, type: 'general' };
1123
+ }
1124
+ });
1125
+ // Voice transcription via OpenAI Whisper
1126
+ // Voice transcription via backend proxy (OpenAI Whisper)
1127
+ electron_1.ipcMain.handle('voice:transcribe', async (_event, audioBase64) => {
1128
+ if (!(0, auth_1.isAuthenticated)()) {
1129
+ return { success: false, error: 'Please sign in to use voice features.' };
1130
+ }
1131
+ try {
1132
+ const text = await (0, ai_client_1.transcribeViaBackend)(audioBase64);
1133
+ logger_1.default.info('[Voice] Transcription:', text.slice(0, 100));
1134
+ return { success: true, text: text.trim() };
1135
+ }
1136
+ catch (error) {
1137
+ const msg = error instanceof Error ? error.message : String(error);
1138
+ logger_1.default.error('[Voice] Transcription error:', msg);
1139
+ return { success: false, error: msg };
1140
+ }
1141
+ });
1142
+ // Dictation: receive audio from indicator window, transcribe, paste
1143
+ electron_1.ipcMain.handle('dictation:audio-ready', async (_event, audioBase64) => {
1144
+ const { handleAudioReady } = await Promise.resolve().then(() => __importStar(require('./modules/dictation')));
1145
+ return handleAudioReady(audioBase64);
1146
+ });
1147
+ // Dictation: enable/disable
1148
+ electron_1.ipcMain.handle('dictation:set-enabled', async (_event, enabled) => {
1149
+ try {
1150
+ if (enabled && !(0, auth_1.isAuthenticated)()) {
1151
+ return { success: false, error: 'Please sign in to use dictation.' };
1152
+ }
1153
+ (0, store_1.setSetting)('dictationEnabled', enabled);
1154
+ if (enabled) {
1155
+ if (!dictationIndicatorWindow || dictationIndicatorWindow.isDestroyed()) {
1156
+ createDictationIndicatorWindow();
1157
+ }
1158
+ const { initializeDictation } = await Promise.resolve().then(() => __importStar(require('./modules/dictation')));
1159
+ await initializeDictation(dictationIndicatorWindow);
1160
+ logger_1.default.info('[Dictation] Enabled');
1161
+ }
1162
+ else {
1163
+ const { teardownDictation } = await Promise.resolve().then(() => __importStar(require('./modules/dictation')));
1164
+ await teardownDictation();
1165
+ if (dictationIndicatorWindow && !dictationIndicatorWindow.isDestroyed()) {
1166
+ dictationIndicatorWindow.hide();
1167
+ }
1168
+ logger_1.default.info('[Dictation] Disabled');
1169
+ }
1170
+ return { success: true };
1171
+ }
1172
+ catch (error) {
1173
+ return { success: false, error: String(error) };
1174
+ }
1175
+ });
1176
+ // Dictation: update settings
1177
+ electron_1.ipcMain.handle('dictation:set-settings', async (_event, settings) => {
1178
+ const current = (0, store_1.getSetting)('dictationSettings') || {};
1179
+ const updated = { ...current, ...settings };
1180
+ (0, store_1.setSetting)('dictationSettings', updated);
1181
+ // Update live dictation module if running
1182
+ try {
1183
+ const dictation = await Promise.resolve().then(() => __importStar(require('./modules/dictation')));
1184
+ if (settings.shortcutModifiers) {
1185
+ dictation.setDictationShortcut(settings.shortcutModifiers);
1186
+ }
1187
+ if (settings.aiCleanup !== undefined) {
1188
+ dictation.setDictationAICleanup(settings.aiCleanup);
1189
+ }
1190
+ if (settings.soundFeedback !== undefined) {
1191
+ dictation.setDictationSoundFeedback(settings.soundFeedback);
1192
+ }
1193
+ if (settings.maxDurationSeconds !== undefined) {
1194
+ dictation.setDictationMaxDuration(settings.maxDurationSeconds);
1195
+ }
1196
+ if (settings.excludedApps !== undefined) {
1197
+ dictation.setDictationExcludedApps(settings.excludedApps);
1198
+ }
1199
+ if (settings.language !== undefined) {
1200
+ dictation.setDictationLanguage(settings.language);
1201
+ }
1202
+ if (settings.pasteMethod !== undefined) {
1203
+ dictation.setDictationPasteMethod(settings.pasteMethod);
1204
+ }
1205
+ if (settings.endSilenceMs !== undefined || settings.initialSilenceMs !== undefined || settings.segmentationSilenceMs !== undefined) {
1206
+ dictation.setDictationTimingOptions({
1207
+ endSilenceMs: settings.endSilenceMs,
1208
+ initialSilenceMs: settings.initialSilenceMs,
1209
+ segmentationSilenceMs: settings.segmentationSilenceMs,
1210
+ });
1211
+ }
1212
+ }
1213
+ catch {
1214
+ // Module not loaded yet
1215
+ }
1216
+ return { success: true };
1217
+ });
1218
+ // Dictation: history
1219
+ electron_1.ipcMain.handle('dictation:get-history', async (_event, limit) => {
1220
+ const { getDictationHistory } = await Promise.resolve().then(() => __importStar(require('./db/database')));
1221
+ return getDictationHistory(limit || 50);
1222
+ });
1223
+ electron_1.ipcMain.handle('dictation:clear-history', async () => {
1224
+ const { clearDictationHistory } = await Promise.resolve().then(() => __importStar(require('./db/database')));
1225
+ clearDictationHistory();
1226
+ return { success: true };
1227
+ });
1228
+ // Dictation: personal dictionary
1229
+ electron_1.ipcMain.handle('dictation:get-dictionary', async () => {
1230
+ const { getDictionaryWords } = await Promise.resolve().then(() => __importStar(require('./db/database')));
1231
+ return getDictionaryWords();
1232
+ });
1233
+ electron_1.ipcMain.handle('dictation:add-dictionary-word', async (_event, word) => {
1234
+ const { addDictionaryWord } = await Promise.resolve().then(() => __importStar(require('./db/database')));
1235
+ addDictionaryWord(word);
1236
+ return { success: true };
1237
+ });
1238
+ electron_1.ipcMain.handle('dictation:remove-dictionary-word', async (_event, id) => {
1239
+ const { removeDictionaryWord } = await Promise.resolve().then(() => __importStar(require('./db/database')));
1240
+ removeDictionaryWord(id);
1241
+ return { success: true };
1242
+ });
1243
+ electron_1.ipcMain.handle('dictation:clear-dictionary', async () => {
1244
+ const { clearDictionary } = await Promise.resolve().then(() => __importStar(require('./db/database')));
1245
+ clearDictionary();
1246
+ return { success: true };
1247
+ });
1248
+ // Dictation: real-time speech — push audio buffer
1249
+ electron_1.ipcMain.on('dictation:push-audio', (_event, pcmBuffer) => {
1250
+ Promise.resolve().then(() => __importStar(require('./modules/azure-speech-realtime'))).then((mod) => {
1251
+ mod.pushAudioData(pcmBuffer);
1252
+ }).catch(() => { });
1253
+ });
1254
+ // AI usage — daily call count
1255
+ electron_1.ipcMain.handle('ai:get-usage', async () => {
1256
+ try {
1257
+ const usage = await (0, ai_client_1.getAIUsage)();
1258
+ return { success: true, ...usage };
1259
+ }
1260
+ catch (error) {
1261
+ return { success: false, error: error instanceof Error ? error.message : String(error) };
1262
+ }
1263
+ });
1264
+ // Promo code redemption
1265
+ electron_1.ipcMain.handle('promo:redeem', async (_event, code) => {
1266
+ try {
1267
+ const redemption = await (0, ai_client_1.redeemPromoCode)(code);
1268
+ return { success: true, redemption };
1269
+ }
1270
+ catch (error) {
1271
+ return { success: false, error: error instanceof Error ? error.message : String(error) };
1272
+ }
1273
+ });
1274
+ // Update shortcut
1275
+ electron_1.ipcMain.handle('settings:set-shortcut', async (_event, shortcut) => {
1276
+ try {
1277
+ const { updateShortcut } = require('./modules/hotkeys');
1278
+ const success = updateShortcut(shortcut, () => createSelectionWindow());
1279
+ if (success) {
1280
+ (0, store_1.setSetting)('activationShortcut', shortcut);
1281
+ return { success: true };
1282
+ }
1283
+ return { success: false, error: 'Failed to register shortcut. It may conflict with another app.' };
1284
+ }
1285
+ catch (error) {
1286
+ return { success: false, error: String(error) };
1287
+ }
1288
+ });
1289
+ // Browse for screenshot folder
1290
+ electron_1.ipcMain.handle('settings:browse-folder', async () => {
1291
+ logger_1.default.info('[Settings] Browse folder dialog opening...');
1292
+ try {
1293
+ const result = await electron_1.dialog.showOpenDialog({
1294
+ properties: ['openDirectory'],
1295
+ title: 'Choose screenshot folder',
1296
+ });
1297
+ logger_1.default.info('[Settings] Dialog result:', result.canceled ? 'canceled' : result.filePaths);
1298
+ if (result.canceled || !result.filePaths.length)
1299
+ return { success: false };
1300
+ const folder = result.filePaths[0];
1301
+ (0, store_1.setSetting)('screenshotFolder', folder);
1302
+ logger_1.default.info('[Settings] Screenshot folder saved:', folder);
1303
+ logger_1.default.info('[Settings] Read back:', (0, store_1.getSetting)('screenshotFolder'));
1304
+ return { success: true, folder };
1305
+ }
1306
+ catch (error) {
1307
+ logger_1.default.error('[Settings] Browse dialog error:', error);
1308
+ return { success: false, error: String(error) };
1309
+ }
1310
+ });
1311
+ // Set screenshot folder directly
1312
+ electron_1.ipcMain.handle('settings:set-generic', async (_event, data) => {
1313
+ (0, store_1.setSetting)(data.key, data.value);
1314
+ return { success: true };
1315
+ });
1316
+ electron_1.ipcMain.handle('settings:set-screenshot-folder', async (_event, folder) => {
1317
+ logger_1.default.info('[Settings] Setting screenshot folder to:', folder || '(default)');
1318
+ (0, store_1.setSetting)('screenshotFolder', folder);
1319
+ return { success: true };
1320
+ });
1321
+ // Scroll capture settings
1322
+ electron_1.ipcMain.handle('settings:set-scroll-capture', async (_event, settings) => {
1323
+ const current = (0, store_1.getSetting)('scrollCapture') || {};
1324
+ const updated = { ...current, ...settings };
1325
+ (0, store_1.setSetting)('scrollCapture', updated);
1326
+ // Re-register shortcut if it changed
1327
+ if (settings.shortcut && settings.shortcut !== current.shortcut) {
1328
+ electron_1.globalShortcut.unregister(current.shortcut || 'CommandOrControl+Shift+A');
1329
+ const success = electron_1.globalShortcut.register(settings.shortcut, () => {
1330
+ scrollCaptureMode = true;
1331
+ createSelectionWindow();
1332
+ });
1333
+ if (!success)
1334
+ return { success: false, error: 'Failed to register shortcut' };
1335
+ }
1336
+ return { success: true };
1337
+ });
1338
+ // Calibrate scroll: hide settings, wait for user to position mouse on scrollable content, then measure
1339
+ electron_1.ipcMain.handle('settings:calibrate-scroll', async () => {
1340
+ try {
1341
+ // Hide main panel window so it's not in the way
1342
+ if (mainPanelWindow && !mainPanelWindow.isDestroyed()) {
1343
+ mainPanelWindow.hide();
1344
+ }
1345
+ logger_1.default.info('[Calibrate] Settings hidden. Waiting 3s for user to position mouse over scrollable content...');
1346
+ // Show a native notification telling user what to do
1347
+ const { Notification } = require('electron');
1348
+ const notif = new Notification({
1349
+ title: 'Scroll Calibration',
1350
+ body: 'Move your mouse over scrollable content. Calibrating in 3 seconds...',
1351
+ silent: true,
1352
+ });
1353
+ notif.show();
1354
+ // Wait for user to move mouse to scrollable area
1355
+ await new Promise((resolve) => setTimeout(resolve, 3000));
1356
+ // Get current mouse position and create a region around it
1357
+ const mousePos = await nut_js_1.mouse.getPosition();
1358
+ logger_1.default.info(`[Calibrate] Mouse at: ${mousePos.x}, ${mousePos.y}`);
1359
+ const calRegion = {
1360
+ x: Math.max(0, mousePos.x - 200),
1361
+ y: Math.max(0, mousePos.y - 250),
1362
+ width: 400,
1363
+ height: 500,
1364
+ };
1365
+ const { calibrateScroll } = require('./modules/scroll-capture');
1366
+ const pixelsPerScroll = await calibrateScroll(calRegion);
1367
+ logger_1.default.info(`[Calibrate] Result: ${pixelsPerScroll} pixels per scroll unit`);
1368
+ // Save
1369
+ const current = (0, store_1.getSetting)('scrollCapture') || {};
1370
+ (0, store_1.setSetting)('scrollCapture', { ...current, pixelsPerScroll });
1371
+ // Show main panel window again
1372
+ if (mainPanelWindow && !mainPanelWindow.isDestroyed()) {
1373
+ mainPanelWindow.show();
1374
+ }
1375
+ return { success: true, pixelsPerScroll };
1376
+ }
1377
+ catch (error) {
1378
+ logger_1.default.error('[Calibrate] Error:', error);
1379
+ // Show main panel window again on error
1380
+ if (mainPanelWindow && !mainPanelWindow.isDestroyed()) {
1381
+ mainPanelWindow.show();
1382
+ }
1383
+ return { success: false, error: String(error) };
1384
+ }
1385
+ });
1386
+ // Inline edit: apply AI result to source app
1387
+ electron_1.ipcMain.handle('inline-edit:apply', async (_event, text) => {
1388
+ try {
1389
+ // Write AI response to clipboard
1390
+ (0, clipboard_1.writeClipboardText)(text);
1391
+ await new Promise((resolve) => setTimeout(resolve, 100));
1392
+ // Minimize overlay temporarily to give focus back to source app
1393
+ if (overlayWindow && !overlayWindow.isDestroyed()) {
1394
+ overlayWindow.hide();
1395
+ }
1396
+ await new Promise((resolve) => setTimeout(resolve, 150));
1397
+ // Simulate Ctrl+V to paste
1398
+ await (0, keystroke_1.simulatePaste)();
1399
+ await new Promise((resolve) => setTimeout(resolve, 200));
1400
+ // Show overlay again
1401
+ if (overlayWindow && !overlayWindow.isDestroyed()) {
1402
+ overlayWindow.show();
1403
+ }
1404
+ return { success: true };
1405
+ }
1406
+ catch (error) {
1407
+ return { success: false, error: String(error) };
1408
+ }
1409
+ });
1410
+ // Inline edit: undo
1411
+ electron_1.ipcMain.handle('inline-edit:undo', async () => {
1412
+ try {
1413
+ if (overlayWindow && !overlayWindow.isDestroyed()) {
1414
+ overlayWindow.hide();
1415
+ }
1416
+ await new Promise((resolve) => setTimeout(resolve, 150));
1417
+ // Simulate Ctrl+Z in the source app
1418
+ await (0, keystroke_1.simulateUndo)();
1419
+ await new Promise((resolve) => setTimeout(resolve, 100));
1420
+ // Restore original clipboard
1421
+ (0, clipboard_1.restoreClipboardState)();
1422
+ if (overlayWindow && !overlayWindow.isDestroyed()) {
1423
+ overlayWindow.show();
1424
+ }
1425
+ return { success: true };
1426
+ }
1427
+ catch (error) {
1428
+ return { success: false, error: String(error) };
1429
+ }
1430
+ });
1431
+ // Clipboard operations
1432
+ // Native file drag from overlay
1433
+ // Save edited image (overwrites original, or writes to new file if locked on Windows)
1434
+ electron_1.ipcMain.handle('overlay:save-edited-image', async (_event, data) => {
1435
+ logger_1.default.info('[Editor] save-edited-image called, path:', data.filepath, 'base64 length:', data.base64?.length);
1436
+ try {
1437
+ if (!isPathSafe(data.filepath)) {
1438
+ logger_1.default.warn('[Editor] isPathSafe REJECTED path:', data.filepath);
1439
+ return { success: false, error: 'Invalid file path' };
1440
+ }
1441
+ const buffer = Buffer.from(data.base64, 'base64');
1442
+ let savedPath = data.filepath;
1443
+ try {
1444
+ fs.writeFileSync(data.filepath, buffer);
1445
+ }
1446
+ catch (writeErr) {
1447
+ // On Windows, file may be locked by Chromium or other process.
1448
+ // Write to a sibling .edited.png file and update DB reference.
1449
+ const dir = path.dirname(data.filepath);
1450
+ const base = path.basename(data.filepath, path.extname(data.filepath));
1451
+ savedPath = path.join(dir, `${base}_edited.png`);
1452
+ logger_1.default.info('[Editor] Original locked, writing to:', savedPath);
1453
+ fs.writeFileSync(savedPath, buffer);
1454
+ // Update database record to point to the new file
1455
+ try {
1456
+ const { getDatabase } = require('./db/database');
1457
+ const db = getDatabase();
1458
+ db.prepare('UPDATE captures SET screenshot_path = ? WHERE screenshot_path = ?').run(savedPath, data.filepath);
1459
+ logger_1.default.info('[Editor] Updated DB screenshot_path:', data.filepath, '->', savedPath);
1460
+ }
1461
+ catch (dbErr) {
1462
+ logger_1.default.warn('[Editor] DB update failed (non-fatal):', dbErr);
1463
+ }
1464
+ }
1465
+ logger_1.default.info('[Editor] Saved edited image:', savedPath, 'size:', buffer.length);
1466
+ // Invalidate thumbnail cache for both old and new paths
1467
+ thumbnailCache.delete(data.filepath);
1468
+ thumbnailCache.delete(savedPath);
1469
+ // Notify all windows that a capture was updated so thumbnails refresh
1470
+ for (const win of electron_1.BrowserWindow.getAllWindows()) {
1471
+ if (!win.isDestroyed()) {
1472
+ win.webContents.send('capture:updated', savedPath);
1473
+ }
1474
+ }
1475
+ return { success: true };
1476
+ }
1477
+ catch (error) {
1478
+ logger_1.default.error('[Editor] save-edited-image FAILED:', error);
1479
+ return { success: false, error: String(error) };
1480
+ }
1481
+ });
1482
+ // Create temp annotated copies of images with note banners
1483
+ electron_1.ipcMain.handle('overlay:annotate-files', async (_event, filepaths, notesMap) => {
1484
+ const embedEnabled = (0, store_1.getSetting)('noteEmbedInImage') !== false;
1485
+ if (!embedEnabled)
1486
+ return { paths: filepaths };
1487
+ const tmpDir = electron_1.app.getPath('temp');
1488
+ const annotatedPaths = [];
1489
+ for (const fp of filepaths) {
1490
+ const note = notesMap[fp];
1491
+ if (note && fs.existsSync(fp)) {
1492
+ try {
1493
+ const sharp = require('sharp');
1494
+ const meta = await sharp(fp).metadata();
1495
+ const buf = fs.readFileSync(fp);
1496
+ const annotated = await overlayNoteOnImage(buf, note, meta.width || 800);
1497
+ const tmpPath = path.join(tmpDir, `sb-annotated-${Date.now()}-${path.basename(fp)}`);
1498
+ fs.writeFileSync(tmpPath, annotated);
1499
+ annotatedPaths.push(tmpPath);
1500
+ // Clean up after 2 minutes
1501
+ setTimeout(() => { try {
1502
+ fs.unlinkSync(tmpPath);
1503
+ }
1504
+ catch { } }, 120000);
1505
+ }
1506
+ catch {
1507
+ annotatedPaths.push(fp); // fallback to original
1508
+ }
1509
+ }
1510
+ else {
1511
+ annotatedPaths.push(fp);
1512
+ }
1513
+ }
1514
+ return { paths: annotatedPaths };
1515
+ });
1516
+ electron_1.ipcMain.on('overlay:start-drag', async (event, filepaths, notesMap) => {
1517
+ const validFiles = filepaths.filter((fp) => fs.existsSync(fp));
1518
+ if (validFiles.length === 0)
1519
+ return;
1520
+ const hasNotes = notesMap && Object.values(notesMap).some(Boolean);
1521
+ let dragFiles = validFiles;
1522
+ // Annotate files with note banners if embed is enabled
1523
+ if (hasNotes && (0, store_1.getSetting)('noteEmbedInImage') !== false) {
1524
+ const tmpDir = electron_1.app.getPath('temp');
1525
+ const annotated = [];
1526
+ for (const fp of validFiles) {
1527
+ const note = notesMap[fp];
1528
+ if (note) {
1529
+ try {
1530
+ const sharp = require('sharp');
1531
+ const meta = await sharp(fp).metadata();
1532
+ const buf = fs.readFileSync(fp);
1533
+ const result = await overlayNoteOnImage(buf, note, meta.width || 800);
1534
+ const tmpPath = path.join(tmpDir, `sb-drag-${Date.now()}-${path.basename(fp)}`);
1535
+ fs.writeFileSync(tmpPath, result);
1536
+ annotated.push(tmpPath);
1537
+ setTimeout(() => { try {
1538
+ fs.unlinkSync(tmpPath);
1539
+ }
1540
+ catch { } }, 120000);
1541
+ }
1542
+ catch {
1543
+ annotated.push(fp);
1544
+ }
1545
+ }
1546
+ else {
1547
+ annotated.push(fp);
1548
+ }
1549
+ }
1550
+ dragFiles = annotated;
1551
+ }
1552
+ const icon = electron_1.nativeImage.createFromPath(validFiles[0]).resize({ width: 64, height: 64 });
1553
+ event.sender.startDrag({
1554
+ file: dragFiles[0],
1555
+ files: dragFiles,
1556
+ icon,
1557
+ });
1558
+ const allNotes = hasNotes ? filepaths.map((fp) => notesMap[fp]).filter(Boolean).join('\n\n') : '';
1559
+ logger_1.default.info('[Drag] Started native drag for', dragFiles.length, 'files', allNotes ? '(with notes)' : '');
1560
+ setPendingNotes(allNotes || null);
1561
+ });
1562
+ electron_1.ipcMain.handle('overlay:copy-screenshot', async (_event, filepath, clickPos, noteText) => {
1563
+ try {
1564
+ if (!fs.existsSync(filepath)) {
1565
+ return { success: false, error: 'File not found' };
1566
+ }
1567
+ let image = await loadImageForClipboard(filepath);
1568
+ if (image.isEmpty()) {
1569
+ return { success: false, error: 'Unsupported image format' };
1570
+ }
1571
+ // If click position provided and setting enabled, draw red circle indicator
1572
+ if (clickPos && clickPos.x !== undefined && clickPos.y !== undefined) {
1573
+ const recSettings = (0, store_1.getSetting)('recordingSettings');
1574
+ if (recSettings?.showClickIndicatorInCopy !== false) {
1575
+ image = drawClickIndicator(image, clickPos.x, clickPos.y);
1576
+ }
1577
+ }
1578
+ if (noteText) {
1579
+ const embedEnabled = (0, store_1.getSetting)('noteEmbedInImage') !== false; // default true
1580
+ if (embedEnabled) {
1581
+ try {
1582
+ const pngBuf = image.toPNG();
1583
+ const size = image.getSize();
1584
+ const annotated = await overlayNoteOnImage(pngBuf, noteText, size.width);
1585
+ electron_1.clipboard.write({ image: electron_1.nativeImage.createFromBuffer(annotated), text: noteText });
1586
+ }
1587
+ catch (overlayErr) {
1588
+ logger_1.default.warn('[Copy] Note overlay failed:', overlayErr);
1589
+ electron_1.clipboard.write({ image, text: noteText });
1590
+ }
1591
+ }
1592
+ else {
1593
+ electron_1.clipboard.write({ image, text: noteText });
1594
+ }
1595
+ setPendingNotes(noteText);
1596
+ }
1597
+ else {
1598
+ electron_1.clipboard.writeImage(image);
1599
+ setPendingNotes(null);
1600
+ }
1601
+ return { success: true };
1602
+ }
1603
+ catch (error) {
1604
+ logger_1.default.error('[Copy] copyScreenshot failed:', error);
1605
+ return { success: false, error: String(error) };
1606
+ }
1607
+ });
1608
+ // Copy multiple screenshots as a stitched composite image
1609
+ electron_1.ipcMain.handle('overlay:copy-multiple-screenshots', async (_event, filepaths, notesMap) => {
1610
+ try {
1611
+ // Collect all notes for the selected screenshots
1612
+ const allNotes = notesMap
1613
+ ? filepaths.map((fp) => notesMap[fp]).filter(Boolean).join('\n\n')
1614
+ : '';
1615
+ const embedEnabled = (0, store_1.getSetting)('noteEmbedInImage') !== false;
1616
+ // Helper: write image to clipboard, optionally with note overlay
1617
+ const writeImageWithNotes = async (imgBuf, width, notes) => {
1618
+ if (notes && embedEnabled) {
1619
+ try {
1620
+ const annotated = await overlayNoteOnImage(imgBuf, notes, width);
1621
+ electron_1.clipboard.write({ image: electron_1.nativeImage.createFromBuffer(annotated), text: notes });
1622
+ }
1623
+ catch {
1624
+ electron_1.clipboard.write({ image: electron_1.nativeImage.createFromBuffer(imgBuf), text: notes });
1625
+ }
1626
+ }
1627
+ else if (notes) {
1628
+ electron_1.clipboard.write({ image: electron_1.nativeImage.createFromBuffer(imgBuf), text: notes });
1629
+ }
1630
+ else {
1631
+ electron_1.clipboard.writeImage(electron_1.nativeImage.createFromBuffer(imgBuf));
1632
+ }
1633
+ setPendingNotes(notes || null);
1634
+ };
1635
+ if (filepaths.length === 1) {
1636
+ const image = await loadImageForClipboard(filepaths[0]);
1637
+ const pngBuf = image.toPNG();
1638
+ const size = image.getSize();
1639
+ await writeImageWithNotes(pngBuf, size.width, allNotes);
1640
+ return { success: true };
1641
+ }
1642
+ // Try sharp first (better composite support)
1643
+ try {
1644
+ const sharp = require('sharp');
1645
+ const metas = await Promise.all(filepaths.map(async (fp) => {
1646
+ const meta = await sharp(fp).metadata();
1647
+ return { path: fp, width: meta.width || 200, height: meta.height || 200 };
1648
+ }));
1649
+ const gap = 4;
1650
+ const totalWidth = metas.reduce((sum, m) => sum + m.width, 0) + gap * (metas.length - 1);
1651
+ const maxHeight = Math.max(...metas.map((m) => m.height));
1652
+ const compositeInputs = [];
1653
+ let xOffset = 0;
1654
+ for (const m of metas) {
1655
+ compositeInputs.push({ input: m.path, left: xOffset, top: Math.round((maxHeight - m.height) / 2) });
1656
+ xOffset += m.width + gap;
1657
+ }
1658
+ const compositeBuffer = await sharp({
1659
+ create: { width: totalWidth, height: maxHeight, channels: 4, background: { r: 0, g: 0, b: 0, alpha: 0 } },
1660
+ })
1661
+ .composite(compositeInputs)
1662
+ .png()
1663
+ .toBuffer();
1664
+ await writeImageWithNotes(compositeBuffer, totalWidth, allNotes);
1665
+ return { success: true };
1666
+ }
1667
+ catch (sharpErr) {
1668
+ logger_1.default.warn('[Copy] sharp unavailable for merge, using nativeImage:', sharpErr);
1669
+ }
1670
+ // Fallback: merge using nativeImage raw bitmap stitching
1671
+ const images = filepaths.map((fp) => {
1672
+ const img = electron_1.nativeImage.createFromPath(fp);
1673
+ return { img, size: img.getSize() };
1674
+ });
1675
+ const gap = 4;
1676
+ const totalWidth = images.reduce((sum, { size }) => sum + size.width, 0) + gap * (images.length - 1);
1677
+ const maxHeight = Math.max(...images.map(({ size }) => size.height));
1678
+ // Create merged BGRA bitmap buffer
1679
+ const bytesPerPixel = 4; // BGRA
1680
+ const rowBytes = totalWidth * bytesPerPixel;
1681
+ const mergedBuf = Buffer.alloc(rowBytes * maxHeight, 0); // transparent black
1682
+ let xOffset = 0;
1683
+ for (const { img, size } of images) {
1684
+ const bitmap = img.toBitmap();
1685
+ const srcRowBytes = size.width * bytesPerPixel;
1686
+ const yStart = Math.round((maxHeight - size.height) / 2);
1687
+ for (let row = 0; row < size.height; row++) {
1688
+ const srcStart = row * srcRowBytes;
1689
+ const destStart = (yStart + row) * rowBytes + xOffset * bytesPerPixel;
1690
+ bitmap.copy(mergedBuf, destStart, srcStart, srcStart + srcRowBytes);
1691
+ }
1692
+ xOffset += size.width + gap;
1693
+ }
1694
+ const merged = electron_1.nativeImage.createFromBitmap(mergedBuf, { width: totalWidth, height: maxHeight });
1695
+ const mergedPng = merged.toPNG();
1696
+ if (allNotes) {
1697
+ await writeImageWithNotes(mergedPng, totalWidth, allNotes);
1698
+ }
1699
+ else {
1700
+ electron_1.clipboard.writeImage(merged);
1701
+ setPendingNotes(null);
1702
+ }
1703
+ return { success: true };
1704
+ }
1705
+ catch (error) {
1706
+ logger_1.default.error('[Copy] Merge failed:', error);
1707
+ return { success: false, error: String(error) };
1708
+ }
1709
+ });
1710
+ // Export screenshots to user's folder and copy file paths to clipboard
1711
+ // mode: 'files' = copy as file drop list, 'paths' = copy paths as text
1712
+ electron_1.ipcMain.handle('overlay:export-screenshots', async (_event, data) => {
1713
+ try {
1714
+ const { execSync } = require('child_process');
1715
+ // Step 1: Export/copy files to the user's screenshot folder
1716
+ const exportDir = getCapturesDir();
1717
+ ensureCapturesDir();
1718
+ const exportedPaths = [];
1719
+ for (const fp of data.filepaths) {
1720
+ const basename = path.basename(fp);
1721
+ const destPath = path.join(exportDir, basename);
1722
+ // If already in the target dir, use as-is
1723
+ if (path.normalize(fp) === path.normalize(destPath)) {
1724
+ exportedPaths.push(fp);
1725
+ }
1726
+ else {
1727
+ fs.copyFileSync(fp, destPath);
1728
+ exportedPaths.push(destPath);
1729
+ }
1730
+ }
1731
+ // Write notes text file if any notes exist
1732
+ const notesMap = data.notesMap || {};
1733
+ const allNotes = data.filepaths
1734
+ .map((fp) => notesMap[fp])
1735
+ .filter(Boolean)
1736
+ .join('\n\n');
1737
+ let notesFilePath = null;
1738
+ if (allNotes) {
1739
+ notesFilePath = path.join(exportDir, `notes-${Date.now()}.txt`);
1740
+ fs.writeFileSync(notesFilePath, allNotes, 'utf-8');
1741
+ exportedPaths.push(notesFilePath);
1742
+ logger_1.default.info('[Export] Notes file written:', notesFilePath);
1743
+ }
1744
+ logger_1.default.info(`[Export] ${exportedPaths.length} files to ${exportDir}`);
1745
+ if (data.mode === 'paths') {
1746
+ // Step 2a: Copy paths as text
1747
+ electron_1.clipboard.writeText(exportedPaths.join('\n'));
1748
+ return { success: true, paths: exportedPaths };
1749
+ }
1750
+ // Step 2b: Copy as file drop list
1751
+ if (process.platform === 'win32') {
1752
+ // Windows: Write a .ps1 script, run with exec (async, non-blocking).
1753
+ // exec inherits parent's desktop/window station so clipboard access works.
1754
+ // Script sleeps after setting clipboard so the process stays alive as
1755
+ // clipboard owner long enough for the user to paste.
1756
+ const { exec: execAsync } = require('child_process');
1757
+ const tmpScript = path.join(electron_1.app.getPath('temp'), 'sb-copy-' + Date.now() + '.ps1');
1758
+ const psLines = [
1759
+ 'Add-Type -AssemblyName System.Windows.Forms',
1760
+ ];
1761
+ if (allNotes) {
1762
+ // Use DataObject to set both file list AND text on clipboard simultaneously
1763
+ psLines.push('$data = New-Object System.Windows.Forms.DataObject');
1764
+ psLines.push('$col = New-Object System.Collections.Specialized.StringCollection');
1765
+ // Only add image files to the file drop list (not the notes .txt)
1766
+ for (const fp of exportedPaths) {
1767
+ if (!fp.endsWith('.txt')) {
1768
+ psLines.push(`[void]$col.Add('${fp.replace(/'/g, "''")}')`);
1769
+ }
1770
+ }
1771
+ psLines.push('$data.SetFileDropList($col)');
1772
+ psLines.push(`$data.SetText('${allNotes.replace(/'/g, "''").replace(/\r?\n/g, "`r`n")}')`);
1773
+ psLines.push('[System.Windows.Forms.Clipboard]::SetDataObject($data, $true)');
1774
+ }
1775
+ else {
1776
+ psLines.push('$col = New-Object System.Collections.Specialized.StringCollection');
1777
+ for (const fp of exportedPaths) {
1778
+ psLines.push(`[void]$col.Add('${fp.replace(/'/g, "''")}')`);
1779
+ }
1780
+ psLines.push('[System.Windows.Forms.Clipboard]::SetFileDropList($col)');
1781
+ }
1782
+ psLines.push('Start-Sleep -Seconds 5'); // Keep alive for 5s as clipboard owner
1783
+ fs.writeFileSync(tmpScript, psLines.join('\r\n'), 'utf8');
1784
+ logger_1.default.info('[Export] PS1 script written:', tmpScript);
1785
+ logger_1.default.info('[Export] Paths:', exportedPaths);
1786
+ // exec (not execSync) — runs in background, inherits desktop
1787
+ execAsync(`powershell.exe -NoProfile -STA -ExecutionPolicy Bypass -File "${tmpScript}"`, (err, _stdout, stderr) => {
1788
+ if (err)
1789
+ logger_1.default.error('[Export] PowerShell error:', stderr || err.message);
1790
+ else
1791
+ logger_1.default.info('[Export] PowerShell completed successfully');
1792
+ try {
1793
+ fs.unlinkSync(tmpScript);
1794
+ }
1795
+ catch { }
1796
+ });
1797
+ // Wait for clipboard to be set (PowerShell startup + Add-Type takes ~1s)
1798
+ await new Promise((resolve) => setTimeout(resolve, 1500));
1799
+ logger_1.default.info('[Export] Clipboard should be set for', exportedPaths.length, 'files');
1800
+ }
1801
+ else if (process.platform === 'darwin') {
1802
+ // Use NSPasteboard via AppleScript's ObjC bridge — this is the only
1803
+ // reliable way to set file URLs on the clipboard that macOS apps can paste
1804
+ const urlLines = exportedPaths
1805
+ .map((fp) => `set end of urlList to (current application's |NSURL|'s fileURLWithPath:"${fp}")`)
1806
+ .join('\n');
1807
+ const fullScript = [
1808
+ 'use framework "AppKit"',
1809
+ 'use scripting additions',
1810
+ 'set urlList to {}',
1811
+ urlLines,
1812
+ 'set pb to current application\'s NSPasteboard\'s generalPasteboard()',
1813
+ 'pb\'s clearContents()',
1814
+ 'pb\'s writeObjects:urlList',
1815
+ ].join('\n');
1816
+ const tmpScpt = path.join(electron_1.app.getPath('temp'), 'sb-copy.applescript');
1817
+ fs.writeFileSync(tmpScpt, fullScript, 'utf-8');
1818
+ logger_1.default.info('[Export] AppleScript (NSPasteboard):', fullScript);
1819
+ execSync(`osascript "${tmpScpt}"`);
1820
+ try {
1821
+ fs.unlinkSync(tmpScpt);
1822
+ }
1823
+ catch { }
1824
+ }
1825
+ else {
1826
+ const uriList = exportedPaths.map((fp) => `file://${fp}`).join('\n');
1827
+ execSync(`echo -n "${uriList}" | xclip -selection clipboard -t text/uri-list`);
1828
+ }
1829
+ // Register global shortcut for pasting notes
1830
+ setPendingNotes(allNotes || null);
1831
+ return { success: true, paths: exportedPaths };
1832
+ }
1833
+ catch (error) {
1834
+ logger_1.default.error('[Export] Failed:', error);
1835
+ return { success: false, error: String(error) };
1836
+ }
1837
+ });
1838
+ electron_1.ipcMain.handle('overlay:copy-text', async (_event, text) => {
1839
+ try {
1840
+ electron_1.clipboard.writeText(text);
1841
+ return { success: true };
1842
+ }
1843
+ catch (error) {
1844
+ return { success: false, error: String(error) };
1845
+ }
1846
+ });
1847
+ electron_1.ipcMain.handle('overlay:hide', async () => {
1848
+ if (overlayWindow && !overlayWindow.isDestroyed()) {
1849
+ overlayWindow.close();
1850
+ }
1851
+ return { success: true };
1852
+ });
1853
+ // Overlay pin toggle
1854
+ electron_1.ipcMain.handle('overlay:pin', async () => {
1855
+ overlayPinned = !overlayPinned;
1856
+ return { success: true, pinned: overlayPinned };
1857
+ });
1858
+ // Overlay minimize to PIP
1859
+ electron_1.ipcMain.handle('overlay:minimize-pip', async () => {
1860
+ if (overlayWindow && !overlayWindow.isDestroyed()) {
1861
+ const bounds = overlayWindow.getBounds();
1862
+ overlayOriginalBounds = { width: bounds.width, height: bounds.height, x: bounds.x, y: bounds.y };
1863
+ overlayWindow.setBounds({ x: bounds.x, y: bounds.y, width: 120, height: 40 });
1864
+ overlayWindow.setResizable(false);
1865
+ }
1866
+ return { success: true };
1867
+ });
1868
+ // Overlay restore from PIP
1869
+ electron_1.ipcMain.handle('overlay:restore-pip', async () => {
1870
+ if (overlayWindow && !overlayWindow.isDestroyed() && overlayOriginalBounds) {
1871
+ overlayWindow.setBounds(overlayOriginalBounds);
1872
+ overlayWindow.setResizable(true);
1873
+ overlayOriginalBounds = null;
1874
+ }
1875
+ return { success: true };
1876
+ });
1877
+ // Dock overlay to screen edge
1878
+ electron_1.ipcMain.handle('overlay:dock', async (_event, side) => {
1879
+ if (!overlayWindow || overlayWindow.isDestroyed())
1880
+ return { success: false };
1881
+ const primaryDisplay = electron_1.screen.getPrimaryDisplay();
1882
+ const { width: screenW, height: screenH } = primaryDisplay.size;
1883
+ const dockWidth = 420;
1884
+ if (side === 'undock') {
1885
+ // Restore saved bounds or center
1886
+ const saved = (0, store_1.getSetting)('overlayBounds');
1887
+ if (saved) {
1888
+ overlayWindow.setBounds(saved);
1889
+ }
1890
+ else {
1891
+ overlayWindow.setBounds({ x: Math.round(screenW / 2 - 260), y: 40, width: 520, height: 560 });
1892
+ }
1893
+ }
1894
+ else {
1895
+ const x = side === 'left' ? 0 : screenW - dockWidth;
1896
+ overlayWindow.setBounds({ x, y: 0, width: dockWidth, height: screenH });
1897
+ }
1898
+ return { success: true, side };
1899
+ });
1900
+ // Pin to desktop
1901
+ electron_1.ipcMain.handle('capture:pin-to-desktop', async (_event, imagePath) => {
1902
+ (0, pin_window_1.pinToDesktop)(imagePath);
1903
+ return { success: true };
1904
+ });
1905
+ // Auto-redact an image on disk (manual trigger from renderer)
1906
+ electron_1.ipcMain.handle('redact:auto-redact', async (_event, data) => {
1907
+ try {
1908
+ if (!isPathSafe(data.imagePath))
1909
+ return { success: false, error: 'Invalid path' };
1910
+ const imageBuffer = fs.readFileSync(data.imagePath);
1911
+ const result = await (0, redact_1.autoRedact)(imageBuffer, { secrets: data.secrets, pii: data.pii });
1912
+ if (result.regionsFound > 0) {
1913
+ fs.writeFileSync(data.imagePath, result.buffer);
1914
+ }
1915
+ return { success: true, regionsFound: result.regionsFound };
1916
+ }
1917
+ catch (err) {
1918
+ logger_1.default.error('[Redact] Manual redact failed:', err);
1919
+ return { success: false, error: String(err) };
1920
+ }
1921
+ });
1922
+ // Export as different formats
1923
+ electron_1.ipcMain.handle('capture:export-format', async (_event, data) => {
1924
+ try {
1925
+ if (!isPathSafe(data.imagePath)) {
1926
+ return { success: false, error: 'Invalid file path' };
1927
+ }
1928
+ const sharp = require('sharp');
1929
+ const buf = fs.readFileSync(data.imagePath);
1930
+ const outputPath = data.imagePath.replace(/\.png$/i, `.${data.format}`);
1931
+ if (data.format === 'jpeg') {
1932
+ await sharp(buf).jpeg({ quality: data.quality }).toFile(outputPath);
1933
+ }
1934
+ else {
1935
+ await sharp(buf).webp({ quality: data.quality }).toFile(outputPath);
1936
+ }
1937
+ return { success: true, outputPath };
1938
+ }
1939
+ catch (err) {
1940
+ return { success: false, error: err.message };
1941
+ }
1942
+ });
1943
+ // Share: Imgur anonymous upload
1944
+ electron_1.ipcMain.handle('share:imgur-upload', async (_event, imagePath) => {
1945
+ try {
1946
+ if (!isPathSafe(imagePath)) {
1947
+ return { success: false, error: 'Invalid file path' };
1948
+ }
1949
+ const imageBuffer = fs.readFileSync(imagePath);
1950
+ const base64 = imageBuffer.toString('base64');
1951
+ const https = require('https');
1952
+ const result = await new Promise((resolve, reject) => {
1953
+ const postData = JSON.stringify({ image: base64, type: 'base64' });
1954
+ const req = https.request({
1955
+ hostname: 'api.imgur.com',
1956
+ path: '/3/image',
1957
+ method: 'POST',
1958
+ headers: {
1959
+ Authorization: 'Client-ID 546c25a59c58ad7',
1960
+ 'Content-Type': 'application/json',
1961
+ 'Content-Length': Buffer.byteLength(postData),
1962
+ },
1963
+ }, (res) => {
1964
+ let body = '';
1965
+ res.on('data', (chunk) => {
1966
+ body += chunk;
1967
+ });
1968
+ res.on('end', () => {
1969
+ try {
1970
+ const json = JSON.parse(body);
1971
+ if (json.success) {
1972
+ resolve({ url: json.data.link, deleteHash: json.data.deletehash });
1973
+ }
1974
+ else {
1975
+ reject(new Error(json.data?.error || 'Upload failed'));
1976
+ }
1977
+ }
1978
+ catch {
1979
+ reject(new Error('Invalid response'));
1980
+ }
1981
+ });
1982
+ });
1983
+ req.on('error', reject);
1984
+ req.write(postData);
1985
+ req.end();
1986
+ });
1987
+ // Copy URL to clipboard
1988
+ electron_1.clipboard.writeText(result.url);
1989
+ return { success: true, url: result.url };
1990
+ }
1991
+ catch (err) {
1992
+ return { success: false, error: err instanceof Error ? err.message : String(err) };
1993
+ }
1994
+ });
1995
+ // Share: System share dialog (Windows)
1996
+ electron_1.ipcMain.handle('share:system', async (_event, imagePath) => {
1997
+ try {
1998
+ if (!isPathSafe(imagePath)) {
1999
+ return { success: false, error: 'Invalid file path' };
2000
+ }
2001
+ const { shell } = require('electron');
2002
+ // On Windows, open the file with the system "Share" action
2003
+ await shell.openPath(imagePath);
2004
+ return { success: true };
2005
+ }
2006
+ catch (err) {
2007
+ return { success: false, error: err instanceof Error ? err.message : String(err) };
2008
+ }
2009
+ });
2010
+ // Thumbnail cache: generate 256px thumbnails for gallery
2011
+ // thumbnailCache is declared at module level above
2012
+ electron_1.ipcMain.handle('capture:get-thumbnail', async (_event, imagePath) => {
2013
+ if (thumbnailCache.has(imagePath)) {
2014
+ return { success: true, dataUrl: thumbnailCache.get(imagePath) };
2015
+ }
2016
+ try {
2017
+ const sharp = require('sharp');
2018
+ const buf = await sharp(imagePath).resize(256, 256, { fit: 'inside' }).png({ quality: 60 }).toBuffer();
2019
+ const dataUrl = `data:image/png;base64,${buf.toString('base64')}`;
2020
+ thumbnailCache.set(imagePath, dataUrl);
2021
+ return { success: true, dataUrl };
2022
+ }
2023
+ catch {
2024
+ return { success: false };
2025
+ }
2026
+ });
2027
+ // PDF export
2028
+ electron_1.ipcMain.handle('capture:export-pdf', async (_event, data) => {
2029
+ try {
2030
+ if (!isPathSafe(data.imagePath)) {
2031
+ return { success: false, error: 'Invalid file path' };
2032
+ }
2033
+ const PDFDocument = require('pdfkit');
2034
+ const outputPath = data.imagePath.replace(/\.png$/i, '.pdf');
2035
+ return new Promise((resolve) => {
2036
+ const doc = new PDFDocument({ autoFirstPage: false });
2037
+ const stream = fs.createWriteStream(outputPath);
2038
+ doc.pipe(stream);
2039
+ // Get image dimensions
2040
+ const sharp = require('sharp');
2041
+ sharp(data.imagePath)
2042
+ .metadata()
2043
+ .then((meta) => {
2044
+ const imgW = meta.width || 800;
2045
+ const imgH = meta.height || 600;
2046
+ const pageW = 612; // Letter width in points
2047
+ const margin = 36;
2048
+ const contentW = pageW - margin * 2;
2049
+ const scale = Math.min(1, contentW / imgW);
2050
+ const displayW = imgW * scale;
2051
+ const displayH = imgH * scale;
2052
+ // Calculate page height needed
2053
+ const textHeight = data.aiResponse ? Math.ceil(data.aiResponse.length / 80) * 14 + 40 : 0;
2054
+ const pageH = Math.max(792, displayH + textHeight + margin * 3);
2055
+ doc.addPage({ size: [pageW, pageH], margin });
2056
+ // Title
2057
+ doc
2058
+ .fontSize(10)
2059
+ .fillColor('#666')
2060
+ .text(`SuperBased Capture — ${new Date().toLocaleString()}`, margin, margin);
2061
+ // Image
2062
+ doc.image(data.imagePath, margin, margin + 20, { width: displayW });
2063
+ // AI response
2064
+ if (data.aiResponse) {
2065
+ const textY = margin + 20 + displayH + 20;
2066
+ doc.fontSize(9).fillColor('#999').text('AI Response:', margin, textY);
2067
+ doc
2068
+ .fontSize(11)
2069
+ .fillColor('#333')
2070
+ .text(data.aiResponse, margin, textY + 14, {
2071
+ width: contentW,
2072
+ lineGap: 3,
2073
+ });
2074
+ }
2075
+ doc.end();
2076
+ stream.on('finish', () => resolve({ success: true, outputPath }));
2077
+ stream.on('error', (err) => resolve({ success: false, error: err.message }));
2078
+ })
2079
+ .catch((err) => resolve({ success: false, error: err.message }));
2080
+ });
2081
+ }
2082
+ catch (err) {
2083
+ return { success: false, error: err instanceof Error ? err.message : String(err) };
2084
+ }
2085
+ });
2086
+ // Updater
2087
+ electron_1.ipcMain.handle('updater:check', async () => {
2088
+ try {
2089
+ await (0, updater_1.checkForUpdates)();
2090
+ return { success: true };
2091
+ }
2092
+ catch (error) {
2093
+ return { success: false, error: String(error) };
2094
+ }
2095
+ });
2096
+ electron_1.ipcMain.handle('updater:install', async () => {
2097
+ (0, updater_1.installUpdate)();
2098
+ return { success: true };
2099
+ });
2100
+ // Settings operations
2101
+ electron_1.ipcMain.handle('settings:get-all', async () => {
2102
+ return { ...(0, store_1.getAllSettings)(), appVersion: electron_1.app.getVersion() };
2103
+ });
2104
+ // AI provider/model/key settings are managed via admin console only — not exposed to renderer
2105
+ electron_1.ipcMain.handle('settings:open', async () => {
2106
+ openMainPanelSettings();
2107
+ return { success: true };
2108
+ });
2109
+ // Database operations
2110
+ electron_1.ipcMain.handle('db:get-captures', async (_event, limit) => {
2111
+ return (0, database_1.getCaptures)(limit);
2112
+ });
2113
+ electron_1.ipcMain.handle('db:get-capture', async (_event, id) => {
2114
+ return (0, database_1.getCapture)(id);
2115
+ });
2116
+ electron_1.ipcMain.handle('db:search-captures', async (_event, query) => {
2117
+ return (0, database_1.searchCaptures)(query);
2118
+ });
2119
+ electron_1.ipcMain.handle('db:update-tags', async (_event, data) => {
2120
+ (0, database_1.updateCaptureTags)(data.id, data.tags);
2121
+ return { success: true };
2122
+ });
2123
+ electron_1.ipcMain.handle('db:update-notes', async (_event, data) => {
2124
+ (0, database_1.updateCaptureNotes)(data.id, data.notes);
2125
+ return { success: true };
2126
+ });
2127
+ electron_1.ipcMain.handle('db:get-stats', async () => {
2128
+ return (0, database_1.getCaptureStats)();
2129
+ });
2130
+ // ── Analytics ──
2131
+ electron_1.ipcMain.handle('analytics:get-summary', async () => {
2132
+ const { getAnalyticsSummary } = await Promise.resolve().then(() => __importStar(require('./db/database')));
2133
+ return getAnalyticsSummary();
2134
+ });
2135
+ electron_1.ipcMain.handle('analytics:get-summary-range', async (_event, startDate, endDate) => {
2136
+ const { getAnalyticsSummaryRange } = await Promise.resolve().then(() => __importStar(require('./db/database')));
2137
+ return getAnalyticsSummaryRange(startDate, endDate);
2138
+ });
2139
+ electron_1.ipcMain.handle('analytics:get-trend', async (_event, eventType, granularity, count) => {
2140
+ const db = await Promise.resolve().then(() => __importStar(require('./db/database')));
2141
+ switch (granularity) {
2142
+ case 'hourly': return db.getHourlyTrend(eventType, count);
2143
+ case 'daily': return db.getDailyTrend(eventType, count);
2144
+ case 'weekly': return db.getWeeklyTrend(eventType, count);
2145
+ case 'monthly': return db.getMonthlyTrend(eventType, count);
2146
+ default: return db.getDailyTrend(eventType, count);
2147
+ }
2148
+ });
2149
+ electron_1.ipcMain.handle('analytics:get-top', async (_event, eventType, startDate, endDate, limit) => {
2150
+ const { getAnalyticsTopValues } = await Promise.resolve().then(() => __importStar(require('./db/database')));
2151
+ return getAnalyticsTopValues(eventType, startDate, endDate, limit);
2152
+ });
2153
+ // ── Token Compression Engine ──
2154
+ electron_1.ipcMain.handle('tce:quick-analyze', async (_event, text, settings) => {
2155
+ const { quickAnalyze } = await Promise.resolve().then(() => __importStar(require('./modules/tce')));
2156
+ return quickAnalyze(text, settings);
2157
+ });
2158
+ electron_1.ipcMain.handle('tce:compress', async (_event, text, settings) => {
2159
+ const { compressText } = await Promise.resolve().then(() => __importStar(require('./modules/tce')));
2160
+ const result = await compressText(text, settings);
2161
+ // Convert buffers to base64 for IPC transfer
2162
+ return {
2163
+ pages: result.pages.map((p) => ({
2164
+ pageNumber: p.pageNumber,
2165
+ totalPages: p.totalPages,
2166
+ imageTokens: p.imageTokens,
2167
+ lineRange: p.lineRange,
2168
+ base64: p.buffer.toString('base64'),
2169
+ })),
2170
+ metadata: result.metadata,
2171
+ };
2172
+ });
2173
+ // Preset operations
2174
+ electron_1.ipcMain.handle('presets:get-all', async () => {
2175
+ return (0, database_1.getPresets)();
2176
+ });
2177
+ electron_1.ipcMain.handle('presets:create', async (_event, data) => {
2178
+ const id = (0, database_1.createPreset)(data);
2179
+ return { success: true, id };
2180
+ });
2181
+ electron_1.ipcMain.handle('presets:update', async (_event, data) => {
2182
+ (0, database_1.updatePreset)(data);
2183
+ return { success: true };
2184
+ });
2185
+ electron_1.ipcMain.handle('presets:delete', async (_event, id) => {
2186
+ (0, database_1.deletePreset)(id);
2187
+ return { success: true };
2188
+ });
2189
+ // Gallery
2190
+ electron_1.ipcMain.handle('gallery:open', async () => {
2191
+ createGalleryWindow();
2192
+ return { success: true };
2193
+ });
2194
+ electron_1.ipcMain.handle('capture:start-region', async () => {
2195
+ createSelectionWindow();
2196
+ return { success: true };
2197
+ });
2198
+ // Re-process: open overlay with existing capture
2199
+ electron_1.ipcMain.handle('capture:reprocess', async (_event, captureId) => {
2200
+ const capture = (0, database_1.getCapture)(captureId);
2201
+ if (!capture)
2202
+ return { success: false, error: 'Capture not found' };
2203
+ const region = {
2204
+ x: capture.region_x,
2205
+ y: capture.region_y,
2206
+ width: capture.region_w,
2207
+ height: capture.region_h,
2208
+ };
2209
+ createOverlayWindow({
2210
+ screenshotPath: capture.screenshot_path,
2211
+ captureId,
2212
+ hasApiKey: (0, auth_1.isAuthenticated)(),
2213
+ voiceMode: false,
2214
+ inlineEditMode: false,
2215
+ originalText: null,
2216
+ multiRegion: false,
2217
+ regionScreenshots: [],
2218
+ }, region);
2219
+ return { success: true };
2220
+ });
2221
+ // View: open editor in a separate window for a screenshot
2222
+ electron_1.ipcMain.handle('capture:view', async (_event, screenshotPath, clickPos, siblingPaths) => {
2223
+ logger_1.default.info('[Editor] capture:view called, path:', screenshotPath, 'clickPos:', clickPos);
2224
+ if (!isPathSafe(screenshotPath)) {
2225
+ logger_1.default.warn('[Editor] capture:view path rejected by isPathSafe:', screenshotPath);
2226
+ return { success: false, error: 'Invalid path' };
2227
+ }
2228
+ // If click position provided and setting enabled, create temp file with indicator baked in
2229
+ let pathForEditor = screenshotPath;
2230
+ if (clickPos && clickPos.x !== undefined && clickPos.y !== undefined) {
2231
+ const recSettings = (0, store_1.getSetting)('recordingSettings');
2232
+ if (recSettings?.showClickIndicatorInCopy !== false) {
2233
+ try {
2234
+ let image = await loadImageForClipboard(screenshotPath);
2235
+ if (!image.isEmpty()) {
2236
+ image = drawClickIndicator(image, clickPos.x, clickPos.y);
2237
+ const tmpDir = path.join(electron_1.app.getPath('temp'), 'superbased-editor');
2238
+ if (!fs.existsSync(tmpDir))
2239
+ fs.mkdirSync(tmpDir, { recursive: true });
2240
+ const tmpPath = path.join(tmpDir, `click_${Date.now()}.png`);
2241
+ fs.writeFileSync(tmpPath, image.toPNG());
2242
+ pathForEditor = tmpPath;
2243
+ }
2244
+ }
2245
+ catch (err) {
2246
+ logger_1.default.warn('[Editor] Failed to draw click indicator:', err);
2247
+ }
2248
+ }
2249
+ }
2250
+ const editorWin = new electron_1.BrowserWindow({
2251
+ width: 900,
2252
+ height: 650,
2253
+ ...framelessWindowOptions(),
2254
+ webPreferences: {
2255
+ preload: path.join(__dirname, 'preload.js'),
2256
+ contextIsolation: true,
2257
+ nodeIntegration: false,
2258
+ navigateOnDragDrop: false,
2259
+ },
2260
+ });
2261
+ makeWindowFocusAware(editorWin);
2262
+ attachCrashHandlers(editorWin, 'editor');
2263
+ editorWin.loadFile(path.join(__dirname, '../renderer/editor.html'));
2264
+ editorWin.webContents.on('did-finish-load', () => {
2265
+ logger_1.default.info('[Editor] Sending init: display=', pathForEditor, 'savePath=', screenshotPath);
2266
+ editorWin.webContents.send('overlay:init', {
2267
+ screenshotPath: pathForEditor,
2268
+ savePath: screenshotPath,
2269
+ siblingPaths: siblingPaths || [],
2270
+ });
2271
+ });
2272
+ // Clean up temp file when editor closes
2273
+ if (pathForEditor !== screenshotPath) {
2274
+ editorWin.on('closed', () => {
2275
+ try {
2276
+ fs.unlinkSync(pathForEditor);
2277
+ }
2278
+ catch { /* already cleaned */ }
2279
+ });
2280
+ }
2281
+ return { success: true };
2282
+ });
2283
+ // Onboarding
2284
+ electron_1.ipcMain.handle('window:close-current', async (event) => {
2285
+ const win = electron_1.BrowserWindow.fromWebContents(event.sender);
2286
+ if (win && !win.isDestroyed())
2287
+ win.close();
2288
+ return { success: true };
2289
+ });
2290
+ electron_1.ipcMain.handle('window:minimize', async (event) => {
2291
+ const win = electron_1.BrowserWindow.fromWebContents(event.sender);
2292
+ if (win && !win.isDestroyed())
2293
+ win.minimize();
2294
+ return { success: true };
2295
+ });
2296
+ electron_1.ipcMain.handle('window:maximize', async (event) => {
2297
+ const win = electron_1.BrowserWindow.fromWebContents(event.sender);
2298
+ if (win && !win.isDestroyed()) {
2299
+ if (win.isMaximized()) {
2300
+ win.unmaximize();
2301
+ }
2302
+ else {
2303
+ win.maximize();
2304
+ }
2305
+ }
2306
+ return { success: true };
2307
+ });
2308
+ electron_1.ipcMain.handle('onboarding:complete', async () => {
2309
+ (0, store_1.setSetting)('onboardingComplete', true);
2310
+ if (onboardingWindow && !onboardingWindow.isDestroyed()) {
2311
+ onboardingWindow.close();
2312
+ }
2313
+ return { success: true };
2314
+ });
2315
+ // ── Auth ──
2316
+ electron_1.ipcMain.handle('auth:get-state', async () => {
2317
+ const state = (0, auth_1.getAuthState)();
2318
+ return {
2319
+ isAuthenticated: (0, auth_1.isAuthenticated)(),
2320
+ email: state.email,
2321
+ name: state.name,
2322
+ plan: state.plan,
2323
+ userId: state.userId,
2324
+ };
2325
+ });
2326
+ electron_1.ipcMain.handle('auth:sign-in', async () => {
2327
+ (0, auth_1.openSignIn)();
2328
+ return { success: true };
2329
+ });
2330
+ electron_1.ipcMain.handle('auth:sign-out', async () => {
2331
+ (0, auth_1.signOut)();
2332
+ // Notify all windows of sign-out
2333
+ for (const win of electron_1.BrowserWindow.getAllWindows()) {
2334
+ if (!win.isDestroyed()) {
2335
+ win.webContents.send('auth:state-changed', {
2336
+ isAuthenticated: false,
2337
+ ...(0, auth_1.getAuthState)(),
2338
+ });
2339
+ }
2340
+ }
2341
+ return { success: true };
2342
+ });
2343
+ // ── Recording Feature (V3) — lazy-loaded IPC handlers ──
2344
+ let recordingModule = null;
2345
+ // Allow auto-restore on startup to set the recording module reference
2346
+ /** Set up frame broadcast so recording-session.ts can notify all windows */
2347
+ function wireFrameBroadcast(mod) {
2348
+ const sessionMod = mod.getSessionModule();
2349
+ if (sessionMod) {
2350
+ sessionMod.setFrameBroadcast((data) => {
2351
+ for (const win of electron_1.BrowserWindow.getAllWindows()) {
2352
+ if (!win.isDestroyed()) {
2353
+ win.webContents.send('recording:new-frame', data);
2354
+ }
2355
+ }
2356
+ });
2357
+ }
2358
+ }
2359
+ electron_1.ipcMain.on('recording-module-restored', (_event, mod) => {
2360
+ recordingModule = mod;
2361
+ registerRecordingShortcuts();
2362
+ (0, tray_1.updateTrayRecordingState)(true, false);
2363
+ wireFrameBroadcast(mod);
2364
+ logger_1.default.info('[Recording] Module reference set from auto-restore');
2365
+ });
2366
+ // ── Recording shortcut helpers ──
2367
+ function registerRecordingShortcuts() {
2368
+ const recSettings = (0, store_1.getSetting)('recordingSettings');
2369
+ const shortcuts = recSettings?.shortcuts || {
2370
+ toggleRecord: 'CommandOrControl+Shift+R',
2371
+ pauseResume: 'CommandOrControl+Shift+P',
2372
+ manualCapture: 'CommandOrControl+Shift+M',
2373
+ };
2374
+ // Toggle start/stop recording
2375
+ if (shortcuts.toggleRecord) {
2376
+ const ok = electron_1.globalShortcut.register(shortcuts.toggleRecord, async () => {
2377
+ if (!recordingModule)
2378
+ return;
2379
+ const sessionMod = recordingModule.getSessionModule();
2380
+ if (!sessionMod)
2381
+ return;
2382
+ const session = sessionMod.getCurrentSession();
2383
+ if (session && session.status !== 'completed' && session.status !== 'aborted') {
2384
+ const sessionId = session.id;
2385
+ await sessionMod.stopCurrentSession();
2386
+ notifyRecordingStatusChange();
2387
+ closeRecordingBarWindow();
2388
+ createTimelineWindow(sessionId);
2389
+ }
2390
+ else {
2391
+ const rs = (0, store_1.getSetting)('recordingSettings');
2392
+ await sessionMod.startSession({
2393
+ name: `Recording ${new Date().toLocaleString()}`,
2394
+ profile: (rs?.defaultProfile || 'automated_test'),
2395
+ scope: 'all',
2396
+ showInGallery: rs?.showInGallery !== false,
2397
+ });
2398
+ notifyRecordingStatusChange();
2399
+ }
2400
+ });
2401
+ if (ok)
2402
+ logger_1.default.info(`[Recording] Shortcut registered: ${shortcuts.toggleRecord} (toggle)`);
2403
+ }
2404
+ // Pause/resume
2405
+ if (shortcuts.pauseResume) {
2406
+ const ok = electron_1.globalShortcut.register(shortcuts.pauseResume, async () => {
2407
+ if (!recordingModule)
2408
+ return;
2409
+ const sessionMod = recordingModule.getSessionModule();
2410
+ if (!sessionMod)
2411
+ return;
2412
+ const session = sessionMod.getCurrentSession();
2413
+ if (!session)
2414
+ return;
2415
+ if (session.status === 'paused') {
2416
+ await sessionMod.resumeCurrentSession();
2417
+ }
2418
+ else if (session.status === 'recording') {
2419
+ await sessionMod.pauseCurrentSession();
2420
+ }
2421
+ notifyRecordingStatusChange();
2422
+ });
2423
+ if (ok)
2424
+ logger_1.default.info(`[Recording] Shortcut registered: ${shortcuts.pauseResume} (pause/resume)`);
2425
+ }
2426
+ // Manual capture marker
2427
+ if (shortcuts.manualCapture) {
2428
+ const ok = electron_1.globalShortcut.register(shortcuts.manualCapture, () => {
2429
+ if (!recordingModule)
2430
+ return;
2431
+ const sessionMod = recordingModule.getSessionModule();
2432
+ if (!sessionMod)
2433
+ return;
2434
+ sessionMod.triggerManualCapture();
2435
+ });
2436
+ if (ok)
2437
+ logger_1.default.info(`[Recording] Shortcut registered: ${shortcuts.manualCapture} (manual capture)`);
2438
+ }
2439
+ }
2440
+ function unregisterRecordingShortcuts() {
2441
+ const recSettings = (0, store_1.getSetting)('recordingSettings');
2442
+ const shortcuts = recSettings?.shortcuts || {
2443
+ toggleRecord: 'CommandOrControl+Shift+R',
2444
+ pauseResume: 'CommandOrControl+Shift+P',
2445
+ manualCapture: 'CommandOrControl+Shift+M',
2446
+ };
2447
+ if (shortcuts.toggleRecord)
2448
+ try {
2449
+ electron_1.globalShortcut.unregister(shortcuts.toggleRecord);
2450
+ }
2451
+ catch { }
2452
+ if (shortcuts.pauseResume)
2453
+ try {
2454
+ electron_1.globalShortcut.unregister(shortcuts.pauseResume);
2455
+ }
2456
+ catch { }
2457
+ if (shortcuts.manualCapture)
2458
+ try {
2459
+ electron_1.globalShortcut.unregister(shortcuts.manualCapture);
2460
+ }
2461
+ catch { }
2462
+ }
2463
+ /** Broadcast recording status to all windows + manage bar/timeline windows */
2464
+ function notifyRecordingStatusChange() {
2465
+ logger_1.default.info('[Recording] notifyRecordingStatusChange called');
2466
+ if (!recordingModule)
2467
+ return;
2468
+ const sessionMod = recordingModule.getSessionModule();
2469
+ const session = sessionMod?.getCurrentSession();
2470
+ const data = session
2471
+ ? {
2472
+ status: session.status,
2473
+ sessionId: session.id,
2474
+ frameCount: session.frameCount,
2475
+ duration: Date.now() - session.startedAt,
2476
+ }
2477
+ : { status: 'idle' };
2478
+ for (const win of electron_1.BrowserWindow.getAllWindows()) {
2479
+ if (!win.isDestroyed()) {
2480
+ win.webContents.send('recording:status-change', data);
2481
+ }
2482
+ }
2483
+ // Update tray menu
2484
+ (0, tray_1.updateTrayRecordingState)(true, !!session && session.status === 'recording', !!session && session.status === 'paused');
2485
+ // Manage recording bar window
2486
+ if (session && (session.status === 'recording' || session.status === 'paused')) {
2487
+ // Open bar if not already open
2488
+ if (!recordingBarWindow || recordingBarWindow.isDestroyed()) {
2489
+ createRecordingBarWindow();
2490
+ }
2491
+ }
2492
+ else {
2493
+ // Close bar when stopped/idle
2494
+ closeRecordingBarWindow();
2495
+ }
2496
+ }
2497
+ // Track last completed session for auto-opening timeline (module-scope via closure)
2498
+ electron_1.ipcMain.handle('recording:enable-feature', async () => {
2499
+ try {
2500
+ recordingModule = await Promise.resolve().then(() => __importStar(require('./modules/recording')));
2501
+ const result = await recordingModule.initialize();
2502
+ if (result.success) {
2503
+ (0, store_1.setSetting)('recordingFeatureEnabled', true);
2504
+ registerRecordingShortcuts();
2505
+ wireFrameBroadcast(recordingModule);
2506
+ // Register recording routes on the API server
2507
+ Promise.resolve().then(() => __importStar(require('./modules/api-server'))).then((apiMod) => apiMod.registerRecordingRoutesOnServer())
2508
+ .catch(() => { });
2509
+ }
2510
+ return { success: result.success, providerType: result.providerType, fallbackReason: result.fallbackReason };
2511
+ }
2512
+ catch (err) {
2513
+ return { success: false, error: err instanceof Error ? err.message : String(err) };
2514
+ }
2515
+ });
2516
+ electron_1.ipcMain.handle('recording:disable-feature', async () => {
2517
+ try {
2518
+ unregisterRecordingShortcuts();
2519
+ if (recordingModule) {
2520
+ await recordingModule.teardown();
2521
+ recordingModule = null;
2522
+ }
2523
+ (0, store_1.setSetting)('recordingFeatureEnabled', false);
2524
+ (0, tray_1.updateTrayRecordingState)(false, false);
2525
+ return { success: true };
2526
+ }
2527
+ catch (err) {
2528
+ return { success: false, error: err instanceof Error ? err.message : String(err) };
2529
+ }
2530
+ });
2531
+ electron_1.ipcMain.handle('recording:start', async (_event, options) => {
2532
+ if (!recordingModule)
2533
+ return { success: false, error: 'Recording feature not enabled' };
2534
+ const sessionMod = recordingModule.getSessionModule();
2535
+ if (!sessionMod)
2536
+ return { success: false, error: 'Session module not loaded' };
2537
+ const session = await sessionMod.startSession(options);
2538
+ notifyRecordingStatusChange();
2539
+ return { sessionId: session.id, status: session.status };
2540
+ });
2541
+ electron_1.ipcMain.handle('recording:stop', async () => {
2542
+ if (!recordingModule)
2543
+ return { success: false, error: 'Recording feature not enabled' };
2544
+ const sessionMod = recordingModule.getSessionModule();
2545
+ if (!sessionMod)
2546
+ return { success: false, error: 'Session module not loaded' };
2547
+ const session = await sessionMod.stopCurrentSession();
2548
+ if (!session)
2549
+ return { success: false, error: 'No active recording session' };
2550
+ notifyRecordingStatusChange();
2551
+ closeRecordingBarWindow();
2552
+ createTimelineWindow(session.id);
2553
+ // Track recording analytics
2554
+ const duration = Date.now() - session.startedAt;
2555
+ (0, database_1.trackAnalytics)('recording', 'session', 1, duration, '');
2556
+ (0, database_1.trackAnalytics)('recording', 'frames', session.frameCount, 0, '');
2557
+ return {
2558
+ sessionId: session.id,
2559
+ status: session.status,
2560
+ frameCount: session.frameCount,
2561
+ duration,
2562
+ };
2563
+ });
2564
+ electron_1.ipcMain.handle('recording:pause', async () => {
2565
+ if (!recordingModule)
2566
+ return { success: false, error: 'Recording feature not enabled' };
2567
+ const sessionMod = recordingModule.getSessionModule();
2568
+ if (!sessionMod)
2569
+ return { success: false, error: 'Session module not loaded' };
2570
+ await sessionMod.pauseCurrentSession();
2571
+ notifyRecordingStatusChange();
2572
+ return { success: true };
2573
+ });
2574
+ electron_1.ipcMain.handle('recording:resume', async () => {
2575
+ if (!recordingModule)
2576
+ return { success: false, error: 'Recording feature not enabled' };
2577
+ const sessionMod = recordingModule.getSessionModule();
2578
+ if (!sessionMod)
2579
+ return { success: false, error: 'Session module not loaded' };
2580
+ await sessionMod.resumeCurrentSession();
2581
+ notifyRecordingStatusChange();
2582
+ return { success: true };
2583
+ });
2584
+ electron_1.ipcMain.handle('recording:status', async () => {
2585
+ if (!recordingModule)
2586
+ return { status: 'idle' };
2587
+ const sessionMod = recordingModule.getSessionModule();
2588
+ if (!sessionMod)
2589
+ return { status: 'idle' };
2590
+ const session = sessionMod.getCurrentSession();
2591
+ if (!session)
2592
+ return { status: 'idle' };
2593
+ return {
2594
+ status: session.status,
2595
+ sessionId: session.id,
2596
+ frameCount: session.frameCount,
2597
+ duration: Date.now() - session.startedAt,
2598
+ };
2599
+ });
2600
+ electron_1.ipcMain.handle('recording:get-sessions', async () => {
2601
+ const { getRecordingSessions } = await Promise.resolve().then(() => __importStar(require('./db/database')));
2602
+ return getRecordingSessions();
2603
+ });
2604
+ electron_1.ipcMain.handle('recording:get-session-frames', async (_event, sessionId) => {
2605
+ const { getSessionFrames } = await Promise.resolve().then(() => __importStar(require('./db/database')));
2606
+ return getSessionFrames(sessionId);
2607
+ });
2608
+ // Manual capture marker during recording
2609
+ electron_1.ipcMain.handle('recording:manual-capture', async () => {
2610
+ if (!recordingModule)
2611
+ return { success: false, error: 'Recording feature not enabled' };
2612
+ const sessionMod = recordingModule.getSessionModule();
2613
+ if (!sessionMod)
2614
+ return { success: false, error: 'Session module not loaded' };
2615
+ sessionMod.triggerManualCapture();
2616
+ return { success: true };
2617
+ });
2618
+ // Quick record: start immediately with last-used profile, no dialog
2619
+ electron_1.ipcMain.handle('recording:quick-start', async () => {
2620
+ if (!recordingModule)
2621
+ return { success: false, error: 'Recording feature not enabled' };
2622
+ const sessionMod = recordingModule.getSessionModule();
2623
+ if (!sessionMod)
2624
+ return { success: false, error: 'Session module not loaded' };
2625
+ const recSettings = (0, store_1.getSetting)('recordingSettings') || {};
2626
+ const profile = recSettings.defaultProfile || 'automated_test';
2627
+ const session = await sessionMod.startSession({
2628
+ name: `Quick Recording ${new Date().toLocaleString()}`,
2629
+ profile,
2630
+ scope: 'all',
2631
+ showInGallery: recSettings.showInGallery !== false,
2632
+ });
2633
+ notifyRecordingStatusChange();
2634
+ return { sessionId: session.id, status: session.status };
2635
+ });
2636
+ // Recording settings
2637
+ electron_1.ipcMain.handle('recording:get-settings', async () => {
2638
+ return (0, store_1.getSetting)('recordingSettings') || {};
2639
+ });
2640
+ electron_1.ipcMain.handle('recording:set-settings', async (_event, settings) => {
2641
+ const current = (0, store_1.getSetting)('recordingSettings') || {};
2642
+ const updated = { ...current, ...settings };
2643
+ (0, store_1.setSetting)('recordingSettings', updated);
2644
+ return { success: true };
2645
+ });
2646
+ // Open timeline window
2647
+ electron_1.ipcMain.handle('recording:open-timeline', async (_event, sessionId) => {
2648
+ createTimelineWindow(sessionId);
2649
+ return { success: true };
2650
+ });
2651
+ // Open start recording dialog
2652
+ electron_1.ipcMain.handle('recording:open-start-dialog', async () => {
2653
+ createStartRecordingWindow();
2654
+ return { success: true };
2655
+ });
2656
+ }
2657
+ function createMainPanelWindow() {
2658
+ if (mainPanelWindow && !mainPanelWindow.isDestroyed()) {
2659
+ mainPanelWindow.show();
2660
+ mainPanelWindow.focus();
2661
+ return;
2662
+ }
2663
+ mainPanelWindow = new electron_1.BrowserWindow({
2664
+ width: 860,
2665
+ height: 600,
2666
+ ...framelessWindowOptions(),
2667
+ resizable: true,
2668
+ center: true,
2669
+ webPreferences: {
2670
+ preload: path.join(__dirname, 'preload.js'),
2671
+ contextIsolation: true,
2672
+ nodeIntegration: false,
2673
+ navigateOnDragDrop: false,
2674
+ },
2675
+ });
2676
+ makeWindowFocusAware(mainPanelWindow);
2677
+ attachCrashHandlers(mainPanelWindow, 'main-panel');
2678
+ mainPanelWindow.loadFile(path.join(__dirname, '../renderer/main-panel.html'));
2679
+ mainPanelWindow.on('closed', () => {
2680
+ mainPanelWindow = null;
2681
+ });
2682
+ }
2683
+ function createOnboardingWindow() {
2684
+ onboardingWindow = new electron_1.BrowserWindow({
2685
+ width: 560,
2686
+ height: 520,
2687
+ ...framelessWindowOptions(),
2688
+ resizable: false,
2689
+ center: true,
2690
+ webPreferences: {
2691
+ preload: path.join(__dirname, 'preload.js'),
2692
+ contextIsolation: true,
2693
+ nodeIntegration: false,
2694
+ navigateOnDragDrop: false,
2695
+ },
2696
+ });
2697
+ attachCrashHandlers(onboardingWindow, 'onboarding');
2698
+ onboardingWindow.loadFile(path.join(__dirname, '../renderer/onboarding.html'));
2699
+ onboardingWindow.on('closed', () => {
2700
+ onboardingWindow = null;
2701
+ });
2702
+ }
2703
+ // ── Full-screen capture (no region selection) ──
2704
+ async function doFullScreenCapture() {
2705
+ try {
2706
+ const fullBuffer = await (0, capture_modes_1.captureFullScreen)();
2707
+ ensureCapturesDir();
2708
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
2709
+ const filename = `fullscreen-${timestamp}.png`;
2710
+ const filepath = path.join(getCapturesDir(), filename);
2711
+ fs.writeFileSync(filepath, fullBuffer);
2712
+ const primaryDisplay = electron_1.screen.getPrimaryDisplay();
2713
+ const { width, height } = primaryDisplay.size;
2714
+ const captureId = (0, database_1.saveCapture)({
2715
+ screenshotPath: filepath,
2716
+ regionX: 0,
2717
+ regionY: 0,
2718
+ regionW: width,
2719
+ regionH: height,
2720
+ sourceApp: lastActiveWindow.appName,
2721
+ windowTitle: lastActiveWindow.windowTitle,
2722
+ });
2723
+ // Copy to clipboard
2724
+ const ni = electron_1.nativeImage.createFromBuffer(fullBuffer);
2725
+ electron_1.clipboard.writeImage(ni);
2726
+ // Show overlay
2727
+ createOverlayWindow({
2728
+ screenshotPath: filepath,
2729
+ captureId,
2730
+ hasApiKey: (0, auth_1.isAuthenticated)(),
2731
+ voiceMode: false,
2732
+ inlineEditMode: false,
2733
+ originalText: null,
2734
+ multiRegion: false,
2735
+ regionScreenshots: [filepath],
2736
+ }, { x: 0, y: 0, width, height });
2737
+ }
2738
+ catch (err) {
2739
+ logger_1.default.error('[FullScreenCapture] Error:', err);
2740
+ }
2741
+ }
2742
+ // ── Repeat last capture ──
2743
+ async function doRepeatLastCapture() {
2744
+ const lastRegion = (0, capture_modes_1.getLastCaptureRegion)();
2745
+ if (!lastRegion) {
2746
+ logger_1.default.info('[RepeatCapture] No previous capture region stored');
2747
+ return;
2748
+ }
2749
+ try {
2750
+ await (0, active_window_1.getActiveWindowInfo)().then((info) => {
2751
+ lastActiveWindow = info;
2752
+ });
2753
+ const fullBuffer = await (0, capture_1.captureScreen)();
2754
+ const { filepath, captureId } = await captureAndSaveRegion(fullBuffer, lastRegion);
2755
+ createOverlayWindow({
2756
+ screenshotPath: filepath,
2757
+ captureId,
2758
+ hasApiKey: (0, auth_1.isAuthenticated)(),
2759
+ voiceMode: false,
2760
+ inlineEditMode: false,
2761
+ originalText: null,
2762
+ multiRegion: false,
2763
+ regionScreenshots: [filepath],
2764
+ }, lastRegion);
2765
+ }
2766
+ catch (err) {
2767
+ logger_1.default.error('[RepeatCapture] Error:', err);
2768
+ }
2769
+ }
2770
+ // Check for CLI recording commands before full app startup
2771
+ // CLI commands communicate via HTTP API and exit immediately
2772
+ Promise.resolve().then(() => __importStar(require('./modules/recording/cli'))).then(({ handleCliArgs }) => {
2773
+ if (handleCliArgs(process.argv)) {
2774
+ // CLI command is being handled — don't start the full app
2775
+ return;
2776
+ }
2777
+ })
2778
+ .catch(() => {
2779
+ // CLI module not available, continue normal startup
2780
+ });
2781
+ // Register protocol handler for auth callback
2782
+ if (process.defaultApp) {
2783
+ if (process.argv.length >= 2) {
2784
+ electron_1.app.setAsDefaultProtocolClient('superbased', process.execPath, [path.resolve(process.argv[1])]);
2785
+ }
2786
+ }
2787
+ else {
2788
+ electron_1.app.setAsDefaultProtocolClient('superbased');
2789
+ }
2790
+ // Handle protocol URL on macOS
2791
+ electron_1.app.on('open-url', (_event, url) => {
2792
+ if (url.startsWith('superbased://auth-callback')) {
2793
+ (0, auth_1.handleAuthCallback)(url);
2794
+ // Notify all windows of auth state change
2795
+ for (const win of electron_1.BrowserWindow.getAllWindows()) {
2796
+ if (!win.isDestroyed()) {
2797
+ win.webContents.send('auth:state-changed', {
2798
+ isAuthenticated: (0, auth_1.isAuthenticated)(),
2799
+ ...(0, auth_1.getAuthState)(),
2800
+ });
2801
+ }
2802
+ }
2803
+ // Link device to user + validate license (sends machine_id → backend links device)
2804
+ if ((0, auth_1.isAuthenticated)()) {
2805
+ Promise.resolve().then(() => __importStar(require('./modules/license'))).then((lic) => lic.validateLicense()).catch(() => { });
2806
+ // Flush any queued analytics now that we have an auth token, then call
2807
+ // /usage/link-device so prior anonymous events get backfilled to the user.
2808
+ Promise.resolve().then(() => __importStar(require('./modules/telemetry'))).then((tel) => tel.flushNow()).catch(() => { });
2809
+ Promise.resolve().then(() => __importStar(require('./modules/usage-link'))).then((mod) => mod.linkDeviceOnSignIn()).catch(() => { });
2810
+ }
2811
+ }
2812
+ });
2813
+ // Handle protocol URL on Windows (second-instance)
2814
+ const gotSingleLock = electron_1.app.requestSingleInstanceLock();
2815
+ if (!gotSingleLock) {
2816
+ electron_1.app.quit();
2817
+ }
2818
+ else {
2819
+ electron_1.app.on('second-instance', (_event, argv) => {
2820
+ const url = argv.find((arg) => arg.startsWith('superbased://'));
2821
+ if (url && url.startsWith('superbased://auth-callback')) {
2822
+ (0, auth_1.handleAuthCallback)(url);
2823
+ for (const win of electron_1.BrowserWindow.getAllWindows()) {
2824
+ if (!win.isDestroyed()) {
2825
+ win.webContents.send('auth:state-changed', {
2826
+ isAuthenticated: (0, auth_1.isAuthenticated)(),
2827
+ ...(0, auth_1.getAuthState)(),
2828
+ });
2829
+ }
2830
+ }
2831
+ }
2832
+ // Focus main window
2833
+ if (mainPanelWindow && !mainPanelWindow.isDestroyed()) {
2834
+ if (mainPanelWindow.isMinimized())
2835
+ mainPanelWindow.restore();
2836
+ mainPanelWindow.focus();
2837
+ }
2838
+ });
2839
+ }
2840
+ electron_1.app.whenReady().then(() => {
2841
+ // Register sbfile:// protocol — reads files and returns buffers without holding locks.
2842
+ // This prevents Windows file locking when images are displayed in <img> tags.
2843
+ // URL format: sbfile:///C:/path/to/file.webp?v=1 (triple slash, forward slashes)
2844
+ electron_1.protocol.handle('sbfile', async (request) => {
2845
+ // Parse raw URL string — avoid new URL() which mis-parses Windows drive letters
2846
+ let filePath = request.url.replace(/^sbfile:\/\/\//, '').split('?')[0];
2847
+ filePath = decodeURIComponent(filePath);
2848
+ // Normalize forward slashes to platform separators
2849
+ if (process.platform === 'win32') {
2850
+ filePath = filePath.replace(/\//g, '\\');
2851
+ }
2852
+ try {
2853
+ const buffer = fs.readFileSync(filePath);
2854
+ const ext = path.extname(filePath).toLowerCase();
2855
+ const mimeTypes = {
2856
+ '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
2857
+ '.webp': 'image/webp', '.gif': 'image/gif', '.bmp': 'image/bmp',
2858
+ };
2859
+ return new Response(buffer, {
2860
+ headers: { 'Content-Type': mimeTypes[ext] || 'application/octet-stream' },
2861
+ });
2862
+ }
2863
+ catch (err) {
2864
+ logger_1.default.warn('[sbfile] Failed to serve:', filePath, err);
2865
+ return new Response('Not found', { status: 404 });
2866
+ }
2867
+ });
2868
+ (0, auth_1.loadStoredToken)();
2869
+ (0, database_1.initDatabase)();
2870
+ setupIpcHandlers();
2871
+ // Anonymous heartbeat — let the admin console see this install even if the
2872
+ // user never signs in. No-op when authenticated. Throttled to once / 24h.
2873
+ Promise.resolve().then(() => __importStar(require('./modules/license'))).then((lic) => lic.sendAnonymousHeartbeat())
2874
+ .catch(() => { });
2875
+ // Start the analytics forwarder. Periodically flushes the local event queue
2876
+ // to the backend so admin sees per-user usage data. Defaults to enabled —
2877
+ // user can opt out via Settings > Privacy > "Share usage analytics".
2878
+ Promise.resolve().then(() => __importStar(require('./modules/telemetry'))).then((tel) => {
2879
+ tel.startTelemetry();
2880
+ // One-shot historical backfill — uploads existing local SQLite
2881
+ // analytics_events buckets so the admin sees the same lifetime totals
2882
+ // as the user's local Analytics tab. Resumable across restarts.
2883
+ // Delay 5s so the auth state has settled (so the backfill is correctly
2884
+ // attributed to the user instead of going to the anonymous bucket).
2885
+ setTimeout(() => { tel.backfillLocalAnalytics().catch(() => { }); }, 5000);
2886
+ })
2887
+ .catch(() => { });
2888
+ // Backfill any prior anonymous events for this machine to the user account
2889
+ // if we already have an auth token at startup.
2890
+ if ((0, auth_1.isAuthenticated)()) {
2891
+ Promise.resolve().then(() => __importStar(require('./modules/usage-link'))).then((mod) => mod.linkDeviceOnSignIn()).catch(() => { });
2892
+ }
2893
+ // One-time macOS Screen Recording permission check (non-blocking)
2894
+ checkScreenRecordingPermissionOnce();
2895
+ (0, tray_1.setupTray)(() => createSelectionWindow(), () => openMainPanelSettings(), () => createGalleryWindow(), {
2896
+ onFullScreen: () => doFullScreenCapture(),
2897
+ onRepeatLast: () => doRepeatLastCapture(),
2898
+ onTimedCapture: (delayMs) => {
2899
+ (0, capture_modes_1.startTimedCapture)(delayMs, () => createSelectionWindow());
2900
+ },
2901
+ onStartRecording: () => {
2902
+ logger_1.default.info('[Tray] Start Recording clicked — opening dialog');
2903
+ createStartRecordingWindow();
2904
+ },
2905
+ onQuickRecord: async () => {
2906
+ try {
2907
+ // Trigger quick-start via IPC (reuses the handler logic)
2908
+ const recordingMod = await Promise.resolve().then(() => __importStar(require('./modules/recording')));
2909
+ const sessionMod = recordingMod.getSessionModule();
2910
+ if (sessionMod) {
2911
+ const recSettings = (0, store_1.getSetting)('recordingSettings');
2912
+ await sessionMod.startSession({
2913
+ name: `Quick Recording ${new Date().toLocaleString()}`,
2914
+ profile: (recSettings?.defaultProfile || 'automated_test'),
2915
+ scope: 'all',
2916
+ showInGallery: recSettings?.showInGallery !== false,
2917
+ });
2918
+ (0, tray_1.updateTrayRecordingState)(true, true);
2919
+ }
2920
+ }
2921
+ catch (err) {
2922
+ logger_1.default.error('[Tray] Quick record failed:', err);
2923
+ }
2924
+ },
2925
+ onPauseRecording: async () => {
2926
+ try {
2927
+ const recordingMod = await Promise.resolve().then(() => __importStar(require('./modules/recording')));
2928
+ const sessionMod = recordingMod.getSessionModule();
2929
+ if (sessionMod) {
2930
+ await sessionMod.pauseCurrentSession();
2931
+ (0, tray_1.updateTrayRecordingState)(true, false, true);
2932
+ }
2933
+ }
2934
+ catch (err) {
2935
+ logger_1.default.error('[Tray] Pause failed:', err);
2936
+ }
2937
+ },
2938
+ onResumeRecording: async () => {
2939
+ try {
2940
+ const recordingMod = await Promise.resolve().then(() => __importStar(require('./modules/recording')));
2941
+ const sessionMod = recordingMod.getSessionModule();
2942
+ if (sessionMod) {
2943
+ await sessionMod.resumeCurrentSession();
2944
+ (0, tray_1.updateTrayRecordingState)(true, true);
2945
+ }
2946
+ }
2947
+ catch (err) {
2948
+ logger_1.default.error('[Tray] Resume failed:', err);
2949
+ }
2950
+ },
2951
+ onStopRecording: async () => {
2952
+ try {
2953
+ const recordingMod = await Promise.resolve().then(() => __importStar(require('./modules/recording')));
2954
+ const sessionMod = recordingMod.getSessionModule();
2955
+ if (sessionMod) {
2956
+ const cur = sessionMod.getCurrentSession();
2957
+ const sessionId = cur?.id;
2958
+ await sessionMod.stopCurrentSession();
2959
+ (0, tray_1.updateTrayRecordingState)(true, false);
2960
+ closeRecordingBarWindow();
2961
+ if (sessionId) {
2962
+ createTimelineWindow(sessionId);
2963
+ }
2964
+ }
2965
+ }
2966
+ catch (err) {
2967
+ logger_1.default.error('[Tray] Stop failed:', err);
2968
+ }
2969
+ },
2970
+ onManualCapture: () => {
2971
+ try {
2972
+ const recordingMod = require('./modules/recording');
2973
+ const sessionMod = recordingMod.getSessionModule();
2974
+ if (sessionMod)
2975
+ sessionMod.triggerManualCapture();
2976
+ }
2977
+ catch (err) {
2978
+ logger_1.default.error('[Tray] Manual capture failed:', err);
2979
+ }
2980
+ },
2981
+ onSessionGallery: () => {
2982
+ createTimelineWindow();
2983
+ },
2984
+ onOpenMainPanel: () => {
2985
+ createMainPanelWindow();
2986
+ },
2987
+ });
2988
+ (0, hotkeys_1.registerHotkeys)(() => createSelectionWindow());
2989
+ // Register scroll-capture shortcut
2990
+ const scrollSettings = (0, store_1.getSetting)('scrollCapture');
2991
+ const scrollShortcut = scrollSettings?.shortcut || 'CommandOrControl+Shift+A';
2992
+ const scrollSuccess = electron_1.globalShortcut.register(scrollShortcut, () => {
2993
+ scrollCaptureMode = true;
2994
+ createSelectionWindow();
2995
+ });
2996
+ if (scrollSuccess)
2997
+ logger_1.default.info(`Scroll-capture shortcut registered: ${scrollShortcut}`);
2998
+ // Register full-screen capture shortcut
2999
+ const fullScreenSuccess = electron_1.globalShortcut.register('CommandOrControl+Shift+F', () => {
3000
+ doFullScreenCapture();
3001
+ });
3002
+ if (fullScreenSuccess)
3003
+ logger_1.default.info('Full-screen capture shortcut registered: Ctrl+Shift+F');
3004
+ // Register repeat-last-capture shortcut
3005
+ const repeatSuccess = electron_1.globalShortcut.register('CommandOrControl+Shift+L', () => {
3006
+ doRepeatLastCapture();
3007
+ });
3008
+ if (repeatSuccess)
3009
+ logger_1.default.info('Repeat-last-capture shortcut registered: Ctrl+Shift+L');
3010
+ // Register window capture shortcut (Ctrl+Shift+W) — opens window picker overlay
3011
+ const windowCaptureSuccess = electron_1.globalShortcut.register('CommandOrControl+Shift+W', async () => {
3012
+ try {
3013
+ const result = await (0, window_picker_1.showWindowPicker)();
3014
+ if (!result)
3015
+ return;
3016
+ await (0, active_window_1.getActiveWindowInfo)().then((info) => {
3017
+ lastActiveWindow = info;
3018
+ });
3019
+ // Capture full screen then crop — the source thumbnail is low-res
3020
+ const fullBuffer = await (0, capture_1.captureScreen)();
3021
+ const primaryDisplay = electron_1.screen.getPrimaryDisplay();
3022
+ const { width, height } = primaryDisplay.size;
3023
+ const region = { x: 0, y: 0, width, height };
3024
+ const { filepath, captureId } = await captureAndSaveRegion(fullBuffer, region);
3025
+ // Store window name as metadata
3026
+ lastActiveWindow = { appName: result.name, windowTitle: result.name };
3027
+ createOverlayWindow({
3028
+ screenshotPath: filepath,
3029
+ captureId,
3030
+ hasApiKey: (0, auth_1.isAuthenticated)(),
3031
+ voiceMode: false,
3032
+ inlineEditMode: false,
3033
+ originalText: null,
3034
+ multiRegion: false,
3035
+ regionScreenshots: [filepath],
3036
+ }, region);
3037
+ }
3038
+ catch (err) {
3039
+ logger_1.default.error('[WindowCapture] Error:', err);
3040
+ }
3041
+ });
3042
+ if (windowCaptureSuccess)
3043
+ logger_1.default.info('Window capture shortcut registered: Ctrl+Shift+W');
3044
+ // Register color picker shortcut (Ctrl+Shift+C)
3045
+ const colorPickerSuccess = electron_1.globalShortcut.register('CommandOrControl+Shift+C', () => {
3046
+ (0, color_picker_1.startColorPicker)();
3047
+ });
3048
+ if (colorPickerSuccess)
3049
+ logger_1.default.info('Color picker shortcut registered: Ctrl+Shift+C');
3050
+ // Register OCR capture shortcut (Ctrl+Shift+T)
3051
+ const ocrSuccess = electron_1.globalShortcut.register('CommandOrControl+Shift+T', async () => {
3052
+ try {
3053
+ // Capture full screen, then let user select region via selection window
3054
+ // For simplicity, OCR the full screen and show result
3055
+ const buf = await (0, capture_1.captureScreen)();
3056
+ const text = await (0, ocr_1.performOCR)(buf);
3057
+ if (text) {
3058
+ (0, ocr_1.showOCRResult)(text);
3059
+ // Also store in DB if we have a capture
3060
+ }
3061
+ else {
3062
+ (0, ocr_1.showOCRResult)('(No text detected)');
3063
+ }
3064
+ }
3065
+ catch (err) {
3066
+ logger_1.default.error('[OCR] Error:', err);
3067
+ }
3068
+ });
3069
+ if (ocrSuccess)
3070
+ logger_1.default.info('OCR capture shortcut registered: Ctrl+Shift+T');
3071
+ // Register Token Compression shortcut (Ctrl+Shift+E)
3072
+ const tceSuccess = electron_1.globalShortcut.register('CommandOrControl+Shift+E', async () => {
3073
+ try {
3074
+ const autoCopy = (0, store_1.getSetting)('tceAutoCopy') !== false; // default true
3075
+ let text;
3076
+ if (autoCopy) {
3077
+ // Auto-copy: simulate Ctrl+C to grab the current selection.
3078
+ // Wait 500ms first so the user releases Ctrl+Shift+E keys — otherwise
3079
+ // nut.js pressing C while Shift is still held triggers Ctrl+Shift+C (color picker).
3080
+ const { simulateCopy } = await Promise.resolve().then(() => __importStar(require('./modules/keystroke')));
3081
+ const prevClipboard = electron_1.clipboard.readText();
3082
+ await new Promise((resolve) => setTimeout(resolve, 500));
3083
+ await simulateCopy();
3084
+ await new Promise((resolve) => setTimeout(resolve, 200));
3085
+ text = electron_1.clipboard.readText();
3086
+ if (text !== prevClipboard) {
3087
+ logger_1.default.info('[TCE] Auto-copied selection to clipboard');
3088
+ }
3089
+ }
3090
+ else {
3091
+ text = electron_1.clipboard.readText();
3092
+ }
3093
+ if (!text || text.trim().length < 20) {
3094
+ logger_1.default.info('[TCE] Shortcut: no text available');
3095
+ const { Notification } = require('electron');
3096
+ new Notification({
3097
+ title: 'SuperBased — Compress Text',
3098
+ body: autoCopy
3099
+ ? 'Select text first, then press Ctrl+Shift+E.'
3100
+ : 'Copy text to clipboard first, then press Ctrl+Shift+E.',
3101
+ }).show();
3102
+ return;
3103
+ }
3104
+ logger_1.default.info(`[TCE] Shortcut: compressing ${text.length} chars from clipboard`);
3105
+ const { compressToFiles, quickAnalyze } = await Promise.resolve().then(() => __importStar(require('./modules/tce')));
3106
+ // Quick check: is compression actually beneficial?
3107
+ const analysis = quickAnalyze(text);
3108
+ if (analysis.compression.ratio < 1.0) {
3109
+ logger_1.default.info(`[TCE] Compression not beneficial (ratio ${analysis.compression.ratio.toFixed(1)}x). Using auto-preset.`);
3110
+ }
3111
+ if (!analysis.compression.recommend && analysis.compression.ratio < 1.0) {
3112
+ // Still proceed but use auto-preset which picks the smallest size
3113
+ // This maximizes density even if savings are marginal
3114
+ }
3115
+ // Read user TCE settings
3116
+ const tceUserSettings = {};
3117
+ const tcePreset = (0, store_1.getSetting)('tcePreset');
3118
+ tceUserSettings.preset = tcePreset || 'compact';
3119
+ logger_1.default.info(`[TCE] User preset setting: '${tcePreset}' → using '${tceUserSettings.preset}'`);
3120
+ const tceColumnMode = (0, store_1.getSetting)('tceColumnMode');
3121
+ if (tceColumnMode !== undefined)
3122
+ tceUserSettings.columnMode = tceColumnMode;
3123
+ const tceTheme = (0, store_1.getSetting)('tceTheme');
3124
+ if (tceTheme)
3125
+ tceUserSettings.theme = tceTheme;
3126
+ const tceFontSize = (0, store_1.getSetting)('tceFontSize');
3127
+ if (tceFontSize)
3128
+ tceUserSettings.fontSize = tceFontSize;
3129
+ const tceOverlap = (0, store_1.getSetting)('tceOverlapLines');
3130
+ if (tceOverlap !== undefined)
3131
+ tceUserSettings.overlapLines = tceOverlap;
3132
+ const tceWrap = (0, store_1.getSetting)('tceLineWrapping');
3133
+ tceUserSettings.lineWrapping = tceWrap || 'wrap';
3134
+ const { filePaths, metadata } = await compressToFiles(text, tceUserSettings);
3135
+ if (filePaths.length === 0) {
3136
+ logger_1.default.warn('[TCE] No pages generated');
3137
+ return;
3138
+ }
3139
+ // Save first page as a capture record
3140
+ const captureId = (0, database_1.saveCapture)({
3141
+ screenshotPath: filePaths[0],
3142
+ regionX: 0,
3143
+ regionY: 0,
3144
+ regionW: parseInt(metadata.resolution.split('x')[0]) || 800,
3145
+ regionH: parseInt(metadata.resolution.split('x')[1]) || 600,
3146
+ sourceApp: 'Token Compression',
3147
+ windowTitle: `${metadata.totalLines} lines, ${metadata.columnsUsed}-col, ${metadata.presetUsed}`,
3148
+ });
3149
+ // Verify files exist before opening overlay
3150
+ for (const fp of filePaths) {
3151
+ const exists = fs.existsSync(fp);
3152
+ const size = exists ? fs.statSync(fp).size : 0;
3153
+ logger_1.default.info(`[TCE] File check: ${fp} exists=${exists} size=${size}`);
3154
+ }
3155
+ // Open overlay with all compressed pages as screenshots
3156
+ const initData = {
3157
+ screenshotPath: filePaths[0],
3158
+ captureId,
3159
+ hasApiKey: (0, auth_1.isAuthenticated)(),
3160
+ voiceMode: false,
3161
+ inlineEditMode: false,
3162
+ originalText: null,
3163
+ multiRegion: filePaths.length > 1,
3164
+ regionScreenshots: filePaths,
3165
+ };
3166
+ logger_1.default.info(`[TCE] Opening overlay with initData: screenshotPath=${initData.screenshotPath}, regionScreenshots=${initData.regionScreenshots.length} paths`);
3167
+ createOverlayWindow(initData, { x: 0, y: 0, width: parseInt(metadata.resolution.split('x')[0]) || 800, height: parseInt(metadata.resolution.split('x')[1]) || 600 });
3168
+ logger_1.default.info(`[TCE] Opened overlay with ${filePaths.length} compressed pages (${metadata.savingsPercent}% savings)`);
3169
+ // Track TCE capture analytics
3170
+ (0, database_1.trackAnalytics)('capture', 'tce', filePaths.length, 0, 'Token Compression');
3171
+ }
3172
+ catch (err) {
3173
+ logger_1.default.error('[TCE] Shortcut compression failed:', err);
3174
+ }
3175
+ });
3176
+ if (tceSuccess)
3177
+ logger_1.default.info('Token compression shortcut registered: Ctrl+Shift+E');
3178
+ // Show onboarding on first run
3179
+ const onboardingDone = (0, store_1.getSetting)('onboardingComplete');
3180
+ if (!onboardingDone) {
3181
+ createOnboardingWindow();
3182
+ }
3183
+ (0, updater_1.initAutoUpdater)();
3184
+ (0, updater_1.onUpdateStateChanged)((state) => {
3185
+ if (state.status === 'downloaded' && state.version) {
3186
+ (0, tray_2.setTrayUpdateReady)(state.version);
3187
+ }
3188
+ });
3189
+ (0, version_check_1.initVersionCheck)();
3190
+ // Start the always-on HTTP API server for MCP and external tool integration
3191
+ Promise.resolve().then(() => __importStar(require('./modules/api-server'))).then(async (apiMod) => {
3192
+ await apiMod.startApiServer();
3193
+ // Write MCP config file for external tool discovery
3194
+ const { writeMCPConfig } = await Promise.resolve().then(() => __importStar(require('./modules/mcp-config')));
3195
+ writeMCPConfig(apiMod.getApiAuthToken());
3196
+ })
3197
+ .catch((err) => {
3198
+ logger_1.default.error('[API] Failed to start API server:', err);
3199
+ });
3200
+ // Auto-restore recording feature if it was previously enabled
3201
+ const recordingWasEnabled = (0, store_1.getSetting)('recordingFeatureEnabled');
3202
+ logger_1.default.info('[Startup] Recording was previously enabled:', recordingWasEnabled);
3203
+ if (recordingWasEnabled) {
3204
+ Promise.resolve().then(() => __importStar(require('./modules/recording'))).then(async (mod) => {
3205
+ const result = await mod.initialize();
3206
+ if (result.success) {
3207
+ logger_1.default.info(`[Recording] Auto-restored on startup (provider: ${result.providerType})`);
3208
+ // Register recording routes on the API server
3209
+ Promise.resolve().then(() => __importStar(require('./modules/api-server'))).then((apiMod) => apiMod.registerRecordingRoutesOnServer())
3210
+ .catch(() => { });
3211
+ // Store module ref so IPC handlers can use it — simulate enable
3212
+ // The recordingModule var is inside setupIpcHandlers closure, so we use an event
3213
+ electron_1.ipcMain.emit('recording-module-restored', null, mod);
3214
+ }
3215
+ else {
3216
+ logger_1.default.warn('[Recording] Failed to auto-restore:', result.fallbackReason);
3217
+ }
3218
+ })
3219
+ .catch((err) => {
3220
+ logger_1.default.error('[Recording] Failed to auto-restore:', err);
3221
+ });
3222
+ }
3223
+ // Auto-cleanup old screenshots
3224
+ const cleanupDays = (0, store_1.getSetting)('autoCleanupDays') || 0;
3225
+ if (cleanupDays > 0) {
3226
+ try {
3227
+ const capturesDir = getCapturesDir();
3228
+ const cutoff = Date.now() - cleanupDays * 24 * 60 * 60 * 1000;
3229
+ const files = fs.readdirSync(capturesDir);
3230
+ let removed = 0;
3231
+ for (const f of files) {
3232
+ const fp = path.join(capturesDir, f);
3233
+ try {
3234
+ const stat = fs.statSync(fp);
3235
+ if (stat.isFile() && stat.mtimeMs < cutoff && /\.(png|jpg|jpeg|webp)$/i.test(f)) {
3236
+ fs.unlinkSync(fp);
3237
+ removed++;
3238
+ }
3239
+ }
3240
+ catch { }
3241
+ }
3242
+ if (removed > 0)
3243
+ logger_1.default.info(`[AutoCleanup] Removed ${removed} screenshots older than ${cleanupDays} days`);
3244
+ }
3245
+ catch (err) {
3246
+ logger_1.default.error('[AutoCleanup] Error:', err);
3247
+ }
3248
+ }
3249
+ // Initialize dictation if enabled
3250
+ const dictationEnabled = (0, store_1.getSetting)('dictationEnabled');
3251
+ if (dictationEnabled) {
3252
+ createDictationIndicatorWindow();
3253
+ Promise.resolve().then(() => __importStar(require('./modules/dictation'))).then((mod) => {
3254
+ if (dictationIndicatorWindow && !dictationIndicatorWindow.isDestroyed()) {
3255
+ mod.initializeDictation(dictationIndicatorWindow);
3256
+ }
3257
+ })
3258
+ .catch((err) => logger_1.default.error('[Dictation] Failed to initialize:', err));
3259
+ }
3260
+ logger_1.default.info('SuperBased is running (V3 wiring version). Press Ctrl+Shift+S to start capturing.');
3261
+ logger_1.default.info('[Startup] recordingFeatureEnabled:', (0, store_1.getSetting)('recordingFeatureEnabled'));
3262
+ logger_1.default.info('[Startup] dictationEnabled:', dictationEnabled);
3263
+ });
3264
+ electron_1.app.on('will-quit', () => {
3265
+ (0, hotkeys_1.unregisterHotkeys)();
3266
+ // Flush any queued analytics so we don't lose the last minute of activity.
3267
+ Promise.resolve().then(() => __importStar(require('./modules/telemetry'))).then((tel) => tel.stopTelemetry())
3268
+ .catch(() => { });
3269
+ // Teardown dictation
3270
+ Promise.resolve().then(() => __importStar(require('./modules/dictation'))).then((mod) => mod.teardownDictation())
3271
+ .catch(() => { });
3272
+ closeDictationIndicatorWindow();
3273
+ // Update MCP config to stopped
3274
+ Promise.resolve().then(() => __importStar(require('./modules/mcp-config'))).then((cfgMod) => cfgMod.updateMCPConfigStopped())
3275
+ .catch(() => { });
3276
+ // Stop the API server
3277
+ Promise.resolve().then(() => __importStar(require('./modules/api-server'))).then((apiMod) => apiMod.stopApiServer())
3278
+ .catch(() => { });
3279
+ });
3280
+ electron_1.app.on('window-all-closed', () => {
3281
+ // App stays alive in the system tray
3282
+ });
3283
+ electron_1.app.on('child-process-gone', (_event, details) => {
3284
+ logger_1.default.error(`[Crash] Child process gone: type=${details.type}, reason=${details.reason}`);
3285
+ });
3286
+ //# sourceMappingURL=main.js.map