diff --git a/MeetingAssistant.Tests/NotificationActivationArgumentsTests.cs b/MeetingAssistant.Tests/NotificationActivationArgumentsTests.cs index 6fe719e..f1d44f0 100644 --- a/MeetingAssistant.Tests/NotificationActivationArgumentsTests.cs +++ b/MeetingAssistant.Tests/NotificationActivationArgumentsTests.cs @@ -25,4 +25,16 @@ public sealed class NotificationActivationArgumentsTests Assert.Equal("abc123", arguments["promptId"]); Assert.Equal("continue", arguments["response"]); } + + [Fact] + public void InactivityPromptActionsIncludePauseAndParseItsResponse() + { + Assert.Contains( + MeetingInactivityPromptActions.All, + action => action.Content == "Pause transcription" && + action.ResponseArgument == "pause"); + Assert.Equal( + MeetingInactivityPromptResponse.Pause, + MeetingInactivityPromptActions.ParseResponse("pause")); + } } diff --git a/MeetingAssistant.Tests/RecordingCoordinatorTests.cs b/MeetingAssistant.Tests/RecordingCoordinatorTests.cs index e5d0973..9e89090 100644 --- a/MeetingAssistant.Tests/RecordingCoordinatorTests.cs +++ b/MeetingAssistant.Tests/RecordingCoordinatorTests.cs @@ -9,6 +9,7 @@ using MeetingAssistant.Workflow; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; +using System.Collections.Concurrent; using System.Threading.Channels; namespace MeetingAssistant.Tests; @@ -116,6 +117,52 @@ public sealed class RecordingCoordinatorTests Assert.False(stopped.IsRecording); } + [Fact] + public async Task PauseRoutesSilenceAndUnpauseResumesCapturedAudioThroughSameRun() + { + var audioSource = new ControlledAudioSource(); + var provider = new CapturingAudioStreamingTranscriptionProvider(); + var audioArchive = new InMemoryRecordedAudioStore(); + var pipelineFactory = new TestSpeechRecognitionPipelineFactory(provider); + var coordinator = new MeetingRecordingCoordinator( + audioSource, + pipelineFactory, + new InMemoryTranscriptStore(), + new InMemoryMeetingNoteStore(), + new CapturingMeetingNoteOpener(), + new InMemoryMeetingArtifactStore(), + audioArchive, + new CapturingMeetingSummaryPipeline(), + Options.Create(new MeetingAssistantOptions()), + NullLogger.Instance); + + await coordinator.StartAsync(CancellationToken.None); + var paused = await coordinator.SetTranscriptionPausedAsync(true, CancellationToken.None); + await audioSource.WriteAsync(new AudioChunk([1, 2, 3, 4], 16000, 1), CancellationToken.None); + await WaitUntilAsync(() => provider.Chunks.Count >= 1); + + Assert.True(paused.IsRecording); + Assert.True(paused.IsPaused); + Assert.Equal([0, 0, 0, 0], provider.Chunks.ElementAt(0).Pcm); + Assert.Equal([0, 0, 0, 0], audioArchive.AppendedChunks[0].Pcm); + + var unpaused = await coordinator.SetTranscriptionPausedAsync(false, CancellationToken.None); + await audioSource.WriteAsync(new AudioChunk([5, 6], 16000, 1), CancellationToken.None); + await WaitUntilAsync(() => provider.Chunks.Count >= 2); + + Assert.True(unpaused.IsRecording); + Assert.False(unpaused.IsPaused); + Assert.Equal([5, 6], provider.Chunks.ElementAt(1).Pcm); + Assert.Equal([5, 6], audioArchive.AppendedChunks[1].Pcm); + Assert.Equal(1, pipelineFactory.CreateCount); + + await coordinator.SetTranscriptionPausedAsync(true, CancellationToken.None); + var stopped = await coordinator.StopAsync(CancellationToken.None); + + Assert.False(stopped.IsRecording); + Assert.Equal(1, pipelineFactory.CreateCount); + } + [Fact] public async Task TranscriptLineWorkflowRuleTransformsLiveTranscriptAfterDurableAppend() { @@ -596,6 +643,50 @@ public sealed class RecordingCoordinatorTests noteStore.SavedNote?.Frontmatter.EndTime); } + [Fact] + public async Task InactivityPromptCanPauseItsOriginatingActiveMeeting() + { + var clock = new ManualMeetingInactivityClock(DateTimeOffset.Parse("2026-06-02T10:30:00+02:00")); + var promptService = new CapturingMeetingInactivityPromptService(MeetingInactivityPromptResponse.Pause); + var coordinator = new MeetingRecordingCoordinator( + new ControlledAudioSource(), + new TestSpeechRecognitionPipelineFactory(new EchoStreamingTranscriptionProvider()), + new InMemoryTranscriptStore(), + new InMemoryMeetingNoteStore(), + new CapturingMeetingNoteOpener(), + new InMemoryMeetingArtifactStore(), + new InMemoryRecordedAudioStore(), + new CapturingMeetingSummaryPipeline(), + Options.Create(new MeetingAssistantOptions + { + Recording = + { + InactivitySafeguard = + { + FirstPromptAfter = TimeSpan.FromSeconds(2), + ReminderPromptAfter = [], + AutoStopAfter = TimeSpan.FromMinutes(30), + CheckInterval = TimeSpan.FromSeconds(1) + } + } + }), + NullLogger.Instance, + inactivityPromptService: promptService, + inactivityClock: clock); + + await coordinator.StartAsync(CancellationToken.None); + await WaitUntilAsync(() => clock.PendingDelayCount > 0); + clock.Advance(TimeSpan.FromSeconds(2)); + await promptService.WaitForPromptAsync(); + await WaitUntilAsync(() => coordinator.CurrentStatus.IsPaused); + await WaitUntilAsync(() => promptService.DismissAllCount >= 1); + + Assert.True(coordinator.CurrentStatus.IsRecording); + Assert.True(promptService.DismissAllCount >= 1); + + await coordinator.StopAsync(CancellationToken.None); + } + [Fact] public async Task InactivitySafeguardAutoStopsNormallyAndUsesMeetingStartWhenNoTranscriptArrives() { @@ -749,6 +840,645 @@ public sealed class RecordingCoordinatorTests await coordinator.StopAsync(CancellationToken.None); } + [Fact] + public async Task NewTranscriptTextDismissesOutstandingInactivityPrompts() + { + var clock = new ManualMeetingInactivityClock(DateTimeOffset.Parse("2026-06-02T12:30:00+02:00")); + var promptService = new IgnoringMeetingInactivityPromptService(); + var audioSource = new ControlledAudioSource(); + var transcriptStore = new InMemoryTranscriptStore(); + var coordinator = new MeetingRecordingCoordinator( + audioSource, + new TestSpeechRecognitionPipelineFactory(new EchoStreamingTranscriptionProvider()), + transcriptStore, + new InMemoryMeetingNoteStore(), + new CapturingMeetingNoteOpener(), + new InMemoryMeetingArtifactStore(), + new InMemoryRecordedAudioStore(), + new CapturingMeetingSummaryPipeline(), + Options.Create(new MeetingAssistantOptions + { + Recording = + { + InactivitySafeguard = + { + FirstPromptAfter = TimeSpan.FromSeconds(2), + ReminderPromptAfter = [], + AutoStopAfter = TimeSpan.FromMinutes(30), + CheckInterval = TimeSpan.FromSeconds(1) + } + } + }), + NullLogger.Instance, + inactivityPromptService: promptService, + inactivityClock: clock); + + await coordinator.StartAsync(CancellationToken.None); + await WaitUntilAsync(() => clock.PendingDelayCount > 0); + clock.Advance(TimeSpan.FromSeconds(2)); + await promptService.WaitForPromptAsync(); + + await audioSource.WriteAsync(new AudioChunk([1, 0], 16000, 1), CancellationToken.None); + await transcriptStore.WaitForTextAsync("chunk:2"); + + await WaitUntilAsync(() => promptService.DismissAllCount == 1); + Assert.Single(promptService.Requests); + + await coordinator.StopAsync(CancellationToken.None); + } + + [Fact] + public async Task BlankTranscriptSegmentDoesNotDismissOutstandingInactivityPrompts() + { + var clock = new ManualMeetingInactivityClock(DateTimeOffset.Parse("2026-06-02T12:40:00+02:00")); + var promptService = new IgnoringMeetingInactivityPromptService(); + var audioSource = new ControlledAudioSource(); + var transcriptStore = new InMemoryTranscriptStore(); + var provider = new SequencedStreamingTranscriptionProvider( + [ + new TranscriptionSegment(TimeSpan.Zero, TimeSpan.Zero, "Unknown", " "), + new TranscriptionSegment( + TimeSpan.Zero, + TimeSpan.Zero, + "System", + "", + TranscriptionSegmentKind.Marker, + MarkerId: "test-marker") + ]); + var coordinator = new MeetingRecordingCoordinator( + audioSource, + new TestSpeechRecognitionPipelineFactory(provider), + transcriptStore, + new InMemoryMeetingNoteStore(), + new CapturingMeetingNoteOpener(), + new InMemoryMeetingArtifactStore(), + new InMemoryRecordedAudioStore(), + new CapturingMeetingSummaryPipeline(), + Options.Create(new MeetingAssistantOptions + { + Recording = + { + InactivitySafeguard = + { + FirstPromptAfter = TimeSpan.FromSeconds(2), + ReminderPromptAfter = [], + AutoStopAfter = TimeSpan.FromMinutes(30), + CheckInterval = TimeSpan.FromSeconds(1) + } + } + }), + NullLogger.Instance, + inactivityPromptService: promptService, + inactivityClock: clock); + + await coordinator.StartAsync(CancellationToken.None); + await WaitUntilAsync(() => clock.PendingDelayCount > 0); + clock.Advance(TimeSpan.FromSeconds(2)); + await promptService.WaitForPromptAsync(); + + await audioSource.WriteAsync(new AudioChunk([1, 0], 16000, 1), CancellationToken.None); + await audioSource.WriteAsync(new AudioChunk([2, 0], 16000, 1), CancellationToken.None); + await WaitUntilAsync(() => transcriptStore.Segments.Count == 2); + + Assert.Equal(0, promptService.DismissAllCount); + + await coordinator.StopAsync(CancellationToken.None); + } + + [Fact] + public async Task LateTranscriptFromStoppedRunDoesNotDismissCurrentRunInactivityPrompt() + { + var clock = new ManualMeetingInactivityClock(DateTimeOffset.Parse("2026-06-02T12:42:00+02:00")); + var promptService = new IgnoringMeetingInactivityPromptService(); + var delayedProvider = new DelayedSegmentOnAudioCompletionProvider( + new TranscriptionSegment(TimeSpan.Zero, TimeSpan.FromSeconds(1), "Guest-01", "late old-run text")); + var coordinator = new MeetingRecordingCoordinator( + new ControlledAudioSource(), + new SequencedSpeechRecognitionPipelineFactory( + delayedProvider, + new EchoStreamingTranscriptionProvider()), + new InMemoryTranscriptStore(), + new InMemoryMeetingNoteStore(), + new CapturingMeetingNoteOpener(), + new InMemoryMeetingArtifactStore(), + new InMemoryRecordedAudioStore(), + new CapturingMeetingSummaryPipeline(), + Options.Create(new MeetingAssistantOptions + { + Recording = + { + InactivitySafeguard = + { + FirstPromptAfter = TimeSpan.FromSeconds(2), + ReminderPromptAfter = [], + AutoStopAfter = TimeSpan.FromMinutes(30), + CheckInterval = TimeSpan.FromSeconds(1) + } + } + }), + NullLogger.Instance, + inactivityPromptService: promptService, + inactivityClock: clock); + + await coordinator.StartAsync(CancellationToken.None); + await WaitUntilAsync(() => clock.PendingDelayCount > 0); + var oldStopTask = coordinator.StopAsync(CancellationToken.None); + await delayedProvider.WaitForAudioCompletionAsync(); + + await coordinator.StartAsync(CancellationToken.None); + await WaitUntilAsync(() => clock.PendingDelayCount >= 2); + clock.Advance(TimeSpan.FromSeconds(2)); + await promptService.WaitForPromptAsync(); + Assert.Equal(0, promptService.DismissAllCount); + + delayedProvider.ReleaseSegment(); + await oldStopTask; + + Assert.True(coordinator.CurrentStatus.IsRecording); + Assert.Equal(0, promptService.DismissAllCount); + + await coordinator.StopAsync(CancellationToken.None); + } + + [Fact] + public async Task NewTranscriptTextInvalidatesAnAlreadyDequeuedInactivityAction() + { + var clock = new ManualMeetingInactivityClock(DateTimeOffset.Parse("2026-06-02T12:45:00+02:00")); + var promptService = new IgnoringMeetingInactivityPromptService(); + var audioSource = new ControlledAudioSource(); + var transcriptStore = new InMemoryTranscriptStore(); + var coordinator = new MeetingRecordingCoordinator( + audioSource, + new TestSpeechRecognitionPipelineFactory(new EchoStreamingTranscriptionProvider()), + transcriptStore, + new InMemoryMeetingNoteStore(), + new CapturingMeetingNoteOpener(), + new InMemoryMeetingArtifactStore(), + new InMemoryRecordedAudioStore(), + new CapturingMeetingSummaryPipeline(), + Options.Create(new MeetingAssistantOptions + { + Recording = + { + InactivitySafeguard = + { + FirstPromptAfter = TimeSpan.FromSeconds(2), + ReminderPromptAfter = [], + AutoStopAfter = TimeSpan.FromMinutes(30), + CheckInterval = TimeSpan.FromSeconds(1) + } + } + }), + NullLogger.Instance, + inactivityPromptService: promptService, + inactivityClock: clock); + + await coordinator.StartAsync(CancellationToken.None); + await WaitUntilAsync(() => clock.PendingDelayCount > 0); + clock.Advance(TimeSpan.FromSeconds(2)); + await promptService.WaitForPromptAsync(); + + await audioSource.WriteAsync(new AudioChunk([1, 0], 16000, 1), CancellationToken.None); + await transcriptStore.WaitForTextAsync("chunk:2"); + await WaitUntilAsync(() => promptService.DismissAllCount == 1); + await promptService.RespondAsync(MeetingInactivityPromptResponse.Stop); + + Assert.True(coordinator.CurrentStatus.IsRecording); + + await coordinator.StopAsync(CancellationToken.None); + } + + [Fact] + public async Task InactivityActionRemainsValidUntilNewTranscriptIsDurablyWritten() + { + var clock = new ManualMeetingInactivityClock(DateTimeOffset.Parse("2026-06-02T12:47:00+02:00")); + var promptService = new IgnoringMeetingInactivityPromptService(); + var audioSource = new ControlledAudioSource(); + var transcriptStore = new InMemoryTranscriptStore(); + var coordinator = new MeetingRecordingCoordinator( + audioSource, + new TestSpeechRecognitionPipelineFactory(new EchoStreamingTranscriptionProvider()), + transcriptStore, + new InMemoryMeetingNoteStore(), + new CapturingMeetingNoteOpener(), + new InMemoryMeetingArtifactStore(), + new InMemoryRecordedAudioStore(), + new CapturingMeetingSummaryPipeline(), + Options.Create(new MeetingAssistantOptions + { + Recording = + { + InactivitySafeguard = + { + FirstPromptAfter = TimeSpan.FromSeconds(2), + ReminderPromptAfter = [], + AutoStopAfter = TimeSpan.FromMinutes(30), + CheckInterval = TimeSpan.FromSeconds(1) + } + } + }), + NullLogger.Instance, + inactivityPromptService: promptService, + inactivityClock: clock); + + await coordinator.StartAsync(CancellationToken.None); + await WaitUntilAsync(() => clock.PendingDelayCount > 0); + clock.Advance(TimeSpan.FromSeconds(2)); + await promptService.WaitForPromptAsync(); + + transcriptStore.BlockNextAppend(); + await audioSource.WriteAsync(new AudioChunk([1, 0], 16000, 1), CancellationToken.None); + await transcriptStore.WaitForBlockedAppendAsync(); + var responseTask = promptService.RespondAsync(MeetingInactivityPromptResponse.Stop); + await WaitUntilAsync(() => !coordinator.CurrentStatus.IsRecording || responseTask.IsCompleted); + + try + { + Assert.False(coordinator.CurrentStatus.IsRecording); + } + finally + { + transcriptStore.ReleaseBlockedAppend(); + await responseTask; + if (coordinator.CurrentStatus.IsRecording) + { + await coordinator.StopAsync(CancellationToken.None); + } + } + } + + [Fact] + public async Task PausingTranscriptionInvalidatesAnAlreadyDequeuedInactivityAction() + { + var clock = new ManualMeetingInactivityClock(DateTimeOffset.Parse("2026-06-02T12:50:00+02:00")); + var promptService = new IgnoringMeetingInactivityPromptService(); + var coordinator = new MeetingRecordingCoordinator( + new ControlledAudioSource(), + new TestSpeechRecognitionPipelineFactory(new EchoStreamingTranscriptionProvider()), + new InMemoryTranscriptStore(), + new InMemoryMeetingNoteStore(), + new CapturingMeetingNoteOpener(), + new InMemoryMeetingArtifactStore(), + new InMemoryRecordedAudioStore(), + new CapturingMeetingSummaryPipeline(), + Options.Create(new MeetingAssistantOptions + { + Recording = + { + InactivitySafeguard = + { + FirstPromptAfter = TimeSpan.FromSeconds(2), + ReminderPromptAfter = [], + AutoStopAfter = TimeSpan.FromMinutes(30), + CheckInterval = TimeSpan.FromSeconds(1) + } + } + }), + NullLogger.Instance, + inactivityPromptService: promptService, + inactivityClock: clock); + + await coordinator.StartAsync(CancellationToken.None); + await WaitUntilAsync(() => clock.PendingDelayCount > 0); + clock.Advance(TimeSpan.FromSeconds(2)); + await promptService.WaitForPromptAsync(); + + await coordinator.SetTranscriptionPausedAsync(true, CancellationToken.None); + await promptService.RespondAsync(MeetingInactivityPromptResponse.Stop); + + Assert.True(coordinator.CurrentStatus.IsRecording); + Assert.True(coordinator.CurrentStatus.IsPaused); + + await coordinator.StopAsync(CancellationToken.None); + } + + [Fact] + public async Task TranscriptWrittenWhilePauseActionWaitsForCoordinatorInvalidatesThatAction() + { + var clock = new ManualMeetingInactivityClock(DateTimeOffset.Parse("2026-06-02T12:52:00+02:00")); + var promptService = new IgnoringMeetingInactivityPromptService(); + var audioSource = new ControlledAudioSource(); + var transcriptStore = new InMemoryTranscriptStore(); + var noteStore = new InMemoryMeetingNoteStore(); + var coordinator = new MeetingRecordingCoordinator( + audioSource, + new TestSpeechRecognitionPipelineFactory(new EchoStreamingTranscriptionProvider()), + transcriptStore, + noteStore, + new CapturingMeetingNoteOpener(), + new InMemoryMeetingArtifactStore(), + new InMemoryRecordedAudioStore(), + new CapturingMeetingSummaryPipeline(), + Options.Create(new MeetingAssistantOptions + { + Recording = + { + InactivitySafeguard = + { + FirstPromptAfter = TimeSpan.FromSeconds(2), + ReminderPromptAfter = [], + AutoStopAfter = TimeSpan.FromMinutes(30), + CheckInterval = TimeSpan.FromSeconds(1) + } + } + }), + NullLogger.Instance, + inactivityPromptService: promptService, + inactivityClock: clock); + + await coordinator.StartAsync(CancellationToken.None); + await WaitUntilAsync(() => clock.PendingDelayCount > 0); + clock.Advance(TimeSpan.FromSeconds(2)); + await promptService.WaitForPromptAsync(); + + noteStore.BlockNextRead(); + promptService.BlockNextDismiss(); + var metadataTask = coordinator.AttachMetadataToCurrentMeetingAsync( + new MeetingMetadata("Updated meeting", [], ""), + CancellationToken.None); + await noteStore.WaitForBlockedReadAsync(); + var responseTask = promptService.RespondAsync(MeetingInactivityPromptResponse.Pause); + + await audioSource.WriteAsync(new AudioChunk([1, 0], 16000, 1), CancellationToken.None); + await transcriptStore.WaitForTextAsync("chunk:2"); + await Task.Delay(25); + noteStore.ReleaseBlockedRead(); + await promptService.WaitForBlockedDismissAsync(); + try + { + Assert.Same(responseTask, await Task.WhenAny(responseTask, Task.Delay(TimeSpan.FromSeconds(1)))); + } + finally + { + promptService.ReleaseBlockedDismiss(); + } + + await Task.WhenAll(metadataTask, responseTask); + + Assert.True(coordinator.CurrentStatus.IsRecording); + Assert.False(coordinator.CurrentStatus.IsPaused); + Assert.Equal(1, promptService.DismissAllCount); + + await coordinator.StopAsync(CancellationToken.None); + } + + [Fact] + public async Task PausingWhileAutoStopDecisionIsInFlightKeepsTheMeetingActive() + { + var clock = new ManualMeetingInactivityClock(DateTimeOffset.Parse("2026-06-02T12:55:00+02:00")); + var coordinator = new MeetingRecordingCoordinator( + new ControlledAudioSource(), + new TestSpeechRecognitionPipelineFactory(new EchoStreamingTranscriptionProvider()), + new InMemoryTranscriptStore(), + new InMemoryMeetingNoteStore(), + new CapturingMeetingNoteOpener(), + new InMemoryMeetingArtifactStore(), + new InMemoryRecordedAudioStore(), + new CapturingMeetingSummaryPipeline(), + Options.Create(new MeetingAssistantOptions + { + Recording = + { + InactivitySafeguard = + { + FirstPromptAfter = TimeSpan.Zero, + ReminderPromptAfter = [], + AutoStopAfter = TimeSpan.FromSeconds(5), + CheckInterval = TimeSpan.FromSeconds(1) + } + } + }), + NullLogger.Instance, + inactivityClock: clock); + + await coordinator.StartAsync(CancellationToken.None); + await WaitUntilAsync(() => clock.PendingDelayCount > 0); + clock.BlockNextNowRead(); + clock.Advance(TimeSpan.FromSeconds(5)); + await clock.WaitForBlockedNowReadAsync(); + + await coordinator.SetTranscriptionPausedAsync(true, CancellationToken.None); + clock.ReleaseBlockedNowRead(); + await WaitUntilAsync(() => !coordinator.CurrentStatus.IsRecording || clock.PendingDelayCount > 0); + + Assert.True(coordinator.CurrentStatus.IsRecording); + Assert.True(coordinator.CurrentStatus.IsPaused); + + await coordinator.StopAsync(CancellationToken.None); + } + + [Fact] + public async Task PausingWhileAnInactivityPromptIsBeingShownDismissesTheLatePrompt() + { + var clock = new ManualMeetingInactivityClock(DateTimeOffset.Parse("2026-06-02T12:57:00+02:00")); + var promptService = new BlockingMeetingInactivityPromptService(); + var coordinator = new MeetingRecordingCoordinator( + new ControlledAudioSource(), + new TestSpeechRecognitionPipelineFactory(new EchoStreamingTranscriptionProvider()), + new InMemoryTranscriptStore(), + new InMemoryMeetingNoteStore(), + new CapturingMeetingNoteOpener(), + new InMemoryMeetingArtifactStore(), + new InMemoryRecordedAudioStore(), + new CapturingMeetingSummaryPipeline(), + Options.Create(new MeetingAssistantOptions + { + Recording = + { + InactivitySafeguard = + { + FirstPromptAfter = TimeSpan.FromSeconds(2), + ReminderPromptAfter = [], + AutoStopAfter = TimeSpan.FromMinutes(30), + CheckInterval = TimeSpan.FromSeconds(1) + } + } + }), + NullLogger.Instance, + inactivityPromptService: promptService, + inactivityClock: clock); + + await coordinator.StartAsync(CancellationToken.None); + await WaitUntilAsync(() => clock.PendingDelayCount > 0); + clock.Advance(TimeSpan.FromSeconds(2)); + await promptService.WaitForShowStartedAsync(); + + await coordinator.SetTranscriptionPausedAsync(true, CancellationToken.None); + promptService.ReleaseShow(); + await promptService.WaitForShowCompletedAsync(); + await promptService.WaitForLateDismissAsync(); + + Assert.False(promptService.IsVisible); + Assert.True(coordinator.CurrentStatus.IsPaused); + + await coordinator.StopAsync(CancellationToken.None); + } + + [Fact] + public async Task PausedTranscriptionSuspendsInactivitySafeguardUntilUnpaused() + { + var clock = new ManualMeetingInactivityClock(DateTimeOffset.Parse("2026-06-02T13:00:00+02:00")); + var promptService = new IgnoringMeetingInactivityPromptService(); + var audioSource = new ControlledAudioSource(); + var coordinator = new MeetingRecordingCoordinator( + audioSource, + new TestSpeechRecognitionPipelineFactory(new EchoStreamingTranscriptionProvider()), + new InMemoryTranscriptStore(), + new InMemoryMeetingNoteStore(), + new CapturingMeetingNoteOpener(), + new InMemoryMeetingArtifactStore(), + new InMemoryRecordedAudioStore(), + new CapturingMeetingSummaryPipeline(), + Options.Create(new MeetingAssistantOptions + { + Recording = + { + InactivitySafeguard = + { + FirstPromptAfter = TimeSpan.FromSeconds(2), + ReminderPromptAfter = [], + AutoStopAfter = TimeSpan.FromSeconds(5), + CheckInterval = TimeSpan.FromSeconds(1) + } + } + }), + NullLogger.Instance, + inactivityPromptService: promptService, + inactivityClock: clock); + + await coordinator.StartAsync(CancellationToken.None); + await WaitUntilAsync(() => clock.PendingDelayCount > 0); + await coordinator.SetTranscriptionPausedAsync(true, CancellationToken.None); + + clock.Advance(TimeSpan.FromSeconds(10)); + await WaitUntilAsync(() => !coordinator.CurrentStatus.IsRecording || clock.PendingDelayCount > 0); + + Assert.True(coordinator.CurrentStatus.IsRecording); + Assert.True(coordinator.CurrentStatus.IsPaused); + Assert.Empty(promptService.Requests); + + await coordinator.SetTranscriptionPausedAsync(false, CancellationToken.None); + clock.Advance(TimeSpan.FromSeconds(1)); + await WaitUntilAsync(() => clock.PendingDelayCount > 0); + Assert.Empty(promptService.Requests); + + clock.Advance(TimeSpan.FromSeconds(1)); + await promptService.WaitForPromptAsync(); + + Assert.Single(promptService.Requests); + Assert.True(coordinator.CurrentStatus.IsRecording); + + await coordinator.StopAsync(CancellationToken.None); + } + + [Fact] + public async Task PausedTranscriptionAutoStopsNormallyAfterFourHoursWithoutShowingPrompt() + { + var clock = new ManualMeetingInactivityClock(DateTimeOffset.Parse("2026-06-02T14:00:00+02:00")); + var promptService = new IgnoringMeetingInactivityPromptService(); + var coordinator = new MeetingRecordingCoordinator( + new ControlledAudioSource(), + new TestSpeechRecognitionPipelineFactory(new EchoStreamingTranscriptionProvider()), + new InMemoryTranscriptStore(), + new InMemoryMeetingNoteStore(), + new CapturingMeetingNoteOpener(), + new InMemoryMeetingArtifactStore(), + new InMemoryRecordedAudioStore(), + new CapturingMeetingSummaryPipeline(), + Options.Create(new MeetingAssistantOptions + { + Recording = + { + InactivitySafeguard = + { + Enabled = false, + FirstPromptAfter = TimeSpan.FromSeconds(2), + ReminderPromptAfter = [], + AutoStopAfter = TimeSpan.FromSeconds(5), + CheckInterval = TimeSpan.FromSeconds(1) + } + } + }), + NullLogger.Instance, + inactivityPromptService: promptService, + inactivityClock: clock); + + await coordinator.StartAsync(CancellationToken.None); + await WaitUntilAsync(() => clock.PendingDelayCount > 0); + await coordinator.SetTranscriptionPausedAsync(true, CancellationToken.None); + + clock.Advance(TimeSpan.FromHours(4) - TimeSpan.FromMinutes(1)); + await WaitUntilAsync(() => clock.PendingDelayCount > 0); + Assert.True(coordinator.CurrentStatus.IsRecording); + Assert.Empty(promptService.Requests); + + clock.Advance(TimeSpan.FromMinutes(1)); + await WaitUntilAsync(() => !coordinator.CurrentStatus.IsRecording || clock.PendingDelayCount > 0); + + Assert.False(coordinator.CurrentStatus.IsRecording); + Assert.Empty(promptService.Requests); + } + + [Fact] + public async Task UnpauseAtMaximumPauseDeadlineKeepsMeetingActiveAndResetsPauseTimer() + { + var clock = new ManualMeetingInactivityClock(DateTimeOffset.Parse("2026-06-02T18:00:00+02:00")); + var promptService = new IgnoringMeetingInactivityPromptService(); + var coordinator = new MeetingRecordingCoordinator( + new ControlledAudioSource(), + new TestSpeechRecognitionPipelineFactory(new EchoStreamingTranscriptionProvider()), + new InMemoryTranscriptStore(), + new InMemoryMeetingNoteStore(), + new CapturingMeetingNoteOpener(), + new InMemoryMeetingArtifactStore(), + new InMemoryRecordedAudioStore(), + new CapturingMeetingSummaryPipeline(), + Options.Create(new MeetingAssistantOptions + { + Recording = + { + InactivitySafeguard = + { + FirstPromptAfter = TimeSpan.FromSeconds(2), + ReminderPromptAfter = [], + AutoStopAfter = TimeSpan.FromSeconds(3), + MaximumPauseDuration = TimeSpan.FromSeconds(5), + CheckInterval = TimeSpan.FromSeconds(1) + } + } + }), + NullLogger.Instance, + inactivityPromptService: promptService, + inactivityClock: clock); + + await coordinator.StartAsync(CancellationToken.None); + await WaitUntilAsync(() => clock.PendingDelayCount > 0); + await coordinator.SetTranscriptionPausedAsync(true, CancellationToken.None); + + clock.BlockNextNowRead(); + clock.Advance(TimeSpan.FromSeconds(5)); + await clock.WaitForBlockedNowReadAsync(); + await coordinator.SetTranscriptionPausedAsync(false, CancellationToken.None); + clock.ReleaseBlockedNowRead(); + await WaitUntilAsync(() => clock.PendingDelayCount > 0); + + Assert.True(coordinator.CurrentStatus.IsRecording); + Assert.False(coordinator.CurrentStatus.IsPaused); + + await coordinator.SetTranscriptionPausedAsync(true, CancellationToken.None); + clock.Advance(TimeSpan.FromSeconds(4)); + await WaitUntilAsync(() => clock.PendingDelayCount > 0); + + Assert.True(coordinator.CurrentStatus.IsRecording); + Assert.Empty(promptService.Requests); + + clock.Advance(TimeSpan.FromSeconds(1)); + await WaitUntilAsync(() => !coordinator.CurrentStatus.IsRecording || clock.PendingDelayCount > 0); + + Assert.False(coordinator.CurrentStatus.IsRecording); + Assert.Empty(promptService.Requests); + } + [Fact] public async Task StartUsesCurrentOutlookMeetingMetadataWhenAvailable() { @@ -2048,9 +2778,10 @@ public sealed class RecordingCoordinatorTests var transcriptStore = new InMemoryTranscriptStore(); var speakerIdentification = new BlockingSpeakerIdentificationService("Guest03", "Chris"); var provider = new OrderedChunkProvider(); + var pipelineFactory = new TestSpeechRecognitionPipelineFactory(provider); var coordinator = new MeetingRecordingCoordinator( audioSource, - new TestSpeechRecognitionPipelineFactory(provider), + pipelineFactory, transcriptStore, new InMemoryMeetingNoteStore(), new CapturingMeetingNoteOpener(), @@ -2076,6 +2807,8 @@ public sealed class RecordingCoordinatorTests await WaitUntilAsync(() => transcriptStore.ReplacedSegments.Any(segment => segment.Text?.Contains("first", StringComparison.Ordinal) == true)); Assert.Equal("Chris", transcriptStore.ReplacedSegments.Single().Speaker); await Task.Delay(50); + await coordinator.SetTranscriptionPausedAsync(true, CancellationToken.None); + await coordinator.SetTranscriptionPausedAsync(false, CancellationToken.None); await audioSource.WriteAsync(new AudioChunk(Samples(8, 9, 10, 11, 12, 13, 14, 15), 4, 1), CancellationToken.None); await transcriptStore.WaitForTextAsync("second"); @@ -2088,6 +2821,7 @@ public sealed class RecordingCoordinatorTests Assert.Contains( transcriptStore.ReplacedSegments, segment => segment.Text?.Contains("first", StringComparison.Ordinal) == true && segment.Speaker == "Chris"); + Assert.Equal(1, pipelineFactory.CreateCount); } [Fact] @@ -2928,6 +3662,9 @@ public sealed class RecordingCoordinatorTests private readonly object gate = new(); private readonly List segments = []; private readonly string transcriptPath; + private TaskCompletionSource? blockedAppendStarted; + private TaskCompletionSource? releaseBlockedAppend; + private bool blockNextAppend; public InMemoryTranscriptStore(string transcriptPath = "memory-transcript.md") { @@ -2951,8 +3688,29 @@ public sealed class RecordingCoordinatorTests return CreateSessionAsync(cancellationToken); } - public Task AppendLineAsync(TranscriptSession session, string line, CancellationToken cancellationToken) + public async Task AppendLineAsync( + TranscriptSession session, + string line, + CancellationToken cancellationToken) { + TaskCompletionSource? appendStarted = null; + TaskCompletionSource? appendRelease = null; + lock (gate) + { + if (blockNextAppend) + { + blockNextAppend = false; + appendStarted = blockedAppendStarted; + appendRelease = releaseBlockedAppend; + } + } + + if (appendRelease is not null) + { + appendStarted!.TrySetResult(); + await appendRelease.Task.WaitAsync(cancellationToken); + } + int index; lock (gate) { @@ -2960,7 +3718,33 @@ public sealed class RecordingCoordinatorTests segments.Add(ParseTranscriptLine(line)); } - return Task.FromResult(new TranscriptLineReference(session.TranscriptPath, index, line)); + return new TranscriptLineReference(session.TranscriptPath, index, line); + } + + public void BlockNextAppend() + { + lock (gate) + { + blockNextAppend = true; + blockedAppendStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + releaseBlockedAppend = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + } + } + + public Task WaitForBlockedAppendAsync() + { + lock (gate) + { + return blockedAppendStarted!.Task.WaitAsync(TimeSpan.FromSeconds(5)); + } + } + + public void ReleaseBlockedAppend() + { + lock (gate) + { + releaseBlockedAppend?.TrySetResult(); + } } public Task ReplaceLineAsync( @@ -3111,6 +3895,9 @@ public sealed class RecordingCoordinatorTests private sealed class InMemoryMeetingNoteStore : IMeetingNoteStore { private readonly string notePath; + private TaskCompletionSource? blockedReadStarted; + private TaskCompletionSource? releaseBlockedRead; + private bool blockNextRead; public InMemoryMeetingNoteStore(string notePath = "memory-meeting.md") { @@ -3125,9 +3912,33 @@ public sealed class RecordingCoordinatorTests return Task.FromResult(SavedNote); } - public Task ReadAsync(string path, CancellationToken cancellationToken) + public async Task ReadAsync(string path, CancellationToken cancellationToken) { - return Task.FromResult(SavedNote ?? throw new FileNotFoundException(path)); + if (blockNextRead) + { + blockNextRead = false; + blockedReadStarted!.TrySetResult(); + await releaseBlockedRead!.Task.WaitAsync(cancellationToken); + } + + return SavedNote ?? throw new FileNotFoundException(path); + } + + public void BlockNextRead() + { + blockNextRead = true; + blockedReadStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + releaseBlockedRead = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + } + + public Task WaitForBlockedReadAsync() + { + return blockedReadStarted!.Task.WaitAsync(TimeSpan.FromSeconds(5)); + } + + public void ReleaseBlockedRead() + { + releaseBlockedRead?.TrySetResult(); } public void UpdateAttendees(IEnumerable attendees) @@ -4018,6 +4829,8 @@ public sealed class RecordingCoordinatorTests public List AppendedChunkSizes { get; } = []; + public List AppendedChunks { get; } = []; + public bool Completed { get; private set; } public bool Deleted { get; private set; } @@ -4055,6 +4868,7 @@ public sealed class RecordingCoordinatorTests public Task AppendAsync(AudioChunk chunk, CancellationToken cancellationToken) { store.AppendedChunkSizes.Add(chunk.Pcm.Length); + store.AppendedChunks.Add(chunk); store.AppendObserved.TrySetResult(); return Task.CompletedTask; } @@ -4113,8 +4927,11 @@ public sealed class RecordingCoordinatorTests this.finalize = finalize ?? ((_, _, _, _) => Task.FromResult>([])); } + public int CreateCount { get; private set; } + public ISpeechRecognitionPipeline Create() { + CreateCount++; return new TestSpeechRecognitionPipeline(provider, finalize); } } @@ -4705,13 +5522,44 @@ public sealed class RecordingCoordinatorTests { private readonly object gate = new(); private readonly List delays = []; + private readonly TaskCompletionSource blockedNowReadObserved = + new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource releaseBlockedNowRead = + new(TaskCreationOptions.RunContinuationsAsynchronously); + private DateTimeOffset now; + private bool blockNextNowRead; public ManualMeetingInactivityClock(DateTimeOffset now) { - Now = now; + this.now = now; } - public DateTimeOffset Now { get; private set; } + public DateTimeOffset Now + { + get + { + var shouldBlock = false; + lock (gate) + { + if (blockNextNowRead) + { + blockNextNowRead = false; + shouldBlock = true; + } + } + + if (shouldBlock) + { + blockedNowReadObserved.TrySetResult(); + releaseBlockedNowRead.Task.GetAwaiter().GetResult(); + } + + lock (gate) + { + return now; + } + } + } public int PendingDelayCount { @@ -4759,8 +5607,8 @@ public sealed class RecordingCoordinatorTests List due; lock (gate) { - Now += duration; - due = delays.Where(delay => delay.DueAt <= Now).ToList(); + now += duration; + due = delays.Where(delay => delay.DueAt <= now).ToList(); foreach (var delay in due) { delays.Remove(delay); @@ -4774,6 +5622,24 @@ public sealed class RecordingCoordinatorTests } } + public void BlockNextNowRead() + { + lock (gate) + { + blockNextNowRead = true; + } + } + + public Task WaitForBlockedNowReadAsync() + { + return blockedNowReadObserved.Task.WaitAsync(TimeSpan.FromSeconds(5)); + } + + public void ReleaseBlockedNowRead() + { + releaseBlockedNowRead.TrySetResult(); + } + private sealed class ScheduledDelay { public ScheduledDelay(DateTimeOffset dueAt, TaskCompletionSource completion) @@ -4803,6 +5669,8 @@ public sealed class RecordingCoordinatorTests public List Requests { get; } = []; + public int DismissAllCount { get; private set; } + public async Task ShowStopPromptAsync( MeetingInactivityPromptRequest request, Func handleResponseAsync, @@ -4820,21 +5688,50 @@ public sealed class RecordingCoordinatorTests { return promptObserved.Task.WaitAsync(TimeSpan.FromSeconds(5)); } + + public Task DismissAllAsync(CancellationToken cancellationToken) + { + DismissAllCount++; + return Task.CompletedTask; + } + } + + private sealed class SequencedSpeechRecognitionPipelineFactory : ISpeechRecognitionPipelineFactory + { + private readonly Queue providers; + + public SequencedSpeechRecognitionPipelineFactory(params IStreamingTranscriptionProvider[] providers) + { + this.providers = new Queue(providers); + } + + public ISpeechRecognitionPipeline Create() + { + return new TestSpeechRecognitionPipeline( + providers.Dequeue(), + (_, _, _, _) => Task.FromResult>([])); + } } private sealed class IgnoringMeetingInactivityPromptService : IMeetingInactivityPromptService { private readonly TaskCompletionSource promptObserved = new(TaskCreationOptions.RunContinuationsAsynchronously); + private TaskCompletionSource? blockedDismissObserved; + private TaskCompletionSource? releaseBlockedDismiss; + private Func? handleResponseAsync; public List Requests { get; } = []; + public int DismissAllCount { get; private set; } + public Task ShowStopPromptAsync( MeetingInactivityPromptRequest request, Func handleResponseAsync, CancellationToken cancellationToken) { Requests.Add(request); + this.handleResponseAsync = handleResponseAsync; promptObserved.TrySetResult(); return Task.CompletedTask; } @@ -4843,6 +5740,98 @@ public sealed class RecordingCoordinatorTests { return promptObserved.Task.WaitAsync(TimeSpan.FromSeconds(5)); } + + public async Task DismissAllAsync(CancellationToken cancellationToken) + { + DismissAllCount++; + if (blockedDismissObserved is not null && releaseBlockedDismiss is not null) + { + blockedDismissObserved.TrySetResult(); + await releaseBlockedDismiss.Task.WaitAsync(cancellationToken); + blockedDismissObserved = null; + releaseBlockedDismiss = null; + } + } + + public void BlockNextDismiss() + { + blockedDismissObserved = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + releaseBlockedDismiss = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + } + + public Task WaitForBlockedDismissAsync() + { + return blockedDismissObserved!.Task.WaitAsync(TimeSpan.FromSeconds(5)); + } + + public void ReleaseBlockedDismiss() + { + releaseBlockedDismiss!.TrySetResult(); + } + + public Task RespondAsync(MeetingInactivityPromptResponse response) + { + return handleResponseAsync is null + ? Task.CompletedTask + : handleResponseAsync(response, CancellationToken.None); + } + } + + private sealed class BlockingMeetingInactivityPromptService : IMeetingInactivityPromptService + { + private readonly TaskCompletionSource showStarted = + new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource releaseShow = + new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource showCompleted = + new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource lateDismissed = + new(TaskCreationOptions.RunContinuationsAsynchronously); + private int dismissCount; + + public bool IsVisible { get; private set; } + + public async Task ShowStopPromptAsync( + MeetingInactivityPromptRequest request, + Func handleResponseAsync, + CancellationToken cancellationToken) + { + showStarted.TrySetResult(); + await releaseShow.Task.WaitAsync(cancellationToken); + IsVisible = true; + showCompleted.TrySetResult(); + } + + public Task DismissAllAsync(CancellationToken cancellationToken) + { + IsVisible = false; + if (Interlocked.Increment(ref dismissCount) >= 2) + { + lateDismissed.TrySetResult(); + } + + return Task.CompletedTask; + } + + public Task WaitForShowStartedAsync() + { + return showStarted.Task.WaitAsync(TimeSpan.FromSeconds(5)); + } + + public Task WaitForShowCompletedAsync() + { + return showCompleted.Task.WaitAsync(TimeSpan.FromSeconds(5)); + } + + public Task WaitForLateDismissAsync() + { + return lateDismissed.Task.WaitAsync(TimeSpan.FromSeconds(5)); + } + + public void ReleaseShow() + { + releaseShow.TrySetResult(); + } } private sealed class CapturedChunkThenCancelAudioSource : IMeetingAudioSource @@ -4898,6 +5887,31 @@ public sealed class RecordingCoordinatorTests } } + private sealed class SequencedStreamingTranscriptionProvider : IStreamingTranscriptionProvider + { + private readonly IReadOnlyList segments; + + public SequencedStreamingTranscriptionProvider(IReadOnlyList segments) + { + this.segments = segments; + } + + public async IAsyncEnumerable TranscribeAsync( + IAsyncEnumerable audio, + SpeechRecognitionPipelineOptions options, + [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken) + { + var index = 0; + await foreach (var _ in audio.WithCancellation(cancellationToken)) + { + if (index < segments.Count) + { + yield return segments[index++]; + } + } + } + } + private sealed class EchoStreamingTranscriptionProvider : IStreamingTranscriptionProvider { public bool FirstChunkWasObservedBeforeSourceCompleted { get; private set; } @@ -4915,6 +5929,62 @@ public sealed class RecordingCoordinatorTests } } + private sealed class CapturingAudioStreamingTranscriptionProvider : IStreamingTranscriptionProvider + { + public ConcurrentQueue Chunks { get; } = new(); + + public async IAsyncEnumerable TranscribeAsync( + IAsyncEnumerable audio, + SpeechRecognitionPipelineOptions options, + [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken) + { + await foreach (var chunk in audio.WithCancellation(cancellationToken)) + { + Chunks.Enqueue(chunk); + } + + yield break; + } + } + + private sealed class DelayedSegmentOnAudioCompletionProvider : IStreamingTranscriptionProvider + { + private readonly TranscriptionSegment segment; + private readonly TaskCompletionSource audioCompleted = + new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource releaseSegment = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + public DelayedSegmentOnAudioCompletionProvider(TranscriptionSegment segment) + { + this.segment = segment; + } + + public async IAsyncEnumerable TranscribeAsync( + IAsyncEnumerable audio, + SpeechRecognitionPipelineOptions options, + [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken) + { + await foreach (var _ in audio.WithCancellation(cancellationToken)) + { + } + + audioCompleted.TrySetResult(); + await releaseSegment.Task.WaitAsync(cancellationToken); + yield return segment; + } + + public Task WaitForAudioCompletionAsync() + { + return audioCompleted.Task.WaitAsync(TimeSpan.FromSeconds(5)); + } + + public void ReleaseSegment() + { + releaseSegment.TrySetResult(); + } + } + private sealed class FinalSegmentOnAudioCompletionProvider : IStreamingTranscriptionProvider { public async IAsyncEnumerable TranscribeAsync( diff --git a/MeetingAssistant.Tests/TaskbarIconTests.cs b/MeetingAssistant.Tests/TaskbarIconTests.cs index b1cdbb6..ec2eea3 100644 --- a/MeetingAssistant.Tests/TaskbarIconTests.cs +++ b/MeetingAssistant.Tests/TaskbarIconTests.cs @@ -74,7 +74,8 @@ public sealed class TaskbarIconTests menu, ("Open agent", MeetingTaskbarAction.EditRules, false), ("Finish meeting", MeetingTaskbarAction.StopRecording, true), - ("Microphone", MeetingTaskbarAction.OpenSubmenu, true), + ("Pause transcription", MeetingTaskbarAction.PauseTranscription, true), + ("Microphone", MeetingTaskbarAction.OpenSubmenu, false), ("Cancel meeting recording and discard", MeetingTaskbarAction.AbortRecording, false), ("Switch to english\tCtrl+Alt+L", MeetingTaskbarAction.SwitchProfile, false), ("Exit", MeetingTaskbarAction.Exit, true)); @@ -94,10 +95,32 @@ public sealed class TaskbarIconTests menu, ("Open agent", MeetingTaskbarAction.EditRules, false), ("Finish meeting", MeetingTaskbarAction.StopRecording, true), - ("Cancel meeting recording and discard", MeetingTaskbarAction.AbortRecording, true), + ("Pause transcription", MeetingTaskbarAction.PauseTranscription, true), + ("Cancel meeting recording and discard", MeetingTaskbarAction.AbortRecording, false), ("Exit", MeetingTaskbarAction.Exit, true)); } + [Fact] + public void TranscriptionPauseActionTracksActivePauseStateWithoutHidingFinish() + { + var runningMenu = MeetingTaskbarMenuBuilder.Build( + Status(isRecording: true, state: RecordingProcessState.Recording, profile: "default"), + [Profile("default")]); + var pausedMenu = MeetingTaskbarMenuBuilder.Build( + Status(isRecording: true, state: RecordingProcessState.Recording, profile: "default", isPaused: true), + [Profile("default")]); + + Assert.Contains(runningMenu.Items, item => + item.Action == MeetingTaskbarAction.PauseTranscription && + item.Text == "Pause transcription"); + Assert.Contains(pausedMenu.Items, item => + item.Action == MeetingTaskbarAction.UnpauseTranscription && + item.Text == "Unpause transcription"); + Assert.Contains(pausedMenu.Items, item => + item.Action == MeetingTaskbarAction.StopRecording && + item.Text == "Finish meeting"); + } + [Fact] public void ProcessingMenuShowsSummarizingButAllowsStartingNewRecordings() { @@ -200,7 +223,8 @@ public sealed class TaskbarIconTests private static RecordingStatus Status( bool isRecording = false, RecordingProcessState state = RecordingProcessState.Idle, - string? profile = null) + string? profile = null, + bool isPaused = false) { return new RecordingStatus( isRecording, @@ -209,7 +233,8 @@ public sealed class TaskbarIconTests state == RecordingProcessState.Idle ? null : "context.md", state == RecordingProcessState.Idle ? null : "summary.md", state, - profile); + profile, + isPaused); } [SupportedOSPlatform("windows")] diff --git a/MeetingAssistant/MeetingAssistantOptions.cs b/MeetingAssistant/MeetingAssistantOptions.cs index 4ec402e..e7e7f75 100644 --- a/MeetingAssistant/MeetingAssistantOptions.cs +++ b/MeetingAssistant/MeetingAssistantOptions.cs @@ -165,6 +165,8 @@ public sealed class RecordingInactivitySafeguardOptions public TimeSpan AutoStopAfter { get; set; } = TimeSpan.FromMinutes(30); + public TimeSpan MaximumPauseDuration { get; set; } = TimeSpan.FromHours(4); + public TimeSpan InferredEndPadding { get; set; } = TimeSpan.FromMinutes(1); public TimeSpan CheckInterval { get; set; } = TimeSpan.FromSeconds(15); diff --git a/MeetingAssistant/Recording/IMeetingInactivityPromptService.cs b/MeetingAssistant/Recording/IMeetingInactivityPromptService.cs index 58fa9d6..f2ddd67 100644 --- a/MeetingAssistant/Recording/IMeetingInactivityPromptService.cs +++ b/MeetingAssistant/Recording/IMeetingInactivityPromptService.cs @@ -6,6 +6,8 @@ public interface IMeetingInactivityPromptService MeetingInactivityPromptRequest request, Func handleResponseAsync, CancellationToken cancellationToken); + + Task DismissAllAsync(CancellationToken cancellationToken); } public sealed record MeetingInactivityPromptRequest( @@ -18,9 +20,32 @@ public enum MeetingInactivityPromptResponse { Dismissed, Continue, + Pause, Stop } +internal sealed record MeetingInactivityPromptAction( + string Content, + string ResponseArgument, + MeetingInactivityPromptResponse Response); + +internal static class MeetingInactivityPromptActions +{ + public static IReadOnlyList All { get; } = + [ + new("Yes", "stop", MeetingInactivityPromptResponse.Stop), + new("No", "continue", MeetingInactivityPromptResponse.Continue), + new("Pause transcription", "pause", MeetingInactivityPromptResponse.Pause) + ]; + + public static MeetingInactivityPromptResponse ParseResponse(string? value) + { + return All.FirstOrDefault(action => + action.ResponseArgument.Equals(value, StringComparison.OrdinalIgnoreCase)) + ?.Response ?? MeetingInactivityPromptResponse.Continue; + } +} + public sealed class NoopMeetingInactivityPromptService : IMeetingInactivityPromptService { public Task ShowStopPromptAsync( @@ -30,4 +55,9 @@ public sealed class NoopMeetingInactivityPromptService : IMeetingInactivityPromp { return Task.CompletedTask; } + + public Task DismissAllAsync(CancellationToken cancellationToken) + { + return Task.CompletedTask; + } } diff --git a/MeetingAssistant/Recording/MeetingRecordingCoordinator.cs b/MeetingAssistant/Recording/MeetingRecordingCoordinator.cs index 3279848..43315f1 100644 --- a/MeetingAssistant/Recording/MeetingRecordingCoordinator.cs +++ b/MeetingAssistant/Recording/MeetingRecordingCoordinator.cs @@ -96,7 +96,8 @@ public sealed class MeetingRecordingCoordinator currentArtifacts?.AssistantContextPath, currentArtifacts?.SummaryPath, GetProcessState(currentRun), - currentRun?.LaunchProfileName); + currentRun?.LaunchProfileName, + IsRecording && currentRun?.IsTranscriptionPaused == true); public MeetingSessionArtifacts? CurrentArtifacts => currentArtifacts; @@ -292,7 +293,7 @@ public sealed class MeetingRecordingCoordinator runOptions.SpeakerIdentification.MaxSnippetsPerSpeaker, logger); run.Task = Task.Run(() => RecordAsync(run), CancellationToken.None); - if (runOptions.Recording.InactivitySafeguard.Enabled) + if (ShouldRunInactivitySafeguard(runOptions.Recording.InactivitySafeguard)) { _ = Task.Run( () => RunInactivitySafeguardAsync(run), @@ -334,11 +335,14 @@ public sealed class MeetingRecordingCoordinator public async Task StopAsync(CancellationToken cancellationToken) { - return await StopAsync(null, cancellationToken); + return await StopAsync(null, null, null, null, cancellationToken); } private async Task StopAsync( DateTimeOffset? inferredEndTime, + RecordingRun? expectedRun, + long? expectedActivityVersion, + DateTimeOffset? expectedPauseStartedAt, CancellationToken cancellationToken) { RecordingRun run; @@ -347,13 +351,30 @@ public sealed class MeetingRecordingCoordinator await gate.WaitAsync(cancellationToken); try { - if (currentRun is null || currentRun.IsCaptureStopping) + if (currentRun is null || + currentRun.IsCaptureStopping || + expectedRun is not null && !ReferenceEquals(currentRun, expectedRun)) { return CurrentStatus; } run = currentRun; - if (inferredEndTime is not null) + var inactivityStopClaimed = expectedActivityVersion is not null; + if (expectedActivityVersion is not null && + (inferredEndTime is null || + !run.TryClaimInactivityStop(expectedActivityVersion.Value, inferredEndTime.Value))) + { + return CurrentStatus; + } + + var maximumPauseStopClaimed = expectedPauseStartedAt is not null; + if (expectedPauseStartedAt is not null && + !run.TryClaimMaximumPauseStop(expectedPauseStartedAt.Value)) + { + return CurrentStatus; + } + + if (!inactivityStopClaimed && !maximumPauseStopClaimed && inferredEndTime is not null) { run.SetInferredEndTime(inferredEndTime.Value); } @@ -363,7 +384,7 @@ public sealed class MeetingRecordingCoordinator { run.Abort(); } - else + else if (!inactivityStopClaimed && !maximumPauseStopClaimed) { run.StopCapture(); } @@ -409,6 +430,65 @@ public sealed class MeetingRecordingCoordinator return CurrentStatus; } + public async Task SetTranscriptionPausedAsync( + bool isPaused, + CancellationToken cancellationToken) + { + return await SetTranscriptionPausedAsync(isPaused, null, null, cancellationToken); + } + + private async Task SetTranscriptionPausedAsync( + bool isPaused, + RecordingRun? expectedRun, + long? expectedActivityVersion, + CancellationToken cancellationToken) + { + await gate.WaitAsync(cancellationToken); + try + { + var run = currentRun; + if (run is null || + run.IsCaptureStopping || + expectedRun is not null && !ReferenceEquals(run, expectedRun)) + { + return CurrentStatus; + } + + var changed = false; + await run.PipelineGate.WaitAsync(cancellationToken); + try + { + var changedAt = inactivityClock.Now; + changed = run.TrySetTranscriptionPaused( + isPaused, + changedAt, + expectedActivityVersion); + } + finally + { + run.PipelineGate.Release(); + } + + if (changed && isPaused) + { + await DismissInactivityPromptsAsync(cancellationToken); + } + + if (changed) + { + logger.LogInformation( + "Meeting transcription {PauseState}", + isPaused ? "paused" : "unpaused"); + } + + return CurrentStatus; + } + finally + { + gate.Release(); + } + } + public async Task AbortAsync(CancellationToken cancellationToken) { RecordingRun run; @@ -661,8 +741,7 @@ public sealed class MeetingRecordingCoordinator chunk.Channels); } - await run.RecordedAudio.AppendAsync(chunk, run.CaptureCancellation); - await run.WriteAudioAsync(chunk, run.CaptureCancellation); + await run.RouteCapturedAudioAsync(chunk, run.CaptureCancellation); } logger.LogInformation( @@ -701,7 +780,6 @@ public sealed class MeetingRecordingCoordinator run.ResetSpeakerIdentification(); } - run.RecordTranscriptActivity(segment, inactivityClock.Now); var sample = run.TryAddSpeakerSample(segment); if (sample is not null) { @@ -718,6 +796,47 @@ public sealed class MeetingRecordingCoordinator var relabeledSegment = run.Relabel(segment); run.AddLiveSegment(relabeledSegment); await AppendTranscriptSegmentAsync(run, relabeledSegment, cancellationToken); + run.RecordTranscriptActivity(segment, inactivityClock.Now); + if (!string.IsNullOrWhiteSpace(segment.Text)) + { + await DismissInactivityPromptsForRunAsync(run, cancellationToken); + } + } + } + + private async Task DismissInactivityPromptsForRunAsync( + RecordingRun run, + CancellationToken cancellationToken) + { + await gate.WaitAsync(cancellationToken); + try + { + if (!ReferenceEquals(currentRun, run) || run.IsCaptureStopping) + { + return; + } + + await DismissInactivityPromptsAsync(cancellationToken); + } + finally + { + gate.Release(); + } + } + + private async Task DismissInactivityPromptsAsync(CancellationToken cancellationToken) + { + try + { + await inactivityPromptService.DismissAllAsync(cancellationToken); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + throw; + } + catch (Exception exception) + { + logger.LogWarning(exception, "Failed to dismiss transcript inactivity prompts"); } } @@ -845,7 +964,10 @@ public sealed class MeetingRecordingCoordinator private async Task RunInactivitySafeguardAsync(RecordingRun run) { var safeguardOptions = run.Options.Recording.InactivitySafeguard; - var promptThresholds = GetInactivityPromptThresholds(safeguardOptions); + var promptThresholds = safeguardOptions.Enabled + ? GetInactivityPromptThresholds(safeguardOptions) + : []; + var checkInterval = GetInactivitySafeguardCheckInterval(safeguardOptions); var promptedThresholds = new HashSet(); var lastActivityVersion = run.GetTranscriptActivitySnapshot().ActivityVersion; @@ -853,7 +975,7 @@ public sealed class MeetingRecordingCoordinator "Recording inactivity safeguard started with prompt thresholds {PromptThresholds}, auto-stop {AutoStopAfter}, check interval {CheckInterval}", string.Join(", ", promptThresholds), safeguardOptions.AutoStopAfter, - safeguardOptions.CheckInterval); + checkInterval); try { @@ -869,9 +991,38 @@ public sealed class MeetingRecordingCoordinator snapshot.LastTranscriptActivityAt); } + var pauseStartedAt = snapshot.TranscriptionPausedAt; + if (pauseStartedAt is not null) + { + var maximumPauseDuration = safeguardOptions.MaximumPauseDuration; + if (maximumPauseDuration > TimeSpan.Zero && + inactivityClock.Now - pauseStartedAt.Value >= maximumPauseDuration) + { + logger.LogWarning( + "Recording inactivity safeguard stopping meeting after transcription remained paused for {PauseDuration}", + maximumPauseDuration); + var stopStatus = await StopAsync( + null, + run, + null, + pauseStartedAt, + CancellationToken.None); + if (!stopStatus.IsRecording) + { + return; + } + } + + await inactivityClock.DelayAsync( + checkInterval, + run.CaptureCancellation); + continue; + } + var now = inactivityClock.Now; var inactivityDuration = now - snapshot.LastTranscriptActivityAt; - if (safeguardOptions.AutoStopAfter > TimeSpan.Zero && + if (safeguardOptions.Enabled && + safeguardOptions.AutoStopAfter > TimeSpan.Zero && inactivityDuration >= safeguardOptions.AutoStopAfter) { var inferredEndTime = run.GetInactivitySafeguardEndTime(safeguardOptions.InferredEndPadding); @@ -879,8 +1030,16 @@ public sealed class MeetingRecordingCoordinator "Recording inactivity safeguard auto-stopping meeting after {InactivityDuration} without transcript text; inferred end time {InferredEndTime}", inactivityDuration, inferredEndTime); - await StopAsync(inferredEndTime, CancellationToken.None); - return; + var stopStatus = await StopAsync( + inferredEndTime, + run, + snapshot.ActivityVersion, + null, + CancellationToken.None); + if (!stopStatus.IsRecording) + { + return; + } } foreach (var threshold in promptThresholds) @@ -897,6 +1056,7 @@ public sealed class MeetingRecordingCoordinator inactivityDuration, threshold, inferredEndTime); + var promptActivityVersion = snapshot.ActivityVersion; await inactivityPromptService.ShowStopPromptAsync( new MeetingInactivityPromptRequest( inactivityDuration, @@ -912,16 +1072,36 @@ public sealed class MeetingRecordingCoordinator if (response == MeetingInactivityPromptResponse.Stop) { - await StopAsync(inferredEndTime, CancellationToken.None); + await StopAsync( + inferredEndTime, + run, + promptActivityVersion, + null, + CancellationToken.None); + } + else if (response == MeetingInactivityPromptResponse.Pause) + { + await SetTranscriptionPausedAsync( + true, + run, + promptActivityVersion, + CancellationToken.None); } }, run.CaptureCancellation); + var currentActivity = run.GetTranscriptActivitySnapshot(); + if (currentActivity.IsTranscriptionPaused || + currentActivity.ActivityVersion != promptActivityVersion) + { + await DismissInactivityPromptsAsync(run.CaptureCancellation); + } + break; } await inactivityClock.DelayAsync( - GetInactivitySafeguardCheckInterval(safeguardOptions), + checkInterval, run.CaptureCancellation); } } @@ -1821,6 +2001,11 @@ public sealed class MeetingRecordingCoordinator .ToList(); } + private static bool ShouldRunInactivitySafeguard(RecordingInactivitySafeguardOptions options) + { + return options.Enabled || options.MaximumPauseDuration > TimeSpan.Zero; + } + private static TimeSpan GetInactivitySafeguardCheckInterval( RecordingInactivitySafeguardOptions options) { @@ -1877,6 +2062,8 @@ public sealed class MeetingRecordingCoordinator private TimeSpan? lastTranscriptSegmentEnd; private long transcriptActivityVersion; private DateTimeOffset? inferredEndTime; + private bool isTranscriptionPaused; + private DateTimeOffset? transcriptionPausedAt; public RecordingRun( CancellationTokenSource captureCancellation, @@ -1960,6 +2147,17 @@ public sealed class MeetingRecordingCoordinator public bool HasAttachedPromptMetadata { get; private set; } + public bool IsTranscriptionPaused + { + get + { + lock (transcriptActivityGate) + { + return isTranscriptionPaused; + } + } + } + public AssistantContextState ContextState { get; private set; } = AssistantContextState.CollectingMetadata; public DateTimeOffset? InferredEndTime @@ -1983,6 +2181,37 @@ public sealed class MeetingRecordingCoordinator HasAttachedPromptMetadata = true; } + public bool TrySetTranscriptionPaused( + bool isPaused, + DateTimeOffset changedAt, + long? expectedActivityVersion) + { + lock (transcriptActivityGate) + { + if (expectedActivityVersion is not null && + transcriptActivityVersion != expectedActivityVersion.Value) + { + return false; + } + + if (isTranscriptionPaused == isPaused) + { + return false; + } + + isTranscriptionPaused = isPaused; + transcriptionPausedAt = isPaused ? changedAt : null; + + if (!isPaused) + { + lastTranscriptActivityAt = changedAt; + } + + transcriptActivityVersion++; + return true; + } + } + public void Abort() { IsAborted = true; @@ -2011,13 +2240,17 @@ public sealed class MeetingRecordingCoordinator return string.Equals(LaunchProfileName, launchProfileName, StringComparison.OrdinalIgnoreCase); } - public async ValueTask WriteAudioAsync(AudioChunk chunk, CancellationToken cancellationToken) + public async ValueTask RouteCapturedAudioAsync(AudioChunk chunk, CancellationToken cancellationToken) { await PipelineGate.WaitAsync(cancellationToken); try { - AppendAudio(chunk); - await Pipeline.WriteAsync(chunk, cancellationToken); + var routedChunk = IsTranscriptionPaused + ? chunk with { Pcm = new byte[chunk.Pcm.Length] } + : chunk; + await RecordedAudio.AppendAsync(routedChunk, cancellationToken); + AppendAudio(routedChunk); + await Pipeline.WriteAsync(routedChunk, cancellationToken); } finally { @@ -2201,7 +2434,9 @@ public sealed class MeetingRecordingCoordinator return new TranscriptActivitySnapshot( lastTranscriptActivityAt, lastTranscriptSegmentEnd, - transcriptActivityVersion); + transcriptActivityVersion, + isTranscriptionPaused, + transcriptionPausedAt); } } @@ -2221,6 +2456,35 @@ public sealed class MeetingRecordingCoordinator } } + public bool TryClaimInactivityStop(long expectedActivityVersion, DateTimeOffset endTime) + { + lock (transcriptActivityGate) + { + if (isTranscriptionPaused || transcriptActivityVersion != expectedActivityVersion) + { + return false; + } + + inferredEndTime = endTime; + StopCapture(); + return true; + } + } + + public bool TryClaimMaximumPauseStop(DateTimeOffset expectedPauseStartedAt) + { + lock (transcriptActivityGate) + { + if (!isTranscriptionPaused || transcriptionPausedAt != expectedPauseStartedAt) + { + return false; + } + + StopCapture(); + return true; + } + } + public void AppendAudio(AudioChunk chunk) { speakerSampleCollector.AppendAudio(chunk); @@ -2350,7 +2614,9 @@ public sealed class MeetingRecordingCoordinator public sealed record TranscriptActivitySnapshot( DateTimeOffset LastTranscriptActivityAt, TimeSpan? LastTranscriptSegmentEnd, - long ActivityVersion); + long ActivityVersion, + bool IsTranscriptionPaused, + DateTimeOffset? TranscriptionPausedAt); private static int StateRank(AssistantContextState state) { @@ -2405,7 +2671,8 @@ public sealed record RecordingStatus( string? AssistantContextPath, string? SummaryPath, RecordingProcessState State = RecordingProcessState.Idle, - string? LaunchProfile = null); + string? LaunchProfile = null, + bool IsPaused = false); public enum RecordingProcessState { diff --git a/MeetingAssistant/Recording/WindowsMeetingInactivityPromptService.Windows.cs b/MeetingAssistant/Recording/WindowsMeetingInactivityPromptService.Windows.cs index 3cef4c6..79a2904 100644 --- a/MeetingAssistant/Recording/WindowsMeetingInactivityPromptService.Windows.cs +++ b/MeetingAssistant/Recording/WindowsMeetingInactivityPromptService.Windows.cs @@ -11,7 +11,7 @@ public sealed class WindowsMeetingInactivityPromptService : IMeetingInactivityPr private const string NotificationGroup = "meeting-inactivity"; private readonly ConcurrentDictionary pendingPrompts = new(StringComparer.OrdinalIgnoreCase); private readonly ILogger logger; - private readonly object registrationGate = new(); + private readonly object notificationGate = new(); private bool registered; public WindowsMeetingInactivityPromptService(ILogger logger) @@ -37,24 +37,27 @@ public sealed class WindowsMeetingInactivityPromptService : IMeetingInactivityPr try { - EnsureRegistered(); - var promptId = Guid.NewGuid().ToString("N"); - pendingPrompts[promptId] = new PendingPrompt(handleResponseAsync); - logger.LogInformation( - "Registered native Windows inactivity notification {PromptId} response callback at threshold {Threshold}", - promptId, - request.Threshold); - var notification = BuildNotification(promptId, request); - notification.Show(toast => + lock (notificationGate) { - toast.Group = NotificationGroup; - toast.Tag = promptId; - toast.ExpirationTime = MeetingToastExpirationPolicy.StopReminderExpiration(DateTimeOffset.Now); - }); - logger.LogInformation( - "Displayed native Windows inactivity notification {PromptId} at threshold {Threshold}", - promptId, - request.Threshold); + EnsureRegistered(); + var promptId = Guid.NewGuid().ToString("N"); + pendingPrompts[promptId] = new PendingPrompt(handleResponseAsync); + logger.LogInformation( + "Registered native Windows inactivity notification {PromptId} response callback at threshold {Threshold}", + promptId, + request.Threshold); + var notification = BuildNotification(promptId, request); + notification.Show(toast => + { + toast.Group = NotificationGroup; + toast.Tag = promptId; + toast.ExpirationTime = MeetingToastExpirationPolicy.StopReminderExpiration(DateTimeOffset.Now); + }); + logger.LogInformation( + "Displayed native Windows inactivity notification {PromptId} at threshold {Threshold}", + promptId, + request.Threshold); + } } catch (Exception exception) { @@ -76,6 +79,36 @@ public sealed class WindowsMeetingInactivityPromptService : IMeetingInactivityPr return Task.CompletedTask; } + public Task DismissAllAsync(CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + lock (notificationGate) + { + if (pendingPrompts.IsEmpty) + { + return Task.CompletedTask; + } + + pendingPrompts.Clear(); + if (!OperatingSystem.IsWindowsVersionAtLeast(10, 0, 17763)) + { + return Task.CompletedTask; + } + + try + { + ToastNotificationManagerCompat.History.RemoveGroup(NotificationGroup); + logger.LogInformation("Dismissed all native Windows inactivity notifications"); + } + catch (Exception exception) + { + logger.LogWarning(exception, "Failed to dismiss native Windows inactivity notifications"); + } + + return Task.CompletedTask; + } + } + public Task StopAsync(CancellationToken cancellationToken) { return Task.CompletedTask; @@ -83,29 +116,28 @@ public sealed class WindowsMeetingInactivityPromptService : IMeetingInactivityPr public void Dispose() { - if (!registered) + lock (notificationGate) { - return; - } + if (!registered) + { + return; + } - try - { - ToastNotificationManagerCompat.OnActivated -= OnNotificationInvoked; - } - catch (Exception exception) - { - logger.LogWarning(exception, "Failed to detach native Windows toast notification activation handler"); + try + { + ToastNotificationManagerCompat.OnActivated -= OnNotificationInvoked; + registered = false; + } + catch (Exception exception) + { + logger.LogWarning(exception, "Failed to detach native Windows toast notification activation handler"); + } } } private void EnsureRegistered() { - if (registered) - { - return; - } - - lock (registrationGate) + lock (notificationGate) { if (registered) { @@ -122,29 +154,25 @@ public sealed class WindowsMeetingInactivityPromptService : IMeetingInactivityPr string promptId, MeetingInactivityPromptRequest request) { - var yesButton = new ToastButton() - .SetContent("Yes") - .AddArgument("source", NotificationSource) - .AddArgument("promptId", promptId) - .AddArgument("response", "stop") - .SetBackgroundActivation(); - - var noButton = new ToastButton() - .SetContent("No") - .AddArgument("source", NotificationSource) - .AddArgument("promptId", promptId) - .AddArgument("response", "continue") - .SetBackgroundActivation(); - - return new ToastContentBuilder() + var builder = new ToastContentBuilder() .AddArgument("source", NotificationSource) .AddArgument("promptId", promptId) .SetToastScenario(ToastScenario.Reminder) .SetToastDuration(ToastDuration.Long) .AddText("Stop meeting?") - .AddText($"No transcript text has arrived for {FormatDuration(request.InactivityDuration)}.") - .AddButton(yesButton) - .AddButton(noButton); + .AddText($"No transcript text has arrived for {FormatDuration(request.InactivityDuration)}."); + + foreach (var action in MeetingInactivityPromptActions.All) + { + builder.AddButton(new ToastButton() + .SetContent(action.Content) + .AddArgument("source", NotificationSource) + .AddArgument("promptId", promptId) + .AddArgument("response", action.ResponseArgument) + .SetBackgroundActivation()); + } + + return builder; } private void OnNotificationInvoked(ToastNotificationActivatedEventArgsCompat args) @@ -177,10 +205,9 @@ public sealed class WindowsMeetingInactivityPromptService : IMeetingInactivityPr return; } - var response = TryGetArgument(arguments, "response", out var responseValue) && - string.Equals(responseValue, "stop", StringComparison.OrdinalIgnoreCase) - ? MeetingInactivityPromptResponse.Stop - : MeetingInactivityPromptResponse.Continue; + var response = TryGetArgument(arguments, "response", out var responseValue) + ? MeetingInactivityPromptActions.ParseResponse(responseValue) + : MeetingInactivityPromptResponse.Continue; _ = Task.Run(async () => { try diff --git a/MeetingAssistant/Taskbar/MeetingTaskbarMenu.cs b/MeetingAssistant/Taskbar/MeetingTaskbarMenu.cs index a59a485..5ac55f3 100644 --- a/MeetingAssistant/Taskbar/MeetingTaskbarMenu.cs +++ b/MeetingAssistant/Taskbar/MeetingTaskbarMenu.cs @@ -9,6 +9,8 @@ public enum MeetingTaskbarAction OpenSubmenu, StartRecording, StopRecording, + PauseTranscription, + UnpauseTranscription, AbortRecording, SwitchProfile, SelectMicrophone, @@ -51,6 +53,15 @@ public static class MeetingTaskbarMenuBuilder } var secondaryControls = new List(); + if (status.IsRecording) + { + secondaryControls.Add(new MeetingTaskbarMenuItem( + status.IsPaused ? "Unpause transcription" : "Pause transcription", + status.IsPaused + ? MeetingTaskbarAction.UnpauseTranscription + : MeetingTaskbarAction.PauseTranscription)); + } + if (microphones is { Count: > 0 }) { secondaryControls.Add(BuildMicrophoneMenu(microphones, currentMicrophoneDeviceId)); diff --git a/MeetingAssistant/Taskbar/UnoTaskbarIconService.Windows.cs b/MeetingAssistant/Taskbar/UnoTaskbarIconService.Windows.cs index cf481c6..33f5659 100644 --- a/MeetingAssistant/Taskbar/UnoTaskbarIconService.Windows.cs +++ b/MeetingAssistant/Taskbar/UnoTaskbarIconService.Windows.cs @@ -249,6 +249,12 @@ public sealed class UnoTaskbarIconService : IHostedService, IDisposable case MeetingTaskbarAction.StopRecording: await coordinator.StopAsync(CancellationToken.None); break; + case MeetingTaskbarAction.PauseTranscription: + await coordinator.SetTranscriptionPausedAsync(true, CancellationToken.None); + break; + case MeetingTaskbarAction.UnpauseTranscription: + await coordinator.SetTranscriptionPausedAsync(false, CancellationToken.None); + break; case MeetingTaskbarAction.AbortRecording: await coordinator.AbortAsync(CancellationToken.None); break; diff --git a/MeetingAssistant/appsettings.json b/MeetingAssistant/appsettings.json index 3219cce..7c73960 100644 --- a/MeetingAssistant/appsettings.json +++ b/MeetingAssistant/appsettings.json @@ -36,6 +36,7 @@ "00:10:00" ], "AutoStopAfter": "00:30:00", + "MaximumPauseDuration": "04:00:00", "InferredEndPadding": "00:01:00", "CheckInterval": "00:00:15" } diff --git a/README.md b/README.md index 21b41e1..e62c13b 100644 --- a/README.md +++ b/README.md @@ -50,12 +50,14 @@ The default global controls are: - `Ctrl+Alt+Z`: abort the active run and delete its artifacts. - `Ctrl+Alt+S`: capture the active window into the meeting context. -The tray presents `Finish meeting` as the primary action during capture; microphone selection, cancel/discard, and profile switching remain separate controls. `Exit` is always available and requires confirmation while any meeting is recording or processing. +The tray presents `Finish meeting` as the primary action during capture; pause/unpause transcription, microphone selection, cancel/discard, and profile switching remain separate controls. A paused meeting stays active and can still be finished or canceled normally. `Exit` is always available and requires confirmation while any meeting is recording or processing. The loopback HTTP surface exposes health and recording status, recording start/stop/toggle/abort operations, profile-specific equivalents, and diagnostics/retry operations. It has no application authentication. Some generated retry links use `GET` while starting work, so port `5090` must remain a trusted loopback-only control surface. Stopping capture lets buffered transcription, speaker work, meeting-note image OCR, screenshot OCR, and summary generation finish. Another meeting can start while an older stopped run finalizes; each run retains isolated options and artifact paths. +Pausing transcription keeps the active recognition pipeline and meeting session alive, including Azure conversation transcription and the run's speaker context. Captured audio is replaced with equal-length silence before it reaches the temporary WAV or transcription backend, so real audio from the paused interval is discarded while provider continuity and meeting-relative timing are preserved. Normal transcript-inactivity notifications and auto-stop are suppressed during pause, while a separate four-hour maximum continuous pause prevents a forgotten paused meeting from running indefinitely. The recording status response exposes pause state as `isPaused`. + During an active run, microphone creation failures and disconnects are retried every second with fresh endpoint selection. The meeting and system-loopback capture stay active, with microphone silence mixed in until capture resumes. This recovery does not cover a failed system-loopback source. Outlook enrichment selects an unambiguous current or imminent appointment. A scheduled prompt shown during an active recording can apply that exact appointment's title, eligible attendees, agenda, and scheduled end without interrupting capture; explicit prompt metadata wins over a slower background lookup. diff --git a/docs/meeting-assistant-configuration.md b/docs/meeting-assistant-configuration.md index 8af2138..41e8bb7 100644 --- a/docs/meeting-assistant-configuration.md +++ b/docs/meeting-assistant-configuration.md @@ -38,6 +38,7 @@ This example is abbreviated so the most common shape is readable. The checked-in "FirstPromptAfter": "00:02:00", "ReminderPromptAfter": [ "00:05:00", "00:10:00" ], "AutoStopAfter": "00:30:00", + "MaximumPauseDuration": "04:00:00", "InferredEndPadding": "00:01:00", "CheckInterval": "00:00:15" } @@ -131,20 +132,23 @@ The default profile is always named `default`. Non-default profile hotkeys are r During recording, Meeting Assistant captures microphone and system loopback separately, buffers both streams to align samples, cleans the microphone stream through a local adaptive echo canceller using loopback as the far-end reference, then mixes the cleaned microphone and system streams into the normal 16 kHz mono PCM chunks. If one source is quiet beyond the alignment timeout, the available source is mixed with synthetic silence so microphone-only speech and system-only playback keep flowing to transcription. +The tray's fine-grained controls expose `Pause transcription` while a meeting is active and `Unpause transcription` while it is paused. Pause does not stop audio devices, finish the meeting, replace the speech-recognition pipeline, or reset run-local speaker mappings and collected samples. Instead, each captured mixed chunk is replaced with equal-length PCM silence before it reaches the temporary WAV, live speaker buffer, or configured transcription provider. This discards real audio from the paused interval while preserving the provider session and meeting-relative timing. In particular, Azure keeps the same active `ConversationTranscriber` and push stream; pause therefore does not suspend Azure connection time or billing. `Finish meeting` and cancel/discard remain available while paused, and `/recording/status` reports the state in `isPaused`. + On Windows, `Recording:MicrophoneDeviceId` can pin capture to a specific active microphone endpoint id. Leave it blank to follow the Windows default capture endpoint. The tray icon menu also exposes `Microphone`, listing active microphone endpoints with the effective endpoint checked. Selecting a microphone there overrides the configured/default microphone for later recording starts until another microphone is selected or the process exits. `Recording:MicrophoneMixGain` and `Recording:SystemAudioMixGain` are applied during the final mix and default to `1`. `Recording:TemporaryRecordingsFolder` controls where the temporary mixed WAV is written while the run is active. Temporary WAV files are deleted after the run completes, and stale temporary recordings from interrupted runs are deleted when the application starts. If an Azure Speech meeting cannot drain transcription before `Recording:StopProcessingTimeout`, Meeting Assistant keeps the WAV and writes a durable backlog item under `TemporaryRecordingsFolder\offline-transcription-backlog`. The background backlog worker retries those queued meetings, replays each WAV through a fresh speech pipeline, rewrites the original transcript, completes meeting metadata and summary generation, then removes the backlog item and WAV. `Recording:MaxMetadataAttendeeImportCount` limits how many attendees Outlook metadata enrichment imports into meeting-note frontmatter. The default is `30`; when an appointment has more attendees than that, Meeting Assistant still imports title, agenda, and scheduled end time, but leaves attendees empty because large invites are usually presentation-style meetings. -`Recording:InactivitySafeguard` watches active recordings for long periods without transcript text. The timer starts at meeting start and resets whenever a live transcript segment with text arrives. By default the app asks whether to stop after 2, 5, and 10 minutes of inactivity through native Windows app notifications with action buttons, requests reminder-style toast behavior, keeps each stop reminder actionable for 1 minute, and automatically stops normally after 30 minutes. Ignoring a notification does not block later checks or auto-stop. Safeguard stops are not aborts: transcription drain, speaker processing, screenshots, and summary generation continue through the normal stop flow. When the safeguard stops a run, the meeting end time is inferred as the last transcript segment timestamp plus `InferredEndPadding`; if no transcript text arrived, it uses meeting start plus the same padding. +`Recording:InactivitySafeguard` watches active recordings for long periods without transcript text. The timer starts at meeting start and resets whenever a live transcript segment with text is written. Writing new transcript text also dismisses every outstanding inactivity notification and invalidates its actions. By default the app asks whether to stop after 2, 5, and 10 minutes of inactivity through native Windows app notifications with Yes, No, and `Pause transcription` actions, requests reminder-style toast behavior, keeps each stop reminder actionable for 1 minute, and automatically stops normally after 30 minutes. While transcription is intentionally paused, those prompts and the ordinary transcript-inactivity stop are fully suspended. A separate `MaximumPauseDuration`, defaulting to 4 hours, normally stops a meeting that remains continuously paused without showing an inactivity notification; it remains active when the ordinary inactivity safeguard is disabled, while a non-positive value disables the paused-session cutoff. Unpausing clears the continuous-pause timer and restarts transcript-inactivity timing from that moment. Ignoring a notification does not block later checks or auto-stop. Safeguard stops are not aborts: transcription drain, speaker processing, screenshots, and summary generation continue through the normal stop flow. When transcript inactivity stops a run, the meeting end time is inferred as the last transcript segment timestamp plus `InferredEndPadding`; if no transcript text arrived, it uses meeting start plus the same padding. | Setting | Purpose | | --- | --- | -| `Enabled` | Enables the inactivity safeguard for active recordings. | +| `Enabled` | Enables transcript-inactivity prompts and `AutoStopAfter`; `MaximumPauseDuration` remains independent. | | `FirstPromptAfter` | First transcript-inactivity duration before showing the stop prompt. | | `ReminderPromptAfter` | Additional transcript-inactivity durations before showing another stop prompt. | | `AutoStopAfter` | Transcript-inactivity duration after which Meeting Assistant stops the recording normally without prompting again. | +| `MaximumPauseDuration` | Maximum continuous transcription pause before Meeting Assistant stops the meeting normally without an inactivity notification; defaults to 4 hours, and a non-positive value disables it. | | `InferredEndPadding` | Padding added to the last transcript timestamp, or meeting start when no transcript arrived, for safeguard-triggered end times. | | `CheckInterval` | Polling interval for checking the active recording inactivity state. | diff --git a/openspec/changes/add-transcription-pause-controls/.openspec.yaml b/openspec/changes/add-transcription-pause-controls/.openspec.yaml new file mode 100644 index 0000000..032461f --- /dev/null +++ b/openspec/changes/add-transcription-pause-controls/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-09-02 diff --git a/openspec/changes/add-transcription-pause-controls/design.md b/openspec/changes/add-transcription-pause-controls/design.md new file mode 100644 index 0000000..65079e6 --- /dev/null +++ b/openspec/changes/add-transcription-pause-controls/design.md @@ -0,0 +1,67 @@ +## Context + +Meeting Assistant currently has one active `RecordingRun` that owns its speech-recognition pipeline, transcript session, temporary WAV, speaker mappings, and live speaker samples. Mixed audio chunks are written to both the WAV and the active pipeline. Transcript inactivity is tracked separately, and Windows inactivity toasts share a notification group but expose only stop/continue callbacks. + +The Azure Speech SDK `ConversationTranscriber` has start and stop operations but no pause operation. Stopping ends the ongoing real-time recognition session, and recreating or restarting recognition can reset backend speaker IDs. Continuous recognition does support an open push stream containing silence, so the provider session can remain alive without receiving the meeting's actual audio during a pause. + +## Goals / Non-Goals + +**Goals:** + +- Pause the transcription of an active meeting without finishing its recording run. +- Prevent actual paused audio from reaching either durable temporary audio or a remote/local transcription backend. +- Preserve the same recognition pipeline, Azure conversation transcriber, transcript session, speaker mappings, collected speaker samples, and artifacts. +- Keep normal finish, cancel/discard, and profile-switch controls usable while paused. +- Treat intentional pause as distinct from inactivity and dismiss notifications that become obsolete when transcript text resumes. + +**Non-Goals:** + +- Suspend microphone or loopback device capture at the operating-system layer. +- Disconnect or stop the configured speech-recognition backend while paused. +- Reduce Azure connection time or billing during a pause. +- Persist pause state across process restarts or stopped meeting backlog replay. +- Add a pause hotkey. + +## Decisions + +### Preserve the pipeline by substituting silence at the recording-run boundary + +For each mixed audio chunk captured while paused, the coordinator will create an equal-length zeroed PCM chunk and route that chunk to the temporary WAV, live speaker audio buffer, and current speech-recognition pipeline. Real captured samples are discarded at that boundary. + +This keeps audio duration and transcript timestamps aligned while keeping the Azure push stream active. Dropping chunks entirely was rejected because a sufficiently long input gap can stop or reconnect a provider session. Calling `StopTranscribingAsync` was rejected because it terminates the ongoing Azure operation and cannot guarantee stable backend speaker IDs when started again. + +### Keep pause state on the active recording run + +The run will expose a thread-safe paused flag and coordinator pause/unpause operations. `RecordingStatus` will expose the flag so tray rendering and the loopback status endpoint observe the same state. Pause requests outside an active capture will be harmless, and normal stop/abort paths will remain authoritative. + +The paused flag will not become another post-recording process state: a paused run is still an active recording and continues to offer Finish and Cancel. + +### Separate transcript inactivity from a maximum continuous pause + +The inactivity safeguard will skip transcript-inactivity prompting and its ordinary auto-stop while the run is paused. Pausing will dismiss all outstanding inactivity notifications. A separate `MaximumPauseDuration`, defaulting to four hours, will normally stop a run that remains continuously paused for that duration without showing inactivity notifications. Unpausing will clear the paused-duration timer, set a new transcript-inactivity baseline, and advance the activity version so prompt thresholds start over rather than firing immediately. + +### Make notification lifecycle part of the prompt-service contract + +`IMeetingInactivityPromptService` will gain an operation to dismiss all active inactivity prompts. The Windows implementation will remove the notification group from Action Center and clear its pending callback registry. The no-op and test implementations will implement the same public contract. + +The coordinator will call dismissal only after a non-empty live segment has been durably appended, matching the user's observable meaning of a new transcription being written. Notification callbacks will verify that their originating run is still current before changing recording state. + +### Model pause as one toggling tray action + +The active-recording tray menu will show `Pause transcription` while running and `Unpause transcription` while paused. It will stay in the fine-grained controls section below the dedicated `Finish meeting` section. The inactivity toast will add `Pause transcription` alongside the existing Yes/No stop controls. + +## Risks / Trade-offs + +- **Azure may still reconnect for unrelated transport failures during a long pause** → Reuse the existing Azure reconnect behavior; the application preserves meeting artifacts and resets backend speaker assumptions only if Azure actually creates a new SDK session. +- **Silence consumes provider connection time and temporary WAV space** → Accept this to preserve provider/session continuity and timestamp alignment; document that pause is not a cost-suspension mechanism. +- **A forgotten pause could otherwise keep capture and provider resources alive indefinitely** → Apply the separate four-hour maximum continuous pause while keeping the shorter transcript-inactivity prompts fully suppressed. +- **A transcript result already buffered by the provider can arrive just after pause** → Keep and write it because it represents audio submitted before the pause boundary. +- **A stale notification action could affect a later meeting** → Clear pending callbacks on dismissal and verify the originating run before applying stop or pause. + +## Migration Plan + +No data or configuration migration is required. Deploy the updated executable normally. Rollback restores the previous controls; existing meeting artifacts and speaker identities remain compatible. + +## Open Questions + +None. diff --git a/openspec/changes/add-transcription-pause-controls/proposal.md b/openspec/changes/add-transcription-pause-controls/proposal.md new file mode 100644 index 0000000..95e3ead --- /dev/null +++ b/openspec/changes/add-transcription-pause-controls/proposal.md @@ -0,0 +1,28 @@ +## Why + +Transcript-inactivity notifications remain visible after transcription has resumed, and there is no way to intentionally suspend transcription during a break without ending the meeting and losing the active recognition session. Meeting Assistant should distinguish intentional pauses from accidental inactivity while preserving the meeting run and speaker context. + +## What Changes + +- Dismiss every outstanding transcript-inactivity notification as soon as a new non-empty transcript segment is written. +- Allow an active meeting transcription to be paused and unpaused without ending the recording run, replacing captured audio with silence so paused audio is neither persisted nor sent to the transcription backend. +- Keep the active speech-recognition pipeline, including the Azure conversation transcriber session, run-local speaker mappings, artifacts, and normal finish/cancel controls intact across a pause. +- Suspend transcript-inactivity prompts and the ordinary inactivity stop while paused, but normally stop a meeting that remains continuously paused for four hours by default; restart inactivity timing when transcription is unpaused. +- Add `Pause transcription` / `Unpause transcription` to the active-recording tray menu and add `Pause transcription` to transcript-inactivity notifications. + +## Capabilities + +### New Capabilities + +None. + +### Modified Capabilities + +- `meeting-recording`: Add pause state and controls, intentional-pause inactivity behavior, and automatic dismissal of obsolete inactivity notifications. +- `meeting-transcription`: Preserve one streaming recognition session and speaker context while paused audio is replaced with silence. + +## Impact + +- Affects recording status and coordinator behavior, inactivity prompt abstractions and the Windows toast implementation, tray menu modeling/rendering, and loopback status output. +- Affects the audio routed to temporary recordings, live speaker sampling, and configured streaming speech-recognition providers during an intentional pause. +- Adds one paused-session safety-timeout setting under the existing inactivity safeguard, adds no external dependency, and does not change normal finish, cancel/discard, profile-switch, or post-recording processing behavior. diff --git a/openspec/changes/add-transcription-pause-controls/specs/meeting-recording/spec.md b/openspec/changes/add-transcription-pause-controls/specs/meeting-recording/spec.md new file mode 100644 index 0000000..07b73f6 --- /dev/null +++ b/openspec/changes/add-transcription-pause-controls/specs/meeting-recording/spec.md @@ -0,0 +1,213 @@ +## ADDED Requirements + +### Requirement: Active transcription can be paused without ending the meeting +Meeting Assistant SHALL allow transcription for an active meeting recording to be paused and unpaused without stopping the meeting run. + +While transcription is paused, Meeting Assistant SHALL keep the recording status active, SHALL preserve the meeting artifacts and run-local speaker context, and SHALL keep the normal finish and cancel/discard controls available. + +When transcription is unpaused, Meeting Assistant SHALL resume transcribing newly captured audio through the existing meeting run. + +Pausing or unpausing when no active recording exists SHALL leave recording state unchanged. + +#### Scenario: Active transcription is paused and unpaused +- **GIVEN** a meeting is actively recording +- **WHEN** the user pauses transcription +- **THEN** the meeting remains active and reports that transcription is paused +- **AND** keeps its existing artifacts and speaker context +- **WHEN** the user unpauses transcription +- **THEN** newly captured audio is transcribed in the same meeting run + +#### Scenario: Paused meeting can still be finished +- **GIVEN** an active meeting transcription is paused +- **WHEN** the user finishes the meeting +- **THEN** Meeting Assistant follows the normal stop, transcription drain, speaker processing, and summary flow + +#### Scenario: Pause request while idle is harmless +- **GIVEN** no meeting recording is active +- **WHEN** transcription pause is requested +- **THEN** Meeting Assistant remains idle + +## MODIFIED Requirements + +### Requirement: Windows taskbar icon controls recording +Meeting Assistant SHALL show a Windows taskbar notification icon when running on Windows. + +The taskbar icon SHALL indicate whether the newest meeting process is idle, actively recording, or post-recording processing/summarizing. + +When a new meeting is actively recording while an older stopped meeting is still transcribing, recognizing speakers, or summarizing, the taskbar icon SHALL show the new active recording state. + +The taskbar icon right-click menu SHALL expose recording controls based on the current state and configured launch profiles. + +The taskbar icon right-click menu SHALL expose an Exit action in every recording state. + +When Meeting Assistant is idle or only processing older stopped meetings, the menu SHALL allow starting a meeting recording for each configured launch profile. + +When a meeting is actively recording, the menu SHALL allow stopping the recording and continuing transcription/summary generation. + +During an active recording, the normal stop action SHALL be labeled `Finish meeting` and SHALL be the only action in a dedicated menu section immediately below the `Open agent` section. + +During an active recording, pause/unpause, microphone selection, cancel/discard, and profile-switch actions SHALL appear in a separate fine-grained controls section below `Finish meeting`. + +When a meeting is actively recording and transcription is running, the menu SHALL expose `Pause transcription`. + +When a meeting is actively recording and transcription is paused, the menu SHALL expose `Unpause transcription` and SHALL continue exposing `Finish meeting`. + +When a meeting is actively recording, the menu SHALL allow canceling the recording and discarding that run's artifacts. + +When a meeting is actively recording, the menu SHALL allow switching to each configured launch profile other than the current active profile. + +Selecting Exit while Meeting Assistant is idle SHALL stop the application without an additional confirmation prompt. + +Selecting Exit while Meeting Assistant is recording, transcribing, recognizing speakers, or summarizing SHALL show a confirmation dialog before stopping the application. + +#### Scenario: Idle tray menu can start configured profiles +- **GIVEN** launch profiles `default` and `english` are configured +- **AND** no meeting recording is active +- **WHEN** the taskbar menu is opened +- **THEN** it offers start recording actions for `default` and `english` + +#### Scenario: Recording tray menu prioritizes finishing the meeting +- **GIVEN** launch profiles `default` and `english` are configured +- **AND** a meeting is actively recording with profile `default` +- **WHEN** the taskbar menu is opened +- **THEN** `Finish meeting` is the only action in the section immediately below `Open agent` +- **AND** pause, microphone selection, cancel/discard, and switching to `english` appear in a separate following section +- **AND** the menu does not offer switching to `default` + +#### Scenario: Tray pause action changes to unpause +- **GIVEN** a meeting is actively recording with transcription running +- **WHEN** the taskbar menu is opened +- **THEN** it offers `Pause transcription` +- **WHEN** transcription is paused and the taskbar menu is opened again +- **THEN** it offers `Unpause transcription` +- **AND** still offers `Finish meeting` + +#### Scenario: Active recording has priority over older summarizing runs +- **GIVEN** an older meeting is still summarizing +- **WHEN** a newer meeting is actively recording +- **THEN** the taskbar icon indicates recording + +#### Scenario: Tray menu always exposes Exit +- **GIVEN** Meeting Assistant is running +- **WHEN** the taskbar menu is opened +- **THEN** it offers an Exit action + +#### Scenario: Idle Exit stops immediately +- **GIVEN** no recording, transcription, speaker recognition, or summary work is running +- **WHEN** the user selects Exit from the taskbar menu +- **THEN** Meeting Assistant stops the application without an additional confirmation prompt + +#### Scenario: In-progress Exit asks for confirmation +- **GIVEN** Meeting Assistant is recording, transcribing, recognizing speakers, or summarizing +- **WHEN** the user selects Exit from the taskbar menu +- **THEN** Meeting Assistant asks for confirmation before stopping the application + +### Requirement: Recording inactivity safeguard stops forgotten meetings +Meeting Assistant SHALL track transcript inactivity during an active recording from the later of meeting start, the most recent unpause, or the most recent live transcript segment that contains text. + +Meeting Assistant SHALL show a stop prompt when transcript inactivity reaches configured prompt thresholds. The default thresholds SHALL be 2 minutes, 5 minutes, and 10 minutes. + +On Windows, the stop prompt SHALL use a native Windows app notification with stop, continue, and pause-transcription action buttons. + +On Windows, the stop prompt notification SHALL request reminder-style toast behavior and remain actionable for 1 minute. + +The stop prompt SHALL ask whether to stop the meeting and SHALL provide affirmative, negative, and pause-transcription actions. + +Showing or ignoring the stop prompt SHALL NOT block later inactivity checks, reminder prompts, or automatic stop. + +If the user accepts the stop prompt, Meeting Assistant SHALL stop the recording normally, allowing transcription, speaker recognition, and summary generation to continue as for a normal stop. + +If the user selects pause from the stop prompt, Meeting Assistant SHALL pause transcription for that same active meeting without finishing it. + +When a new non-empty live transcript segment is written, Meeting Assistant SHALL dismiss all outstanding transcript-inactivity notifications and invalidate their pending actions. + +While transcription is intentionally paused, Meeting Assistant SHALL NOT show transcript-inactivity prompts and SHALL NOT apply the ordinary transcript-inactivity auto-stop threshold. + +Meeting Assistant SHALL normally stop a meeting that remains continuously paused for the configured maximum pause duration, defaulting to 4 hours, without first showing a transcript-inactivity notification. This maximum continuous-pause cutoff SHALL remain active when ordinary transcript-inactivity prompting and auto-stop are disabled. + +When transcription is unpaused, Meeting Assistant SHALL clear the continuous-pause timer and restart transcript-inactivity timing from the unpause time. + +Meeting Assistant SHALL automatically stop the recording normally when transcript inactivity reaches the configured auto-stop threshold, defaulting to 30 minutes. + +When the inactivity safeguard stops a recording, Meeting Assistant SHALL infer the meeting end time from the most recent transcript segment timestamp plus configured padding, defaulting to 1 minute. If no transcript segment has arrived, Meeting Assistant SHALL infer the end time from the meeting start time plus the same padding. + +When a recording stops normally and its meeting note, transcript, and assistant context contain no user-authored or captured content beyond generated default headings and metadata, Meeting Assistant SHALL delete the run artifacts instead of running summary generation. + +#### Scenario: Inactive recording prompts the user +- **GIVEN** a recording is active +- **AND** no transcript text has arrived for the first configured inactivity prompt threshold +- **WHEN** the inactivity safeguard checks the active recording +- **THEN** Meeting Assistant prompts the user whether to stop the meeting with a native Windows app notification when running on Windows +- **AND** the notification offers pause transcription +- **AND** the notification remains actionable for 1 minute +- **AND** does not abort or discard meeting artifacts + +#### Scenario: Ignored inactivity prompt does not block auto-stop +- **GIVEN** a recording is active +- **AND** the inactivity safeguard prompt was shown +- **WHEN** the user ignores the prompt until the automatic stop threshold is reached +- **THEN** Meeting Assistant stops the recording normally without waiting for a prompt response + +#### Scenario: User accepts inactivity stop prompt +- **GIVEN** a recording is active +- **AND** the inactivity safeguard prompt is shown +- **WHEN** the user chooses to stop the meeting +- **THEN** Meeting Assistant stops the recording normally +- **AND** continues normal transcription and summary processing +- **AND** writes the inferred meeting end time to meeting artifacts + +#### Scenario: User pauses from inactivity prompt +- **GIVEN** a recording is active +- **AND** the inactivity safeguard prompt is shown +- **WHEN** the user chooses to pause transcription +- **THEN** Meeting Assistant dismisses the outstanding inactivity notifications +- **AND** pauses transcription without finishing the meeting + +#### Scenario: Inactive recording automatically stops +- **GIVEN** a recording is active +- **AND** no transcript text has arrived through the configured automatic stop threshold +- **WHEN** the inactivity safeguard checks the active recording +- **THEN** Meeting Assistant stops the recording normally without aborting artifacts +- **AND** writes the inferred meeting end time to meeting artifacts + +#### Scenario: New transcript text resets inactivity prompts +- **GIVEN** a recording is active +- **AND** one or more inactivity prompts were shown +- **WHEN** a new transcript segment with text is written +- **AND** the segment belongs to that active recording +- **THEN** Meeting Assistant dismisses every outstanding inactivity notification +- **AND** invalidates their pending actions +- **AND** resets the inactivity prompt schedule from that transcript arrival + +#### Scenario: Paused transcription suppresses inactivity safeguard +- **GIVEN** an active meeting transcription is paused +- **WHEN** configured transcript-inactivity prompt or automatic-stop thresholds pass before the maximum pause duration +- **THEN** Meeting Assistant does not show an inactivity prompt +- **AND** does not stop the meeting for transcript inactivity +- **WHEN** transcription is unpaused +- **THEN** inactivity timing restarts from the unpause time + +#### Scenario: Continuously paused meeting is stopped after four hours +- **GIVEN** an active meeting transcription is paused continuously +- **WHEN** the configured maximum pause duration of 4 hours is reached +- **THEN** Meeting Assistant does not show a transcript-inactivity notification +- **AND** stops the meeting normally + +#### Scenario: Maximum pause remains active when transcript-inactivity handling is disabled +- **GIVEN** ordinary transcript-inactivity prompting and auto-stop are disabled +- **AND** an active meeting transcription is paused continuously +- **WHEN** the configured maximum pause duration is reached +- **THEN** Meeting Assistant stops the meeting normally without an inactivity notification + +#### Scenario: An older run cannot dismiss a current run's notification +- **GIVEN** an older stopped meeting is still draining transcription +- **AND** a newer active meeting has an outstanding transcript-inactivity notification +- **WHEN** the older meeting writes a late transcript segment +- **THEN** the newer meeting's notification and pending actions remain active + +#### Scenario: Empty stopped recording is cleaned up +- **GIVEN** a recording is active +- **AND** the meeting note, transcript, and assistant context only contain generated default content +- **WHEN** the recording stops normally +- **THEN** Meeting Assistant deletes the run artifacts +- **AND** does not run summary generation diff --git a/openspec/changes/add-transcription-pause-controls/specs/meeting-transcription/spec.md b/openspec/changes/add-transcription-pause-controls/specs/meeting-transcription/spec.md new file mode 100644 index 0000000..1354994 --- /dev/null +++ b/openspec/changes/add-transcription-pause-controls/specs/meeting-transcription/spec.md @@ -0,0 +1,28 @@ +## ADDED Requirements + +### Requirement: Streaming recognition sessions survive intentional transcription pauses +Meeting Assistant SHALL preserve the active streaming speech-recognition pipeline and transcript session while transcription is intentionally paused. + +For every mixed audio chunk captured while paused, Meeting Assistant SHALL discard the captured sample values and SHALL send an equal-duration PCM silence chunk to the temporary recording, live speaker audio buffer, and configured speech-recognition pipeline. + +Meeting Assistant SHALL NOT clear run-local speaker mappings or previously collected speaker samples when transcription is paused or unpaused. + +When Azure Speech is the configured provider, Meeting Assistant SHALL keep the same active `ConversationTranscriber` operation and push audio stream across the pause rather than stopping and recreating the Azure recognition session. + +#### Scenario: Paused audio is replaced with silence +- **GIVEN** an active meeting transcription is paused +- **WHEN** the audio source captures a non-silent mixed audio chunk +- **THEN** the temporary recording and speech-recognition pipeline receive an equal-length silent chunk +- **AND** neither receives the captured sample values + +#### Scenario: Azure session remains active across pause +- **GIVEN** Azure Speech is transcribing an active meeting with speaker attribution +- **WHEN** transcription is paused and later unpaused +- **THEN** Meeting Assistant keeps the same conversation transcriber and push stream active +- **AND** preserves run-local speaker mappings and collected speaker samples +- **AND** newly captured audio after unpause continues through that session + +#### Scenario: Buffered pre-pause result is retained +- **GIVEN** the transcription backend accepted audio before transcription was paused +- **WHEN** the corresponding transcript result arrives after the pause begins +- **THEN** Meeting Assistant writes that transcript result to the same meeting transcript diff --git a/openspec/changes/add-transcription-pause-controls/tasks.md b/openspec/changes/add-transcription-pause-controls/tasks.md new file mode 100644 index 0000000..c76000d --- /dev/null +++ b/openspec/changes/add-transcription-pause-controls/tasks.md @@ -0,0 +1,38 @@ +## 1. Inactivity notification lifecycle + +- [x] 1.1 Add a failing coordinator behavior test proving that a newly written non-empty transcript segment dismisses every outstanding inactivity prompt. +- [x] 1.2 Extend the inactivity prompt service contract and Windows implementation to invalidate callbacks and remove the complete inactivity notification group. + +## 2. Pause and unpause behavior + +- [x] 2.1 Add a failing coordinator behavior test proving that pause keeps the run active, routes equal-duration silence instead of captured audio, and unpause resumes real audio through the same pipeline. +- [x] 2.2 Implement thread-safe pause state, coordinator pause/unpause controls, status reporting, and silence substitution without resetting speaker state or the active pipeline. +- [x] 2.3 Add a failing behavior test proving that inactivity prompts and auto-stop are suspended while paused and restart from the unpause time. +- [x] 2.4 Implement pause-aware inactivity timing and guard prompt callbacks so stale notifications cannot control another run. + +## 3. User controls + +- [x] 3.1 Add a failing tray-menu behavior test for `Pause transcription` / `Unpause transcription` while `Finish meeting` remains available. +- [x] 3.2 Add the tray pause toggle action in the fine-grained controls section and wire it to the coordinator. +- [x] 3.3 Add a failing inactivity-prompt behavior test proving the pause response pauses the originating active meeting. +- [x] 3.4 Add the `Pause transcription` Windows notification action and route its response through the guarded coordinator pause path. + +## 4. Documentation and verification + +- [x] 4.1 Update the operational documentation with pause behavior, Azure session continuity, silence substitution, and the tray/notification controls. +- [x] 4.2 Refactor the touched paths for DRYness, SOLID boundaries, and simplicity while preserving behavior, including pause/inactivity race handling found during independent review. +- [x] 4.3 Run focused recording/taskbar tests, the Windows application build, the full solution tests, and `openspec validate add-transcription-pause-controls --strict`. +- [x] 4.4 Inspect the local health and recording-status surfaces without restarting or interrupting an active meeting run. + +## 5. Maximum continuous pause + +- [x] 5.1 Add a failing coordinator behavior test proving that ordinary inactivity prompts remain suppressed while paused and the meeting stops normally after four continuous paused hours. +- [x] 5.2 Track the continuous pause start and implement the configurable four-hour paused-session safety stop without allowing an unpause race to stop the meeting. +- [x] 5.3 Update configuration documentation and rerun focused tests, the Windows build, the full suite, and strict OpenSpec validation. + +## 6. Review follow-up + +- [x] 6.1 Keep the maximum continuous-pause cutoff active when ordinary inactivity handling is disabled, with a failing public behavior test. +- [x] 6.2 Scope notification dismissal to the active run and move activity invalidation after durable transcript append, with overlapping-run and blocked-write regression tests. +- [x] 6.3 Make pause-notification activity validation atomic and make tray pause/unpause actions intent-specific, with race and stale-menu tests. +- [x] 6.4 Complete an independent simplification review and rerun all required validation before commit.