Turn meetings into live agent loops. Record, transcribe, and analyze meetings with real-time AI intelligence — before, during, and after calls.
feat: meeting context fixes
Om Gateee4f1b7f0ca3
diff --git a/src/main/server/trpc/procedures/recordings.ts b/src/main/server/trpc/procedures/recordings.tsindex b4382b9..ddc14ec 100644--- a/src/main/server/trpc/procedures/recordings.ts+++ b/src/main/server/trpc/procedures/recordings.ts@@ -218,10 +218,13 @@ export const recordingsRouter = router({}),cleanupStale: protectedProcedure- .input(z.object({ maxAgeMinutes: z.number().default(30) }))+ .input(z.object({+ maxAgeMinutes: z.number().default(60),+ excludeSessionId: z.string().optional(),+ })).output(z.object({ cleaned: z.number(), recovered: z.number() })).mutation(async ({ input, ctx }) => {- logger.info({ maxAgeMinutes: input.maxAgeMinutes }, 'Cleaning up stale recordings');+ logger.info({ maxAgeMinutes: input.maxAgeMinutes, excludeSessionId: input.excludeSessionId }, 'Cleaning up stale recordings');const recordings = getAllRecordings();const now = Date.now();@@ -236,7 +239,7 @@ export const recordingsRouter = router({// Try to recover processing recordings from VideoDBif (apiKey) {const processingRecordings = recordings.filter(- r => r.status === 'processing' && !r.videoId+ r => r.status === 'processing' && !r.videoId && r.sessionId !== input.excludeSessionId);for (const recording of processingRecordings) {@@ -257,9 +260,12 @@ export const recordingsRouter = router({}}- // Mark truly stale recordings as failedconst updatedRecordings = getAllRecordings();for (const recording of updatedRecordings) {+ if (recording.sessionId === input.excludeSessionId) {+ continue;+ }+if ((recording.status === 'processing' || recording.status === 'recording') && !(recording as any).shortOverview) {const createdAt = new Date(recording.createdAt).getTime();const age = now - createdAt;diff --git a/src/renderer/App.tsx b/src/renderer/App.tsxindex 81fef7f..a658276 100644--- a/src/renderer/App.tsx+++ b/src/renderer/App.tsx@@ -19,6 +19,7 @@ import {} from './components/copilot';import { useCopilotStore } from './stores/copilot.store';import { useMeetingSetupStore } from './stores/meeting-setup.store';+import { useSessionLifecycle, resetAllSessionStores } from './hooks/useSessionLifecycle';import { MCPServersPanel } from './components/settings/MCPServersPanel';import { CalendarPanel } from './components/settings/CalendarPanel';import { WorkflowsPanel } from './components/settings/WorkflowsPanel';@@ -279,11 +280,19 @@ function RecordingView({ onBack }: RecordingViewProps) {const { isCallActive, callSummary, nudgeHistory } = useCopilotStore();const { status } = useSession();const meetingSetupStore = useMeetingSetupStore();+ const { prepareNewSession } = useSessionLifecycle();const isRecording = status === 'recording';const isProcessing = status === 'processing' || status === 'stopping';const isIdle = status === 'idle';+ // Handle navigation when session becomes idle (via useEffect, not during render)+ React.useEffect(() => {+ if (isIdle && !callSummary) {+ onBack?.();+ }+ }, [isIdle, callSummary, onBack]);+// Get checklist from meeting setupconst { checklist } = meetingSetupStore;const hasChecklist = checklist.length > 0;@@ -299,16 +308,14 @@ function RecordingView({ onBack }: RecordingViewProps) {useCopilot();- // Reset meeting setup when starting a new call+ // Reset all session state when starting a new callconst handleStartNewCall = () => {- useCopilotStore.getState().reset();- meetingSetupStore.reset();+ prepareNewSession();};- // Go back to home+ // Go back to home - clear all session stateconst handleGoBack = () => {- useCopilotStore.getState().reset();- meetingSetupStore.reset();+ prepareNewSession();onBack?.();};@@ -366,9 +373,9 @@ function RecordingView({ onBack }: RecordingViewProps) {);}- // If idle, go back to home (user shouldn't see RecordingView when idle)- if (isIdle) {- onBack?.();+ // If idle with no summary, the useEffect above handles navigation+ // Return null to prevent flash of recording UI+ if (isIdle && !callSummary) {return null;}@@ -404,12 +411,25 @@ function RecordingView({ onBack }: RecordingViewProps) {);}-function SettingsView() {+interface SettingsViewProps {+ initialTab?: 'account' | 'calendar' | 'mcpServers' | 'workflows' | null;+ onClearInitialTab?: () => void;+}++function SettingsView({ initialTab, onClearInitialTab }: SettingsViewProps) {const [activeSettingsTab, setActiveSettingsTab] = useState<'account' | 'calendar' | 'mcpServers' | 'workflows'- >('account');+ >(initialTab || 'account');const configStore = useConfigStore();+ // Apply initial tab when it changes+ React.useEffect(() => {+ if (initialTab) {+ setActiveSettingsTab(initialTab);+ onClearInitialTab?.();+ }+ }, [initialTab, onClearInitialTab]);+const settingsTabs = [{ id: 'account' as const, label: 'Account' },{ id: 'calendar' as const, label: 'Calendar' },@@ -499,12 +519,17 @@ export function App() {currentMeeting?: { id: string; summary: string };nextMeeting: { id: string; summary: string; description?: string };} | null>(null);+ // Recording ID to navigate to after recording ends+ const [pendingRecordingNavigation, setPendingRecordingNavigation] = useState<number | null>(null);+ // Settings tab to show when navigating to settings+ const [initialSettingsTab, setInitialSettingsTab] = useState<'account' | 'calendar' | 'mcpServers' | 'workflows' | null>(null);const configStore = useConfigStore();const sessionStore = useSessionStore();const meetingSetupStore = useMeetingSetupStore();const { status: sessionStatus, startRecording, stopRecording } = useSession();const { allGranted, loading: permissionsLoading, checkPermissions } = usePermissions();+ const { prepareNewSession, prepareNewSessionWithInfo, waitForIdle } = useSessionLifecycle();// Global listener for recorder events - persists during navigationuseGlobalRecorderEvents();@@ -517,9 +542,8 @@ export function App() {// Handle "open meeting setup" from notification/tray clickconst unsubOpenSetup = window.electronAPI.calendarOn.onOpenMeetingSetup((meeting) => {- // Pre-fill the meeting setup store with meeting data- meetingSetupStore.reset();- meetingSetupStore.setInfo(meeting.summary, meeting.description || '');+ // Clear all stale state and pre-fill meeting info+ prepareNewSessionWithInfo(meeting.summary, meeting.description || '');// Switch to home tab and show meeting setupsetActiveTab('home');@@ -528,9 +552,8 @@ export function App() {// Handle "auto-start recording" from notification or default_record behaviorconst unsubAutoStart = window.electronAPI.calendarOn.onAutoStartRecording(async (meeting) => {- // Skip UX entirely - start recording with meeting name- meetingSetupStore.reset();- meetingSetupStore.setInfo(meeting.summary, meeting.description || '');+ // Clear ALL stale state (including old call summaries) before starting new recording+ prepareNewSessionWithInfo(meeting.summary, meeting.description || '');// Ensure we're on home tabsetActiveTab('home');@@ -568,7 +591,7 @@ export function App() {unsubAutoStart();unsubOverlap();};- }, [isAuthenticated, meetingSetupStore, startRecording]);+ }, [isAuthenticated, startRecording, prepareNewSessionWithInfo]);// Handle pending overlap action (stop current, start next)React.useEffect(() => {@@ -583,8 +606,11 @@ export function App() {// Clear the current recording meetingawait window.electronAPI.calendar.setRecordingMeeting(null);- // Wait a moment for recording to fully stop- await new Promise(resolve => setTimeout(resolve, 500));+ // Wait for session to properly reach idle state (no arbitrary timeout)+ await waitForIdle();++ // Clear all stale state before starting next meeting+ prepareNewSessionWithInfo(nextMeeting.summary, nextMeeting.description || '');// Notify main process about new meeting we're recordingawait window.electronAPI.calendar.setRecordingMeeting(nextMeeting.id);@@ -603,7 +629,7 @@ export function App() {if (pendingOverlap) {handleOverlap();}- }, [pendingOverlap, stopRecording, startRecording]);+ }, [pendingOverlap, stopRecording, startRecording, waitForIdle, prepareNewSessionWithInfo]);// Clear recording meeting when session becomes idleReact.useEffect(() => {@@ -631,13 +657,24 @@ export function App() {// Handle start recording button from HomeView - show MeetingSetupFlowconst handleStartRecording = () => {+ prepareNewSession(); // Clear any stale state from previous sessionssetShowMeetingSetup(true);};- // Handle returning from recording/setup mode+ // Handle returning from recording/setup mode - navigate to history (detail page if we have a recording ID)const handleExitRecordingMode = () => {setShowMeetingSetup(false);- sessionStore.reset();++ // Capture recording ID before clearing state (may be null if something went wrong)+ const recordingId = sessionStore.recordingId;+ if (recordingId) {+ setPendingRecordingNavigation(recordingId);+ }++ // Always navigate to history - shows detail if we have ID, otherwise shows list+ setActiveTab('history');++ prepareNewSession();};const renderContent = () => {@@ -716,13 +753,26 @@ export function App() {<HomeViewonStartRecording={handleStartRecording}onNavigateToHistory={() => setActiveTab('history')}- onNavigateToSettings={() => setActiveTab('settings')}+ onNavigateToSettings={(tab) => {+ if (tab) setInitialSettingsTab(tab);+ setActiveTab('settings');+ }}/>);case 'history':- return <HistoryView />;+ return (+ <HistoryView+ initialSelectedRecordingId={pendingRecordingNavigation}+ onClearInitialSelection={() => setPendingRecordingNavigation(null)}+ />+ );case 'settings':- return <SettingsView />;+ return (+ <SettingsView+ initialTab={initialSettingsTab}+ onClearInitialTab={() => setInitialSettingsTab(null)}+ />+ );}};diff --git a/src/renderer/components/history/HistoryView.tsx b/src/renderer/components/history/HistoryView.tsxindex 61dbf4c..b11503c 100644--- a/src/renderer/components/history/HistoryView.tsx+++ b/src/renderer/components/history/HistoryView.tsx@@ -3,13 +3,28 @@ import { RefreshCw, Inbox, Search } from 'lucide-react';import { RecordingCard } from './RecordingCard';import { RecordingDetailPage } from './RecordingDetailPage';import { trpc } from '../../api/trpc';+import { useSessionStore } from '../../stores/session.store';import type { Recording } from '../../../shared/schemas/recording.schema';-export function HistoryView() {- const [selectedRecordingId, setSelectedRecordingId] = useState<number | null>(null);+interface HistoryViewProps {+ initialSelectedRecordingId?: number | null;+ onClearInitialSelection?: () => void;+}++export function HistoryView({ initialSelectedRecordingId, onClearInitialSelection }: HistoryViewProps = {}) {+ const [selectedRecordingId, setSelectedRecordingId] = useState<number | null>(initialSelectedRecordingId ?? null);++ useEffect(() => {+ if (initialSelectedRecordingId != null) {+ setSelectedRecordingId(initialSelectedRecordingId);+ onClearInitialSelection?.();+ }+ }, [initialSelectedRecordingId, onClearInitialSelection]);const [hasCleanedUp, setHasCleanedUp] = useState(false);const [searchQuery, setSearchQuery] = useState('');+ const activeSessionId = useSessionStore((state) => state.sessionId);+const { data: recordings, isLoading, refetch } = trpc.recordings.list.useQuery(undefined,{@@ -27,17 +42,22 @@ export function HistoryView() {useEffect(() => {if (!hasCleanedUp && recordings) {+ // Check for stale recordings older than 1 hour (excluding active session)const staleCount = recordings.filter(r => (r.status === 'processing' || r.status === 'recording') &&- Date.now() - new Date(r.createdAt).getTime() > 30 * 60 * 1000+ r.sessionId !== activeSessionId &&+ Date.now() - new Date(r.createdAt).getTime() > 60 * 60 * 1000).length;if (staleCount > 0) {- cleanupMutation.mutate({ maxAgeMinutes: 30 });+ cleanupMutation.mutate({+ maxAgeMinutes: 60,+ excludeSessionId: activeSessionId || undefined,+ });}setHasCleanedUp(true);}- }, [recordings, hasCleanedUp]);+ }, [recordings, hasCleanedUp, activeSessionId]);// Sort recordings by date (newest first) and filter by search queryconst filteredRecordings = useMemo(() => {diff --git a/src/renderer/components/home/HomeView.tsx b/src/renderer/components/home/HomeView.tsxindex b1c75dd..c9b8f2d 100644--- a/src/renderer/components/home/HomeView.tsx+++ b/src/renderer/components/home/HomeView.tsx@@ -365,7 +365,7 @@ function WorkflowItem({interface HomeViewProps {onStartRecording: () => void;onNavigateToHistory: () => void;- onNavigateToSettings: () => void;+ onNavigateToSettings: (tab?: 'account' | 'calendar' | 'mcpServers' | 'workflows') => void;}interface WorkflowData {@@ -692,7 +692,7 @@ export function HomeView({ onStartRecording, onNavigateToHistory, onNavigateToSe<MCPIcon /><span className="flex-1 text-[18px] font-medium text-black">MCPs</span><button- onClick={onNavigateToSettings}+ onClick={() => onNavigateToSettings('mcpServers')}className="flex items-center gap-[4px] text-[14px] font-medium text-[#ec5b16] hover:opacity-80"><span className="text-[14px]">+</span>@@ -713,7 +713,7 @@ export function HomeView({ onStartRecording, onNavigateToHistory, onNavigateToSe</p></div><button- onClick={onNavigateToSettings}+ onClick={() => onNavigateToSettings('mcpServers')}className="flex items-center gap-[4px] bg-white border border-[#e4e4ec] px-[16px] py-[12px] rounded-[12px] shadow-[0px_1.272px_15.267px_0px_rgba(0,0,0,0.05)] hover:bg-gray-50 transition-colors"><span className="text-[14px]">+</span>@@ -736,7 +736,7 @@ export function HomeView({ onStartRecording, onNavigateToHistory, onNavigateToSe<WorkflowIcon /><span className="flex-1 text-[18px] font-medium text-black">Workflows</span><button- onClick={onNavigateToSettings}+ onClick={() => onNavigateToSettings('workflows')}className="flex items-center gap-[4px] text-[14px] font-medium text-[#ec5b16] hover:opacity-80"><span className="text-[14px]">+</span>@@ -757,7 +757,7 @@ export function HomeView({ onStartRecording, onNavigateToHistory, onNavigateToSe</p></div><button- onClick={onNavigateToSettings}+ onClick={() => onNavigateToSettings('workflows')}className="flex items-center gap-[4px] bg-white border border-[#e4e4ec] px-[16px] py-[12px] rounded-[12px] shadow-[0px_1.272px_15.267px_0px_rgba(0,0,0,0.05)] hover:bg-gray-50 transition-colors"><span className="text-[14px]">+</span>@@ -770,7 +770,7 @@ export function HomeView({ onStartRecording, onNavigateToHistory, onNavigateToSe<WorkflowItemkey={workflow.id}workflow={workflow}- onEdit={onNavigateToSettings}+ onEdit={() => onNavigateToSettings('workflows')}/>))}</div>diff --git a/src/renderer/components/meeting-setup/InfoStep.tsx b/src/renderer/components/meeting-setup/InfoStep.tsxindex 780e919..330b753 100644--- a/src/renderer/components/meeting-setup/InfoStep.tsx+++ b/src/renderer/components/meeting-setup/InfoStep.tsx@@ -57,7 +57,7 @@ interface InfoStepProps {isSkipping?: boolean;onBack: () => void;onNext: (name: string, description: string) => void;- onSkip: () => void;+ onSkip: (name: string, description: string) => void;}export function InfoStep({@@ -172,7 +172,10 @@ export function InfoStep({{/* Skip and Record button */}<buttontype="button"- onClick={onSkip}+ onClick={() => {+ console.log('[InfoStep] Skip clicked, passing name:', name.trim(), 'description:', description.trim());+ onSkip(name.trim(), description.trim());+ }}disabled={isDisabled}className="w-full flex items-center justify-center gap-[6px] px-[20px] py-[12px] bg-transparent border border-dashed border-[#c0c0c8] rounded-[12px] text-[14px] font-medium text-[#464646] hover:border-[#ec5b16] hover:text-[#ec5b16] disabled:opacity-50 disabled:cursor-not-allowed transition-colors">diff --git a/src/renderer/components/meeting-setup/MeetingSetupFlow.tsx b/src/renderer/components/meeting-setup/MeetingSetupFlow.tsxindex bba348c..07dfbcb 100644--- a/src/renderer/components/meeting-setup/MeetingSetupFlow.tsx+++ b/src/renderer/components/meeting-setup/MeetingSetupFlow.tsx@@ -54,12 +54,26 @@ export function MeetingSetupFlow({ onCancel }: MeetingSetupFlowProps) {}, [setStep]);// Skip setup and start recording with whatever data is already filled- const handleSkipAndRecord = async () => {- const meetingName = name.trim() || generateDefaultMeetingName();+ // Accepts optional overrides for name/description from local step state+ const handleSkipAndRecord = async (overrideName?: string, overrideDescription?: string) => {+ console.log('[MeetingSetupFlow] handleSkipAndRecord called');+ console.log('[MeetingSetupFlow] overrideName:', overrideName);+ console.log('[MeetingSetupFlow] overrideDescription:', overrideDescription);+ console.log('[MeetingSetupFlow] store name:', name);+ console.log('[MeetingSetupFlow] store description:', description);++ const finalName = (overrideName ?? name).trim() || generateDefaultMeetingName();+ const finalDescription = (overrideDescription ?? description).trim();++ console.log('[MeetingSetupFlow] finalName:', finalName);+ console.log('[MeetingSetupFlow] finalDescription:', finalDescription);++ // Update store so RecordingHeader can display the correct name+ setInfo(finalName, finalDescription);await startRecording({- name: meetingName,- description: description.trim(),+ name: finalName,+ description: finalDescription,questions: questions.filter(q => q.answer), // Only include answered questionschecklist,});diff --git a/src/renderer/hooks/useSession.ts b/src/renderer/hooks/useSession.tsindex 426723d..aa1028c 100644--- a/src/renderer/hooks/useSession.ts+++ b/src/renderer/hooks/useSession.ts@@ -5,7 +5,7 @@ import { useVisualIndexStore } from '../stores/visual-index.store';import { useConfigStore } from '../stores/config.store';import { useCopilotStore } from '../stores/copilot.store';import { useMCPStore } from '../stores/mcp.store';-import { useMeetingSetupStore } from '../stores/meeting-setup.store';+import { useLiveAssistStore } from '../stores/live-assist.store';import { trpc } from '../api/trpc';import { getElectronAPI } from '../api/ipc';import type { ProbingQuestion } from '../../shared/types/meeting-setup.types';@@ -125,6 +125,11 @@ export function useSession() {meetingChecklist: meetingSetup?.checklist,});+ // Store recording ID for post-session navigation+ if (recordingResult?.id) {+ sessionStore.setRecordingId(recordingResult.id);+ }+const hasTranscription = transcriptionStore.enabled && (result.micWsConnectionId || result.sysAudioWsConnectionId);const hasVisualIndex = useVisualIndexStore.getState().enabled && result.screenWsConnectionId;@@ -208,6 +213,7 @@ export function useSession() {transcriptionStore.clear();useVisualIndexStore.getState().clear();+ useLiveAssistStore.getState().clear();const copilotState = useCopilotStore.getState();if (!copilotState.callSummary) {@@ -225,6 +231,7 @@ export function useSession() {transcriptionStore.clear();useVisualIndexStore.getState().clear();+ useLiveAssistStore.getState().clear();useCopilotStore.getState().reset();}}, [sessionStore, transcriptionStore, stopRecordingMutation]);diff --git a/src/renderer/hooks/useSessionLifecycle.ts b/src/renderer/hooks/useSessionLifecycle.tsnew file mode 100644index 0000000..e0c9754--- /dev/null+++ b/src/renderer/hooks/useSessionLifecycle.ts@@ -0,0 +1,111 @@+/**+ * useSessionLifecycle Hook+ *+ * Centralized session lifecycle manager that ensures atomic state transitions.+ * All session start/stop operations should go through this hook to prevent+ * stale state issues and race conditions.+ */++import { useCallback } from 'react';+import { useSessionStore } from '../stores/session.store';+import { useCopilotStore } from '../stores/copilot.store';+import { useMeetingSetupStore } from '../stores/meeting-setup.store';+import { useTranscriptionStore } from '../stores/transcription.store';+import { useLiveAssistStore } from '../stores/live-assist.store';+import { useVisualIndexStore } from '../stores/visual-index.store';+import { useMCPStore } from '../stores/mcp.store';++/**+ * Clears all session-related stores atomically.+ * This is the single source of truth for "what needs to be reset for a fresh session".+ */+export function resetAllSessionStores() {+ // Clear copilot state (metrics, nudges, summary, transcripts)+ useCopilotStore.getState().reset();++ // Clear meeting setup state (name, description, questions, checklist)+ useMeetingSetupStore.getState().reset();++ // Clear transcription state+ useTranscriptionStore.getState().clear();++ // Clear live assist state+ useLiveAssistStore.getState().clear();++ // Clear visual index state+ useVisualIndexStore.getState().clear();++ // Clear MCP results (but keep server configs)+ useMCPStore.getState().clearResults();+}++/**+ * Returns a promise that resolves when session status becomes 'idle'.+ * Uses Zustand subscription for proper state-based waiting.+ */+export function waitForSessionIdle(): Promise<void> {+ return new Promise<void>((resolve) => {+ // Check if already idle+ if (useSessionStore.getState().status === 'idle') {+ resolve();+ return;+ }++ // Subscribe and wait for idle+ const unsub = useSessionStore.subscribe((state) => {+ if (state.status === 'idle') {+ unsub();+ resolve();+ }+ });+ });+}++export function useSessionLifecycle() {+ const sessionStore = useSessionStore();++ /**+ * Prepares a fresh session by clearing all stale state.+ * MUST be called before any new recording starts.+ *+ * This ensures:+ * - Old call summaries don't show up for new calls+ * - Previous meeting setup data is cleared+ * - Transcripts, assists, and visual index are fresh+ */+ const prepareNewSession = useCallback(() => {+ resetAllSessionStores();++ // Clear session error but preserve stream preferences+ sessionStore.setError(null);+ }, [sessionStore]);++ /**+ * Wait for the current session to reach idle state.+ * Use this instead of arbitrary setTimeout delays.+ */+ const waitForIdle = useCallback(() => {+ return waitForSessionIdle();+ }, []);++ /**+ * Prepare for a new session and optionally pre-fill meeting info.+ * Use this when navigating to meeting setup from notifications/calendar.+ */+ const prepareNewSessionWithInfo = useCallback(+ (name: string, description: string) => {+ prepareNewSession();+ useMeetingSetupStore.getState().setInfo(name, description);+ },+ [prepareNewSession]+ );++ return {+ prepareNewSession,+ prepareNewSessionWithInfo,+ waitForIdle,+ resetAllSessionStores,+ };+}++export default useSessionLifecycle;diff --git a/src/renderer/stores/session.store.ts b/src/renderer/stores/session.store.tsindex 1947c0a..b67c3c6 100644--- a/src/renderer/stores/session.store.ts+++ b/src/renderer/stores/session.store.ts@@ -11,6 +11,7 @@ interface StreamState {interface SessionState {status: SessionStatus;sessionId: string | null;+ recordingId: number | null; // Database recording ID for navigation after stopsessionToken: string | null;tokenExpiresAt: number | null;startTime: number | null;@@ -22,6 +23,7 @@ interface SessionState {// ActionssetStatus: (status: SessionStatus) => void;+ setRecordingId: (id: number | null) => void;startSession: (sessionId: string, sessionToken: string, expiresAt: number, screenWsConnectionId?: string) => void;stopSession: () => void;setSessionToken: (token: string, expiresAt: number) => void;@@ -44,6 +46,7 @@ const initialStreams: StreamState = {export const useSessionStore = create<SessionState>((set, get) => ({status: 'idle',sessionId: null,+ recordingId: null,sessionToken: null,tokenExpiresAt: null,startTime: null,@@ -55,6 +58,8 @@ export const useSessionStore = create<SessionState>((set, get) => ({setStatus: (status) => set({ status }),+ setRecordingId: (id) => set({ recordingId: id }),+startSession: (sessionId, sessionToken, expiresAt, screenWsConnectionId) => {set({status: 'recording',@@ -118,6 +123,7 @@ export const useSessionStore = create<SessionState>((set, get) => ({set({status: 'idle',sessionId: null,+ recordingId: null,startTime: null,elapsedTime: 0,streams: initialStreams,