Skip to content

The open alternative to Salesforce, designed for AI.

[4/4] Desktop Recorder: add desktop application coverage (#25900)

Thomas des Francsfd9d6a6a03c9
diff --git a/packages/twenty-companion/src/main/__tests__/dev-runner.test.mjs b/packages/twenty-companion/src/main/__tests__/dev-runner.test.mjs
new file mode 100644
index 00000000000..35fcf63bedb
--- /dev/null
+++ b/packages/twenty-companion/src/main/__tests__/dev-runner.test.mjs
@@ -0,0 +1,119 @@
+import { EventEmitter } from 'node:events';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ spawn: vi.fn(),
+ context: vi.fn(),
+ server: { listen: vi.fn(), close: vi.fn() },
+ watcher: { watch: vi.fn(), dispose: vi.fn() },
+ mkdir: vi.fn(),
+ writeFile: vi.fn(),
+}));
+vi.mock('node:child_process', () => ({ spawn: mocks.spawn }));
+vi.mock('node:fs/promises', () => ({
+ mkdir: mocks.mkdir,
+ writeFile: mocks.writeFile,
+}));
+vi.mock('vite', () => ({ createServer: async () => mocks.server }));
+vi.mock('esbuild', () => ({ context: mocks.context }));
+vi.mock('electron', () => ({ default: '/electron' }));
+
+let onStart;
+let onEnd;
+let children;
+let previousSignals;
+beforeEach(async () => {
+ vi.resetModules();
+ vi.clearAllMocks();
+ previousSignals = new Map(
+ ['SIGINT', 'SIGTERM'].map((signal) => [signal, process.listeners(signal)]),
+ );
+ vi.spyOn(process, 'exit').mockImplementation(() => undefined);
+ children = [];
+ mocks.spawn.mockImplementation(() => {
+ const child = new EventEmitter();
+ child.connected = true;
+ child.send = vi.fn();
+ child.kill = vi.fn();
+ children.push(child);
+ return child;
+ });
+ mocks.context.mockImplementation(async (options) => {
+ options.plugins[0].setup({
+ onStart: (callback) => {
+ onStart = callback;
+ },
+ onEnd: (callback) => {
+ onEnd = callback;
+ },
+ });
+ return mocks.watcher;
+ });
+ await import('../../../scripts/dev.mjs');
+});
+afterEach(async () => {
+ for (const [signal, previous] of previousSignals) {
+ for (const listener of process.listeners(signal)) {
+ if (!previous.includes(listener)) {
+ if (signal === 'SIGTERM') listener();
+ process.removeListener(signal, listener);
+ }
+ }
+ }
+ await vi.waitFor(() => expect(mocks.server.close).toHaveBeenCalled());
+ vi.restoreAllMocks();
+});
+const successfulBuild = async () => {
+ onStart();
+ await onEnd({
+ errors: [],
+ outputFiles: [{ path: '/dist/main.cjs', contents: new Uint8Array([1]) }],
+ });
+};
+
+it('starts Electron only after a successful build and keeps it alive after errors', async () => {
+ onStart();
+ await onEnd({ errors: ['syntax error'] });
+ expect(mocks.spawn).not.toHaveBeenCalled();
+ expect(mocks.writeFile).not.toHaveBeenCalled();
+ await successfulBuild();
+ expect(mocks.spawn).toHaveBeenCalledOnce();
+ onStart();
+ await onEnd({ errors: ['syntax error'] });
+ expect(children[0].send).not.toHaveBeenCalled();
+ expect(children[0].kill).not.toHaveBeenCalled();
+});
+
+it('requests restarts without killing the child, then waits for its acknowledged exit', async () => {
+ await successfulBuild();
+ await successfulBuild();
+ await successfulBuild();
+ expect(children[0].send).toHaveBeenCalledWith(
+ { type: 'development-restart' },
+ expect.any(Function),
+ );
+ expect(children[0].kill).not.toHaveBeenCalled();
+ expect(mocks.spawn).toHaveBeenCalledOnce();
+ children[0].emit('message', { type: 'development-restarting' });
+ children[0].emit('exit', 0);
+ expect(mocks.spawn).toHaveBeenCalledTimes(2);
+});
+
+it('waits for an ongoing build before relaunching an exiting child', async () => {
+ await successfulBuild();
+ await successfulBuild();
+ onStart();
+ children[0].emit('message', { type: 'development-restarting' });
+ children[0].emit('exit', 0);
+ expect(mocks.spawn).toHaveBeenCalledOnce();
+ await onEnd({ errors: [], outputFiles: [] });
+ expect(mocks.spawn).toHaveBeenCalledTimes(2);
+});
+
+it('closes Vite and the watcher when Electron quits normally', async () => {
+ await successfulBuild();
+ children[0].emit('exit', 0);
+ await vi.waitFor(() => expect(mocks.server.close).toHaveBeenCalled());
+ expect(mocks.watcher.dispose).toHaveBeenCalledOnce();
+ expect(mocks.spawn).toHaveBeenCalledOnce();
+});
diff --git a/packages/twenty-companion/src/main/services/__tests__/Companion.test.ts b/packages/twenty-companion/src/main/services/__tests__/Companion.test.ts
new file mode 100644
index 00000000000..0687a5d0fa5
--- /dev/null
+++ b/packages/twenty-companion/src/main/services/__tests__/Companion.test.ts
@@ -0,0 +1,996 @@
+import { createDeferred } from '../../utils/createDeferred';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { DEFAULT_SETTINGS } from '../../../shared/constants/DEFAULT_SETTINGS';
+import { nativeTheme } from 'electron';
+
+const mocks = vi.hoisted(() => ({
+ listeners: new Map<string, (event: Record<string, unknown>) => void>(),
+ init: vi.fn(),
+ shutdown: vi.fn(),
+ start: vi.fn(),
+ stop: vi.fn(),
+ pause: vi.fn(),
+ resume: vi.fn(),
+ openApp: vi.fn(),
+ focusApp: vi.fn(),
+ writeSettings: vi.fn(),
+ prepare: vi.fn(),
+ permission: vi.fn(),
+ request: vi.fn(),
+ open: vi.fn(),
+ restore: vi.fn(),
+ handled: vi.fn(),
+ connect: vi.fn(),
+ oauth: vi.fn(),
+ accessibilityTrusted: vi.fn(),
+ loginSettings: vi.fn(),
+ registerShortcut: vi.fn(),
+ readSettings: vi.fn(),
+ notification: vi.fn(),
+ showNotification: vi.fn(),
+}));
+vi.mock('electron', () => ({
+ app: {
+ getPath: () => '/tmp/twenty-companion-test',
+ focus: mocks.focusApp,
+ setLoginItemSettings: mocks.loginSettings,
+ },
+ nativeTheme: { themeSource: 'system' },
+ shell: { openExternal: mocks.open },
+ systemPreferences: {
+ isTrustedAccessibilityClient: mocks.accessibilityTrusted,
+ },
+ Notification: class {
+ constructor(options: unknown) {
+ mocks.notification(options);
+ }
+ static isSupported() {
+ return true;
+ }
+ on = vi.fn();
+ show = mocks.showNotification;
+ },
+}));
+vi.mock('@recallai/desktop-sdk', () => ({
+ default: {
+ init: mocks.init,
+ shutdown: mocks.shutdown,
+ startRecording: mocks.start,
+ stopRecording: mocks.stop,
+ pauseRecording: mocks.pause,
+ resumeRecording: mocks.resume,
+ prepareDesktopAudioRecording: mocks.prepare,
+ requestPermission: mocks.permission,
+ removeEventListener: (name: string) => mocks.listeners.delete(name),
+ addEventListener: (
+ name: string,
+ callback: (event: Record<string, unknown>) => void,
+ ) => mocks.listeners.set(name, callback),
+ },
+}));
+vi.mock('../SecureStore', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('../SecureStore')>()),
+ SecureStore: class {
+ readSettings = mocks.readSettings;
+ readHandledMeetings = async () => [];
+ writeHandledMeetings = mocks.handled;
+ writeSettings = mocks.writeSettings;
+ },
+}));
+vi.mock('../../utils/connectOAuth', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('../../utils/connectOAuth')>()),
+ connectOAuth: mocks.oauth,
+}));
+vi.mock('../TwentyClient', () => ({
+ TwentyClient: class {
+ workspaceUrl = 'https://acme.twenty.com';
+ restore = mocks.restore;
+ connect = mocks.connect;
+ companion = mocks.request;
+ disconnect = vi.fn();
+ },
+}));
+import { Companion } from '../Companion';
+
+const originalPlatform = process.platform;
+const originalArch = process.arch;
+const originalGetSystemVersionDescriptor = Object.getOwnPropertyDescriptor(
+ process,
+ 'getSystemVersion',
+);
+let companion: Companion;
+beforeEach(async () => {
+ Object.defineProperty(process, 'platform', {
+ value: 'darwin',
+ configurable: true,
+ });
+ Object.defineProperty(process, 'arch', {
+ value: 'arm64',
+ configurable: true,
+ });
+ vi.clearAllMocks();
+ vi.useFakeTimers();
+ mocks.listeners.clear();
+ mocks.accessibilityTrusted.mockReturnValue(false);
+ mocks.readSettings.mockResolvedValue({ ...DEFAULT_SETTINGS });
+ mocks.writeSettings.mockResolvedValue(undefined);
+ Object.defineProperty(process, 'getSystemVersion', {
+ configurable: true,
+ value: () => '15.0.0',
+ });
+ mocks.restore.mockResolvedValue({ serverUrl: 'https://api.twenty.com' });
+ mocks.request.mockImplementation(async (body: { action: string }) => {
+ if (body.action === 'configuration')
+ return { apiUrl: 'https://eu-central-1.recall.ai' };
+ if (body.action === 'agenda')
+ return {
+ workspace: { id: 'workspace-1', name: 'Acme' },
+ meetings: [],
+ recordings: [],
+ calendarConnected: true,
+ };
+ if (body.action === 'create-upload')
+ return {
+ callRecordingId: 'recording-1',
+ uploadToken: 'ephemeral-upload-token',
+ apiUrl: 'https://eu-central-1.recall.ai',
+ };
+ return {};
+ });
+ mocks.prepare.mockResolvedValue('system-audio-window');
+ mocks.stop.mockResolvedValue(undefined);
+ mocks.start.mockResolvedValue(undefined);
+ companion = new Companion(
+ () => undefined,
+ mocks.openApp,
+ mocks.registerShortcut,
+ );
+ await companion.initialize();
+});
+afterEach(async () => {
+ await companion.shutdown();
+ vi.useRealTimers();
+ Object.defineProperty(process, 'platform', { value: originalPlatform });
+ Object.defineProperty(process, 'arch', { value: originalArch });
+ if (originalGetSystemVersionDescriptor === undefined) {
+ Reflect.deleteProperty(process, 'getSystemVersion');
+ } else {
+ Object.defineProperty(
+ process,
+ 'getSystemVersion',
+ originalGetSystemVersionDescriptor,
+ );
+ }
+});
+const allowPermissions = () => {
+ mocks.accessibilityTrusted.mockReturnValue(true);
+ for (const permission of ['microphone', 'accessibility', 'system-audio'])
+ mocks.listeners.get('permission-status')?.({
+ permission,
+ status: 'granted',
+ });
+};
+
+describe('desktop capture lifecycle', () => {
+ it('opens the recording library on the workspace frontend', async () => {
+ await companion.command({ type: 'open-recordings' });
+ expect(mocks.open).toHaveBeenCalledWith(
+ 'https://acme.twenty.com/objects/callRecordings',
+ );
+ });
+
+ it('brings Companion forward after authorization while the workspace finishes connecting', async () => {
+ const authorization = createDeferred();
+ const workspace = createDeferred<void>();
+ mocks.oauth.mockReturnValueOnce(authorization.promise);
+ mocks.connect.mockReturnValueOnce(workspace.promise);
+ const pending = companion.command({
+ type: 'connect',
+ serverUrl: 'https://first.twenty.com',
+ });
+ expect(mocks.openApp).not.toHaveBeenCalled();
+ authorization.resolve({ serverUrl: 'https://first.twenty.com' });
+ await vi.waitFor(() => expect(mocks.connect).toHaveBeenCalled());
+ expect(mocks.openApp).toHaveBeenCalledTimes(1);
+ if (process.platform === 'darwin')
+ expect(mocks.focusApp).toHaveBeenCalledWith({ steal: true });
+ expect(companion.state.connection).toBe('connecting');
+ workspace.resolve();
+ await pending;
+ expect(companion.state.connection).toBe('connected');
+ });
+
+ it('cancels a pending sign-in and allows another workspace attempt', async () => {
+ mocks.oauth.mockImplementation(
+ (_url: string, _open: unknown, signal: AbortSignal) =>
+ new Promise((_resolve, reject) =>
+ signal.addEventListener('abort', () => reject(new Error('Canceled'))),
+ ),
+ );
+ const pending = companion.command({
+ type: 'connect',
+ serverUrl: 'https://first.twenty.com',
+ });
+ expect(companion.state.connection).toBe('connecting');
+ await companion.command({ type: 'cancel-connect' });
+ await pending;
+ expect(companion.state.connection).not.toBe('connecting');
+ expect(companion.state.error).toBeNull();
+ expect(mocks.connect).not.toHaveBeenCalled();
+ const retry = companion.command({
+ type: 'connect',
+ serverUrl: 'https://second.twenty.com',
+ });
+ expect(mocks.oauth).toHaveBeenLastCalledWith(
+ 'https://second.twenty.com',
+ expect.any(Function),
+ expect.any(AbortSignal),
+ );
+ await companion.command({ type: 'cancel-connect' });
+ await retry;
+ });
+
+ it('ignores credentials returned after cancellation', async () => {
+ const result = createDeferred();
+ mocks.oauth.mockReturnValue(result.promise);
+ const pending = companion.command({
+ type: 'connect',
+ serverUrl: 'https://first.twenty.com',
+ });
+ await companion.command({ type: 'cancel-connect' });
+ result.resolve({ serverUrl: 'https://first.twenty.com' });
+ await pending;
+ expect(mocks.connect).not.toHaveBeenCalled();
+ expect(companion.state.error).toBeNull();
+ expect(mocks.openApp).not.toHaveBeenCalled();
+ expect(mocks.focusApp).not.toHaveBeenCalled();
+ });
+
+ it('registers saved shortcuts and persists a replacement', async () => {
+ expect(mocks.registerShortcut).toHaveBeenCalledWith(
+ DEFAULT_SETTINGS.openShortcut,
+ );
+ await companion.command({
+ type: 'settings',
+ settings: { openShortcut: 'Control+Alt+K' },
+ });
+ expect(mocks.registerShortcut).toHaveBeenLastCalledWith('Control+Alt+K');
+ expect(companion.state.settings.openShortcut).toBe('Control+Alt+K');
+ expect(mocks.writeSettings).toHaveBeenLastCalledWith(
+ expect.objectContaining({ openShortcut: 'Control+Alt+K' }),
+ );
+ });
+
+ it('keeps the previous shortcut when registration fails', async () => {
+ mocks.registerShortcut.mockImplementationOnce(() => {
+ throw new Error('Shortcut in use');
+ });
+ await companion.command({
+ type: 'settings',
+ settings: { openShortcut: 'Control+Alt+K' },
+ });
+ expect(companion.state.settings.openShortcut).toBe(
+ DEFAULT_SETTINGS.openShortcut,
+ );
+ expect(companion.state.error?.message).toBe('Shortcut in use');
+ });
+
+ it('restores the shortcut if saving fails', async () => {
+ mocks.writeSettings.mockRejectedValueOnce(new Error('Cannot save'));
+ await companion.command({
+ type: 'settings',
+ settings: { openShortcut: 'Control+Alt+K' },
+ });
+ expect(mocks.registerShortcut).toHaveBeenLastCalledWith(
+ DEFAULT_SETTINGS.openShortcut,
+ );
+ expect(companion.state.settings.openShortcut).toBe(
+ DEFAULT_SETTINGS.openShortcut,
+ );
+ });
+
+ it('applies saved appearance at startup and changes it without changing launch at login', async () => {
+ await companion.shutdown();
+ mocks.readSettings.mockResolvedValue({
+ ...DEFAULT_SETTINGS,
+ appearance: 'dark',
+ });
+ await companion.initialize();
+ expect(nativeTheme.themeSource).toBe('dark');
+ await companion.command({
+ type: 'settings',
+ settings: { ...companion.state.settings, appearance: 'light' },
+ });
+ expect(nativeTheme.themeSource).toBe('light');
+ expect(mocks.writeSettings).toHaveBeenLastCalledWith(
+ expect.objectContaining({ appearance: 'light' }),
+ );
+ expect(mocks.loginSettings).not.toHaveBeenCalled();
+ await companion.command({
+ type: 'settings',
+ settings: { ...companion.state.settings, launchAtLogin: true },
+ });
+ expect(mocks.loginSettings).toHaveBeenCalledWith({
+ openAtLogin: true,
+ });
+ });
+
+ it('retains the current settings when saving a preference fails', async () => {
+ mocks.writeSettings.mockRejectedValueOnce(
+ new Error('Could not save preferences'),
+ );
+ await companion.command({
+ type: 'settings',
+ settings: { ...companion.state.settings, appearance: 'dark' },
+ });
+ expect(companion.state.settings.appearance).toBe('system');
+ expect(nativeTheme.themeSource).toBe('system');
+ expect(companion.state.error?.message).toBe('Could not save preferences');
+ });
+
+ it('mutes call detection prompts without disabling detection or recording interruption alerts', async () => {
+ const event = {
+ window: {
+ id: 'call-window',
+ title: 'Quick call',
+ url: 'https://meet.google.com/adhoc',
+ },
+ };
+ mocks.listeners.get('meeting-detected')?.(event);
+ expect(mocks.notification).toHaveBeenLastCalledWith(
+ expect.objectContaining({ title: 'Call detected' }),
+ );
+ await companion.command({
+ type: 'settings',
+ settings: { ...companion.state.settings, notifyOnDetectedCall: false },
+ });
+ mocks.notification.mockClear();
+ mocks.listeners.get('meeting-detected')?.(event);
+ expect(mocks.notification).not.toHaveBeenCalled();
+ expect(companion.state.detectedCalls).toHaveLength(1);
+ allowPermissions();
+ await companion.command({ type: 'record' });
+ mocks.listeners.get('network-status')?.({ status: 'disconnected' });
+ expect(mocks.notification).toHaveBeenCalledWith(
+ expect.objectContaining({ title: 'Recording interrupted' }),
+ );
+ });
+
+ it('restores meeting detection without requesting permissions at startup', () => {
+ expect(mocks.init).toHaveBeenCalledWith({
+ apiUrl: 'https://eu-central-1.recall.ai',
+ acquirePermissionsOnStartup: [],
+ });
+ });
+ it('does not obtain an upload until all capture permissions are granted', async () => {
+ await companion.command({ type: 'record' });
+ expect(companion.state.error).toBeNull();
+ expect(companion.state.permissionSetup).toEqual({
+ windowId: undefined,
+ intent: 'record',
+ });
+ expect(mocks.permission).not.toHaveBeenCalled();
+ expect(mocks.openApp).toHaveBeenCalledOnce();
+ expect(mocks.start).not.toHaveBeenCalled();
+ expect(
+ mocks.request.mock.calls.some(
+ ([body]) => body.action === 'create-upload',
+ ),
+ ).toBe(false);
+ });
+ it('opens macOS settings for a previously denied permission without prompting again', async () => {
+ companion.state.permissions.microphone = 'denied';
+ await companion.command({ type: 'record' });
+ expect(mocks.open).not.toHaveBeenCalled();
+ await companion.command({ type: 'permission', permission: 'microphone' });
+ expect(mocks.permission).not.toHaveBeenCalled();
+ expect(mocks.open).toHaveBeenCalledWith(
+ 'x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone',
+ );
+ expect(companion.state.permissionSetup).not.toBeNull();
+ });
+ it('guides the user to the next missing permission and retains the selected call', async () => {
+ companion.state.permissions.microphone = 'granted';
+ await companion.command({ type: 'record', windowId: 'call-1' });
+ expect(mocks.permission).not.toHaveBeenCalled();
+ expect(companion.state.permissionSetup).toEqual({
+ windowId: 'call-1',
+ intent: 'record',
+ });
+ await companion.command({ type: 'permission', permission: 'system-audio' });
+ expect(mocks.permission).toHaveBeenCalledWith('system-audio');
+ });
+ it('does not start recording when permissions change, and lets the user dismiss setup', async () => {
+ await companion.command({ type: 'record' });
+ allowPermissions();
+ expect(mocks.start).not.toHaveBeenCalled();
+ expect(companion.state.permissionSetup).not.toBeNull();
+ await companion.command({ type: 'cancel-permission-setup' });
+ expect(companion.state.permissionSetup).toBeNull();
+ });
+ it('recognizes approval in System Settings without prompting or restarting capture', async () => {
+ companion.state.permissions.accessibility = 'denied';
+ mocks.accessibilityTrusted.mockReturnValue(true);
+ companion.refreshPermissions();
+ expect(companion.state.permissions.accessibility).toBe('granted');
+ expect(mocks.accessibilityTrusted).toHaveBeenLastCalledWith(false);
+ await companion.command({
+ type: 'permission',
+ permission: 'accessibility',
+ });
+ expect(mocks.open).not.toHaveBeenCalled();
+ expect(mocks.permission).not.toHaveBeenCalled();
+ expect(mocks.shutdown).not.toHaveBeenCalled();
+ expect(mocks.start).not.toHaveBeenCalled();
+ });
+ it('updates the open setup guide after approval even with auto-join disabled', async () => {
+ await companion.command({ type: 'record' });
+ companion.state.settings.autoJoin = false;
+ mocks.accessibilityTrusted.mockReturnValue(true);
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(companion.state.permissions.accessibility).toBe('granted');
+ expect(companion.state.permissions.microphone).toBe('not_requested');
+ expect(companion.state.permissions['system-audio']).toBe('not_requested');
+ expect(mocks.start).not.toHaveBeenCalled();
+ });
+ it('does not let a delayed SDK denial overwrite current macOS approval', () => {
+ mocks.accessibilityTrusted.mockReturnValue(true);
+ mocks.listeners.get('permission-status')?.({
+ permission: 'accessibility',
+ status: 'denied',
+ });
+ expect(companion.state.permissions.accessibility).toBe('granted');
+ });
+ it('recognizes revoked native permissions and blocks a new recording', async () => {
+ allowPermissions();
+ mocks.accessibilityTrusted.mockReturnValue(false);
+ await companion.command({ type: 'record' });
+ expect(companion.state.permissions.accessibility).toBe('denied');
+ expect(companion.state.permissionSetup).not.toBeNull();
+ expect(mocks.start).not.toHaveBeenCalled();
+ await companion.command({
+ type: 'permission',
+ permission: 'accessibility',
+ });
+ expect(mocks.open).toHaveBeenCalledWith(
+ 'x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility',
+ );
+ });
+ it.each([
+ ['microphone', 'Privacy_Microphone'],
+ ['system-audio', 'Privacy_ScreenCapture'],
+ ['accessibility', 'Privacy_Accessibility'],
+ ] as const)(
+ 'opens Settings for denied %s even when SDK initialization fails',
+ async (permission, pane) => {
+ await companion.shutdown();
+ mocks.init.mockRejectedValueOnce(new Error('SDK unavailable'));
+ await companion.initialize();
+ expect(companion.state.error).not.toBeNull();
+ companion.state.permissions[permission] = 'denied';
+ mocks.init.mockClear();
+ await companion.command({ type: 'permission', permission });
+ expect(mocks.init).not.toHaveBeenCalled();
+ expect(mocks.permission).not.toHaveBeenCalled();
+ expect(mocks.open).toHaveBeenLastCalledWith(
+ `x-apple.systempreferences:com.apple.preference.security?${pane}`,
+ );
+ expect(companion.state.error).toBeNull();
+ },
+ );
+ it.each(['microphone', 'system-audio', 'accessibility'] as const)(
+ 'requests the native %s prompt before offering Settings after a denial',
+ async (permission) => {
+ mocks.permission.mockImplementationOnce(async () => {
+ mocks.listeners.get('permission-status')?.({
+ permission,
+ status: 'denied',
+ });
+ });
+ await companion.command({ type: 'permission', permission });
+ expect(mocks.permission).toHaveBeenCalledWith(permission);
+ expect(mocks.open).not.toHaveBeenCalled();
+ expect(companion.state.permissions[permission]).toBe('denied');
+
+ await companion.command({ type: 'permission', permission });
+ expect(mocks.permission).toHaveBeenCalledOnce();
+ const pane = {
+ microphone: 'Privacy_Microphone',
+ 'system-audio': 'Privacy_ScreenCapture',
+ accessibility: 'Privacy_Accessibility',
+ }[permission];
+ expect(mocks.open).toHaveBeenCalledWith(
+ `x-apple.systempreferences:com.apple.preference.security?${pane}`,
+ );
+ },
+ );
+ it('records system audio with a server upload token and keeps that token out of renderer state', async () => {
+ allowPermissions();
+ await companion.command({ type: 'record' });
+ expect(mocks.prepare).toHaveBeenCalledOnce();
+ expect(mocks.start).toHaveBeenCalledWith({
+ windowId: 'system-audio-window',
+ uploadToken: 'ephemeral-upload-token',
+ });
+ expect(JSON.stringify(companion.state)).not.toContain(
+ 'ephemeral-upload-token',
+ );
+ mocks.listeners.get('recording-started')?.({
+ window: { id: 'system-audio-window' },
+ });
+ expect(companion.state.activeRecording?.status).toBe('recording');
+ await companion.command({ type: 'stop' });
+ expect(mocks.stop).toHaveBeenCalledWith({
+ windowId: 'system-audio-window',
+ });
+ mocks.listeners.get('recording-ended')?.({
+ window: { id: 'system-audio-window' },
+ });
+ expect(companion.state.activeRecording).toBeNull();
+ expect(companion.state.notice?.type).toBe('recording-finished');
+ });
+ it.each([
+ ['zoom', 'https://zoom.us/j/123456789'],
+ ['microsoft_teams', 'https://teams.microsoft.com/l/meetup-join/call'],
+ ['google_meet', 'https://meet.google.com/abc-defg-hij'],
+ ['slack', undefined],
+ ])(
+ 'records a detected %s call with its own capture window',
+ async (platform, url) => {
+ allowPermissions();
+ mocks.listeners.get('meeting-detected')?.({
+ window: { id: 'provider-window', title: 'Team call', platform, url },
+ });
+ await companion.command({ type: 'record', windowId: 'provider-window' });
+ expect(mocks.prepare).not.toHaveBeenCalled();
+ expect(mocks.start).toHaveBeenCalledWith({
+ windowId: 'provider-window',
+ uploadToken: 'ephemeral-upload-token',
+ });
+ expect(mocks.request).toHaveBeenCalledWith(
+ expect.objectContaining({
+ action: 'create-upload',
+ platform,
+ meetingUrl: url,
+ }),
+ );
+ },
+ );
+ it('blocks a matching bot call but allows one manual recording during an unrelated calendar event', async () => {
+ allowPermissions();
+ companion.state.settings.autoRecord = true;
+ companion.state.meetings = [
+ {
+ id: 'event-1',
+ title: 'Scheduled',
+ startsAt: new Date(Date.now() - 1000).toISOString(),
+ endsAt: new Date(Date.now() + 60_000).toISOString(),
+ url: 'https://meet.google.com/scheduled',
+ recordingEnabled: true,
+ usesCalendarBot: true,
+ },
+ ];
+ mocks.listeners.get('meeting-detected')?.({
+ window: {
+ id: 'window-1',
+ url: 'https://meet.google.com/scheduled',
+ title: 'Scheduled',
+ platform: 'google_meet',
+ },
+ });
+ await companion.command({ type: 'record', windowId: 'window-1' });
+ expect(mocks.start).not.toHaveBeenCalled();
+ await Promise.all([
+ companion.command({ type: 'record' }),
+ companion.command({ type: 'record' }),
+ ]);
+ expect(mocks.start).toHaveBeenCalledOnce();
+ expect(mocks.prepare).toHaveBeenCalledOnce();
+ expect(mocks.request).toHaveBeenCalledWith(
+ expect.objectContaining({
+ action: 'create-upload',
+ platform: 'desktop-audio',
+ calendarEventId: undefined,
+ meetingUrl: undefined,
+ }),
+ );
+ });
+ it('stops an uncertain start before reporting capture failure', async () => {
+ allowPermissions();
+ mocks.start.mockRejectedValueOnce(new Error('Start timed out'));
+ await companion.command({ type: 'record' });
+ expect(mocks.stop).toHaveBeenCalledWith({
+ windowId: 'system-audio-window',
+ });
+ expect(companion.state.activeRecording).toBeNull();
+ expect(mocks.request).toHaveBeenCalledWith(
+ expect.objectContaining({ action: 'capture-failed' }),
+ );
+ });
+
+ it('shows network interruption without claiming the recording has uploaded', async () => {
+ allowPermissions();
+ await companion.command({ type: 'record' });
+ mocks.listeners.get('network-status')?.({ status: 'disconnected' });
+ expect(companion.state.activeRecording).not.toBeNull();
+ expect(companion.state.notice?.type).toBe('network-lost');
+ await vi.advanceTimersByTimeAsync(0);
+ expect(mocks.stop).toHaveBeenCalledOnce();
+ expect(companion.state.activeRecording).toBeNull();
+ mocks.listeners.get('network-status')?.({ status: 'reconnected' });
+ expect(companion.state.notice?.type).toBe('network-restored');
+ expect(mocks.start).toHaveBeenCalledOnce();
+ });
+
+ it('cannot complete setup until all permissions are enabled and never records just by continuing', async () => {
+ await companion.command({ type: 'complete-setup' });
+ expect(companion.state.settings.setupCompleted).toBe(false);
+ expect(mocks.writeSettings).not.toHaveBeenCalled();
+ allowPermissions();
+ await companion.command({ type: 'complete-setup' });
+ expect(companion.state.settings.setupCompleted).toBe(true);
+ expect(mocks.writeSettings).toHaveBeenCalledWith(
+ expect.objectContaining({ setupCompleted: true }),
+ );
+ expect(mocks.start).not.toHaveBeenCalled();
+ });
+
+ it('opens permission review without prompting or creating a recording', async () => {
+ await companion.command({ type: 'begin-permission-setup' });
+ expect(companion.state.permissionSetup).toEqual({});
+ expect(mocks.openApp).toHaveBeenCalledOnce();
+ expect(mocks.permission).not.toHaveBeenCalled();
+ expect(mocks.start).not.toHaveBeenCalled();
+ });
+
+ it('pauses and resumes the same recording and excludes paused time', async () => {
+ allowPermissions();
+ await companion.command({ type: 'record' });
+ mocks.listeners.get('recording-started')?.({
+ window: { id: 'system-audio-window' },
+ });
+ await companion.command({ type: 'pause' });
+ expect(mocks.pause).toHaveBeenCalledWith({
+ windowId: 'system-audio-window',
+ });
+ expect(companion.state.activeRecording?.status).toBe('paused');
+ expect(companion.isRecording).toBe(true);
+ await vi.advanceTimersByTimeAsync(10_000);
+ await companion.command({ type: 'resume' });
+ expect(mocks.resume).toHaveBeenCalledWith({
+ windowId: 'system-audio-window',
+ });
+ expect(companion.state.activeRecording?.status).toBe('recording');
+ expect(companion.state.activeRecording?.pausedMilliseconds).toBe(10_000);
+ expect(companion.state.activeRecording?.pausedAt).toBeUndefined();
+ expect(mocks.start).toHaveBeenCalledOnce();
+ });
+
+ it('does not report a successful pause when Recall rejects it', async () => {
+ allowPermissions();
+ await companion.command({ type: 'record' });
+ mocks.listeners.get('recording-started')?.({
+ window: { id: 'system-audio-window' },
+ });
+ mocks.pause.mockRejectedValueOnce(new Error('Could not pause capture'));
+ await companion.command({ type: 'pause' });
+ expect(companion.state.activeRecording?.status).toBe('recording');
+ expect(companion.state.error?.message).toBe('Could not pause capture');
+ });
+
+ it('can finish a paused recording and retains the pause if stopping fails', async () => {
+ allowPermissions();
+ await companion.command({ type: 'record' });
+ mocks.listeners.get('recording-started')?.({
+ window: { id: 'system-audio-window' },
+ });
+ await companion.command({ type: 'pause' });
+ mocks.stop.mockRejectedValueOnce(new Error('Stop failed'));
+ await companion.command({ type: 'stop' });
+ expect(companion.state.activeRecording?.status).toBe('paused');
+ expect(companion.isRecording).toBe(true);
+ await companion.command({ type: 'stop' });
+ expect(companion.state.activeRecording).toBeNull();
+ expect(companion.isRecording).toBe(false);
+ });
+
+ it('does not restore a recording that ended while its pause request was in flight', async () => {
+ allowPermissions();
+ await companion.command({ type: 'record' });
+ mocks.listeners.get('recording-started')?.({
+ window: { id: 'system-audio-window' },
+ });
+ let finishPause: () => void = () => undefined;
+ mocks.pause.mockImplementationOnce(
+ () =>
+ new Promise<void>((resolve) => {
+ finishPause = resolve;
+ }),
+ );
+ const pending = companion.command({ type: 'pause' });
+ mocks.listeners.get('recording-ended')?.({
+ window: { id: 'system-audio-window' },
+ });
+ finishPause();
+ await pending;
+ expect(companion.state.activeRecording).toBeNull();
+ });
+
+ it('ignores expected audio interruption events during a pause', async () => {
+ allowPermissions();
+ await companion.command({ type: 'record' });
+ mocks.listeners.get('recording-started')?.({
+ window: { id: 'system-audio-window' },
+ });
+ await companion.command({ type: 'pause' });
+ mocks.listeners.get('media-capture-status')?.({
+ window: { id: 'system-audio-window' },
+ type: 'audio',
+ capturing: false,
+ });
+ expect(companion.state.notice).toBeNull();
+ });
+
+ it('keeps a finished recording visible while its webhook catches up, then accepts completion', async () => {
+ allowPermissions();
+ await companion.command({ type: 'record' });
+ mocks.listeners.get('recording-ended')?.({
+ window: { id: 'system-audio-window' },
+ });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(companion.state.recordings[0]).toMatchObject({
+ id: 'recording-1',
+ status: 'PROCESSING',
+ });
+ mocks.request.mockResolvedValueOnce({
+ workspace: { id: 'workspace-1', name: 'Acme' },
+ meetings: [],
+ calendarConnected: true,
+ recordings: [
+ {
+ id: 'recording-1',
+ title: 'Unscheduled conversation',
+ status: 'COMPLETED',
+ },
+ ],
+ });
+ await companion.refresh();
+ expect(companion.state.recordings).toHaveLength(1);
+ expect(companion.state.recordings[0].status).toBe('COMPLETED');
+ });
+});
+
+it('merges simultaneous preference changes and does not reset omitted values', async () => {
+ const { commandSchema } =
+ await import('../../../shared/validation-schemas/commandSchema');
+ await Promise.all([
+ companion.command(
+ commandSchema.parse({
+ type: 'settings',
+ settings: { appearance: 'dark' },
+ }),
+ ),
+ companion.command(
+ commandSchema.parse({ type: 'settings', settings: { autoJoin: false } }),
+ ),
+ ]);
+ expect(companion.state.settings).toMatchObject({
+ appearance: 'dark',
+ autoJoin: false,
+ });
+ expect(mocks.writeSettings).toHaveBeenLastCalledWith(
+ expect.objectContaining({ appearance: 'dark', autoJoin: false }),
+ );
+});
+
+it('keeps controls when stopping after a network failure fails and allows retry', async () => {
+ allowPermissions();
+ await companion.command({ type: 'record' });
+ mocks.stop.mockRejectedValueOnce(new Error('Could not stop capture'));
+ mocks.listeners.get('network-status')?.({ status: 'disconnected' });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(companion.state.activeRecording?.status).toBe('recording');
+ expect(companion.state.error?.message).toBe('Could not stop capture');
+ await companion.command({ type: 'stop' });
+ expect(companion.state.activeRecording).toBeNull();
+ await companion.command({ type: 'record' });
+ expect(mocks.start).toHaveBeenCalledOnce();
+ expect(companion.state.error?.message).toContain('Reconnect to the internet');
+});
+
+it('clears workspace data and stops detecting calls after disconnect', async () => {
+ companion.state.updatedAt = new Date().toISOString();
+ companion.state.recordings = [
+ { id: 'recording-1', title: 'Private', status: 'COMPLETED' },
+ ];
+ mocks.listeners.get('meeting-detected')?.({ window: { id: 'call-1' } });
+ await companion.command({ type: 'disconnect' });
+ mocks.listeners.get('meeting-detected')?.({ window: { id: 'late-call' } });
+ expect(companion.state).toMatchObject({
+ connection: 'disconnected',
+ workspace: null,
+ recordings: [],
+ detectedCalls: [],
+ calendarConnected: false,
+ updatedAt: null,
+ });
+});
+
+it('waits for a pending setup before shutting down and never starts capture after quitting', async () => {
+ allowPermissions();
+ const { promise, resolve } = createDeferred<string>();
+ mocks.prepare.mockReturnValueOnce(promise);
+ const recording = companion.command({ type: 'record' });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(companion.isRecording).toBe(true);
+ const shutdown = companion.shutdown();
+ resolve('system-audio-window');
+ await Promise.all([recording, shutdown]);
+ expect(mocks.start).not.toHaveBeenCalled();
+ expect(companion.state.activeRecording).toBeNull();
+ expect(mocks.listeners.size).toBe(0);
+});
+
+it('waits for pause to settle before stopping and retains a usable state if stop fails', async () => {
+ allowPermissions();
+ await companion.command({ type: 'record' });
+ const { promise, resolve } = createDeferred<void>();
+ mocks.pause.mockReturnValueOnce(promise);
+ const pause = companion.command({ type: 'pause' });
+ const stop = companion.command({ type: 'stop' });
+ mocks.stop.mockRejectedValueOnce(new Error('Stop failed'));
+ resolve();
+ await Promise.all([pause, stop]);
+ expect(companion.state.activeRecording?.status).toBe('paused');
+ await companion.command({ type: 'stop' });
+ expect(companion.state.activeRecording).toBeNull();
+});
+
+it('keeps controls usable if quitting fails to stop a recording', async () => {
+ allowPermissions();
+ await companion.command({ type: 'record' });
+ mocks.stop.mockRejectedValueOnce(new Error('Stop failed'));
+ await expect(companion.shutdown()).rejects.toThrow('Stop failed');
+ await companion.command({ type: 'stop' });
+ expect(companion.state.activeRecording).toBeNull();
+});
+
+it('does not switch workspaces while recording setup is pending', async () => {
+ allowPermissions();
+ const prepare = createDeferred<string>();
+ mocks.prepare.mockReturnValueOnce(prepare.promise);
+ const record = companion.command({ type: 'record' });
+ await vi.advanceTimersByTimeAsync(0);
+ await companion.command({
+ type: 'connect',
+ serverUrl: 'https://other.twenty.com',
+ });
+ expect(mocks.oauth).not.toHaveBeenCalled();
+ expect(companion.state.workspace?.name).toBe('Acme');
+ prepare.resolve('system-audio-window');
+ await record;
+});
+
+it('keeps the existing workspace usable when a new login is canceled', async () => {
+ mocks.oauth.mockRejectedValueOnce(new Error('Connection canceled'));
+ await companion.command({
+ type: 'connect',
+ serverUrl: 'https://other.twenty.com',
+ });
+ expect(companion.state.connection).toBe('connected');
+ expect(companion.state.workspace?.name).toBe('Acme');
+ expect(mocks.shutdown).not.toHaveBeenCalled();
+});
+
+it('does not save a new login that finishes after quitting', async () => {
+ const oauth = createDeferred<{ serverUrl: string }>();
+ mocks.oauth.mockReturnValueOnce(oauth.promise);
+ const connect = companion.command({
+ type: 'connect',
+ serverUrl: 'https://other.twenty.com',
+ });
+ await companion.shutdown();
+ oauth.resolve({ serverUrl: 'https://other.twenty.com' });
+ await connect;
+ expect(mocks.connect).not.toHaveBeenCalled();
+});
+
+it('initializes with recovered settings and reports the recovery after loading the workspace', async () => {
+ await companion.shutdown();
+ const { SettingsRecoveryError } =
+ await import('../../errors/SettingsRecoveryError');
+ mocks.readSettings.mockRejectedValueOnce(
+ new SettingsRecoveryError(
+ {
+ ...DEFAULT_SETTINGS,
+ autoJoin: false,
+ autoRecord: false,
+ appearance: 'dark',
+ },
+ 'Review recovered settings',
+ ),
+ );
+ await companion.initialize();
+ expect(companion.state.connection).toBe('connected');
+ expect(companion.state.settings).toMatchObject({
+ autoJoin: false,
+ autoRecord: false,
+ appearance: 'dark',
+ });
+ expect(companion.state.error?.message).toBe('Review recovered settings');
+ expect(mocks.writeSettings).not.toHaveBeenCalled();
+});
+
+it('keeps the installation recovery action with the failure', async () => {
+ const { DesktopRecorderUnavailableError } =
+ await import('../../errors/DesktopRecorderUnavailableError');
+ mocks.request.mockRejectedValueOnce(
+ new DesktopRecorderUnavailableError('https://acme.twenty.com'),
+ );
+ await companion.command({ type: 'refresh' });
+ expect(companion.state.error).toMatchObject({
+ recovery: {
+ type: 'open-desktop-installation',
+ serverUrl: 'https://acme.twenty.com',
+ },
+ });
+ await companion.command({ type: 'dismiss-error' });
+ expect(companion.state.error).toBeNull();
+});
+
+it('disconnects consistently if resetting the SDK fails after credentials were saved', async () => {
+ mocks.oauth.mockResolvedValueOnce({ serverUrl: 'https://other.twenty.com' });
+ mocks.shutdown.mockRejectedValueOnce(new Error('SDK reset failed'));
+ await companion.command({
+ type: 'connect',
+ serverUrl: 'https://other.twenty.com',
+ });
+ expect(companion.state.connection).toBe('disconnected');
+ expect(companion.state.workspace).toBeNull();
+ expect(companion.state.meetings).toEqual([]);
+ expect(companion.state.error?.message).toBe('SDK reset failed');
+});
+
+it('retries a failed browser launch on the next auto-join tick', async () => {
+ companion.state.settings.setupCompleted = true;
+ companion.state.meetings = [
+ {
+ id: 'event-1',
+ title: 'Meeting',
+ startsAt: new Date(Date.now()).toISOString(),
+ endsAt: new Date(Date.now() + 60_000).toISOString(),
+ url: 'https://meet.google.com/test',
+ recordingEnabled: true,
+ usesCalendarBot: false,
+ },
+ ];
+ mocks.open.mockRejectedValueOnce(new Error('Browser unavailable'));
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(mocks.handled).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(mocks.open).toHaveBeenCalledTimes(2);
+ expect(mocks.handled).toHaveBeenCalledOnce();
+});
+
+it('allows a later detection update to retry after capture fails', async () => {
+ allowPermissions();
+ companion.state.settings.setupCompleted = true;
+ companion.state.settings.autoRecord = true;
+ const event = {
+ window: {
+ id: 'retry-call',
+ title: 'Meeting',
+ url: 'https://meet.google.com/test',
+ platform: 'google_meet',
+ },
+ };
+ mocks.start.mockRejectedValueOnce(new Error('Capture unavailable'));
+ mocks.listeners.get('meeting-detected')?.(event);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(mocks.start).toHaveBeenCalledOnce();
+ expect(companion.state.activeRecording).toBeNull();
+ mocks.listeners.get('meeting-updated')?.(event);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(mocks.start).toHaveBeenCalledTimes(2);
+ expect(companion.state.activeRecording?.windowId).toBe('retry-call');
+});
diff --git a/packages/twenty-companion/src/main/services/__tests__/SecureStore.test.ts b/packages/twenty-companion/src/main/services/__tests__/SecureStore.test.ts
new file mode 100644
index 00000000000..ec2d2e3ba52
--- /dev/null
+++ b/packages/twenty-companion/src/main/services/__tests__/SecureStore.test.ts
@@ -0,0 +1,117 @@
+import { mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { DEFAULT_SETTINGS } from '../../../shared/constants/DEFAULT_SETTINGS';
+import { SecureStore } from '../SecureStore';
+import { SettingsRecoveryError } from '../../errors/SettingsRecoveryError';
+
+vi.mock('electron', () => ({ safeStorage: {} }));
+let directory: string;
+beforeEach(async () => {
+ directory = await mkdtemp(join(tmpdir(), 'companion-settings-'));
+});
+afterEach(async () => {
+ await rm(directory, { recursive: true, force: true });
+});
+
+describe('saved preferences', () => {
+ it('adds new defaults to existing installations without resetting their choices', async () => {
+ await writeFile(
+ join(directory, 'settings.json'),
+ JSON.stringify({
+ autoJoin: false,
+ autoRecord: true,
+ launchAtLogin: true,
+ setupCompleted: true,
+ }),
+ );
+ expect(await new SecureStore(directory).readSettings()).toEqual({
+ ...DEFAULT_SETTINGS,
+ autoJoin: false,
+ autoRecord: true,
+ launchAtLogin: true,
+ setupCompleted: true,
+ });
+ });
+
+ it('restores custom appearance and notification preferences from disk', async () => {
+ const settings = {
+ ...DEFAULT_SETTINGS,
+ appearance: 'dark' as const,
+ notifyOnDetectedCall: false,
+ showMeetingCountdown: false,
+ };
+ await new SecureStore(directory).writeSettings(settings);
+ expect(await new SecureStore(directory).readSettings()).toEqual(settings);
+ });
+});
+
+it('returns isolated defaults for separate instances', async () => {
+ const store = new SecureStore(directory);
+ const settings = await store.readSettings();
+ settings.autoRecord = true;
+ expect((await store.readSettings()).autoRecord).toBe(false);
+});
+
+it('keeps valid preferences and a backup when an individual setting is invalid', async () => {
+ const { readdir, readFile } = await import('node:fs/promises');
+ const original = JSON.stringify({
+ ...DEFAULT_SETTINGS,
+ appearance: 'sepia',
+ autoJoin: false,
+ launchAtLogin: true,
+ });
+ await writeFile(join(directory, 'settings.json'), original);
+ const error = await new SecureStore(directory)
+ .readSettings()
+ .catch((error: unknown) => error);
+ expect(error).toBeInstanceOf(SettingsRecoveryError);
+ expect((error as SettingsRecoveryError).settings).toMatchObject({
+ appearance: 'system',
+ autoJoin: false,
+ launchAtLogin: true,
+ });
+ const backup = (await readdir(directory)).find((name) =>
+ name.startsWith('settings.json.damaged-'),
+ );
+ expect(backup).toBeDefined();
+ expect(await readFile(join(directory, backup!), 'utf8')).toBe(original);
+});
+
+it('does not enable automation when the saved file is malformed', async () => {
+ await writeFile(join(directory, 'settings.json'), '{');
+ const error = await new SecureStore(directory)
+ .readSettings()
+ .catch((error: unknown) => error);
+ expect(error).toBeInstanceOf(SettingsRecoveryError);
+ expect((error as SettingsRecoveryError).settings).toMatchObject({
+ autoJoin: false,
+ autoRecord: false,
+ });
+});
+
+it('reports read failures instead of treating them as a new installation', async () => {
+ const { mkdir } = await import('node:fs/promises');
+ await mkdir(join(directory, 'settings.json'));
+ await expect(new SecureStore(directory).readSettings()).rejects.toThrow(
+ 'Could not read your settings',
+ );
+});
+
+it('does not forget skipped meetings when their file is corrupted', async () => {
+ await writeFile(join(directory, 'handled-meetings.json'), '{broken');
+ await expect(
+ new SecureStore(directory).readHandledMeetings(),
+ ).rejects.toThrow('Automatic joining is off');
+});
+
+it('preserves the newest skipped-meeting snapshot across concurrent writes', async () => {
+ const store = new SecureStore(directory);
+ await Promise.all([
+ store.writeHandledMeetings(['first']),
+ store.writeHandledMeetings(['first', 'second']),
+ store.writeHandledMeetings(['second']),
+ ]);
+ expect(await store.readHandledMeetings()).toEqual(['second']);
+});
diff --git a/packages/twenty-companion/src/main/services/__tests__/TwentyClient.test.ts b/packages/twenty-companion/src/main/services/__tests__/TwentyClient.test.ts
new file mode 100644
index 00000000000..2525316feaf
--- /dev/null
+++ b/packages/twenty-companion/src/main/services/__tests__/TwentyClient.test.ts
@@ -0,0 +1,426 @@
+import { createDeferred } from '../../utils/createDeferred';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { type Agenda } from '../../../shared/types/Agenda';
+import { TwentyClient } from '../TwentyClient';
+import { DesktopRecorderUnavailableError } from '../../errors/DesktopRecorderUnavailableError';
+
+const fetchMock = vi.fn();
+const credentials = {
+ serverUrl: 'https://crm.twenty.com',
+ clientId: 'client-1',
+ accessToken: 'test-access',
+ refreshToken: 'test-refresh',
+ expiresAt: Date.now() + 3_600_000,
+};
+const store = {
+ readCredentials: vi.fn(),
+ clearCredentials: vi.fn(),
+ writeCredentials: vi.fn(),
+};
+const json = (body: unknown, status = 200) =>
+ new Response(JSON.stringify(body), {
+ status,
+ headers: { 'Content-Type': 'application/json' },
+ });
+beforeEach(() => {
+ vi.resetAllMocks();
+ vi.stubGlobal('fetch', fetchMock);
+ vi.mocked(store.readCredentials).mockResolvedValue(credentials);
+});
+afterEach(() => vi.unstubAllGlobals());
+const discovery = (logo?: string) =>
+ fetchMock.mockImplementation(async (url: string) => {
+ if (url.endsWith('/client-config'))
+ return json({ publicFunctionDomain: 'withtwenty.com' });
+ if (url.endsWith('/metadata'))
+ return json({
+ data: {
+ currentWorkspace: {
+ id: 'workspace-1',
+ displayName: 'Twenty',
+ logo,
+ subdomain: 'twenty',
+ workspaceUrls: {
+ subdomainUrl: 'https://twenty.twenty.com/',
+ customUrl: 'https://crm.twenty.com/',
+ },
+ },
+ },
+ });
+ return json({ message: 'No Route trigger found' }, 404);
+ });
+
+describe('cloud custom-domain connection', () => {
+ it('does not save a new account when the recording backend is unavailable', async () => {
+ discovery();
+ const client = new TwentyClient(store);
+ await client.restore();
+ await expect(
+ client.connect({ ...credentials, clientId: 'new-client' }),
+ ).rejects.toThrow('Install it to continue');
+ expect(store.writeCredentials).not.toHaveBeenCalled();
+ await client.disconnect();
+ expect(fetchMock).toHaveBeenLastCalledWith(
+ `${credentials.serverUrl}/oauth/revoke`,
+ expect.objectContaining({
+ body: new URLSearchParams({
+ token: credentials.refreshToken,
+ client_id: credentials.clientId,
+ }),
+ }),
+ );
+ });
+ it('resolves the workspace logo using Twenty image URLs', async () => {
+ discovery('workspace-logo.png?token=signed-image-token');
+ const client = new TwentyClient(store);
+ await client.restore();
+ await client.companion<Agenda>({ action: 'agenda' }).catch(() => undefined);
+ expect(client.workspace?.logoUrl).toBe(
+ 'https://crm.twenty.com/files/workspace-logo.png?token=signed-image-token',
+ );
+ expect(fetchMock).toHaveBeenCalledWith(
+ 'https://crm.twenty.com/metadata',
+ expect.objectContaining({
+ body: expect.stringContaining('displayName logo'),
+ }),
+ );
+ });
+
+ it('ignores image URLs that cannot be loaded safely', async () => {
+ discovery('https://user:[email protected]/logo.png');
+ const client = new TwentyClient(store);
+ await client.restore();
+ await client.companion<Agenda>({ action: 'agenda' }).catch(() => undefined);
+ expect(client.workspace).toEqual({ id: 'workspace-1', name: 'Twenty' });
+ });
+
+ it('uses the workspace function domain and distinguishes a missing backend from failed login', async () => {
+ discovery();
+ const client = new TwentyClient(store);
+ await client.restore();
+ await expect(
+ client.companion<Agenda>({ action: 'agenda' }),
+ ).rejects.toThrow(
+ 'Desktop Recorder is unavailable in this workspace. Install it to continue.',
+ );
+ expect(fetchMock).toHaveBeenCalledWith(
+ 'https://twenty.withtwenty.com/companion/desktop',
+ expect.objectContaining({
+ method: 'POST',
+ body: JSON.stringify({ action: 'agenda' }),
+ redirect: 'error',
+ }),
+ );
+ expect(client.workspace).toEqual({ id: 'workspace-1', name: 'Twenty' });
+ expect(client.workspaceUrl).toBe('https://crm.twenty.com');
+ });
+ it('does not misdiagnose a missing metadata endpoint as an uninstalled companion', async () => {
+ fetchMock.mockImplementation(async (url: string) =>
+ url.endsWith('/client-config')
+ ? json({ publicFunctionDomain: 'withtwenty.com' })
+ : json({}, 404),
+ );
+ const client = new TwentyClient(store);
+ await client.restore();
+ await expect(
+ client.companion<Agenda>({ action: 'agenda' }),
+ ).rejects.toThrow('404 for /metadata');
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+ it('handles GraphQL errors returned with HTTP 200', async () => {
+ fetchMock.mockImplementation(async (url: string) =>
+ url.endsWith('/client-config')
+ ? json({ publicFunctionDomain: 'withtwenty.com' })
+ : json({ errors: [{ message: 'Unauthorized' }] }),
+ );
+ const client = new TwentyClient(store);
+ await client.restore();
+ await expect(
+ client.companion<Agenda>({ action: 'agenda' }),
+ ).rejects.toThrow('Twenty could not load your workspace');
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+ it('returns the personal agenda once the backend is available', async () => {
+ discovery();
+ const fallback = fetchMock.getMockImplementation();
+ fetchMock.mockImplementation(async (url: string) =>
+ url.endsWith('/companion/desktop')
+ ? json({
+ workspace: { id: 'workspace-1', name: 'Twenty' },
+ meetings: [],
+ recordings: [],
+ calendarConnected: true,
+ })
+ : fallback?.(url),
+ );
+ const client = new TwentyClient(store);
+ await client.restore();
+ expect(await client.companion<Agenda>({ action: 'agenda' })).toEqual({
+ workspace: { id: 'workspace-1', name: 'Twenty' },
+ recordings: [],
+ meetings: [],
+ calendarConnected: true,
+ });
+ });
+});
+
+it('does not restore a signed-out session when a token refresh finishes late', async () => {
+ discovery();
+ const fallback = fetchMock.getMockImplementation();
+ const refresh = createDeferred<Response>();
+ const requested = createDeferred<void>();
+ fetchMock.mockImplementation(async (url: string) => {
+ if (url.endsWith('/oauth/token')) {
+ requested.resolve();
+ return refresh.promise;
+ }
+ return url.endsWith('/oauth/revoke') ? json({}) : fallback?.(url);
+ });
+ vi.mocked(store.readCredentials).mockResolvedValue({
+ ...credentials,
+ expiresAt: 0,
+ });
+ const client = new TwentyClient(store);
+ await client.restore();
+ const request = client
+ .companion<Agenda>({ action: 'agenda' })
+ .catch((error: unknown) => error);
+ await requested.promise;
+ await client.disconnect();
+ refresh.resolve(
+ json({
+ access_token: 'rotated',
+ refresh_token: 'rotated-refresh',
+ expires_in: 3600,
+ }),
+ );
+ expect(await request).toBeInstanceOf(Error);
+ expect(store.writeCredentials).not.toHaveBeenCalled();
+ await expect(client.companion<Agenda>({ action: 'agenda' })).rejects.toThrow(
+ 'Connect your Twenty workspace',
+ );
+});
+
+it('clears credentials after an in-flight refresh write, preserving disk sign-out', async () => {
+ discovery();
+ const fallback = fetchMock.getMockImplementation();
+ fetchMock.mockImplementation(async (url: string) =>
+ url.endsWith('/oauth/token')
+ ? json({
+ access_token: 'rotated',
+ refresh_token: 'rotated-refresh',
+ expires_in: 3600,
+ })
+ : url.endsWith('/oauth/revoke')
+ ? json({})
+ : fallback?.(url),
+ );
+ const writing = createDeferred<void>();
+ const finishWrite = createDeferred<void>();
+ vi.mocked(store.readCredentials).mockResolvedValue({
+ ...credentials,
+ expiresAt: 0,
+ });
+ vi.mocked(store.writeCredentials).mockImplementationOnce(() => {
+ writing.resolve();
+ return finishWrite.promise;
+ });
+ const client = new TwentyClient(store);
+ await client.restore();
+ const request = client
+ .companion<Agenda>({ action: 'agenda' })
+ .catch((error: unknown) => error);
+ await writing.promise;
+ const disconnect = client.disconnect();
+ expect(store.clearCredentials).not.toHaveBeenCalled();
+ finishWrite.resolve();
+ await disconnect;
+ expect(await request).toBeInstanceOf(Error);
+ expect(store.clearCredentials).toHaveBeenCalledOnce();
+ expect(client.workspace).toBeNull();
+});
+
+it('accepts null timestamps while a recording is being prepared', async () => {
+ discovery();
+ const fallback = fetchMock.getMockImplementation();
+ fetchMock.mockImplementation(async (url: string) =>
+ url.endsWith('/desktop')
+ ? json({
+ workspace: { id: 'workspace-1', name: 'Twenty' },
+ meetings: [],
+ calendarConnected: true,
+ recordings: [
+ {
+ id: 'recording-1',
+ title: 'Pending conversation',
+ status: 'JOINING',
+ startedAt: null,
+ endedAt: null,
+ calendarEventId: null,
+ },
+ ],
+ })
+ : fallback?.(url),
+ );
+ const client = new TwentyClient(store);
+ await client.restore();
+ expect(
+ (await client.companion<Agenda>({ action: 'agenda' })).recordings[0],
+ ).toMatchObject({ status: 'JOINING', startedAt: null });
+});
+
+it.each([401, 403, 500, 503])(
+ 'does not suggest reinstalling after HTTP %s',
+ async (status) => {
+ discovery();
+ const fallback = fetchMock.getMockImplementation();
+ fetchMock.mockImplementation(async (url: string) =>
+ url.endsWith('/desktop') ? json({}, status) : fallback?.(url),
+ );
+ const client = new TwentyClient(store);
+ await expect(client.connect(credentials)).rejects.toThrow(
+ `Twenty returned ${status}`,
+ );
+ expect(store.writeCredentials).not.toHaveBeenCalled();
+ },
+);
+
+it.each([
+ new TypeError('Failed to fetch'),
+ new DOMException('Request timed out', 'TimeoutError'),
+])('preserves connection failures: %s', async (error) => {
+ discovery();
+ const fallback = fetchMock.getMockImplementation();
+ fetchMock.mockImplementation(async (url: string) => {
+ if (url.endsWith('/desktop')) throw error;
+ return fallback?.(url);
+ });
+ const client = new TwentyClient(store);
+ await expect(client.connect(credentials)).rejects.toBe(error);
+ expect(store.writeCredentials).not.toHaveBeenCalled();
+});
+
+it('does not suggest reinstalling for an invalid configuration response', async () => {
+ discovery();
+ const fallback = fetchMock.getMockImplementation();
+ fetchMock.mockImplementation(async (url: string) =>
+ url.endsWith('/desktop') ? json({}) : fallback?.(url),
+ );
+ const error = await new TwentyClient(store)
+ .connect(credentials)
+ .catch((error: unknown) => error);
+ expect(error).toBeInstanceOf(Error);
+ expect(error).not.toBeInstanceOf(DesktopRecorderUnavailableError);
+ expect(store.writeCredentials).not.toHaveBeenCalled();
+});
+
+it('offers installation after sign-in when the backend route is missing', async () => {
+ discovery();
+ const fallback = fetchMock.getMockImplementation();
+ fetchMock.mockImplementation(async (url: string) =>
+ url.endsWith('/desktop')
+ ? json({ message: 'No Route trigger found' }, 404)
+ : fallback?.(url),
+ );
+ await expect(
+ new TwentyClient(store).connect(credentials),
+ ).rejects.toBeInstanceOf(DesktopRecorderUnavailableError);
+ expect(store.writeCredentials).not.toHaveBeenCalled();
+});
+
+it('reuses validated workspace discovery after saving a connection', async () => {
+ discovery('logo.png');
+ const fallback = fetchMock.getMockImplementation();
+ fetchMock.mockImplementation(async (url: string, init?: RequestInit) =>
+ url.endsWith('/desktop')
+ ? json(
+ JSON.parse(String(init?.body)).action === 'configuration'
+ ? { apiUrl: 'https://eu-central-1.recall.ai' }
+ : {
+ workspace: { id: 'workspace-1', name: 'Twenty' },
+ meetings: [],
+ recordings: [],
+ calendarConnected: true,
+ },
+ )
+ : fallback?.(url),
+ );
+ const client = new TwentyClient(store);
+ await client.connect(credentials);
+ expect(client.workspace?.logoUrl).toBe(
+ 'https://crm.twenty.com/files/logo.png',
+ );
+ await client.companion<Agenda>({ action: 'agenda' });
+ expect(
+ fetchMock.mock.calls.filter(([url]) => url.endsWith('/metadata')),
+ ).toHaveLength(1);
+ expect(
+ fetchMock.mock.calls.filter(([url]) => url.endsWith('/client-config')),
+ ).toHaveLength(1);
+});
+
+it('preserves the current workspace when saving a replacement connection fails', async () => {
+ discovery();
+ const fallback = fetchMock.getMockImplementation();
+ fetchMock.mockImplementation(async (url: string) =>
+ url.endsWith('/desktop')
+ ? json({ apiUrl: 'https://eu-central-1.recall.ai' })
+ : fallback?.(url),
+ );
+ const client = new TwentyClient(store);
+ await client.connect(credentials);
+ const workspace = client.workspace;
+ vi.mocked(store.writeCredentials).mockRejectedValueOnce(
+ new Error('Keychain unavailable'),
+ );
+ await expect(
+ client.connect({ ...credentials, clientId: 'replacement' }),
+ ).rejects.toThrow('Keychain unavailable');
+ expect(client.workspace).toEqual(workspace);
+ expect(client.workspaceUrl).toBe('https://crm.twenty.com');
+});
+
+it('aborts the configuration probe without saving credentials', async () => {
+ discovery();
+ const fallback = fetchMock.getMockImplementation();
+ const controller = new AbortController();
+ fetchMock.mockImplementation(async (url: string, init?: RequestInit) => {
+ if (!url.endsWith('/desktop')) return fallback?.(url);
+ return new Promise<Response>((_, reject) => {
+ init?.signal?.addEventListener(
+ 'abort',
+ () => reject(init.signal?.reason),
+ { once: true },
+ );
+ controller.abort();
+ });
+ });
+ await expect(
+ new TwentyClient(store).connect(credentials, controller.signal),
+ ).rejects.toMatchObject({ name: 'AbortError' });
+ expect(store.writeCredentials).not.toHaveBeenCalled();
+});
+
+it('restores the previous account when canceled during the credential write', async () => {
+ discovery();
+ const fallback = fetchMock.getMockImplementation();
+ fetchMock.mockImplementation(async (url: string) =>
+ url.endsWith('/desktop')
+ ? json({ apiUrl: 'https://eu-central-1.recall.ai' })
+ : fallback?.(url),
+ );
+ const client = new TwentyClient(store);
+ await client.connect(credentials);
+ const controller = new AbortController();
+ vi.mocked(store.writeCredentials).mockImplementationOnce(async () => {
+ controller.abort();
+ });
+ await expect(
+ client.connect(
+ { ...credentials, clientId: 'replacement' },
+ controller.signal,
+ ),
+ ).rejects.toMatchObject({ name: 'AbortError' });
+ expect(store.writeCredentials).toHaveBeenLastCalledWith(credentials);
+ expect(client.workspace?.id).toBe('workspace-1');
+});
diff --git a/packages/twenty-companion/src/main/utils/__tests__/connectOAuth.test.ts b/packages/twenty-companion/src/main/utils/__tests__/connectOAuth.test.ts
new file mode 100644
index 00000000000..e6381b90776
--- /dev/null
+++ b/packages/twenty-companion/src/main/utils/__tests__/connectOAuth.test.ts
@@ -0,0 +1,232 @@
+import { createServer } from 'node:http';
+import { createHash } from 'node:crypto';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { connectOAuth } from '../connectOAuth';
+import { getDesktopInstallationUrl } from '../getDesktopInstallationUrl';
+import { validateServerUrl } from '../validateServerUrl';
+
+const servers: ReturnType<typeof createServer>[] = [];
+const listen = async (server: ReturnType<typeof createServer>) => {
+ servers.push(server);
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const address = server.address();
+ if (!address || typeof address === 'string')
+ throw new Error('Missing address');
+
+ return `http://127.0.0.1:${address.port}`;
+};
+afterEach(async () => {
+ vi.unstubAllGlobals();
+ await Promise.all(
+ servers.splice(0).map(
+ (server) =>
+ new Promise<void>((resolve) => {
+ server.closeAllConnections();
+ server.close(() => resolve());
+ }),
+ ),
+ );
+});
+
+describe('Twenty OAuth', () => {
+ it('links to the integration installation page on the discovered frontend', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ issuer: 'https://api.twenty.com',
+ authorization_endpoint: 'https://app.twenty.com/authorize',
+ }),
+ ),
+ ),
+ );
+ await expect(
+ getDesktopInstallationUrl('https://api.twenty.com'),
+ ).resolves.toBe(
+ 'https://app.twenty.com/settings/applications/available/8bdaaa9f-dc53-4247-a89b-aa386c9b3244',
+ );
+ });
+ it('does not open the browser or register an app when CLI discovery is missing', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ issuer: 'https://api.twenty.com',
+ authorization_endpoint: 'https://app.twenty.com/authorize',
+ }),
+ ),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ const openBrowser = vi.fn();
+ await expect(
+ connectOAuth('https://api.twenty.com', openBrowser),
+ ).rejects.toThrow('does not support CLI sign-in');
+ expect(openBrowser).not.toHaveBeenCalled();
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('opens setup on the discovered frontend when the input is an API host', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ issuer: 'https://api.twenty.com',
+ authorization_endpoint:
+ 'https://app.twenty.com/authorize?iss=https%3A%2F%2Fapi.twenty.com',
+ }),
+ ),
+ ),
+ );
+ await expect(
+ getDesktopInstallationUrl('https://api.twenty.com'),
+ ).resolves.toBe(
+ 'https://app.twenty.com/settings/applications/available/8bdaaa9f-dc53-4247-a89b-aa386c9b3244',
+ );
+ });
+ it('uses the existing CLI client with state validation and PKCE through real HTTP boundaries', async () => {
+ let origin = '';
+ let challenge = '';
+ let issuedToken = false;
+ const server = createServer(async (request, response) => {
+ const chunks: Buffer[] = [];
+ for await (const chunk of request) chunks.push(Buffer.from(chunk));
+ const body = Buffer.concat(chunks).toString();
+ response.setHeader('Content-Type', 'application/json');
+ if (request.url === '/.well-known/oauth-authorization-server')
+ response.end(
+ JSON.stringify({
+ issuer: origin,
+ cli_client_id: 'cli-client',
+ authorization_endpoint: `${origin}/authorize?iss=${encodeURIComponent(origin)}`,
+ authorization_response_iss_parameter_supported: true,
+ }),
+ );
+ else if (request.url === '/oauth/register') {
+ throw new Error('Desktop sign-in must not register an OAuth-only app');
+ } else if (request.url === '/oauth/token') {
+ const parameters = new URLSearchParams(body);
+ expect(parameters.get('client_secret')).toBeNull();
+ expect(parameters.get('client_id')).toBe('cli-client');
+ expect(
+ createHash('sha256')
+ .update(parameters.get('code_verifier') ?? '')
+ .digest('base64url'),
+ ).toBe(challenge);
+ expect(parameters.get('code')).toBe('test-code');
+ issuedToken = true;
+ response.end(
+ JSON.stringify({
+ access_token: 'access',
+ refresh_token: 'refresh',
+ expires_in: 3600,
+ }),
+ );
+ } else response.writeHead(404).end('{}');
+ });
+ origin = await listen(server);
+ const credentials = await connectOAuth(origin, async (value) => {
+ const authorization = new URL(value);
+ expect(authorization.pathname).toBe('/authorize');
+ expect(authorization.searchParams.get('iss')).toBe(origin);
+ challenge = authorization.searchParams.get('code_challenge') ?? '';
+ const callback = new URL(
+ authorization.searchParams.get('redirect_uri') ?? '',
+ );
+ callback.search = new URLSearchParams({
+ state: 'wrong',
+ code: 'test-code',
+ iss: origin,
+ }).toString();
+ expect((await fetch(callback)).status).toBe(400);
+ expect(issuedToken).toBe(false);
+ callback.searchParams.set(
+ 'state',
+ authorization.searchParams.get('state') ?? '',
+ );
+ const response = await fetch(callback);
+ expect(response.status).toBe(200);
+ expect(response.headers.get('cache-control')).toBe('no-store');
+ expect(await response.text()).toBe(
+ 'Returning to Twenty… You can close this tab.',
+ );
+ });
+ expect(credentials.accessToken).toBe('access');
+ expect(issuedToken).toBe(true);
+ });
+ it('only accepts HTTPS origins and explicit loopback development origins', () => {
+ expect(validateServerUrl('https://acme.twenty.com/')).toBe(
+ 'https://acme.twenty.com',
+ );
+ expect(validateServerUrl('http://localhost:3000')).toBe(
+ 'http://localhost:3000',
+ );
+ for (const url of [
+ 'http://crm.example.com',
+ 'https://user:[email protected]',
+ 'https://crm.example.com/path',
+ 'https://crm.example.com?key=secret',
+ ])
+ expect(() => validateServerUrl(url)).toThrow();
+ });
+});
+
+it.each(['discovery', 'token'])(
+ 'cancels a stalled OAuth %s request',
+ async (phase) => {
+ const controller = new AbortController();
+ let origin = '';
+ const server = createServer((request, response) => {
+ if (phase === 'discovery' || request.url === '/oauth/token') {
+ controller.abort();
+ return;
+ }
+ response.setHeader('Content-Type', 'application/json');
+ response.end(
+ JSON.stringify({
+ issuer: origin,
+ cli_client_id: 'cli-client',
+ authorization_endpoint: `${origin}/authorize`,
+ }),
+ );
+ });
+ origin = await listen(server);
+ const openBrowser = vi.fn(async (url: string) => {
+ const authorization = new URL(url);
+ const callback = new URL(authorization.searchParams.get('redirect_uri')!);
+ callback.searchParams.set(
+ 'state',
+ authorization.searchParams.get('state')!,
+ );
+ callback.searchParams.set('code', 'code');
+ await fetch(callback);
+ });
+ await expect(
+ connectOAuth(origin, openBrowser, controller.signal),
+ ).rejects.toMatchObject({ name: 'AbortError' });
+ expect(openBrowser).toHaveBeenCalledTimes(phase === 'discovery' ? 0 : 1);
+ },
+);
+
+it('keeps a request deadline when a caller supplies its own signal', async () => {
+ const { requestJson } = await import('../requestJson');
+ const caller = new AbortController();
+ const timeout = new AbortController();
+ const deadline = vi
+ .spyOn(AbortSignal, 'timeout')
+ .mockReturnValue(timeout.signal);
+ const server = createServer(() =>
+ timeout.abort(new DOMException('Timed out', 'TimeoutError')),
+ );
+ const origin = await listen(server);
+ try {
+ await expect(
+ requestJson(origin, {
+ signal: caller.signal,
+ }),
+ ).rejects.toMatchObject({ name: 'TimeoutError' });
+ expect(caller.signal.aborted).toBe(false);
+ } finally {
+ deadline.mockRestore();
+ }
+});
diff --git a/packages/twenty-companion/src/main/utils/__tests__/createDevelopmentRestart.test.ts b/packages/twenty-companion/src/main/utils/__tests__/createDevelopmentRestart.test.ts
new file mode 100644
index 00000000000..8bb91df94fd
--- /dev/null
+++ b/packages/twenty-companion/src/main/utils/__tests__/createDevelopmentRestart.test.ts
@@ -0,0 +1,50 @@
+import { afterEach, expect, it, vi } from 'vitest';
+import { createDevelopmentRestart } from '../createDevelopmentRestart';
+
+let dispose: (() => void) | undefined;
+afterEach(() => {
+ dispose?.();
+ vi.useRealTimers();
+});
+
+it('restarts immediately while idle and coalesces repeated requests', () => {
+ vi.useFakeTimers();
+ const restart = vi.fn();
+ const controller = createDevelopmentRestart(() => false, restart);
+ dispose = controller.dispose;
+ controller.request();
+ controller.request();
+ expect(restart).toHaveBeenCalledOnce();
+ expect(vi.getTimerCount()).toBe(0);
+});
+
+it('waits through capture startup, recording, pause, and finishing', () => {
+ vi.useFakeTimers();
+ let busy = true;
+ const restart = vi.fn();
+ const controller = createDevelopmentRestart(() => busy, restart);
+ dispose = controller.dispose;
+ controller.request();
+ for (let build = 0; build < 3; build++) {
+ controller.request();
+ vi.advanceTimersByTime(30_000);
+ }
+ expect(restart).not.toHaveBeenCalled();
+ expect(vi.getTimerCount()).toBe(1);
+ busy = false;
+ vi.advanceTimersByTime(250);
+ expect(restart).toHaveBeenCalledOnce();
+ expect(vi.getTimerCount()).toBe(0);
+});
+
+it('cancels a pending restart on disposal', () => {
+ vi.useFakeTimers();
+ const restart = vi.fn();
+ const controller = createDevelopmentRestart(() => true, restart);
+ dispose = controller.dispose;
+ controller.request();
+ controller.dispose();
+ vi.advanceTimersByTime(1000);
+ expect(restart).not.toHaveBeenCalled();
+ expect(vi.getTimerCount()).toBe(0);
+});
diff --git a/packages/twenty-companion/src/main/utils/__tests__/createTrayMenuTemplate.test.ts b/packages/twenty-companion/src/main/utils/__tests__/createTrayMenuTemplate.test.ts
new file mode 100644
index 00000000000..db6b88fac11
--- /dev/null
+++ b/packages/twenty-companion/src/main/utils/__tests__/createTrayMenuTemplate.test.ts
@@ -0,0 +1,347 @@
+import { describe, expect, it, vi } from 'vitest';
+import {
+ type MenuItemConstructorOptions,
+ type MenuItem,
+ type KeyboardEvent,
+} from 'electron';
+import { DEFAULT_SETTINGS } from '../../../shared/constants/DEFAULT_SETTINGS';
+import { type CompanionState } from '../../../shared/types/CompanionState';
+import { type Meeting } from '../../../shared/types/Meeting';
+import { createTrayMenuTemplate } from '../createTrayMenuTemplate';
+import { getTrayTitle } from '../getTrayTitle';
+
+const NOW = Date.parse('2026-09-07T12:00:00Z');
+const state = (overrides: Partial<CompanionState> = {}): CompanionState => ({
+ connection: 'connected',
+ serverUrl: 'https://api.twenty.com',
+ workspace: { id: 'workspace', name: 'Apple' },
+ meetings: [],
+ recordings: [],
+ calendarConnected: true,
+ detectedCalls: [],
+ activeRecording: null,
+ permissions: {
+ microphone: 'granted',
+ accessibility: 'granted',
+ 'system-audio': 'granted',
+ },
+ settings: { ...DEFAULT_SETTINGS, setupCompleted: true },
+ skippedMeetingIds: [],
+ updatedAt: new Date(NOW).toISOString(),
+ error: null,
+ notice: null,
+ permissionSetup: null,
+ ...overrides,
+});
+const meeting = (overrides: Partial<Meeting> = {}): Meeting => ({
+ id: 'f8e44a6f-c367-4003-8ab2-1cc8a22727cb',
+ title: 'Product catch-up',
+ startsAt: '2026-09-07T13:00:00Z',
+ endsAt: '2026-09-07T14:00:00Z',
+ url: 'https://meet.google.com/example',
+ recordingEnabled: true,
+ usesCalendarBot: true,
+ ...overrides,
+});
+const actions = () => ({
+ command: vi.fn(),
+ openApp: vi.fn(),
+ setSetting: vi.fn(),
+ quit: vi.fn(),
+});
+const select = (menu: MenuItemConstructorOptions[], label: string) => {
+ const item = menu.find((entry) => entry.label === label);
+ expect(item, label).toBeDefined();
+ expect(item?.enabled, label).not.toBe(false);
+ item?.click?.({} as MenuItem, undefined, {} as KeyboardEvent);
+};
+
+describe('native tray menu actions', () => {
+ it('can hide the meeting countdown without hiding the active recording indicator', () => {
+ const current = state({ meetings: [meeting()] });
+ expect(getTrayTitle(current, NOW)).toBe('60m');
+ current.settings.showMeetingCountdown = false;
+ expect(getTrayTitle(current, NOW)).toBe('');
+ current.activeRecording = {
+ id: 'recording',
+ windowId: 'call',
+ title: 'Quick call',
+ startedAt: new Date(NOW).toISOString(),
+ status: 'recording',
+ };
+ expect(getTrayTitle(current, NOW)).toBe('●');
+ current.activeRecording.status = 'paused';
+ expect(getTrayTitle(current, NOW)).toBe('Paused');
+ });
+
+ it('shows the next meeting countdown when it is more than one hour away', () => {
+ expect(
+ getTrayTitle(
+ state({
+ meetings: [meeting({ startsAt: '2026-09-07T14:30:00Z' })],
+ }),
+ NOW,
+ ),
+ ).toBe('2h 30m');
+ });
+
+ it('opens setup without starting capture when permissions have not been set up', () => {
+ const handlers = actions();
+ const menu = createTrayMenuTemplate(
+ state({ settings: DEFAULT_SETTINGS }),
+ handlers,
+ NOW,
+ );
+ select(menu, 'Continue setup…');
+ expect(handlers.openApp).toHaveBeenCalledOnce();
+ expect(handlers.command).not.toHaveBeenCalled();
+ expect(menu.some((item) => item.label === 'New recording')).toBe(false);
+ });
+
+ it('offers connection before workspace actions when disconnected', () => {
+ const handlers = actions();
+ const menu = createTrayMenuTemplate(
+ state({ connection: 'disconnected' }),
+ handlers,
+ NOW,
+ );
+ select(menu, 'Connect workspace…');
+ expect(handlers.openApp).toHaveBeenCalledOnce();
+ expect(menu.some((item) => item.label === 'Recordings…')).toBe(false);
+ });
+
+ it('routes recording and settings to the existing app commands', () => {
+ const handlers = actions();
+ const menu = createTrayMenuTemplate(state(), handlers, NOW);
+ select(menu, 'New recording');
+ select(menu, 'Settings…');
+ expect(handlers.command).toHaveBeenCalledWith({ type: 'record' });
+ expect(handlers.openApp.mock.calls).toEqual([['settings']]);
+ });
+
+ it('allows resume and finish while paused, and locks controls during transitions', () => {
+ const handlers = actions();
+ const activeRecording = {
+ id: 'recording',
+ windowId: 'call',
+ title: 'Conversation',
+ startedAt: new Date(NOW).toISOString(),
+ status: 'paused' as const,
+ };
+ const menu = createTrayMenuTemplate(
+ state({ activeRecording }),
+ handlers,
+ NOW,
+ );
+ select(menu, 'Resume recording');
+ select(menu, 'Finish recording');
+ expect(handlers.command.mock.calls).toEqual([
+ [{ type: 'resume' }],
+ [{ type: 'stop' }],
+ ]);
+ for (const status of [
+ 'starting',
+ 'pausing',
+ 'resuming',
+ 'stopping',
+ ] as const) {
+ const changing = createTrayMenuTemplate(
+ state({ activeRecording: { ...activeRecording, status } }),
+ handlers,
+ NOW,
+ );
+ expect(
+ changing.find((item) => item.label === 'Finish recording')?.enabled,
+ ).toBe(false);
+ expect(changing.some((item) => item.label === 'New recording')).toBe(
+ false,
+ );
+ }
+ });
+
+ it('keeps join and skip tied to the selected meeting and excludes past meetings', () => {
+ const handlers = actions();
+ const next = meeting();
+ const menu = createTrayMenuTemplate(
+ state({
+ meetings: [
+ meeting({ title: 'Past', endsAt: '2026-09-07T11:00:00Z' }),
+ next,
+ ],
+ }),
+ handlers,
+ NOW,
+ );
+ const submenu = menu.find((item) =>
+ item.label?.includes(next.title),
+ )?.submenu;
+ expect(Array.isArray(submenu)).toBe(true);
+ select(submenu as MenuItemConstructorOptions[], 'Join meeting');
+ select(submenu as MenuItemConstructorOptions[], 'Skip auto-join');
+ expect(handlers.command.mock.calls).toEqual([
+ [{ type: 'join', meetingId: next.id }],
+ [{ type: 'skip', meetingId: next.id }],
+ ]);
+ expect(menu.some((item) => item.label?.includes('Past'))).toBe(false);
+ const skipped = createTrayMenuTemplate(
+ state({ meetings: [next], skippedMeetingIds: [next.id] }),
+ handlers,
+ NOW,
+ );
+ const skippedSubmenu = skipped.find((item) =>
+ item.label?.includes(next.title),
+ )?.submenu as MenuItemConstructorOptions[];
+ expect(
+ skippedSubmenu.find((item) => item.label === 'Restore auto-join')
+ ?.enabled,
+ ).toBe(true);
+ select(skippedSubmenu, 'Restore auto-join');
+ expect(handlers.command).toHaveBeenLastCalledWith({
+ type: 'unskip',
+ meetingId: next.id,
+ });
+ });
+
+ it('updates individual preferences without overwriting the rest of the settings', () => {
+ const handlers = actions();
+ const menu = createTrayMenuTemplate(state(), handlers, NOW);
+ expect(
+ menu.find((item) => item.label === 'Automatically join meetings'),
+ ).toMatchObject({ type: 'checkbox', checked: true });
+ select(menu, 'Automatically join meetings');
+ expect(handlers.setSetting.mock.calls).toEqual([['autoJoin', false]]);
+ expect(menu.some((item) => item.label === 'Launch at login')).toBe(false);
+ });
+
+ it('groups the next three events by local day with titles above their times', () => {
+ const localNow = new Date(2026, 8, 7, 12).getTime();
+ const at = (day: number, hour: number) =>
+ new Date(2026, 8, day, hour).toISOString();
+ const menu = createTrayMenuTemplate(
+ state({
+ meetings: [
+ meeting({
+ id: 'fourth',
+ title: 'Later',
+ startsAt: at(10, 10),
+ endsAt: at(10, 11),
+ }),
+ meeting({
+ id: 'tomorrow',
+ title: 'Planning',
+ startsAt: at(8, 10),
+ endsAt: at(8, 11),
+ }),
+ meeting({
+ id: 'today',
+ title: 'Design sync',
+ startsAt: at(7, 13),
+ endsAt: at(7, 14),
+ }),
+ meeting({
+ id: 'third',
+ title: 'Review',
+ startsAt: at(9, 10),
+ endsAt: at(9, 11),
+ }),
+ ],
+ }),
+ actions(),
+ localNow,
+ { supportsHeaders: true, supportsSublabels: true },
+ );
+ expect(
+ menu
+ .filter((item) => item.type === 'header')
+ .slice(0, 2)
+ .map((item) => item.label),
+ ).toEqual(['Today', 'Tomorrow']);
+ const events = menu.filter((item) => item.submenu);
+ expect(events.map((item) => item.label)).toEqual([
+ 'Design sync',
+ 'Planning',
+ 'Review',
+ ]);
+ expect(events[0].sublabel).toContain('In 60 min');
+ expect(events[0].sublabel).toContain(' – ');
+ expect(events[0].accessibilityLabel).toContain('Today');
+ });
+
+ it('offers a direct join action for one imminent meeting without starting capture', () => {
+ const handlers = actions();
+ const next = meeting({
+ startsAt: new Date(NOW + 5 * 60_000).toISOString(),
+ });
+ const menu = createTrayMenuTemplate(
+ state({ meetings: [next] }),
+ handlers,
+ NOW,
+ );
+ select(menu, `Join ${next.title}`);
+ expect(handlers.command.mock.calls).toEqual([
+ [{ type: 'join', meetingId: next.id }],
+ ]);
+ });
+
+ it('does not promote one event when several meetings overlap or a call is active', () => {
+ const imminent = meeting({
+ startsAt: new Date(NOW - 60_000).toISOString(),
+ });
+ for (const current of [
+ state({
+ meetings: [
+ imminent,
+ { ...imminent, id: 'other', title: 'Other meeting' },
+ ],
+ }),
+ state({
+ meetings: [imminent],
+ detectedCalls: [
+ { id: 'call', title: 'Live conversation', platform: 'zoom' },
+ ],
+ }),
+ ]) {
+ const menu = createTrayMenuTemplate(current, actions(), NOW);
+ expect(menu.some((item) => item.label === `Join ${imminent.title}`)).toBe(
+ false,
+ );
+ }
+ });
+
+ it('retains event times on platforms without native sublabels and marks missing links', () => {
+ const current = state({
+ meetings: [meeting({ url: null, recordingEnabled: false })],
+ });
+ const menu = createTrayMenuTemplate(current, actions(), NOW);
+ const event = menu.find((item) => item.submenu);
+ expect(event?.sublabel).toBeUndefined();
+ expect(event?.label).toContain(' – ');
+ expect(event?.label).toContain('No meeting link');
+ const submenu = event?.submenu as MenuItemConstructorOptions[];
+ expect(
+ submenu.find((item) => item.label === 'No meeting link')?.enabled,
+ ).toBe(false);
+ expect(submenu.some((item) => item.label === 'Recording off')).toBe(true);
+ expect(menu.some((item) => item.type === 'header')).toBe(false);
+ });
+
+ it('shows an ongoing event as Now and preserves the full title for accessibility', () => {
+ const title = 'Product & Design ' + 'review '.repeat(10);
+ const menu = createTrayMenuTemplate(
+ state({
+ meetings: [
+ meeting({ title, startsAt: new Date(NOW - 60_000).toISOString() }),
+ ],
+ }),
+ actions(),
+ NOW,
+ { supportsHeaders: true, supportsSublabels: true },
+ );
+ const event = menu.find((item) => item.submenu);
+ expect(event?.sublabel).toContain('Now');
+ expect(event?.label).toContain('…');
+ expect(event?.label).toContain('&&');
+ expect(event?.accessibilityLabel).toContain(title);
+ expect(event?.toolTip).toContain(title);
+ });
+});
diff --git a/packages/twenty-companion/src/main/utils/createDeferred.ts b/packages/twenty-companion/src/main/utils/createDeferred.ts
new file mode 100644
index 00000000000..bdd6ddea7af
--- /dev/null
+++ b/packages/twenty-companion/src/main/utils/createDeferred.ts
@@ -0,0 +1,7 @@
+export const createDeferred = <TData>() => {
+ let resolve!: (value: TData | PromiseLike<TData>) => void;
+ const promise = new Promise<TData>((settle) => {
+ resolve = settle;
+ });
+ return { promise, resolve };
+};
diff --git a/packages/twenty-companion/src/renderer/components/__tests__/Onboarding.test.tsx b/packages/twenty-companion/src/renderer/components/__tests__/Onboarding.test.tsx
new file mode 100644
index 00000000000..e272c4598a7
--- /dev/null
+++ b/packages/twenty-companion/src/renderer/components/__tests__/Onboarding.test.tsx
@@ -0,0 +1,99 @@
+// @vitest-environment jsdom
+import { cleanup, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { i18n } from '@lingui/core';
+import { Onboarding } from '../Onboarding';
+import { ThemeProvider } from '@ui/theme-constants/ThemeProvider';
+import { createInitialState } from '../../../shared/utils/createInitialState';
+import { type CompanionState } from '../../../shared/types/CompanionState';
+import { messages } from '../../locales/en';
+
+const command = vi.fn().mockResolvedValue(undefined);
+const page = (state: CompanionState) => (
+ <ThemeProvider colorScheme="light">
+ <Onboarding state={state} command={command} isPending={() => false} />
+ </ThemeProvider>
+);
+const connectedState = (): CompanionState => ({
+ ...createInitialState(),
+ connection: 'connected',
+ updatedAt: new Date().toISOString(),
+ permissions: {
+ microphone: 'granted',
+ 'system-audio': 'granted',
+ accessibility: 'granted',
+ },
+});
+beforeEach(() => {
+ command.mockClear();
+ i18n.load('en', messages);
+ i18n.activate('en');
+});
+afterEach(cleanup);
+
+it('shows connection before permissions and waits for the workspace to load', () => {
+ const { rerender } = render(page(createInitialState()));
+ expect(
+ screen.getByRole('heading', { name: 'Connect your workspace' }),
+ ).toBeDefined();
+ rerender(page({ ...connectedState(), updatedAt: null }));
+ expect(
+ screen.getByRole('heading', { name: 'Connecting your workspace' }),
+ ).toBeDefined();
+ expect(screen.queryByRole('button', { name: 'Finish' })).toBeNull();
+});
+
+it('opens the app immediately after first-time setup without starting a recording', async () => {
+ render(page(connectedState()));
+ const user = userEvent.setup();
+ await user.click(screen.getByRole('button', { name: 'Finish' }));
+ expect(command).toHaveBeenCalledExactlyOnceWith({ type: 'complete-setup' });
+ expect(
+ screen.queryByRole('button', { name: 'Open my workspace' }),
+ ).toBeNull();
+ expect(command.mock.calls.some(([value]) => value.type === 'record')).toBe(
+ false,
+ );
+});
+
+it('returns from settings permission review without showing first-time setup', async () => {
+ const state = connectedState();
+ state.settings.setupCompleted = true;
+ state.permissionSetup = {};
+ render(page(state));
+ await userEvent.setup().click(screen.getByRole('button', { name: 'Finish' }));
+ expect(command).toHaveBeenCalledExactlyOnceWith({
+ type: 'cancel-permission-setup',
+ });
+ expect(
+ screen.queryByRole('button', { name: 'Open my workspace' }),
+ ).toBeNull();
+});
+
+it('keeps required permissions enforced and preserves an explicit recording intent', async () => {
+ const state = connectedState();
+ state.settings.setupCompleted = true;
+ state.permissionSetup = { intent: 'record', windowId: 'call-window' };
+ const { rerender } = render(
+ page({
+ ...state,
+ permissions: { ...state.permissions, microphone: 'denied' },
+ }),
+ );
+ expect(
+ (
+ screen.getByRole('button', {
+ name: 'Start recording',
+ }) as HTMLButtonElement
+ ).disabled,
+ ).toBe(true);
+ rerender(page(state));
+ await userEvent
+ .setup()
+ .click(screen.getByRole('button', { name: 'Start recording' }));
+ expect(command).toHaveBeenCalledExactlyOnceWith({
+ type: 'record',
+ windowId: 'call-window',
+ });
+});
diff --git a/packages/twenty-companion/src/renderer/components/__tests__/RecordingTimer.test.tsx b/packages/twenty-companion/src/renderer/components/__tests__/RecordingTimer.test.tsx
new file mode 100644
index 00000000000..8d46e4e502f
--- /dev/null
+++ b/packages/twenty-companion/src/renderer/components/__tests__/RecordingTimer.test.tsx
@@ -0,0 +1,85 @@
+// @vitest-environment jsdom
+import { Profiler } from 'react';
+import { act, cleanup, render, screen } from '@testing-library/react';
+import { afterEach, expect, it, vi } from 'vitest';
+import { RecordingTimer } from '../RecordingTimer';
+import { useCompanion } from '../../hooks/useCompanion';
+import { createInitialState } from '../../../shared/utils/createInitialState';
+import { type ActiveRecording } from '../../../shared/types/ActiveRecording';
+
+const START = Date.parse('2026-09-08T12:00:00Z');
+const recording: ActiveRecording = {
+ id: 'recording',
+ windowId: 'window',
+ title: 'Call',
+ startedAt: new Date(START).toISOString(),
+ status: 'recording',
+};
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+ delete window.companion;
+});
+
+it('updates elapsed time without rerendering navigation', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(START);
+ window.companion = {
+ getState: async () => createInitialState(),
+ command: vi.fn(),
+ onState: () => () => undefined,
+ onNavigate: () => () => undefined,
+ };
+ const navigationRendered = vi.fn();
+ const Layout = () => {
+ const { page } = useCompanion();
+ return (
+ <>
+ <Profiler id="navigation" onRender={navigationRendered}>
+ <nav>{page}</nav>
+ </Profiler>
+ <RecordingTimer recording={recording} />
+ </>
+ );
+ };
+ await act(async () => {
+ render(<Layout />);
+ });
+ navigationRendered.mockClear();
+ await act(async () => {
+ vi.advanceTimersByTime(5000);
+ });
+ expect(screen.getByText('00:05')).toBeDefined();
+ expect(navigationRendered).not.toHaveBeenCalled();
+});
+
+it('freezes while paused and resumes without counting the pause', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(START + 5000);
+ const { rerender, unmount } = render(
+ <RecordingTimer recording={recording} />,
+ );
+ rerender(
+ <RecordingTimer
+ recording={{
+ ...recording,
+ status: 'paused',
+ pausedAt: new Date(START + 5000).toISOString(),
+ }}
+ />,
+ );
+ await act(async () => {
+ vi.advanceTimersByTime(60_000);
+ });
+ expect(screen.getByText('00:05')).toBeDefined();
+ rerender(
+ <RecordingTimer recording={{ ...recording, pausedMilliseconds: 60_000 }} />,
+ );
+ expect(screen.getByText('00:05')).toBeDefined();
+ await act(async () => {
+ vi.advanceTimersByTime(1000);
+ });
+ expect(screen.getByText('00:06')).toBeDefined();
+ unmount();
+ expect(vi.getTimerCount()).toBe(0);
+});
diff --git a/packages/twenty-companion/src/renderer/components/__tests__/sharedControls.test.tsx b/packages/twenty-companion/src/renderer/components/__tests__/sharedControls.test.tsx
new file mode 100644
index 00000000000..318cff0b832
--- /dev/null
+++ b/packages/twenty-companion/src/renderer/components/__tests__/sharedControls.test.tsx
@@ -0,0 +1,33 @@
+// @vitest-environment jsdom
+import { cleanup, render, screen } from '@testing-library/react';
+import { afterEach, expect, it } from 'vitest';
+import { IconSettings } from 'twenty-ui/icon';
+import { IconButton } from '@ui/primitives/input/IconButton/IconButton';
+import { Button } from '@ui/primitives/input/Button/Button';
+
+afterEach(cleanup);
+
+it('keeps a native accessible name on composed icon buttons', () => {
+ render(<IconButton Icon={IconSettings} aria-label="Open settings" />);
+ expect(screen.getByRole('button', { name: 'Open settings' })).toBeDefined();
+});
+
+it('keeps the legacy accessible name when both name props are supplied', () => {
+ render(
+ <IconButton
+ Icon={IconSettings}
+ ariaLabel="Settings"
+ aria-label="Native label"
+ />,
+ );
+ expect(screen.getByRole('button', { name: 'Settings' })).toBeDefined();
+});
+
+it('places the disclosure state on the actual button', () => {
+ render(<Button title="See more" ariaExpanded={false} />);
+ expect(
+ screen
+ .getByRole('button', { name: /See more/ })
+ .getAttribute('aria-expanded'),
+ ).toBe('false');
+});
diff --git a/packages/twenty-companion/src/renderer/hooks/__tests__/useCompanion.test.tsx b/packages/twenty-companion/src/renderer/hooks/__tests__/useCompanion.test.tsx
new file mode 100644
index 00000000000..94ed92cbe7c
--- /dev/null
+++ b/packages/twenty-companion/src/renderer/hooks/__tests__/useCompanion.test.tsx
@@ -0,0 +1,123 @@
+// @vitest-environment jsdom
+import { act } from 'react';
+import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { i18n } from '@lingui/core';
+import { messages } from '../../locales/en';
+import { createInitialState } from '../../../shared/utils/createInitialState';
+import { type CompanionCommand } from '../../../shared/types/CompanionCommand';
+import { createDeferred } from '../../../main/utils/createDeferred';
+import { useCompanion } from '../useCompanion';
+
+const Controls = () => {
+ const { command, isPending, state } = useCompanion();
+ return (
+ <>
+ <button
+ disabled={isPending('settings')}
+ onClick={() =>
+ void command({ type: 'settings', settings: { autoJoin: false } })
+ }
+ >
+ Save settings
+ </button>
+ <button
+ disabled={isPending('stop')}
+ onClick={() => void command({ type: 'stop' })}
+ >
+ Finish recording
+ </button>
+ <button onClick={() => void command({ type: 'dismiss-error' })}>
+ Dismiss
+ </button>
+ <button
+ onClick={() =>
+ void command({ type: 'connect', serverUrl: 'https://twenty.com' })
+ }
+ >
+ Connect
+ </button>
+ <button onClick={() => void command({ type: 'cancel-connect' })}>
+ Cancel connection
+ </button>
+ {state.error && <p role="alert">{state.error.message}</p>}
+ </>
+ );
+};
+beforeEach(() => {
+ i18n.load('en', messages);
+ i18n.activate('en');
+ window.companion = {
+ getState: async () => createInitialState(),
+ command: vi.fn().mockResolvedValue(undefined),
+ onState: () => () => undefined,
+ onNavigate: () => () => undefined,
+ };
+});
+afterEach(() => {
+ cleanup();
+ delete window.companion;
+});
+
+it('keeps recording controls and dismissal available during a settings save', async () => {
+ const pending = createDeferred<void>();
+ const command = vi
+ .mocked(window.companion!.command)
+ .mockImplementation(async (command: CompanionCommand) => {
+ if (command.type === 'settings') await pending.promise;
+ });
+ render(<Controls />);
+ const user = userEvent.setup();
+ await user.click(screen.getByRole('button', { name: 'Save settings' }));
+ expect(
+ (screen.getByRole('button', { name: 'Save settings' }) as HTMLButtonElement)
+ .disabled,
+ ).toBe(true);
+ await user.click(screen.getByRole('button', { name: 'Finish recording' }));
+ await user.click(screen.getByRole('button', { name: 'Dismiss' }));
+ expect(command).toHaveBeenCalledWith({ type: 'stop' });
+ expect(command).toHaveBeenCalledWith({ type: 'dismiss-error' });
+ await act(async () => pending.resolve());
+ await waitFor(() =>
+ expect(
+ (
+ screen.getByRole('button', {
+ name: 'Save settings',
+ }) as HTMLButtonElement
+ ).disabled,
+ ).toBe(false),
+ );
+});
+
+it('delivers cancellation while sign-in is still pending', async () => {
+ const pending = createDeferred<void>();
+ const command = vi
+ .mocked(window.companion!.command)
+ .mockImplementation(async (command) => {
+ if (command.type === 'connect') await pending.promise;
+ if (command.type === 'cancel-connect') pending.resolve();
+ });
+ render(<Controls />);
+ const user = userEvent.setup();
+ await user.click(screen.getByRole('button', { name: 'Connect' }));
+ await user.click(screen.getByRole('button', { name: 'Cancel connection' }));
+ expect(command).toHaveBeenCalledWith({ type: 'cancel-connect' });
+});
+
+it('releases a failed action so it can be retried', async () => {
+ vi.mocked(window.companion!.command).mockRejectedValueOnce(
+ new Error('IPC disconnected'),
+ );
+ render(<Controls />);
+ await userEvent
+ .setup()
+ .click(screen.getByRole('button', { name: 'Save settings' }));
+ expect((await screen.findByRole('alert')).textContent).toContain(
+ 'Please try again',
+ );
+ expect(
+ (screen.getByRole('button', { name: 'Save settings' }) as HTMLButtonElement)
+ .disabled,
+ ).toBe(false);
+});
diff --git a/packages/twenty-companion/src/renderer/utils/__tests__/format.test.ts b/packages/twenty-companion/src/renderer/utils/__tests__/format.test.ts
new file mode 100644
index 00000000000..caf89921ac3
--- /dev/null
+++ b/packages/twenty-companion/src/renderer/utils/__tests__/format.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, it } from 'vitest';
+import { elapsedRecording } from '../elapsedRecording';
+import { type ActiveRecording } from '../../../shared/types/ActiveRecording';
+
+const RECORDING: ActiveRecording = {
+ id: 'recording',
+ windowId: 'window',
+ title: 'Call',
+ startedAt: '2026-09-07T09:00:00Z',
+ status: 'recording',
+};
+describe('recording duration', () => {
+ it('freezes the elapsed time during a pause', () => {
+ const paused = {
+ ...RECORDING,
+ status: 'paused' as const,
+ pausedAt: '2026-09-07T09:01:15Z',
+ };
+ expect(elapsedRecording(paused, Date.parse('2026-09-07T09:10:00Z'))).toBe(
+ '01:15',
+ );
+ });
+ it('excludes completed pauses when recording resumes', () => {
+ expect(
+ elapsedRecording(
+ { ...RECORDING, pausedMilliseconds: 60_000 },
+ Date.parse('2026-09-07T09:02:15Z'),
+ ),
+ ).toBe('01:15');
+ });
+ it('never shows a negative duration after a clock adjustment', () => {
+ expect(
+ elapsedRecording(RECORDING, Date.parse('2026-09-07T08:59:50Z')),
+ ).toBe('00:00');
+ });
+});
diff --git a/packages/twenty-companion/src/renderer/utils/__tests__/noticeMessage.test.ts b/packages/twenty-companion/src/renderer/utils/__tests__/noticeMessage.test.ts
new file mode 100644
index 00000000000..f86ecfed513
--- /dev/null
+++ b/packages/twenty-companion/src/renderer/utils/__tests__/noticeMessage.test.ts
@@ -0,0 +1,28 @@
+import { i18n } from '@lingui/core';
+import { afterEach, expect, it } from 'vitest';
+import { messages } from '../../locales/en';
+import { noticeMessage } from '../noticeMessage';
+
+afterEach(() => {
+ i18n.load('en', messages);
+ i18n.activate('en');
+});
+it('translates recording notifications without relying on their English wording', () => {
+ i18n.load('fr', {
+ 'Recording ended. Twenty is processing your conversation.':
+ 'Enregistrement terminé.',
+ });
+ i18n.activate('fr');
+ expect(noticeMessage({ type: 'recording-finished' })).toBe(
+ 'Enregistrement terminé.',
+ );
+});
+it('interpolates a meeting title using the compiled source catalog', () => {
+ i18n.load('en', messages);
+ i18n.activate('en');
+ expect(
+ noticeMessage({ type: 'opening-meeting', title: 'Product demo' }),
+ ).toBe(
+ 'Opening Product demo. Complete any meeting provider confirmation to enter.',
+ );
+});
diff --git a/packages/twenty-companion/src/renderer/utils/__tests__/shortcut.test.ts b/packages/twenty-companion/src/renderer/utils/__tests__/shortcut.test.ts
new file mode 100644
index 00000000000..735276ab55e
--- /dev/null
+++ b/packages/twenty-companion/src/renderer/utils/__tests__/shortcut.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, it } from 'vitest';
+import { shortcutFromKeyboardEvent } from '../shortcutFromKeyboardEvent';
+import { formatShortcut } from '../formatShortcut';
+import { DEFAULT_SETTINGS } from '../../../shared/constants/DEFAULT_SETTINGS';
+
+const key = {
+ key: 'a',
+ code: 'KeyA',
+ repeat: false,
+ metaKey: false,
+ ctrlKey: false,
+ altKey: false,
+ shiftKey: false,
+};
+
+describe('shortcut capture', () => {
+ it.each([
+ [{ ...key, metaKey: true, shiftKey: true }, 'Command+Shift+A'],
+ [
+ { ...key, ctrlKey: true, altKey: true, code: 'Digit4', key: '4' },
+ 'Control+Alt+4',
+ ],
+ [{ ...key, altKey: true, code: 'Space', key: ' ' }, 'Alt+Space'],
+ [{ ...key, ctrlKey: true, code: 'F12', key: 'F12' }, 'Control+F12'],
+ [
+ { ...key, ctrlKey: true, code: 'F12', key: 'Unidentified' },
+ 'Control+F12',
+ ],
+ [{ ...key, metaKey: true, key: 'q' }, 'Command+A'],
+ ])('creates an Electron accelerator from %o', (event, expected) => {
+ expect(shortcutFromKeyboardEvent(event)).toBe(expected);
+ });
+ it.each([
+ key,
+ { ...key, shiftKey: true },
+ { ...key, metaKey: true, repeat: true },
+ { ...key, metaKey: true, key: 'Escape', code: 'Escape' },
+ { ...key, metaKey: true, key: 'Meta', code: 'MetaLeft' },
+ ])('ignores unsupported or incomplete combinations: %o', (event) => {
+ expect(shortcutFromKeyboardEvent(event)).toBeNull();
+ });
+});
+
+it('formats the shared default for macOS and other platforms', () => {
+ expect(formatShortcut(DEFAULT_SETTINGS.openShortcut, true)).toBe(
+ '⌘ + Shift + Space',
+ );
+ expect(formatShortcut(DEFAULT_SETTINGS.openShortcut, false)).toBe(
+ 'Ctrl + Shift + Space',
+ );
+ expect(formatShortcut('Control+Alt+7', true)).toBe('Ctrl + ⌥ + 7');
+ expect(formatShortcut('Control+Alt+7', false)).toBe('Ctrl + Alt + 7');
+});
diff --git a/packages/twenty-companion/src/shared/utils/__tests__/meetings.test.ts b/packages/twenty-companion/src/shared/utils/__tests__/meetings.test.ts
new file mode 100644
index 00000000000..88fd4707b78
--- /dev/null
+++ b/packages/twenty-companion/src/shared/utils/__tests__/meetings.test.ts
@@ -0,0 +1,106 @@
+import { describe, expect, it } from 'vitest';
+import { getDueMeetings } from '../getDueMeetings';
+import { getMeetingUrl } from '../getMeetingUrl';
+import { matchMeeting } from '../matchMeeting';
+import { type Meeting } from '../../types/Meeting';
+
+const NOW = Date.parse('2026-09-07T12:00:10Z');
+const MEETING: Meeting = {
+ id: 'meeting-1',
+ title: 'Design review',
+ startsAt: '2026-09-07T12:00:00Z',
+ endsAt: '2026-09-07T12:30:00Z',
+ url: 'https://meet.google.com/abc-defg-hij',
+ recordingEnabled: true,
+ usesCalendarBot: true,
+};
+
+describe('meeting scheduling', () => {
+ it('opens a due meeting once and respects skip across restarts', () => {
+ expect(
+ getDueMeetings({
+ meetings: [MEETING],
+ handledIds: new Set(),
+ now: NOW,
+ lastSyncedAt: NOW,
+ }),
+ ).toEqual([MEETING]);
+ expect(
+ getDueMeetings({
+ meetings: [MEETING],
+ handledIds: new Set([MEETING.id]),
+ now: NOW,
+ lastSyncedAt: NOW,
+ }),
+ ).toEqual([]);
+ });
+ it('does not open old meetings after wake or a stale calendar', () => {
+ expect(
+ getDueMeetings({
+ meetings: [MEETING],
+ handledIds: new Set(),
+ now: NOW,
+ lastSyncedAt: NOW - 91_000,
+ }),
+ ).toEqual([]);
+ expect(
+ getDueMeetings({
+ meetings: [MEETING],
+ handledIds: new Set(),
+ now: NOW + 60_000,
+ lastSyncedAt: NOW + 60_000,
+ }),
+ ).toEqual([]);
+ });
+ it('matches participant-specific join links and duplicate calendar copies', () => {
+ expect(
+ matchMeeting({
+ meetings: [MEETING, { ...MEETING, id: 'copy' }],
+ url: `${MEETING.url}?authuser=1`,
+ now: NOW,
+ })?.usesCalendarBot,
+ ).toBe(true);
+ expect(
+ matchMeeting({
+ meetings: [MEETING],
+ url: MEETING.url ?? undefined,
+ now: NOW + 3_600_000,
+ }),
+ ).toBeUndefined();
+ });
+ it('rejects executable, local and credential-bearing meeting links', () => {
+ for (const url of [
+ 'javascript:alert(1)',
+ 'file:///tmp/a',
+ 'http://meet.google.com/a',
+ 'https://user:[email protected]/a',
+ ])
+ expect(() => getMeetingUrl(url)).toThrow();
+ });
+});
+
+it('does not repeatedly auto-join meetings with unsupported links', () => {
+ expect(
+ getDueMeetings({
+ meetings: [{ ...MEETING, url: 'javascript:alert(1)' }],
+ handledIds: new Set(),
+ now: NOW,
+ lastSyncedAt: NOW,
+ }),
+ ).toEqual([]);
+});
+
+it('matches Zoom host aliases but keeps distinct ports separate', () => {
+ const zoom = { ...MEETING, url: 'https://www.zoom.us/j/123' };
+ expect(
+ matchMeeting({ meetings: [zoom], url: 'https://zoom.us/j/123', now: NOW })
+ ?.id,
+ ).toBe(zoom.id);
+ expect(
+ matchMeeting({
+ meetings: [zoom],
+ url: 'https://zoom.us:8443/j/123',
+ now: NOW,
+ }),
+ ).toBeUndefined();
+});