Repository navigation
Expand file tree
/
Copy pathindex.ts
More file actions
1430 lines (1275 loc) · 45.6 KB
/
Copy pathindex.ts
File metadata and controls
1430 lines (1275 loc) · 45.6 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
/**
* Milady Desktop App — Electrobun Main Entry
*
* Creates the main BrowserWindow, wires up RPC handlers,
* sets up system tray, application menu, and starts the agent.
*/
import fs from "node:fs";
import { createServer as createNetServer } from "node:net";
import os from "node:os";
import path from "node:path";
import Electrobun, {
ApplicationMenu,
BrowserWindow,
Updater,
Utils,
WGPU,
webgpu,
} from "electrobun/bun";
import {
pushApiBaseToRenderer,
resolveDesktopRuntimeMode,
resolveInitialApiBase,
} from "./api-base";
import {
buildApplicationMenu,
EMPTY_HEARTBEAT_MENU_SNAPSHOT,
type HeartbeatMenuSnapshot,
parseSettingsWindowAction,
} from "./application-menu";
import { showBackgroundNoticeOnce } from "./background-notice";
import {
type CloudAuthWindowLike,
CloudAuthWindowManager,
readNavigationEventUrl,
} from "./cloud-auth-window";
import { configureDesktopLocalApiAuth, getAgentManager } from "./native/agent";
import { getDesktopManager } from "./native/desktop";
import { disposeNativeModules, initializeNativeModules } from "./native/index";
import {
enableVibrancy,
ensureShadow,
setNativeDragRegion,
setTrafficLightsPosition,
} from "./native/mac-window-effects";
import { getPermissionManager } from "./native/permissions";
import { checkWebGpuSupport } from "./native/webgpu-browser-support";
import { readBuiltPreloadScript } from "./preload-validation";
import { registerRpcHandlers } from "./rpc-handlers";
import { PUSH_CHANNEL_TO_RPC_MESSAGE } from "./rpc-schema";
import {
isDetachedSurface,
type ManagedWindowLike,
SurfaceWindowManager,
} from "./surface-windows";
type SendToWebview = (message: string, payload?: unknown) => void;
type HeartbeatMenuTriggerSummary = {
enabled: boolean;
nextRunAtMs?: number;
lastRunAtIso?: string;
};
type HeartbeatMenuHealthResponse = {
activeTriggers?: number;
totalExecutions?: number;
totalFailures?: number;
lastExecutionAt?: number;
};
const HEARTBEAT_MENU_REFRESH_MS = 30_000;
const CONFIG_EXPORT_FILE_NAME = "milady-config.json";
// Browser surface stays off by default until the packaged WebGPU/browser path
// is hardened across the supported desktop release targets.
const BROWSER_SURFACE_ENABLED =
process.env.MILADY_ENABLE_BROWSER_SURFACE === "1";
let heartbeatMenuSnapshot: HeartbeatMenuSnapshot =
EMPTY_HEARTBEAT_MENU_SNAPSHOT;
let heartbeatMenuRefreshTimer: ReturnType<typeof setInterval> | null = null;
// ============================================================================
// App Menu
// ============================================================================
import {
isAgentReady,
onAgentReadyChange,
setAgentReady,
} from "./agent-ready-state";
import { DEFAULT_PORT } from "./constants";
function setupApplicationMenu(): void {
const isMac = process.platform === "darwin";
const menu = buildApplicationMenu({
isMac,
browserEnabled: BROWSER_SURFACE_ENABLED,
heartbeatSnapshot: heartbeatMenuSnapshot,
detachedWindows: surfaceWindowManager?.listWindows() ?? [],
agentReady: isAgentReady(),
});
ApplicationMenu.setApplicationMenu(
menu as unknown as Parameters<typeof ApplicationMenu.setApplicationMenu>[0],
);
}
// Refresh the application menu whenever agent readiness changes.
onAgentReadyChange(() => setupApplicationMenu());
function summarizeDesktopActionError(error: unknown, fallback: string): string {
const message = error instanceof Error ? error.message : fallback;
const trimmed = message.trim();
if (!trimmed) return fallback;
return trimmed.length > 80 ? `${trimmed.slice(0, 77)}...` : trimmed;
}
function summarizeHeartbeatMenuError(error: unknown): string {
return summarizeDesktopActionError(error, "Heartbeat status unavailable");
}
function buildApiRequestHeaders(contentType?: string): Record<string, string> {
const headers: Record<string, string> = {
Accept: "application/json",
};
if (contentType) {
headers["Content-Type"] = contentType;
}
const apiToken =
process.env.MILADY_API_TOKEN?.trim() ?? process.env.ELIZA_API_TOKEN?.trim();
if (apiToken) {
headers.Authorization = `Bearer ${apiToken}`;
}
return headers;
}
function resolveHeartbeatMenuApiBase(): string | null {
const port = getAgentManager().getStatus().port;
if (typeof port === "number" && port > 0) {
return `http://127.0.0.1:${port}`;
}
return resolveInitialApiBase(process.env);
}
async function fetchHeartbeatMenuSnapshot(
apiBase: string,
): Promise<HeartbeatMenuSnapshot> {
const headers = buildApiRequestHeaders();
const [triggersResponse, healthResponse] = await Promise.all([
fetch(`${apiBase}/api/triggers`, { headers }),
fetch(`${apiBase}/api/triggers/health`, { headers }),
]);
if (!triggersResponse.ok) {
throw new Error(`Trigger list failed (${triggersResponse.status})`);
}
if (!healthResponse.ok) {
throw new Error(`Trigger health failed (${healthResponse.status})`);
}
const triggersPayload = (await triggersResponse.json()) as {
triggers?: HeartbeatMenuTriggerSummary[];
};
const healthPayload =
(await healthResponse.json()) as HeartbeatMenuHealthResponse;
const triggers = Array.isArray(triggersPayload.triggers)
? triggersPayload.triggers
: [];
const enabledTriggers = triggers.filter((trigger) => trigger.enabled);
const nextRunCandidates = enabledTriggers
.map((trigger) =>
typeof trigger.nextRunAtMs === "number" ? trigger.nextRunAtMs : null,
)
.filter((value): value is number => typeof value === "number");
const lastRunCandidates = triggers
.map((trigger) => {
if (!trigger.lastRunAtIso) return null;
const parsed = Date.parse(trigger.lastRunAtIso);
return Number.isNaN(parsed) ? null : parsed;
})
.filter((value): value is number => typeof value === "number");
return {
loading: false,
error: null,
totalHeartbeats: triggers.length,
activeHeartbeats:
typeof healthPayload.activeTriggers === "number"
? healthPayload.activeTriggers
: enabledTriggers.length,
totalExecutions:
typeof healthPayload.totalExecutions === "number"
? healthPayload.totalExecutions
: 0,
totalFailures:
typeof healthPayload.totalFailures === "number"
? healthPayload.totalFailures
: 0,
lastRunAtMs:
typeof healthPayload.lastExecutionAt === "number"
? healthPayload.lastExecutionAt
: lastRunCandidates.length > 0
? Math.max(...lastRunCandidates)
: null,
nextRunAtMs:
nextRunCandidates.length > 0 ? Math.min(...nextRunCandidates) : null,
};
}
async function refreshHeartbeatMenuSnapshot(): Promise<void> {
const apiBase = resolveHeartbeatMenuApiBase();
if (!apiBase) {
heartbeatMenuSnapshot = {
...heartbeatMenuSnapshot,
loading: false,
error: "Agent unavailable",
};
setupApplicationMenu();
return;
}
try {
heartbeatMenuSnapshot = await fetchHeartbeatMenuSnapshot(apiBase);
} catch (error) {
heartbeatMenuSnapshot = {
...heartbeatMenuSnapshot,
loading: false,
error: summarizeHeartbeatMenuError(error),
};
}
setupApplicationMenu();
}
function startHeartbeatMenuRefresh(): void {
if (heartbeatMenuRefreshTimer) return;
void refreshHeartbeatMenuSnapshot();
heartbeatMenuRefreshTimer = setInterval(() => {
void refreshHeartbeatMenuSnapshot();
}, HEARTBEAT_MENU_REFRESH_MS);
}
// ============================================================================
// macOS Native Window Effects (vibrancy, shadow, traffic lights, drag region)
// ============================================================================
const MAC_TRAFFIC_LIGHTS_X = 14;
const MAC_TRAFFIC_LIGHTS_Y = 12;
const MAC_NATIVE_DRAG_REGION_X = 92;
const MAC_NATIVE_DRAG_REGION_HEIGHT = 40;
function applyMacOSWindowEffects(win: BrowserWindow): void {
if (process.platform !== "darwin") return;
const ptr = (win as { ptr?: unknown }).ptr;
if (!ptr) {
console.warn("[MacEffects] win.ptr unavailable — skipping native effects");
return;
}
enableVibrancy(ptr as Parameters<typeof enableVibrancy>[0]);
ensureShadow(ptr as Parameters<typeof ensureShadow>[0]);
const alignButtons = () =>
setTrafficLightsPosition(
ptr as Parameters<typeof setTrafficLightsPosition>[0],
MAC_TRAFFIC_LIGHTS_X,
MAC_TRAFFIC_LIGHTS_Y,
);
const alignDragRegion = () =>
setNativeDragRegion(
ptr as Parameters<typeof setNativeDragRegion>[0],
MAC_NATIVE_DRAG_REGION_X,
MAC_NATIVE_DRAG_REGION_HEIGHT,
);
alignButtons();
alignDragRegion();
setTimeout(() => {
alignButtons();
alignDragRegion();
}, 120);
win.on("resize", () => {
alignButtons();
alignDragRegion();
});
console.log("[MacEffects] Native macOS window effects applied");
}
// ============================================================================
// Window State Persistence
// ============================================================================
interface WindowState {
x: number;
y: number;
width: number;
height: number;
}
const DEFAULT_WINDOW_STATE: WindowState = {
x: 100,
y: 100,
width: 1200,
height: 800,
};
function loadWindowState(statePath: string): WindowState {
try {
if (fs.existsSync(statePath)) {
const data = JSON.parse(fs.readFileSync(statePath, "utf8"));
if (typeof data.width === "number" && typeof data.height === "number") {
return { ...DEFAULT_WINDOW_STATE, ...data };
}
}
} catch {
// Ignore parse/read errors — return default
}
return DEFAULT_WINDOW_STATE;
}
let saveTimer: ReturnType<typeof setTimeout> | null = null;
function scheduleStateSave(statePath: string, win: BrowserWindow): void {
if (saveTimer) clearTimeout(saveTimer);
saveTimer = setTimeout(() => {
try {
const { x, y } = win.getPosition();
const { width, height } = win.getSize();
const dir = path.dirname(statePath);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(
statePath,
JSON.stringify({ x, y, width, height }),
"utf8",
);
} catch {
// Ignore save errors
}
}, 500);
}
// ============================================================================
// Main Window
// ============================================================================
let currentWindow: BrowserWindow | null = null;
let currentSendToWebview: SendToWebview | null = null;
let surfaceWindowManager: SurfaceWindowManager | null = null;
let cloudAuthWindowManager: CloudAuthWindowManager | null = null;
let rendererUrlPromise: Promise<string> | null = null;
let backgroundWindowPromise: Promise<void> | null = null;
let isQuitting = false;
let lastFocusedWindow: ManagedWindowLike | null = null;
function sendToActiveRenderer(message: string, payload?: unknown): void {
currentSendToWebview?.(message, payload);
if (!currentSendToWebview)
console.debug("[Main] Dropped renderer message (no window):", message);
}
// ============================================================================
// Renderer Static Server
// ============================================================================
/**
* Serve the renderer dist over HTTP so WKWebView can load it without
* file:// CORS restrictions (crossorigin ES modules break over file://).
* Returns the base URL e.g. "http://localhost:5174".
*/
async function startRendererServer(): Promise<string> {
const rendererDir = path.resolve(import.meta.dir, "../renderer");
if (!fs.existsSync(rendererDir)) {
console.warn("[Renderer] renderer dir not found:", rendererDir);
return "";
}
// Find a free port starting at 5174 (5173 reserved for Vite dev)
const getPort = (start: number): Promise<number> =>
new Promise((resolve) => {
const srv = createNetServer();
srv.listen(start, "127.0.0.1", () => {
const { port } = srv.address() as { port: number };
srv.close(() => resolve(port));
});
srv.on("error", () => resolve(getPort(start + 1)));
});
const port = await getPort(5174);
const mimeTypes: Record<string, string> = {
".html": "text/html; charset=utf-8",
".js": "application/javascript",
".mjs": "application/javascript",
".css": "text/css",
".png": "image/png",
".jpg": "image/jpeg",
".svg": "image/svg+xml",
".ico": "image/x-icon",
".json": "application/json",
".gz": "application/octet-stream",
".wasm": "application/wasm",
".glb": "model/gltf-binary",
".gltf": "model/gltf+json",
};
// Determine the expected agent API base URL so we can inject it into the
// HTML before the renderer JS runs. This prevents a 404 fatal-error loop
// where the renderer fetches /api/auth/status relative to the static server.
// If the agent falls back to a dynamic port, apiBaseUpdate messages will
// update window.__MILADY_API_BASE__ and the client will pick it up lazily.
const initialApiBase = resolveInitialApiBase(
process.env as Record<string, string | undefined>,
);
const initialApiToken =
resolveDesktopRuntimeMode(process.env as Record<string, string | undefined>)
.mode === "local"
? configureDesktopLocalApiAuth()
: (process.env.MILADY_API_TOKEN?.trim() ??
process.env.ELIZA_API_TOKEN?.trim() ??
"");
// Inject the API base into index.html so it's available before React mounts.
function injectApiBaseIntoHtml(html: string): string {
if (!initialApiBase) {
return html;
}
const script = `<script>window.__MILADY_API_BASE__=${JSON.stringify(initialApiBase)};${initialApiToken ? `Object.defineProperty(window,"__MILADY_API_TOKEN__",{value:${JSON.stringify(initialApiToken)},configurable:true,writable:true,enumerable:false});` : ""}</script>`;
// Inject before </head> if present, otherwise before <body>
if (html.includes("</head>")) {
return html.replace("</head>", `${script}</head>`);
}
if (html.includes("<body")) {
return html.replace("<body", `${script}<body`);
}
return script + html;
}
Bun.serve({
port,
hostname: "127.0.0.1",
fetch(req) {
const urlPath =
new URL(req.url).pathname.replace(/^\//, "") || "index.html";
let filePath = path.join(rendererDir, urlPath);
// Path traversal guard: ensure resolved path stays within rendererDir
if (
!filePath.startsWith(rendererDir + path.sep) &&
filePath !== rendererDir
) {
filePath = path.join(rendererDir, "index.html");
}
let isGzipped = false;
let requestedExt = path.extname(filePath);
// Check for pre-compressed .gz file if the uncompressed file doesn't exist
if (!fs.existsSync(filePath) && fs.existsSync(`${filePath}.gz`)) {
filePath = `${filePath}.gz`;
isGzipped = true;
}
// SPA fallback — serve index.html for unknown paths
if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory()) {
filePath = path.join(rendererDir, "index.html");
requestedExt = ".html";
isGzipped = false;
}
try {
const content = fs.readFileSync(filePath);
// Inject API base into HTML responses
if (requestedExt === ".html" || filePath.endsWith("index.html")) {
const html = injectApiBaseIntoHtml(content.toString("utf8"));
return new Response(html, {
headers: {
"Content-Type": "text/html; charset=utf-8",
"Access-Control-Allow-Origin": "*",
},
});
}
const headers: Record<string, string> = {
"Content-Type": mimeTypes[requestedExt] ?? "application/octet-stream",
"Access-Control-Allow-Origin": "*",
};
if (isGzipped) {
headers["Content-Encoding"] = "gzip";
}
return new Response(content, { headers });
} catch {
return new Response("Not found", { status: 404 });
}
},
});
console.log(`[Renderer] Static server on http://127.0.0.1:${port}`);
return `http://127.0.0.1:${port}`;
}
async function resolveRendererUrl(): Promise<string> {
// Resolve the renderer URL — prefer env override (dev HMR), then built-in static server
let rendererUrl =
process.env.MILADY_RENDERER_URL ?? process.env.VITE_DEV_SERVER_URL ?? "";
if (!rendererUrl) {
rendererUrlPromise ??= startRendererServer();
rendererUrl = await rendererUrlPromise;
}
if (!rendererUrl) {
// Last resort: file:// (may have CORS issues with crossorigin module scripts)
rendererUrl = `file://${path.resolve(import.meta.dir, "../renderer/index.html")}`;
console.warn(
"[Main] Falling back to file:// renderer URL — CORS issues possible",
);
}
return rendererUrl;
}
async function createMainWindow(): Promise<BrowserWindow> {
const rendererUrl = await resolveRendererUrl();
// Load persisted window state
const statePath = path.join(Utils.paths.userData, "window-state.json");
const state = loadWindowState(statePath);
// Read the pre-built webview bridge preload (built by `bun run build:preload`).
// The preload runs in the webview context after Electrobun's built-in preload,
// setting up Milady's direct Electrobun RPC bridge on the window.
let preload: string;
try {
preload = readBuiltPreloadScript(import.meta.dir);
} catch (err) {
console.error("[Main] Failed to read preload script:", err);
preload = "// preload unavailable";
}
const win = new BrowserWindow({
title: "Milady",
url: rendererUrl,
preload,
frame: {
width: state.width,
height: state.height,
x: state.x,
y: state.y,
},
// hiddenInset hides the title bar and insets traffic lights — macOS only.
// On Windows/Linux use the default title bar so the window remains draggable.
titleBarStyle: process.platform === "darwin" ? "hiddenInset" : "default",
// Transparent background for vibrancy — macOS only.
// On Windows/Linux a solid background prevents rendering artifacts.
transparent: process.platform === "darwin",
});
// Apply native macOS vibrancy, shadow, and traffic light positioning
applyMacOSWindowEffects(win);
// Persist window state on resize and move
win.on("resize", () => scheduleStateSave(statePath, win));
win.on("move", () => scheduleStateSave(statePath, win));
return win;
}
function attachMainWindow(win: BrowserWindow): BrowserWindow {
const sendToWebview = wireRpcAndModules(win);
currentWindow = win;
currentSendToWebview = sendToWebview;
trackFocusedWindow(win);
win.webview.on("dom-ready", () => {
injectApiBase(win);
});
// Prevent the main webview from navigating to external URLs.
// The renderer is always served from localhost — any other navigation
// (e.g. from a compromised plugin) should open in the default browser.
win.webview.on("will-navigate", (event: unknown) => {
const e = event as {
url?: string;
data?: { detail?: string };
preventDefault?: () => void;
};
const url = readNavigationEventUrl(e);
try {
const parsed = new URL(url);
const isAllowed =
parsed.protocol === "file:" ||
parsed.hostname === "localhost" ||
parsed.hostname === "127.0.0.1" ||
parsed.protocol === "views:";
if (!isAllowed) {
e.preventDefault?.();
void import("electrobun/bun")
.then(({ Utils }) => {
try {
Utils.openExternal(url);
} catch {
// Ignore external open failures during navigation blocking.
}
})
.catch(() => {});
}
} catch {
// Unparseable URL — block it.
e.preventDefault?.();
}
});
win.on("close", () => {
if (currentWindow?.id === win.id) {
currentWindow = null;
currentSendToWebview = null;
}
if (!isQuitting) {
void ensureBackgroundWindow();
}
});
return win;
}
async function ensureBackgroundWindow(): Promise<void> {
if (isQuitting || currentWindow || backgroundWindowPromise) {
return;
}
backgroundWindowPromise = (async () => {
const replacementWindow = attachMainWindow(await createMainWindow());
try {
replacementWindow.minimize();
console.log("[Main] Recreated minimized window after close");
showBackgroundRunNoticeOnce();
} catch (err) {
console.warn("[Main] Failed to minimize background window:", err);
}
injectApiBase(replacementWindow);
})().finally(() => {
backgroundWindowPromise = null;
});
await backgroundWindowPromise;
}
function showBackgroundRunNoticeOnce(): void {
try {
showBackgroundNoticeOnce({
fileSystem: fs,
userDataDir: Utils.paths.userData,
showNotification: (options) => {
Utils.showNotification(options);
},
});
} catch (error) {
console.warn("[Main] Failed to persist background notice marker:", error);
}
}
// ============================================================================
// Settings Window
// ============================================================================
async function createSettingsWindow(tabHint?: string): Promise<void> {
if (!surfaceWindowManager) return;
await surfaceWindowManager.openSettingsWindow(tabHint);
}
function showMainSurface(surface: string): void {
void getDesktopManager().showWindow();
sendToActiveRenderer("desktopTrayMenuClick", {
itemId: `show-main:${surface}`,
});
}
function resolveDefaultDialogPath(): string {
const downloadsPath = path.join(os.homedir(), "Downloads");
return fs.existsSync(downloadsPath) ? downloadsPath : os.homedir();
}
async function exportConfigFromMenu(): Promise<void> {
const apiBase = resolveHeartbeatMenuApiBase();
if (!apiBase) {
Utils.showNotification({
title: "Config Export Failed",
body: "Agent unavailable",
});
return;
}
try {
const response = await fetch(`${apiBase}/api/config`, {
headers: buildApiRequestHeaders(),
});
if (!response.ok) {
throw new Error(`Config fetch failed (${response.status})`);
}
const config = await response.json();
const dialog = await getDesktopManager().showSaveDialog({
defaultPath: resolveDefaultDialogPath(),
allowedFileTypes: "json",
});
if (dialog.canceled || dialog.filePaths.length === 0) {
return;
}
const outputPath = path.join(dialog.filePaths[0], CONFIG_EXPORT_FILE_NAME);
fs.writeFileSync(
outputPath,
`${JSON.stringify(config, null, 2)}\n`,
"utf8",
);
Utils.showNotification({
title: "Config Exported",
body: `Saved to ${outputPath}`,
});
} catch (error) {
Utils.showNotification({
title: "Config Export Failed",
body: summarizeDesktopActionError(error, "Config export failed"),
});
}
}
async function importConfigFromMenu(): Promise<void> {
const apiBase = resolveHeartbeatMenuApiBase();
if (!apiBase) {
Utils.showNotification({
title: "Config Import Failed",
body: "Agent unavailable",
});
return;
}
try {
const dialog = await getDesktopManager().showOpenDialog({
defaultPath: resolveDefaultDialogPath(),
allowedFileTypes: "json",
canChooseFiles: true,
canChooseDirectory: false,
allowsMultipleSelection: false,
});
if (dialog.canceled || dialog.filePaths.length === 0) {
return;
}
const inputPath = dialog.filePaths[0];
const rawConfig = fs.readFileSync(inputPath, "utf8");
const parsedConfig = JSON.parse(rawConfig) as unknown;
if (
typeof parsedConfig !== "object" ||
parsedConfig === null ||
Array.isArray(parsedConfig)
) {
throw new Error("Config file must contain a JSON object");
}
const response = await fetch(`${apiBase}/api/config`, {
method: "PUT",
headers: buildApiRequestHeaders("application/json"),
body: JSON.stringify(parsedConfig),
});
if (!response.ok) {
throw new Error(`Config import failed (${response.status})`);
}
Utils.showNotification({
title: "Config Imported",
body: `Loaded ${path.basename(inputPath)}`,
});
} catch (error) {
Utils.showNotification({
title: "Config Import Failed",
body: summarizeDesktopActionError(error, "Config import failed"),
});
}
}
function trackFocusedWindow(window: ManagedWindowLike): void {
lastFocusedWindow = window;
window.on("focus", () => {
lastFocusedWindow = window;
});
}
function toggleFocusedWindowDevTools(): void {
const targetWindow = lastFocusedWindow ?? currentWindow;
const webview = targetWindow?.webview as
| {
toggleDevTools?: () => void;
openDevTools?: () => void;
}
| undefined;
if (typeof webview?.toggleDevTools === "function") {
webview.toggleDevTools();
return;
}
if (typeof webview?.openDevTools === "function") {
webview.openDevTools();
return;
}
Utils.showNotification({
title: "Developer Tools Unavailable",
body: "The focused window does not expose Electrobun devtools controls.",
});
}
// ============================================================================
// RPC + Native Module Wiring
// ============================================================================
// Type alias for the untyped rpc send proxy (used at runtime for push messages)
type RpcSendProxy = Record<string, ((payload: unknown) => void) | undefined>;
/**
* Structural type for the Electrobun RPC instance.
* The actual runtime object returned by createRPC exposes `send` and
* `setRequestHandler`, but the base RPCWithTransport interface only has
* `setTransport`. We use a structural type to avoid casts.
*
* `(params: never) => unknown` for handler values: any typed handler
* `(p: T) => R` satisfies this via TypeScript's function contravariance
* (`never extends T` is always true).
*/
type ElectrobunRpcInstance = {
send?: RpcSendProxy;
setRequestHandler?: (
handlers: Record<string, (params: never) => unknown>,
) => void;
};
function wireRpcAndModules(
win: BrowserWindow,
): (message: string, payload?: unknown) => void {
// Access the rpc instance from the webview (set during window creation)
const rpc = win.webview.rpc as ElectrobunRpcInstance | undefined;
// Create the sendToWebview callback that native modules use to push events.
// Uses typed RPC push messages instead of JS evaluation.
const sendToWebview = (message: string, payload?: unknown): void => {
// Resolve via map (legacy colon-separated format) or use message directly
// as the RPC method name (Electrobun camelCase format).
const rpcMessage = PUSH_CHANNEL_TO_RPC_MESSAGE[message] ?? message;
if (rpc?.send) {
const sender = rpc?.send?.[rpcMessage];
if (sender) {
sender(payload ?? null);
return;
}
}
console.warn(`[sendToWebview] No RPC method for message: ${message}`);
};
// Initialize native modules with window + sendToWebview
initializeNativeModules(win, sendToWebview);
// Register RPC handlers
registerRpcHandlers(rpc, sendToWebview);
return sendToWebview;
}
/**
* Wire RPC handlers on a secondary window (e.g. settings) without calling
* initializeNativeModules — avoids overwriting the main window reference on
* DesktopManager and other singletons.
*/
function wireSettingsRpc(win: BrowserWindow): void {
const rpc = win.webview.rpc as unknown as ElectrobunRpcInstance | undefined;
const sendToWebview = (message: string, payload?: unknown): void => {
const rpcMessage = PUSH_CHANNEL_TO_RPC_MESSAGE[message] ?? message;
if (rpc?.send) {
const sender = rpc?.send?.[rpcMessage];
if (sender) {
sender(payload ?? null);
return;
}
}
console.warn(
`[sendToWebview:settings] No RPC method for message: ${message}`,
);
};
// Register request handlers on the settings window's RPC — reuses the same
// handler registry but does not touch native module singletons.
registerRpcHandlers(rpc, sendToWebview);
}
// ============================================================================
// API Base Injection
// ============================================================================
function injectApiBase(win: BrowserWindow): void {
const runtimeResolution = resolveDesktopRuntimeMode(
process.env as Record<string, string | undefined>,
);
if (runtimeResolution.externalApi.invalidSources.length > 0) {
console.warn(
`[Main] Invalid API base env vars: ${runtimeResolution.externalApi.invalidSources.join(", ")}`,
);
}
if (
runtimeResolution.mode === "external" &&
runtimeResolution.externalApi.base
) {
pushApiBaseToRenderer(
win,
runtimeResolution.externalApi.base,
process.env.MILADY_API_TOKEN,
);
setAgentReady(true);
return;
}
const agent = getAgentManager();
const port =
agent.getPort() ?? (Number(process.env.MILADY_PORT) || DEFAULT_PORT);
const apiToken = configureDesktopLocalApiAuth();
pushApiBaseToRenderer(win, `http://127.0.0.1:${port}`, apiToken);
setAgentReady(true);
}
// ============================================================================
// Agent Startup
// ============================================================================
/**
* Push real OS permission states into the agent REST API so the renderer's
* PermissionsSection shows correct statuses and capability toggles unlock.
*/
async function syncPermissionsToRestApi(
port: number,
startup = false,
): Promise<void> {
try {
const permissions = await getPermissionManager().checkAllPermissions();
await fetch(`http://127.0.0.1:${port}/api/permissions/state`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ permissions, startup }),
});
} catch (err) {
console.warn("[Main] Permission sync failed:", err);
}
}
async function _startAgent(win: BrowserWindow): Promise<void> {
const runtimeResolution = resolveDesktopRuntimeMode(
process.env as Record<string, string | undefined>,
);
if (runtimeResolution.mode !== "local") {
console.log(
`[Main] Skipping embedded agent startup (${runtimeResolution.mode} mode)`,
);
injectApiBase(win);
return;
}
const agent = getAgentManager();
const apiToken = configureDesktopLocalApiAuth();
try {
const status = await agent.start();
if (status.state === "running" && status.port) {
pushApiBaseToRenderer(win, `http://127.0.0.1:${status.port}`, apiToken);
setAgentReady(true);
// Sync real OS permission states to the REST API so the renderer
// can display them and capability toggles can unlock.
// Pass startup=true so the backend skips scheduling a restart for
// capabilities that are being auto-enabled for the first time.
syncPermissionsToRestApi(status.port, true);
}
} catch (err) {
console.error("[Main] Agent start failed:", err);
}
}
// ============================================================================
// Auto-Updater
// ============================================================================