Skip to content

Turn meetings into live agent loops. Record, transcribe, and analyze meetings with real-time AI intelligence — before, during, and after calls.

feat: fix abandoned session exports handling

Om Gate0e5a6f5a16d7
diff --git a/package-lock.json b/package-lock.json
index d7ed1e9..e7ed9bc 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -33,7 +33,7 @@
"react-dom": "^19.1.0",
"react-markdown": "^10.1.0",
"uuid": "^11.1.0",
- "videodb": "^0.2.0",
+ "videodb": "^0.2.2",
"zod": "^3.25.4",
"zustand": "^5.0.4"
},
@@ -12227,9 +12227,9 @@
}
},
"node_modules/videodb": {
- "version": "0.2.0",
- "resolved": "https://registry.npmjs.org/videodb/-/videodb-0.2.0.tgz",
- "integrity": "sha512-Gb87/7+Sm9LyRm4nA4f/jwe6Lx5xzJtr+L+9Q2hkqbj0wXryIDrzvXzFaCbc+du9tuaNeMwsUHeA1WNb1lVOww==",
+ "version": "0.2.2",
+ "resolved": "https://registry.npmjs.org/videodb/-/videodb-0.2.2.tgz",
+ "integrity": "sha512-c3gy301vUshrkBXR3ZuuKcCh8TpbUWYmhZIMtIRwRmIFCIby6fIYmwJ6eFNXDs2aFYr0wShg+mJVRPorlpdj5w==",
"hasInstallScript": true,
"license": "Apache-2.0",
"dependencies": {
@@ -12272,9 +12272,9 @@
}
},
"node_modules/videodb/node_modules/tar": {
- "version": "7.5.9",
- "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.9.tgz",
- "integrity": "sha512-BTLcK0xsDh2+PUe9F6c2TlRp4zOOBMTkoQHQIWSIzI0R7KG46uEwq4OPk2W7bZcprBMsuaeFsqwYr7pjh6CuHg==",
+ "version": "7.5.11",
+ "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.11.tgz",
+ "integrity": "sha512-ChjMH33/KetonMTAtpYdgUFr0tbz69Fp2v7zWxQfYZX4g5ZN2nOBXm1R2xyA+lMIKrLKIoKAwFj93jE/avX9cQ==",
"license": "BlueOak-1.0.0",
"dependencies": {
"@isaacs/fs-minipass": "^4.0.0",
diff --git a/package.json b/package.json
index a65dc28..84619c7 100644
--- a/package.json
+++ b/package.json
@@ -51,7 +51,7 @@
"react-dom": "^19.1.0",
"react-markdown": "^10.1.0",
"uuid": "^11.1.0",
- "videodb": "^0.2.0",
+ "videodb": "^0.2.2",
"zod": "^3.25.4",
"zustand": "^5.0.4"
},
diff --git a/src/main/ipc/capture.ts b/src/main/ipc/capture.ts
index e51ce64..0675192 100644
--- a/src/main/ipc/capture.ts
+++ b/src/main/ipc/capture.ts
@@ -4,9 +4,12 @@ import { connect } from 'videodb';
import type { WebSocketConnection, WebSocketMessage } from 'videodb';
import type { Channel } from '../../shared/schemas/capture.schema';
import type { RecorderEvent, TranscriptEvent, StartRecordingParams } from '../../shared/types/ipc.types';
-import { registerSessionUser, setupSessionWebSocket, cleanupSessionWebSocket } from '../services/session-events.service';
+import { setupSessionWebSocket, cleanupSessionWebSocket } from '../services/session-events.service';
+import { startExportPoller, stopExportPoller, stopAllExportPollers } from '../services/export-poller.service';
import { createChildLogger } from '../lib/logger';
import { applyVideoDBPatches } from '../lib/videodb-patch';
+import { loadAppConfig, loadRuntimeConfig } from '../lib/config';
+import { getUserByAccessToken } from '../db';
const logger = createChildLogger('ipc-capture');
@@ -27,6 +30,12 @@ let micWebSocket: WebSocketConnection | null = null;
let sysAudioWebSocket: WebSocketConnection | null = null;
let transcriptListenerActive = false;
+// Track current session for export polling
+let currentSessionId: string | null = null;
+let currentApiKey: string | null = null;
+let currentAccessToken: string | null = null;
+let currentApiUrl: string | undefined = undefined;
+
function ensureVideoDBPatched(): void {
if (!app.isPackaged) return;
try {
@@ -262,9 +271,7 @@ export function setupCaptureHandlers(): void {
logger.info({ sessionId: config.sessionId, enableTranscription }, 'Starting recording - IPC handler called');
try {
- registerSessionUser(config.sessionId, accessToken);
-
- // Set up session WebSocket for capture_session events (exported, etc.)
+ // Set up session WebSocket for capture_session events (informational logging)
const sessionWsId = await setupSessionWebSocket(sessionToken, apiUrl);
if (sessionWsId) {
logger.info({ sessionWsId }, '[WS] Session WebSocket connected for capture events');
@@ -360,10 +367,6 @@ export function setupCaptureHandlers(): void {
throw new Error('No capture channels available. Check permissions.');
}
- if (captureChannels.length === 0) {
- throw new Error('No capture channels available. Check permissions.');
- }
-
logger.info({ captureChannels }, 'Starting capture with channels');
try {
await captureClient.startSession({
@@ -386,6 +389,15 @@ export function setupCaptureHandlers(): void {
});
logger.info({ sessionId: config.sessionId }, 'recording:started event emitted');
+ // Store session info for export polling when recording stops
+ currentSessionId = config.sessionId;
+ currentAccessToken = accessToken;
+ currentApiUrl = apiUrl;
+
+ // Get API key from user record for export polling
+ const user = getUserByAccessToken(accessToken);
+ currentApiKey = user?.apiKey || null;
+
return {
success: true,
sessionId: config.sessionId,
@@ -412,6 +424,12 @@ export function setupCaptureHandlers(): void {
async (): Promise<{ success: boolean; error?: string }> => {
logger.info('Stopping recording');
+ // Capture session info before cleanup
+ const sessionIdForPoller = currentSessionId;
+ const apiKeyForPoller = currentApiKey;
+ const accessTokenForPoller = currentAccessToken;
+ const apiUrlForPoller = currentApiUrl;
+
try {
if (captureClient) {
removeCaptureEventListeners();
@@ -442,12 +460,39 @@ export function setupCaptureHandlers(): void {
await cleanupTranscriptWebSockets();
await cleanupSessionWebSocket();
+ // Start export poller to detect when video is ready
+ // This replaces the unreliable WebSocket-based approach
+ if (sessionIdForPoller && apiKeyForPoller && accessTokenForPoller) {
+ logger.info({ sessionId: sessionIdForPoller }, 'Starting export poller');
+ startExportPoller(
+ sessionIdForPoller,
+ apiKeyForPoller,
+ accessTokenForPoller,
+ apiUrlForPoller
+ );
+ } else {
+ logger.warn('Missing session info for export poller');
+ }
+
+ // Clear stored session info
+ currentSessionId = null;
+ currentApiKey = null;
+ currentAccessToken = null;
+ currentApiUrl = undefined;
+
return { success: true };
} catch (error) {
logger.error({ error }, 'Failed to stop recording');
await cleanupTranscriptWebSockets();
await cleanupSessionWebSocket();
cleanupCapture();
+
+ // Clear stored session info on error too
+ currentSessionId = null;
+ currentApiKey = null;
+ currentAccessToken = null;
+ currentApiUrl = undefined;
+
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error',
@@ -581,6 +626,15 @@ export async function shutdownCaptureClient(): Promise<void> {
await cleanupTranscriptWebSockets();
await cleanupSessionWebSocket();
+ // Stop all export pollers
+ stopAllExportPollers();
+
+ // Clear session tracking
+ currentSessionId = null;
+ currentApiKey = null;
+ currentAccessToken = null;
+ currentApiUrl = undefined;
+
if (captureClient) {
logger.info('Shutting down CaptureClient before app quit');
diff --git a/src/main/server/trpc/procedures/recordings.ts b/src/main/server/trpc/procedures/recordings.ts
index daa830c..afd65a2 100644
--- a/src/main/server/trpc/procedures/recordings.ts
+++ b/src/main/server/trpc/procedures/recordings.ts
@@ -19,6 +19,8 @@ import {
getRecordingById,
} from '../../../db';
import { createChildLogger } from '../../../lib/logger';
+import { loadRuntimeConfig } from '../../../lib/config';
+import { checkAndRecoverSession } from '../../../services/recording-export.service';
const logger = createChildLogger('recordings-procedure');
@@ -154,17 +156,47 @@ export const recordingsRouter = router({
cleanupStale: protectedProcedure
.input(z.object({ maxAgeMinutes: z.number().default(30) }))
- .output(z.object({ cleaned: z.number() }))
- .mutation(async ({ input }) => {
+ .output(z.object({ cleaned: z.number(), recovered: z.number() }))
+ .mutation(async ({ input, ctx }) => {
logger.info({ maxAgeMinutes: input.maxAgeMinutes }, 'Cleaning up stale recordings');
const recordings = getAllRecordings();
const now = Date.now();
const maxAgeMs = input.maxAgeMinutes * 60 * 1000;
let cleaned = 0;
+ let recovered = 0;
+
+ const apiKey = ctx.user?.apiKey;
+ const runtimeConfig = loadRuntimeConfig();
+ const apiUrl = runtimeConfig.apiUrl;
+
+ // Try to recover processing recordings from VideoDB
+ if (apiKey) {
+ const processingRecordings = recordings.filter(
+ r => r.status === 'processing' && !r.videoId
+ );
+
+ for (const recording of processingRecordings) {
+ const result = await checkAndRecoverSession(
+ recording.sessionId,
+ apiKey,
+ apiUrl,
+ true // trigger insights
+ );
+
+ if (result.exported && result.success) {
+ recovered++;
+ logger.info(
+ { recordingId: recording.id, sessionId: recording.sessionId, videoId: result.videoId },
+ 'Recording recovered'
+ );
+ }
+ }
+ }
- for (const recording of recordings) {
- // Only clean up recordings that are stuck AND have no useful data
+ // Mark truly stale recordings as failed
+ const updatedRecordings = getAllRecordings();
+ for (const recording of updatedRecordings) {
if ((recording.status === 'processing' || recording.status === 'recording') && !recording.callSummary) {
const createdAt = new Date(recording.createdAt).getTime();
const age = now - createdAt;
@@ -180,7 +212,7 @@ export const recordingsRouter = router({
}
}
- logger.info({ cleaned }, 'Stale recordings cleanup complete');
- return { cleaned };
+ logger.info({ cleaned, recovered }, 'Stale recordings cleanup complete');
+ return { cleaned, recovered };
}),
});
diff --git a/src/main/services/export-poller.service.ts b/src/main/services/export-poller.service.ts
new file mode 100644
index 0000000..b4072b6
--- /dev/null
+++ b/src/main/services/export-poller.service.ts
@@ -0,0 +1,130 @@
+/**
+ * Export Poller Service
+ *
+ * Polls VideoDB for capture session export completion.
+ * Replaces the unreliable WebSocket-based approach.
+ */
+
+import { createChildLogger } from '../lib/logger';
+import { updateRecordingBySessionId } from '../db';
+import { checkSessionExport, recoverExportedRecording } from './recording-export.service';
+
+const logger = createChildLogger('export-poller');
+
+// Polling configuration
+const POLL_INTERVAL_MS = 3000; // 3 seconds
+const MAX_POLL_DURATION_MS = 30 * 60 * 1000; // 30 minutes max
+
+// Track active pollers
+interface ActivePoller {
+ intervalId: NodeJS.Timeout;
+ startTime: number;
+ apiKey: string;
+ apiUrl?: string;
+}
+
+const activePollers = new Map<string, ActivePoller>();
+
+/**
+ * Start polling for capture session export completion
+ */
+export function startExportPoller(
+ sessionId: string,
+ apiKey: string,
+ _accessToken: string, // Kept for API compatibility, not used
+ apiUrl?: string
+): void {
+ if (activePollers.has(sessionId)) {
+ logger.debug({ sessionId }, 'Poller already active for session');
+ return;
+ }
+
+ logger.info({ sessionId }, 'Starting export poller');
+
+ const startTime = Date.now();
+
+ const pollForExport = async () => {
+ const elapsed = Date.now() - startTime;
+
+ // Check timeout
+ if (elapsed > MAX_POLL_DURATION_MS) {
+ logger.warn({ sessionId, elapsedMs: elapsed }, 'Polling timed out');
+ stopExportPoller(sessionId);
+ updateRecordingBySessionId(sessionId, { status: 'failed' });
+ return;
+ }
+
+ const result = await checkSessionExport(sessionId, apiKey, apiUrl);
+
+ logger.debug(
+ { sessionId, status: result.status, exportedVideoId: result.videoId },
+ 'Polled session status'
+ );
+
+ if (result.exported && result.videoId) {
+ logger.info({ sessionId, exportedVideoId: result.videoId }, 'Session exported!');
+ stopExportPoller(sessionId);
+
+ const recovery = await recoverExportedRecording(
+ sessionId,
+ result.videoId,
+ apiKey,
+ apiUrl,
+ true // trigger insights
+ );
+
+ if (!recovery.success) {
+ logger.error({ sessionId, error: recovery.error }, 'Failed to recover recording');
+ }
+ } else if (result.status === 'failed') {
+ logger.error({ sessionId }, 'Session failed on VideoDB');
+ stopExportPoller(sessionId);
+ updateRecordingBySessionId(sessionId, { status: 'failed' });
+ } else if (result.error) {
+ // Transient error, keep polling
+ logger.debug({ sessionId, error: result.error }, 'Poll error, will retry');
+ }
+ };
+
+ // Poll immediately, then at intervals
+ pollForExport();
+ const intervalId = setInterval(pollForExport, POLL_INTERVAL_MS);
+
+ activePollers.set(sessionId, { intervalId, startTime, apiKey, apiUrl });
+}
+
+/**
+ * Stop the export poller for a session
+ */
+export function stopExportPoller(sessionId: string): void {
+ const poller = activePollers.get(sessionId);
+ if (poller) {
+ clearInterval(poller.intervalId);
+ activePollers.delete(sessionId);
+ logger.debug({ sessionId }, 'Stopped poller');
+ }
+}
+
+/**
+ * Stop all active pollers (for app shutdown)
+ */
+export function stopAllExportPollers(): void {
+ for (const [sessionId] of activePollers) {
+ stopExportPoller(sessionId);
+ }
+ logger.info({ count: activePollers.size }, 'All pollers stopped');
+}
+
+/**
+ * Check if a poller is active for a session
+ */
+export function isPollerActive(sessionId: string): boolean {
+ return activePollers.has(sessionId);
+}
+
+/**
+ * Get count of active pollers
+ */
+export function getActivePollerCount(): number {
+ return activePollers.size;
+}
diff --git a/src/main/services/recording-export.service.ts b/src/main/services/recording-export.service.ts
new file mode 100644
index 0000000..48b12ca
--- /dev/null
+++ b/src/main/services/recording-export.service.ts
@@ -0,0 +1,175 @@
+/**
+ * Recording Export Service
+ *
+ * Centralized service for handling capture session exports.
+ * Used by:
+ * - Export poller (real-time polling after recording stops)
+ * - Session recovery (startup recovery for missed exports)
+ * - Cleanup stale (on-demand recovery check)
+ */
+
+import { connect } from 'videodb';
+import type { CaptureSessionFull } from 'videodb';
+import { createChildLogger } from '../lib/logger';
+import { updateRecordingBySessionId } from '../db';
+import { createInsightsService } from './insights.service';
+
+const logger = createChildLogger('recording-export');
+
+export interface ExportCheckResult {
+ exported: boolean;
+ videoId?: string;
+ status?: string;
+ error?: string;
+}
+
+export interface ExportRecoveryResult {
+ success: boolean;
+ recordingId?: number;
+ videoId?: string;
+ error?: string;
+}
+
+/**
+ * Check if a capture session has exported
+ */
+export async function checkSessionExport(
+ sessionId: string,
+ apiKey: string,
+ apiUrl?: string
+): Promise<ExportCheckResult> {
+ try {
+ const conn = connect(apiUrl ? { apiKey, baseUrl: apiUrl } : { apiKey });
+ const session: CaptureSessionFull = await conn.getCaptureSession(sessionId);
+ await session.refresh();
+
+ return {
+ exported: !!session.exportedVideoId,
+ videoId: session.exportedVideoId,
+ status: session.status,
+ };
+ } catch (error) {
+ const errorMsg = error instanceof Error ? error.message : String(error);
+ logger.debug({ sessionId, error: errorMsg }, 'Failed to check session export status');
+ return {
+ exported: false,
+ error: errorMsg,
+ };
+ }
+}
+
+/**
+ * Recover a recording that has exported on VideoDB
+ * Updates the local database and triggers insights processing
+ */
+export async function recoverExportedRecording(
+ sessionId: string,
+ videoId: string,
+ apiKey: string,
+ apiUrl?: string,
+ triggerInsights: boolean = true
+): Promise<ExportRecoveryResult> {
+ try {
+ const conn = connect(apiUrl ? { apiKey, baseUrl: apiUrl } : { apiKey });
+ const collection = await conn.getCollection();
+ const video = await collection.getVideo(videoId);
+
+ // Parse duration from video.length
+ let duration: number | null = null;
+ if (video.length) {
+ const parsed = parseFloat(video.length);
+ if (!isNaN(parsed)) {
+ duration = Math.round(parsed);
+ }
+ }
+
+ // Update recording in database
+ const recording = updateRecordingBySessionId(sessionId, {
+ videoId,
+ streamUrl: video.streamUrl || null,
+ playerUrl: video.playerUrl || null,
+ duration,
+ status: 'available',
+ insightsStatus: 'pending',
+ });
+
+ if (!recording) {
+ return {
+ success: false,
+ error: 'Recording not found in database',
+ };
+ }
+
+ logger.info(
+ {
+ sessionId,
+ recordingId: recording.id,
+ videoId,
+ streamUrl: video.streamUrl,
+ playerUrl: video.playerUrl,
+ duration,
+ },
+ 'Recording recovered with video info'
+ );
+
+ // Trigger insights processing (fire and forget)
+ if (triggerInsights) {
+ const insightsService = createInsightsService(apiKey, apiUrl);
+ insightsService
+ .processRecording(recording.id, videoId)
+ .then((result) => {
+ logger.info({ recordingId: recording.id, result }, 'Insights processing completed');
+ })
+ .catch((err) => {
+ logger.error({ error: err, recordingId: recording.id }, 'Insights processing failed');
+ });
+ }
+
+ return {
+ success: true,
+ recordingId: recording.id,
+ videoId,
+ };
+ } catch (error) {
+ const errorMsg = error instanceof Error ? error.message : String(error);
+ logger.error({ sessionId, videoId, error: errorMsg }, 'Failed to recover exported recording');
+ return {
+ success: false,
+ error: errorMsg,
+ };
+ }
+}
+
+/**
+ * Check and recover a session in one call
+ * Convenience method that combines checkSessionExport + recoverExportedRecording
+ */
+export async function checkAndRecoverSession(
+ sessionId: string,
+ apiKey: string,
+ apiUrl?: string,
+ triggerInsights: boolean = true
+): Promise<ExportRecoveryResult & { exported: boolean }> {
+ const checkResult = await checkSessionExport(sessionId, apiKey, apiUrl);
+
+ if (!checkResult.exported || !checkResult.videoId) {
+ return {
+ exported: false,
+ success: false,
+ error: checkResult.error || 'Not exported yet',
+ };
+ }
+
+ const recoveryResult = await recoverExportedRecording(
+ sessionId,
+ checkResult.videoId,
+ apiKey,
+ apiUrl,
+ triggerInsights
+ );
+
+ return {
+ exported: true,
+ ...recoveryResult,
+ };
+}
diff --git a/src/main/services/session-events.service.ts b/src/main/services/session-events.service.ts
index b587d8a..4ada00e 100644
--- a/src/main/services/session-events.service.ts
+++ b/src/main/services/session-events.service.ts
@@ -1,26 +1,12 @@
import { connect } from 'videodb';
import type { WebSocketConnection } from 'videodb';
import { createChildLogger } from '../lib/logger';
-import { updateRecordingBySessionId, getUserByAccessToken } from '../db';
-import { createInsightsService } from './insights.service';
const logger = createChildLogger('session-events');
let sessionWebSocket: WebSocketConnection | null = null;
let sessionListenerActive = false;
-// Map session IDs to access tokens for user lookup when export completes
-const sessionUserMap = new Map<string, string>();
-
-/**
- * Register a session with its user's access token.
- * Called when recording starts so we can look up the user when export completes.
- */
-export function registerSessionUser(sessionId: string, accessToken: string): void {
- sessionUserMap.set(sessionId, accessToken);
- logger.debug({ sessionId }, 'Registered session user mapping');
-}
-
/**
* Set up WebSocket connection to receive capture session lifecycle events.
* This replaces the webhook-based approach that required cloudflared tunnel.
@@ -78,10 +64,13 @@ async function listenForSessionEvents(ws: WebSocketConnection): Promise<void> {
logger.info({ event, sessionId, status }, '[SessionWS] Session event received');
+ // Note: We no longer rely on WebSocket for export detection.
+ // Export completion is handled by the export-poller.service.ts which polls the API.
+ // These events are kept for informational logging only.
switch (event) {
case 'capture_session.exported': {
- logger.info({ sessionId, data }, '[SessionWS] Processing capture_session.exported');
- await handleCaptureSessionExported(sessionId, data);
+ // Informational only - actual handling is done by export poller
+ logger.info({ sessionId, data }, '[SessionWS] Received capture_session.exported (handled by poller)');
break;
}
@@ -96,7 +85,7 @@ async function listenForSessionEvents(ws: WebSocketConnection): Promise<void> {
}
case 'capture_session.stopped': {
- logger.info({ sessionId }, '[SessionWS] Capture session stopped, waiting for export');
+ logger.info({ sessionId }, '[SessionWS] Capture session stopped, export poller will detect completion');
break;
}
@@ -128,113 +117,6 @@ async function listenForSessionEvents(ws: WebSocketConnection): Promise<void> {
}
}
-/**
- * Handle the capture_session.exported event.
- * Updates the recording with video info and triggers insights processing.
- */
-async function handleCaptureSessionExported(
- sessionId: string,
- data: Record<string, unknown>
-): Promise<void> {
- logger.info({ sessionId, data }, '[SessionWS] handleCaptureSessionExported called');
-
- if (!data) {
- logger.warn({ sessionId }, '[SessionWS] No data in capture_session.exported event');
- return;
- }
-
- logger.info({ sessionId, dataKeys: Object.keys(data) }, '[SessionWS] Data keys available');
-
- // Extract video info from the event data
- const videoId = data.exported_video_id as string | undefined;
- const streamUrl = data.stream_url as string | undefined;
- const playerUrl = data.player_url as string | undefined;
- const duration = data.duration as number | undefined;
-
- logger.info(
- { sessionId, videoId, streamUrl, playerUrl, duration },
- '[SessionWS] Extracted data from payload'
- );
-
- if (!videoId) {
- logger.warn(
- { sessionId, data },
- '[SessionWS] No exported_video_id in capture_session.exported event'
- );
- return;
- }
-
- logger.info({ sessionId, videoId }, '[SessionWS] Processing capture session export');
-
- const recording = updateRecordingBySessionId(sessionId, {
- videoId,
- streamUrl: streamUrl || null,
- playerUrl: playerUrl || null,
- duration: duration || null,
- status: 'available',
- insightsStatus: 'pending',
- });
-
- if (!recording) {
- logger.warn({ sessionId }, '[SessionWS] Recording not found for session');
- return;
- }
-
- logger.info(
- {
- recordingId: recording.id,
- videoId,
- status: recording.status,
- insightsStatus: recording.insightsStatus,
- },
- '[SessionWS] Recording updated with video info'
- );
-
- const accessToken = sessionUserMap.get(sessionId);
- logger.info(
- {
- sessionId,
- hasAccessToken: !!accessToken,
- sessionUserMapSize: sessionUserMap.size,
- },
- '[SessionWS] Looking up user for session'
- );
-
- if (!accessToken) {
- logger.warn({ sessionId }, '[SessionWS] No user mapping found for session, skipping insights');
- return;
- }
-
- const user = getUserByAccessToken(accessToken);
- if (!user) {
- logger.warn({ sessionId }, '[SessionWS] User not found for session, skipping insights');
- return;
- }
-
- logger.info(
- { sessionId, userId: user.id, userName: user.name },
- '[SessionWS] Starting insights processing'
- );
-
- const insightsService = createInsightsService(user.apiKey);
-
- // Fire and forget - don't await
- insightsService
- .processRecording(recording.id, videoId)
- .then((result) => {
- logger.info({ recordingId: recording.id, result }, '[SessionWS] Insights processing completed');
- })
- .catch((error) => {
- logger.error(
- { error, recordingId: recording.id },
- '[SessionWS] Background insights processing failed'
- );
- });
-
- sessionUserMap.delete(sessionId);
- logger.info({ sessionId }, '[SessionWS] Session user mapping cleaned up');
-}
-
/**
* Clean up the session WebSocket connection.
* Called when recording stops or app shuts down.
diff --git a/src/main/services/session-recovery.service.ts b/src/main/services/session-recovery.service.ts
index 0f1d413..d007e14 100644
--- a/src/main/services/session-recovery.service.ts
+++ b/src/main/services/session-recovery.service.ts
@@ -1,238 +1,83 @@
-import { connect } from 'videodb';
+/**
+ * Session Recovery Service
+ *
+ * Recovers recordings that were exported by VideoDB while the app was closed.
+ * Called on app startup to handle missed exports.
+ */
+
import { createChildLogger } from '../lib/logger';
-import { getAllRecordings, updateRecordingBySessionId } from '../db';
-import { createInsightsService } from './insights.service';
+import { getAllRecordings } from '../db';
+import { checkAndRecoverSession } from './recording-export.service';
const logger = createChildLogger('session-recovery');
-interface RecoveryDetail {
- sessionId: string;
- status: 'recovered' | 'failed' | 'skipped';
- reason?: string;
-}
-
export interface RecoveryResult {
recovered: number;
failed: number;
skipped: number;
- details: RecoveryDetail[];
}
/**
- * Service to recover recordings that were exported by VideoDB while the app was closed.
- *
- * When the app is closed during the export process, the WebSocket listener is terminated
- * and the `capture_session.exported` event is missed. This service checks VideoDB for
- * any sessions that have completed export and updates the local database accordingly.
+ * Recover any recordings stuck in 'processing' status
*/
-export class SessionRecoveryService {
- private apiKey: string;
- private baseUrl?: string;
-
- constructor(apiKey: string, baseUrl?: string) {
- this.apiKey = apiKey;
- this.baseUrl = baseUrl;
+export async function recoverPendingSessions(
+ apiKey: string,
+ apiUrl?: string
+): Promise<RecoveryResult> {
+ const result: RecoveryResult = {
+ recovered: 0,
+ failed: 0,
+ skipped: 0,
+ };
+
+ const allRecordings = getAllRecordings();
+ const pendingRecordings = allRecordings.filter(
+ r => r.status === 'processing' && !r.videoId
+ );
+
+ if (pendingRecordings.length === 0) {
+ logger.debug('No pending recordings to recover');
+ return result;
}
- /**
- * Recover any recordings stuck in 'processing' status.
- * Called on app startup to handle sessions that exported while app was closed.
- */
- async recoverPendingSessions(): Promise<RecoveryResult> {
- const result: RecoveryResult = {
- recovered: 0,
- failed: 0,
- skipped: 0,
- details: [],
- };
+ logger.info({ count: pendingRecordings.length }, 'Found pending recordings to recover');
- try {
- // 1. Get all recordings stuck in 'processing'
- const allRecordings = getAllRecordings();
- const pendingRecordings = allRecordings.filter(
- r => r.status === 'processing'
- );
-
- if (pendingRecordings.length === 0) {
- logger.info('No pending recordings to recover');
- return result;
- }
+ for (const recording of pendingRecordings) {
+ const recovery = await checkAndRecoverSession(
+ recording.sessionId,
+ apiKey,
+ apiUrl,
+ true // trigger insights
+ );
+ if (recovery.exported && recovery.success) {
+ result.recovered++;
logger.info(
- { count: pendingRecordings.length },
- 'Found pending recordings to recover'
+ { sessionId: recording.sessionId, videoId: recovery.videoId },
+ 'Recording recovered'
);
-
- // 2. Connect to VideoDB and list capture sessions
- const conn = this.baseUrl
- ? connect({ apiKey: this.apiKey, baseUrl: this.baseUrl })
- : connect({ apiKey: this.apiKey });
-
- const collection = await conn.getCollection();
-
- // Fetch all capture sessions
- const captureSessions = await collection.listCaptureSessions();
-
- logger.info(
- { totalSessions: captureSessions.length },
- 'Fetched capture sessions from VideoDB'
+ } else if (recovery.exported && !recovery.success) {
+ result.failed++;
+ logger.error(
+ { sessionId: recording.sessionId, error: recovery.error },
+ 'Failed to recover exported recording'
);
-
- // Build a map of sessionId -> captureSession for quick lookup
- const sessionMap = new Map(
- captureSessions.map(s => [s.id, s])
+ } else {
+ result.skipped++;
+ logger.debug(
+ { sessionId: recording.sessionId },
+ 'Recording not exported yet, skipping'
);
-
- // 3. Process each pending recording
- for (const recording of pendingRecordings) {
- const captureSession = sessionMap.get(recording.sessionId);
-
- if (!captureSession) {
- // Session not found in VideoDB - might be too old or different collection
- result.skipped++;
- result.details.push({
- sessionId: recording.sessionId,
- status: 'skipped',
- reason: 'Session not found in VideoDB',
- });
- logger.debug(
- { sessionId: recording.sessionId },
- 'Session not found in VideoDB, skipping'
- );
- continue;
- }
-
- if (!captureSession.exportedVideoId) {
- // Session exists but hasn't exported yet - still processing server-side
- result.skipped++;
- result.details.push({
- sessionId: recording.sessionId,
- status: 'skipped',
- reason: `Session status: ${captureSession.status}, no exportedVideoId yet`,
- });
- logger.debug(
- { sessionId: recording.sessionId, status: captureSession.status },
- 'Session has no exportedVideoId yet, skipping'
- );
- continue;
- }
-
- // 4. Session has exported! Fetch video details
- try {
- logger.info(
- { sessionId: recording.sessionId, exportedVideoId: captureSession.exportedVideoId },
- 'Recovering session with exported video'
- );
-
- const video = await collection.getVideo(captureSession.exportedVideoId);
-
- // Parse duration from video.length (it's a string like "123.45")
- let duration: number | null = null;
- if (video.length) {
- const parsed = parseFloat(video.length);
- if (!isNaN(parsed)) {
- duration = Math.round(parsed);
- }
- }
-
- // 5. Update the recording in DB
- const updated = updateRecordingBySessionId(recording.sessionId, {
- videoId: captureSession.exportedVideoId,
- streamUrl: video.streamUrl || null,
- playerUrl: video.playerUrl || null,
- duration,
- status: 'available',
- insightsStatus: 'pending',
- });
-
- if (updated) {
- logger.info(
- {
- sessionId: recording.sessionId,
- recordingId: updated.id,
- videoId: captureSession.exportedVideoId,
- streamUrl: video.streamUrl,
- playerUrl: video.playerUrl,
- },
- 'Recording recovered successfully'
- );
-
- result.recovered++;
- result.details.push({
- sessionId: recording.sessionId,
- status: 'recovered',
- });
-
- // 6. Kick off insights processing (fire and forget)
- this.triggerInsightsProcessing(
- updated.id,
- captureSession.exportedVideoId
- );
- } else {
- logger.warn(
- { sessionId: recording.sessionId },
- 'Failed to update recording in database'
- );
- result.failed++;
- result.details.push({
- sessionId: recording.sessionId,
- status: 'failed',
- reason: 'Database update returned null',
- });
- }
- } catch (error) {
- const errorMsg = error instanceof Error ? error.message : String(error);
- logger.error(
- { sessionId: recording.sessionId, error: errorMsg },
- 'Failed to recover recording'
- );
-
- result.failed++;
- result.details.push({
- sessionId: recording.sessionId,
- status: 'failed',
- reason: errorMsg,
- });
- }
- }
-
- logger.info(
- { recovered: result.recovered, failed: result.failed, skipped: result.skipped },
- 'Session recovery complete'
- );
- return result;
-
- } catch (error) {
- const errorMsg = error instanceof Error ? error.message : String(error);
- logger.error({ error: errorMsg }, 'Session recovery failed');
- throw error;
}
}
- private triggerInsightsProcessing(recordingId: number, videoId: string): void {
- const insightsService = createInsightsService(this.apiKey, this.baseUrl);
-
- insightsService
- .processRecording(recordingId, videoId)
- .then((result) => {
- logger.info(
- { recordingId, success: result.success },
- 'Insights processing completed for recovered recording'
- );
- })
- .catch((error) => {
- const errorMsg = error instanceof Error ? error.message : String(error);
- logger.error(
- { error: errorMsg, recordingId },
- 'Insights processing failed for recovered recording'
- );
- });
- }
+ logger.info(result, 'Session recovery complete');
+ return result;
}
-export function createSessionRecoveryService(
- apiKey: string,
- baseUrl?: string
-): SessionRecoveryService {
- return new SessionRecoveryService(apiKey, baseUrl);
+// Factory function for backward compatibility
+export function createSessionRecoveryService(apiKey: string, apiUrl?: string) {
+ return {
+ recoverPendingSessions: () => recoverPendingSessions(apiKey, apiUrl),
+ };
}
diff --git a/src/types/videodb.d.ts b/src/types/videodb.d.ts
index 20eccee..fa7b6b3 100644
--- a/src/types/videodb.d.ts
+++ b/src/types/videodb.d.ts
@@ -98,7 +98,9 @@ declare module 'videodb' {
endUserId?: string;
callbackUrl?: string;
metadata?: Record<string, unknown>;
+ exportedVideoId?: string;
rtstreams: RTStream[];
+ createdAt?: number;
refresh(): Promise<void>;
getRTStream(category: RTStreamCategory): RTStream[];
}
diff --git a/videodb-recorder b/videodb-recorder
new file mode 100644
index 0000000..e69de29