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: stop recordings automatically at the 2 hour mark

codeashufdbfd46f4546
diff --git a/README.md b/README.md
index a53144d..ad713a8 100644
--- a/README.md
+++ b/README.md
@@ -104,6 +104,7 @@ Call.md turns meetings into live agent loops. It records locally, transcribes in
- **Google Calendar Integration** - Sync upcoming meetings
### Privacy & Storage
+- **2 Hour Recording Limit** - Recordings stop themselves after 2 hours of recording time, with a warning 5 minutes before
- **Local-First** - SQLite database, all data stored on your machine
- **Screen & Audio Recording** - Capture screen, microphone, and system audio simultaneously
- **Recording History** - Browse and review past recordings with full transcripts
@@ -311,6 +312,15 @@ Grant these in **System Preferences > Privacy & Security**.
- Wait 5-10 seconds for first transcripts
- Check internet connectivity
+**A recording stopped on its own:**
+- Recordings are capped at 2 hours and stop automatically when they reach it.
+ You get a system notification 5 minutes before, and the recording is saved
+ and summarised exactly as if you had pressed Stop
+- Paused time does not count toward the limit, so the cutoff matches the
+ elapsed timer shown during the meeting
+- To change the cap, edit `MAX_RECORDING_DURATION_MS` in
+ `src/shared/constants/recording.ts` and rebuild
+
**Transcription is in the wrong language:**
- Set the meeting language in **Settings → Transcription** (it applies to the
next recording, not one already in progress)
diff --git a/src/main/ipc/capture.ts b/src/main/ipc/capture.ts
index 43caa37..196a4af 100644
--- a/src/main/ipc/capture.ts
+++ b/src/main/ipc/capture.ts
@@ -20,9 +20,23 @@ import {
updateWidgetVisualAnalysis,
clearWidgetState,
} from './widget';
+import {
+ startRecordingLimit,
+ pauseRecordingLimit,
+ resumeRecordingLimit,
+ clearRecordingLimit,
+} from '../services/recording-limit.service';
+import {
+ MAX_RECORDING_DURATION_MS,
+ RECORDING_LIMIT_STOP_GRACE_MS,
+} from '../../shared/constants/recording';
const logger = createChildLogger('ipc-capture');
+/** Tracks that make up the whole session, in the order the renderer sends them. */
+const ALL_TRACKS = ['mic', 'system_audio', 'screen'] as const;
+type TrackName = (typeof ALL_TRACKS)[number];
+
let mainWindow: BrowserWindow | null = null;
let captureClient: CaptureClient | null = null;
@@ -374,10 +388,67 @@ function removeCaptureEventListeners(): void {
});
}
+/**
+ * Whether a pause/resume call covers the whole session rather than one stream.
+ *
+ * The renderer uses the same IPC for both: the pause button sends every track,
+ * while toggling a single stream sends just that one. Only the former should
+ * pause the recording-length clock.
+ */
+function isFullSessionToggle(tracks: string[]): boolean {
+ const requested = new Set(tracks);
+ return requested.size === ALL_TRACKS.length && ALL_TRACKS.every((track) => requested.has(track));
+}
+
+/**
+ * Arms the recording-length cutoff for the session that just started.
+ *
+ * The stop itself is handed to the renderer, because its stop path also
+ * finalises the recording, generates the meeting summary and resets the
+ * session stores - none of which happen if the capture client is simply torn
+ * down here. If no renderer picks it up (window closed), the fallback below
+ * stops the capture anyway so a recording can never run past the limit.
+ */
+function armRecordingLimit(): void {
+ startRecordingLimit({
+ onWarning: (msRemaining) => {
+ sendRecorderEvent({
+ event: 'recording:limit-warning',
+ data: { msRemaining, limitMs: MAX_RECORDING_DURATION_MS },
+ });
+ },
+
+ onLimitReached: () => {
+ const limitedSessionId = currentSessionId;
+
+ sendRecorderEvent({
+ event: 'recording:limit-reached',
+ data: { limitMs: MAX_RECORDING_DURATION_MS },
+ });
+
+ setTimeout(() => {
+ // Stop only if this exact session is still running: the renderer may
+ // already have stopped it, and the user may have started a new one.
+ if (!captureClient || currentSessionId !== limitedSessionId) return;
+
+ logger.warn(
+ { sessionId: limitedSessionId, graceMs: RECORDING_LIMIT_STOP_GRACE_MS },
+ 'Renderer did not stop the recording at the limit, stopping from the main process'
+ );
+ stopRecordingInternal().catch((error) => {
+ logger.error({ error }, 'Fallback stop at the recording limit failed');
+ });
+ }, RECORDING_LIMIT_STOP_GRACE_MS);
+ },
+ });
+}
+
// Function to stop recording (used by widget and IPC handler)
async function stopRecordingInternal(): Promise<{ success: boolean; error?: string }> {
logger.info('Stopping recording (internal)');
+ clearRecordingLimit();
+
// Capture session info before cleanup
const sessionIdForPoller = currentSessionId;
const apiKeyForPoller = currentApiKey;
@@ -468,13 +539,15 @@ export function setupCaptureHandlers(): void {
// pause
async () => {
if (captureClient) {
- await captureClient.pauseTracks(['mic', 'system_audio', 'screen'] as ('mic' | 'system_audio' | 'screen')[]);
+ await captureClient.pauseTracks([...ALL_TRACKS] as TrackName[]);
+ pauseRecordingLimit();
}
},
// resume
async () => {
if (captureClient) {
- await captureClient.resumeTracks(['mic', 'system_audio', 'screen'] as ('mic' | 'system_audio' | 'screen')[]);
+ await captureClient.resumeTracks([...ALL_TRACKS] as TrackName[]);
+ resumeRecordingLimit();
}
},
// stop
@@ -638,6 +711,9 @@ export function setupCaptureHandlers(): void {
throw captureError;
}
+ // Cut the recording off once it reaches the maximum length
+ armRecordingLimit();
+
// Manually emit recording:started immediately (matches Python behavior, doesn't wait for SDK event)
logger.info({ sessionId: config.sessionId }, 'Emitting recording:started event to renderer');
sendRecorderEvent({
@@ -699,7 +775,12 @@ export function setupCaptureHandlers(): void {
'recorder-pause-tracks',
async (_event, tracks: string[]): Promise<void> => {
if (captureClient) {
- await captureClient.pauseTracks(tracks as ('mic' | 'system_audio' | 'screen')[]);
+ await captureClient.pauseTracks(tracks as TrackName[]);
+
+ // Pausing a single stream is not pausing the meeting.
+ if (isFullSessionToggle(tracks)) {
+ pauseRecordingLimit();
+ }
}
}
);
@@ -708,7 +789,11 @@ export function setupCaptureHandlers(): void {
'recorder-resume-tracks',
async (_event, tracks: string[]): Promise<void> => {
if (captureClient) {
- await captureClient.resumeTracks(tracks as ('mic' | 'system_audio' | 'screen')[]);
+ await captureClient.resumeTracks(tracks as TrackName[]);
+
+ if (isFullSessionToggle(tracks)) {
+ resumeRecordingLimit();
+ }
}
}
);
@@ -787,6 +872,8 @@ export function setupCaptureHandlers(): void {
// Cleanup capture client for synchronous cleanup (doesn't wait for shutdown)
function cleanupCapture(): void {
+ clearRecordingLimit();
+
if (captureClient) {
removeCaptureEventListeners();
@@ -801,6 +888,8 @@ function cleanupCapture(): void {
// Async cleanup that waits for shutdown to complete (for tests or external cleanup)
export async function cleanupCaptureAsync(): Promise<void> {
+ clearRecordingLimit();
+
if (captureClient) {
removeCaptureEventListeners();
diff --git a/src/main/services/recording-limit.service.ts b/src/main/services/recording-limit.service.ts
new file mode 100644
index 0000000..54fc0f8
--- /dev/null
+++ b/src/main/services/recording-limit.service.ts
@@ -0,0 +1,174 @@
+/**
+ * Recording Limit Service
+ *
+ * Enforces the maximum recording length. Counts recording time only: pausing
+ * banks the elapsed total and stops the clock, so the cutoff matches the timer
+ * the user sees rather than wall-clock time.
+ *
+ * Lives in the main process so the deadline survives a hidden window, where
+ * Chromium throttles renderer timers.
+ */
+
+import { createChildLogger } from '../lib/logger';
+import {
+ MAX_RECORDING_DURATION_MS,
+ RECORDING_LIMIT_WARNING_MS,
+} from '../../shared/constants/recording';
+
+const logger = createChildLogger('recording-limit');
+
+export interface RecordingLimitCallbacks {
+ /** Called once, `RECORDING_LIMIT_WARNING_MS` before the cutoff. */
+ onWarning: (msRemaining: number) => void;
+ /** Called when the limit is reached. */
+ onLimitReached: () => void;
+}
+
+interface LimitState {
+ callbacks: RecordingLimitCallbacks;
+ /** Recording time banked from segments that have already ended. */
+ accumulatedMs: number;
+ /** When the current segment started, or null while paused. */
+ segmentStartedAt: number | null;
+ warningTimer: NodeJS.Timeout | null;
+ cutoffTimer: NodeJS.Timeout | null;
+ warningFired: boolean;
+}
+
+let state: LimitState | null = null;
+
+/** Recording time counted so far, in ms. */
+function getElapsedMs(current: LimitState): number {
+ // null means paused - compare explicitly, a timestamp of 0 is falsy.
+ const openSegment =
+ current.segmentStartedAt !== null ? Date.now() - current.segmentStartedAt : 0;
+ return current.accumulatedMs + openSegment;
+}
+
+function clearTimers(current: LimitState): void {
+ if (current.warningTimer) clearTimeout(current.warningTimer);
+ if (current.cutoffTimer) clearTimeout(current.cutoffTimer);
+ current.warningTimer = null;
+ current.cutoffTimer = null;
+}
+
+/**
+ * (Re)arms the warning and cutoff timers from the time recorded so far.
+ *
+ * Timers do not advance while the machine is asleep, so the cutoff re-checks
+ * the real elapsed time when it fires and re-arms if it woke up early.
+ */
+function armTimers(current: LimitState): void {
+ clearTimers(current);
+
+ const remainingMs = MAX_RECORDING_DURATION_MS - getElapsedMs(current);
+
+ if (remainingMs <= 0) {
+ fireLimit(current);
+ return;
+ }
+
+ const warningDelay = remainingMs - RECORDING_LIMIT_WARNING_MS;
+ if (!current.warningFired && warningDelay > 0) {
+ current.warningTimer = setTimeout(() => {
+ if (state !== current) return;
+ current.warningFired = true;
+ current.warningTimer = null;
+
+ const msRemaining = MAX_RECORDING_DURATION_MS - getElapsedMs(current);
+ logger.info({ msRemaining }, 'Recording approaching the maximum length');
+ current.callbacks.onWarning(msRemaining);
+ }, warningDelay);
+ }
+
+ current.cutoffTimer = setTimeout(() => {
+ if (state !== current) return;
+ current.cutoffTimer = null;
+
+ // The machine may have slept; only stop once the time is genuinely used up.
+ const stillRemaining = MAX_RECORDING_DURATION_MS - getElapsedMs(current);
+ if (stillRemaining > 0) {
+ logger.debug({ stillRemaining }, 'Cutoff timer fired early, re-arming');
+ armTimers(current);
+ return;
+ }
+
+ fireLimit(current);
+ }, remainingMs);
+}
+
+function fireLimit(current: LimitState): void {
+ clearTimers(current);
+ logger.info(
+ { elapsedMs: getElapsedMs(current), limitMs: MAX_RECORDING_DURATION_MS },
+ 'Recording reached the maximum length, stopping'
+ );
+ current.callbacks.onLimitReached();
+}
+
+/**
+ * Starts tracking a new recording. Replaces any previous tracker.
+ */
+export function startRecordingLimit(callbacks: RecordingLimitCallbacks): void {
+ clearRecordingLimit();
+
+ const current: LimitState = {
+ callbacks,
+ accumulatedMs: 0,
+ segmentStartedAt: Date.now(),
+ warningTimer: null,
+ cutoffTimer: null,
+ warningFired: false,
+ };
+
+ state = current;
+ armTimers(current);
+
+ logger.info({ limitMs: MAX_RECORDING_DURATION_MS }, 'Recording limit armed');
+}
+
+/** Stops the clock while the recording is paused. */
+export function pauseRecordingLimit(): void {
+ const current = state;
+ if (!current || current.segmentStartedAt === null) return;
+
+ current.accumulatedMs = getElapsedMs(current);
+ current.segmentStartedAt = null;
+ clearTimers(current);
+
+ logger.info({ elapsedMs: current.accumulatedMs }, 'Recording limit paused');
+}
+
+/** Restarts the clock after a pause. */
+export function resumeRecordingLimit(): void {
+ const current = state;
+ if (!current || current.segmentStartedAt !== null) return;
+
+ current.segmentStartedAt = Date.now();
+ armTimers(current);
+
+ logger.info(
+ { remainingMs: MAX_RECORDING_DURATION_MS - getElapsedMs(current) },
+ 'Recording limit resumed'
+ );
+}
+
+/** Clears the tracker. Safe to call when nothing is being tracked. */
+export function clearRecordingLimit(): void {
+ if (!state) return;
+
+ clearTimers(state);
+ state = null;
+ logger.debug('Recording limit cleared');
+}
+
+/** Recording time left before the cutoff, or null when nothing is tracked. */
+export function getRecordingTimeRemainingMs(): number | null {
+ if (!state) return null;
+ return Math.max(0, MAX_RECORDING_DURATION_MS - getElapsedMs(state));
+}
+
+/** Whether a recording is currently being tracked. */
+export function isRecordingLimitActive(): boolean {
+ return state !== null;
+}
diff --git a/src/renderer/App.tsx b/src/renderer/App.tsx
index 109b655..f711eef 100644
--- a/src/renderer/App.tsx
+++ b/src/renderer/App.tsx
@@ -564,8 +564,10 @@ export function App() {
const { allGranted, loading: permissionsLoading, checkPermissions } = usePermissions();
const { prepareNewSession, prepareNewSessionWithInfo, waitForIdle } = useSessionLifecycle();
- // Global listener for recorder events - persists during navigation
- useGlobalRecorderEvents();
+ // Global listener for recorder events - persists during navigation.
+ // The main process cuts recordings off at the maximum length and asks us to
+ // run the normal stop flow, so the recording is finalised like any other.
+ useGlobalRecorderEvents({ onRecordingLimitReached: stopRecording });
const isAuthenticated = configStore.isAuthenticated();
diff --git a/src/renderer/hooks/useGlobalRecorderEvents.ts b/src/renderer/hooks/useGlobalRecorderEvents.ts
index 0814ab8..d0c6290 100644
--- a/src/renderer/hooks/useGlobalRecorderEvents.ts
+++ b/src/renderer/hooks/useGlobalRecorderEvents.ts
@@ -4,14 +4,29 @@ import { useTranscriptionStore } from '../stores/transcription.store';
import { useVisualIndexStore } from '../stores/visual-index.store';
import { useCopilotStore } from '../stores/copilot.store';
import { getElectronAPI } from '../api/ipc';
-import type { RecorderEvent, TranscriptEvent, VisualIndexEvent } from '../../shared/types/ipc.types';
+import { formatDurationLabel } from '../../shared/constants/recording';
+import type {
+ RecorderEvent,
+ TranscriptEvent,
+ VisualIndexEvent,
+ RecordingLimitWarningEvent,
+ RecordingLimitReachedEvent,
+} from '../../shared/types/ipc.types';
+
+interface GlobalRecorderEventOptions {
+ /**
+ * Called when the recording hits the maximum length. Should run the normal
+ * stop flow so the recording is finalised and the summary generated.
+ */
+ onRecordingLimitReached?: () => void | Promise<void>;
+}
/**
* Global hook to listen for recorder events from the main process.
* This should be called ONCE at the App level to ensure transcript events
* are captured even when navigating between pages.
*/
-export function useGlobalRecorderEvents() {
+export function useGlobalRecorderEvents(options: GlobalRecorderEventOptions = {}) {
const sessionStore = useSessionStore();
const transcriptionStore = useTranscriptionStore();
const visualIndexStore = useVisualIndexStore();
@@ -20,6 +35,11 @@ export function useGlobalRecorderEvents() {
const sessionStoreRef = useRef(sessionStore);
const transcriptionStoreRef = useRef(transcriptionStore);
const visualIndexStoreRef = useRef(visualIndexStore);
+ const optionsRef = useRef(options);
+
+ useEffect(() => {
+ optionsRef.current = options;
+ }, [options]);
// Keep refs updated
useEffect(() => {
@@ -57,6 +77,35 @@ export function useGlobalRecorderEvents() {
session.setStatus('idle');
break;
+ case 'recording:limit-warning': {
+ // A two-hour meeting usually means the app is in the tray, so warn
+ // through the OS rather than with an in-app toast nobody will see.
+ const warning = event.data as RecordingLimitWarningEvent;
+ const remaining = formatDurationLabel(warning.msRemaining);
+ const limit = formatDurationLabel(warning.limitMs);
+
+ getElectronAPI()?.app.showNotification(
+ 'Recording ends soon',
+ `This recording reaches the ${limit} limit in ${remaining} and will stop automatically.`
+ );
+ break;
+ }
+
+ case 'recording:limit-reached': {
+ const reached = event.data as RecordingLimitReachedEvent;
+ const limit = formatDurationLabel(reached.limitMs);
+
+ getElectronAPI()?.app.showNotification(
+ 'Recording stopped',
+ `The ${limit} recording limit was reached. Your recording is being saved.`
+ );
+
+ // Run the same stop path as the Stop button so the recording is
+ // finalised, the summary is generated and the stores are reset.
+ void optionsRef.current.onRecordingLimitReached?.();
+ break;
+ }
+
case 'transcript':
if (event.data && transcription.enabled) {
const transcript = event.data as TranscriptEvent;
diff --git a/src/shared/constants/recording.ts b/src/shared/constants/recording.ts
new file mode 100644
index 0000000..5897f0f
--- /dev/null
+++ b/src/shared/constants/recording.ts
@@ -0,0 +1,39 @@
+/**
+ * Recording Limits
+ *
+ * A recording stops itself once it reaches `MAX_RECORDING_DURATION_MS` of
+ * actual recording time. Paused time does not count, so the cutoff lines up
+ * with the elapsed timer shown during the meeting.
+ *
+ * The main process owns the deadline (see `recording-limit.service`) because
+ * Chromium throttles timers in hidden windows, and a two-hour meeting usually
+ * means the app has been in the tray for most of it.
+ */
+
+/** Recordings are cut off after this much recording time. */
+export const MAX_RECORDING_DURATION_MS = 2 * 60 * 60 * 1000; // 2 hours
+
+/** How long before the cutoff the user is warned. */
+export const RECORDING_LIMIT_WARNING_MS = 5 * 60 * 1000; // 5 minutes
+
+/**
+ * If the renderer does not complete the stop within this window - its window
+ * may be gone - the main process stops the capture itself.
+ */
+export const RECORDING_LIMIT_STOP_GRACE_MS = 20 * 1000;
+
+/**
+ * Renders a duration as a short phrase for notifications, e.g. "2 hours",
+ * "5 minutes", "1 hour 30 minutes".
+ */
+export function formatDurationLabel(ms: number): string {
+ const totalMinutes = Math.max(0, Math.round(ms / 60000));
+ const hours = Math.floor(totalMinutes / 60);
+ const minutes = totalMinutes % 60;
+
+ const parts: string[] = [];
+ if (hours > 0) parts.push(`${hours} hour${hours === 1 ? '' : 's'}`);
+ if (minutes > 0) parts.push(`${minutes} minute${minutes === 1 ? '' : 's'}`);
+
+ return parts.length > 0 ? parts.join(' ') : 'less than a minute';
+}
diff --git a/src/shared/types/ipc.types.ts b/src/shared/types/ipc.types.ts
index daee76b..7cf6e76 100644
--- a/src/shared/types/ipc.types.ts
+++ b/src/shared/types/ipc.types.ts
@@ -20,6 +20,8 @@ export interface RecorderEvent {
| 'recording:started'
| 'recording:stopped'
| 'recording:error'
+ | 'recording:limit-warning'
+ | 'recording:limit-reached'
| 'transcript'
| 'visual_index'
| 'upload:progress'
@@ -28,6 +30,19 @@ export interface RecorderEvent {
data?: unknown;
}
+/** Payload for `recording:limit-warning`. */
+export interface RecordingLimitWarningEvent {
+ /** Recording time left before the cutoff, in ms. */
+ msRemaining: number;
+ /** The maximum recording length, in ms. */
+ limitMs: number;
+}
+
+/** Payload for `recording:limit-reached`. */
+export interface RecordingLimitReachedEvent {
+ limitMs: number;
+}
+
export interface TranscriptEvent {
text: string;
isFinal: boolean;
diff --git a/tasks/todo.md b/tasks/todo.md
index 8c6e0e8..8104b54 100644
--- a/tasks/todo.md
+++ b/tasks/todo.md
@@ -2,6 +2,9 @@
Branch: `fix/security-hardening-and-issues`
+> Also on this branch: a 2 hour recording cutoff. See
+> [Recording length limit](#recording-length-limit) at the end.
+
Covers the three open issues on `video-db/call.md`:
- [#27](https://github.com/video-db/call.md/issues/27) — Security & Privacy Audit
@@ -149,3 +152,60 @@ migration, new credentials never appear in the DB file, and a legacy plaintext
transcripts in SQLite would break search and every existing query; the file is
now `0600` inside a `0700` directory, which is the meaningful part of that
finding. Full-database encryption (SQLCipher) is a separate piece of work.
+
+---
+
+# Recording length limit
+
+Requested separately: recordings should auto-cut after 2 hours.
+
+## Design
+
+- [x] Limit lives in the **main process** (`recording-limit.service.ts`).
+ Chromium throttles timers in hidden windows and a two-hour meeting means
+ the app is in the tray for most of it, so a renderer timer is not
+ trustworthy for this.
+- [x] Counts **recording time, not wall-clock**. Pausing banks the elapsed
+ total and stops the clock, so the cutoff lands exactly when the on-screen
+ timer reads 2:00:00. A meeting paused for three hours is not punished for
+ it.
+- [x] Only a full pause counts. The renderer uses one IPC for both the pause
+ button (all three tracks) and per-stream toggles (one track), so
+ `isFullSessionToggle()` distinguishes them.
+- [x] The cutoff **asks the renderer to run its normal stop flow** rather than
+ tearing down the capture client directly. The renderer's path is what
+ finalises the recording, generates the meeting summary and resets the
+ session stores.
+- [x] Main-process fallback after 20s if no renderer acts (window gone), gated
+ on the session id so it can never stop a *newer* recording.
+- [x] Warning 5 minutes out, delivered as an OS notification.
+- [x] Cutoff cleared on stop and on both cleanup paths.
+
+## Tunables — `src/shared/constants/recording.ts`
+
+| Constant | Value |
+| --- | --- |
+| `MAX_RECORDING_DURATION_MS` | 2 hours |
+| `RECORDING_LIMIT_WARNING_MS` | 5 minutes |
+| `RECORDING_LIMIT_STOP_GRACE_MS` | 20 seconds |
+
+## Review
+
+10 tests in `tests/recording-limit.test.ts`, driven by `node:test` mock timers
+so a two-hour limit runs instantly. They cover the cutoff boundary, the single
+warning, pause/resume arithmetic, disarming on stop, tracker replacement, and
+out-of-order pause/resume calls.
+
+Those tests caught a real bug before it shipped: `getElapsedMs()` tested
+`segmentStartedAt` for truthiness, but `null` is the paused sentinel — a
+timestamp of `0` would have frozen the clock. Production `Date.now()` is never
+0, so only the mocked clock exposed it. Fixed to compare against `null`.
+
+Not verified end to end: a real two-hour recording. The timer semantics are
+covered by unit tests and the main-to-renderer event uses the same
+`sendRecorderEvent` channel every other recorder event already runs on.
+
+Known limit: if the 20s fallback fires, the capture stops and the export poller
+still finalises the video, but the copilot summary is skipped because no
+renderer ran the stop flow. That path only happens when the window is gone. The
+widget's Stop button has the same pre-existing gap.
diff --git a/tests/recording-limit.test.ts b/tests/recording-limit.test.ts
new file mode 100644
index 0000000..f3bdff0
--- /dev/null
+++ b/tests/recording-limit.test.ts
@@ -0,0 +1,215 @@
+/**
+ * Tests for the recording-length cutoff.
+ *
+ * Uses node:test mock timers so a two-hour limit runs instantly. Electron is
+ * stubbed through the require cache because the service pulls in the logger.
+ *
+ * Run with: npm test
+ */
+
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import os from 'node:os';
+import Module from 'node:module';
+
+const electronPath = require.resolve('electron');
+require.cache[electronPath] = Object.assign(new Module(electronPath), {
+ id: electronPath,
+ filename: electronPath,
+ loaded: true,
+ exports: {
+ app: { getPath: () => os.tmpdir(), isPackaged: true },
+ safeStorage: { isEncryptionAvailable: () => false },
+ },
+});
+
+// eslint-disable-next-line @typescript-eslint/no-var-requires
+const limit = require('../src/main/services/recording-limit.service') as typeof import('../src/main/services/recording-limit.service');
+// eslint-disable-next-line @typescript-eslint/no-var-requires
+const constants = require('../src/shared/constants/recording') as typeof import('../src/shared/constants/recording');
+
+const {
+ startRecordingLimit,
+ pauseRecordingLimit,
+ resumeRecordingLimit,
+ clearRecordingLimit,
+ getRecordingTimeRemainingMs,
+ isRecordingLimitActive,
+} = limit;
+
+const { MAX_RECORDING_DURATION_MS, RECORDING_LIMIT_WARNING_MS, formatDurationLabel } = constants;
+
+const MINUTE = 60 * 1000;
+
+/** Records callback invocations so tests can assert on ordering and counts. */
+function spyCallbacks() {
+ const calls = { warnings: [] as number[], stops: 0 };
+ return {
+ calls,
+ onWarning: (msRemaining: number) => calls.warnings.push(msRemaining),
+ onLimitReached: () => {
+ calls.stops += 1;
+ },
+ };
+}
+
+test('the limit is two hours', () => {
+ assert.equal(MAX_RECORDING_DURATION_MS, 2 * 60 * 60 * 1000);
+});
+
+test('stops the recording once the limit is reached', (t) => {
+ t.mock.timers.enable({ apis: ['setTimeout', 'Date'] });
+ t.after(() => clearRecordingLimit());
+
+ const spy = spyCallbacks();
+ startRecordingLimit(spy);
+
+ t.mock.timers.tick(MAX_RECORDING_DURATION_MS - 1);
+ assert.equal(spy.calls.stops, 0, 'must not stop before the limit');
+
+ t.mock.timers.tick(1);
+ assert.equal(spy.calls.stops, 1, 'stops exactly at the limit');
+});
+
+test('warns five minutes before the cutoff', (t) => {
+ t.mock.timers.enable({ apis: ['setTimeout', 'Date'] });
+ t.after(() => clearRecordingLimit());
+
+ const spy = spyCallbacks();
+ startRecordingLimit(spy);
+
+ t.mock.timers.tick(MAX_RECORDING_DURATION_MS - RECORDING_LIMIT_WARNING_MS - 1);
+ assert.equal(spy.calls.warnings.length, 0);
+
+ t.mock.timers.tick(1);
+ assert.equal(spy.calls.warnings.length, 1, 'warns once');
+ assert.equal(spy.calls.warnings[0], RECORDING_LIMIT_WARNING_MS);
+ assert.equal(spy.calls.stops, 0, 'warning is not a stop');
+
+ t.mock.timers.tick(RECORDING_LIMIT_WARNING_MS);
+ assert.equal(spy.calls.stops, 1);
+ assert.equal(spy.calls.warnings.length, 1, 'still only one warning');
+});
+
+test('paused time does not count toward the limit', (t) => {
+ t.mock.timers.enable({ apis: ['setTimeout', 'Date'] });
+ t.after(() => clearRecordingLimit());
+
+ const spy = spyCallbacks();
+ startRecordingLimit(spy);
+
+ t.mock.timers.tick(30 * MINUTE); // 30 min recorded
+ pauseRecordingLimit();
+
+ t.mock.timers.tick(5 * 60 * MINUTE); // paused for five hours
+ assert.equal(spy.calls.stops, 0, 'a pause must never trigger the cutoff');
+ assert.equal(getRecordingTimeRemainingMs(), MAX_RECORDING_DURATION_MS - 30 * MINUTE);
+
+ resumeRecordingLimit();
+
+ t.mock.timers.tick(MAX_RECORDING_DURATION_MS - 30 * MINUTE - 1);
+ assert.equal(spy.calls.stops, 0);
+
+ t.mock.timers.tick(1);
+ assert.equal(spy.calls.stops, 1, 'stops after two hours of recording, not wall-clock');
+});
+
+test('a warning already due still fires after a pause', (t) => {
+ t.mock.timers.enable({ apis: ['setTimeout', 'Date'] });
+ t.after(() => clearRecordingLimit());
+
+ const spy = spyCallbacks();
+ startRecordingLimit(spy);
+
+ // Pause with less than the warning lead time left.
+ t.mock.timers.tick(MAX_RECORDING_DURATION_MS - 2 * MINUTE);
+ assert.equal(spy.calls.warnings.length, 1, 'warning already fired before the pause');
+
+ pauseRecordingLimit();
+ t.mock.timers.tick(60 * MINUTE);
+ resumeRecordingLimit();
+
+ t.mock.timers.tick(2 * MINUTE);
+ assert.equal(spy.calls.stops, 1);
+ assert.equal(spy.calls.warnings.length, 1, 'the warning is not repeated on resume');
+});
+
+test('stopping the recording disarms the cutoff', (t) => {
+ t.mock.timers.enable({ apis: ['setTimeout', 'Date'] });
+
+ const spy = spyCallbacks();
+ startRecordingLimit(spy);
+ assert.equal(isRecordingLimitActive(), true);
+
+ clearRecordingLimit();
+ assert.equal(isRecordingLimitActive(), false);
+ assert.equal(getRecordingTimeRemainingMs(), null);
+
+ t.mock.timers.tick(MAX_RECORDING_DURATION_MS * 2);
+ assert.equal(spy.calls.stops, 0, 'a stopped recording must never be re-stopped');
+ assert.equal(spy.calls.warnings.length, 0);
+});
+
+test('a new recording gets a full budget and the old one is dropped', (t) => {
+ t.mock.timers.enable({ apis: ['setTimeout', 'Date'] });
+ t.after(() => clearRecordingLimit());
+
+ const first = spyCallbacks();
+ startRecordingLimit(first);
+ t.mock.timers.tick(90 * MINUTE);
+
+ const second = spyCallbacks();
+ startRecordingLimit(second);
+ assert.equal(getRecordingTimeRemainingMs(), MAX_RECORDING_DURATION_MS);
+
+ t.mock.timers.tick(MAX_RECORDING_DURATION_MS);
+ assert.equal(second.calls.stops, 1);
+ assert.equal(first.calls.stops, 0, 'the replaced tracker must not fire');
+});
+
+test('reports the time remaining as recording progresses', (t) => {
+ t.mock.timers.enable({ apis: ['setTimeout', 'Date'] });
+ t.after(() => clearRecordingLimit());
+
+ assert.equal(getRecordingTimeRemainingMs(), null, 'null when idle');
+
+ startRecordingLimit(spyCallbacks());
+ assert.equal(getRecordingTimeRemainingMs(), MAX_RECORDING_DURATION_MS);
+
+ t.mock.timers.tick(45 * MINUTE);
+ assert.equal(getRecordingTimeRemainingMs(), MAX_RECORDING_DURATION_MS - 45 * MINUTE);
+
+ t.mock.timers.tick(MAX_RECORDING_DURATION_MS);
+ assert.equal(getRecordingTimeRemainingMs(), 0, 'never goes negative');
+});
+
+test('pause and resume are safe to call out of order', (t) => {
+ t.mock.timers.enable({ apis: ['setTimeout', 'Date'] });
+ t.after(() => clearRecordingLimit());
+
+ // No active recording - these must not throw.
+ pauseRecordingLimit();
+ resumeRecordingLimit();
+
+ const spy = spyCallbacks();
+ startRecordingLimit(spy);
+
+ resumeRecordingLimit(); // already running
+ t.mock.timers.tick(30 * MINUTE);
+
+ pauseRecordingLimit();
+ pauseRecordingLimit(); // double pause must not bank the time twice
+ assert.equal(getRecordingTimeRemainingMs(), MAX_RECORDING_DURATION_MS - 30 * MINUTE);
+
+ resumeRecordingLimit();
+ t.mock.timers.tick(MAX_RECORDING_DURATION_MS - 30 * MINUTE);
+ assert.equal(spy.calls.stops, 1);
+});
+
+test('formats durations for notifications', () => {
+ assert.equal(formatDurationLabel(MAX_RECORDING_DURATION_MS), '2 hours');
+ assert.equal(formatDurationLabel(RECORDING_LIMIT_WARNING_MS), '5 minutes');
+ assert.equal(formatDurationLabel(60 * MINUTE), '1 hour');
+ assert.equal(formatDurationLabel(90 * MINUTE), '1 hour 30 minutes');
+ assert.equal(formatDurationLabel(0), 'less than a minute');
+});