forked from intel/AI-Playground
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmain.ts
More file actions
2647 lines (2414 loc) · 90.9 KB
/
Copy pathmain.ts
File metadata and controls
2647 lines (2414 loc) · 90.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
import koffi from 'koffi'
if (isAdmin()) {
const lib = koffi.load('user32.dll')
const MB_ICONINFORMATION = 0x40
const MessageBoxW = lib.func('__stdcall', 'MessageBoxW', 'int', [
'void *',
'str16',
'str16',
'uint',
])
MessageBoxW(
null,
'For security reasons, AI Playground cannot be executed with administrative permissions. Please restart AI Playground from a Windows account without Administrator rights.',
'AI Playground',
MB_ICONINFORMATION,
)
process.exit(0)
}
import {
app,
BrowserWindow,
desktopCapturer,
dialog,
ipcMain,
IpcMainEvent,
IpcMainInvokeEvent,
MessageBoxOptions,
MessageBoxSyncOptions,
nativeImage,
net,
OpenDialogSyncOptions,
protocol,
screen,
session,
shell,
systemPreferences,
utilityProcess,
UtilityProcess,
} from 'electron'
import path from 'node:path'
import { pathToFileURL } from 'node:url'
import fs from 'fs'
import { exec, spawn } from 'node:child_process'
import { promisify } from 'node:util'
const execAsync = promisify(exec)
import { randomUUID } from 'node:crypto'
import sudo from 'sudo-prompt'
import { PathsManager } from './pathsManager'
import { appLoggerInstance } from './logging/logger.ts'
import {
aiplaygroundApiServiceRegistry,
ApiServiceRegistryImpl,
} from './subprocesses/apiServiceRegistry'
import {
ComfyUiBackendService,
COMFYUI_DEFAULT_PARAMETERS,
} from './subprocesses/comfyUIBackendService'
import { AiBackendService } from './subprocesses/aiBackendService'
import { HomeAgentBackendService } from './subprocesses/homeAgentBackendService'
import { LLAMACPP_DEFAULT_PARAMETERS } from './subprocesses/llamaCppBackendService'
import { filterPartnerPresets, updateIntelPresets } from './subprocesses/updateIntelPresets.ts'
import { getGitHubRepoUrl, resolveBackendVersion, resolveModels } from './remoteUpdates.ts'
import * as comfyuiTools from './subprocesses/comfyuiTools'
import {
getMcpServerStatus,
invokeMcpServerTool,
listMcpServers,
listMcpServerTools,
startMcpServer,
stopAllMcpServers,
stopMcpServer,
} from './subprocesses/mcpManager'
import {
close as closeWebBrowser,
destroyWebBrowser,
getState as getWebBrowserState,
hide as hideWebBrowser,
interact as interactWebBrowser,
navigate as navigateWebBrowser,
readPage as readWebBrowserPage,
screenshot as screenshotWebBrowser,
search as searchWebBrowser,
setWebBrowserMainWindow,
show as showWebBrowser,
type WebBrowserInteraction,
} from './subprocesses/webBrowserManager'
import {
addMcpServer,
detectAndRegisterAutoMcpServers,
getMcpConfigPath,
getMcpServerConfig,
isAutoDetectId,
updateMcpServer,
removeMcpServer,
type McpServerConfig,
} from './subprocesses/mcpServers'
import { externalResourcesDir, getMediaDir } from './util.ts'
import { packagedResourcesRoot } from './aipgRoot.ts'
import { loadDemoProfile, type DemoProfile } from './demoProfile.ts'
import type { ModelPaths } from '@/assets/js/store/models.ts'
import type { IndexedDocument, EmbedInquiry } from '@/assets/js/store/textInference.ts'
import { BackendServiceName } from '@/assets/js/store/backendServices.ts'
import {
detectGpuHardwareDevices,
type GpuHardwareDevice,
} from './subprocesses/hardwareDiscovery.ts'
import z from 'zod'
const ProductModeUiI18nSchema = z.object({
titleOne: z.string(),
titleTwo: z.string(),
subtitle: z.string().optional(),
description: z.string(),
supportedHardware: z.string(),
features: z.array(z.object({ labelKey: z.string(), detailKey: z.string() })).optional(),
})
const ProductModeFileSchema = z.object({
mode: z.enum(['studio', 'essentials', 'nvidia']),
priority: z.number(),
recommendForIntelDeviceIds: z.array(z.string()).default([]),
recommendForNvidia: z.boolean().default(false),
experimental: z.boolean().default(false),
displayOrder: z.number(),
requiresNvidiaGpu: z.boolean().default(false),
includePresets: z.array(z.string()).optional(),
excludePresets: z.array(z.string()).optional(),
excludeVariantBackends: z.array(z.string()).optional(),
ui: z.object({
i18n: ProductModeUiI18nSchema,
}),
})
type ProductModeFileConfig = z.infer<typeof ProductModeFileSchema>
function loadProductModeConfigs(): ProductModeFileConfig[] {
try {
const modeDirs = fs
.readdirSync(modesDir, { withFileTypes: true })
.filter((e) => e.isDirectory() && e.name !== 'base')
const configs: ProductModeFileConfig[] = []
for (const dir of modeDirs) {
const modeFile = path.join(modesDir, dir.name, 'mode.json')
if (!fs.existsSync(modeFile)) continue
const raw = fs.readFileSync(modeFile, 'utf-8')
const parsed = ProductModeFileSchema.parse(JSON.parse(raw))
configs.push({
...parsed,
recommendForIntelDeviceIds: parsed.recommendForIntelDeviceIds.map((id) => id.toLowerCase()),
})
}
return configs
} catch (e) {
appLogger.warn(`Failed to read product mode configs: ${e}`, 'electron-backend')
return []
}
}
function loadModeConfig(mode: string): ProductModeFileConfig | null {
const modeFile = path.join(modesDir, mode, 'mode.json')
if (!fs.existsSync(modeFile)) return null
try {
const raw = fs.readFileSync(modeFile, 'utf-8')
return ProductModeFileSchema.parse(JSON.parse(raw))
} catch (e) {
appLogger.warn(`Failed to read mode config for ${mode}: ${e}`, 'electron-backend')
return null
}
}
// }
// The built directory structure
//
// ├─┬─┬ dist
// │ │ └── index.html
// │ │
// │ ├─┬ dist-electron
// │ │ ├── main.js
// │ │ └── preload.js
// │
process.env.DIST = path.join(__dirname, '../')
process.env.VITE_PUBLIC = path.join(__dirname, app.isPackaged ? '../..' : '../../../public')
const externalRes = path.resolve(
app.isPackaged ? packagedResourcesRoot() : path.join(__dirname, '../../external/'),
)
const modesDir = path.resolve(
app.isPackaged
? path.join(packagedResourcesRoot(), 'modes')
: path.join(__dirname, '../../../modes/'),
)
// On Linux (incl. headless Xvfb/VNC), Chromium's GPU process is often "not
// usable" and Electron aborts on startup. Disable hardware acceleration so the
// software rasterizer is used. This does NOT affect AI/compute workloads, which
// use Level Zero/SYCL/Vulkan directly. --no-sandbox avoids SUID-sandbox issues.
if (process.platform === 'linux') {
app.disableHardwareAcceleration()
app.commandLine.appendSwitch('disable-gpu')
app.commandLine.appendSwitch('no-sandbox')
}
const singleInstanceLock = app.requestSingleInstanceLock()
const appLogger = appLoggerInstance
let win: BrowserWindow | null
let serviceRegistry: ApiServiceRegistryImpl | null = null
const mediaDir = getMediaDir()
fs.mkdirSync(mediaDir, { recursive: true })
const mediaInputDir = path.join(mediaDir, 'input')
fs.mkdirSync(mediaInputDir, { recursive: true })
/** Resolve aipg-media://… to an absolute file path under `mediaDir` (no path traversal). */
function getLocalPathFromAipgMediaUrl(url: string): string | null {
if (typeof url !== 'string' || !url.startsWith('aipg-media://')) return null
// `aipg-media` is registered as a *standard* scheme, so Chromium parses the
// segment after `://` as the URL authority and lowercases it. The current
// URL format therefore keeps the media-relative path in the URL *path* under
// a constant `media` authority (see `mediaUrl()` in `src/lib/utils.ts`) so
// case-sensitive filenames survive on case-sensitive filesystems (Linux).
//
// Legacy URLs (`aipg-media://<relative-path>`) put the path directly in the
// authority; keep resolving those for already-persisted media references.
// (Their case was lost to the authority lowercasing, so they only ever
// resolved on case-insensitive filesystems — unchanged by this branch.)
let parsed: URL
try {
parsed = new URL(url)
} catch {
return null
}
const relativeRaw = parsed.host === 'media' ? parsed.pathname : parsed.host + parsed.pathname
// Strip any trailing slash — Chromium occasionally appends one to
// custom-protocol URLs (e.g. `…/foo.png/`), and `net.fetch(file://.../foo.png/)`
// treats the trailing slash as "directory" and fails.
// `decodeURIComponent` throws `URIError` on malformed `%` sequences (e.g.
// `%E0`); treat that as an invalid URL rather than letting the exception
// escape into the protocol handler or IPC reply.
let decodedUrl: string
try {
decodedUrl = decodeURIComponent(relativeRaw.replace(/[/\\]+$/, ''))
} catch {
return null
}
const fullPath = path.normalize(path.join(mediaDir, decodedUrl))
const base = path.resolve(mediaDir)
const relative = path.relative(base, fullPath)
if (relative.startsWith('..') || path.isAbsolute(relative)) return null
return fullPath
}
let langchainChild: UtilityProcess | null = null
// 🚧 Use ['ENV_NAME'] avoid vite:define plugin - Vite@2.x
const VITE_DEV_SERVER_URL = process.env['VITE_DEV_SERVER_URL']
if (process.env.AIPG_DEBUGGING_PORT) {
app.commandLine.appendSwitch('remote-debugging-port', process.env.AIPG_DEBUGGING_PORT)
}
// const APP_TOOL_HEIGHT = 209;
const appSize = {
width: 820,
height: 128,
maxChatContentHeight: 0,
}
const ThemeSchema = z.enum(['dark', 'lnl', 'bmg', 'light'])
const ProductModeSchema = z.enum(['studio', 'essentials', 'nvidia'])
const LocalSettingsSchema = z.object({
debug: z.boolean().default(false),
deviceArchOverride: z.enum(['bmg', 'acm', 'arl_h', 'wcl', 'lnl', 'mtl']).nullable().default(null),
isAdminExec: z.boolean().default(false),
availableThemes: z.array(ThemeSchema).default(['dark', 'lnl', 'bmg', 'light']),
currentTheme: ThemeSchema.default('bmg'),
productMode: ProductModeSchema.optional(),
isDemoModeEnabled: z.boolean().default(false),
demoModeResetInSeconds: z.number().min(1).nullable().default(null),
demoModePasscode: z.string().optional(),
// Gates the Home Agent feature (Telegram bridge backend, setup wizard surface,
// header toggle, bundled preset). Default false: opt-in by editing settings.json.
isHomeAgentEnabled: z.boolean().default(false),
languageOverride: z.string().nullable().default(null),
remoteRepository: z.string().default('intel/ai-playground'),
huggingfaceEndpoint: z.string().default('https://huggingface.co'),
mcpAutoDetectionDismissed: z.array(z.string()).default([]),
// Allowed OpenVINO devices for image-gen dropdowns (in-process upscale +
// OVMS image variants). Case-insensitive prefix match against device IDs.
// Default excludes NPU because RealESRGAN_x4plus and SDXL exceed current
// Intel NPU memory budgets on most shipping hardware. Override per-machine
// by editing settings.json, e.g. ["AUTO", "CPU", "GPU", "NPU"] to re-enable.
openvinoImageGenDevices: z.array(z.string()).default(['CPU', 'GPU']),
// Last inference device chosen per backend, keyed by service name
// (e.g. 'llamacpp-backend') or '<serviceName>:stt' for the OpenVINO STT
// sub-device. Restored at boot in each service's detectDevices() so the app
// does not reset to the default GPU (iGPU) on every restart.
lastSelectedDevicePerBackend: z.record(z.string(), z.string()).default({}),
/** When true, skip hardware probe and treat Phison SSD as detected (optional overlay in userData settings). */
PhisonSSDdetected: z.boolean().optional().default(false),
})
export type LocalSettings = z.infer<typeof LocalSettingsSchema>
export type ProductMode = z.infer<typeof ProductModeSchema>
function resolveProductMode(s: LocalSettings): string {
return s.productMode === 'essentials'
? 'essentials'
: s.productMode === 'nvidia'
? 'nvidia'
: 'studio'
}
type PresetLoadConfig = {
baseDir: string
modeDir: string
imageFallbackDirs: string[]
includePresets?: string[]
excludePresets?: string[]
excludeVariantBackends?: string[]
}
function getPresetLoadConfig(s: LocalSettings): PresetLoadConfig {
const mode = resolveProductMode(s)
const variant = s.isDemoModeEnabled ? 'demo' : 'presets'
const modeConfig = loadModeConfig(mode)
const basePresetsDir = path.join(modesDir, 'base', 'presets')
// When the Home Agent feature is disabled, drop its bundled preset so it does
// not appear in the chat preset selector. `includePresets` (when defined)
// takes precedence over `excludePresets`, so we need to filter both lists.
const includePresets = s.isHomeAgentEnabled
? modeConfig?.includePresets
: modeConfig?.includePresets?.filter((p) => p !== 'home-agent-chat')
const baseExcludePresets = modeConfig?.excludePresets ?? []
const excludePresets = s.isHomeAgentEnabled
? modeConfig?.excludePresets
: [...baseExcludePresets, 'home-agent-chat']
return {
baseDir: path.join(modesDir, 'base', variant),
modeDir: path.join(modesDir, mode, variant),
imageFallbackDirs: variant === 'demo' ? [basePresetsDir] : [],
includePresets,
excludePresets,
excludeVariantBackends: modeConfig?.excludeVariantBackends,
}
}
function getModeDemoDir(s: LocalSettings): string {
return path.join(modesDir, resolveProductMode(s), 'demo')
}
type PresetFile = { content: string; image: string | null }
function findPresetImage(baseName: string, dirs: string[]): string | null {
for (const dir of dirs) {
for (const ext of ['.png', '.jpg', '.jpeg']) {
const imagePath = path.join(dir, `${baseName}${ext}`)
if (fs.existsSync(imagePath)) return imagePath
}
}
return null
}
async function readPresetsFromDir(
dir: string,
imageFallbackDirs: string[] = [],
): Promise<Map<string, PresetFile>> {
const result = new Map<string, PresetFile>()
if (!fs.existsSync(dir)) return result
await fs.promises.mkdir(dir, { recursive: true })
const files = await fs.promises.readdir(dir)
const presetFiles = files.filter((f) => f.endsWith('.json') && !f.startsWith('_'))
await Promise.all(
presetFiles.map(async (file) => {
const raw = await fs.promises.readFile(path.join(dir, file), { encoding: 'utf-8' })
const content = process.platform !== 'win32' ? raw.replaceAll('\\\\', '/') : raw
const baseName = path.basename(file, '.json')
let imageBase64: string | null = null
const imagePath = findPresetImage(baseName, [dir, ...imageFallbackDirs])
if (imagePath) {
try {
const imageBuffer = await fs.promises.readFile(imagePath)
const ext = path.extname(imagePath).toLowerCase()
const mimeType = ext === '.png' ? 'image/png' : 'image/jpeg'
imageBase64 = `data:${mimeType};base64,${imageBuffer.toString('base64')}`
} catch (error) {
appLogger.warn(`Failed to read image file ${imagePath}: ${error}`, 'electron-backend')
}
}
result.set(baseName, { content, image: imageBase64 })
}),
)
return result
}
function applyPresetFilter(
presets: Map<string, PresetFile>,
config: PresetLoadConfig,
): Map<string, PresetFile> {
if (config.includePresets) {
const allowed = new Set(config.includePresets)
for (const key of presets.keys()) {
if (!allowed.has(key)) presets.delete(key)
}
} else if (config.excludePresets) {
for (const excluded of config.excludePresets) {
presets.delete(excluded)
}
}
if (config.excludeVariantBackends?.length) {
const excludedBackends = new Set(config.excludeVariantBackends)
for (const [key, file] of presets) {
try {
const parsed = JSON.parse(file.content)
if (parsed?.type !== 'comfy' || !Array.isArray(parsed.variants)) continue
const filtered = parsed.variants.filter(
(v: { backend?: string }) => !(v?.backend && excludedBackends.has(v.backend)),
)
if (filtered.length === parsed.variants.length) continue
parsed.variants = filtered
presets.set(key, { ...file, content: JSON.stringify(parsed) })
} catch (e) {
appLogger.warn(`Failed to filter variants for preset "${key}": ${e}`, 'electron-backend')
}
}
}
return presets
}
let settings = LocalSettingsSchema.parse({})
let demoProfile: DemoProfile | null = null
/** Packaged: `resources/settings.json` (same role as dev `external/settings-dev.json`). */
function getPackagedSettingsPath(): string {
return path.join(packagedResourcesRoot(), 'settings.json')
}
/** Dev-only defaults shipped in the repo (read-only for the app). */
function getDevSettingsDefaultsPath(): string {
return path.join(__dirname, '../../external/settings-dev.json')
}
/** Dev: userData overlay so edits do not touch the repo (avoids Vite reload loops). */
function getUserLocalSettingsPath(): string {
return path.join(app.getPath('userData'), 'ai-playground-local-settings.json')
}
/** Packaged: read/write `resources/settings.json`. Dev: read/write userData overlay only. */
function getWritableSettingsPath(): string {
if (app.isPackaged) {
return getPackagedSettingsPath()
}
return getUserLocalSettingsPath()
}
function persistLocalSettingsToDisk(): void {
const settingPath = getWritableSettingsPath()
const parsed = LocalSettingsSchema.parse(settings)
const serialized = JSON.stringify(parsed, null, 2)
const tmpPath = `${settingPath}.${randomUUID()}.tmp`
try {
fs.mkdirSync(path.dirname(settingPath), { recursive: true })
fs.writeFileSync(tmpPath, serialized, { encoding: 'utf8' })
fs.renameSync(tmpPath, settingPath)
} catch (e) {
try {
fs.unlinkSync(tmpPath)
} catch {
// ignore cleanup failure
}
appLogger.error(`failed to persist local settings: ${e}`, 'electron-backend')
}
}
protocol.registerSchemesAsPrivileged([
{
scheme: 'aipg-media',
privileges: {
secure: true,
supportFetchAPI: true, // impotant
standard: true,
bypassCSP: true, // impotant
stream: true,
// Required so canvases can read pixels from `aipg-media://` images
// (mask / outpaint editors call `getImageData()` / `toDataURL()`).
// The handler below must also emit `Access-Control-Allow-Origin`.
corsEnabled: true,
},
},
])
async function loadSettings() {
settings = LocalSettingsSchema.parse({})
if (app.isPackaged) {
const packagedPath = getPackagedSettingsPath()
appLogger.info(`loading packaged settings from ${packagedPath}`, 'electron-backend')
if (fs.existsSync(packagedPath)) {
try {
const raw = JSON.parse(fs.readFileSync(packagedPath, { encoding: 'utf8' }))
settings = LocalSettingsSchema.parse({ ...settings, ...raw })
} catch (e) {
appLogger.error(`failed to load settings: ${e}`, 'electron-backend')
}
}
} else {
const defaultsPath = getDevSettingsDefaultsPath()
let devDefaultsRaw: Record<string, unknown> | null = null
appLogger.info(`loading dev defaults from ${defaultsPath}`, 'electron-backend')
if (fs.existsSync(defaultsPath)) {
try {
devDefaultsRaw = JSON.parse(fs.readFileSync(defaultsPath, { encoding: 'utf8' }))
settings = LocalSettingsSchema.parse({ ...settings, ...devDefaultsRaw })
} catch (e) {
appLogger.error(`failed to load dev defaults: ${e}`, 'electron-backend')
}
}
const userPath = getUserLocalSettingsPath()
appLogger.info(`loading dev user settings from ${userPath}`, 'electron-backend')
if (fs.existsSync(userPath)) {
try {
const raw = JSON.parse(fs.readFileSync(userPath, { encoding: 'utf8' }))
settings = LocalSettingsSchema.parse({ ...settings, ...raw })
} catch (e) {
appLogger.error(`failed to load dev user settings: ${e}`, 'electron-backend')
}
}
// PhisonSSDdetected: true if userData *or* repo settings-dev says so. Repo true still beats
// stale userData false; userData true still works when repo has false (dev Phison UI without hardware).
if (devDefaultsRaw) {
const repoWantsPhison =
'PhisonSSDdetected' in devDefaultsRaw && Boolean(devDefaultsRaw.PhisonSSDdetected)
settings = LocalSettingsSchema.parse({
...settings,
PhisonSSDdetected: Boolean(settings.PhisonSSDdetected) || repoWantsPhison,
})
}
}
appLogger.info(`settings loaded: ${JSON.stringify({ settings })}`, 'electron-backend')
if (settings.isDemoModeEnabled) {
const modeDemoDir = getModeDemoDir(settings)
const baseDemoDir = path.join(modesDir, 'base', 'demo')
try {
demoProfile = loadDemoProfile(modeDemoDir, baseDemoDir, appLogger)
} catch (e) {
appLogger.error(`Failed to load demo profile: ${e}`, 'demo-profile')
}
}
return settings
}
async function createWindow() {
win = new BrowserWindow({
title: 'AI PLAYGROUND',
icon: path.join(process.env.VITE_PUBLIC, 'app-ico.svg'),
transparent: false,
resizable: true,
frame: false,
// fullscreen: true,
width: 1440,
height: 951,
webPreferences: {
preload: path.join(__dirname, '../preload/preload.js'),
contextIsolation: true,
},
})
setWebBrowserMainWindow(win)
win.on('close', () => {
// Tear down the headless web-browser window so the app can quit cleanly.
destroyWebBrowser()
})
// [HA-DIAG] Temporary: surface renderer `[HA-DIAG]` perf logs in the main
// terminal stream (renderer console.log normally only reaches DevTools).
// Remove together with the renderer-side [HA-DIAG] logging.
win.webContents.on('console-message', (event: unknown, ...rest: unknown[]) => {
const e = event as { message?: string }
// Electron 35+ passes a single event object with `.message`; older builds
// pass (event, level, message, line, sourceId).
const message =
typeof e?.message === 'string' ? e.message : ((rest[1] as string | undefined) ?? '')
// Route through appLogger so the line reaches the in-app debug viewer (fed
// by the `debugLog` IPC). appLogger also mirrors back to the renderer, which
// App.vue re-logs as `[ha-diag] <message>` — that re-enters this handler. The
// `[ha-diag]` source prefix (absent from the original renderer line) marks
// the echo, so skipping it breaks the otherwise-infinite loop.
if (message.includes('[HA-DIAG]') && !message.includes('[ha-diag]')) {
appLogger.info(message, 'ha-diag')
}
})
win.webContents.on('did-finish-load', () => {
setTimeout(() => {
appLogger.onWebcontentReady(win!.webContents)
// [HA-DIAG] One-shot marker: if you see this line, the rebuilt main process
// with the renderer-log forwarder is running. If it's absent, main.ts did
// not reload — fully restart Electron (HMR only reloads the renderer).
appLogger.info(
'[HA-DIAG] forwarder installed — renderer perf logs will appear here',
'ha-diag',
)
}, 100)
// Check localStorage for developer settings after page loads
setTimeout(async () => {
try {
const openDevConsoleOnStartup = await win!.webContents.executeJavaScript(
`(() => {
try {
const developerSettings = localStorage.getItem('developerSettings');
if (developerSettings) {
const parsed = JSON.parse(developerSettings);
return parsed.openDevConsoleOnStartup === true;
}
} catch (e) {
return false;
}
return false;
})()`,
)
if (openDevConsoleOnStartup && app.isPackaged && !settings.debug) {
win!.webContents.openDevTools({ mode: 'detach', activate: true })
}
} catch (e) {
appLogger.error(`Failed to check developer settings: ${e}`, 'electron-backend')
}
}, 500)
})
// Pipe renderer console warnings/errors to the app log file. Writes via
// logMessageToFile directly: the regular logger methods echo every message
// back to the renderer's debug stream, which a console-logging renderer
// would turn into a feedback loop. Rate-limited so a hot error loop can't
// bloat the log file (appendFileSync blocks the main process).
const RENDERER_LOG_WINDOW_MS = 1000
const MAX_RENDERER_LOGS_PER_WINDOW = 10
let rendererLogWindowStart = 0
let rendererLogCount = 0
win.webContents.on('console-message', (event) => {
if (event.level !== 'warning' && event.level !== 'error') return
const now = Date.now()
if (now - rendererLogWindowStart > RENDERER_LOG_WINDOW_MS) {
rendererLogWindowStart = now
rendererLogCount = 0
}
if (rendererLogCount < MAX_RENDERER_LOGS_PER_WINDOW) {
appLogger.logMessageToFile(
`[${event.level}] ${event.message} (${event.sourceId}:${event.lineNumber})`,
'renderer',
)
} else if (rendererLogCount === MAX_RENDERER_LOGS_PER_WINDOW) {
appLogger.logMessageToFile(
'rate limit exceeded, suppressing further messages this second',
'renderer',
)
}
rendererLogCount++
})
win.webContents.on('render-process-gone', (_event, details) => {
appLogger.error(
`render-process-gone: reason=${details.reason} exitCode=${details.exitCode}`,
'electron-backend',
true,
)
dialog.showErrorBox(
'AI Playground — Renderer Crashed',
`The application window has crashed unexpectedly.\n\n` +
`Reason: ${details.reason}\n` +
`Exit code: ${details.exitCode}\n\n` +
`Check logs for details:\n${appLogger.pathToLogFiles}`,
)
})
win.webContents.on('did-fail-load', (_event, errorCode, errorDescription, validatedURL) => {
if (errorCode === -3) return // ERR_ABORTED: navigation cancelled, not a failure
appLogger.error(
`did-fail-load: code=${errorCode} desc="${errorDescription}" url="${validatedURL}"`,
'electron-backend',
true,
)
})
const session = win.webContents.session
if (!app.isPackaged || settings.debug) {
//Open devTool if the app is not packaged
win.webContents.openDevTools({ mode: 'detach', activate: true })
}
if (settings.isDemoModeEnabled) {
win.setFullScreen(true)
win.maximize()
win.setKiosk(true)
}
session.webRequest.onBeforeSendHeaders((details, callback) => {
callback({
requestHeaders: {
...details.requestHeaders,
Origin: '*',
},
})
})
session.webRequest.onHeadersReceived((details, callback) => {
if (details.url.match(/^http:\/\/(localhost|127.0.0.1)/)) {
const headers = new Headers()
if (details.responseHeaders) {
for (const [headerName, values] of Object.entries(details.responseHeaders)) {
for (const v of values) {
headers.append(headerName, v)
}
}
}
const append = (name: string, value: string) => {
if (!headers.get(name)?.includes(value)) {
headers.append(name, value)
}
}
// Defer to the upstream backend's `Access-Control-Allow-Origin` if
// it is already set. Otherwise the backend's specific origin (e.g.
// `http://localhost:25413`) gets joined with our wildcard, yielding
// `http://localhost:25413, *` which browsers reject as invalid.
if (!headers.has('Access-Control-Allow-Origin')) {
headers.append('Access-Control-Allow-Origin', '*')
}
append('Access-Control-Allow-Methods', 'GET')
append('Access-Control-Allow-Methods', 'POST')
append('Access-Control-Allow-Headers', 'x-requested-with')
append('Access-Control-Allow-Headers', 'Content-Type')
append('Access-Control-Allow-Headers', 'Authorization')
// Loopback auth token header used by AI Playground's renderer to
// authenticate to the ai-backend Flask service. Must be in the
// preflight allow-list or the browser blocks the request.
append('Access-Control-Allow-Headers', 'X-AIPG-Auth')
details.responseHeaders = Object.fromEntries([...headers.entries()].map(([k, v]) => [k, [v]]))
callback(details)
} else {
return callback(details)
}
})
win.webContents.session.setPermissionRequestHandler((_, permission, callback) => {
if (
permission === 'media' ||
permission === 'clipboard-sanitized-write'
// permission === "clipboard-sanitized-write"
) {
callback(true)
} else {
callback(false)
}
})
if (VITE_DEV_SERVER_URL) {
await win.loadURL(VITE_DEV_SERVER_URL)
appLogger.info('load url:' + VITE_DEV_SERVER_URL, 'electron-backend')
} else {
await win.loadFile(path.join(process.env.DIST, 'index.html'))
}
// Make all links open with the browser, not with the application
win.webContents.setWindowOpenHandler(({ url }) => {
if (url.startsWith('https:')) shell.openExternal(url)
if (url.startsWith('http://localhost')) shell.openExternal(url)
if (url.startsWith('http://127.0.0.1')) shell.openExternal(url)
return { action: 'deny' }
})
return win
}
function spawnLangchainUtilityProcess() {
if (langchainChild) {
appLogger.info('Langchain utility process already running', 'electron-backend')
return
}
appLogger.info('Starting langchain utility process', 'electron-backend')
try {
appLogger.info(path.join(__dirname, '../langchain/langchain.js'), 'electron-backend')
langchainChild = utilityProcess.fork(
path.join(__dirname, '../langchain/langchain.js'),
undefined,
{ stdio: 'pipe' },
)
langchainChild.stdout?.on('data', (data) => {
appLogger.info(data.toString(), 'langchain')
})
langchainChild.stderr?.on('data', (data) => {
appLogger.error(data.toString(), 'langchain')
})
langchainChild.postMessage({
type: 'init',
embeddingCachePath: path.join(externalResourcesDir(), 'embeddingCache'),
})
langchainChild.on('message', (message) => {
appLogger.info(
`Message from langchain utility process: Type ${message.type}`,
'electron-backend',
)
})
langchainChild.on('error', (error) => {
appLogger.error(`Error from langchain utility process: ${error}`, 'electron-backend')
})
langchainChild.on('exit', (code) => {
if (code !== 0) {
appLogger.info(`Langchain utility process exited with code ${code}`, 'electron-backend')
}
setTimeout(() => {
spawnLangchainUtilityProcess()
}, 1000)
langchainChild = null
})
} catch (error) {
appLogger.error(`Error starting langchain utility process: ${error}`, 'electron-backend')
}
}
function handleUtilityFunction<T, R>(
eventType: string,
child: UtilityProcess | null,
args: T,
): Promise<R> {
if (!child) {
throw new Error('Utility process is not running')
}
return new Promise((resolve, reject) => {
const messageHandler = (message: { type: string; returnValue: R }) => {
if (message.type === eventType) {
child.off('message', messageHandler)
resolve(message.returnValue)
}
}
const errorHandler = (type: string, location: string, report: string) => {
const error = new Error(`Error in ${type} at ${location}: ${report}`)
child.off('error', errorHandler)
reject(error)
}
child.on('message', messageHandler)
child.on('error', errorHandler)
child.postMessage({ type: eventType, args: args })
})
}
app.on('before-quit', () => {
destroyWebBrowser()
})
app.on('quit', async () => {
await stopAllMcpServers()
if (singleInstanceLock) {
app.releaseSingleInstanceLock()
}
})
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', async () => {
try {
await stopAllMcpServers()
await serviceRegistry?.stopAllServices()
} catch {}
if (process.platform !== 'darwin') {
app.quit()
win = null
}
})
app.on('activate', () => {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
app.on('second-instance', (_event, _commandLine, _workingDirectory) => {
if (win && !win.isDestroyed()) {
if (win.isMinimized()) {
win.restore()
}
win.focus()
}
})
async function initServiceRegistry(win: BrowserWindow, settings: LocalSettings) {
serviceRegistry = await aiplaygroundApiServiceRegistry(win, settings)
const homeAgent = serviceRegistry.getService('home-agent-backend')
if (homeAgent instanceof HomeAgentBackendService) {
homeAgent.registerIpcHandlers()
}
return serviceRegistry
}
function initEventHandle() {
screen.on('display-metrics-changed', (_event, display, _changedMetrics) => {
if (win) {
win.setBounds({
x: 0,
y: 0,
width: display.workAreaSize.width,
height: display.workAreaSize.height,
})
win.webContents.send(
'display-metrics-changed',
display.workAreaSize.width,
display.workAreaSize.height,
)
}
})
ipcMain.handle('getThemeSettings', async () => {
return {
availableThemes: settings.availableThemes,
currentTheme: settings.currentTheme,
}
})
ipcMain.handle('getLocaleSettings', async () => {
return {
locale: app.getLocale(),
languageOverride: settings.languageOverride,
}
})
ipcMain.handle('getLocalSettings', () => {
return LocalSettingsSchema.parse(settings)
})
ipcMain.handle('updateLocalSettings', (_event, updates: Partial<LocalSettings>) => {
Object.assign(settings, updates)
const shouldReloadDemoProfile =
settings.isDemoModeEnabled && ('productMode' in updates || 'isDemoModeEnabled' in updates)
if (shouldReloadDemoProfile) {
const modeDemoDir = getModeDemoDir(settings)
const baseDemoDir = path.join(modesDir, 'base', 'demo')
try {
demoProfile = loadDemoProfile(modeDemoDir, baseDemoDir, appLogger)
} catch (e) {
appLogger.error(`Failed to reload demo profile after settings change: ${e}`, 'demo-profile')
}
}
persistLocalSettingsToDisk()
appLogger.info(`Updated local settings: ${JSON.stringify(updates)}`, 'electron-backend')
return { success: true }
})
ipcMain.handle('detectHardwareForModeRecommendation', async () => {
let detected: GpuHardwareDevice[] = []
let hasNvidia = false
let detectSuccess = true
try {
const probe = await detectGpuHardwareDevices()
detected = probe.detected
hasNvidia = probe.hasNvidia
appLogger.info(`Detected GPU devices: ${JSON.stringify(detected)}`, 'electron-backend')
appLogger.info(`Has NVIDIA: ${hasNvidia}`, 'electron-backend')
} catch (e) {
detectSuccess = false
appLogger.warn(`GPU detection failed: ${e}`, 'electron-backend')
}
const configs = loadProductModeConfigs()
const modeCatalog = configs
.sort((a, b) => a.displayOrder - b.displayOrder)
.map((c) => ({
mode: c.mode,
experimental: c.experimental,
ui: c.ui,
}))
const gpuIds = detected
.map((d) => d.gpuDeviceId)
.filter((id): id is string => id !== null)
.map((id) => id.toLowerCase())
// Highest priority wins.
const eligible = configs
.filter((c) => c.mode !== 'nvidia' || hasNvidia)
.filter((c) => {
if (c.mode === 'nvidia') return c.recommendForNvidia === true
if (!c.recommendForIntelDeviceIds.length) return false
if (gpuIds.length === 0) return false
return gpuIds.some((id) => c.recommendForIntelDeviceIds.includes(id))
})
.sort((a, b) => b.priority - a.priority)
const recommendedMode: ProductMode = eligible[0]?.mode ?? 'studio'