-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathVoicePageModel.cs
More file actions
813 lines (700 loc) · 30.5 KB
/
VoicePageModel.cs
File metadata and controls
813 lines (700 loc) · 30.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Maui.Media;
using CommunityToolkit.Maui.Alerts;
using CommunityToolkit.Maui.Core;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Logging;
using Plugin.Maui.Audio;
using Telepathic.Models;
using Telepathic.Services;
using Telepathic.Data.UserMemory;
namespace Telepathic.PageModels;
public enum VoicePhase { Recording, Transcribing, Reviewing }
public partial class VoicePageModel : ObservableObject, IProjectTaskPageModel
{
// Interface implementations
IAsyncRelayCommand<ProjectTask> IProjectTaskPageModel.NavigateToTaskCommand => NavigateToTaskCommand;
IAsyncRelayCommand<ProjectTask> IProjectTaskPageModel.AcceptRecommendationCommand => AcceptRecommendationCommand;
IAsyncRelayCommand<ProjectTask> IProjectTaskPageModel.RejectRecommendationCommand => RejectRecommendationCommand;
IAsyncRelayCommand<ProjectTask> IProjectTaskPageModel.AssistCommand => AssistCommand;
bool IProjectTaskPageModel.IsBusy => IsBusy;
private readonly IAudioManager _audioManager;
private readonly IChatClientService _chatClientService;
private readonly ModalErrorHandler _errorHandler;
private readonly ILogger<VoicePageModel> _logger;
private readonly TaskAssistHandler _taskAssistHandler;
private readonly IUserMemoryStore _memoryStore;
private readonly ISpeechToText _speechToText;
IAudioSource? _audioSource = null;
IAudioRecorder? _recorder;
readonly ITranscriptionService _transcriber;
private CancellationTokenSource? _recordingCts;
[ObservableProperty] bool isRecording;
[ObservableProperty] bool isBusy;
[ObservableProperty] VoicePhase phase = VoicePhase.Recording;
[ObservableProperty] string recordButtonText = "🎤 Record";
[ObservableProperty] string transcript = string.Empty;
[ObservableProperty] string liveTranscript = string.Empty;
[ObservableProperty] bool useSpeechToText = true; // Default to real-time STT
// Status indicator properties
[ObservableProperty] bool isAnalyzingContext;
[ObservableProperty] string analysisStatusTitle = "Processing";
[ObservableProperty] string analysisStatusDetail = "Preparing to analyze your recording...";
// Extracted projects and tasks
[ObservableProperty] List<Project> projects = new();
// Priority options for pickers
public ObservableCollection<int?> PriorityOptions { get; } = new() { null, 1, 2, 3, 4, 5 };
private readonly ProjectRepository _projectRepository;
private readonly TaskRepository _taskRepository;
// Stopwatch for measuring performance
private Stopwatch _stopwatch = new();
public VoicePageModel(
IAudioManager audioManager,
ITranscriptionService transcriber,
ModalErrorHandler errorHandler,
IChatClientService chatClientService,
ProjectRepository projectRepository,
TaskRepository taskRepository,
ILogger<VoicePageModel> logger,
TaskAssistHandler taskAssistHandler,
IUserMemoryStore memoryStore,
ISpeechToText speechToText)
{
// _audio = audio;
_audioManager = audioManager;
_transcriber = transcriber;
_errorHandler = errorHandler;
_chatClientService = chatClientService;
_projectRepository = projectRepository;
_taskRepository = taskRepository;
_logger = logger;
_taskAssistHandler = taskAssistHandler;
_memoryStore = memoryStore;
_speechToText = speechToText;
// Subscribe to completion event once (like working sample)
_speechToText.RecognitionResultCompleted += OnRecognitionTextCompleted;
_speechToText.StateChanged += OnSpeechToTextStateChanged;
_logger.LogInformation("Voice Modal Page Model initialized");
}
/// <summary>
/// Navigate to the task detail page for a specific task
/// </summary>
[RelayCommand]
private Task NavigateToTask(ProjectTask? task)
{
if (task == null) return Task.CompletedTask;
_logger.LogInformation("Navigating to task details page for task: {TaskTitle}", task.Title);
return Shell.Current.GoToAsync($"task?id={task.ID}");
}
[RelayCommand]
private async Task ToggleRecordingAsync()
{
// Route to appropriate recording method based on mode
if (UseSpeechToText)
{
await ToggleSpeechToTextAsync();
}
else
{
await ToggleAudioRecordingAsync();
}
}
/// <summary>
/// Toggle Speech-to-Text recording with real-time transcription
/// </summary>
private async Task ToggleSpeechToTextAsync()
{
if (!IsRecording)
{
try
{
// Use ISpeechToText's built-in permission request (like working sample)
_logger.LogInformation("Requesting speech recognition permissions");
var isGranted = await _speechToText.RequestPermissions(CancellationToken.None);
if (!isGranted)
{
_logger.LogWarning("Speech recognition permission not granted");
await Shell.Current.DisplayAlert(
"Permission Required",
"Speech recognition requires microphone and speech permissions. Please enable them in System Settings > Privacy & Security.",
"OK");
return;
}
// Check network connectivity (required for online STT)
if (Connectivity.NetworkAccess != NetworkAccess.Internet)
{
_logger.LogWarning("No internet connection for STT");
await Shell.Current.DisplayAlert(
"Internet Required",
"Speech recognition requires an internet connection. Would you like to try audio recording mode instead?",
"OK");
return;
}
_logger.LogInformation("Starting Speech-to-Text recording");
_stopwatch.Restart();
_recordingCts = new CancellationTokenSource();
// Configure audio device to prefer external microphones
_logger.LogInformation("Configuring audio device for external microphone");
var deviceInfo = AudioDeviceService.ConfigureForExternalMicrophone();
// Show toast with selected microphone
var toast = Toast.Make(deviceInfo, ToastDuration.Short);
await toast.Show();
// Log available input devices for debugging
var availableDevices = AudioDeviceService.GetAvailableInputDevices();
_logger.LogInformation("Available audio input devices: {Devices}", string.Join(", ", availableDevices));
// Subscribe to updated event (completed already subscribed in constructor)
_speechToText.RecognitionResultUpdated += OnRecognitionTextUpdated;
_logger.LogInformation("Starting STT listener with culture: {Culture}, Partial: {Partial}",
CultureInfo.CurrentCulture.Name, true);
// Start listening with partial results
await _speechToText.StartListenAsync(
new CommunityToolkit.Maui.Media.SpeechToTextOptions
{
Culture = CultureInfo.CurrentCulture,
ShouldReportPartialResults = true
},
_recordingCts.Token);
_logger.LogInformation("STT listener started successfully");
IsRecording = true;
RecordButtonText = "⏹ Stop";
}
catch (Exception ex)
{
_logger.LogError(ex, "Error starting STT recording");
_errorHandler.HandleError(ex);
await CleanupSpeechToText();
}
}
else
{
try
{
_logger.LogInformation("Stopping Speech-to-Text recording");
_stopwatch.Stop();
Phase = VoicePhase.Transcribing;
// Unsubscribe from updated event before stopping
_speechToText.RecognitionResultUpdated -= OnRecognitionTextUpdated;
// Stop listening (don't cancel token first - let it complete gracefully)
_logger.LogInformation("Calling StopListenAsync");
await _speechToText.StopListenAsync(CancellationToken.None);
IsRecording = false;
RecordButtonText = "🎤 Record";
_logger.LogInformation("STT recording stopped after {Duration}ms - waiting for completion event", _stopwatch.ElapsedMilliseconds);
// The RecognitionResultCompleted event will handle the rest
}
catch (Exception ex)
{
_logger.LogError(ex, "Error stopping STT recording");
_errorHandler.HandleError(ex);
IsRecording = false;
RecordButtonText = "🎤 Record";
await CleanupSpeechToText();
}
}
}
/// <summary>
/// Toggle audio recording (legacy mode) - records audio then transcribes via API
/// </summary>
private async Task ToggleAudioRecordingAsync()
{
if (!IsRecording)
{
try
{
// Check for microphone permissions first
_logger.LogInformation("Checking microphone permissions");
var status = await Permissions.CheckStatusAsync<Permissions.Microphone>();
if (status != PermissionStatus.Granted)
{
_logger.LogInformation("Requesting microphone permissions");
status = await Permissions.RequestAsync<Permissions.Microphone>();
if (status != PermissionStatus.Granted)
{
_logger.LogWarning("Microphone permission denied");
// Permission denied - offer fallback
bool navigateToManual = await Shell.Current.DisplayAlert(
"Microphone Access Denied",
"Voice recording requires microphone access. Would you like to enter tasks manually instead?",
"Enter Manually", "Cancel");
if (navigateToManual)
{
_logger.LogInformation("User chose manual task entry after permission denial");
// Navigate to manual task entry
await Shell.Current.GoToAsync("task");
await Shell.Current.Navigation.PopModalAsync(); // Close this modal
}
return;
}
}
_logger.LogInformation("Starting audio recording");
_stopwatch.Restart();
// Configure audio device to prefer external microphones
_logger.LogInformation("Configuring audio device for external microphone");
var deviceInfo = AudioDeviceService.ConfigureForExternalMicrophone();
// Show toast with selected microphone
var toast = Toast.Make(deviceInfo, ToastDuration.Short);
await toast.Show();
// Log available input devices for debugging
var availableDevices = AudioDeviceService.GetAvailableInputDevices();
_logger.LogInformation("Available audio input devices: {Devices}", string.Join(", ", availableDevices));
_recorder = _audioManager.CreateRecorder();
await _recorder.StartAsync();
IsRecording = true;
RecordButtonText = "⏹ Stop";
}
catch (Exception ex)
{
_logger.LogError(ex, "Error starting recording");
_errorHandler.HandleError(ex);
}
}
else
{
try
{
if (_recorder == null)
{
_logger.LogWarning("Recorder is null - cannot stop recording");
return;
}
_audioSource = await _recorder.StopAsync();
IsRecording = false;
RecordButtonText = "🎤 Record";
// Log recording duration
_stopwatch.Stop();
_logger.LogInformation("Voice recording completed in {RecordingDuration}ms", _stopwatch.ElapsedMilliseconds);
Phase = VoicePhase.Transcribing;
// Now we'll actually transcribe the audio!
await TranscribeAsync();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error stopping recording");
_errorHandler.HandleError(ex);
IsRecording = false;
RecordButtonText = "🎤 Record";
}
}
}
/// <summary>
/// Event handler for real-time speech recognition updates
/// </summary>
private void OnRecognitionTextUpdated(object? sender, SpeechToTextRecognitionResultUpdatedEventArgs args)
{
MainThread.BeginInvokeOnMainThread(() =>
{
var resultText = args.RecognitionResult ?? string.Empty;
#if IOS
// iOS sends individual words, so append with space
if (!string.IsNullOrEmpty(LiveTranscript) && !string.IsNullOrEmpty(resultText))
{
LiveTranscript += " " + resultText;
}
else
{
LiveTranscript += resultText;
}
#else
// Android sends cumulative text, so replace
LiveTranscript = resultText;
#endif
_logger.LogInformation("STT partial result received: '{Text}' ({Length} chars)",
LiveTranscript.Length > 50 ? LiveTranscript.Substring(0, 50) + "..." : LiveTranscript,
LiveTranscript.Length);
});
}
/// <summary>
/// Event handler for speech recognition state changes
/// </summary>
private void OnSpeechToTextStateChanged(object? sender, SpeechToTextStateChangedEventArgs args)
{
_logger.LogInformation("STT state changed to: {State}", args.State);
}
/// <summary>
/// Event handler for completed speech recognition
/// </summary>
private void OnRecognitionTextCompleted(object? sender, SpeechToTextRecognitionResultCompletedEventArgs args)
{
MainThread.BeginInvokeOnMainThread(async () =>
{
try
{
_logger.LogInformation("STT completion event fired");
var result = args.RecognitionResult;
// Use LiveTranscript (contains full cumulative text from updates)
// On iOS, result.Text only contains the last word, not the full transcript
var finalText = LiveTranscript;
_logger.LogInformation("STT result - IsSuccessful: {IsSuccessful}, result.Text length: {Length}, LiveTranscript length: {LiveLength}, Exception: {Exception}",
result?.IsSuccessful ?? false,
result?.Text?.Length ?? 0,
finalText?.Length ?? 0,
result?.Exception?.Message ?? "None");
// Check if we have any text to work with
if (!string.IsNullOrWhiteSpace(finalText))
{
Transcript = finalText;
_logger.LogInformation("STT completed successfully: {Length} chars - '{Preview}'",
Transcript.Length,
Transcript.Length > 100 ? Transcript.Substring(0, 100) + "..." : Transcript);
// Clear live transcript AFTER phase change so UI transitions smoothly
LiveTranscript = string.Empty;
// Show progress indicators during AI task extraction
IsAnalyzingContext = true;
AnalysisStatusTitle = "Analyzing Content";
AnalysisStatusDetail = "Using AI to identify tasks and projects in your recording...";
// Extract tasks from the transcript
await ExtractTasksAsync();
IsAnalyzingContext = false;
}
else
{
var errorMsg = result?.Exception?.Message ?? "No text detected";
_logger.LogWarning("STT completed but no text - returning to recording phase. Error: {Error}", errorMsg);
Phase = VoicePhase.Recording;
LiveTranscript = string.Empty; // Clear any partial text
}
await CleanupSpeechToText();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error in STT completion handler");
_errorHandler.HandleError(ex);
await CleanupSpeechToText();
Phase = VoicePhase.Recording;
}
});
}
/// <summary>
/// Cleanup STT resources and event subscriptions
/// </summary>
private async Task CleanupSpeechToText()
{
try
{
// Only unsubscribe from updated event (completed is permanent in constructor)
_speechToText.RecognitionResultUpdated -= OnRecognitionTextUpdated;
_recordingCts?.Dispose();
_recordingCts = null;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during STT cleanup");
}
await Task.CompletedTask;
}
private async Task TranscribeAsync()
{
try
{
IsBusy = true;
IsAnalyzingContext = true;
AnalysisStatusTitle = "Processing Audio";
AnalysisStatusDetail = "Preparing your recording for transcription...";
// Create a temporary file path to save our recording
string audioFilePath = Path.Combine(FileSystem.CacheDirectory, $"recording_{DateTime.Now:yyyyMMddHHmmss}.wav");
_logger.LogInformation("Saving audio to temporary file at {FilePath}", audioFilePath);
// Save the audio source to a file
if (_audioSource != null)
{
AnalysisStatusDetail = "Saving audio recording...";
await using (var fileStream = File.Create(audioFilePath))
{
var audioStream = _audioSource.GetAudioStream();
await audioStream.CopyToAsync(fileStream);
}
_logger.LogInformation("Audio successfully saved to file");
}
else
{
_logger.LogError("Audio source is null - no recording available");
throw new InvalidOperationException("No recording is available to transcribe");
}
// Verify the file exists
if (!File.Exists(audioFilePath))
{
_logger.LogError("Recorded audio file not found at {FilePath}", audioFilePath);
throw new FileNotFoundException("Recorded audio file not found");
}
// Transcribe the audio using Whisper
_logger.LogInformation("Starting audio transcription");
_stopwatch.Restart();
AnalysisStatusTitle = "Transcribing";
AnalysisStatusDetail = "Converting your voice to text using AI...";
Transcript = await _transcriber.TranscribeAsync(audioFilePath, CancellationToken.None);
_stopwatch.Stop();
_logger.LogInformation("Audio transcription completed in {TranscriptionDuration}ms, length: {TranscriptLength}",
_stopwatch.ElapsedMilliseconds, Transcript?.Length ?? 0);
AnalysisStatusTitle = "Analyzing";
AnalysisStatusDetail = "Identifying projects and tasks from your recording...";
// Extract projects and tasks from the transcript
await ExtractTasksAsync();
}
catch (Exception ex)
{
_logger.LogError(ex, "Transcription failed");
_errorHandler.HandleError(ex);
// Return to recording phase if transcription fails
Phase = VoicePhase.Recording;
}
finally
{
IsBusy = false;
IsAnalyzingContext = false;
}
}
/// <summary>
/// Extract projects and tasks from the transcript using AI
/// </summary>
private async Task ExtractTasksAsync()
{
try
{
if (string.IsNullOrWhiteSpace(Transcript) || !_chatClientService.IsInitialized)
{
_logger.LogWarning("Cannot extract tasks: transcript is empty or chat client is not initialized");
return;
}
// Clear previous extraction results
Projects.Clear();
_logger.LogInformation("Starting task extraction from transcript");
_stopwatch.Restart();
AnalysisStatusTitle = "Analyzing Content";
AnalysisStatusDetail = "Using AI to identify tasks and projects in your recording...";
// Get user memory snapshot for context
var snapshot = await _memoryStore.GetSnapshotAsync(MemoryConstants.UserId);
string? userContext = null;
if (snapshot != null)
{
userContext = snapshot.GetFormattedText();
_logger.LogInformation("Including memory snapshot in voice analysis (version {Version})", snapshot.Version);
}
// ignore the audio and just see if we can get something meaningful from this text
// Transcript = "This week we are going to the Good Friday service at church, but we need to get Nolan from the airport around 9:30. This weekend we have an easter egg hunt at church and then after church Sunday morning we are going to Mammy's house for lunch and an egg hunt. We need to take a dish and the bag of candy for filling eggs.";
// Create a prompt that will extract projects and tasks from the transcript
var prompt = $@"
Extract projects and tasks from this voice memo transcript.
Analyze the text to identify actionable tasks I need to keep track of. Use the following instructions:
1. Tasks are actionable items that can be completed, such as 'Buy groceries' or 'Call Mom'.
2. Projects are larger tasks that may contain multiple smaller tasks, such as 'Plan birthday party' or 'Organize closet'.
3. Tasks must be grouped under a project and cannot be grouped under multiple projects.
4. Any mentioned due dates use the YYYY-MM-DD format
Here's the transcript: {Transcript}";
// Get response from the AI service with user context
var chatClient = _chatClientService.GetClient();
var response = await chatClient.GetResponseAsync<ProjectsJson>(prompt);
_stopwatch.Stop();
_logger.LogInformation("Task extraction completed in {ExtractionDuration}ms", _stopwatch.ElapsedMilliseconds);
if (response?.Result != null)
{
// Track successful voice analysis
await _memoryStore.LogEventAsync(MemoryEvent.Create(
"voice:analyze",
null,
new
{
project_count = response.Result.Projects.Count,
task_count = response.Result.Projects.Sum(p => p.Tasks.Count),
duration_ms = _stopwatch.ElapsedMilliseconds
},
1.5));
// Mark all extracted tasks as recommendations
foreach (var project in response.Result.Projects)
{
foreach (var task in project.Tasks)
{
task.IsRecommendation = true;
}
}
Projects = response.Result.Projects;
_logger.LogInformation("Found {NumberOfProjects} projects", Projects.Count);
_logger.LogInformation("Found {NumberOfTasks} tasks", Projects.Sum(p => p.Tasks.Count));
// Check if no projects or tasks were detected
if (Projects.Count == 0)
{
_logger.LogWarning("No projects or tasks detected in transcript");
await Shell.Current.DisplayAlert(
"No Tasks Detected",
"No projects or tasks were detected in your voice memo. Would you like to try again?",
"OK");
// Return to recording phase
await ReRecordAsync();
return;
}
Phase = VoicePhase.Reviewing;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Task extraction failed");
_errorHandler.HandleError(ex);
}
}
/// <summary>
/// Delete a project and its tasks from the list
/// </summary>
[RelayCommand]
private void DeleteProject(Project? project)
{
if (project != null)
{
Projects.Remove(project);
_logger.LogInformation("Deleted project: {ProjectName}", project.Name);
}
}
/// <summary>
/// Delete a task from its project
/// </summary>
[RelayCommand]
private void DeleteTask(ProjectTask? task)
{
if (task == null) return;
foreach (var project in Projects)
{
if (project.Tasks.Contains(task))
{
project.Tasks.Remove(task);
_logger.LogInformation("Deleted task: {TaskTitle} from project: {ProjectName}",
task.Title, project.Name);
break;
}
}
}
[RelayCommand]
private Task TaskCompleted(ProjectTask task)
{
return _taskRepository.SaveItemAsync(task);
}
/// <summary>
/// Accept a recommended task and add it to its project
/// </summary>
[RelayCommand]
private async Task AcceptRecommendation(ProjectTask task)
{
// Track recommendation acceptance (strong positive signal)
await _memoryStore.LogEventAsync(MemoryEvent.Create(
"recommendation:accept",
task.Title,
new { source = "voice" },
1.5)); // Higher weight - explicit user choice
// Mark the task as no longer a recommendation
task.IsRecommendation = false;
_logger.LogInformation("Accepted recommended task: {TaskTitle}", task.Title);
}
/// <summary>
/// Reject a recommended task
/// </summary>
[RelayCommand]
private async Task RejectRecommendation(ProjectTask task)
{
// Track recommendation rejection (strong negative signal)
await _memoryStore.LogEventAsync(MemoryEvent.Create(
"recommendation:reject",
task.Title,
new { source = "voice" },
1.5)); // Higher weight - explicit user choice
// Find and remove the task from its project
foreach (var project in Projects)
{
if (project.Tasks.Contains(task))
{
project.Tasks.Remove(task);
_logger.LogInformation("Rejected recommended task: {TaskTitle} from project: {ProjectName}",
task.Title, project.Name);
break;
}
}
}
/// <summary>
/// Start the recording process over
/// </summary>
[RelayCommand]
private async Task ReRecordAsync()
{
_logger.LogInformation("Re-starting recording process");
// Reset everything back to initial state
Phase = VoicePhase.Recording;
Transcript = string.Empty;
LiveTranscript = string.Empty; // Clear live transcript
Projects.Clear();
// Wait a moment to ensure UI updates
await Task.Delay(100);
}
/// <summary>
/// Save all projects and tasks
/// </summary>
[RelayCommand]
private async Task SaveAsync()
{
try
{
_logger.LogInformation("Starting save operation for voice memo");
_stopwatch.Restart();
IsBusy = true;
int projectCount = 0;
int taskCount = 0;
// Save each project and its tasks
foreach (var projectVm in Projects)
{
// Save the project to get its ID
await _projectRepository.SaveItemAsync(projectVm);
projectCount++;
// Save each task associated with this project
foreach (var taskVm in projectVm.Tasks)
{
taskVm.ProjectID = projectVm.ID; // Set the project ID for the task
await _taskRepository.SaveItemAsync(taskVm);
taskCount++;
}
}
_stopwatch.Stop();
_logger.LogInformation("Voice memo saved successfully: {ProjectCount} projects and {TaskCount} tasks in {SaveDuration}ms",
projectCount, taskCount, _stopwatch.ElapsedMilliseconds);
// Close the modal
await Shell.Current.GoToAsync("..");
// Notify the user that everything was saved
await Shell.Current.DisplayAlert("Success", "Your projects and tasks are save and secure.", "OK");
}
catch (Exception ex)
{
_logger.LogError(ex, "Error saving voice memo data");
_errorHandler.HandleError(ex);
}
finally
{
IsBusy = false;
}
}
[RelayCommand]
private async Task GoBackAsync()
{
_logger.LogInformation("Navigating back from voice modal");
await Shell.Current.GoToAsync("..");
}
/// <summary>
/// Handle assist action on a task using the TaskAssistHandler service
/// </summary>
[RelayCommand]
private async Task Assist(ProjectTask task)
{
if (task == null || task.AssistType == AssistType.None)
return;
try
{
IsBusy = true;
await _taskAssistHandler.HandleAssistAsync(task, false);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error performing assist action");
_errorHandler.HandleError(ex);
}
finally
{
IsBusy = false;
}
}
}