Repository navigation
Expand file tree
/
Copy pathmain.js
More file actions
1031 lines (993 loc) · 35.9 KB
/
Copy pathmain.js
File metadata and controls
1031 lines (993 loc) · 35.9 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, Menu, screen, ipcMain, dialog, shell } = require('electron')
const path = require('path')
const fs = require('fs')
const brain = require('./brain')
const llm = require('./llm')
const { elStart } = require('./el')
const tools = require('./tools')
const SIZE = 180
const CHAT_W = 320
// widget/icon.png: the mark on a transparent background — docs/logo.png is
// flattened RGB and shows as a hard square in the taskbar
const ICON = path.join(__dirname, 'icon.png')
// styling belongs to the bot, so a cloned bot keeps its outfit
const STYLE_KEYS = [
'skin', 'ink', 'pupils', 'mood', 'voice', 'voicePitch', 'aura',
'voiceMode', 'elVoice', 'fxBloom', 'fxHalation', 'fxScan',
'fxChrome', 'fxHolo', 'fxHue', 'fxRim', 'fxGlass', 'fxGloss', 'fxScratch',
'name', 'model', 'soul',
]
// a *look* is the outfit a preset saves and applies: every style key except
// mood (a state) and the voice engine + ElevenLabs voice (a choice made once
// per bot), and who the bot is: its name, model and persona. Applying a look
// must never silently drop a bot back to babble or swap its brain
const NOT_A_LOOK = ['mood', 'voiceMode', 'elVoice', 'name', 'model', 'soul']
const LOOK_KEYS = STYLE_KEYS.filter((k) => !NOT_A_LOOK.includes(k))
const STYLE_DEFAULTS = {
skin: '#16181a',
ink: '#e9ebec',
pupils: false,
mood: 'auto',
voice: true,
voicePitch: 1,
aura: 'none',
voiceMode: 'babble', // 'babble' | 'el'
elVoice: '', // ElevenLabs voice id, per bot
name: 'bbot',
model: '', // OpenRouter model id; empty = the global default
soul: '', // the bot's persona, sent as the system prompt; empty = soul.md
fxBloom: 0, // post-processing intensities, 0..1
fxHalation: 0,
fxScan: 0,
fxChrome: 0,
fxHolo: 0,
fxHue: 0,
fxRim: 0,
fxGlass: 0,
fxGloss: 0,
fxScratch: 0,
}
const GLOBAL_DEFAULTS = {
orKey: '', // OpenRouter API key
defaultModel: llm.DEFAULT_MODEL, // for every bot that doesn't pick its own
bot: 'bbot', // the primary bbot's id
clones: [], // ids of extra bbots to respawn at launch
bots: {}, // per-bot style, name, model and persona
presets: [], // user-saved looks, shared by every bbot
elKey: '', // ElevenLabs API key (global)
showFeed: true, // chat shows the conversation, or just the entry box
captions: false, // closed captions under the bot while it speaks
desktopTools: false, // let the bot search/read/open files here
toolRoots: tools.DEFAULT_ROOTS(), // the only folders those tools may touch
}
const cfgPath = () => path.join(app.getPath('userData'), 'widget-config.json')
let cfg = { ...GLOBAL_DEFAULTS }
try {
cfg = { ...GLOBAL_DEFAULTS, ...JSON.parse(fs.readFileSync(cfgPath(), 'utf8')) }
} catch {}
// migrate a pre-clone config: top-level style keys move into bots._default
{
const legacy = {}
for (const k of STYLE_KEYS) {
if (k in cfg) {
legacy[k] = cfg[k]
delete cfg[k]
}
}
if (Object.keys(legacy).length) {
cfg.bots = { ...cfg.bots, _default: { ...legacy, ...(cfg.bots?._default || {}) } }
}
}
const save = () => {
try {
fs.writeFileSync(cfgPath(), JSON.stringify(cfg))
} catch {}
}
// a first-time clone rolls its own identity: fresh fit, fresh voice
const RANDOM_FITS = [
{ skin: '#16181a', ink: '#e9ebec' }, // midnight
{ skin: '#f4f5f6', ink: '#101214' }, // ghost
{ skin: '#0a0f0b', ink: '#b6ff3d' }, // terminal
{ skin: '#ff9ecb', ink: '#5f1d3a' }, // bubblegum
{ skin: '#4ecdc4', ink: '#0b3437' }, // ocean
{ skin: '#ffd166', ink: '#4a3405' }, // honey
{ skin: '#a78bfa', ink: '#241a4d' }, // grape
{ skin: '#ff6b6b', ink: '#4d0f0f' }, // cherry
{ skin: '#1f6feb', ink: '#dbe9ff' }, // cobalt
{ skin: '#2d3436', ink: '#ffb8b8' }, // charcoal rose
]
function randomStyle() {
const worn = new Set(Object.values(cfg.bots).map((b) => b.skin))
const pool = RANDOM_FITS.filter((f) => !worn.has(f.skin))
const fits = pool.length ? pool : RANDOM_FITS
const fit = fits[Math.floor(Math.random() * fits.length)]
const auras = ['glow', 'ring', 'particles']
return {
...fit,
pupils: Math.random() < 0.35,
mood: 'auto',
voice: true,
voicePitch: Math.round((0.7 + Math.random() * 0.9) * 20) / 20,
aura: Math.random() < 0.35 ? auras[Math.floor(Math.random() * auras.length)] : 'none',
}
}
const styleFor = (botId) => ({
...STYLE_DEFAULTS,
...(cfg.bots._default || {}),
...(botId ? cfg.bots[botId] || {} : {}),
})
// --- instances: the primary bbot plus any clones ---
const instances = new Map()
let seq = 0
const primary = () => [...instances.values()].find((i) => i.primary)
const persistClones = () => {
cfg.clones = [...instances.values()].filter((i) => !i.primary).map((i) => i.botId)
save()
}
const mergedCfg = (inst) => ({
...styleFor(inst.botId),
orKey: cfg.orKey,
defaultModel: cfg.defaultModel,
bot: inst.botId,
presets: cfg.presets,
lookKeys: LOOK_KEYS, // the settings window saves/applies exactly these
styleDefaults: STYLE_DEFAULTS,
elKey: cfg.elKey,
showFeed: cfg.showFeed,
captions: cfg.captions,
desktopTools: cfg.desktopTools,
toolRoots: cfg.toolRoots,
})
function botOf(e) {
for (const inst of instances.values()) {
for (const w of [inst.win, inst.chat, inst.settings, inst.cap, inst.shot]) {
if (w && !w.isDestroyed() && w.webContents === e.sender) return inst
}
}
return primary()
}
const toWin = (inst, ch, p) =>
inst?.win && !inst.win.isDestroyed() && inst.win.webContents.send(ch, p)
const toChat = (inst, ch, p) =>
inst?.chat && !inst.chat.isDestroyed() && inst.chat.webContents.send(ch, p)
function broadcastCfg() {
for (const inst of instances.values()) {
const c = mergedCfg(inst)
for (const w of [inst.win, inst.chat, inst.settings, inst.cap]) {
if (w && !w.isDestroyed()) w.webContents.send('cfg', c)
}
}
}
function spawnBot(botId, { primary: isPrimary = false, x, y } = {}) {
const inst = {
key: isPrimary ? 'main' : `c${++seq}`,
primary: isPrimary,
botId: botId || 'bbot',
win: null,
chat: null,
settings: null,
chatH: 60,
cap: null, // the caption strip, made on first word
capH: 44,
resizing: false,
moving: null,
adjusting: false,
adjustTimer: null,
thread: [], // this bot's conversation, OpenAI message shape
}
inst.win = new BrowserWindow({
width: SIZE,
height: SIZE,
...(x != null ? { x: Math.round(x), y: Math.round(y) } : {}),
icon: ICON,
transparent: true,
frame: false,
resizable: true,
minWidth: 80,
minHeight: 80,
maximizable: false,
fullscreenable: false,
alwaysOnTop: true,
hasShadow: false,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
},
})
inst.win.setAlwaysOnTop(true, 'screen-saver')
inst.win.setAspectRatio(1)
inst.win.loadFile('index.html')
inst.win.on('move', () => {
if (!inst.win.isDestroyed() && !inst.resizing && !inst.adjusting)
inst.win.webContents.send('dragging', screenPos(inst.win))
positionChat(inst)
positionCaptions(inst)
})
// the chrome reflection is anchored to the screen, so it needs to know
// where the window starts out
inst.win.webContents.on('did-finish-load', () => {
if (!inst.win.isDestroyed()) inst.win.webContents.send('dragging', { ...screenPos(inst.win), settle: true })
})
inst.win.on('closed', () => closeBot(inst))
instances.set(inst.key, inst)
return inst
}
// window centre as a fraction of its display's work area, -0.5..0.5
function screenPos(w) {
const b = w.getBounds()
const a = screen.getDisplayMatching(b).workArea
return {
nx: (b.x + b.width / 2 - a.x) / a.width - 0.5,
ny: (b.y + b.height / 2 - a.y) / a.height - 0.5,
}
}
function closeBot(inst) {
if (!instances.has(inst.key)) return
instances.delete(inst.key)
for (const w of [inst.chat, inst.settings, inst.cap]) {
if (w && !w.isDestroyed()) w.destroy()
}
if (inst.win && !inst.win.isDestroyed()) inst.win.destroy()
if (!inst.primary) persistClones()
}
// Manual drag and resize run on their own fast loop, and the size eases
// toward the cursor instead of snapping to it — the corner still tracks the
// pointer, but through a short spring, so it glides rather than stutters.
// The loop only runs while something is in motion or still settling.
let motionTimer = null
function motionTick() {
const p = screen.getCursorScreenPoint()
let busy = false
for (const inst of instances.values()) {
const w = inst.win
if (!w || w.isDestroyed()) continue
if (inst.resizing || inst.sizeCur != null) {
const b = w.getBounds()
// the centre is pinned for the whole gesture, so DPI rounding of the
// bounds can't walk it around
if (!inst.pin) inst.pin = { x: b.x + b.width / 2, y: b.y + b.height / 2 }
const { x: cx, y: cy } = inst.pin
if (inst.resizing)
inst.sizeTarget = Math.max(80, Math.min(800, 2 * Math.max(Math.abs(p.x - cx), Math.abs(p.y - cy))))
if (inst.sizeCur == null) inst.sizeCur = b.width
const t = inst.sizeTarget ?? inst.sizeCur
// ease: a third of the way each tick, snapping when close
inst.sizeCur += (t - inst.sizeCur) * (inst.resizing ? 0.32 : 0.28)
if (Math.abs(t - inst.sizeCur) < 0.4) inst.sizeCur = t
const size = Math.round(inst.sizeCur)
if (size !== b.width || size !== b.height) {
inst.adjusting = true // the 'move' events this fires aren't a drag
w.setBounds({ x: Math.round(cx - size / 2), y: Math.round(cy - size / 2), width: size, height: size })
}
if (!inst.resizing && inst.sizeCur === t) {
// settled: release the gesture state
inst.sizeCur = null
inst.sizeTarget = null
inst.pin = null
inst.adjusting = false
positionChat(inst)
positionCaptions(inst)
} else busy = true
} else if (inst.moving) {
// full bounds with the size captured at drag start — setPosition alone
// lets DPI rounding drift the size a pixel per tick
const nx = Math.round(p.x - inst.moving.dx)
const ny = Math.round(p.y - inst.moving.dy)
const b = w.getBounds()
if (nx !== b.x || ny !== b.y)
w.setBounds({ x: nx, y: ny, width: inst.moving.w, height: inst.moving.h })
busy = true
}
}
if (!busy) {
clearInterval(motionTimer)
motionTimer = null
}
}
function wakeMotion() {
if (!motionTimer) motionTimer = setInterval(motionTick, 8)
}
// The renderers can't see the pointer once it leaves their windows, so global
// gaze is driven from one shared poll.
setInterval(() => {
const p = screen.getCursorScreenPoint()
for (const inst of instances.values()) {
const w = inst.win
if (!w || w.isDestroyed()) continue
const b = w.getBounds()
const cx = b.x + b.width / 2
const cy = b.y + b.height / 2
const kx = p.x - cx
const ky = p.y - cy
inst.curTick = (inst.curTick || 0) + 1
const moved =
!inst.lastCur || Math.abs(kx - inst.lastCur.x) >= 1 || Math.abs(ky - inst.lastCur.y) >= 1
if (moved || inst.curTick % 15 === 0) {
inst.lastCur = { x: kx, y: ky }
w.webContents.send('cursor', { x: kx, y: ky })
}
}
}, 33)
// --- chat: a transparent bubble window anchored above each face ---
function chatBounds(inst) {
const b = inst.win.getBounds()
const area = screen.getDisplayMatching(b).workArea
const gap = 6
let x = Math.round(b.x + b.width / 2 - CHAT_W / 2)
x = Math.max(area.x, Math.min(x, area.x + area.width - CHAT_W))
// Prefer above, shrinking to the room there (the log scrolls inside);
// only sit below when above is genuinely cramped AND below is roomier.
const above = b.y - area.y - gap
const below = area.y + area.height - (b.y + b.height) - gap
let h
let y
let sitsBelow = false
if (above >= 160 || above >= below) {
h = Math.max(60, Math.min(inst.chatH, above))
y = b.y - h - gap
} else {
sitsBelow = true
h = Math.max(60, Math.min(inst.chatH, below))
y = b.y + b.height + gap
}
return { x, y: Math.round(y), width: CHAT_W, height: Math.round(h), below: sitsBelow }
}
function positionChat(inst) {
if (!inst.chat || inst.chat.isDestroyed() || !inst.win || inst.win.isDestroyed()) return
const { below, ...bounds } = chatBounds(inst)
inst.chat.setBounds(bounds)
if (inst.chatBelow !== below) {
// flipped anchor flips the page layout: input stays beside the bot
inst.chatBelow = below
toChat(inst, 'chat-orient', { below })
}
}
function hideChat(inst) {
inst.chat.hide()
toWin(inst, 'chat-state', { state: 'end' })
}
function showChat(inst) {
positionChat(inst)
inst.chat.show()
inst.chat.webContents.send('chat-focus')
toWin(inst, 'chat-state', { state: 'open' })
}
function toggleChat(inst) {
// hide/show, never destroy — the transcript lives in the window and only
// the clear button empties it
if (inst.chat && !inst.chat.isDestroyed()) {
if (inst.chat.isVisible()) hideChat(inst)
else showChat(inst)
return
}
inst.chatH = 60 // a fresh chat starts compact; the page reports real size
const at = chatBounds(inst) // born in place — no centered flash, no jump
inst.chat = new BrowserWindow({
...at,
icon: ICON,
show: false,
transparent: true,
frame: false,
resizable: false,
maximizable: false,
fullscreenable: false,
alwaysOnTop: true,
hasShadow: false,
skipTaskbar: true,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
},
})
inst.chat.setAlwaysOnTop(true, 'screen-saver')
inst.chat.loadFile('chat.html')
// links in replies open in the real browser, never in-widget
inst.chat.webContents.setWindowOpenHandler(({ url }) => {
if (/^https?:/.test(url)) require('electron').shell.openExternal(url)
return { action: 'deny' }
})
inst.chat.webContents.on('will-navigate', (e) => e.preventDefault())
inst.chat.once('ready-to-show', () => {
positionChat(inst)
inst.chat.show()
inst.chat.webContents.send('chat-focus')
})
inst.chat.on('closed', () => {
inst.chat = null
toWin(inst, 'chat-state', { state: 'end' })
})
toWin(inst, 'chat-state', { state: 'open' })
}
function toggleSettings(inst) {
if (inst.settings && !inst.settings.isDestroyed()) {
inst.settings.close()
return
}
const W = 430
const H = 620
const b = inst.win.getBounds()
const area = screen.getDisplayMatching(b).workArea
let x = b.x + b.width + 14
if (x + W > area.x + area.width) x = b.x - W - 14
x = Math.max(area.x, Math.min(x, area.x + area.width - W))
const y = Math.max(area.y, Math.min(b.y, area.y + area.height - H))
inst.settings = new BrowserWindow({
width: W,
height: H,
x,
y,
icon: ICON,
transparent: true,
frame: false,
resizable: false,
maximizable: false,
fullscreenable: false,
alwaysOnTop: true,
hasShadow: false,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
},
})
inst.settings.loadFile('settings.html')
inst.settings.webContents.setWindowOpenHandler(({ url }) => {
if (/^https?:/.test(url)) require('electron').shell.openExternal(url)
return { action: 'deny' }
})
inst.settings.webContents.on('will-navigate', (e) => e.preventDefault())
inst.settings.on('closed', () => (inst.settings = null))
}
// --- captions: a click-through strip under the face that prints each word
// as the voice reaches it. The face window owns the audio clock and sends
// the words; this just hosts and places them ---
function captionBounds(inst) {
const b = inst.win.getBounds()
const area = screen.getDisplayMatching(b).workArea
const w = Math.max(280, Math.min(520, Math.round(b.width * 1.8)))
const h = Math.max(44, Math.min(160, inst.capH))
let x = Math.round(b.x + b.width / 2 - w / 2)
x = Math.max(area.x, Math.min(x, area.x + area.width - w))
// tucked under the head: the face sits 15% in from the window edge
let y = Math.round(b.y + b.height * 0.86)
if (y + h > area.y + area.height) y = Math.round(b.y - h + b.height * 0.12) // no room: over the brow
return { x, y, width: w, height: h }
}
function positionCaptions(inst) {
if (!inst.cap || inst.cap.isDestroyed() || !inst.win || inst.win.isDestroyed()) return
inst.cap.setBounds(captionBounds(inst))
}
function captionWindow(inst) {
if (inst.cap && !inst.cap.isDestroyed()) return inst.cap
inst.cap = new BrowserWindow({
...captionBounds(inst),
icon: ICON,
show: false,
transparent: true,
frame: false,
resizable: false,
movable: false,
focusable: false,
maximizable: false,
fullscreenable: false,
alwaysOnTop: true,
hasShadow: false,
skipTaskbar: true,
webPreferences: { preload: path.join(__dirname, 'preload.js') },
})
inst.cap.setAlwaysOnTop(true, 'screen-saver')
inst.cap.setIgnoreMouseEvents(true) // never in the way of a click
inst.cap.loadFile('captions.html')
inst.cap.on('closed', () => (inst.cap = null))
return inst.cap
}
function hideCaptions(inst) {
if (inst.cap && !inst.cap.isDestroyed()) {
inst.cap.webContents.send('caption', { clear: true })
inst.cap.hide()
}
}
ipcMain.on('caption', (e, m) => {
const inst = botOf(e)
if (!inst?.win || inst.win.isDestroyed()) return
if (!cfg.captions) return
if (m.clear) return hideCaptions(inst)
const cap = captionWindow(inst)
const deliver = () => {
if (cap.isDestroyed()) return
if ((m.word || m.words) && !cap.isVisible()) {
positionCaptions(inst)
cap.showInactive()
}
cap.webContents.send('caption', m)
if (m.end) {
clearTimeout(inst.capHide)
inst.capHide = setTimeout(() => cap.isDestroyed() || cap.hide(), 2600)
} else clearTimeout(inst.capHide)
}
if (cap.webContents.isLoading()) cap.webContents.once('did-finish-load', deliver)
else deliver()
})
ipcMain.on('caption-size', (e, h) => {
const inst = botOf(e)
if (!inst) return
const next = Math.max(44, Math.min(160, Math.round(h)))
if (next === inst.capH) return
inst.capH = next
positionCaptions(inst)
})
// --- export: the bot as a 1080×1080 transparent PNG, every effect intact.
// A hidden offscreen window renders index.html in export mode (no controls,
// no ground shadow, no float) at the target size, then a capture with alpha
// goes to a save dialog ---
const EXPORT_PX = 1080
async function exportPng(inst) {
if (!inst?.win || inst.win.isDestroyed()) return { error: 'no bot' }
if (inst.shot && !inst.shot.isDestroyed()) return { error: 'busy' }
const shot = new BrowserWindow({
width: EXPORT_PX,
height: EXPORT_PX,
show: false,
transparent: true,
frame: false,
skipTaskbar: true,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
offscreen: true,
backgroundThrottling: false,
},
})
inst.shot = shot
try {
shot.webContents.setFrameRate(60)
await shot.loadFile('index.html', { query: { export: '1' } })
// the face builds, fx layers ease in (260ms), the sphere warp maps
// generate: give it a moment to settle
await new Promise((r) => setTimeout(r, 1200))
let img = await shot.webContents.capturePage()
const sz = img.getSize()
if (sz.width !== EXPORT_PX || sz.height !== EXPORT_PX) img = img.resize({ width: EXPORT_PX, height: EXPORT_PX })
const name = styleFor(inst.botId).name || 'bbot'
const safe = name.replace(/[^\w.-]+/g, '-').toLowerCase()
if (process.env.BBOT_EXPORT_TO) {
// headless check: skip the dialog and write straight out
fs.writeFileSync(process.env.BBOT_EXPORT_TO, img.toPNG())
return { path: process.env.BBOT_EXPORT_TO }
}
const { canceled, filePath } = await dialog.showSaveDialog(inst.settings && !inst.settings.isDestroyed() ? inst.settings : inst.win, {
title: 'Export bbot',
defaultPath: path.join(app.getPath('downloads'), `${safe}-${EXPORT_PX}.png`),
filters: [{ name: 'PNG image', extensions: ['png'] }],
})
if (canceled || !filePath) return { canceled: true }
fs.writeFileSync(filePath, img.toPNG())
return { path: filePath }
} catch (err) {
return { error: err?.message || String(err) }
} finally {
if (!shot.isDestroyed()) shot.destroy()
inst.shot = null
}
}
ipcMain.handle('export-png', (e) => exportPng(botOf(e)))
if (process.env.BBOT_EXPORT_TO)
app.whenReady().then(() => setTimeout(async () => console.log('export', JSON.stringify(await exportPng(primary()))), 4000))
// --- the right-click menu: spawn another bbot, dismiss clones ---
function faceMenu(inst) {
const template = [
{ label: styleFor(inst.botId).name || 'bbot', enabled: false },
{ type: 'separator' },
{ label: 'Chat', click: () => toggleChat(inst) },
{ label: 'Customize', click: () => toggleSettings(inst) },
{ label: 'Export PNG…', click: () => exportPng(inst) },
{
label: 'New bbot',
click: () => {
// a new bot rolls its own identity: fresh fit, fresh voice, own thread
const id = `bot-${Date.now().toString(36)}`
cfg.bots[id] = { ...randomStyle(), name: `bbot ${instances.size + 1}` }
save()
const b = inst.win.getBounds()
spawnBot(id, { x: b.x + b.width + 16, y: b.y })
persistClones()
},
},
]
if (!inst.primary) {
template.push({ type: 'separator' })
template.push({ label: 'Dismiss this bbot', click: () => closeBot(inst) })
}
Menu.buildFromTemplate(template).popup({ window: inst.win })
}
// --- connection status: the OpenRouter key, checked once ---
llm.on('status', (s) => {
for (const w of BrowserWindow.getAllWindows()) {
if (!w.isDestroyed()) w.webContents.send('bridge-status', s)
}
})
// --- IPC (everything resolves the calling window's bbot) ---
ipcMain.handle('get-cfg', (e) => mergedCfg(botOf(e)))
ipcMain.handle('get-size', (e) => {
const inst = botOf(e)
return inst?.win && !inst.win.isDestroyed() ? inst.win.getBounds().width : SIZE
})
ipcMain.on('set-cfg', (e, patch) => {
const inst = botOf(e)
if (!inst) return
const styleTarget = inst.botId || '_default'
for (const k of STYLE_KEYS) {
if (k in patch) cfg.bots[styleTarget] = { ...cfg.bots[styleTarget], [k]: patch[k] }
}
for (const k of ['orKey', 'defaultModel', 'presets', 'elKey', 'showFeed', 'captions', 'desktopTools', 'toolRoots']) {
if (k in patch) cfg[k] = patch[k]
}
if ('toolRoots' in patch)
cfg.toolRoots = [...new Set((cfg.toolRoots || []).map((r) => String(r).trim()).filter(Boolean))]
save()
broadcastCfg()
if ('orKey' in patch) llm.connect(cfg.orKey)
if ('desktopTools' in patch || 'toolRoots' in patch) pushToolState()
if ('captions' in patch && !patch.captions)
for (const i of instances.values()) hideCaptions(i)
})
ipcMain.on('react', (e, name) => toWin(botOf(e), 'react', name))
ipcMain.on('set-size', (e, size) => {
const inst = botOf(e)
if (!inst?.win || inst.win.isDestroyed()) return
const s = Math.max(80, Math.min(800, Math.round(size)))
const b = inst.win.getBounds()
inst.adjusting = true
clearTimeout(inst.adjustTimer)
inst.adjustTimer = setTimeout(() => (inst.adjusting = false), 300)
inst.win.setBounds({
x: Math.round(b.x + b.width / 2 - s / 2),
y: Math.round(b.y + b.height / 2 - s / 2),
width: s,
height: s,
})
})
ipcMain.on('resize-start', (e) => {
const inst = botOf(e)
if (!inst) return
inst.resizing = true
wakeMotion()
})
ipcMain.on('resize-end', (e) => {
const inst = botOf(e)
if (inst) inst.resizing = false // the loop keeps running until the size settles
})
ipcMain.on('move-start', (e) => {
const inst = botOf(e)
if (!inst?.win || inst.win.isDestroyed()) return
const p = screen.getCursorScreenPoint()
const b = inst.win.getBounds()
inst.moving = { dx: p.x - b.x, dy: p.y - b.y, w: b.width, h: b.height }
wakeMotion()
})
ipcMain.on('move-end', (e) => (botOf(e).moving = null))
ipcMain.on('toggle-settings', (e) => toggleSettings(botOf(e)))
ipcMain.on('toggle-chat', (e) => toggleChat(botOf(e)))
ipcMain.on('face-menu', (e) => faceMenu(botOf(e)))
ipcMain.on('bridge-connect', () => llm.connect(cfg.orKey))
ipcMain.on('bridge-disconnect', () => llm.disconnect())
ipcMain.handle('get-bridge-status', () => llm.status)
ipcMain.handle('list-models', async () => {
try {
return { models: await llm.listModels() }
} catch (e) {
return { error: e?.message || 'fetch failed' }
}
})
ipcMain.on('close-chat', (e) => {
const inst = botOf(e)
if (inst?.chat && !inst.chat.isDestroyed() && inst.chat.isVisible()) hideChat(inst)
})
ipcMain.on('chat-size', (e, h) => {
const inst = botOf(e)
if (!inst) return
const next = Math.max(60, Math.min(600, Math.round(h)))
if (Math.abs(next - inst.chatH) < 8) return
inst.chatH = next
positionChat(inst)
})
// the bot's persona: its own soul if it has one, else soul.md — minus the
// note above its first rule, which is for people reading the file
const SOUL = (() => {
try {
const text = fs.readFileSync(path.join(__dirname, 'soul.md'), 'utf8')
return text.split(/^---$/m).slice(1).join('---').trim() || text
} catch {
return ''
}
})()
const THREAD_MAX = 40 // messages kept per bot; older ones fall off the front
ipcMain.on('chat-send', async (e, text) => {
const inst = botOf(e)
if (!inst) return
const msg = String(text).slice(0, 2000)
// no fake answers: chat needs a working OpenRouter key
if (llm.status !== 'on') {
toChat(inst, 'chat-error', {
text:
llm.status === 'denied'
? 'OpenRouter key rejected — check it in settings → config'
: 'no OpenRouter key yet — add one in settings → config',
})
toWin(inst, 'chat-state', { state: 'error' })
return
}
if (llm.turn) llm.stop() // barge-in: a new message replaces the one in flight
toWin(inst, 'chat-state', { state: 'thinking' })
// barge-in: a new message interrupts whatever he's still saying
if (inst.el) {
inst.el.abort()
inst.el = null
}
toWin(inst, 'el-audio', { stop: true })
// voice routing: an ElevenLabs session for this turn, or the babble path
const voiceId = await elVoiceFor(inst)
const el = voiceId ? elStart(cfg.elKey, voiceId, (a) => toWin(inst, 'el-audio', a)) : null
inst.el = el
toChat(inst, 'chat-pace', { mode: el ? 'voice' : 'text' }) // reveal follows the voice
const style = styleFor(inst.botId)
try {
let streaming = false
const r = await llm.chat({
model: style.model || cfg.defaultModel,
system: style.soul || SOUL,
messages: [...inst.thread, { role: 'user', content: msg }],
tools: cfg.desktopTools ? tools.manifest() : [],
runTool: (name, input) => runTool(inst, name, input),
onEvent: (ev) => {
if (ev.type === 'delta') {
if (!streaming) {
streaming = true
toWin(inst, 'chat-state', { state: 'streaming' })
}
toChat(inst, 'chat-delta', { text: ev.content })
if (el) el.feed(ev.content) // the voice rides the stream
else toWin(inst, 'speak', { text: ev.content })
}
if (ev.type === 'tool') toWin(inst, 'chat-state', { state: 'tool' })
if (ev.type === 'reasoning') think(inst, ev.content)
},
})
inst.thread = r.messages.slice(-THREAD_MAX)
if (el) {
if (!streaming) el.feed(r.text) // arrived un-streamed
el.end()
if (inst.el === el) inst.el = null
} else {
if (!streaming) toWin(inst, 'speak', { text: r.text })
toWin(inst, 'speak', { done: true }) // flush any buffered partial word
}
toChat(inst, 'chat-reply', { text: r.text })
toWin(inst, 'chat-state', { state: 'reply', ...brain.inferMood(r.text) })
} catch (err) {
el?.abort()
if (inst.el === el) inst.el = null
if (err?.message === 'stopped') return // replaced by a newer message
const why =
err?.message === 'timeout'
? 'timed out waiting for a reply'
: err?.message === 'offline'
? 'not connected to OpenRouter'
: err?.message || 'something broke'
toChat(inst, 'chat-error', { text: why })
toWin(inst, 'chat-state', { state: 'error' })
}
})
ipcMain.handle('pick-folder', async (e) => {
const inst = botOf(e)
const r = await dialog.showOpenDialog(inst?.settings && !inst.settings.isDestroyed() ? inst.settings : undefined, {
properties: ['openDirectory'],
title: 'Let the bot see this folder',
})
return r.canceled ? null : r.filePaths[0]
})
// --- desktop tools: offered to the model as functions, run here, scoped to
// cfg.toolRoots. The face focuses while it works and the chat logs what was
// done ---
// the model thinking out loud: the face acts the thought (a mood read from
// the text, a thought cloud with its gist) and the chat's typing bubble
// whispers it
function think(inst, text) {
if (!text || !String(text).trim()) return
const th = brain.inferThought(text)
toWin(inst, 'chat-state', { state: 'reasoning', mood: th.mood, react: th.react, text: th.gist })
toChat(inst, 'chat-thought', { text: th.gist })
}
// what the MCP panel in settings shows: what the tools are, and what the bot
// has done with them. In-memory; a fresh launch starts clean
const toolLog = [] // newest first, capped
const toolStats = {} // name → { count, errors, lastAt }
const TOOL_LOG_MAX = 40
const toolState = () => ({
on: !!cfg.desktopTools,
bridge: llm.status,
tools: tools.manifest().map((t) => ({ ...t, ...(toolStats[t.name] || { count: 0, errors: 0, lastAt: 0 }) })),
roots: cfg.toolRoots,
log: toolLog,
})
const pushToolState = () => {
const st = toolState()
for (const inst of instances.values())
if (inst.settings && !inst.settings.isDestroyed()) inst.settings.webContents.send('tool-state', st)
}
ipcMain.handle('get-tool-state', () => toolState())
llm.on('status', pushToolState)
async function runTool(inst, name, input) {
const t0 = Date.now()
const record = (result) => {
const s = (toolStats[name] ||= { count: 0, errors: 0, lastAt: 0 })
s.count++
if (result.is_error) s.errors++
s.lastAt = t0
toolLog.unshift({
at: t0,
ms: Date.now() - t0,
name,
summary: tools.describe(name, input),
error: !!result.is_error,
detail: result.is_error ? result.content?.[0]?.text : undefined,
bot: styleFor(inst?.botId).name || '',
})
toolLog.length = Math.min(toolLog.length, TOOL_LOG_MAX)
pushToolState()
}
if (!cfg.desktopTools) {
const off = { content: [{ type: 'text', text: 'desktop tools are switched off in the widget' }], is_error: true }
record(off)
return off
}
toWin(inst, 'chat-state', { state: 'tool' })
const result = await tools.run(name, input, { roots: cfg.toolRoots, shell })
const { meta, ...wire } = result
record(result)
toChat(inst, 'chat-note', {
text: (result.is_error ? "couldn't: " : '') + tools.describe(name, input),
error: !!result.is_error,
})
toWin(inst, 'chat-state', { state: 'thinking' }) // the reply is still cooking
return wire
}
ipcMain.on('reset-thread', (e) => {
const inst = botOf(e)
if (inst) inst.thread = []
})
ipcMain.on('voice-hush', (e) => toWin(botOf(e), 'speak', { hush: true }))
ipcMain.on('voice-stop', (e) => {
// the user wants quiet NOW: kill the EL stream and all queued audio
const inst = botOf(e)
if (!inst) return
inst.el?.abort()
inst.el = null
toWin(inst, 'el-audio', { stop: true })
toWin(inst, 'speak', { hush: true })
toChat(inst, 'voice-mark', { ended: true }) // free the text to finish
})
// typing in the chat box: the caret's screen point, made relative to the
// face's centre so the renderer can look at it the way it looks at the cursor
ipcMain.on('caret', (e, p) => {
const inst = botOf(e)
if (!inst?.win || inst.win.isDestroyed() || !p) return
const b = inst.win.getBounds()
toWin(inst, 'caret', { x: p.x - (b.x + b.width / 2), y: p.y - (b.y + b.height / 2) })
})
// the face window owns the audio clock; it reports when speech starts/ends
ipcMain.on('el-mark', (e, m) => toChat(botOf(e), 'voice-mark', m))
// --- ElevenLabs: list the account's voices for the picker ---
let elVoiceCache = null // { key, ids } — the account's voices, per key
async function elVoices() {
if (!cfg.elKey) return { error: 'no key' }
try {
const res = await require('electron').net.fetch('https://api.elevenlabs.io/v1/voices', {
headers: { 'xi-api-key': cfg.elKey },
})
if (!res.ok) return { error: res.status === 401 ? 'key rejected' : `error ${res.status}` }
const j = await res.json()
const voices = (j.voices || []).map((v) => ({ id: v.voice_id, name: v.name }))
elVoiceCache = { key: cfg.elKey, ids: voices.map((v) => v.id) }
return { voices }
} catch (e) {
return { error: e?.message || 'fetch failed' }
}
}
ipcMain.handle('el-voices', elVoices)
// the voice to speak with, or null for the babble path. The saved id is
// checked against the account (a swapped key leaves ids from the old one
// behind); a bot on ElevenLabs with no usable voice yet borrows the account's
// first voice and keeps it, rather than quietly babbling or erroring while
// the settings say ElevenLabs
async function elVoiceFor(inst) {
const style = styleFor(inst.botId)
if (style.voiceMode !== 'el' || style.voice === false || !cfg.elKey) return null
if (elVoiceCache?.key !== cfg.elKey) await elVoices()
const ids = elVoiceCache?.key === cfg.elKey ? elVoiceCache.ids : null
if (style.elVoice && (!ids || ids.includes(style.elVoice))) return style.elVoice
const id = ids?.[0]
if (!id) return style.elVoice || null // can't check — speak with what we have
const target = inst.botId || '_default'
cfg.bots[target] = { ...cfg.bots[target], elVoice: id }
save()
broadcastCfg()
return id
}
// --- start with the system: a login item pointing electron at this folder ---
const loginItem = { path: process.execPath, args: [__dirname] }
ipcMain.handle('get-autostart', () => app.getLoginItemSettings(loginItem).openAtLogin)
ipcMain.on('set-autostart', (_e, on) => {
app.setLoginItemSettings({ openAtLogin: !!on, ...loginItem })
})
// --- OG link previews: fetched here, cached per session ---
const ogCache = new Map()
ipcMain.handle('og-fetch', async (_e, url) => {
try {
const u = new URL(url)
if (!/^https?:$/.test(u.protocol)) return null
if (ogCache.has(url)) return ogCache.get(url)
const ctrl = new AbortController()
const timer = setTimeout(() => ctrl.abort(), 6000)
const res = await require('electron').net.fetch(url, {
signal: ctrl.signal,
redirect: 'follow',
})
clearTimeout(timer)
if (!res.ok || !(res.headers.get('content-type') || '').includes('text/html'))
throw new Error('not a page')
const html = (await res.text()).slice(0, 300000)
const meta = (name) =>
html.match(
new RegExp(`<meta[^>]+(?:property|name)=["']${name}["'][^>]*content=["']([^"']+)["']`, 'i')
)?.[1] ??
html.match(
new RegExp(`<meta[^>]+content=["']([^"']+)["'][^>]*(?:property|name)=["']${name}["']`, 'i')
)?.[1] ??
null
const title = meta('og:title') || html.match(/<title[^>]*>([^<]{1,200})/i)?.[1] || null
const out = title
? {
title: title.trim(),
description: (meta('og:description') || meta('description') || '').slice(0, 200),
image: meta('og:image'),
host: u.host,
}
: null
ogCache.set(url, out)
return out
} catch {
ogCache.set(url, null)
return null
}
})
ipcMain.handle('get-hello', () => ({ status: llm.status }))
// renderer crash reporter: uncaught errors land in userData/renderer-errors.log
ipcMain.on('rlog', (_e, msg) => {
try {
fs.appendFileSync(