forked from shubhamshnd/Open-Cluely
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathrepomix-output.txt
More file actions
14981 lines (12638 loc) · 452 KB
/
Copy pathrepomix-output.txt
File metadata and controls
14981 lines (12638 loc) · 452 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
This file is a merged representation of the entire codebase, combined into a single document by Repomix.
================================================================
File Summary
================================================================
Purpose:
--------
This file contains a packed representation of the entire repository's contents.
It is designed to be easily consumable by AI systems for analysis, code review,
or other automated processes.
File Format:
------------
The content is organized as follows:
1. This summary section
2. Repository information
3. Directory structure
4. Repository files (if enabled)
5. Multiple file entries, each consisting of:
a. A separator line (================)
b. The file path (File: path/to/file)
c. Another separator line
d. The full contents of the file
e. A blank line
Usage Guidelines:
-----------------
- This file should be treated as read-only. Any changes should be made to the
original repository files, not this packed version.
- When processing this file, use the file path to distinguish
between different files in the repository.
- Be aware that this file may contain sensitive information. Handle it with
the same level of security as you would the original repository.
Notes:
------
- Some files may have been excluded based on .gitignore rules and Repomix's configuration
- Binary files are not included in this packed representation. Please refer to the Repository Structure section for a complete list of file paths, including binary files
- Files matching patterns in .gitignore are excluded
- Files matching default ignore patterns are excluded
- Files are sorted by Git change count (files with more changes are at the bottom)
================================================================
Directory Structure
================================================================
.env.example
.gitignore
assets/chrome.ico
assets/README.md
BUILD_INSTRUCTIONS.md
notes.md
package.json
README.md
scripts/fetch-gemini-models.js
SETUP-VOSK.md
src/bootstrap/environment.js
src/config.js
src/main-process/features/assistant/gemini-runtime.js
src/main-process/features/assistant/ipc.js
src/main-process/features/assistant/screenshot-manager.js
src/main-process/features/settings/ipc.js
src/main-process/features/window/window-constants.js
src/main-process/features/window/window-controller.js
src/main-process/shared/safe-send.js
src/main-process/start-application.js
src/main-process/startup-logging.js
src/main.js
src/services/ai/gemini-service.js
src/services/ai/prompts.js
src/services/assembly-ai/ipc.js
src/services/assembly-ai/service.js
src/services/assembly-ai/stt-history.js
src/services/state/app-state.js
src/windows/assistant/pcm-capture-worklet.js
src/windows/assistant/preload.js
src/windows/assistant/preload/actions.js
src/windows/assistant/preload/create-electron-api.js
src/windows/assistant/preload/helpers.js
src/windows/assistant/preload/listeners.js
src/windows/assistant/renderer-globals.d.ts
src/windows/assistant/renderer.html
src/windows/assistant/renderer.js
src/windows/assistant/renderer/features/ai-context/context-bundle.js
src/windows/assistant/renderer/features/ai-context/message-store.js
src/windows/assistant/renderer/features/ai-context/message-types.js
src/windows/assistant/renderer/features/ai-context/toggle-ui.js
src/windows/assistant/renderer/features/assembly-ai/audio-pipeline.js
src/windows/assistant/renderer/features/assembly-ai/source-state.js
src/windows/assistant/renderer/features/assembly-ai/transcript-buffer.js
src/windows/assistant/renderer/features/chat/chat-ui-manager.js
src/windows/assistant/renderer/features/layout/window-adjustments.js
src/windows/assistant/renderer/features/listeners/event-listeners.js
src/windows/assistant/renderer/features/listeners/ipc-listeners.js
src/windows/assistant/renderer/features/settings/settings-panel-manager.js
src/windows/assistant/renderer/features/settings/shortcut-manager.js
src/windows/assistant/renderer/features/transcription/transcription-manager.js
src/windows/assistant/styles.css
src/windows/assistant/window.js
src/windows/legacy/renderer-webspeech-broken.js
src/windows/legacy/renderer-whisper-backup.js
src/windows/legacy/whisper-worker.js
================================================================
Files
================================================================
================
File: assets/README.md
================
# Assets Folder - Chrome Icons Required
This folder should contain Chrome icon files for building the disguised executable.
## Required Files:
1. **chrome.ico** (Windows) - 256x256 or higher
2. **chrome.icns** (macOS) - For Mac builds
3. **chrome.png** (Linux) - 512x512 for Linux builds
## How to Get Chrome Icons:
### Method 1: Extract from Chrome Installation
**Windows:**
1. Navigate to: `C:\Program Files\Google\Chrome\Application\`
2. Find `chrome.exe`
3. Right-click → Properties → Icons tab
4. Use a tool like [ResourceHacker](http://www.angusj.com/resourcehacker/) to extract
5. Save as `chrome.ico` in this folder
### Method 2: Download from Icon Sites
**Recommended Sites:**
- https://icon-icons.com/icon/chrome/194617
- https://www.iconfinder.com/icons/386254/chrome_icon
- https://icons8.com/icons/set/chrome
**Download Requirements:**
- **Windows**: ICO format, 256x256 pixels minimum
- **macOS**: ICNS format (if building for Mac)
- **Linux**: PNG format, 512x512 pixels
### Method 3: Use Online Converter
If you have a Chrome PNG:
1. Go to: https://convertio.co/png-ico/
2. Upload Chrome PNG (high resolution)
3. Convert to ICO (256x256)
4. Download and save as `chrome.ico`
## File Placement:
After obtaining the icons, your folder should look like:
```
d:\Open-Cluely\assets\
├── chrome.ico ← Windows icon (REQUIRED for building)
├── chrome.icns ← macOS icon (optional)
├── chrome.png ← Linux icon (optional)
└── README.md ← This file
```
## Verification:
Before building, verify:
- [ ] `chrome.ico` exists in this folder
- [ ] Icon is 256x256 or higher resolution
- [ ] Icon looks like the official Chrome logo
## Quick Build Test:
After adding icons, test the build:
```bash
npm run build
```
If successful, you should see:
- `dist/GoogleChrome.exe` with Chrome icon
- Icon visible in File Explorer
- Icon shows in Task Manager
## Troubleshooting:
**Icon doesn't show:**
- Make sure filename is exactly `chrome.ico`
- Check file is in ICO format (not renamed PNG)
- Resolution must be 256x256 or higher
- Try rebuilding with `--clean` flag
**Can't find Chrome icon:**
- Check `C:\Program Files\Google\Chrome\Application\chrome.exe`
- Use ResourceHacker to extract icon from chrome.exe
- Or download from icon sites listed above
---
**Note:** This is for educational purposes and authorized use only.
================
File: scripts/fetch-gemini-models.js
================
// ============================================================================
// SCRIPT: fetch-gemini-models.js
// ============================================================================
// Fetches all supported Google Gemini models from the API and shows which
// ones support generateContent (usable for chat/AI).
//
// Usage:
// node scripts/fetch-gemini-models.js
//
// Reads GEMINI_API_KEY from .env (same as the app). Supports comma-separated
// keys — uses the first valid one found.
// ============================================================================
const https = require('https');
const path = require('path');
// Load .env from project root (same as app infrastructure)
require('dotenv').config({ path: path.join(__dirname, '..', '.env') });
const { getGeminiModels } = require('../src/config');
// ============================================================================
// API key resolution (mirrors the app's multi-key support)
// ============================================================================
function resolveApiKey() {
const raw = String(process.env.GEMINI_API_KEY || '').trim();
if (!raw) {
return null;
}
// Support comma-separated keys — use the first non-empty one
const keys = raw.split(',').map((k) => k.trim()).filter(Boolean);
return keys[0] || null;
}
// ============================================================================
// HTTP helpers
// ============================================================================
function httpsGet(url) {
return new Promise((resolve, reject) => {
https.get(url, (res) => {
const chunks = [];
res.on('data', (chunk) => chunks.push(chunk));
res.on('end', () => {
const body = Buffer.concat(chunks).toString();
if (res.statusCode >= 400) {
let parsed;
try { parsed = JSON.parse(body); } catch { parsed = { message: body }; }
const msg = parsed?.error?.message || parsed?.message || body;
reject(new Error(`HTTP ${res.statusCode}: ${msg}`));
} else {
try {
resolve(JSON.parse(body));
} catch {
reject(new Error('Failed to parse response as JSON'));
}
}
});
res.on('error', reject);
}).on('error', reject);
});
}
// ============================================================================
// Fetch models from both v1 and v1beta endpoints
// ============================================================================
async function fetchModels(apiKey, apiVersion) {
const url = `https://generativelanguage.googleapis.com/${apiVersion}/models?key=${apiKey}`;
try {
const data = await httpsGet(url);
return (data.models || []);
} catch (error) {
console.warn(` [${apiVersion}] ${error.message}`);
return [];
}
}
// ============================================================================
// Display helpers
// ============================================================================
function formatModel(model, configuredModels) {
const name = model.name || ''; // e.g. "models/gemini-1.5-flash"
const displayName = model.displayName || name;
const shortName = name.replace(/^models\//, '');
const methods = (model.supportedGenerationMethods || []);
const supportsGenerate = methods.includes('generateContent');
const isConfigured = configuredModels.includes(shortName);
const tags = [];
if (supportsGenerate) tags.push('generateContent');
if (isConfigured) tags.push('IN CONFIG');
return { shortName, displayName, supportsGenerate, isConfigured, tags, methods };
}
// ============================================================================
// Main
// ============================================================================
async function main() {
console.log('=== Gemini Model Fetcher ===\n');
const apiKey = resolveApiKey();
if (!apiKey) {
console.error('ERROR: GEMINI_API_KEY not set in .env');
console.error(' Add your key to .env: GEMINI_API_KEY=your_key_here');
process.exit(1);
}
console.log(`API key loaded from .env (${apiKey.slice(0, 8)}...)\n`);
const configuredModels = getGeminiModels();
console.log('Models currently in src/config.js:');
configuredModels.forEach((m) => console.log(` - ${m}`));
console.log();
// Fetch from both API versions to get the widest coverage
console.log('Fetching models from Google Generative AI API...');
const [v1Models, v1betaModels] = await Promise.all([
fetchModels(apiKey, 'v1'),
fetchModels(apiKey, 'v1beta')
]);
// Deduplicate by model name
const seen = new Set();
const allModels = [...v1Models, ...v1betaModels].filter((m) => {
if (seen.has(m.name)) return false;
seen.add(m.name);
return true;
});
if (allModels.length === 0) {
console.error('No models returned. Check your API key and internet connection.');
process.exit(1);
}
const formatted = allModels.map((m) => formatModel(m, configuredModels));
// Split into generateContent-capable vs others
const generateModels = formatted.filter((m) => m.supportsGenerate);
const otherModels = formatted.filter((m) => !m.supportsGenerate);
// ---- generateContent-capable models ----
console.log(`\n${'─'.repeat(60)}`);
console.log(`Models supporting generateContent (${generateModels.length} found):`);
console.log('─'.repeat(60));
for (const m of generateModels) {
const configured = m.isConfigured ? ' ✓ IN CONFIG' : '';
console.log(` ${m.shortName}${configured}`);
if (m.displayName && m.displayName !== m.shortName) {
console.log(` Display name: ${m.displayName}`);
}
}
// ---- other models ----
if (otherModels.length > 0) {
console.log(`\n${'─'.repeat(60)}`);
console.log(`Other models (no generateContent support, ${otherModels.length} found):`);
console.log('─'.repeat(60));
for (const m of otherModels) {
const methods = m.methods.join(', ') || 'none';
console.log(` ${m.shortName} [${methods}]`);
}
}
// ---- config validation ----
console.log(`\n${'─'.repeat(60)}`);
console.log('Config validation:');
console.log('─'.repeat(60));
const generateModelNames = generateModels.map((m) => m.shortName);
for (const name of configuredModels) {
const valid = generateModelNames.includes(name);
const status = valid ? ' OK' : ' NOT FOUND / UNSUPPORTED';
console.log(` ${name}${status}`);
}
console.log(`\nTotal models: ${allModels.length} (${generateModels.length} support generateContent)\n`);
}
main().catch((err) => {
console.error('Fatal error:', err.message);
process.exit(1);
});
================
File: SETUP-VOSK.md
================
# Vosk Setup Guide
This guide provides detailed instructions for setting up Vosk speech recognition in Open-Cluely.
## Prerequisites
- Python 3.8 or newer
- pip (Python package installer)
- A working microphone
- At least 2GB of free disk space (for the model)
## Installation Steps
### 1. Install Python Dependencies
```bash
# Install Vosk
pip install vosk
# Install sounddevice for audio capture
pip install sounddevice
# Install requests (used for model download)
pip install requests
```
### 2. Model Download
When you first run Open-Cluely, it will automatically download the Vosk model (approximately 1.8GB). However, if you want to download it manually:
1. Create a models directory in your application folder
2. Download the model from [Vosk's model repository](https://alphacephei.com/vosk/models)
3. Extract the model files into the models directory
The default model used is `vosk-model-small-en-us-0.15`, which provides a good balance between accuracy and performance.
## Troubleshooting
### Common Issues
#### 1. No Microphone Access
**Symptoms:**
- No transcription appears
- Error messages about audio device
**Solutions:**
- Check if your microphone is properly connected
- Verify microphone permissions in your OS settings
- Try selecting a different audio input device
#### 2. Model Download Fails
**Symptoms:**
- Error during first launch
- Missing model files
**Solutions:**
- Check your internet connection
- Manually download the model (see Manual Model Installation below)
- Verify you have enough disk space
#### 3. Performance Issues
**Symptoms:**
- Delayed transcription
- High CPU usage
**Solutions:**
- Close other CPU-intensive applications
- Consider using a smaller model
- Ensure your Python installation matches your system architecture (32/64 bit)
### Manual Model Installation
If the automatic model download fails, you can install it manually:
1. Create a directory: `models`
2. Download the model from: https://alphacephei.com/vosk/models
3. Select `vosk-model-small-en-us-0.15` (recommended)
4. Extract the downloaded archive into the models directory
5. Verify the path structure matches: `models/vosk-model-small-en-us-0.15/`
## Advanced Configuration
### Selecting Different Models
Vosk offers various models with different sizes and languages. You can change the model by:
1. Downloading a different model from [Vosk Models](https://alphacephei.com/vosk/models)
2. Extracting it to the models directory
3. Updating the model path in the application settings
Available model types:
- Small models (~50MB) - Fast but less accurate
- Medium models (~1.8GB) - Good balance (recommended)
- Large models (~4GB) - Most accurate but slower
### Audio Device Selection
By default, the system's default microphone is used. To use a different audio device:
1. List available devices:
```python
import sounddevice as sd
print(sd.query_devices())
```
2. Note the device index you want to use
3. Update the device settings in your configuration
## System-Specific Notes
### Windows
- Ensure Microsoft Visual C++ Redistributable is installed
- Use Python 3.8+ 64-bit version
- Check Windows Security for microphone permissions
### macOS
- Grant microphone permissions in System Preferences
- Install Python through Homebrew for best compatibility
### Linux
- Install PortAudio development package:
```bash
# Ubuntu/Debian
sudo apt-get install portaudio19-dev
# Fedora
sudo dnf install portaudio-devel
```
- Ensure your user has audio device permissions
## Additional Resources
- [Vosk API Documentation](https://alphacephei.com/vosk/api)
- [Vosk Models Repository](https://alphacephei.com/vosk/models)
- [sounddevice Documentation](https://python-sounddevice.readthedocs.io/)
## Support
If you encounter any issues not covered in this guide:
1. Check the [GitHub Issues](https://github.com/yourusername/open-cluely/issues)
2. Create a new issue with:
- Your system information
- Error messages
- Steps to reproduce the problem
================
File: src/main-process/shared/safe-send.js
================
function createSafeSender(getMainWindow) {
return function sendToRenderer(channel, data) {
const mainWindow = typeof getMainWindow === 'function' ? getMainWindow() : null;
if (!mainWindow || mainWindow.isDestroyed()) return false;
const contents = mainWindow.webContents;
if (!contents || contents.isDestroyed()) return false;
if (typeof contents.isCrashed === 'function' && contents.isCrashed()) {
return false;
}
const frame = contents.mainFrame;
if (frame && typeof frame.isDestroyed === 'function' && frame.isDestroyed()) {
return false;
}
try {
contents.send(channel, data);
return true;
} catch (error) {
console.error(`Failed to send renderer event "${channel}":`, error.message);
return false;
}
};
}
module.exports = {
createSafeSender
};
================
File: src/services/assembly-ai/ipc.js
================
function registerAssemblyAiIpc({ ipcMain, assemblyAiService }) {
ipcMain.handle('start-voice-recognition', (_event, { source } = {}) => {
const resolvedSource = source === 'system' ? 'system' : 'mic';
console.log(`IPC: start-voice-recognition [${resolvedSource}]`);
assemblyAiService.emitSttDebug({
source: resolvedSource,
event: 'ipc-start',
message: 'Renderer requested source start'
});
return assemblyAiService.startAssemblyAiStream(resolvedSource);
});
ipcMain.on('audio-chunk', (_event, payload = {}) => {
assemblyAiService.handleAudioChunk(payload);
});
ipcMain.handle('stop-voice-recognition', (_event, { source } = {}) => {
console.log(`IPC: stop-voice-recognition [${source}]`);
return assemblyAiService.stopVoiceRecognition({ source });
});
ipcMain.handle('get-desktop-sources', async () => {
return assemblyAiService.getDesktopSources();
});
ipcMain.handle('transcribe-audio', async (_event, base64Audio) => {
console.log('IPC: transcribe-audio called, size:', base64Audio?.length || 0);
return assemblyAiService.transcribeAudio(base64Audio);
});
}
module.exports = {
registerAssemblyAiIpc
};
================
File: src/services/assembly-ai/stt-history.js
================
function normalizeSttSource(source) {
return source === 'system' ? 'system' : 'mic';
}
function normalizeTranscriptForMerge(text) {
return String(text || '')
.toLowerCase()
.replace(/[^a-z0-9\s]/g, ' ')
.replace(/\s+/g, ' ')
.trim();
}
function mergeTranscriptText(existingText, incomingText) {
const current = String(existingText || '').trim();
const incoming = String(incomingText || '').trim();
if (!current) return incoming;
if (!incoming) return current;
const currentNorm = normalizeTranscriptForMerge(current);
const incomingNorm = normalizeTranscriptForMerge(incoming);
if (!incomingNorm) return current;
if (!currentNorm) return incoming;
if (currentNorm === incomingNorm) {
return incoming.length >= current.length ? incoming : current;
}
if (incomingNorm.includes(currentNorm)) {
return incoming;
}
if (currentNorm.includes(incomingNorm)) {
return current;
}
const currentWords = current.split(/\s+/);
const incomingWords = incoming.split(/\s+/);
const maxOverlap = Math.min(12, currentWords.length, incomingWords.length);
let overlap = 0;
for (let size = maxOverlap; size > 0; size -= 1) {
const currentTail = currentWords.slice(-size).join(' ').toLowerCase();
const incomingHead = incomingWords.slice(0, size).join(' ').toLowerCase();
if (currentTail === incomingHead) {
overlap = size;
break;
}
}
if (overlap > 0) {
const remainder = incomingWords.slice(overlap).join(' ');
if (!remainder) return current;
return `${current} ${remainder}`.replace(/\s+/g, ' ').trim();
}
return `${current} ${incoming}`.replace(/\s+/g, ' ').trim();
}
function createSttHistoryManager({
getGeminiService,
emitSttDebug,
mergeWindowMs = 2400
}) {
const sttHistoryBuffers = {
mic: { text: '', segments: 0, timer: null },
system: { text: '', segments: 0, timer: null }
};
function clearSttHistoryTimer(source) {
const resolvedSource = normalizeSttSource(source);
const timer = sttHistoryBuffers[resolvedSource].timer;
if (timer) {
clearTimeout(timer);
sttHistoryBuffers[resolvedSource].timer = null;
}
}
function resetSttHistoryBuffer(source) {
const resolvedSource = normalizeSttSource(source);
clearSttHistoryTimer(resolvedSource);
sttHistoryBuffers[resolvedSource].text = '';
sttHistoryBuffers[resolvedSource].segments = 0;
}
function flushSttHistoryBuffer(source, reason = 'pause-timeout') {
const resolvedSource = normalizeSttSource(source);
const buffer = sttHistoryBuffers[resolvedSource];
const finalText = String(buffer.text || '').trim();
const segmentCount = buffer.segments;
clearSttHistoryTimer(resolvedSource);
buffer.text = '';
buffer.segments = 0;
const geminiService = getGeminiService();
if (!finalText || !geminiService) {
return;
}
try {
const label = resolvedSource === 'system' ? 'Host' : 'You';
geminiService.addToHistory('user', `${label}: ${finalText}`);
emitSttDebug({
source: resolvedSource,
event: 'history-flush',
message: 'Merged transcript added to Gemini history',
meta: {
reason,
chars: finalText.length,
segments: segmentCount
}
});
} catch (error) {
emitSttDebug({
source: resolvedSource,
level: 'error',
event: 'history-flush-failed',
message: error?.message || 'Failed to add merged transcript to history'
});
}
}
function flushAllSttHistoryBuffers(reason = 'flush-all') {
flushSttHistoryBuffer('mic', reason);
flushSttHistoryBuffer('system', reason);
}
function queueSttHistorySegment(source, transcriptText) {
const resolvedSource = normalizeSttSource(source);
const buffer = sttHistoryBuffers[resolvedSource];
buffer.text = mergeTranscriptText(buffer.text, transcriptText);
buffer.segments += 1;
emitSttDebug({
source: resolvedSource,
event: 'history-buffer',
message: 'Buffered final transcript segment',
meta: {
segments: buffer.segments,
chars: buffer.text.length
}
});
clearSttHistoryTimer(resolvedSource);
buffer.timer = setTimeout(() => {
flushSttHistoryBuffer(resolvedSource, 'pause-timeout');
}, mergeWindowMs);
}
function dispose() {
resetSttHistoryBuffer('mic');
resetSttHistoryBuffer('system');
}
return {
flushAllSttHistoryBuffers,
flushSttHistoryBuffer,
queueSttHistorySegment,
resetSttHistoryBuffer,
dispose
};
}
module.exports = {
createSttHistoryManager,
normalizeSttSource
};
================
File: src/windows/assistant/pcm-capture-worklet.js
================
class PcmCaptureProcessor extends AudioWorkletProcessor {
constructor() {
super();
this.chunkSize = 2048;
this.buffer = new Float32Array(this.chunkSize * 4);
this.writeOffset = 0;
}
process(inputs) {
const input = inputs[0];
if (!input || input.length === 0) {
return true;
}
const channelData = input[0];
if (!channelData || channelData.length === 0) {
return true;
}
this.pushSamples(channelData);
return true;
}
pushSamples(channelData) {
let readOffset = 0;
while (readOffset < channelData.length) {
const freeSpace = this.buffer.length - this.writeOffset;
const toCopy = Math.min(freeSpace, channelData.length - readOffset);
this.buffer.set(channelData.subarray(readOffset, readOffset + toCopy), this.writeOffset);
this.writeOffset += toCopy;
readOffset += toCopy;
while (this.writeOffset >= this.chunkSize) {
const chunk = this.buffer.slice(0, this.chunkSize);
this.port.postMessage(chunk);
const remaining = this.writeOffset - this.chunkSize;
if (remaining > 0) {
this.buffer.copyWithin(0, this.chunkSize, this.writeOffset);
}
this.writeOffset = remaining;
}
}
}
}
registerProcessor('pcm-capture-processor', PcmCaptureProcessor);
================
File: src/windows/assistant/preload/create-electron-api.js
================
const { createInvokeActions } = require('./actions');
const { createEventActions } = require('./listeners');
function createElectronApi(ipcRenderer) {
const invokeActions = createInvokeActions(ipcRenderer);
const eventActions = createEventActions(ipcRenderer);
return {
...invokeActions,
...eventActions,
log: (message) => {
console.log('PreloadAPI log:', message);
},
isAvailable: () => true
};
}
module.exports = {
createElectronApi
};
================
File: src/windows/assistant/preload/helpers.js
================
function invokeWithFallback(ipcRenderer, { channel, label, fallback, transformArgs }) {
return (...args) => {
const callArgs = typeof transformArgs === 'function' ? transformArgs(args) : args;
console.log(`PreloadAPI: ${label} called`);
return ipcRenderer.invoke(channel, ...callArgs).catch((error) => {
console.error(`PreloadAPI: ${label} error:`, error);
return typeof fallback === 'function' ? fallback(error) : fallback;
});
};
}
function createEventListener(ipcRenderer, { channel, label }) {
return (callback) => {
const handler = (_event, payload) => {
try {
callback(payload);
} catch (error) {
console.error(`PreloadAPI: ${label} callback error:`, error);
}
};
ipcRenderer.on(channel, handler);
return () => {
console.log(`PreloadAPI: removing ${label} listener`);
ipcRenderer.removeListener(channel, handler);
};
};
}
module.exports = {
createEventListener,
invokeWithFallback
};
================
File: src/windows/assistant/renderer-globals.d.ts
================
export {};
declare global {
interface Window {
electronAPI: any;
}
}
================
File: src/windows/assistant/renderer/features/ai-context/context-bundle.js
================
import {
contextLineForMessage,
isScreenshotMessageType,
isSystemMessageType,
isTranscriptMessageType,
summaryLineForMessage
} from './message-types.js';
export function buildFilteredAiContextBundle({
messages,
isMessageIncludedForAi,
charBudget,
emitTruncationLog = true,
onTruncationLog
}) {
const candidates = messages
.filter(isMessageIncludedForAi)
.map((message) => ({
message,
contextLine: contextLineForMessage(message),
summaryLine: summaryLineForMessage(message)
}))
.filter((entry) => entry.contextLine.length > 0);
const selectedReversed = [];
let currentChars = 0;
let dropped = 0;
for (let index = candidates.length - 1; index >= 0; index -= 1) {
const entry = candidates[index];
const nextCost = entry.contextLine.length + 1;
if (currentChars + nextCost > charBudget) {
dropped += 1;
continue;
}
selectedReversed.push(entry);
currentChars += nextCost;
}
const selected = selectedReversed.reverse();
if (emitTruncationLog && dropped > 0 && typeof onTruncationLog === 'function') {
onTruncationLog(dropped, charBudget);
}
const transcriptContext = selected
.filter((entry) => isTranscriptMessageType(entry.message.type))
.map((entry) => entry.contextLine)
.join('\n');
const sessionSummary = selected
.filter((entry) => !isSystemMessageType(entry.message.type))
.map((entry) => entry.summaryLine)
.filter((line) => line.length > 0)
.slice(-16)
.join('\n');
const enabledScreenshotIds = Array.from(
new Set(
selected
.filter((entry) => isScreenshotMessageType(entry.message.type))
.map((entry) => entry.message.screenshotId)
.filter((value) => typeof value === 'string' && value.trim().length > 0)
)
);
return {
contextString: selected.map((entry) => entry.contextLine).join('\n'),
transcriptContext,
sessionSummary,
enabledScreenshotIds,
droppedMessages: dropped,
selectedMessages: selected.length,
charBudget
};
}
================
File: src/windows/assistant/renderer/features/ai-context/message-store.js
================
import {