-
Notifications
You must be signed in to change notification settings - Fork 264
Expand file tree
/
Copy pathlaunchd-startup-scenarios.test.ts
More file actions
1757 lines (1536 loc) Β· 65.1 KB
/
Copy pathlaunchd-startup-scenarios.test.ts
File metadata and controls
1757 lines (1536 loc) Β· 65.1 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
/**
* Launchd Startup Scenarios β smoke tests covering every bootstrap edge case:
*
* 1. Fresh cold start (no previous state)
* 2. Attach to healthy running services
* 3. Attach fails: controller unhealthy β teardown + cold start
* 4. Attach fails: openclaw port not listening β teardown + cold start
* 5. Port occupied β web server fallback to OS-assigned port
* 6. Plist config drift β bootout + re-bootstrap
* 7. NEXU_HOME mismatch β teardown stale services
* 8. Services running but runtime-ports.json missing β teardown
* 9. Previous Electron dead (stale PID) β fresh web port
* 10. Stop via bootout β Start re-bootstraps from plist
* 11. effectivePorts always returned (cold start and attach)
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
// ---------------------------------------------------------------------------
// Mocks
// ---------------------------------------------------------------------------
vi.mock("node:os", () => ({
homedir: vi.fn(() => "/Users/testuser"),
userInfo: vi.fn(() => ({ uid: 501 })),
}));
vi.mock("node:child_process", () => ({
// lsof (detectPortOccupier/findFreePort) β no occupier found
execFile: vi.fn(
(
_cmd: string,
_args: string[],
callback: (
error: Error | null,
result: { stdout: string; stderr: string },
) => void,
) => {
callback(new Error("no process"), { stdout: "", stderr: "" });
},
),
}));
vi.mock("node:fs/promises", () => ({
mkdir: vi.fn().mockResolvedValue(undefined),
writeFile: vi.fn().mockResolvedValue(undefined),
readFile: vi.fn().mockRejectedValue(new Error("ENOENT")),
unlink: vi.fn().mockResolvedValue(undefined),
rename: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("node:net", () => {
const createServer = vi.fn(() => ({
once() {},
listen(_port: number, _host: string, cb: () => void) {
setTimeout(() => cb(), 0);
},
close(cb: () => void) {
setTimeout(() => cb(), 0);
},
}));
const createConnection = vi.fn(() => {
// Return a mock socket that emits "connect" immediately
const handlers: Record<string, (() => void)[]> = {};
const socket = {
once(event: string, cb: () => void) {
if (!handlers[event]) handlers[event] = [];
handlers[event].push(cb);
// Auto-emit "connect" on next tick to simulate healthy port
if (event === "connect") {
setTimeout(() => cb(), 0);
}
},
destroy: vi.fn(),
setTimeout: vi.fn(),
};
return socket;
});
return {
default: {
createServer,
createConnection,
},
createServer,
createConnection,
};
});
const mockLaunchdManager = {
getServiceStatus: vi.fn(),
installService: vi.fn(),
startService: vi.fn(),
stopServiceGracefully: vi.fn(),
bootoutService: vi.fn(),
bootoutAndWaitForExit: vi.fn(),
waitForExit: vi.fn(),
isServiceInstalled: vi.fn(),
hasPlistFile: vi.fn(),
isServiceRegistered: vi.fn(),
rebootstrapFromPlist: vi.fn(),
getPlistDir: vi.fn(() => "/tmp/test-plist"),
getDomain: vi.fn(() => "gui/501"),
};
vi.mock("../../apps/desktop/main/services/launchd-manager", () => ({
LaunchdManager: vi.fn(() => mockLaunchdManager),
SERVICE_LABELS: {
controller: (isDev: boolean) =>
isDev ? "io.nexu.controller.dev" : "io.nexu.controller",
openclaw: (isDev: boolean) =>
isDev ? "io.nexu.openclaw.dev" : "io.nexu.openclaw",
},
}));
vi.mock("../../apps/desktop/main/services/plist-generator", () => ({
generatePlist: vi.fn((type: string) => `<plist>mock-${type}-v2</plist>`),
}));
const mockWebServer = {
port: 50810,
close: vi.fn().mockResolvedValue(undefined),
};
vi.mock("../../apps/desktop/main/services/embedded-web-server", () => ({
startEmbeddedWebServer: vi
.fn()
.mockImplementation((opts: { port: number }) => {
// Simulate OS-assigned port when port=0
mockWebServer.port = opts.port === 0 ? 59999 : opts.port;
return Promise.resolve(mockWebServer);
}),
}));
vi.mock("../../apps/desktop/main/runtime/manifests", () => ({
ensurePackagedOpenclawSidecar: vi.fn(() => "/app/openclaw-sidecar"),
}));
vi.mock("../../apps/desktop/shared/workspace-paths", () => ({
getWorkspaceRoot: vi.fn(() => "/repo"),
}));
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function makeBootstrapEnv(
overrides?: Record<string, unknown>,
): Record<string, unknown> {
return {
isDev: true,
controllerPort: 50800,
openclawPort: 18789,
webPort: 50810,
webRoot: "/repo/apps/web/dist",
nodePath: "/usr/local/bin/node",
controllerEntryPath: "/repo/apps/controller/dist/index.js",
openclawPath: "/repo/openclaw-runtime/node_modules/openclaw/openclaw.mjs",
openclawConfigPath: "/tmp/state/openclaw.json",
openclawStateDir: "/tmp/state",
controllerCwd: "/repo/apps/controller",
openclawCwd: "/repo",
nexuHome: "/tmp/nexu-home",
plistDir: "/tmp/test-plist",
webUrl: "http://127.0.0.1:50810",
openclawSkillsDir: "/tmp/state/skills",
skillhubStaticSkillsDir: "/repo/apps/desktop/static/bundled-skills",
platformTemplatesDir: "/repo/apps/controller/static/platform-templates",
openclawBinPath: "/repo/openclaw-runtime/bin/openclaw",
openclawExtensionsDir: "/repo/node_modules/openclaw/extensions",
skillNodePath: "/repo/apps/desktop/node_modules",
openclawTmpDir: "/tmp/state/tmp",
proxyEnv: {
NO_PROXY: "localhost,127.0.0.1,::1",
},
controllerStartupValidationTimeoutMs: 500,
...overrides,
};
}
function makeRuntimePorts(overrides?: Record<string, unknown>) {
return JSON.stringify({
writtenAt: new Date().toISOString(),
electronPid: 12345,
controllerPort: 50800,
openclawPort: 18789,
webPort: 50810,
nexuHome: "/tmp/nexu-home",
isDev: true,
...overrides,
});
}
function mockRunningService(env?: Record<string, string>): {
label: string;
plistPath: string;
status: string;
pid: number;
env?: Record<string, string>;
} {
return {
label: "test",
plistPath: "",
status: "running",
pid: 1234,
...(env ? { env } : {}),
};
}
function mockStoppedService() {
return { label: "test", plistPath: "", status: "stopped" };
}
function mockUnknownService() {
return { label: "test", plistPath: "", status: "unknown" };
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
describe("Launchd Startup Scenarios", () => {
const originalPlatform = process.platform;
beforeEach(async () => {
vi.clearAllMocks();
Object.defineProperty(process, "platform", {
value: "darwin",
configurable: true,
});
mockWebServer.port = 50810;
// Restore embedded web server mock (some tests override it)
const webServerMod = await import(
"../../apps/desktop/main/services/embedded-web-server"
);
(
webServerMod.startEmbeddedWebServer as ReturnType<typeof vi.fn>
).mockImplementation((opts: { port: number }) => {
mockWebServer.port = opts.port === 0 ? 59999 : opts.port;
return Promise.resolve(mockWebServer);
});
// Defaults: no services, not installed
mockLaunchdManager.getServiceStatus.mockResolvedValue(mockUnknownService());
mockLaunchdManager.isServiceInstalled.mockResolvedValue(false);
mockLaunchdManager.installService.mockResolvedValue(undefined);
mockLaunchdManager.startService.mockResolvedValue(undefined);
mockLaunchdManager.bootoutService.mockResolvedValue(undefined);
mockLaunchdManager.bootoutAndWaitForExit.mockResolvedValue(undefined);
mockLaunchdManager.waitForExit.mockResolvedValue(undefined);
mockLaunchdManager.rebootstrapFromPlist.mockResolvedValue(undefined);
// Controller readiness probe succeeds
vi.stubGlobal(
"fetch",
vi.fn().mockResolvedValue({ status: 200, ok: true }),
);
});
afterEach(() => {
Object.defineProperty(process, "platform", {
value: originalPlatform,
configurable: true,
});
vi.unstubAllGlobals();
});
// -----------------------------------------------------------------------
// Scenario 1: Fresh cold start
// -----------------------------------------------------------------------
it("Scenario 1: fresh cold start installs and starts both services", async () => {
const { bootstrapWithLaunchd } = await import(
"../../apps/desktop/main/services/launchd-bootstrap"
);
const result = await bootstrapWithLaunchd(makeBootstrapEnv() as never);
expect(mockLaunchdManager.installService).toHaveBeenCalledTimes(2);
expect(result.isAttach).toBe(false);
expect(result.effectivePorts.controllerPort).toBe(50800);
expect(result.effectivePorts.openclawPort).toBe(18789);
expect(result.effectivePorts.webPort).toBe(50810);
});
// -----------------------------------------------------------------------
// Scenario 2: Attach to healthy running services
// -----------------------------------------------------------------------
it("Scenario 2: attach to healthy running services reuses recovered ports", async () => {
const fsMock = await import("node:fs/promises");
(fsMock.readFile as ReturnType<typeof vi.fn>)
// cleanup phase reads controller plist β not found
.mockRejectedValueOnce(new Error("ENOENT"))
// cleanup phase reads openclaw plist β not found
.mockRejectedValueOnce(new Error("ENOENT"))
// stale session detection reads runtime-ports.json
.mockResolvedValueOnce(makeRuntimePorts())
// recover phase reads runtime-ports.json
.mockResolvedValueOnce(makeRuntimePorts());
// Both services running with correct NEXU_HOME
mockLaunchdManager.getServiceStatus.mockResolvedValue(
mockRunningService({ NEXU_HOME: "/tmp/nexu-home", PORT: "50800" }),
);
// Health probes: controller HTTP ok, openclaw port listening
vi.stubGlobal(
"fetch",
vi.fn().mockResolvedValue({ status: 200, ok: true }),
);
const { bootstrapWithLaunchd } = await import(
"../../apps/desktop/main/services/launchd-bootstrap"
);
const result = await bootstrapWithLaunchd(makeBootstrapEnv() as never);
expect(result.isAttach).toBe(true);
expect(result.effectivePorts.controllerPort).toBe(50800);
expect(result.effectivePorts.webPort).toBe(50810);
// Should NOT have installed fresh services
expect(mockLaunchdManager.bootoutService).not.toHaveBeenCalled();
});
// -----------------------------------------------------------------------
// Scenario 3: Controller unhealthy on attach β restart
// -----------------------------------------------------------------------
it("Scenario 3: controller unhealthy on attach triggers bootout + reinstall", async () => {
const fsMock = await import("node:fs/promises");
(fsMock.readFile as ReturnType<typeof vi.fn>)
.mockRejectedValueOnce(new Error("ENOENT")) // cleanup: controller plist
.mockRejectedValueOnce(new Error("ENOENT")) // cleanup: openclaw plist
.mockResolvedValueOnce(makeRuntimePorts()) // stale session detection
.mockResolvedValueOnce(makeRuntimePorts()); // recover phase
// Both services report running
mockLaunchdManager.getServiceStatus.mockResolvedValue(
mockRunningService({ NEXU_HOME: "/tmp/nexu-home", PORT: "50800" }),
);
// Controller health probe FAILS
vi.stubGlobal(
"fetch",
vi.fn((input: string | URL) => {
const url = String(input);
if (url.includes("/health")) {
return Promise.reject(new Error("ECONNREFUSED"));
}
return Promise.resolve({ status: 200, ok: true });
}),
);
const { bootstrapWithLaunchd } = await import(
"../../apps/desktop/main/services/launchd-bootstrap"
);
await bootstrapWithLaunchd(makeBootstrapEnv() as never);
// Should have bootout the unhealthy controller
expect(mockLaunchdManager.bootoutAndWaitForExit).toHaveBeenCalled();
// Should have reinstalled
expect(mockLaunchdManager.installService).toHaveBeenCalled();
});
// -----------------------------------------------------------------------
// Scenario 5: Web port occupied β fallback to OS-assigned port
// -----------------------------------------------------------------------
it("Scenario 5: web port occupied falls back to next port", async () => {
const webServerMock = await import(
"../../apps/desktop/main/services/embedded-web-server"
);
let callCount = 0;
(
webServerMock.startEmbeddedWebServer as ReturnType<typeof vi.fn>
).mockImplementation((opts: { port: number }) => {
callCount++;
if (callCount === 1) {
// First call fails (port occupied)
const err = Object.assign(new Error("EADDRINUSE"), {
code: "EADDRINUSE",
});
return Promise.reject(err);
}
// Second call with port+1 succeeds
mockWebServer.port = opts.port;
return Promise.resolve(mockWebServer);
});
const { bootstrapWithLaunchd } = await import(
"../../apps/desktop/main/services/launchd-bootstrap"
);
const result = await bootstrapWithLaunchd(makeBootstrapEnv() as never);
// Should have tried the next adjacent port after the first failure
expect(webServerMock.startEmbeddedWebServer).toHaveBeenCalledTimes(2);
const secondCall = (
webServerMock.startEmbeddedWebServer as ReturnType<typeof vi.fn>
).mock.calls[1][0];
expect(secondCall.port).toBe(50811); // webPort + 1
// effectivePorts should reflect the actual bound port
expect(result.effectivePorts.webPort).toBe(50811);
});
// -----------------------------------------------------------------------
// Scenario 6: Plist config drift β bootout + re-bootstrap
// -----------------------------------------------------------------------
it("Scenario 6: plist content change triggers bootout + re-bootstrap", async () => {
const fsMock = await import("node:fs/promises");
// installService reads existing plist to compare
// Return OLD content that differs from generated plist
(fsMock.readFile as ReturnType<typeof vi.fn>)
// First call: runtime-ports.json β ENOENT
.mockRejectedValueOnce(new Error("ENOENT"))
// Second call: controller plist β old content
.mockResolvedValueOnce("<plist>mock-controller-v1</plist>")
// Third call: openclaw plist β old content
.mockResolvedValueOnce("<plist>mock-openclaw-v1</plist>");
// Services already registered
mockLaunchdManager.isServiceInstalled.mockResolvedValue(true);
let controllerStatusCalls = 0;
let openclawStatusCalls = 0;
mockLaunchdManager.getServiceStatus.mockImplementation((label: string) => {
if (label.includes("controller")) {
controllerStatusCalls++;
return Promise.resolve(
controllerStatusCalls <= 2
? mockStoppedService()
: mockRunningService(),
);
}
openclawStatusCalls++;
return Promise.resolve(
openclawStatusCalls <= 2 ? mockStoppedService() : mockRunningService(),
);
});
const { bootstrapWithLaunchd } = await import(
"../../apps/desktop/main/services/launchd-bootstrap"
);
await bootstrapWithLaunchd(makeBootstrapEnv() as never);
// installService should detect drift and re-bootstrap
expect(mockLaunchdManager.installService).toHaveBeenCalledTimes(2);
});
// -----------------------------------------------------------------------
// Scenario 7: NEXU_HOME mismatch β teardown stale services
// -----------------------------------------------------------------------
it("Scenario 7: NEXU_HOME mismatch tears down stale services", async () => {
const fsMock = await import("node:fs/promises");
(fsMock.readFile as ReturnType<typeof vi.fn>)
.mockRejectedValueOnce(new Error("ENOENT")) // cleanup: controller plist
.mockRejectedValueOnce(new Error("ENOENT")) // cleanup: openclaw plist
.mockResolvedValueOnce(makeRuntimePorts({ nexuHome: "/wrong/nexu-home" })) // stale session detection
.mockResolvedValueOnce(
makeRuntimePorts({ nexuHome: "/wrong/nexu-home" }),
); // recover phase
mockLaunchdManager.getServiceStatus.mockResolvedValue(
mockRunningService({ NEXU_HOME: "/wrong/nexu-home" }),
);
const { bootstrapWithLaunchd } = await import(
"../../apps/desktop/main/services/launchd-bootstrap"
);
await bootstrapWithLaunchd(
makeBootstrapEnv({ nexuHome: "/correct/nexu-home" }) as never,
);
expect(mockLaunchdManager.bootoutAndWaitForExit).toHaveBeenCalled();
// Should still install and start services after teardown
expect(mockLaunchdManager.installService).toHaveBeenCalled();
});
// -----------------------------------------------------------------------
// Scenario 8: Services running but runtime-ports.json missing β teardown
// -----------------------------------------------------------------------
it("Scenario 8: services running without runtime-ports.json are torn down", async () => {
// readFile ENOENT for runtime-ports.json (default mock)
// But services are running
mockLaunchdManager.getServiceStatus.mockResolvedValue(mockRunningService());
const { bootstrapWithLaunchd } = await import(
"../../apps/desktop/main/services/launchd-bootstrap"
);
await bootstrapWithLaunchd(makeBootstrapEnv() as never);
// Should teardown orphaned services
expect(mockLaunchdManager.bootoutAndWaitForExit).toHaveBeenCalled();
// Then do clean install
expect(mockLaunchdManager.installService).toHaveBeenCalled();
});
// -----------------------------------------------------------------------
// Scenario 9: Previous Electron dead β fresh web port
// -----------------------------------------------------------------------
it("Scenario 9: dead Electron PID uses fresh web port instead of recovered", async () => {
const fsMock = await import("node:fs/promises");
const portsData = makeRuntimePorts({
electronPid: 999999, // PID that doesn't exist
webPort: 55555,
});
(fsMock.readFile as ReturnType<typeof vi.fn>)
.mockRejectedValueOnce(new Error("ENOENT")) // cleanup: controller plist
.mockRejectedValueOnce(new Error("ENOENT")) // cleanup: openclaw plist
.mockResolvedValueOnce(portsData) // stale session detection
.mockResolvedValueOnce(portsData); // recover phase
mockLaunchdManager.getServiceStatus.mockResolvedValue(
mockRunningService({ NEXU_HOME: "/tmp/nexu-home", PORT: "50800" }),
);
const { bootstrapWithLaunchd } = await import(
"../../apps/desktop/main/services/launchd-bootstrap"
);
const result = await bootstrapWithLaunchd(makeBootstrapEnv() as never);
// Should use fresh web port (50810 from env) instead of recovered 55555
// because the previous Electron is dead and its web server port is stale
expect(result.effectivePorts.webPort).not.toBe(55555);
});
// -----------------------------------------------------------------------
// Scenario 10: effectivePorts always present (cold start)
// -----------------------------------------------------------------------
it("Scenario 10: effectivePorts always returned on cold start", async () => {
const { bootstrapWithLaunchd } = await import(
"../../apps/desktop/main/services/launchd-bootstrap"
);
const result = await bootstrapWithLaunchd(makeBootstrapEnv() as never);
expect(result.effectivePorts).toBeDefined();
expect(typeof result.effectivePorts.controllerPort).toBe("number");
expect(typeof result.effectivePorts.openclawPort).toBe("number");
expect(typeof result.effectivePorts.webPort).toBe("number");
expect(typeof result.isAttach).toBe("boolean");
});
// -----------------------------------------------------------------------
// Scenario 11: effectivePorts always present (attach)
// -----------------------------------------------------------------------
it("Scenario 11: effectivePorts always returned on attach", async () => {
const fsMock = await import("node:fs/promises");
(fsMock.readFile as ReturnType<typeof vi.fn>)
.mockRejectedValueOnce(new Error("ENOENT")) // cleanup: controller plist
.mockRejectedValueOnce(new Error("ENOENT")) // cleanup: openclaw plist
.mockResolvedValueOnce(makeRuntimePorts()) // stale session detection
.mockResolvedValueOnce(makeRuntimePorts()); // recover phase
mockLaunchdManager.getServiceStatus.mockResolvedValue(
mockRunningService({ NEXU_HOME: "/tmp/nexu-home", PORT: "50800" }),
);
const { bootstrapWithLaunchd } = await import(
"../../apps/desktop/main/services/launchd-bootstrap"
);
const result = await bootstrapWithLaunchd(makeBootstrapEnv() as never);
expect(result.effectivePorts).toBeDefined();
expect(result.isAttach).toBe(true);
expect(result.effectivePorts.controllerPort).toBe(50800);
});
// -----------------------------------------------------------------------
// Scenario 12: runtime-ports.json written after bootstrap
// -----------------------------------------------------------------------
it("Scenario 12: runtime-ports.json is written with actual ports after bootstrap", async () => {
const fsMock = await import("node:fs/promises");
const { bootstrapWithLaunchd } = await import(
"../../apps/desktop/main/services/launchd-bootstrap"
);
await bootstrapWithLaunchd(makeBootstrapEnv() as never);
// writeFile should have been called for runtime-ports.json
const writeCalls = (fsMock.writeFile as ReturnType<typeof vi.fn>).mock
.calls;
const portsWrite = writeCalls.find(
(call: unknown[]) =>
typeof call[0] === "string" &&
(call[0] as string).includes("runtime-ports.json"),
);
expect(portsWrite).toBeDefined();
// biome-ignore lint/style/noNonNullAssertion: guarded by toBeDefined above
const written = JSON.parse(portsWrite![1] as string);
expect(written.controllerPort).toBe(50800);
expect(written.openclawPort).toBe(18789);
expect(written.electronPid).toBe(process.pid);
});
// -----------------------------------------------------------------------
// Scenario 13: Stale plist from different installation β cleanup
// -----------------------------------------------------------------------
it("Scenario 13: stale plist from different installation is cleaned up", async () => {
const fsMock = await import("node:fs/promises");
// readFile calls during cleanup:
// 1. controller plist: stale content (different from what generatePlist produces)
// 2. openclaw plist: stale content
// Then runtime-ports.json and later reads: ENOENT
(fsMock.readFile as ReturnType<typeof vi.fn>)
.mockResolvedValueOnce("<plist>old-controller-from-v0.1.5</plist>")
.mockResolvedValueOnce("<plist>old-openclaw-from-v0.1.5</plist>")
.mockRejectedValue(new Error("ENOENT"));
const { bootstrapWithLaunchd } = await import(
"../../apps/desktop/main/services/launchd-bootstrap"
);
await bootstrapWithLaunchd(makeBootstrapEnv() as never);
// Should have bootout stale services
expect(mockLaunchdManager.bootoutService).toHaveBeenCalled();
// Should have deleted stale plist files (unlink called)
expect(fsMock.unlink).toHaveBeenCalled();
// Should still install fresh services after cleanup
expect(mockLaunchdManager.installService).toHaveBeenCalledTimes(2);
});
// -----------------------------------------------------------------------
// Scenario 14: Non-stale plist (same cwd) is NOT cleaned up
// -----------------------------------------------------------------------
it("Scenario 14: plist with matching content is not cleaned up", async () => {
const fsMock = await import("node:fs/promises");
const plistGen = await import(
"../../apps/desktop/main/services/plist-generator"
);
// readFile returns exactly what generatePlist produces β not stale
const controllerPlist = (
plistGen.generatePlist as ReturnType<typeof vi.fn>
)("controller");
const openclawPlist = (plistGen.generatePlist as ReturnType<typeof vi.fn>)(
"openclaw",
);
(fsMock.readFile as ReturnType<typeof vi.fn>)
.mockResolvedValueOnce(controllerPlist)
.mockResolvedValueOnce(openclawPlist)
.mockRejectedValue(new Error("ENOENT"));
const { bootstrapWithLaunchd } = await import(
"../../apps/desktop/main/services/launchd-bootstrap"
);
await bootstrapWithLaunchd(makeBootstrapEnv() as never);
// Should NOT have tried to bootout (plist cwd matches)
// Note: bootoutService may be called for other reasons, but unlink
// should NOT have been called for plist files during cleanup phase
const unlinkCalls = (fsMock.unlink as ReturnType<typeof vi.fn>).mock.calls;
const plistUnlinks = unlinkCalls.filter(
(call: unknown[]) =>
typeof call[0] === "string" && (call[0] as string).endsWith(".plist"),
);
expect(plistUnlinks).toHaveLength(0);
});
// -----------------------------------------------------------------------
// Scenario 15: Controller port occupied β findFreePort picks next port
// -----------------------------------------------------------------------
it("Scenario 15: controller port conflict resolved via findFreePort", async () => {
const netMock = await import("node:net");
let listenCallCount = 0;
(netMock.createServer as ReturnType<typeof vi.fn>).mockImplementation(
() => {
const handlers: Record<string, ((...args: unknown[]) => void)[]> = {};
return {
once(event: string, cb: (...args: unknown[]) => void) {
if (!handlers[event]) handlers[event] = [];
handlers[event].push(cb);
},
listen(port: number, _host: string, cb: () => void) {
listenCallCount++;
if (port === 50800) {
setTimeout(
() => handlers.error?.[0]?.(new Error("EADDRINUSE")),
0,
);
} else {
setTimeout(() => cb(), 0);
}
},
close(cb: () => void) {
setTimeout(() => cb(), 0);
},
};
},
);
const { bootstrapWithLaunchd } = await import(
"../../apps/desktop/main/services/launchd-bootstrap"
);
const result = await bootstrapWithLaunchd(makeBootstrapEnv() as never);
// Controller should have been moved to 50801
expect(result.effectivePorts.controllerPort).toBe(50801);
expect(listenCallCount).toBeGreaterThanOrEqual(2);
});
// -----------------------------------------------------------------------
// Scenario 16: OpenClaw port occupied β findFreePort picks next port
// -----------------------------------------------------------------------
it("Scenario 16: openclaw port conflict resolved via findFreePort", async () => {
const netMock = await import("node:net");
(netMock.createServer as ReturnType<typeof vi.fn>).mockImplementation(
() => {
const handlers: Record<string, ((...args: unknown[]) => void)[]> = {};
return {
once(event: string, cb: (...args: unknown[]) => void) {
if (!handlers[event]) handlers[event] = [];
handlers[event].push(cb);
},
listen(port: number, _host: string, cb: () => void) {
if (port === 18789) {
setTimeout(
() => handlers.error?.[0]?.(new Error("EADDRINUSE")),
0,
);
} else {
setTimeout(() => cb(), 0);
}
},
close(cb: () => void) {
setTimeout(() => cb(), 0);
},
};
},
);
const { bootstrapWithLaunchd } = await import(
"../../apps/desktop/main/services/launchd-bootstrap"
);
const result = await bootstrapWithLaunchd(makeBootstrapEnv() as never);
expect(result.effectivePorts.openclawPort).toBe(18790);
});
// -----------------------------------------------------------------------
// Scenario 17: isDev mismatch β recovered ports not reused
// -----------------------------------------------------------------------
it("Scenario 17: isDev mismatch skips port recovery", async () => {
const fsMock = await import("node:fs/promises");
const prodPorts = makeRuntimePorts({ isDev: false, controllerPort: 44444 });
(fsMock.readFile as ReturnType<typeof vi.fn>)
.mockRejectedValueOnce(new Error("ENOENT")) // cleanup: controller plist
.mockRejectedValueOnce(new Error("ENOENT")) // cleanup: openclaw plist
.mockResolvedValueOnce(prodPorts) // stale session detection
.mockResolvedValueOnce(prodPorts); // recover phase
// Services running (from a prod session)
mockLaunchdManager.getServiceStatus.mockResolvedValue(
mockRunningService({ NEXU_HOME: "/tmp/nexu-home" }),
);
const { bootstrapWithLaunchd } = await import(
"../../apps/desktop/main/services/launchd-bootstrap"
);
const result = await bootstrapWithLaunchd(
makeBootstrapEnv({ isDev: true }) as never,
);
// Should NOT reuse prod ports β use fresh defaults
expect(result.effectivePorts.controllerPort).toBe(50800);
expect(result.isAttach).toBe(false);
});
// -----------------------------------------------------------------------
// Scenario 18: App version mismatch tears down stale services
// -----------------------------------------------------------------------
it("Scenario 18: app version mismatch tears down stale services instead of attaching", async () => {
const fsMock = await import("node:fs/promises");
const ports = makeRuntimePorts({
appVersion: "0.9.0",
openclawStateDir: "/tmp/state",
userDataPath: "/tmp/user-data",
buildSource: "packaged",
});
(fsMock.readFile as ReturnType<typeof vi.fn>)
.mockRejectedValueOnce(new Error("ENOENT"))
.mockRejectedValueOnce(new Error("ENOENT"))
.mockResolvedValueOnce(ports)
.mockResolvedValueOnce(ports);
mockLaunchdManager.getServiceStatus.mockResolvedValue(
mockRunningService({ NEXU_HOME: "/tmp/nexu-home", PORT: "50800" }),
);
const { bootstrapWithLaunchd } = await import(
"../../apps/desktop/main/services/launchd-bootstrap"
);
const result = await bootstrapWithLaunchd(
makeBootstrapEnv({
appVersion: "1.0.0",
userDataPath: "/tmp/user-data",
buildSource: "packaged",
}) as never,
);
expect(result.isAttach).toBe(false);
expect(mockLaunchdManager.bootoutAndWaitForExit).toHaveBeenCalled();
expect(mockLaunchdManager.installService).toHaveBeenCalledTimes(2);
});
// -----------------------------------------------------------------------
// Scenario 19: Build identity mismatch tears down stale services
// -----------------------------------------------------------------------
it("Scenario 19: build identity mismatch refuses cross-attach", async () => {
const fsMock = await import("node:fs/promises");
const ports = makeRuntimePorts({
appVersion: "1.0.0",
openclawStateDir: "/tmp/other-state",
userDataPath: "/tmp/other-user-data",
buildSource: "beta",
});
(fsMock.readFile as ReturnType<typeof vi.fn>)
.mockRejectedValueOnce(new Error("ENOENT"))
.mockRejectedValueOnce(new Error("ENOENT"))
.mockResolvedValueOnce(ports)
.mockResolvedValueOnce(ports);
mockLaunchdManager.getServiceStatus.mockResolvedValue(
mockRunningService({ NEXU_HOME: "/tmp/nexu-home", PORT: "50800" }),
);
const { bootstrapWithLaunchd } = await import(
"../../apps/desktop/main/services/launchd-bootstrap"
);
const result = await bootstrapWithLaunchd(
makeBootstrapEnv({
appVersion: "1.0.0",
openclawStateDir: "/tmp/state",
userDataPath: "/tmp/user-data",
buildSource: "stable",
}) as never,
);
expect(result.isAttach).toBe(false);
expect(mockLaunchdManager.bootoutAndWaitForExit).toHaveBeenCalled();
expect(mockLaunchdManager.installService).toHaveBeenCalledTimes(2);
}, 15000);
it("Scenario 19b: missing runtimeIdentityPath in old packaged metadata refuses cross-attach", async () => {
const fsMock = await import("node:fs/promises");
const runtimePorts = JSON.parse(
makeRuntimePorts({
appVersion: "1.0.0",
openclawStateDir: "/tmp/state",
userDataPath: "/tmp/user-data",
buildSource: "packaged",
}),
) as Record<string, unknown>;
const { runtimeIdentityPath: _runtimeIdentityPath, ...legacyPorts } =
runtimePorts;
const ports = JSON.stringify(legacyPorts);
(fsMock.readFile as ReturnType<typeof vi.fn>)
.mockRejectedValueOnce(new Error("ENOENT"))
.mockRejectedValueOnce(new Error("ENOENT"))
.mockResolvedValueOnce(ports)
.mockResolvedValueOnce(ports);
mockLaunchdManager.getServiceStatus.mockResolvedValue(
mockRunningService({ NEXU_HOME: "/tmp/nexu-home", PORT: "50800" }),
);
const { bootstrapWithLaunchd } = await import(
"../../apps/desktop/main/services/launchd-bootstrap"
);
const result = await bootstrapWithLaunchd(
makeBootstrapEnv({
isDev: false,
appVersion: "1.0.0",
openclawStateDir: "/tmp/state",
userDataPath: "/tmp/user-data",
buildSource: "packaged",
runtimeIdentityPath: "/Applications/Nexu-B.app/Contents/Resources",
}) as never,
);
expect(result.isAttach).toBe(false);
expect(
mockLaunchdManager.bootoutAndWaitForExit.mock.calls.length +
mockLaunchdManager.bootoutService.mock.calls.length,
).toBeGreaterThan(0);
expect(mockLaunchdManager.installService).toHaveBeenCalledTimes(2);
}, 15000);
// -----------------------------------------------------------------------
// Scenario 20: Partial attach β only controller running
// -----------------------------------------------------------------------
it("Scenario 20: partial attach with only controller running still recovers ports", async () => {
const fsMock = await import("node:fs/promises");
(fsMock.readFile as ReturnType<typeof vi.fn>)
.mockRejectedValueOnce(new Error("ENOENT")) // cleanup: controller plist
.mockRejectedValueOnce(new Error("ENOENT")) // cleanup: openclaw plist
.mockResolvedValueOnce(makeRuntimePorts()) // stale session detection
.mockResolvedValueOnce(makeRuntimePorts()); // recover phase
// Controller running, openclaw stopped
mockLaunchdManager.getServiceStatus
.mockResolvedValueOnce(
mockRunningService({ NEXU_HOME: "/tmp/nexu-home", PORT: "50800" }),
) // controller check 1
.mockResolvedValueOnce(mockStoppedService()) // openclaw check 1
.mockResolvedValueOnce(
mockRunningService({ NEXU_HOME: "/tmp/nexu-home", PORT: "50800" }),
) // controller health recheck
.mockResolvedValueOnce(mockStoppedService()) // openclaw subsequent
.mockResolvedValueOnce(mockStoppedService()) // controller after cleanup
.mockResolvedValueOnce(mockStoppedService()) // openclaw after cleanup
.mockResolvedValueOnce(mockRunningService({ PORT: "50800" })) // controller ensure
.mockResolvedValueOnce(mockRunningService({ PORT: "50800" })) // controller validate
.mockResolvedValueOnce(mockStoppedService()) // openclaw ensure
.mockResolvedValue(mockRunningService()); // openclaw running afterwards
const { bootstrapWithLaunchd } = await import(
"../../apps/desktop/main/services/launchd-bootstrap"
);
const result = await bootstrapWithLaunchd(makeBootstrapEnv() as never);
// Should still recover ports (anyRunning = true)
expect(result.effectivePorts.controllerPort).toBe(50800);
// openclaw should be installed since it's not running
expect(mockLaunchdManager.installService).toHaveBeenCalled();
});
// -----------------------------------------------------------------------
// Scenario 19: Web server both attempts fail β bootstrap throws
// -----------------------------------------------------------------------
it("Scenario 19: web server startup failure propagates as error", async () => {
const webServerMock = await import(
"../../apps/desktop/main/services/embedded-web-server"
);
// All attempts fail with EADDRINUSE (5 adjacent ports + port 0 fallback)
(
webServerMock.startEmbeddedWebServer as ReturnType<typeof vi.fn>
).mockRejectedValue(
Object.assign(new Error("EADDRINUSE"), { code: "EADDRINUSE" }),
);
const { bootstrapWithLaunchd } = await import(
"../../apps/desktop/main/services/launchd-bootstrap"
);
await expect(
bootstrapWithLaunchd(makeBootstrapEnv() as never),
).rejects.toThrow("all port attempts exhausted");
});
// -----------------------------------------------------------------------
// Scenario 20: Prod labels used when isDev=false
// -----------------------------------------------------------------------
it("Scenario 20: prod mode uses non-dev labels and plist dir", async () => {
const { bootstrapWithLaunchd } = await import(
"../../apps/desktop/main/services/launchd-bootstrap"
);
const result = await bootstrapWithLaunchd(
makeBootstrapEnv({ isDev: false }) as never,
);
expect(result.labels.controller).toBe("io.nexu.controller");
expect(result.labels.openclaw).toBe("io.nexu.openclaw");
});
// -----------------------------------------------------------------------
// Scenario 21: Only controller plist stale, openclaw ok β partial cleanup
// -----------------------------------------------------------------------
it("Scenario 21: partial stale cleanup β only stale plist is removed", async () => {
const fsMock = await import("node:fs/promises");
const plistGen = await import(
"../../apps/desktop/main/services/plist-generator"
);
const currentOpenclawPlist = (
plistGen.generatePlist as ReturnType<typeof vi.fn>
)("openclaw");
(fsMock.readFile as ReturnType<typeof vi.fn>)
// controller plist: STALE
.mockResolvedValueOnce("<plist>old-controller</plist>")