-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.js
More file actions
1776 lines (1679 loc) · 83.3 KB
/
Copy pathmain.js
File metadata and controls
1776 lines (1679 loc) · 83.3 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
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const { app, BrowserWindow, ipcMain, globalShortcut, screen, session, desktopCapturer, shell, systemPreferences, powerMonitor, dialog, safeStorage, clipboard, nativeImage } = require('electron');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const { pathToFileURL } = require('url');
const { migrateLegacyUserData } = require('./src/identity-migration');
const currentUserDataPath = app.getPath('userData');
const legacyUserDataPath = path.join(path.dirname(currentUserDataPath), 'volyx-lens-legacy');
const identityMigration = migrateLegacyUserData({ legacyUserData: legacyUserDataPath, currentUserData: currentUserDataPath });
if (identityMigration.migrated.length) console.log(`[identity] migrated ${identityMigration.migrated.length} legacy data file${identityMigration.migrated.length === 1 ? '' : 's'}`);
const store = require('./src/store');
const { captureScreenshot } = require('./src/screen');
const { createSTT } = require('./src/stt');
const { cancelOfflineTranscriptions } = require('./src/offline-stt');
const { MODES } = require('./src/prompts');
const { createResponseRoute, chooseInitialProvider, streamWithFallback } = require('./src/response-router');
const { rms16 } = require('./src/wav');
const { planScreenInput } = require('./src/capabilities');
const { mediaPermissionStatus, requestMediaPermission } = require('./src/permissions');
const { RealtimeTranscriptionManager } = require('./src/realtime-stt');
const { AUDIO_SAMPLE_RATE } = require('./src/audio-config');
const { resolveRealtimeTranscription } = require('./src/provider-config');
const { runRealtimeDiagnostic, LiveRealtimeDiagnostic } = require('./src/realtime-diagnostic');
const { runResponseDiagnostic } = require('./src/response-diagnostic');
const { createShortcutRegistry } = require('./src/shortcut-registry');
const { createPersonalContextStore, KINDS: PERSONAL_CONTEXT_KINDS } = require('./src/personal-context-store');
const { parseContextDocument, MAX_FILE_BYTES } = require('./src/document-context');
const { buildPersonalContext } = require('./src/personal-context');
const { normalizeSpokenDigits, formatTranscript, transcriptFilename } = require('./src/transcript-tools');
const { findCrossTalkDuplicate, findCrossTalkDuplicateAcrossCandidateWindow } = require('./src/transcript-dedupe');
const { joinTranscriptSegments, appendConversationSegment } = require('./src/transcript-grouping');
const { detectQuestion, estimateQuestionConfidence } = require('./src/question-detection');
const { createAutoAssistPolicy } = require('./src/auto-assist');
const { planMeetingRecap, transcriptText } = require('./src/meeting-recap');
const { meetingFilename, formatMeetingRecord } = require('./src/meeting-notes');
const { buildSttVocab } = require('./src/transcript-hygiene');
const { createTaskContext } = require('./src/task-context');
const { fingerprintDataUrl, isNearDuplicateFingerprint } = require('./src/image-fingerprint');
const { createLocalOcr } = require('./src/local-ocr');
const { createSystemAudioCapture } = require('./src/system-audio-capture');
const { createAcousticEchoFilter } = require('./src/acoustic-echo-filter');
const { createMicEchoCoordinator } = require('./src/mic-echo-coordinator');
const { detectTextOverlap, scoreTextRelevance } = require('./src/text-index');
const { sanitizeProviderError } = require('./src/provider-error');
const { createUpdateManager } = require('./src/update-manager');
const { DEFAULT_DOCK_SIZES, dockBounds, dockIntentPoint, dockSideForIntent, railCenter, sameBounds } = require('./src/window-docking');
const { createWindowAutoFitController } = require('./src/window-auto-fit');
const { createChatHistory } = require('./src/chat-history');
const { createMeetingStore } = require('./src/meeting-store');
const { createMeetingDetector } = require('./src/meeting-detect');
const { shouldAttachScreen, missingContextMessage, SOURCE_UNCERTAINTY_RULE } = require('./src/response-context');
const chatHistory = createChatHistory();
const meetingStore = createMeetingStore({ dir: path.join(currentUserDataPath, 'meetings') });
const meetingDetector = createMeetingDetector();
let meetingDetectedNotified = false;
const personalContextStore = createPersonalContextStore({ userDataPath: currentUserDataPath, safeStorage });
const AUTO_ANSWER_CONFIDENCE_MIN = 0.5;
const AUTO_ANSWER_COOLDOWN_MS = 60000;
const autoAnswerPolicy = createAutoAssistPolicy({ cooldownMs: AUTO_ANSWER_COOLDOWN_MS });
const taskContext = createTaskContext({
createFingerprint: (dataUrl) => fingerprintDataUrl(dataUrl, nativeImage),
isNearDuplicate: isNearDuplicateFingerprint,
detectOverlap: detectTextOverlap,
scoreRelevance: scoreTextRelevance,
});
const localOcr = createLocalOcr({ app });
const acousticEchoFilter = createAcousticEchoFilter({ sampleRate: AUDIO_SAMPLE_RATE });
const micEchoCoordinator = createMicEchoCoordinator({
filter: acousticEchoFilter,
maxBytes: AUDIO_SAMPLE_RATE * 2 * 4,
onMicrophone: (pcm) => processMicrophonePcm(pcm),
});
let lastSystemAudioLevelAt = 0;
function publishSystemAudioLevel(pcm, now = Date.now()) {
if (!Buffer.isBuffer(pcm) || pcm.length < 2 || now - lastSystemAudioLevelAt < 100) return;
lastSystemAudioLevelAt = now;
send('audio:level', { channel: 'them', level: Math.min(1, rms16(pcm) / 32768) });
}
const systemAudioCapture = createSystemAudioCapture({
app,
onPcm: (pcm) => { publishSystemAudioLevel(pcm); acceptPcm('them', pcm); },
onState: ({ state: sourceState, reason }) => {
if (sourceState !== 'ready') send('audio:level', { channel: 'them', level: 0 });
send('transcription:state', { status: 'source', channel: 'them', sourceState, ...(reason ? { reason } : {}) });
},
onUnexpectedExit: () => {
if (state.capturing || desiredCapturing) setCapturing(false, { immediate: true, reason: 'system-audio-disconnected' });
},
});
const MAX_SAVED_TASK_IMAGES_PER_REQUEST = 39;
const LARGE_TASK_CONTEXT_CONFIRM_THRESHOLD = 8;
const FEATURE_REQUEST_TIMEOUT_MS = 120000;
let taskContextCapturePromise = null;
let taskContextGeneration = 0;
let taskContextOcrGeneration = 0;
const pendingTaskContextOcr = new Set();
let win = null;
let windowDock = { side: 'top', collapsed: false, anchor: null };
let windowAutoFit = null;
const AUTO_FIT_DELAY_MS = 400;
// Fail closed until the trusted renderer finishes booting and reports whether
// onboarding or Settings is visible.
let uiModalOpen = true;
let rendererModalStateReported = false;
let modalRestoreCollapsed = null;
function activeDisplayId() {
if (win && !win.isDestroyed()) return screen.getDisplayMatching(win.getBounds()).id;
return screen.getDisplayNearestPoint(screen.getCursorScreenPoint()).id;
}
// -------- capture / transcript state --------
const state = { capturing: false, busy: false, transcribing: { you: false, them: false } };
let sttDisabled = false; // hard-stop latch; set only for auth/model errors (401/403/model_not_found)
let sttFailures = 0; // consecutive transient failures, drives exponential backoff
let sttBackoffUntil = 0; // epoch ms; batch flushing is skipped while now < this
const STT_RETRY_BASE_MS = 8000;
const STT_RETRY_MAX_MS = 120000;
const buffers = { you: [], them: [] };
const flushPromises = { you: null, them: null };
const transcript = []; // grouped conversation turns: { id, channel, text, ts, segments }
const recentTranscriptSegments = []; // bounded raw finals used only for cross-talk detection
const transcriptSegmentArrivalTimes = new Map();
const detectedQuestionsByTurn = new Map();
let transcriptSegmentSequence = 0;
let captureWarningTimer = null;
let captureLimitTimer = null;
let desiredCapturing = false;
let pendingDisplayCapture = false; // true only while the app's own getDisplayMedia flow is in flight
let captureTransition = Promise.resolve(false);
let pendingStopImmediate = false;
let pendingStopReason = null;
const FLUSH_MS = 3500;
const MIN_BYTES = Math.floor(AUDIO_SAMPLE_RATE * 2 * 0.6); // ~0.6s
const RMS_GATE = 240;
const MAX_BATCH_CHUNKS = 180; // roughly 30 seconds per speaker at 4096 samples/chunk
const MAX_TRANSCRIPT_TURNS = 500;
let flushTimer = null;
let realtimeManager = null;
const drainingRealtimeManagers = new Set();
let transcriptionMode = 'idle';
let sessionGeneration = 0;
let transcriptEpoch = 0;
let featureRunId = 0;
let activeFeatureRequest = null;
let responseDiagnosticPromise = null;
let realtimeDiagnosticPromise = null;
let liveRealtimeDiagnostic = null;
let liveRealtimeDiagnosticTimer = null;
let transcriptSequence = 0;
let finalizedSegmentWatermark = 0;
let captureStartedAt = null;
let lastCaptureStartedAt = null;
let lastCaptureEndedAt = null;
const transcriptionDiagnostics = {
connectedChannels: 0,
totalChannels: 0,
lastLatencyMs: null,
lastStatus: 'idle',
lastStatusAt: null,
crossTalkSuppressed: 0,
acousticEchoSuppressed: 0,
lastEchoCorrelation: 0,
maxEchoCorrelation: 0,
micDelayDropped: 0,
};
function send(channel, data) {
if (win && !win.isDestroyed() && win.webContents && !win.webContents.isDestroyed()) win.webContents.send(channel, data);
}
const updateManager = createUpdateManager({
app,
platform: process.platform,
arch: process.arch,
releaseBuild: require('./package.json').volyxReleaseBuild === true,
updaterFactory: () => require('electron-updater').autoUpdater,
emit: (value) => send('update:state', value),
});
function taskContextState(extra = {}) {
return { ...taskContext.summary(), ...extra };
}
function publishTaskContextState(extra = {}) {
const value = taskContextState(extra);
send('task-context:state', value);
return value;
}
async function processTaskContextOcr(captureId, dataUrl, generation) {
pendingTaskContextOcr.add(captureId);
try {
let result;
try { result = await localOcr.recognize(dataUrl, { jobId: captureId }); }
catch { result = { status: 'failed' }; }
if (generation !== taskContextOcrGeneration || !result || result.status === 'cancelled') return;
const status = ['ready', 'failed', 'unavailable'].includes(result.status) ? result.status : 'failed';
const updated = taskContext.setOcrResult(captureId, { status, text: result.text || '', truncated: result.truncated === true });
if (updated.ocrUpdated) publishTaskContextState(updated);
} finally {
pendingTaskContextOcr.delete(captureId);
}
}
async function captureTaskContextScreen() {
if (taskContextCapturePromise) return taskContextCapturePromise;
taskContextCapturePromise = (async () => {
const generation = taskContextGeneration;
const dataUrl = await captureScreenshot({ maxWidth: 1920, format: 'jpeg', quality: 80, displayId: activeDisplayId() });
if (generation !== taskContextGeneration) return taskContextState({ added: false, canceled: true });
if (!dataUrl) throw new Error('No screen image was available. Check macOS Screen Recording permission.');
const ocrAvailable = localOcr.availability().available;
const result = taskContext.add(dataUrl, { ocrStatus: ocrAvailable ? 'pending' : 'unavailable' });
for (const captureId of pendingTaskContextOcr) {
if (!taskContext.has(captureId)) localOcr.cancel(captureId);
}
const stateValue = publishTaskContextState(result);
if (result.added && ocrAvailable) void processTaskContextOcr(result.addedCapture.id, dataUrl, taskContextOcrGeneration);
const message = result.duplicate
? 'Task context already contains that exact screen.'
: result.nearDuplicate
? 'Task context already contains a visually similar screen, so the new capture was not saved. No AI request was made.'
: result.budgetBlocked
? 'Task context could not save that screen because pinned captures fill the available memory or capture-count budget. Unpin or remove a capture and try again. No AI request was made.'
: `Task context saved screen ${result.addedCapture.sequence} in memory.${result.evicted ? ` ${result.evicted} oldest unpinned screen${result.evicted === 1 ? '' : 's'} removed to stay within the memory budget.` : ''}${ocrAvailable ? ' Local text indexing queued.' : ' Local text indexing is unavailable on this build.'} No AI request was made.`;
send('status', { message });
return stateValue;
})();
try { return await taskContextCapturePromise; }
finally { taskContextCapturePromise = null; }
}
function undoTaskContext() {
taskContextGeneration += 1;
const result = taskContext.undo();
if (result.removedCapture) localOcr.cancel(result.removedCapture.id);
return publishTaskContextState(result);
}
function removeTaskContextCapture(id) {
const captureId = String(id || '');
if (!/^tc-\d+$/.test(captureId)) return publishTaskContextState({ removed: false, removedCapture: null });
localOcr.cancel(captureId);
return publishTaskContextState(taskContext.remove(captureId));
}
function pinTaskContextCapture(id, pinned) {
const captureId = String(id || '');
if (!/^tc-\d+$/.test(captureId)) return publishTaskContextState({ updated: false, updatedCapture: null });
return publishTaskContextState(taskContext.setPinned(captureId, pinned === true));
}
function clearTaskContext() {
taskContextGeneration += 1;
taskContextOcrGeneration += 1;
localOcr.cancelAll();
pendingTaskContextOcr.clear();
return publishTaskContextState(taskContext.clear());
}
function publicTranscriptTurn(turn) {
return { id: turn.id, channel: turn.channel, text: turn.text, ts: turn.ts };
}
function removeRecentTranscriptSegment(segmentId) {
const index = recentTranscriptSegments.findIndex((segment) => segment.id === segmentId);
if (index >= 0) recentTranscriptSegments.splice(index, 1);
transcriptSegmentArrivalTimes.delete(segmentId);
}
function removeTranscriptSegment(segment) {
const turnIndex = transcript.findIndex((turn) => turn.id === segment.turnId);
if (turnIndex < 0) return null;
const turn = transcript[turnIndex];
turn.segments = turn.segments.filter((entry) => entry.id !== segment.id);
if (!turn.segments.length) {
transcript.splice(turnIndex, 1);
send('transcript:remove', { id: turn.id, channel: turn.channel, reason: 'cross_talk' });
return null;
}
turn.text = joinTranscriptSegments(turn.segments);
turn.ts = turn.segments[0].ts;
send('transcript:update', publicTranscriptTurn(turn));
return turn.ts;
}
function rememberTranscriptSegment(segment, receivedAt) {
recentTranscriptSegments.push(segment);
transcriptSegmentArrivalTimes.set(segment.id, receivedAt);
while (recentTranscriptSegments.length > 40) {
const removed = recentTranscriptSegments.shift();
transcriptSegmentArrivalTimes.delete(removed.id);
}
}
function resetTranscriptData() {
transcript.length = 0;
recentTranscriptSegments.length = 0;
transcriptSegmentArrivalTimes.clear();
detectedQuestionsByTurn.clear();
autoAnswerPolicy.reset();
meetingDetector.reset();
meetingDetectedNotified = false;
transcriptSequence = 0;
transcriptSegmentSequence = 0;
finalizedSegmentWatermark = 0;
transcriptionDiagnostics.crossTalkSuppressed = 0;
}
function recordTranscript({ channel, text, ts = Date.now() }, generation = sessionGeneration, epoch = transcriptEpoch) {
if (generation !== sessionGeneration || epoch !== transcriptEpoch) return;
const clean = normalizeSpokenDigits(String(text || '').trim()).slice(0, 12000);
if (!clean) return;
const normalizedChannel = channel === 'you' ? 'you' : 'them';
const timestamp = Number.isFinite(ts) ? ts : Date.now();
const receivedAt = Date.now();
const candidate = { channel: normalizedChannel, text: clean, ts: timestamp };
const duplicate = findCrossTalkDuplicate(recentTranscriptSegments, candidate, transcriptSegmentArrivalTimes, receivedAt)
|| findCrossTalkDuplicateAcrossCandidateWindow(recentTranscriptSegments, candidate, transcriptSegmentArrivalTimes, receivedAt);
if (duplicate) {
transcriptionDiagnostics.crossTalkSuppressed += 1;
transcriptionDiagnostics.lastStatus = 'cross_talk_suppressed';
transcriptionDiagnostics.lastStatusAt = receivedAt;
if (normalizedChannel === 'you') {
send('transcript:suppressed', { channel: 'you', duplicateOf: duplicate.turn.turnId, reason: 'cross_talk' });
return;
}
for (const leakedSegment of duplicate.turns || [duplicate.turn]) {
removeRecentTranscriptSegment(leakedSegment.id);
const survivingTs = removeTranscriptSegment(leakedSegment);
if (store.getSettings().transcription && store.getSettings().transcription.meetingDetection === true) {
let state;
if (survivingTs === null) {
state = meetingDetector.remove(leakedSegment.turnId);
} else {
state = meetingDetector.update(leakedSegment.turnId, survivingTs);
}
if (!state.meeting && meetingDetectedNotified) {
meetingDetectedNotified = false;
send('meeting:cleared', {});
}
}
}
}
const segment = { id: ++transcriptSegmentSequence, channel: normalizedChannel, text: clean, ts: timestamp };
const { turn, updated } = appendConversationSegment(transcript, segment, () => ++transcriptSequence);
rememberTranscriptSegment(segment, receivedAt);
if (transcript.length > MAX_TRANSCRIPT_TURNS) {
const removed = transcript.splice(0, transcript.length - MAX_TRANSCRIPT_TURNS);
const removedTurnIds = new Set(removed.map((oldTurn) => oldTurn.id));
for (let index = recentTranscriptSegments.length - 1; index >= 0; index -= 1) {
if (!removedTurnIds.has(recentTranscriptSegments[index].turnId)) continue;
transcriptSegmentArrivalTimes.delete(recentTranscriptSegments[index].id);
recentTranscriptSegments.splice(index, 1);
}
}
send(updated ? 'transcript:update' : 'transcript', publicTranscriptTurn(turn));
if (normalizedChannel === 'you') {
send('question:clear', { reason: 'user_replied' });
} else if (store.getSettings().questionDetection !== false) {
const question = detectQuestion(turn.text);
if (question && detectedQuestionsByTurn.get(turn.id) !== question) {
detectedQuestionsByTurn.set(turn.id, question);
send('question:detected', { turnId: turn.id, text: question, ts: timestamp });
maybeAutoAnswer(question, timestamp);
}
}
if (store.getSettings().transcription && store.getSettings().transcription.meetingDetection === true && !updated) {
const state = meetingDetector.add({ id: turn.id, channel: normalizedChannel, text: turn.text, ts: timestamp });
if (state.meeting && !meetingDetectedNotified) {
meetingDetectedNotified = true;
send('meeting:detected', { since: state.detectedSince });
}
}
}
// Opt-in automatic assistance (Milestone 3). Manual "Draft answer" stays
// available regardless; this only fires when the user enabled Auto-assist,
// the question is confidently a question, no dialog is open, and the cooldown
// / dedupe policy permits it. Partials never reach this path — only finalized
// Them turns are recorded.
function maybeAutoAnswer(question, ts) {
const settings = store.getSettings();
if (settings.autoAnswer !== true || settings.questionDetection === false) return;
if (uiModalOpen) return;
const minConfidence = typeof settings.autoAnswerConfidence === 'number' && settings.autoAnswerConfidence >= 0 && settings.autoAnswerConfidence <= 1
? settings.autoAnswerConfidence : AUTO_ANSWER_CONFIDENCE_MIN;
if (estimateQuestionConfidence(question) < minConfidence) return;
const cooldownMs = Number(settings.autoAnswerCooldownSec) > 0 ? Number(settings.autoAnswerCooldownSec) * 1000 : AUTO_ANSWER_COOLDOWN_MS;
const decision = autoAnswerPolicy.evaluate({ question, now: ts, busy: state.busy, capturing: state.capturing, cooldownMs });
if (!decision.shouldAnswer) return;
autoAnswerPolicy.record(question, ts);
send('question:clear', { reason: 'auto_answer' });
send('status', { message: 'Auto-assist is drafting a reply to the detected question…' });
runFeature('auto-assist', question);
}
function updateTranscriptionDiagnostics(event = {}) {
const allowedStatuses = new Set(['idle', 'connecting', 'connected', 'channel', 'latency', 'activity', 'item_failed', 'active', 'fallback', 'failed', 'stopped']);
const status = allowedStatuses.has(event.status) ? event.status : 'update';
if (status === 'channel') {
transcriptionDiagnostics.connectedChannels = Math.max(0, Number(event.connectedChannels) || 0);
transcriptionDiagnostics.totalChannels = Math.max(0, Number(event.totalChannels) || 0);
}
if (status === 'latency') transcriptionDiagnostics.lastLatencyMs = Math.max(0, Number(event.latencyMs) || 0);
const channel = ['you', 'them'].includes(event.channel) ? `:${event.channel}` : '';
const activity = ['speech', 'processing'].includes(event.activity) ? `:${event.activity}` : '';
transcriptionDiagnostics.lastStatus = `${status}${channel}${activity}`;
transcriptionDiagnostics.lastStatusAt = Date.now();
}
function getSessionDiagnostics() {
const settings = store.getSettings();
const now = Date.now();
const startedAt = captureStartedAt || lastCaptureStartedAt;
const endedAt = state.capturing ? null : lastCaptureEndedAt;
const durationEnd = state.capturing ? now : (endedAt || now);
return {
version: 1,
generatedAt: new Date(now).toISOString(),
appVersion: app.getVersion(),
platform: process.platform,
session: {
active: state.capturing,
startedAt: startedAt ? new Date(startedAt).toISOString() : null,
endedAt: endedAt ? new Date(endedAt).toISOString() : null,
durationMs: startedAt ? Math.max(0, durationEnd - startedAt) : 0,
},
response: {
defaultProvider: settings.provider,
fallbackProvider: settings.fallbackProvider || null,
},
shortcuts: getShortcutStatus(),
transcription: {
mode: transcriptionMode,
provider: (settings.transcription || {}).realtimeProvider || null,
connectedChannels: transcriptionDiagnostics.connectedChannels,
totalChannels: transcriptionDiagnostics.totalChannels,
lastLatencyMs: transcriptionDiagnostics.lastLatencyMs,
lastStatus: transcriptionDiagnostics.lastStatus,
lastStatusAt: transcriptionDiagnostics.lastStatusAt ? new Date(transcriptionDiagnostics.lastStatusAt).toISOString() : null,
crossTalkSuppressed: transcriptionDiagnostics.crossTalkSuppressed,
acousticEchoSuppressed: transcriptionDiagnostics.acousticEchoSuppressed,
lastEchoCorrelation: Number(transcriptionDiagnostics.lastEchoCorrelation.toFixed(3)),
maxEchoCorrelation: Number(transcriptionDiagnostics.maxEchoCorrelation.toFixed(3)),
micDelayDropped: transcriptionDiagnostics.micDelayDropped,
},
audio: {
microphoneEnabled: (settings.audio || {}).micEnabled !== false,
systemEnabled: (settings.audio || {}).systemEnabled !== false,
browserMicProcessing: (settings.audio || {}).browserMicProcessing !== false,
},
transcript: {
turns: transcript.length,
characters: transcript.reduce((total, turn) => total + turn.text.length, 0),
lastAt: transcript.length ? new Date(transcript[transcript.length - 1].ts).toISOString() : null,
},
};
}
async function exportTranscript(format) {
const normalizedFormat = ['txt', 'md', 'json'].includes(format) ? format : 'txt';
if (!transcript.length) throw new Error('There is no transcript to export.');
const result = await dialog.showSaveDialog(win, {
title: 'Export Volyx Lens transcript',
defaultPath: transcriptFilename(normalizedFormat),
filters: [{ name: normalizedFormat.toUpperCase(), extensions: [normalizedFormat] }],
});
if (result.canceled || !result.filePath) return { canceled: true };
await writePrivateExport(result.filePath, formatTranscript(transcript, normalizedFormat));
return { canceled: false, filename: path.basename(result.filePath), turns: transcript.length };
}
async function exportMeetingRecord(id, format) {
const normalizedFormat = ['txt', 'md', 'json'].includes(format) ? format : 'md';
const record = meetingStore.get(String(id || ''));
if (!record) throw new Error('That meeting record is no longer available.');
const result = await dialog.showSaveDialog(win, {
title: 'Export meeting notes',
defaultPath: meetingFilename(normalizedFormat, record.endedAt || Date.now()),
filters: [{ name: normalizedFormat.toUpperCase(), extensions: [normalizedFormat] }],
});
if (result.canceled || !result.filePath) return { canceled: true };
await writePrivateExport(result.filePath, formatMeetingRecord(record, normalizedFormat));
return { canceled: false, filename: path.basename(result.filePath), turns: record.turns.length };
}
// Write a transcript export privately and atomically. The content is written
// to a 0600 temp file in the same directory as the destination and renamed
// into place, so the sensitive bytes never exist at permissive permissions
// even if the destination is replaced or a chmod-style second step fails.
async function writePrivateExport(filePath, content) {
const tmpPath = `${filePath}.${process.pid}.${crypto.randomBytes(6).toString('hex')}.tmp`;
try {
await fs.promises.writeFile(tmpPath, content, { encoding: 'utf8', mode: 0o600 });
await fs.promises.rename(tmpPath, filePath);
} catch (error) {
await fs.promises.unlink(tmpPath).catch(() => {});
throw error;
}
}
// -------- window --------
const WINDOW_TITLE = 'Utility';
const APP_ENTRY_PATH = path.join(__dirname, 'renderer', 'index.html');
const APP_ENTRY_URL = pathToFileURL(APP_ENTRY_PATH).href;
function isTrustedRenderer(webContents, frame = webContents && webContents.mainFrame) {
return Boolean(win && !win.isDestroyed() && webContents === win.webContents && frame === win.webContents.mainFrame && frame && frame.url === APP_ENTRY_URL);
}
function isTrustedFileOrigin(value, { optional = false } = {}) {
if (!value) return optional;
try { return new URL(value).protocol === 'file:'; }
catch { return value === 'file://' || value === 'file:///'; }
}
function publishDockState() {
if (!win || win.isDestroyed() || win.webContents.isDestroyed()) return;
win.webContents.send('window:dock-state', { side: windowDock.side, collapsed: windowDock.collapsed });
}
function applyDockBounds({ side = windowDock.side, collapsed = windowDock.collapsed, anchor = windowDock.anchor, targetDisplay = null } = {}) {
if (!win || win.isDestroyed()) return;
windowAutoFit?.cancel();
const currentBounds = win.getBounds();
const resolvedAnchor = anchor || railCenter(currentBounds, windowDock.side, DEFAULT_DOCK_SIZES);
const display = targetDisplay || screen.getDisplayNearestPoint(resolvedAnchor);
const nextBounds = dockBounds({ workArea: display.workArea, side, anchor: resolvedAnchor, collapsed });
windowDock = { side, collapsed, anchor: resolvedAnchor };
if (collapsed) win.setMinimumSize(1, 1);
if (!sameBounds(currentBounds, nextBounds)) win.setBounds(nextBounds, false);
if (!collapsed) win.setMinimumSize(500, 480);
publishDockState();
}
function fitWindowToMovedEdge(anchor) {
if (!win || win.isDestroyed()) return;
if (windowDock.collapsed || !anchor) return;
const display = screen.getDisplayNearestPoint(anchor);
const side = dockSideForIntent({ point: anchor, workArea: display.workArea });
applyDockBounds({ side, collapsed: false, anchor, targetDisplay: display });
}
function createWindow() {
const { workArea } = screen.getPrimaryDisplay();
const { width: W, height: H } = DEFAULT_DOCK_SIZES.expanded;
let rendererHasLoaded = false;
win = new BrowserWindow({
width: W,
height: H,
minWidth: 500,
minHeight: 480,
x: Math.round(workArea.x + (workArea.width - W) / 2),
y: workArea.y + 6,
title: WINDOW_TITLE,
frame: false,
transparent: true,
hasShadow: false,
resizable: true,
skipTaskbar: true,
alwaysOnTop: true,
fullscreenable: false,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false,
sandbox: true
}
});
// Best-effort overlay metadata and capture protection. This does not make the process undiscoverable.
win.setTitle(WINDOW_TITLE);
win.setContentProtection(!process.env.VOLYX_LENS_NO_PROTECT);
win.setAlwaysOnTop(true, 'screen-saver', 1);
win.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true });
if (typeof win.setHiddenInMissionControl === 'function') win.setHiddenInMissionControl(true);
windowAutoFit = createWindowAutoFitController({ fit: fitWindowToMovedEdge, delayMs: AUTO_FIT_DELAY_MS });
win.on('will-move', () => {
windowAutoFit?.beginManualMove();
});
win.on('moved', () => {
windowAutoFit?.recordMove(screen.getCursorScreenPoint());
});
win.on('close', () => {
windowAutoFit?.cancel();
});
win.on('closed', () => {
windowAutoFit?.cancel();
windowAutoFit = null;
});
win.loadURL(APP_ENTRY_URL);
win.webContents.setWindowOpenHandler(() => ({ action: 'deny' }));
win.webContents.on('will-navigate', (event, url) => { if (url !== APP_ENTRY_URL) event.preventDefault(); });
win.webContents.on('will-redirect', (event, url) => { if (url !== APP_ENTRY_URL) event.preventDefault(); });
win.webContents.on('will-attach-webview', (event) => event.preventDefault());
win.webContents.on('did-start-loading', () => {
uiModalOpen = true;
rendererModalStateReported = false;
});
win.webContents.on('did-finish-load', () => {
if (!rendererHasLoaded) {
const initialAnchor = windowDock.anchor || { x: workArea.x + workArea.width / 2, y: workArea.y };
applyDockBounds({ side: windowDock.side, collapsed: windowDock.collapsed, anchor: initialAnchor });
} else if (windowDock.collapsed) {
applyDockBounds(windowDock);
} else {
publishDockState();
}
rendererHasLoaded = true;
win.showInactive();
});
win.webContents.on('render-process-gone', (_e, d) => {
uiModalOpen = true;
rendererModalStateReported = false;
console.log('[volyx-lens] renderer gone', JSON.stringify(d));
if (state.capturing) setCapturing(false);
});
}
// -------- STT flushing --------
async function flushChannel(channel, { drain = false } = {}) {
if (flushPromises[channel]) return flushPromises[channel];
const task = (async () => {
const generation = sessionGeneration;
const epoch = transcriptEpoch;
if (sttDisabled) { buffers[channel] = []; return; }
// Transient backoff: postpone transcription and keep the buffered speech instead
// of discarding it. A final drain on stop still flushes best-effort so nothing
// captured up to that point is lost. Buffering stays bounded by MAX_BATCH_CHUNKS.
if (!drain && sttBackoffUntil && Date.now() < sttBackoffUntil) return;
const chunks = buffers[channel];
if (!chunks.length) return;
const pcm = Buffer.concat(chunks);
buffers[channel] = [];
if (pcm.length < MIN_BYTES) return;
if (rms16(pcm) < RMS_GATE) return; // silence gate
state.transcribing[channel] = true;
try {
const settings = store.getSettings();
// Seed batch/offline STT with domain terms from the user's enabled
// personal-context documents so model names and acronyms transcribe
// correctly (see src/transcript-hygiene.js).
const stt = createSTT(settings, {
vocab: buildSttVocab({
personalContext: personalContextStore.getEnabledDocuments().map((document) => document.text || '').join(' '),
}),
});
if (!stt.available) {
if (!sttDisabled) {
sttDisabled = true;
send('status', { message: stt.offlineError || 'Batch fallback is unavailable. If Azure Realtime failed, correct the Azure key, endpoint, or deployment and restart listening; otherwise add an OpenAI or Gemini key for batch fallback.' });
}
return;
}
const res = await stt.transcribe(pcm);
if (res.error) {
if (res.error.code === 'offline_cancelled') return;
handleSttError(res.error);
return;
}
if (sttFailures || sttBackoffUntil) { sttFailures = 0; sttBackoffUntil = 0; } // recovered
if (res.text && res.text.trim()) recordTranscript({ channel, text: res.text }, generation, epoch);
} catch (e) {
console.log('[stt] unexpected error', String(e && e.code || 'unknown').slice(0, 80));
} finally {
state.transcribing[channel] = false;
}
})();
flushPromises[channel] = task;
try { return await task; }
finally { if (flushPromises[channel] === task) flushPromises[channel] = null; }
}
async function drainBatchBuffers() {
await Promise.all(['you', 'them'].map(async (channel) => {
do { await flushChannel(channel, { drain: true }); } while (buffers[channel].length);
}));
}
function handleSttError(err) {
const provider = ['openai', 'gemini', 'offline'].includes(err && err.provider) ? err.provider : 'configured provider';
const status = Number(err && err.status) || 0;
const code = String((err && err.code) || '').slice(0, 80);
console.log('[stt] error', provider, status || 'no-status', code || 'unknown');
if (sttDisabled) return;
const permanent = status === 403 || status === 401 || code === 'model_not_found';
if (permanent) {
sttDisabled = true; // auth/model errors are not transient; stop hammering the API
send('status', { message: `Transcription off: your ${provider} credential cannot access the configured speech-to-text model. Screen features still work. Check Listening settings, then restart listening.` });
return;
}
// Transient 429/5xx/network errors: exponential backoff, keep the pipeline alive.
sttFailures += 1;
const backoffMs = Math.min(STT_RETRY_BASE_MS * Math.pow(2, sttFailures - 1), STT_RETRY_MAX_MS);
sttBackoffUntil = Date.now() + backoffMs;
send('status', { message: `Transcription hit a ${provider} error (${status || code || 'unknown'}); retrying in ${Math.round(backoffMs / 1000)}s.` });
}
function resetSttErrorState() {
sttDisabled = false;
sttFailures = 0;
sttBackoffUntil = 0;
}
function startFlushLoop() {
if (flushTimer) return;
flushTimer = setInterval(() => { flushChannel('you'); flushChannel('them'); }, FLUSH_MS);
}
function stopFlushLoop() { if (flushTimer) { clearInterval(flushTimer); flushTimer = null; } }
function resolveVadSettings(audio = {}) {
const thresholds = { quiet: 80, balanced: 160, noisy: 300 };
return {
threshold: thresholds[audio.sensitivity] || thresholds.balanced,
silenceMs: Math.max(300, Math.min(2000, Number(audio.silenceMs) || 700)),
maxUtteranceMs: 20000,
};
}
function activateBatchTranscription(reason) {
if (!state.capturing || transcriptionMode === 'batch') return;
const previous = realtimeManager;
realtimeManager = null;
if (previous) previous.stop();
transcriptionMode = 'batch';
startFlushLoop();
updateTranscriptionDiagnostics({ status: 'fallback' });
send('transcription:state', { mode: 'batch', status: 'active' });
if (reason) send('status', { message: `Realtime transcription unavailable (${reason}). Using batch transcription for this listening session.` });
}
function startTranscriptionPipeline() {
stopFlushLoop();
const previous = realtimeManager;
realtimeManager = null;
if (previous) previous.stop();
buffers.you = []; buffers.them = [];
const settings = store.getSettings();
const transcription = settings.transcription || {};
const audio = settings.audio || {};
const realtime = resolveRealtimeTranscription(settings);
const enabledChannels = [audio.micEnabled !== false ? 'you' : null, audio.systemEnabled !== false ? 'them' : null].filter(Boolean);
const generation = sessionGeneration;
const epoch = transcriptEpoch;
if (transcription.mode === 'realtime' && realtime.ready) {
transcriptionMode = 'realtime';
let manager;
manager = new RealtimeTranscriptionManager({
apiKey: realtime.apiKey,
provider: realtime.provider,
endpoint: realtime.endpoint,
region: realtime.region,
phrases: realtime.phrases,
model: realtime.model,
language: transcription.language || '',
delay: transcription.delay || 'low',
sampleRate: AUDIO_SAMPLE_RATE,
enabledChannels,
vad: resolveVadSettings(audio),
preRollMs: Math.max(0, Math.min(1000, Number(audio.preRollMs) || 250)),
onPartial: (event) => { if (generation === sessionGeneration && epoch === transcriptEpoch && realtimeManager === manager) send('transcript:partial', event); },
onFinal: (event) => {
if (generation === sessionGeneration && epoch === transcriptEpoch && (realtimeManager === manager || drainingRealtimeManagers.has(manager))) recordTranscript(event, generation, epoch);
},
onState: (event) => {
if (generation !== sessionGeneration || realtimeManager !== manager) return;
updateTranscriptionDiagnostics(event);
send('transcription:state', event);
},
onLatency: (event) => {
if (generation !== sessionGeneration || realtimeManager !== manager) return;
const stateEvent = { mode: 'realtime', status: 'latency', ...event };
updateTranscriptionDiagnostics(stateEvent);
send('transcription:state', stateEvent);
},
onError: (error) => {
if (realtimeManager !== manager) return;
console.log('[stt:realtime] error', String(error && error.code || 'unknown').slice(0, 80));
activateBatchTranscription('the Realtime connection failed');
}
});
realtimeManager = manager;
manager.start().catch(() => {
if (realtimeManager === manager) activateBatchTranscription('the Realtime connection could not start');
});
return;
}
if (transcription.mode === 'realtime' && !realtime.ready) {
send('status', { message: `Realtime transcription is not configured: ${realtime.configurationError} Using batch fallback.` });
}
transcriptionMode = 'batch';
startFlushLoop();
updateTranscriptionDiagnostics({ status: 'fallback' });
send('transcription:state', { mode: 'batch', status: 'active' });
}
async function stopTranscriptionPipeline({ immediate = false } = {}) {
stopFlushLoop();
if (immediate) cancelOfflineTranscriptions();
const previousMode = transcriptionMode;
const manager = realtimeManager;
realtimeManager = null;
if (immediate) {
micEchoCoordinator.clear();
acousticEchoFilter.reset();
if (manager) manager.stop();
for (const draining of drainingRealtimeManagers) draining.stop();
drainingRealtimeManagers.clear();
buffers.you = []; buffers.them = [];
transcriptionMode = 'idle';
updateTranscriptionDiagnostics({ status: 'stopped' });
send('transcription:state', { mode: 'idle', status: 'stopped' });
return;
}
if (manager) {
drainingRealtimeManagers.add(manager);
await manager.stop({ graceMs: 750 });
drainingRealtimeManagers.delete(manager);
}
if (previousMode === 'batch' || flushPromises.you || flushPromises.them || buffers.you.length || buffers.them.length) {
await drainBatchBuffers();
}
buffers.you = []; buffers.them = [];
transcriptionMode = 'idle';
updateTranscriptionDiagnostics({ status: 'stopped' });
send('transcription:state', { mode: 'idle', status: 'stopped' });
}
function routePcm(channel, pcm) {
if (transcriptionMode === 'realtime' && realtimeManager && realtimeManager.append(channel, pcm)) return;
buffers[channel].push(pcm);
if (buffers[channel].length > MAX_BATCH_CHUNKS) buffers[channel].splice(0, buffers[channel].length - MAX_BATCH_CHUNKS);
}
function processMicrophonePcm(pcm) {
const audio = store.getSettings().audio || {};
if (audio.micEnabled !== false && audio.systemEnabled !== false) {
const echo = acousticEchoFilter.inspectMicrophone(pcm);
transcriptionDiagnostics.lastEchoCorrelation = echo.correlation;
transcriptionDiagnostics.maxEchoCorrelation = Math.max(transcriptionDiagnostics.maxEchoCorrelation, echo.correlation);
if (echo.suppress) {
transcriptionDiagnostics.acousticEchoSuppressed += 1;
return;
}
}
routePcm('you', pcm);
}
function acceptPcm(channel, arrayBuffer) {
if (!state.capturing || !['you', 'them'].includes(channel)) return;
let pcm;
try { pcm = Buffer.from(arrayBuffer); } catch { return; }
if (!pcm.length || pcm.length > AUDIO_SAMPLE_RATE * 2 * 2) return;
if (channel === 'them') {
micEchoCoordinator.observeSystem(pcm);
routePcm('them', pcm);
return;
}
const audio = store.getSettings().audio || {};
if (audio.micEnabled !== false && audio.systemEnabled !== false) {
if (!micEchoCoordinator.enqueueMicrophone(pcm)) transcriptionDiagnostics.micDelayDropped += 1;
return;
}
processMicrophonePcm(pcm);
}
// -------- capture toggle --------
function clearCaptureTimers() {
if (captureWarningTimer) clearTimeout(captureWarningTimer);
if (captureLimitTimer) clearTimeout(captureLimitTimer);
captureWarningTimer = null;
captureLimitTimer = null;
}
function scheduleCaptureTimers() {
clearCaptureTimers();
const audio = store.getSettings().audio || {};
const warningMinutes = Math.max(5, Math.min(240, Number(audio.costWarningMinutes) || 30));
const limitMinutes = Math.max(10, Math.min(480, Number(audio.maxSessionMinutes) || 60));
captureWarningTimer = setTimeout(() => {
if (!state.capturing) return;
const channelCount = Number(audio.micEnabled !== false) + Number(audio.systemEnabled !== false);
send('status', { message: `Listening has been active for ${warningMinutes} minutes. ${channelCount} Realtime ${channelCount === 1 ? 'session may' : 'sessions may'} be billable.` });
}, warningMinutes * 60 * 1000);
captureLimitTimer = setTimeout(() => {
if (!state.capturing) return;
send('status', { message: 'Listening stopped at the configured session limit.' });
setCapturing(false);
}, limitMinutes * 60 * 1000);
}
// -------- Meeting history --------
function pendingFinalizeTurns() {
const turns = [];
for (const turn of transcript) {
const fresh = (turn.segments || []).filter((segment) => Number.isFinite(segment.id) && segment.id > finalizedSegmentWatermark);
if (!fresh.length) continue;
const text = joinTranscriptSegments(fresh);
if (!String(text || '').trim()) continue;
turns.push({ id: turn.id, channel: turn.channel, text, ts: fresh[0].ts });
}
return turns;
}
function advanceFinalizeWatermark() {
let max = finalizedSegmentWatermark;
for (const turn of transcript) {
for (const segment of turn.segments || []) {
if (Number.isFinite(segment.id) && segment.id > max) max = segment.id;
}
}
finalizedSegmentWatermark = max;
}
function finalizeMeeting(reason = 'capture-stop', opts = {}) {
const settings = store.getSettings();
const historyEnabled = Boolean(settings.transcription && settings.transcription.historyEnabled);
if (!historyEnabled) return { saved: false, reason: 'disabled' };
// Retain session timestamps when the caller does not pass them explicitly:
// new-session and app-quit finalize without opts, and shutdown clears
// captureStartedAt before the quit finalize runs, so fall back to the last
// known capture start/end.
const startedAt = opts.startedAt || captureStartedAt || lastCaptureStartedAt;
const endedAt = opts.endedAt || lastCaptureEndedAt;
const result = meetingStore.finalize({
turns: pendingFinalizeTurns(),
enabled: true,
reason,
meeting: meetingDetector.snapshot().meeting,
startedAt,
endedAt,
});
advanceFinalizeWatermark();
if (result.saved) send('history:changed', { saved: true, id: result.id, turnCount: result.turnCount });
return result;
}
async function applyCaptureState(active) {
if (active === state.capturing) return state.capturing;
if (active) {
const audio = store.getSettings().audio || {};
micEchoCoordinator.clear();
acousticEchoFilter.reset();
transcriptionDiagnostics.acousticEchoSuppressed = 0;
transcriptionDiagnostics.lastEchoCorrelation = 0;
transcriptionDiagnostics.maxEchoCorrelation = 0;
transcriptionDiagnostics.micDelayDropped = 0;
if (process.platform === 'darwin' && audio.systemEnabled !== false) {
const source = await systemAudioCapture.start();
if (!source.ok) {
desiredCapturing = false;
send('status', { message: `Listening did not start because macOS system audio is unavailable (${source.reason}).` });
return false;
}
}
state.capturing = true;
captureStartedAt = Date.now();
lastCaptureStartedAt = captureStartedAt;
lastCaptureEndedAt = null;
transcriptionDiagnostics.connectedChannels = 0;
transcriptionDiagnostics.totalChannels = 0;
transcriptionDiagnostics.lastLatencyMs = null;
transcriptionDiagnostics.lastStatus = 'connecting';
transcriptionDiagnostics.lastStatusAt = Date.now();
transcriptionDiagnostics.crossTalkSuppressed = 0;
scheduleCaptureTimers();
startTranscriptionPipeline();
send('capture:state', { active: true });
return true;
}
await systemAudioCapture.stop({ immediate: pendingStopImmediate });
if (pendingStopImmediate) micEchoCoordinator.clear();
else micEchoCoordinator.drain();
acousticEchoFilter.reset();
state.capturing = false;
lastCaptureEndedAt = Date.now();
const captureStartedAtEnd = captureStartedAt;
captureStartedAt = null;
clearCaptureTimers();
const immediate = pendingStopImmediate;
const reason = pendingStopReason;
pendingStopImmediate = false;
pendingStopReason = null;
send('capture:state', { active: false, ...(reason ? { reason } : {}) });
await stopTranscriptionPipeline({ immediate });
if (reason !== 'suspend' && reason !== 'lock') {
finalizeMeeting(reason || 'capture-stop', { startedAt: captureStartedAtEnd, endedAt: lastCaptureEndedAt });