-
Notifications
You must be signed in to change notification settings - Fork 264
Expand file tree
/
Copy pathindex.ts
More file actions
1925 lines (1729 loc) Β· 56.2 KB
/
Copy pathindex.ts
File metadata and controls
1925 lines (1729 loc) Β· 56.2 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 { execFileSync } from "node:child_process";
import { existsSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import * as Sentry from "@sentry/electron/main";
import {
BrowserWindow,
Menu,
type MenuItemConstructorOptions,
Tray,
app,
crashReporter,
dialog,
globalShortcut,
nativeImage,
nativeTheme,
powerMonitor,
powerSaveBlocker,
session,
shell,
} from "electron";
import { getOpenclawSkillsDir } from "../shared/desktop-paths";
import type {
DesktopChromeMode,
DesktopSurface,
HostDesktopCommand,
} from "../shared/host";
import { buildChildProcessProxyEnv } from "../shared/proxy-config";
import { getDesktopRuntimeConfig } from "../shared/runtime-config";
import { getDesktopSentryBuildMetadata } from "../shared/sentry-build-metadata";
import {
shouldEnableDesktopUpdateManager,
shouldStartDesktopPeriodicUpdateChecks,
} from "../shared/update-policy";
import { getDesktopAppRoot, getWorkspaceRoot } from "../shared/workspace-paths";
import { DesktopDiagnosticsReporter } from "./desktop-diagnostics";
import { exportDiagnostics } from "./diagnostics-export";
import {
registerIpcHandlers,
setComponentUpdater,
setQuitFallback,
setQuitHandlerOpts,
setUpdateManager,
} from "./ipc";
import { getDesktopRuntimePlatformAdapter } from "./platforms";
import { resolveLaunchdPaths } from "./platforms/mac/launchd-paths";
import type { PrepareForUpdateInstallArgs } from "./platforms/types";
import { RuntimeOrchestrator } from "./runtime/daemon-supervisor";
import {
buildSkillNodePath,
checkOpenclawExtractionNeeded,
createRuntimeUnitManifests,
extractOpenclawSidecarAsync,
} from "./runtime/manifests";
import {
type PortAllocation,
PortAllocationError,
allocateDesktopRuntimePorts,
} from "./runtime/port-allocation";
import {
flushRuntimeLoggers,
rotateDesktopLogSession,
writeDesktopMainLog,
} from "./runtime/runtime-logger";
import {
type LaunchdBootstrapResult,
SERVICE_LABELS,
bootstrapWithLaunchd,
getDefaultPlistDir,
getLogDir,
installLaunchdQuitHandler,
runTeardownAndExit,
teardownLaunchdServices,
} from "./services";
import {
type DesktopShellPreferences,
applyDesktopShellPreferencesOnStartup,
getDesktopShellPreferences,
setDesktopShellPreferencesRuntimeHandler,
} from "./services/desktop-shell-preferences";
import {
startDesktopDevInspectServer,
stopDesktopDevInspectServer,
} from "./services/dev-inspect-server";
import { isLaunchdBootstrapEnabled } from "./services/launchd-bootstrap";
import { ProxyManager } from "./services/proxy-manager";
import { flushV8CoverageIfEnabled } from "./services/v8-coverage";
import { readPendingWindowsUserDataMigration } from "./services/windows-user-data-migration";
import { SleepGuard, type SleepGuardLogEntry } from "./sleep-guard";
import { ComponentUpdater } from "./updater/component-updater";
import { StartupHealthCheck } from "./updater/rollback";
import { UpdateManager } from "./updater/update-manager";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Set display name early (matches productName in package.json).
app.setName("nexu");
nativeTheme.themeSource = "light";
const hasSingleInstanceLock = app.requestSingleInstanceLock();
if (!hasSingleInstanceLock) {
app.quit();
process.exit(0);
}
// Info.plist declares LSUIElement=true so that child processes (spawned with
// ELECTRON_RUN_AS_NODE) don't create extra Dock icons. Show the dock icon
// BEFORE any blocking initialization (tar extraction, directory creation, etc.)
// so users see it immediately on first launch.
void app.dock?.show();
const electronRoot = app.isPackaged
? process.resourcesPath
: getDesktopAppRoot();
const baseRuntimeConfig = getDesktopRuntimeConfig(process.env, {
appVersion: app.getVersion(),
resourcesPath: app.isPackaged ? electronRoot : undefined,
useBuildConfig: app.isPackaged,
});
const runtimePlatformAdapter =
getDesktopRuntimePlatformAdapter(baseRuntimeConfig);
// In launchd mode, skip port probing β the bootstrap has its own port
// recovery via runtime-ports.json and handles leftover processes gracefully.
// Probing here would waste time and the results get overridden by attach anyway.
const useLaunchdMode = isLaunchdBootstrapEnabled();
const runtimeLifecycle = runtimePlatformAdapter.lifecycle;
const { allocations: runtimePortAllocations, runtimeConfig } = useLaunchdMode
? {
allocations: [] as PortAllocation[],
runtimeConfig: baseRuntimeConfig,
}
: await allocateDesktopRuntimePorts(process.env, baseRuntimeConfig).catch(
(error: unknown) => {
if (error instanceof PortAllocationError) {
throw new Error(
`[desktop:ports] ${error.code} purpose=${error.purpose} ` +
`preferredPort=${error.preferredPort ?? "n/a"} ${error.message}`,
);
}
throw error;
},
);
const pendingUserDataMigration =
app.isPackaged && process.platform === "win32"
? readPendingWindowsUserDataMigration()
: null;
const runtimeRoots = runtimePlatformAdapter.capabilities.resolveRuntimeRoots({
app,
electronRoot,
runtimeConfig,
});
if (!useLaunchdMode) {
runtimePlatformAdapter.capabilities.stateMigrationPolicy.run({
runtimeConfig,
runtimeRoots,
isPackaged: app.isPackaged,
pendingUserDataMigration,
log: (message) => {
writeDesktopMainLog({
source: "state-migration",
stream: "system",
kind: "lifecycle",
message,
logFilePath: resolve(
app.getPath("userData"),
"logs",
"desktop-main.log",
),
});
},
});
}
const needsSetupExtraction = checkOpenclawExtractionNeeded(
electronRoot,
app.getPath("userData"),
app.isPackaged,
);
// Set env var BEFORE window creation so the preload can read it for bootstrap data.
if (needsSetupExtraction) {
process.env.NEXU_NEEDS_SETUP_ANIMATION = "1";
}
const runtimeUnitManifests = createRuntimeUnitManifests(
electronRoot,
app.getPath("userData"),
app.isPackaged,
runtimeConfig,
);
const orchestrator = new RuntimeOrchestrator(runtimeUnitManifests);
// Disable Chromium's popup blocker. window.open() inside webviews can lose
// "transient user activation" after async work (fetch β response β open),
// causing silent popup blocking. All popups are already caught by
// setWindowOpenHandler and redirected to shell.openExternal, so this is safe.
app.commandLine.appendSwitch("disable-popup-blocking");
// Keep the renderer running at full speed when backgrounded β without
// these, Chromium pauses the setup-animation video the moment the user
// switches to another app, making the cold-start hand-off look broken.
app.commandLine.appendSwitch("disable-background-timer-throttling");
app.commandLine.appendSwitch("disable-renderer-backgrounding");
app.commandLine.appendSwitch("disable-backgrounding-occluded-windows");
const sentryDsn = runtimeConfig.sentryDsn;
const embeddedWorkspaceTransparentCss = `
html,
body,
#root {
background: transparent !important;
background-color: transparent !important;
}
`;
const desktopDevInspectHost =
process.env.NEXU_DESKTOP_DEV_INSPECT_HOST ?? "127.0.0.1";
const desktopDevInspectPort = Number.parseInt(
process.env.NEXU_DESKTOP_DEV_INSPECT_PORT ?? "5181",
10,
);
const desktopDevInspectToken =
process.env.NEXU_DESKTOP_DEV_INSPECT_TOKEN ?? null;
const desktopDevServerUrl = process.env.NEXU_DESKTOP_DEV_SERVER_URL ?? null;
function readNativeCrashTestTitle(event: Sentry.Event): string | null {
const taggedTitle =
typeof event.tags?.["nexu.crash_title"] === "string"
? event.tags["nexu.crash_title"]
: typeof event.extra?.["nexu.crash_title"] === "string"
? event.extra["nexu.crash_title"]
: null;
if (taggedTitle) {
return taggedTitle;
}
const electronContext = event.contexts?.electron as
| Record<string, unknown>
| undefined;
const crashpadTitle = electronContext?.["crashpad.nexu.crash_title"];
return typeof crashpadTitle === "string" ? crashpadTitle : null;
}
function readNativeCrashTestKind(event: Sentry.Event): string | null {
const taggedKind =
typeof event.tags?.["nexu.crash_kind"] === "string"
? event.tags["nexu.crash_kind"]
: null;
if (taggedKind) {
return taggedKind;
}
const electronContext = event.contexts?.electron as
| Record<string, unknown>
| undefined;
const crashpadKind = electronContext?.["crashpad.nexu.crash_kind"];
return typeof crashpadKind === "string" ? crashpadKind : null;
}
if (sentryDsn) {
const sentryBuildMetadata = getDesktopSentryBuildMetadata(
runtimeConfig.buildInfo,
);
Sentry.init({
dsn: sentryDsn,
environment: app.isPackaged ? "production" : "development",
release: sentryBuildMetadata.release,
...(sentryBuildMetadata.dist ? { dist: sentryBuildMetadata.dist } : {}),
beforeSend(event) {
const testTitle = readNativeCrashTestTitle(event);
if (!testTitle) {
return event;
}
const testKind = readNativeCrashTestKind(event);
const firstException = event.exception?.values?.[0];
const updatedException = event.exception?.values
? {
...event.exception,
values: [
{
...firstException,
type: "Error",
value: testTitle,
},
...event.exception.values.slice(1),
],
}
: {
values: [
{
type: "Error",
value: testTitle,
},
],
};
return {
...event,
message: testTitle,
exception: updatedException,
fingerprint: [testTitle],
tags: {
...event.tags,
"nexu.crash_title": testTitle,
...(testKind ? { "nexu.crash_kind": testKind } : {}),
},
};
},
});
Sentry.setContext("build", sentryBuildMetadata.buildContext);
} else {
crashReporter.start({
companyName: "nexu",
productName: app.getName(),
submitURL: "https://127.0.0.1/desktop-crash-reporter-disabled",
uploadToServer: false,
compress: true,
ignoreSystemCrashHandler: false,
extra: {
environment: app.isPackaged ? "production" : "development",
},
});
}
let mainWindow: BrowserWindow | null = null;
let residentTray: Tray | null = null;
let launchdQuitOptsForResidentEntry:
| Parameters<typeof installLaunchdQuitHandler>[0]
| null = null;
let diagnosticsReporter: DesktopDiagnosticsReporter | null = null;
let systemTray: Tray | null = null;
let pendingMacResidentEntryPreferences: DesktopShellPreferences | null = null;
function isZhLocale(): boolean {
return app.getLocale().toLowerCase().startsWith("zh");
}
function getWindowsTrayStrings(): {
show: string;
hide: string;
quit: string;
} {
if (isZhLocale()) {
return {
show: "ζΎη€Ί Nexu",
hide: "ιθ Nexu",
quit: "ιεΊ Nexu",
};
}
return {
show: "Show Nexu",
hide: "Hide Nexu",
quit: "Quit Nexu",
};
}
function resolveWindowsTrayIconPath(): string {
return app.isPackaged
? join(process.resourcesPath, "tray-icon.ico")
: resolve(getDesktopAppRoot(), "build", "icon.ico");
}
function isForceQuitInProgress(): boolean {
return Boolean((app as unknown as Record<string, unknown>).__nexuForceQuit);
}
function markForceQuitInProgress(): void {
(app as unknown as Record<string, unknown>).__nexuForceQuit = true;
}
/** True if this is the x86_64 build running under Rosetta 2 on Apple Silicon. */
function isRunningUnderRosetta(): boolean {
if (process.platform !== "darwin") return false;
if (process.arch !== "x64") return false;
try {
const out = execFileSync(
"/usr/sbin/sysctl",
["-n", "sysctl.proc_translated"],
{
encoding: "utf8",
timeout: 1000,
},
).trim();
return out === "1";
} catch {
return false;
}
}
/**
* Resolve the latest arm64 dmg URL from the same update feed (channel) the
* user is currently on, so the link mirrors what auto-update would install.
* Reads runtimeConfig (not process.env) because packaged builds bake the
* channel + feed URL into build-config.json, not live env vars.
*/
async function resolveLatestArm64DownloadUrl(): Promise<string> {
const R2_BASE = "https://desktop-releases.nexu.io";
const channel = runtimeConfig.updates.channel ?? "stable";
let baseUrl = `${R2_BASE}/${channel}/arm64`;
const feedOverride = runtimeConfig.urls.updateFeed;
if (feedOverride) {
try {
const u = new URL(feedOverride);
const trimmed = u.pathname.replace(/\/+$/, "");
const swapped = trimmed.replace(/\/x64$/, "/arm64");
u.pathname = swapped.endsWith("/arm64") ? swapped : `${swapped}/arm64`;
u.search = "";
u.hash = "";
baseUrl = u.toString().replace(/\/+$/, "");
} catch {}
}
const ymlUrl = `${baseUrl}/latest-mac.yml`;
try {
const res = await fetch(ymlUrl, { signal: AbortSignal.timeout(3000) });
if (res.ok) {
// electron-builder latest-mac.yml lists both .zip (for delta updates)
// and .dmg under `files:`. We want the dmg.
const match = (await res.text()).match(/url:\s*(\S+\.dmg)/);
if (match?.[1]) return `${baseUrl}/${match[1]}`;
}
} catch {}
return ymlUrl;
}
/**
* Block startup with a warning if the Intel build is running on Apple
* Silicon under Rosetta 2 β the symptoms (slow startup, high CPU, sidecar
* native bindings failing to load) give users no hint of the root cause.
* Skipped in dev and skippable via NEXU_SKIP_ARCH_WARNING=1.
*/
async function warnIfRunningUnderRosetta(): Promise<void> {
if (!app.isPackaged) return;
if (process.env.NEXU_SKIP_ARCH_WARNING === "1") return;
if (!isRunningUnderRosetta()) return;
const downloadUrl = await resolveLatestArm64DownloadUrl();
const isZh = app.getLocale().toLowerCase().startsWith("zh");
const messageBox = isZh
? {
title: "ζ£ζ΅ε°ζΆζδΈεΉι
",
message: "ζ£ε¨ Apple Silicon Mac δΈθΏθ‘ Intel η Nexu",
detail:
"macOS ιθΏ Rosetta 2 ηΏ»θ―θΏθ‘ Intel ηζ¬οΌδΌε―Όθ΄οΌ\nβ’ ε―ε¨ζ―ζ£εΈΈζ
’ 3-5 ε\nβ’ ηι’ε‘ι‘ΏγCPU ε η¨θΏι«\nβ’ ι¨εεη樑εε―θ½ε θ½½ε€±θ΄₯\n\nθ―·δΈθ½½ Apple Silicon (arm64) ηζ¬δ»₯θ·εΎζδ½³δ½ιͺγ",
// Trailing space on the default-button label is a workaround for
// electron/electron#40466 β non-standard button labels otherwise do
// not get the macOS blue default-button highlight. The "(ζ¨θ)"
// suffix is a textual fallback so the recommended action is still
// obvious if the visual highlight ever stops working.
downloadButton: "δΈθ½½ arm64 ηζ¬οΌζ¨θοΌ ",
continueButton: "η»§η»θΏθ‘",
}
: {
title: "Architecture mismatch detected",
message: "Running the Intel build of Nexu on an Apple Silicon Mac",
detail:
"macOS is running this build through Rosetta 2 translation, which causes:\nβ’ 3-5x slower startup\nβ’ Laggy UI and high CPU usage\nβ’ Possible native module load failures\n\nPlease download the Apple Silicon (arm64) build for the best experience.",
downloadButton: "Download arm64 build (recommended) ",
continueButton: "Continue anyway",
};
const result = await dialog.showMessageBox({
type: "warning",
title: messageBox.title,
message: messageBox.message,
detail: messageBox.detail,
buttons: [messageBox.downloadButton, messageBox.continueButton],
defaultId: 0,
cancelId: 1,
noLink: true,
});
if (result.response === 0) {
void shell.openExternal(downloadUrl);
app.exit(0);
}
}
/**
* Controls whether the Develop menu is visible. In local dev it starts enabled
* so the menu matches today's default behavior, but the same shortcut can
* still toggle it for validation. In packaged builds it starts disabled.
*/
let productionDebugMode = !app.isPackaged;
let sleepGuard: SleepGuard | null = null;
let launchdResult: LaunchdBootstrapResult | null = null;
let proxyManager: ProxyManager | null = null;
async function refreshProxyDiagnostics(): Promise<void> {
if (!proxyManager) {
return;
}
const targets = [
{ label: "controller", url: runtimeConfig.urls.controllerBase },
{ label: "openclaw", url: runtimeConfig.urls.openclawBase },
{ label: "external", url: "https://nexu.io" },
];
const snapshot = await proxyManager.collectDiagnostics(
runtimeConfig.proxy,
targets,
);
diagnosticsReporter?.setProxySnapshot(snapshot);
}
// ---------------------------------------------------------------------------
// Unified graceful shutdown β single authoritative teardown path.
// Called by: before-quit, SIGTERM, SIGINT, quit-handler, system shutdown.
// Idempotent: safe to call multiple times (second call is a no-op).
// ---------------------------------------------------------------------------
let shutdownInProgress = false;
const SHUTDOWN_HARD_TIMEOUT_MS = 8_000;
async function gracefulShutdown(reason: string): Promise<void> {
if (shutdownInProgress) return;
shutdownInProgress = true;
writeDesktopMainLog({
source: "shutdown",
stream: "system",
kind: "lifecycle",
message: `graceful shutdown started: ${reason}`,
logFilePath: null,
windowId: null,
});
// Hard timeout: if teardown hangs, force exit after 8 seconds.
const hardTimer = setTimeout(() => {
writeDesktopMainLog({
source: "shutdown",
stream: "system",
kind: "lifecycle",
message: `graceful shutdown hard timeout (${SHUTDOWN_HARD_TIMEOUT_MS}ms), forcing exit`,
logFilePath: null,
windowId: null,
});
process.exit(1);
}, SHUTDOWN_HARD_TIMEOUT_MS);
try {
sleepGuard?.dispose(reason);
await diagnosticsReporter?.flushNow().catch(() => undefined);
flushRuntimeLoggers();
flushV8CoverageIfEnabled();
if (launchdResult) {
await teardownLaunchdServices({
launchd: launchdResult.launchd,
labels: launchdResult.labels,
plistDir: getDefaultPlistDir(!app.isPackaged),
});
}
await orchestrator.dispose().catch(() => undefined);
} finally {
clearTimeout(hardTimer);
}
}
// Cold-start gate: IPC handler for `env:get-runtime-config` waits for this
// promise to resolve before returning, ensuring the renderer always gets the
// final config with correct ports (not the pre-cold-start defaults).
let resolveColdStartReady: () => void;
const coldStartReady = new Promise<void>((r) => {
resolveColdStartReady = r;
});
logLaunchTimeline(
`runtime ports ${runtimePortAllocations
.map(
(allocation) =>
`${allocation.purpose}=${allocation.preferredPort}->${allocation.port} ` +
`strategy=${allocation.strategy} attemptDelta=${allocation.attemptDelta}`,
)
.join(" ")}`,
);
function sendDesktopCommand(
surface: DesktopSurface,
chromeMode: DesktopChromeMode,
): void {
mainWindow?.webContents.send("host:desktop-command", {
type:
chromeMode === "immersive" && surface !== "control"
? "develop:focus-surface"
: "develop:show-shell",
surface,
chromeMode,
});
}
function sendHostDesktopCommand(command: HostDesktopCommand): void {
mainWindow?.webContents.send("host:desktop-command", command);
}
function showAboutDialog(): void {
const version = app.getVersion();
const detailLines = [
`Version ${version}`,
`Electron ${process.versions.electron}`,
`Chromium ${process.versions.chrome}`,
`Node ${process.versions.node}`,
];
const options = {
type: "info" as const,
title: "About Nexu",
message: "Nexu",
detail: detailLines.join("\n"),
buttons: ["OK"],
noLink: true,
};
void (mainWindow
? dialog.showMessageBox(mainWindow, options)
: dialog.showMessageBox(options));
}
function installApplicationMenu(): void {
const developMenu: MenuItemConstructorOptions = {
label: "Develop",
submenu: [
{
label: "Focus Web Surface",
accelerator: "CmdOrCtrl+Shift+1",
click: () => sendDesktopCommand("web", "immersive"),
},
{
label: "Focus OpenClaw Surface",
accelerator: "CmdOrCtrl+Shift+2",
click: () => sendDesktopCommand("openclaw", "immersive"),
},
{ type: "separator" },
{
label: "Show Desktop Shell",
accelerator: "CmdOrCtrl+Shift+0",
click: () => sendDesktopCommand("control", "full"),
},
{
label: "Show Web In Shell",
click: () => sendDesktopCommand("web", "full"),
},
{
label: "Show OpenClaw In Shell",
click: () => sendDesktopCommand("openclaw", "full"),
},
{ type: "separator" },
{
label: "Set Test Balanceβ¦",
click: () =>
sendHostDesktopCommand({ type: "develop:open-set-balance" }),
},
],
};
const helpSubmenu: MenuItemConstructorOptions[] = [
{
label: "Export Diagnosticsβ¦",
click: () => {
void exportDiagnostics({
orchestrator,
runtimeConfig,
source: "help-menu",
}).catch(() => undefined);
},
},
];
// On macOS About/Check-for-Updates live in the application menu by
// platform convention. On Windows/Linux there is no app menu, so surface
// them in Help instead (issue nexu-io/nexu#784).
if (process.platform !== "darwin") {
helpSubmenu.push(
{ type: "separator" },
{
id: "about-nexu",
label: `About Nexu (v${app.getVersion()})`,
click: () => showAboutDialog(),
},
);
}
const helpMenu: MenuItemConstructorOptions = {
role: "help",
submenu: helpSubmenu,
};
const template: MenuItemConstructorOptions[] = [
...(process.platform === "darwin"
? ([
{
role: "appMenu",
submenu: [
{ role: "about" },
{ type: "separator" },
{ role: "services" },
{ type: "separator" },
{ role: "hide" },
{ role: "hideOthers" },
{ role: "unhide" },
{ type: "separator" },
{ role: "quit" },
],
},
] satisfies MenuItemConstructorOptions[])
: []),
{ role: "fileMenu" },
{ role: "editMenu" },
{
label: "View",
submenu: [
// Reload shortcuts are dev-only β in production they expose
// internal "starting local service" screens (see #399).
// They can be unlocked at runtime via Cmd/Ctrl+Shift+Alt+D.
...(productionDebugMode
? ([
{ role: "reload" },
{ role: "forceReload" },
{ type: "separator" },
] satisfies MenuItemConstructorOptions[])
: []),
{ role: "toggleDevTools" },
{ type: "separator" },
{ role: "resetZoom" },
{ role: "zoomIn" },
{ role: "zoomOut" },
{ type: "separator" },
{ role: "togglefullscreen" },
],
},
...(productionDebugMode ? [developMenu] : []),
{ role: "windowMenu" },
helpMenu,
];
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
}
function getDesktopLogFilePath(name: string): string {
return resolve(app.getPath("userData"), "logs", name);
}
function getMainWindowId(): number | null {
return mainWindow?.webContents.id ?? null;
}
function logColdStart(message: string): void {
writeDesktopMainLog({
source: "cold-start",
stream: "system",
kind: "lifecycle",
message,
logFilePath: getDesktopLogFilePath("cold-start.log"),
windowId: getMainWindowId(),
});
}
function logLaunchTimeline(message: string): void {
const launchId = process.env.NEXU_DESKTOP_LAUNCH_ID ?? "unknown";
writeDesktopMainLog({
source: "launch-timeline",
stream: "system",
kind: "lifecycle",
message: `${message} launchId=${launchId}`,
logFilePath: getDesktopLogFilePath("desktop-main.log"),
windowId: getMainWindowId(),
});
}
function logRendererEvent({
source,
stream,
kind,
message,
windowId,
}: {
source: string;
stream: "stdout" | "stderr";
kind: "app" | "lifecycle";
message: string;
windowId?: number | null;
}): void {
writeDesktopMainLog({
source,
stream,
kind,
message,
logFilePath: getDesktopLogFilePath("desktop-main.log"),
windowId,
});
}
function logSleepGuard(entry: SleepGuardLogEntry): void {
writeDesktopMainLog({
source: "sleep-guard",
stream: entry.stream,
kind: entry.kind,
message: entry.message,
logFilePath: getDesktopLogFilePath("desktop-main.log"),
windowId: getMainWindowId(),
});
}
async function waitForControllerReadiness(): Promise<void> {
const startedAt = Date.now();
const timeoutMs = 15_000;
const probeUrl = new URL("/health", runtimeConfig.urls.controllerBase);
let attempt = 0;
while (Date.now() - startedAt < timeoutMs) {
try {
const response = await fetch(probeUrl, {
headers: {
Accept: "application/json",
},
});
if (response.status < 500) {
logColdStart(
`controller ready via ${probeUrl.pathname} status=${response.status} after ${Date.now() - startedAt}ms`,
);
return;
}
} catch {
// Ignore transient startup failures while the controller starts.
}
// Adaptive polling: start aggressive (50ms), increase to 250ms
const delay = Math.min(50 + attempt * 50, 250);
await new Promise((resolve) => setTimeout(resolve, delay));
attempt++;
}
throw new Error(
`Controller readiness probe timed out for ${probeUrl.toString()}`,
);
}
async function runDesktopColdStart(): Promise<void> {
diagnosticsReporter?.markColdStartRunning("starting controller");
logColdStart("starting controller");
await orchestrator.startOne("controller");
diagnosticsReporter?.markColdStartRunning("waiting for controller readiness");
logColdStart("waiting for controller readiness");
await waitForControllerReadiness();
diagnosticsReporter?.markColdStartRunning("starting web");
logColdStart("starting web");
await orchestrator.startOne("web");
const sessionId = rotateDesktopLogSession();
logColdStart(`cold start session ready sessionId=${sessionId}`);
logColdStart("cold start complete");
diagnosticsReporter?.markColdStartSucceeded();
}
async function runLaunchdColdStart(): Promise<void> {
diagnosticsReporter?.markColdStartRunning("launchd bootstrap");
logColdStart("starting launchd bootstrap");
const isDev = !app.isPackaged;
const paths = await resolveLaunchdPaths(
app.isPackaged,
electronRoot,
app.getVersion(),
);
const nexuHome = runtimeConfig.paths.nexuHome.replace(
/^~/,
process.env.HOME ?? "",
);
const runtimeRoots = runtimePlatformAdapter.capabilities.resolveRuntimeRoots({
app,
electronRoot,
runtimeConfig,
});
const { openclawRuntimeRoot, openclawStateDir, openclawConfigPath } =
runtimeRoots;
runtimePlatformAdapter.capabilities.stateMigrationPolicy.run({
runtimeConfig,
runtimeRoots,
isPackaged: app.isPackaged,
pendingUserDataMigration: null,
log: (message) => logColdStart(`state-migration: ${message}`),
});
// In dev mode, serve web app from apps/web/dist
// In packaged mode, serve from resources/web
const webRoot = isDev
? resolve(getWorkspaceRoot(), "apps", "web", "dist")
: resolve(electronRoot, "runtime", "web", "dist");
const repoRoot = getWorkspaceRoot();
const userDataPath = app.getPath("userData");
const openclawSkillsDir = getOpenclawSkillsDir(userDataPath);
const openclawTmpDir = resolve(openclawRuntimeRoot, "tmp");
const openclawBinPath =
process.env.NEXU_OPENCLAW_BIN ?? paths.openclawBinPath;
const openclawExtensionsDir = paths.openclawExtensionsDir;
const skillhubStaticSkillsDir = app.isPackaged
? resolve(electronRoot, "static/bundled-skills")
: resolve(repoRoot, "apps/desktop/static/bundled-skills");
const platformTemplatesDir = app.isPackaged
? resolve(electronRoot, "static/platform-templates")
: resolve(repoRoot, "apps/controller/static/platform-templates");
const skillNodePath = buildSkillNodePath(electronRoot, app.isPackaged);
const proxyEnv = buildChildProcessProxyEnv(runtimeConfig.proxy);
launchdResult = await bootstrapWithLaunchd({
isDev,
controllerPort: runtimeConfig.ports.controller,
openclawPort: Number(
new URL(runtimeConfig.urls.openclawBase).port || 18789,
),
nexuHome,
gatewayToken: isDev ? undefined : runtimeConfig.tokens.gateway,
webPort: runtimeConfig.ports.web,
webRoot,
plistDir: getDefaultPlistDir(isDev),
...paths,
openclawConfigPath,
openclawStateDir,
// Controller-specific env vars
webUrl: runtimeConfig.urls.web,
openclawSkillsDir,
skillhubStaticSkillsDir,
platformTemplatesDir,
openclawBinPath,
openclawExtensionsDir,
skillNodePath,
openclawTmpDir,
proxyEnv,
posthogApiKey:
process.env.POSTHOG_API_KEY ?? runtimeConfig.posthogApiKey ?? undefined,
posthogHost:
process.env.POSTHOG_HOST ?? runtimeConfig.posthogHost ?? undefined,
langfusePublicKey:
process.env.LANGFUSE_PUBLIC_KEY ??
runtimeConfig.langfusePublicKey ??
undefined,
langfuseSecretKey:
process.env.LANGFUSE_SECRET_KEY ??
runtimeConfig.langfuseSecretKey ??
undefined,
langfuseBaseUrl:
process.env.LANGFUSE_BASE_URL ??
runtimeConfig.langfuseBaseUrl ??
undefined,
log: (message: string) => logColdStart(message),
nodeV8Coverage: process.env.NODE_V8_COVERAGE,
desktopE2ECoverage: process.env.NEXU_DESKTOP_E2E_COVERAGE,
desktopE2ECoverageRunId: process.env.NEXU_DESKTOP_E2E_COVERAGE_RUN_ID,
appVersion: app.getVersion(),
userDataPath: app.getPath("userData"),
buildSource:
process.env.NEXU_DESKTOP_BUILD_SOURCE ??
(app.isPackaged ? "packaged" : "local-dev"),
runtimeIdentityPath: app.isPackaged ? process.resourcesPath : undefined,
});
// Wire launchd-managed units into the orchestrator so the control plane
// shows correct status, and Start/Stop buttons work via launchd.
const launchdLogDir = getLogDir(isDev ? nexuHome : undefined);
orchestrator.enableLaunchdMode(
launchdResult.launchd,
{
controller: SERVICE_LABELS.controller(isDev),
openclaw: SERVICE_LABELS.openclaw(isDev),
},
launchdLogDir,
);
// Always sync runtimeConfig with actual effective ports β these may differ
// from the initial config if ports were recovered from a previous session or
// OS-assigned due to conflicts.
const { controllerPort, openclawPort, webPort } =
launchdResult.effectivePorts;
runtimeConfig.ports.controller = controllerPort;
runtimeConfig.ports.web = webPort;
runtimeConfig.urls.controllerBase = `http://127.0.0.1:${controllerPort}`;
runtimeConfig.urls.web = `http://127.0.0.1:${webPort}`;
runtimeConfig.urls.openclawBase = `http://127.0.0.1:${openclawPort}`;
if (launchdResult.isAttach) {
logColdStart(