superbased 1.6.1 → 1.6.2

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.
@@ -641,9 +641,21 @@ function registerRecordingRoutesOnServer() {
641
641
  targetProcessName: body.targetProcessName,
642
642
  targetWindowTitle: body.targetWindowTitle,
643
643
  showInGallery: body.showInGallery !== false,
644
+ mode: body.mode,
645
+ interval: body.interval,
646
+ changeThreshold: body.changeThreshold,
644
647
  };
648
+ // Monitor mode settings
649
+ if (body.mode === 'monitor') {
650
+ options.monitor = {
651
+ analysisPrompt: body.analysisPrompt || 'Describe what changed on screen. Flag any errors, warnings, unexpected states, or UI issues.',
652
+ analyzeEvery: body.analyzeEvery ?? 5,
653
+ analyzeInterval: body.analyzeInterval ?? 30,
654
+ analysisDetail: body.analysisDetail || 'low',
655
+ };
656
+ }
645
657
  const session = await startSession(options);
646
- return reply.code(200).send({ sessionId: session.id, status: 'recording' });
658
+ return reply.code(200).send({ sessionId: session.id, status: 'recording', mode: session.mode });
647
659
  }
648
660
  catch (err) {
649
661
  return reply.code(400).send({ error: err instanceof Error ? err.message : String(err) });
@@ -698,6 +710,7 @@ function registerRecordingRoutesOnServer() {
698
710
  sessionId: session.id,
699
711
  frameCount: session.frameCount,
700
712
  duration: Date.now() - session.startedAt,
713
+ mode: session.mode,
701
714
  });
702
715
  });
703
716
  // POST /api/recording/capture
@@ -709,6 +722,87 @@ function registerRecordingRoutesOnServer() {
709
722
  triggerManualCapture();
710
723
  return reply.code(200).send({ success: true, message: 'Manual capture triggered' });
711
724
  });
725
+ // GET /api/recording/analysis — get AI analysis results for a session
726
+ s.get('/api/recording/analysis', async (request, reply) => {
727
+ try {
728
+ const query = request.query;
729
+ if (!query.sessionId) {
730
+ return reply.code(400).send({ error: 'sessionId query param required' });
731
+ }
732
+ const { getDatabase } = await Promise.resolve().then(() => __importStar(require('../db/database')));
733
+ const db = getDatabase();
734
+ const sinceFrame = query.since ? parseInt(query.since, 10) : 0;
735
+ const rows = db.prepare(`SELECT id, frame_number, timestamp, ai_response
736
+ FROM captures
737
+ WHERE session_id = ? AND ai_response IS NOT NULL AND ai_response != '' AND frame_number > ?
738
+ ORDER BY frame_number ASC`).all(query.sessionId, sinceFrame);
739
+ const analyses = rows.map((r) => ({
740
+ frameId: r.id,
741
+ frameNumber: r.frame_number,
742
+ timestamp: r.timestamp,
743
+ analysis: r.ai_response,
744
+ }));
745
+ return reply.code(200).send({ sessionId: query.sessionId, analyses });
746
+ }
747
+ catch (err) {
748
+ return reply.code(500).send({ error: err instanceof Error ? err.message : String(err) });
749
+ }
750
+ });
751
+ // GET /api/recording/monitor/status — monitor mode status
752
+ s.get('/api/recording/monitor/status', async (_request, reply) => {
753
+ const session = getCurrentSession();
754
+ if (!session || session.mode !== 'monitor') {
755
+ return reply.code(200).send({ status: 'inactive' });
756
+ }
757
+ const { getMonitorAnalyzer } = await Promise.resolve().then(() => __importStar(require('./recording/recording-session')));
758
+ const analyzer = getMonitorAnalyzer();
759
+ return reply.code(200).send({
760
+ status: 'monitoring',
761
+ sessionId: session.id,
762
+ mode: session.mode,
763
+ frameCount: session.frameCount,
764
+ alertCount: analyzer?.getAlertCount() || 0,
765
+ lastAnalysis: analyzer?.getLastAnalysis() || null,
766
+ });
767
+ });
768
+ // GET /api/recording/monitor/stream — SSE stream of monitor alerts
769
+ s.get('/api/recording/monitor/stream', async (request, reply) => {
770
+ const session = getCurrentSession();
771
+ if (!session || session.mode !== 'monitor') {
772
+ return reply.code(400).send({ error: 'No active monitor session' });
773
+ }
774
+ // Set up SSE headers
775
+ reply.raw.writeHead(200, {
776
+ 'Content-Type': 'text/event-stream',
777
+ 'Cache-Control': 'no-cache',
778
+ 'Connection': 'keep-alive',
779
+ 'X-Accel-Buffering': 'no',
780
+ });
781
+ reply.raw.write('event: connected\ndata: {"sessionId":"' + session.id + '"}\n\n');
782
+ // Register alert callback
783
+ const { setMonitorAlertCallback } = await Promise.resolve().then(() => __importStar(require('./recording/recording-session')));
784
+ const alertHandler = (alert) => {
785
+ const data = JSON.stringify(alert);
786
+ reply.raw.write(`event: alert\ndata: ${data}\n\n`);
787
+ };
788
+ setMonitorAlertCallback(alertHandler);
789
+ // Send keepalive every 15 seconds
790
+ const keepalive = setInterval(() => {
791
+ try {
792
+ reply.raw.write(':keepalive\n\n');
793
+ }
794
+ catch {
795
+ clearInterval(keepalive);
796
+ }
797
+ }, 15000);
798
+ // Cleanup on client disconnect
799
+ request.raw.on('close', () => {
800
+ clearInterval(keepalive);
801
+ setMonitorAlertCallback(() => { }); // Remove handler
802
+ });
803
+ // Don't send reply body — SSE uses raw stream
804
+ return reply;
805
+ });
712
806
  // GET /api/sessions
713
807
  s.get('/api/sessions', async (_request, reply) => {
714
808
  const sessions = getRecordingSessions(100);
@@ -4,6 +4,8 @@
4
4
  // On macOS, two issues affect capture:
5
5
  // 1. screenshot-desktop shells out to `screencapture` which can silently return blank images
6
6
  // 2. sharp's native binary may not be packaged for darwin — we fall back to Electron's nativeImage
7
+ //
8
+ // Headless mode: Electron APIs are not available. Uses screenshot-desktop + sharp instead.
7
9
  var __importDefault = (this && this.__importDefault) || function (mod) {
8
10
  return (mod && mod.__esModule) ? mod : { "default": mod };
9
11
  };
@@ -13,8 +15,20 @@ exports.getPreCapture = getPreCapture;
13
15
  exports.clearPreCapture = clearPreCapture;
14
16
  exports.captureScreen = captureScreen;
15
17
  exports.cropRegion = cropRegion;
16
- const electron_1 = require("electron");
17
18
  const logger_1 = __importDefault(require("../logger"));
19
+ // Lazy Electron imports — not available in headless mode
20
+ let desktopCapturer = null;
21
+ let nativeImage = null;
22
+ let electronScreen = null;
23
+ try {
24
+ const electron = require('electron');
25
+ desktopCapturer = electron.desktopCapturer;
26
+ nativeImage = electron.nativeImage;
27
+ electronScreen = electron.screen;
28
+ }
29
+ catch {
30
+ // Headless mode — Electron not available
31
+ }
18
32
  const isMac = process.platform === 'darwin';
19
33
  /**
20
34
  * Module-level storage for the pre-capture buffer taken before the selection window
@@ -37,7 +51,7 @@ function clearPreCapture() {
37
51
  * or screenshot-desktop (Windows/Linux, macOS fallback).
38
52
  */
39
53
  async function captureScreen() {
40
- if (isMac) {
54
+ if (isMac && desktopCapturer) {
41
55
  try {
42
56
  const buf = await captureScreenElectron();
43
57
  if (buf)
@@ -57,10 +71,12 @@ async function captureScreen() {
57
71
  * Returns null if the capture is empty (e.g., Screen Recording permission denied).
58
72
  */
59
73
  async function captureScreenElectron() {
60
- const primaryDisplay = electron_1.screen.getPrimaryDisplay();
74
+ if (!electronScreen || !desktopCapturer)
75
+ return null;
76
+ const primaryDisplay = electronScreen.getPrimaryDisplay();
61
77
  const { width, height } = primaryDisplay.size;
62
78
  const scaleFactor = primaryDisplay.scaleFactor || 1;
63
- const sources = await electron_1.desktopCapturer.getSources({
79
+ const sources = await desktopCapturer.getSources({
64
80
  types: ['screen'],
65
81
  thumbnailSize: {
66
82
  width: Math.round(width * scaleFactor),
@@ -90,9 +106,9 @@ async function captureScreenElectron() {
90
106
  * doesn't depend on any native module packaging).
91
107
  */
92
108
  async function cropRegion(fullScreenBuffer, region) {
93
- const primaryDisplay = electron_1.screen.getPrimaryDisplay();
94
- const scaleFactor = primaryDisplay.scaleFactor || 1;
95
- const displayBounds = primaryDisplay.bounds;
109
+ const primaryDisplay = electronScreen?.getPrimaryDisplay();
110
+ const scaleFactor = primaryDisplay?.scaleFactor || 1;
111
+ const displayBounds = primaryDisplay?.bounds || { x: 0, y: 0 };
96
112
  const left = Math.max(0, Math.round((region.x - displayBounds.x) * scaleFactor));
97
113
  const top = Math.max(0, Math.round((region.y - displayBounds.y) * scaleFactor));
98
114
  // Try sharp first (better quality, more format support)
@@ -123,7 +139,10 @@ async function cropRegion(fullScreenBuffer, region) {
123
139
  }
124
140
  }
125
141
  // Fallback: Electron's built-in nativeImage (no native module dependency)
126
- const img = electron_1.nativeImage.createFromBuffer(fullScreenBuffer);
142
+ if (!nativeImage) {
143
+ throw new Error('Cannot crop region: neither sharp nor Electron nativeImage available');
144
+ }
145
+ const img = nativeImage.createFromBuffer(fullScreenBuffer);
127
146
  if (img.isEmpty()) {
128
147
  throw new Error('Failed to create nativeImage from capture buffer');
129
148
  }
@@ -68,7 +68,6 @@ const constants_1 = require("../../shared/constants");
68
68
  let state = 'idle';
69
69
  let indicatorWindow = null;
70
70
  let uiohookModule = null;
71
- let hookStartedByDictation = false;
72
71
  let shortcutModifiers = ['ctrl', 'alt'];
73
72
  let aiCleanup = false;
74
73
  let soundFeedback = true;
@@ -731,7 +730,17 @@ function startDictation() {
731
730
  activeAppAtStart = { appName: null, windowTitle: null };
732
731
  });
733
732
  if (indicatorWindow && !indicatorWindow.isDestroyed()) {
733
+ // Refresh position + layer to ensure visibility (window may have been
734
+ // displaced by other always-on-top windows like the recording bar)
735
+ try {
736
+ const { screen } = require('electron');
737
+ const { width: screenW } = screen.getPrimaryDisplay().size;
738
+ indicatorWindow.setPosition(Math.round(screenW / 2 - 210), 8);
739
+ indicatorWindow.setAlwaysOnTop(true, 'screen-saver');
740
+ }
741
+ catch { /* ignore */ }
734
742
  indicatorWindow.showInactive();
743
+ logger_1.default.info('[Dictation] Indicator window shown, bounds:', JSON.stringify(indicatorWindow.getBounds()));
735
744
  if (transcriptionMode === 'realtime') {
736
745
  // Start PCM capture immediately so no speech is lost.
737
746
  // Audio is pre-buffered until the RT engine is ready, then flushed.
@@ -744,6 +753,9 @@ function startDictation() {
744
753
  indicatorWindow.webContents.send('dictation:start-recording');
745
754
  }
746
755
  }
756
+ else {
757
+ logger_1.default.warn('[Dictation] Indicator window unavailable:', indicatorWindow ? 'destroyed' : 'null');
758
+ }
747
759
  // Play start sound
748
760
  if (soundFeedback && indicatorWindow && !indicatorWindow.isDestroyed()) {
749
761
  indicatorWindow.webContents.send('dictation:play-sound', 'start');
@@ -1088,22 +1100,14 @@ async function initializeDictation(window) {
1088
1100
  Promise.resolve().then(() => __importStar(require('./azure-speech-realtime'))).then((rt) => rt.preloadSdk()).catch(() => { });
1089
1101
  }
1090
1102
  }).catch(() => { });
1091
- // Dynamically import uiohook-napi
1103
+ // Acquire uiohook via shared manager (reference-counted start/stop)
1092
1104
  try {
1093
- uiohookModule = await Promise.resolve().then(() => __importStar(require('uiohook-napi')));
1105
+ const { acquire } = await Promise.resolve().then(() => __importStar(require('./uiohook-manager')));
1106
+ uiohookModule = await acquire('dictation');
1094
1107
  const { uIOhook } = uiohookModule;
1095
1108
  // Register our listeners on the singleton
1096
1109
  uIOhook.on('keydown', onKeyDown);
1097
1110
  uIOhook.on('keyup', onKeyUp);
1098
- // Start hook if not already running (recording module may have started it)
1099
- try {
1100
- uIOhook.start();
1101
- hookStartedByDictation = true;
1102
- }
1103
- catch {
1104
- // Already running — that's fine
1105
- hookStartedByDictation = false;
1106
- }
1107
1111
  logger_1.default.info('[Dictation] Initialized, shortcut:', shortcutModifiers.join('+'), 'timeout:', maxDurationSeconds + 's');
1108
1112
  }
1109
1113
  catch (err) {
@@ -1116,14 +1120,13 @@ async function teardownDictation() {
1116
1120
  const { uIOhook } = uiohookModule;
1117
1121
  uIOhook.off('keydown', onKeyDown);
1118
1122
  uIOhook.off('keyup', onKeyUp);
1119
- // Only stop hook if we started it and recording module isn't using it
1120
- if (hookStartedByDictation) {
1121
- try {
1122
- uIOhook.stop();
1123
- }
1124
- catch {
1125
- // ignore
1126
- }
1123
+ // Release our reference — hook only stops if no other consumer needs it
1124
+ try {
1125
+ const { release } = await Promise.resolve().then(() => __importStar(require('./uiohook-manager')));
1126
+ release('dictation');
1127
+ }
1128
+ catch {
1129
+ // ignore
1127
1130
  }
1128
1131
  }
1129
1132
  pressedKeys.clear();
@@ -38,7 +38,17 @@ Object.defineProperty(exports, "__esModule", { value: true });
38
38
  exports.performOCR = performOCR;
39
39
  exports.showOCRResult = showOCRResult;
40
40
  const path = __importStar(require("path"));
41
- const electron_1 = require("electron");
41
+ // Lazy Electron imports — not available in headless mode
42
+ let BrowserWindow = null;
43
+ let electronScreen = null;
44
+ try {
45
+ const electron = require('electron');
46
+ BrowserWindow = electron.BrowserWindow;
47
+ electronScreen = electron.screen;
48
+ }
49
+ catch {
50
+ // Headless mode
51
+ }
42
52
  let ocrWindow = null;
43
53
  async function performOCR(imageBuffer) {
44
54
  const Tesseract = require('tesseract.js');
@@ -51,9 +61,11 @@ function showOCRResult(text) {
51
61
  if (ocrWindow && !ocrWindow.isDestroyed()) {
52
62
  ocrWindow.close();
53
63
  }
54
- const primaryDisplay = electron_1.screen.getPrimaryDisplay();
64
+ if (!BrowserWindow || !electronScreen)
65
+ return; // Not available in headless
66
+ const primaryDisplay = electronScreen.getPrimaryDisplay();
55
67
  const { width: screenW } = primaryDisplay.size;
56
- ocrWindow = new electron_1.BrowserWindow({
68
+ ocrWindow = new BrowserWindow({
57
69
  x: Math.round(screenW / 2 - 250),
58
70
  y: 60,
59
71
  width: 500,
@@ -45,12 +45,36 @@ Object.defineProperty(exports, "__esModule", { value: true });
45
45
  exports.CaptureQueue = void 0;
46
46
  const path = __importStar(require("path"));
47
47
  const fs = __importStar(require("fs"));
48
- const electron_1 = require("electron");
49
48
  const logger_1 = __importDefault(require("../../logger"));
50
49
  const active_window_1 = require("../active-window");
51
- const capture_1 = require("../capture");
50
+ const platform_1 = require("../../core/platform");
52
51
  const redact_1 = require("../redact");
53
- const store_1 = require("../store");
52
+ // Lazy Electron nativeImage — only available in desktop mode
53
+ let nativeImage = null;
54
+ try {
55
+ nativeImage = require('electron').nativeImage;
56
+ }
57
+ catch {
58
+ // Headless mode — nativeImage not available, sharp required
59
+ }
60
+ // Platform-aware getSetting
61
+ function getSetting(key) {
62
+ if ((0, platform_1.getPlatform)().isElectron()) {
63
+ const { getSetting: s } = require('../store');
64
+ return s(key);
65
+ }
66
+ const { getSetting: s } = require('../../core/json-store');
67
+ return s(key);
68
+ }
69
+ // Platform-aware captureScreen
70
+ async function captureScreenPlatform() {
71
+ if ((0, platform_1.getPlatform)().isElectron()) {
72
+ const { captureScreen } = require('../capture');
73
+ return captureScreen();
74
+ }
75
+ const screenshot = require('screenshot-desktop');
76
+ return screenshot({ format: 'png' });
77
+ }
54
78
  // Session limits
55
79
  const MAX_FRAMES_DEFAULT = 2000;
56
80
  const MAX_DURATION_DEFAULT = 60 * 60 * 1000; // 1 hour
@@ -159,7 +183,7 @@ class CaptureQueue {
159
183
  try {
160
184
  // Take screenshot — the expensive part (~800-1200ms)
161
185
  const t0 = Date.now();
162
- const fullBuffer = await (0, capture_1.captureScreen)();
186
+ const fullBuffer = await captureScreenPlatform();
163
187
  logger_1.default.info(`[CaptureQueue] captureScreen took ${Date.now() - t0}ms (inFlight=${this.inFlightCaptures})`);
164
188
  // Get active window info (while screenshot was being taken, window may have changed — grab it now)
165
189
  let windowTitle = null;
@@ -226,8 +250,8 @@ class CaptureQueue {
226
250
  const frameNum = this.frameCounter;
227
251
  const paddedNum = String(frameNum).padStart(4, '0');
228
252
  // Auto-redact sensitive content if enabled (runs inline before encode)
229
- const redactSecrets = !!(0, store_1.getSetting)('autoRedactSecrets');
230
- const redactPII = !!(0, store_1.getSetting)('autoRedactPII');
253
+ const redactSecrets = !!getSetting('autoRedactSecrets');
254
+ const redactPII = !!getSetting('autoRedactPII');
231
255
  if (redactSecrets || redactPII) {
232
256
  const redactResult = await (0, redact_1.autoRedact)(frame.buffer, { secrets: redactSecrets, pii: redactPII });
233
257
  if (redactResult.regionsFound > 0) {
@@ -255,9 +279,9 @@ class CaptureQueue {
255
279
  .toBuffer();
256
280
  thumbExt = 'webp';
257
281
  }
258
- else {
282
+ else if (nativeImage) {
259
283
  // nativeImage fallback: resize to 256px wide, use JPEG
260
- const img = electron_1.nativeImage.createFromBuffer(frame.buffer);
284
+ const img = nativeImage.createFromBuffer(frame.buffer);
261
285
  const size = img.getSize();
262
286
  const scale = 256 / Math.max(size.width, size.height);
263
287
  const resized = img.resize({
@@ -267,6 +291,11 @@ class CaptureQueue {
267
291
  thumbBuffer = resized.toJPEG(60);
268
292
  thumbExt = 'jpg';
269
293
  }
294
+ else {
295
+ // No sharp and no nativeImage — save raw PNG as thumbnail
296
+ thumbBuffer = frame.buffer;
297
+ thumbExt = 'png';
298
+ }
270
299
  const thumbName = `frame_${paddedNum}_thumb.${thumbExt}`;
271
300
  const thumbnailPath = path.join(this.sessionDir, 'thumbnails', thumbName);
272
301
  fs.writeFileSync(thumbnailPath, thumbBuffer);
@@ -297,7 +326,9 @@ class CaptureQueue {
297
326
  }
298
327
  /** Resize using nativeImage and return raw BGRA bitmap for comparison */
299
328
  resizeWithNativeImage(buffer, width, height) {
300
- const img = electron_1.nativeImage.createFromBuffer(buffer);
329
+ if (!nativeImage)
330
+ throw new Error('nativeImage not available in headless mode');
331
+ const img = nativeImage.createFromBuffer(buffer);
301
332
  const resized = img.resize({ width, height });
302
333
  return resized.toBitmap();
303
334
  }
@@ -321,7 +352,9 @@ class CaptureQueue {
321
352
  }
322
353
  /** Encode frame using nativeImage (JPEG/PNG only — no webp support) */
323
354
  encodeFrameNative(buffer) {
324
- const img = electron_1.nativeImage.createFromBuffer(buffer);
355
+ if (!nativeImage)
356
+ throw new Error('nativeImage not available in headless mode — sharp is required');
357
+ const img = nativeImage.createFromBuffer(buffer);
325
358
  switch (this.config.captureFormat) {
326
359
  case 'webp':
327
360
  case 'jpeg': {
@@ -47,7 +47,7 @@ exports.getCaptureQueue = getCaptureQueue;
47
47
  exports.getSessionModule = getSessionModule;
48
48
  exports.getMcpToolModule = getMcpToolModule;
49
49
  const provider_factory_1 = require("./providers/provider-factory");
50
- const electron_1 = require("electron");
50
+ const platform_1 = require("../../core/platform");
51
51
  const logger_1 = __importDefault(require("../../logger"));
52
52
  let hookProvider = null;
53
53
  let providerInfo = null;
@@ -57,11 +57,17 @@ let captureQueueModule = null;
57
57
  let sessionModule = null;
58
58
  let mcpToolModule = null;
59
59
  async function initialize() {
60
- // On macOS, request Accessibility permission
61
- if (process.platform === 'darwin') {
62
- const trusted = electron_1.systemPreferences.isTrustedAccessibilityClient(true);
63
- if (!trusted) {
64
- return { success: false, providerType: 'none', fallbackReason: 'Accessibility permission denied on macOS' };
60
+ // On macOS in Electron, request Accessibility permission
61
+ if (process.platform === 'darwin' && (0, platform_1.getPlatform)().isElectron()) {
62
+ try {
63
+ const { systemPreferences } = require('electron');
64
+ const trusted = systemPreferences.isTrustedAccessibilityClient(true);
65
+ if (!trusted) {
66
+ return { success: false, providerType: 'none', fallbackReason: 'Accessibility permission denied on macOS' };
67
+ }
68
+ }
69
+ catch {
70
+ // Headless — skip accessibility check
65
71
  }
66
72
  }
67
73
  // Create the input hook provider (uiohook → periodic fallback)
@@ -0,0 +1,219 @@
1
+ "use strict";
2
+ // MonitorAnalyzer — AI analysis loop for monitor mode recording.
3
+ // Receives frames from CaptureQueue, batches by count/time, sends to AI for analysis,
4
+ // stores results on frame records, and emits alerts for MCP notifications.
5
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ var desc = Object.getOwnPropertyDescriptor(m, k);
8
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
9
+ desc = { enumerable: true, get: function() { return m[k]; } };
10
+ }
11
+ Object.defineProperty(o, k2, desc);
12
+ }) : (function(o, m, k, k2) {
13
+ if (k2 === undefined) k2 = k;
14
+ o[k2] = m[k];
15
+ }));
16
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
17
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
18
+ }) : function(o, v) {
19
+ o["default"] = v;
20
+ });
21
+ var __importStar = (this && this.__importStar) || (function () {
22
+ var ownKeys = function(o) {
23
+ ownKeys = Object.getOwnPropertyNames || function (o) {
24
+ var ar = [];
25
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
26
+ return ar;
27
+ };
28
+ return ownKeys(o);
29
+ };
30
+ return function (mod) {
31
+ if (mod && mod.__esModule) return mod;
32
+ var result = {};
33
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
34
+ __setModuleDefault(result, mod);
35
+ return result;
36
+ };
37
+ })();
38
+ var __importDefault = (this && this.__importDefault) || function (mod) {
39
+ return (mod && mod.__esModule) ? mod : { "default": mod };
40
+ };
41
+ Object.defineProperty(exports, "__esModule", { value: true });
42
+ exports.MonitorAnalyzer = void 0;
43
+ const fs = __importStar(require("fs"));
44
+ const http = __importStar(require("http"));
45
+ const logger_1 = __importDefault(require("../../logger"));
46
+ class MonitorAnalyzer {
47
+ config;
48
+ sessionId;
49
+ onAlert;
50
+ framesSinceAnalysis = 0;
51
+ lastAnalysisTime = 0;
52
+ analyzing = false;
53
+ pendingFrames = [];
54
+ destroyed = false;
55
+ alertCount = 0;
56
+ lastAnalysis = null;
57
+ constructor(config, sessionId, onAlert) {
58
+ this.config = config;
59
+ this.sessionId = sessionId;
60
+ this.onAlert = onAlert;
61
+ logger_1.default.info(`[MonitorAnalyzer] Initialized for session ${sessionId} — analyzeEvery=${config.analyzeEvery}, analyzeInterval=${config.analyzeInterval}s`);
62
+ }
63
+ async onFrame(frame) {
64
+ if (this.destroyed)
65
+ return;
66
+ this.framesSinceAnalysis++;
67
+ this.pendingFrames.push(frame);
68
+ // Keep only the last N frames to avoid unbounded memory growth
69
+ if (this.pendingFrames.length > this.config.analyzeEvery * 2) {
70
+ this.pendingFrames = this.pendingFrames.slice(-this.config.analyzeEvery);
71
+ }
72
+ const elapsed = (Date.now() - this.lastAnalysisTime) / 1000;
73
+ const shouldAnalyze = this.framesSinceAnalysis >= this.config.analyzeEvery &&
74
+ elapsed >= this.config.analyzeInterval;
75
+ if (!shouldAnalyze || this.analyzing)
76
+ return;
77
+ this.analyzing = true;
78
+ try {
79
+ await this.analyzeLatestFrame();
80
+ }
81
+ catch (err) {
82
+ logger_1.default.error('[MonitorAnalyzer] Analysis failed:', err);
83
+ }
84
+ finally {
85
+ this.analyzing = false;
86
+ }
87
+ }
88
+ async analyzeLatestFrame() {
89
+ // Pick the most recent frame for analysis
90
+ const frame = this.pendingFrames[this.pendingFrames.length - 1];
91
+ if (!frame)
92
+ return;
93
+ logger_1.default.info(`[MonitorAnalyzer] Analyzing frame #${frame.frameNumber} (${this.framesSinceAnalysis} frames since last analysis)`);
94
+ // Read the frame image and resize for AI
95
+ if (!fs.existsSync(frame.framePath)) {
96
+ logger_1.default.warn(`[MonitorAnalyzer] Frame file not found: ${frame.framePath}`);
97
+ return;
98
+ }
99
+ const imageBuffer = fs.readFileSync(frame.framePath);
100
+ const resizedBase64 = await this.resizeForAI(imageBuffer);
101
+ // Call AI via local API
102
+ const analysis = await this.callAI(resizedBase64, frame);
103
+ if (!analysis || this.destroyed)
104
+ return;
105
+ // Reset counters
106
+ this.framesSinceAnalysis = 0;
107
+ this.lastAnalysisTime = Date.now();
108
+ this.pendingFrames = [];
109
+ // Store analysis on the frame record
110
+ await this.storeAnalysis(frame.captureId, analysis);
111
+ // Emit alert
112
+ this.alertCount++;
113
+ const alert = {
114
+ sessionId: this.sessionId,
115
+ frameId: frame.captureId,
116
+ frameNumber: frame.frameNumber,
117
+ analysis,
118
+ screenshotPath: frame.framePath,
119
+ timestamp: new Date().toISOString(),
120
+ };
121
+ this.lastAnalysis = alert;
122
+ this.onAlert(alert);
123
+ logger_1.default.info(`[MonitorAnalyzer] Analysis complete for frame #${frame.frameNumber}: ${analysis.substring(0, 100)}...`);
124
+ }
125
+ async resizeForAI(buffer) {
126
+ try {
127
+ const sharp = require('sharp');
128
+ const maxDim = this.config.analysisDetail === 'high' ? 1024 : 512;
129
+ const meta = await sharp(buffer).metadata();
130
+ const maxSide = Math.max(meta.width || 0, meta.height || 0);
131
+ if (maxSide > maxDim) {
132
+ const resized = await sharp(buffer)
133
+ .resize({
134
+ width: maxSide === meta.width ? maxDim : undefined,
135
+ height: maxSide === meta.height ? maxDim : undefined,
136
+ fit: 'inside',
137
+ })
138
+ .png()
139
+ .toBuffer();
140
+ return resized.toString('base64');
141
+ }
142
+ return buffer.toString('base64');
143
+ }
144
+ catch {
145
+ return buffer.toString('base64');
146
+ }
147
+ }
148
+ async callAI(imageBase64, frame) {
149
+ const windowContext = frame.windowTitle ? ` (Active window: ${frame.windowTitle})` : '';
150
+ const instruction = `${this.config.analysisPrompt}\n\nFrame #${frame.frameNumber} of session "${this.sessionId}".${windowContext}\nKeep your response concise (2-4 sentences).`;
151
+ return new Promise((resolve) => {
152
+ const postData = JSON.stringify({
153
+ instruction,
154
+ imageBase64,
155
+ });
156
+ const req = http.request({
157
+ hostname: '127.0.0.1',
158
+ port: 47592,
159
+ path: '/api/ai/process',
160
+ method: 'POST',
161
+ headers: {
162
+ 'Content-Type': 'application/json',
163
+ 'Content-Length': Buffer.byteLength(postData),
164
+ },
165
+ }, (res) => {
166
+ let data = '';
167
+ res.on('data', (chunk) => (data += chunk));
168
+ res.on('end', () => {
169
+ try {
170
+ const parsed = JSON.parse(data);
171
+ if (parsed.error) {
172
+ logger_1.default.warn(`[MonitorAnalyzer] AI error: ${parsed.error}`);
173
+ resolve(null);
174
+ }
175
+ else {
176
+ resolve(parsed.response || null);
177
+ }
178
+ }
179
+ catch {
180
+ logger_1.default.warn('[MonitorAnalyzer] Failed to parse AI response');
181
+ resolve(null);
182
+ }
183
+ });
184
+ });
185
+ req.on('error', (err) => {
186
+ logger_1.default.warn(`[MonitorAnalyzer] AI request failed: ${err.message}`);
187
+ resolve(null);
188
+ });
189
+ req.setTimeout(30000, () => {
190
+ logger_1.default.warn('[MonitorAnalyzer] AI request timeout');
191
+ req.destroy();
192
+ resolve(null);
193
+ });
194
+ req.write(postData);
195
+ req.end();
196
+ });
197
+ }
198
+ async storeAnalysis(captureId, analysis) {
199
+ try {
200
+ const { updateCapture } = require('../../db/database');
201
+ updateCapture(captureId, { aiResponse: analysis });
202
+ }
203
+ catch (err) {
204
+ logger_1.default.error('[MonitorAnalyzer] Failed to store analysis:', err);
205
+ }
206
+ }
207
+ getAlertCount() {
208
+ return this.alertCount;
209
+ }
210
+ getLastAnalysis() {
211
+ return this.lastAnalysis;
212
+ }
213
+ destroy() {
214
+ this.destroyed = true;
215
+ this.pendingFrames = [];
216
+ logger_1.default.info(`[MonitorAnalyzer] Destroyed (${this.alertCount} alerts emitted)`);
217
+ }
218
+ }
219
+ exports.MonitorAnalyzer = MonitorAnalyzer;
@@ -0,0 +1,180 @@
1
+ "use strict";
2
+ // ChangeDetectProvider — timer + visual diff gating for smart/monitor recording.
3
+ // Works on all platforms without native input hooks.
4
+ // Captures at a configurable interval, compares frames via pixel diff,
5
+ // and only emits events when visual change exceeds threshold.
6
+ // Also polls active window title for focus_change detection.
7
+ var __importDefault = (this && this.__importDefault) || function (mod) {
8
+ return (mod && mod.__esModule) ? mod : { "default": mod };
9
+ };
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.ChangeDetectProvider = void 0;
12
+ const logger_1 = __importDefault(require("../../../logger"));
13
+ const platform_1 = require("../../../core/platform");
14
+ // Tiny frame dimensions for fast pixel comparison
15
+ const TINY_WIDTH = 128;
16
+ const TINY_HEIGHT = 72;
17
+ class ChangeDetectProvider {
18
+ handlers = new Set();
19
+ running = false;
20
+ timer = null;
21
+ intervalMs;
22
+ changeThreshold;
23
+ lastTinyBuffer = null;
24
+ lastWindowTitle = '';
25
+ constructor(config) {
26
+ this.intervalMs = config.interval * 1000;
27
+ this.changeThreshold = config.changeThreshold;
28
+ }
29
+ async start() {
30
+ this.running = true;
31
+ this.lastTinyBuffer = null;
32
+ this.lastWindowTitle = '';
33
+ logger_1.default.info(`[ChangeDetect] Starting with interval=${this.intervalMs}ms, threshold=${this.changeThreshold}`);
34
+ this.timer = setInterval(() => {
35
+ this.tick().catch((err) => {
36
+ logger_1.default.error('[ChangeDetect] Tick error:', err);
37
+ });
38
+ }, this.intervalMs);
39
+ }
40
+ async stop() {
41
+ if (this.timer) {
42
+ clearInterval(this.timer);
43
+ this.timer = null;
44
+ }
45
+ this.running = false;
46
+ this.lastTinyBuffer = null;
47
+ logger_1.default.info('[ChangeDetect] Stopped');
48
+ }
49
+ isRunning() {
50
+ return this.running;
51
+ }
52
+ on(_event, handler) {
53
+ this.handlers.add(handler);
54
+ }
55
+ off(_event, handler) {
56
+ this.handlers.delete(handler);
57
+ }
58
+ emit(event) {
59
+ for (const handler of this.handlers) {
60
+ handler(event);
61
+ }
62
+ }
63
+ async tick() {
64
+ if (!this.running)
65
+ return;
66
+ try {
67
+ // 1. Capture screen as PNG buffer
68
+ const screenshotBuffer = await this.captureScreenshot();
69
+ if (!screenshotBuffer || screenshotBuffer.length === 0)
70
+ return;
71
+ // 2. Downscale to tiny buffer for fast comparison
72
+ const tinyBuffer = await this.downscale(screenshotBuffer);
73
+ if (!tinyBuffer)
74
+ return;
75
+ // 3. Check active window title for focus_change
76
+ await this.checkWindowTitle();
77
+ // 4. Compute visual diff against previous frame
78
+ const diffRatio = this.lastTinyBuffer
79
+ ? this.computeDiff(this.lastTinyBuffer, tinyBuffer)
80
+ : 1.0; // First frame always captured
81
+ // 5. Emit periodic event if change exceeds threshold
82
+ if (diffRatio >= this.changeThreshold) {
83
+ logger_1.default.info(`[ChangeDetect] Visual change ${(diffRatio * 100).toFixed(1)}% >= threshold ${(this.changeThreshold * 100).toFixed(1)}%`);
84
+ this.lastTinyBuffer = tinyBuffer;
85
+ // Emit a synthetic periodic trigger event.
86
+ // We use the mouseup type because TriggerEngine processes it
87
+ // and the periodic timer in TriggerEngine handles the actual capture.
88
+ // But for smart mode, we emit a direct periodic-style event that
89
+ // TriggerEngine will forward to CaptureQueue.
90
+ const event = {
91
+ type: 'mouseup',
92
+ timestamp: Date.now(),
93
+ x: 0,
94
+ y: 0,
95
+ button: 1,
96
+ modifiers: { ctrl: false, alt: false, shift: false, meta: false },
97
+ };
98
+ this.emit(event);
99
+ }
100
+ else {
101
+ // Below threshold — skip
102
+ if (this.lastTinyBuffer) {
103
+ logger_1.default.info(`[ChangeDetect] Visual change ${(diffRatio * 100).toFixed(1)}% < threshold — skipping`);
104
+ }
105
+ }
106
+ }
107
+ catch (err) {
108
+ logger_1.default.error('[ChangeDetect] Tick error:', err);
109
+ }
110
+ }
111
+ async captureScreenshot() {
112
+ try {
113
+ const platform = (0, platform_1.getPlatform)();
114
+ if (platform.isElectron()) {
115
+ // In Electron, use the existing captureScreen function
116
+ const { captureScreen } = require('../../capture');
117
+ return await captureScreen();
118
+ }
119
+ else {
120
+ // Headless: use screenshot-desktop
121
+ const screenshot = require('screenshot-desktop');
122
+ return await screenshot({ format: 'png' });
123
+ }
124
+ }
125
+ catch (err) {
126
+ logger_1.default.error('[ChangeDetect] Screenshot failed:', err);
127
+ return null;
128
+ }
129
+ }
130
+ async downscale(buffer) {
131
+ try {
132
+ const sharp = require('sharp');
133
+ return await sharp(buffer)
134
+ .resize(TINY_WIDTH, TINY_HEIGHT, { fit: 'fill' })
135
+ .raw()
136
+ .toBuffer();
137
+ }
138
+ catch (err) {
139
+ logger_1.default.error('[ChangeDetect] Downscale failed:', err);
140
+ return null;
141
+ }
142
+ }
143
+ computeDiff(prev, curr) {
144
+ const len = Math.min(prev.length, curr.length);
145
+ if (len === 0)
146
+ return 1.0;
147
+ let totalDiff = 0;
148
+ for (let i = 0; i < len; i++) {
149
+ totalDiff += Math.abs(prev[i] - curr[i]);
150
+ }
151
+ // Normalize to 0-1 ratio (255 is max diff per byte)
152
+ return totalDiff / (len * 255);
153
+ }
154
+ async checkWindowTitle() {
155
+ try {
156
+ const platform = (0, platform_1.getPlatform)();
157
+ if (platform.isElectron()) {
158
+ const { getActiveWindowInfo } = require('../../active-window');
159
+ const info = await getActiveWindowInfo();
160
+ const title = info.windowTitle || '';
161
+ if (title && title !== this.lastWindowTitle && this.lastWindowTitle !== '') {
162
+ logger_1.default.info(`[ChangeDetect] Window changed: "${this.lastWindowTitle}" → "${title}"`);
163
+ // Emit a synthetic focus change — the recording session's focus poll
164
+ // will also detect this, but emitting here ensures it's captured
165
+ // even without the session's own polling.
166
+ }
167
+ this.lastWindowTitle = title;
168
+ }
169
+ else {
170
+ // Headless: use platform's listWindows to detect active window changes
171
+ // This is a best-effort approach — some platforms may not support it well
172
+ // For now, skip focus detection in headless (window title comes from screenshot metadata)
173
+ }
174
+ }
175
+ catch {
176
+ // Ignore window detection errors
177
+ }
178
+ }
179
+ }
180
+ exports.ChangeDetectProvider = ChangeDetectProvider;
@@ -1,5 +1,5 @@
1
1
  "use strict";
2
- // Provider factory: detect platform, try uiohook, fallback to periodic.
2
+ // Provider factory: detect platform, try uiohook, fallback to periodic or change-detect.
3
3
  // Returns the best available InputHookProvider for the current platform.
4
4
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
5
5
  if (k2 === undefined) k2 = k;
@@ -40,29 +40,50 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
40
40
  Object.defineProperty(exports, "__esModule", { value: true });
41
41
  exports.createInputHookProvider = createInputHookProvider;
42
42
  const logger_1 = __importDefault(require("../../../logger"));
43
- async function createInputHookProvider(periodicIntervalMs) {
44
- // Try uiohook-napi first (works on Windows, macOS, Linux)
43
+ async function createInputHookProvider(optsOrInterval) {
44
+ // Backwards-compatible: accept plain number (periodicIntervalMs) or options object
45
+ const opts = typeof optsOrInterval === 'number'
46
+ ? { intervalMs: optsOrInterval }
47
+ : optsOrInterval || {};
48
+ const mode = opts.mode || 'interaction';
49
+ // Smart or monitor mode → use ChangeDetectProvider (works everywhere, no native hooks)
50
+ if (mode === 'smart' || mode === 'monitor') {
51
+ const { ChangeDetectProvider } = await Promise.resolve().then(() => __importStar(require('./change-detect-provider')));
52
+ const provider = new ChangeDetectProvider({
53
+ interval: (opts.intervalMs || (mode === 'monitor' ? 5000 : 3000)) / 1000,
54
+ changeThreshold: opts.changeThreshold ?? 0.05,
55
+ });
56
+ logger_1.default.info(`[Recording] Using ChangeDetectProvider for ${mode} mode`);
57
+ return { provider, type: 'change-detect' };
58
+ }
59
+ // Periodic mode → use PeriodicProvider
60
+ if (mode === 'periodic') {
61
+ const { PeriodicProvider } = await Promise.resolve().then(() => __importStar(require('./periodic-provider')));
62
+ const provider = new PeriodicProvider(opts.intervalMs || 5000);
63
+ logger_1.default.info('[Recording] Using PeriodicProvider for periodic mode');
64
+ return { provider, type: 'periodic' };
65
+ }
66
+ // Interaction mode → try uiohook-napi first (works on Windows, macOS, Linux)
45
67
  try {
46
- // Verify the native binary can be imported (catches missing/incompatible binaries)
47
68
  await Promise.resolve().then(() => __importStar(require('uiohook-napi')));
48
69
  const { UiohookProvider } = await Promise.resolve().then(() => __importStar(require('./uiohook-provider')));
49
70
  const provider = new UiohookProvider();
50
- // Don't test-start/stop here — on macOS, stopping and restarting a CGEvent tap
51
- // can leave the hook in a broken state. The provider will be started when the
52
- // recording session begins.
53
71
  logger_1.default.info('[Recording] uiohook-napi native binary loaded successfully');
54
72
  return { provider, type: 'uiohook' };
55
73
  }
56
74
  catch (err) {
57
75
  const reason = err instanceof Error ? err.message : String(err);
58
76
  logger_1.default.warn(`[Recording] uiohook-napi unavailable: ${reason}`);
59
- logger_1.default.warn('[Recording] Falling back to periodic capture provider');
60
- // Fallback to periodic timer-based capture
61
- const { PeriodicProvider } = await Promise.resolve().then(() => __importStar(require('./periodic-provider')));
62
- const provider = new PeriodicProvider(periodicIntervalMs || 5000);
77
+ logger_1.default.warn('[Recording] Falling back to ChangeDetectProvider');
78
+ // Fallback to change-detect (smarter than plain periodic)
79
+ const { ChangeDetectProvider } = await Promise.resolve().then(() => __importStar(require('./change-detect-provider')));
80
+ const provider = new ChangeDetectProvider({
81
+ interval: (opts.intervalMs || 3000) / 1000,
82
+ changeThreshold: opts.changeThreshold ?? 0.05,
83
+ });
63
84
  return {
64
85
  provider,
65
- type: 'periodic',
86
+ type: 'change-detect',
66
87
  fallbackReason: reason,
67
88
  };
68
89
  }
@@ -157,11 +157,14 @@ class UiohookProvider {
157
157
  eventCounter = 0;
158
158
  lastLogTime = Date.now();
159
159
  async start() {
160
- // Dynamic import to avoid loading native binary at startup
160
+ // Acquire hook via shared manager (reference-counted — won't kill
161
+ // dictation's listeners when recording stops)
161
162
  if (!this.uiohook) {
162
- this.uiohook = await Promise.resolve().then(() => __importStar(require('uiohook-napi')));
163
+ const { acquire } = await Promise.resolve().then(() => __importStar(require('../../uiohook-manager')));
164
+ this.uiohook = await acquire('recording');
163
165
  }
164
- const { uIOhook } = this.uiohook;
166
+ const mod = this.uiohook;
167
+ const { uIOhook } = mod;
165
168
  // Only register event handlers once — uiohook-napi accumulates listeners
166
169
  // and re-registering causes duplicate events
167
170
  if (!this.handlersRegistered) {
@@ -200,13 +203,14 @@ class UiohookProvider {
200
203
  this.handlersRegistered = true;
201
204
  logger_1.default.info('[uiohook] Event handlers registered');
202
205
  }
203
- uIOhook.start();
204
206
  this.running = true;
205
207
  logger_1.default.info('[uiohook] Hook started, listening for input events');
206
208
  }
207
209
  async stop() {
208
210
  if (this.uiohook && this.running) {
209
- this.uiohook.uIOhook.stop();
211
+ // Release our reference — hook only stops if no other consumer needs it
212
+ const { release } = await Promise.resolve().then(() => __importStar(require('../../uiohook-manager')));
213
+ release('recording');
210
214
  this.running = false;
211
215
  logger_1.default.info('[uiohook] Hook stopped');
212
216
  }
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  // Recording Session — manages the lifecycle of a recording session.
3
3
  // Wires together: InputHookProvider → TriggerEngine → CaptureQueue → Database
4
+ // Works in both Electron (desktop) and headless (Node.js) modes.
4
5
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
5
6
  if (k2 === undefined) k2 = k;
6
7
  var desc = Object.getOwnPropertyDescriptor(m, k);
@@ -38,6 +39,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
38
39
  return (mod && mod.__esModule) ? mod : { "default": mod };
39
40
  };
40
41
  Object.defineProperty(exports, "__esModule", { value: true });
42
+ exports.setMonitorAlertCallback = setMonitorAlertCallback;
43
+ exports.getMonitorAnalyzer = getMonitorAnalyzer;
41
44
  exports.setFrameBroadcast = setFrameBroadcast;
42
45
  exports.getCurrentSession = getCurrentSession;
43
46
  exports.recoverOrphanedSessions = recoverOrphanedSessions;
@@ -49,28 +52,46 @@ exports.resumeCurrentSession = resumeCurrentSession;
49
52
  exports.stopCurrentSession = stopCurrentSession;
50
53
  const path = __importStar(require("path"));
51
54
  const fs = __importStar(require("fs"));
52
- const electron_1 = require("electron");
53
55
  const logger_1 = __importDefault(require("../../logger"));
54
56
  const recording_types_1 = require("../../../shared/recording-types");
55
57
  const trigger_engine_1 = require("./trigger-engine");
56
58
  const capture_queue_1 = require("./capture-queue");
59
+ const monitor_analyzer_1 = require("./monitor-analyzer");
57
60
  const database_1 = require("../../db/database");
58
- const store_1 = require("../store");
61
+ const platform_1 = require("../../core/platform");
59
62
  const active_window_1 = require("../active-window");
60
63
  const constants_1 = require("../../../shared/constants");
64
+ // Platform-aware getSetting: Electron uses electron-store, headless uses json-store
65
+ function getSetting(key) {
66
+ if ((0, platform_1.getPlatform)().isElectron()) {
67
+ const { getSetting: electronGetSetting } = require('../store');
68
+ return electronGetSetting(key);
69
+ }
70
+ const { getSetting: jsonGetSetting } = require('../../core/json-store');
71
+ return jsonGetSetting(key);
72
+ }
61
73
  let currentSession = null;
62
74
  let triggerEngine = null;
63
75
  let captureQueue = null;
64
76
  let hookProvider = null;
77
+ let monitorAnalyzer = null;
65
78
  let focusPollTimer = null;
66
79
  /** Callback for broadcasting frame events to BrowserWindows (set by main.ts) */
67
80
  let onFrameBroadcast = null;
81
+ /** Callback for monitor mode alerts (set by MCP/API layer) */
82
+ let onMonitorAlert = null;
83
+ function setMonitorAlertCallback(cb) {
84
+ onMonitorAlert = cb;
85
+ }
86
+ function getMonitorAnalyzer() {
87
+ return monitorAnalyzer;
88
+ }
68
89
  function setFrameBroadcast(cb) {
69
90
  onFrameBroadcast = cb;
70
91
  }
71
92
  function getSessionsBaseDir() {
72
- const custom = (0, store_1.getSetting)('screenshotFolder');
73
- const baseDir = custom && fs.existsSync(custom) ? custom : path.join(electron_1.app.getPath('userData'), constants_1.CAPTURES_DIR);
93
+ const custom = getSetting('screenshotFolder');
94
+ const baseDir = custom && fs.existsSync(custom) ? custom : path.join((0, platform_1.getPlatform)().getDataDir(), constants_1.CAPTURES_DIR);
74
95
  return path.join(baseDir, 'sessions');
75
96
  }
76
97
  function getCurrentSession() {
@@ -103,10 +124,22 @@ async function startSession(options) {
103
124
  if (currentSession) {
104
125
  throw new Error('A recording session is already active');
105
126
  }
127
+ // Determine recording mode — defaults based on platform
128
+ const isElectron = (0, platform_1.getPlatform)().isElectron();
129
+ const mode = options.mode || (isElectron ? 'interaction' : 'smart');
106
130
  const id = `session_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
107
131
  const config = options.profile === 'custom' && options.config
108
132
  ? options.config
109
133
  : recording_types_1.RECORDING_PROFILES[options.profile] || recording_types_1.RECORDING_PROFILES.automated_test;
134
+ // For smart/periodic/monitor modes, enable periodic trigger and configure interval
135
+ if (mode === 'smart' || mode === 'periodic' || mode === 'monitor') {
136
+ config.triggers.periodic = true;
137
+ config.triggers.periodicInterval = (options.interval || (mode === 'monitor' ? 5 : 3)) * 1000;
138
+ // Smart/monitor use visual change detection in the provider
139
+ if (mode === 'smart' || mode === 'monitor') {
140
+ config.minVisualChangePercent = (options.changeThreshold ?? 0.05) * 100;
141
+ }
142
+ }
110
143
  const sessionDir = path.join(getSessionsBaseDir(), id);
111
144
  fs.mkdirSync(sessionDir, { recursive: true });
112
145
  // Write session config to disk
@@ -137,6 +170,7 @@ async function startSession(options) {
137
170
  startedAt: Date.now(),
138
171
  frameCount: 0,
139
172
  config,
173
+ mode,
140
174
  };
141
175
  // Create capture queue
142
176
  captureQueue = new capture_queue_1.CaptureQueue(config, sessionDir, (frameData) => {
@@ -145,7 +179,7 @@ async function startSession(options) {
145
179
  currentSession.frameCount++;
146
180
  const relativeTime = Date.now() - currentSession.startedAt;
147
181
  // Save to database
148
- (0, database_1.saveRecordingFrame)({
182
+ const captureId = (0, database_1.saveRecordingFrame)({
149
183
  screenshotPath: frameData.framePath,
150
184
  sessionId: currentSession.id,
151
185
  frameNumber: frameData.frameNumber,
@@ -180,6 +214,18 @@ async function startSession(options) {
180
214
  triggerType: frameData.trigger.type,
181
215
  });
182
216
  }
217
+ // Feed frame to monitor analyzer (if in monitor mode)
218
+ if (monitorAnalyzer && currentSession) {
219
+ monitorAnalyzer.onFrame({
220
+ captureId,
221
+ framePath: frameData.framePath,
222
+ frameNumber: frameData.frameNumber,
223
+ sessionId: currentSession.id,
224
+ windowTitle: frameData.windowTitle,
225
+ }).catch((err) => {
226
+ logger_1.default.error('[Recording] Monitor analysis error:', err);
227
+ });
228
+ }
183
229
  });
184
230
  // Create trigger engine (rate limiting via minCaptureInterval is handled here, not in CaptureQueue)
185
231
  triggerEngine = new trigger_engine_1.TriggerEngine({
@@ -212,6 +258,17 @@ async function startSession(options) {
212
258
  }
213
259
  }
214
260
  }, 500);
261
+ // For smart/periodic/monitor modes, create a provider if none is set
262
+ if (!hookProvider && (mode === 'smart' || mode === 'periodic' || mode === 'monitor')) {
263
+ const { createInputHookProvider } = await Promise.resolve().then(() => __importStar(require('./providers/provider-factory')));
264
+ const result = await createInputHookProvider({
265
+ mode,
266
+ intervalMs: (options.interval || (mode === 'monitor' ? 5 : 3)) * 1000,
267
+ changeThreshold: options.changeThreshold ?? 0.05,
268
+ });
269
+ hookProvider = result.provider;
270
+ logger_1.default.info(`[Recording] Created ${result.type} provider for ${mode} mode`);
271
+ }
215
272
  // Wire input hook to trigger engine
216
273
  if (hookProvider) {
217
274
  logger_1.default.info('[Recording] Wiring input hook to trigger engine');
@@ -233,7 +290,17 @@ async function startSession(options) {
233
290
  else {
234
291
  logger_1.default.warn('[Recording] No hook provider available!');
235
292
  }
236
- logger_1.default.info(`[Recording] Session started: ${id} (${options.name})`);
293
+ // Initialize MonitorAnalyzer for monitor mode
294
+ if (mode === 'monitor' && options.monitor) {
295
+ monitorAnalyzer = new monitor_analyzer_1.MonitorAnalyzer(options.monitor, id, (alert) => {
296
+ logger_1.default.info(`[Recording] Monitor alert: frame #${alert.frameNumber} — ${alert.analysis.substring(0, 80)}`);
297
+ if (onMonitorAlert) {
298
+ onMonitorAlert(alert);
299
+ }
300
+ });
301
+ logger_1.default.info('[Recording] MonitorAnalyzer initialized');
302
+ }
303
+ logger_1.default.info(`[Recording] Session started: ${id} (${options.name}, mode=${mode})`);
237
304
  return currentSession;
238
305
  }
239
306
  async function pauseCurrentSession() {
@@ -297,6 +364,11 @@ async function stopCurrentSession() {
297
364
  }
298
365
  currentSession.status = 'completed';
299
366
  const duration = Date.now() - currentSession.startedAt;
367
+ // Clean up monitor analyzer
368
+ if (monitorAnalyzer) {
369
+ monitorAnalyzer.destroy();
370
+ monitorAnalyzer = null;
371
+ }
300
372
  // Clean up capture queue
301
373
  if (captureQueue) {
302
374
  captureQueue.destroy();
@@ -6,8 +6,15 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
6
6
  };
7
7
  Object.defineProperty(exports, "__esModule", { value: true });
8
8
  exports.TriggerEngine = void 0;
9
- const electron_1 = require("electron");
10
9
  const logger_1 = __importDefault(require("../../logger"));
10
+ // Lazy Electron screen — only available in desktop mode (used for DPI scaling)
11
+ let electronScreen = null;
12
+ try {
13
+ electronScreen = require('electron').screen;
14
+ }
15
+ catch {
16
+ // Headless mode — no Electron available
17
+ }
11
18
  // Thresholds
12
19
  const CLICK_POSITION_TOLERANCE = 5;
13
20
  const CLICK_DURATION_MAX = 300;
@@ -482,8 +489,8 @@ class TriggerEngine {
482
489
  // On macOS, uiohook-napi reports CGEvent coordinates in logical points.
483
490
  // On Windows, uiohook uses MSLLHOOKSTRUCT which returns physical pixels
484
491
  // when the process is DPI-aware (Electron's default).
485
- if (trigger.x !== undefined && trigger.y !== undefined && process.platform === 'darwin') {
486
- const scaleFactor = electron_1.screen.getPrimaryDisplay().scaleFactor || 1;
492
+ if (trigger.x !== undefined && trigger.y !== undefined && process.platform === 'darwin' && electronScreen) {
493
+ const scaleFactor = electronScreen.getPrimaryDisplay().scaleFactor || 1;
487
494
  trigger.x = Math.round(trigger.x * scaleFactor);
488
495
  trigger.y = Math.round(trigger.y * scaleFactor);
489
496
  }
@@ -17,7 +17,7 @@ try {
17
17
  name: 'superbased-settings',
18
18
  encryptionKey: 'superbased-v1-key',
19
19
  defaults: {
20
- theme: 'dark',
20
+ theme: 'light',
21
21
  activationShortcut: 'CommandOrControl+Shift+S',
22
22
  autoCloseOverlay: false,
23
23
  autoCloseDelay: 3000,
@@ -40,7 +40,7 @@ try {
40
40
  analyticsOptOut: false,
41
41
  dictationEnabled: true,
42
42
  dictationSettings: {
43
- shortcutModifiers: ['ctrl', 'alt'],
43
+ shortcutModifiers: process.platform === 'darwin' ? ['meta', 'alt'] : ['ctrl', 'alt'],
44
44
  aiCleanup: false,
45
45
  soundFeedback: true,
46
46
  maxDurationSeconds: 120,
@@ -0,0 +1,100 @@
1
+ "use strict";
2
+ // Shared uiohook lifecycle manager — reference-counted start/stop.
3
+ //
4
+ // Both dictation and recording use the same uiohook-napi singleton.
5
+ // Without coordination, recording's stop() kills dictation's listeners.
6
+ // This manager tracks how many consumers need the hook running and only
7
+ // calls the real uIOhook.stop() when the last one releases.
8
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9
+ if (k2 === undefined) k2 = k;
10
+ var desc = Object.getOwnPropertyDescriptor(m, k);
11
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
12
+ desc = { enumerable: true, get: function() { return m[k]; } };
13
+ }
14
+ Object.defineProperty(o, k2, desc);
15
+ }) : (function(o, m, k, k2) {
16
+ if (k2 === undefined) k2 = k;
17
+ o[k2] = m[k];
18
+ }));
19
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
20
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
21
+ }) : function(o, v) {
22
+ o["default"] = v;
23
+ });
24
+ var __importStar = (this && this.__importStar) || (function () {
25
+ var ownKeys = function(o) {
26
+ ownKeys = Object.getOwnPropertyNames || function (o) {
27
+ var ar = [];
28
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
29
+ return ar;
30
+ };
31
+ return ownKeys(o);
32
+ };
33
+ return function (mod) {
34
+ if (mod && mod.__esModule) return mod;
35
+ var result = {};
36
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
37
+ __setModuleDefault(result, mod);
38
+ return result;
39
+ };
40
+ })();
41
+ var __importDefault = (this && this.__importDefault) || function (mod) {
42
+ return (mod && mod.__esModule) ? mod : { "default": mod };
43
+ };
44
+ Object.defineProperty(exports, "__esModule", { value: true });
45
+ exports.acquire = acquire;
46
+ exports.release = release;
47
+ exports.isRunning = isRunning;
48
+ exports.getModule = getModule;
49
+ const logger_1 = __importDefault(require("../logger"));
50
+ let uiohookModule = null;
51
+ const consumers = new Set();
52
+ async function ensureLoaded() {
53
+ if (!uiohookModule) {
54
+ uiohookModule = await Promise.resolve().then(() => __importStar(require('uiohook-napi')));
55
+ }
56
+ return uiohookModule;
57
+ }
58
+ /**
59
+ * Acquire the hook for a named consumer. Starts the native hook if not
60
+ * already running. Returns the uiohook module for event registration.
61
+ */
62
+ async function acquire(consumer) {
63
+ const mod = await ensureLoaded();
64
+ const wasEmpty = consumers.size === 0;
65
+ consumers.add(consumer);
66
+ if (wasEmpty) {
67
+ mod.uIOhook.start();
68
+ logger_1.default.info(`[uiohook-manager] Hook started (consumer: ${consumer})`);
69
+ }
70
+ else {
71
+ logger_1.default.info(`[uiohook-manager] Hook already running, added consumer: ${consumer} (active: ${[...consumers].join(', ')})`);
72
+ }
73
+ return mod;
74
+ }
75
+ /**
76
+ * Release the hook for a named consumer. Only stops the native hook
77
+ * when the last consumer releases.
78
+ */
79
+ function release(consumer) {
80
+ consumers.delete(consumer);
81
+ if (consumers.size === 0 && uiohookModule) {
82
+ uiohookModule.uIOhook.stop();
83
+ logger_1.default.info(`[uiohook-manager] Hook stopped (last consumer: ${consumer})`);
84
+ }
85
+ else {
86
+ logger_1.default.info(`[uiohook-manager] Consumer released: ${consumer} (remaining: ${[...consumers].join(', ') || 'none'})`);
87
+ }
88
+ }
89
+ /**
90
+ * Check if the hook is currently running (any consumer active).
91
+ */
92
+ function isRunning() {
93
+ return consumers.size > 0;
94
+ }
95
+ /**
96
+ * Get the uiohook module without acquiring. Returns null if not loaded.
97
+ */
98
+ function getModule() {
99
+ return uiohookModule;
100
+ }
@@ -38,7 +38,7 @@ exports.DEFAULT_SETTINGS = {
38
38
  aiProvider: 'openai',
39
39
  model: 'gpt-5.4-mini',
40
40
  activationShortcut: exports.DEFAULT_SHORTCUT,
41
- theme: 'dark',
41
+ theme: 'light',
42
42
  autoCloseOverlay: false,
43
43
  autoCloseDelay: 3000,
44
44
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "superbased",
3
- "version": "1.6.1",
3
+ "version": "1.6.2",
4
4
  "main": "dist/electron/main.js",
5
5
  "bin": {
6
6
  "superbased": "./dist/headless/headless/cli.js"
@@ -33,8 +33,8 @@
33
33
  "build:renderer": "webpack --mode production",
34
34
  "build:mcp": "cd mcp-server && npm install && npx tsc",
35
35
  "build:headless": "tsc -p headless/tsconfig.json",
36
- "build": "npm run build:main && npm run build:renderer && npm run build:mcp",
37
- "build:all": "npm run build && npm run build:headless",
36
+ "build": "npm run build:main && npm run build:headless && npm run build:renderer && npm run build:mcp",
37
+ "build:all": "npm run build",
38
38
  "dev:main": "tsc -p tsconfig.json --watch",
39
39
  "dev:renderer": "webpack --mode development --watch",
40
40
  "start": "npm run build && electron .",