Repository navigation
Expand file tree
/
Copy pathtest.js
More file actions
executable file
·3531 lines (3370 loc) · 129 KB
/
Copy pathtest.js
File metadata and controls
executable file
·3531 lines (3370 loc) · 129 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
#!/usr/bin/env node
"use strict";
const assert = require("node:assert/strict");
const { spawn, spawnSync } = require("node:child_process");
const { EventEmitter, once } = require("node:events");
const fs = require("node:fs");
const net = require("node:net");
const os = require("node:os");
const path = require("node:path");
const { PassThrough } = require("node:stream");
const test = require("node:test");
const vm = require("node:vm");
const { makeSocketTempDir: makeUnixSocketTempDir } = require("../../scripts/lib/unix-socket-dir.test-helpers.js");
const {
loadLinuxFeaturePatchDescriptors,
stageEnabledLinuxFeatureInstall,
} = require("../../scripts/lib/linux-features.js");
const {
applySharedAppServerSocketPatch,
descriptors,
sharedTransportClassSource,
} = require("./patch.js");
const socketEnvHook = path.join(__dirname, "socket-env.sh");
const orphanReaper = path.join(__dirname, "orphan-reaper.js");
const attachedCli = path.join(__dirname, "attached-cli.sh");
const testRuntimeRoot = fs.mkdtempSync(
path.join(os.tmpdir(), "shared-app-server-socket-test-runtime-"),
);
const originalRuntimeDir = process.env.XDG_RUNTIME_DIR;
const originalStateDir = process.env.CODEX_LINUX_APP_STATE_DIR;
process.env.XDG_RUNTIME_DIR = testRuntimeRoot;
process.env.CODEX_LINUX_APP_STATE_DIR = testRuntimeRoot;
test.after(() => {
if (originalRuntimeDir == null) delete process.env.XDG_RUNTIME_DIR;
else process.env.XDG_RUNTIME_DIR = originalRuntimeDir;
if (originalStateDir == null) delete process.env.CODEX_LINUX_APP_STATE_DIR;
else process.env.CODEX_LINUX_APP_STATE_DIR = originalStateDir;
fs.rmSync(testRuntimeRoot, { recursive: true, force: true });
});
// XDG_RUNTIME_DIR now names this file's own runtime root under TMPDIR, so the
// fallback for a long TMPDIR is the host's runtime dir.
function makeSocketTempDir(prefix, socketRelativePath = "app-server.sock") {
return makeUnixSocketTempDir(prefix, socketRelativePath, { runtimeDir: originalRuntimeDir });
}
function createProcessSnapshotFs(processesByPid) {
const snapshotsByPid = new Map();
const processForPath = (procPath) => {
const match = procPath.match(/^\/proc\/(\d+)(?:\/(stat|cmdline))?$/);
if (match == null) throw new Error(`unexpected proc path: ${procPath}`);
const pid = Number(match[1]);
const file = match[2];
if (file == null) {
const entry = processesByPid.get(pid);
const processInfo = typeof entry === "function" ? entry() : entry;
if (processInfo != null) snapshotsByPid.set(pid, processInfo);
}
const processInfo = snapshotsByPid.get(pid);
if (processInfo == null) {
const error = new Error(`process ${pid} does not exist`);
error.code = "ENOENT";
throw error;
}
return { processInfo, file };
};
return {
statSync(procPath) {
return { uid: processForPath(procPath).processInfo.uid };
},
readFileSync(procPath) {
const { processInfo, file } = processForPath(procPath);
if (file === "stat") {
return `0 (${processInfo.comm ?? path.basename(processInfo.commandLine[0])}) ${processInfo.state} ${processInfo.ppid} ${Array(17)
.fill("0")
.join(" ")} ${processInfo.startTime}`;
}
if (file === "cmdline") return Buffer.from(`${processInfo.commandLine.join("\0")}\0`);
throw new Error(`unexpected proc file read: ${procPath}`);
},
};
}
function loadOrphanReaperVerifier(processesByPid) {
const source = fs.readFileSync(orphanReaper, "utf8");
const verifierSource = source.replace(
/reapOrphan\(\)\.catch\(\(error\) => \{[\s\S]*?\n\}\);\s*$/,
"globalThis.orphanReaperVerifier = { verifiedOrphanTargets };\n",
);
assert.notEqual(verifierSource, source, "orphan reaper entrypoint must remain replaceable");
const uid = typeof process.getuid === "function" ? process.getuid() : null;
const mockFs = createProcessSnapshotFs(processesByPid);
const context = {
process: {
argv: [process.execPath, orphanReaper, "/test/app-server.sock"],
getuid: () => uid,
},
require(id) {
if (id === "node:fs") return mockFs;
if (id === "node:path") return path;
if (id === "./socket-path.js") return require("./socket-path.js");
throw new Error(`unexpected orphan reaper dependency: ${id}`);
},
};
vm.runInNewContext(verifierSource, context, { filename: orphanReaper });
return context.orphanReaperVerifier.verifiedOrphanTargets;
}
function loadOrphanReaperAdoptionPredicate() {
const source = fs.readFileSync(orphanReaper, "utf8");
const predicateSource = source.replace(
/reapOrphan\(\)\.catch\(\(error\) => \{[\s\S]*?\n\}\);\s*$/,
"globalThis.orphanReaperAdoption = { readProcess, hasExpectedOrphanAdoption };\n",
);
assert.notEqual(predicateSource, source, "orphan reaper entrypoint must remain replaceable");
const uid = typeof process.getuid === "function" ? process.getuid() : null;
const context = {
process: {
argv: [process.execPath, orphanReaper, "/test/app-server.sock"],
getuid: () => uid,
},
require(id) {
if (id === "node:fs") return fs;
if (id === "node:path") return path;
if (id === "./socket-path.js") return require("./socket-path.js");
throw new Error(`unexpected orphan reaper dependency: ${id}`);
},
};
vm.runInNewContext(predicateSource, context, { filename: orphanReaper });
return context.orphanReaperAdoption;
}
const orphanReaperAdoption = loadOrphanReaperAdoptionPredicate();
function startOrphanReaperWithChangedAdopter() {
const socketPath = "/test/app-server.sock";
const lockPath = `${socketPath}.lock`;
const lockContents = "99999999 1 2001 100\n";
const uid = process.getuid();
const authority = {
pid: 2001,
uid,
state: "S",
ppid: 1235,
startTime: "100",
comm: "codex",
commandLine: ["/usr/bin/codex", "app-server", "--listen", `unix://${socketPath}`],
};
const validAdopter = {
pid: 1235,
uid,
state: "S",
ppid: 1,
startTime: "99",
comm: "systemd",
commandLine: ["/nix/store/0123456789abcdef-systemd-257.6/lib/systemd/systemd", "--user"],
};
const changedAdopter = { ...validAdopter, ppid: 321 };
let adopterReads = 0;
const processesByPid = new Map([
[authority.pid, authority],
[validAdopter.pid, () => (adopterReads++ < 2 ? validAdopter : changedAdopter)],
]);
const procFs = createProcessSnapshotFs(processesByPid);
const socket = { dev: 1, ino: 2, uid, isSocket: () => true };
const lock = { dev: 3, ino: 4 };
const listenerInode = "9876";
const signals = [];
const mockFs = {
openSync(filePath) {
if (filePath === lockPath) return 17;
throw new Error(`unexpected open: ${filePath}`);
},
fstatSync(descriptor) {
if (descriptor === 17) return lock;
throw new Error(`unexpected descriptor: ${descriptor}`);
},
closeSync() {},
statSync: procFs.statSync,
lstatSync(filePath) {
if (filePath === socketPath) return socket;
if (filePath === lockPath) return lock;
const error = new Error(`missing path: ${filePath}`);
error.code = "ENOENT";
throw error;
},
readFileSync(filePath) {
if (filePath === 17 || filePath === lockPath) return lockContents;
if (filePath === "/proc/net/unix") {
return `0000000000000000: 00000002 00000000 00010000 0001 01 ${listenerInode} ${socketPath}\n`;
}
return procFs.readFileSync(filePath);
},
readdirSync(filePath) {
if (filePath === "/proc") {
return [{ name: String(authority.pid), isDirectory: () => true }];
}
if (filePath === `/proc/${authority.pid}/fd`) return ["5"];
throw new Error(`unexpected directory read: ${filePath}`);
},
readlinkSync(filePath) {
if (filePath === `/proc/${authority.pid}/fd/5`) return `socket:[${listenerInode}]`;
throw new Error(`unexpected link read: ${filePath}`);
},
};
const source = fs.readFileSync(orphanReaper, "utf8");
const reaperSource = source.replace(
/reapOrphan\(\)\.catch\(\(error\) => \{[\s\S]*?\n\}\);\s*$/,
"globalThis.reaperPromise = reapOrphan();\n",
);
assert.notEqual(reaperSource, source, "orphan reaper entrypoint must remain replaceable");
const context = {
process: {
argv: [process.execPath, orphanReaper, socketPath],
getuid: () => uid,
kill(pid, signal) {
signals.push({ pid, signal });
return true;
},
},
console: { error() {} },
require(id) {
if (id === "node:fs") return mockFs;
if (id === "node:path") return path;
if (id === "./socket-path.js") return require("./socket-path.js");
throw new Error(`unexpected orphan reaper dependency: ${id}`);
},
};
vm.runInNewContext(reaperSource, context, { filename: orphanReaper });
return { reaperPromise: context.reaperPromise, signals };
}
function authorityProcess({ pid, ppid }) {
return {
pid,
uid: process.getuid(),
state: "S",
ppid,
startTime: "100",
commandLine: ["/usr/bin/codex", "app-server", "--listen", "unix:///test/app-server.sock"],
};
}
function lockedAuthority(authority) {
return {
authorityPid: authority.pid,
authorityStartTime: authority.startTime,
};
}
function withFeatureConfig(enabled, callback) {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "shared-app-server-socket-feature-"));
const configPath = path.join(tempDir, "features.json");
const originalConfig = process.env.CODEX_LINUX_FEATURES_CONFIG;
try {
fs.writeFileSync(configPath, `${JSON.stringify({ enabled })}\n`);
process.env.CODEX_LINUX_FEATURES_CONFIG = configPath;
return callback(path.resolve(__dirname, ".."));
} finally {
if (originalConfig == null) delete process.env.CODEX_LINUX_FEATURES_CONFIG;
else process.env.CODEX_LINUX_FEATURES_CONFIG = originalConfig;
fs.rmSync(tempDir, { recursive: true, force: true });
}
}
function procStat(pid, { state = "S", ppid, startTime, utime = "0" }) {
const fields = Array(17).fill("0");
fields[9] = utime;
return `${pid} (codex) ${state} ${ppid} ${fields.join(" ")} ${startTime}\n`;
}
function writeAttachedCliFixtureFile(filePath, contents, mode) {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, contents);
fs.chmodSync(filePath, mode);
}
function createAttachedCliFixture() {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "shared-app-server-attached-cli-"));
const appId = "codex-desktop";
const ownerPid = 41001;
const authorityPid = 41002;
const ownerStartTime = "7001";
const authorityStartTime = "7002";
const listenerInode = "9001";
const recordDir = path.join(root, "runtime", appId, "app-server-bridge");
const socketDir = path.join(root, "runtime", appId, "socket-private");
const socketPath = path.join(socketDir, "app-server.sock");
const lockPath = `${socketPath}.lock`;
const recordPath = path.join(recordDir, "attached-cli-v1");
const procRoot = path.join(root, "proc");
const appDir = path.join(root, "app");
const desktopPath = path.join(root, "bin", "ChatGPT");
const codexPath = path.join(appDir, "resources", "codex");
fs.mkdirSync(recordDir, { recursive: true, mode: 0o700 });
fs.chmodSync(recordDir, 0o700);
fs.mkdirSync(socketDir, { recursive: true, mode: 0o700 });
fs.chmodSync(socketDir, 0o700);
writeAttachedCliFixtureFile(desktopPath, "desktop fixture\n", 0o755);
writeAttachedCliFixtureFile(
codexPath,
"#!/usr/bin/env bash\nprintf '%s\\0' \"$@\" >\"${ATTACHED_TEST_ARGV_FILE:?}\"\nif [[ -n ${ATTACHED_TEST_READY_FILE:-} ]]; then\n : >\"$ATTACHED_TEST_READY_FILE\"\n exec sleep 60\nfi\nexit \"${ATTACHED_TEST_EXIT_STATUS:-0}\"\n",
0o755,
);
writeAttachedCliFixtureFile(socketPath, "socket fixture\n", 0o600);
writeAttachedCliFixtureFile(
lockPath,
`${ownerPid} ${ownerStartTime} ${authorityPid} ${authorityStartTime}\n`,
0o600,
);
writeAttachedCliFixtureFile(
recordPath,
[
"version=1",
`app_id=${appId}`,
`socket=${socketPath}`,
`desktop=${desktopPath}`,
`codex=${codexPath}`,
"",
].join("\n"),
0o600,
);
for (const [pid, processInfo] of [
[ownerPid, { ppid: 1, startTime: ownerStartTime, executable: desktopPath }],
[authorityPid, { ppid: ownerPid, startTime: authorityStartTime, executable: codexPath }],
]) {
const processDir = path.join(procRoot, String(pid));
fs.mkdirSync(processDir, { recursive: true, mode: 0o755 });
fs.mkdirSync(path.join(processDir, "fd"), { mode: 0o700 });
writeAttachedCliFixtureFile(
path.join(processDir, "stat"),
procStat(pid, processInfo),
0o444,
);
const commandLine =
pid === ownerPid
? [desktopPath]
: [
codexPath,
"-c",
"model=fixture",
"app-server",
"--listen",
`unix://${socketPath}`,
];
writeAttachedCliFixtureFile(
path.join(processDir, "cmdline"),
Buffer.from(`${commandLine.join("\0")}\0`),
0o444,
);
fs.symlinkSync(processInfo.executable, path.join(processDir, "exe"));
if (pid === authorityPid) {
fs.symlinkSync(`socket:[${listenerInode}]`, path.join(processDir, "fd", "5"));
}
fs.chmodSync(path.join(processDir, "fd"), 0o500);
fs.chmodSync(processDir, 0o555);
}
writeAttachedCliFixtureFile(
path.join(procRoot, "net", "unix"),
`0000000000000000: 00000002 00000000 00010000 0001 01 ${listenerInode} ${socketPath}\n`,
0o444,
);
return {
appDir,
appId,
authorityPid,
authorityStartTime,
codexPath,
desktopPath,
listenerInode,
lockPath,
ownerPid,
ownerStartTime,
procRoot,
recordDir,
recordPath,
root,
socketDir,
socketPath,
};
}
function attachedCliMetadata(filePath, fixture, changes = {}) {
const metadata = fs.lstatSync(filePath);
let kind;
if (filePath === fixture.socketPath) kind = "socket";
else if (metadata.isSymbolicLink()) kind = "symbolic link";
else if (metadata.isDirectory()) kind = "directory";
else if (metadata.isFile()) kind = "regular file";
else kind = "unknown";
return [
changes.kind ?? kind,
changes.mode ?? (metadata.mode & 0o777).toString(8),
String(changes.uid ?? metadata.uid),
String(changes.dev ?? metadata.dev),
String(changes.ino ?? metadata.ino),
changes.linkTarget ?? (metadata.isSymbolicLink() ? fs.readlinkSync(filePath) : ""),
].join("\t");
}
function removeAttachedCliFixture(fixture) {
for (const pid of [fixture.ownerPid, fixture.authorityPid]) {
const processDir = path.join(fixture.procRoot, String(pid));
try {
fs.chmodSync(processDir, 0o700);
fs.chmodSync(path.join(processDir, "fd"), 0o700);
} catch (error) {
if (error.code !== "ENOENT") throw error;
}
}
fs.rmSync(fixture.root, { recursive: true, force: true });
}
function writeAttachedCliProcessFile(fixture, pid, name, contents) {
const filePath = path.join(fixture.procRoot, String(pid), name);
fs.chmodSync(filePath, 0o644);
fs.writeFileSync(filePath, contents);
fs.chmodSync(filePath, 0o444);
}
function replaceAttachedCliProcessExe(fixture, pid, executable) {
const processDir = path.join(fixture.procRoot, String(pid));
const exePath = path.join(processDir, "exe");
fs.chmodSync(processDir, 0o755);
fs.unlinkSync(exePath);
fs.symlinkSync(executable, exePath);
fs.chmodSync(processDir, 0o555);
}
function selectAttachedCliSymlink(fixture) {
const selected = path.join(fixture.root, "selected-codex");
fs.symlinkSync(fixture.codexPath, selected);
fs.writeFileSync(fixture.recordPath,
fs.readFileSync(fixture.recordPath, "utf8").replace(`codex=${fixture.codexPath}`, `codex=${selected}`));
const cmdline = path.join(fixture.procRoot, String(fixture.authorityPid), "cmdline");
writeAttachedCliProcessFile(fixture, fixture.authorityPid, "cmdline",
fs.readFileSync(cmdline).toString("utf8").replace(fixture.codexPath, selected));
return selected;
}
const attachedCliSourcedTestPrelude = [
'source "$1"',
"attached_cli_effective_uid() {",
" printf '%s\\n' \"$ATTACHED_TEST_UID\"",
"}",
"attached_cli_filesystem_metadata() {",
" local target=$1 metadata kind link= _mode _uid _dev _ino",
' if [[ -n ${ATTACHED_TEST_MISSING_PATH:-} && $target == "$ATTACHED_TEST_MISSING_PATH" ]]; then',
" return 1",
" fi",
' if [[ -n ${ATTACHED_TEST_OVERRIDE_PATH:-} && $target == "$ATTACHED_TEST_OVERRIDE_PATH" ]]; then',
" printf '%s\\n' \"$ATTACHED_TEST_OVERRIDE_METADATA\"",
" return 0",
" fi",
" metadata=$(stat -c $'%F\\t%a\\t%u\\t%d\\t%i' -- \"$target\" 2>/dev/null) || return 1",
" kind=${metadata%%$'\\t'*}",
' if [[ $target == "$ATTACHED_TEST_SOCKET" ]]; then',
" metadata=\"socket\"$'\\t'\"${metadata#*$'\\t'}\"",
" kind=socket",
" fi",
// Regular fixture symlinks have mode 777; real read/write proc FD links have mode 700.
' if [[ $target == "$ATTACHED_TEST_PROC"/*/fd/* && $kind == "symbolic link" ]]; then',
" IFS=$'\\t' read -r kind _mode _uid _dev _ino <<<\"$metadata\"",
" metadata=\"$kind\"$'\\t'700$'\\t'\"$_uid\"$'\\t'\"$_dev\"$'\\t'\"$_ino\"",
" fi",
' if [[ $kind == "symbolic link" ]]; then',
' link=$(readlink -- "$target" 2>/dev/null) || return 1',
" fi",
" printf '%s\\t%s\\n' \"$metadata\" \"$link\"",
"}",
].join("\n");
function runAttachedCliSnapshot(fixture, options = {}) {
const script = [
attachedCliSourcedTestPrelude,
'attached_cli_snapshot "$2" "$3"',
].join("\n");
return spawnSync(
"bash",
["-c", script, "attached-cli-test", attachedCli, fixture.recordDir, fixture.procRoot],
{
encoding: "utf8",
env: attachedCliTestEnvironment(fixture, options),
},
);
}
function attachedCliTestEnvironment(fixture, options = {}) {
return {
...process.env,
...options.environment,
ATTACHED_TEST_ARGV_FILE: path.join(fixture.root, "codex.argv"),
ATTACHED_TEST_MISSING_PATH: options.missingPath ?? "",
ATTACHED_TEST_OVERRIDE_METADATA: options.overrideMetadata ?? "",
ATTACHED_TEST_OVERRIDE_PATH: options.overridePath ?? "",
ATTACHED_TEST_PROC: fixture.procRoot,
ATTACHED_TEST_SOCKET: fixture.socketPath,
ATTACHED_TEST_UID: String(process.getuid()),
CODEX_LINUX_APP_DIR: fixture.appDir,
};
}
async function waitForAttachedCliFile(filePath, child) {
for (let attempt = 0; attempt < 200; attempt += 1) {
if (fs.existsSync(filePath)) return;
if (child.exitCode != null) {
throw new Error(`attached CLI exited before creating ${path.basename(filePath)}`);
}
await new Promise((resolve) => setTimeout(resolve, 10));
}
throw new Error(`timed out waiting for ${path.basename(filePath)}`);
}
function attachedCliMainCommand() {
return [
attachedCliSourcedTestPrelude,
"record_dir=$2",
"proc_root=$3",
"shift 3",
'attached_cli_main "$record_dir" "$proc_root" "$@"',
].join("\n");
}
function runAttachedCliMain(fixture, arguments_ = [], options = {}) {
return spawnSync(
"bash",
[
"-c",
attachedCliMainCommand(),
"attached-cli-test",
attachedCli,
fixture.recordDir,
fixture.procRoot,
...arguments_,
],
{
encoding: "utf8",
env: attachedCliTestEnvironment(fixture, options),
},
);
}
function spawnAttachedCliMain(fixture, arguments_ = [], options = {}) {
return spawn(
"bash",
[
"-c",
attachedCliMainCommand(),
"attached-cli-test",
attachedCli,
fixture.recordDir,
fixture.procRoot,
...arguments_,
],
{
env: attachedCliTestEnvironment(fixture, options),
stdio: ["ignore", "pipe", "pipe"],
},
);
}
async function attachedCliChildResult(child) {
const stdout = [];
const stderr = [];
child.stdout.on("data", (chunk) => stdout.push(chunk));
child.stderr.on("data", (chunk) => stderr.push(chunk));
const [code, signal] = await once(child, "exit");
return {
code,
signal,
stdout: Buffer.concat(stdout).toString("utf8"),
stderr: Buffer.concat(stderr).toString("utf8"),
};
}
function readNulArguments(filePath) {
const parts = fs.readFileSync(filePath).toString("utf8").split("\0");
assert.equal(parts.pop(), "");
return parts;
}
async function waitForSocket(socketPath, child) {
for (let attempt = 0; attempt < 100; attempt += 1) {
if (child.exitCode != null) {
throw new Error(`app-server exited before creating its socket (${child.exitCode})`);
}
try {
if (fs.statSync(socketPath).isSocket()) return;
} catch (error) {
if (error.code !== "ENOENT") throw error;
}
await new Promise((resolve) => setTimeout(resolve, 50));
}
throw new Error("timed out waiting for the app-server socket");
}
async function readWebSocketUpgrade(child) {
const chunks = [];
return new Promise((resolve, reject) => {
const timeout = setTimeout(
() => reject(new Error("timed out waiting for WebSocket upgrade")),
5000,
);
const finish = (error, value) => {
clearTimeout(timeout);
child.stdout.off("data", onData);
child.off("error", onError);
if (error) reject(error);
else resolve(value);
};
const onError = (error) => finish(error);
const onData = (chunk) => {
chunks.push(chunk);
const response = Buffer.concat(chunks).toString("utf8");
if (response.includes("\r\n\r\n")) finish(null, response);
};
child.stdout.on("data", onData);
child.once("error", onError);
});
}
async function stopChild(child, signal = "SIGTERM") {
if (child == null || child.exitCode != null || child.signalCode != null) return;
const closed = new Promise((resolve) => child.once("close", resolve));
child.kill(signal);
await closed;
}
function fakeChild() {
const child = new EventEmitter();
child.pid = process.pid;
child.exitCode = null;
child.signalCode = null;
child.stdin = new PassThrough();
child.stdout = new PassThrough();
child.stderr = new PassThrough();
child.killed = false;
child.kill = () => {
child.killed = true;
child.signalCode = "SIGTERM";
queueMicrotask(() => child.emit("close", null, "SIGTERM"));
return true;
};
return child;
}
function loadInjectedTransport({ spawnImpl, WebSocketImpl = null, fsImpl = fs, timeoutCapMs = null } = {}) {
class DefaultWebSocket extends EventEmitter {
constructor(_url, options) {
super();
this.stream = options.createConnection();
queueMicrotask(() => this.emit("open"));
}
terminate() {
this.terminated = true;
this.stream?.destroy();
}
}
class Adapter {
constructor(socket) {
this.socket = socket;
}
}
const namespace = {
WS: WebSocketImpl ?? DefaultWebSocket,
keepAlive() {},
Codec: class {},
Adapter,
};
const source = sharedTransportClassSource({
webSocketClass: "n.WS",
webSocketUrl: '"ws://localhost/rpc"',
keepAlive: "n.keepAlive",
adapterClass: "n.Adapter",
codecClass: "n.Codec",
maximumFrameBytes: "0x1000000",
maximumFrameHeader: '"frame-limit"',
});
const context = {
n: namespace,
process,
console,
require(id) {
if (id === "node:child_process") return { spawn: spawnImpl };
if (id === "node:fs") return fsImpl;
return require(id);
},
setTimeout(callback, delay, ...args) {
const timer = setTimeout(
callback,
timeoutCapMs == null ? delay : Math.min(delay, timeoutCapMs),
...args,
);
if (timeoutCapMs != null) timer.unref = () => timer;
return timer;
},
clearTimeout,
};
vm.runInNewContext(`${source};globalThis.Transport=CodexLinuxSharedAppServerSocketTransport`, context);
const InjectedTransport = context.Transport;
class Transport extends InjectedTransport {
constructor(socketPath, getConfigOverrides = async () => []) {
super(socketPath, getConfigOverrides);
}
}
return { InjectedTransport, Transport, namespace };
}
async function listenUnix(socketPath) {
const server = net.createServer();
await new Promise((resolve, reject) => {
server.once("error", reject);
server.listen(socketPath, resolve);
});
return server;
}
async function closeServer(server) {
if (server == null) return;
await new Promise((resolve) => server.close(resolve));
}
async function withAttachedCliEnvironment(values, callback) {
const keys = [
"CODEX_CLI_PATH",
"CODEX_LINUX_APP_ID",
"CODEX_LINUX_APP_STATE_DIR",
"XDG_RUNTIME_DIR",
];
const previous = new Map(keys.map((key) => [key, process.env[key]]));
try {
for (const key of keys) {
if (values[key] == null) delete process.env[key];
else process.env[key] = values[key];
}
return await callback();
} finally {
for (const key of keys) {
const value = previous.get(key);
if (value == null) delete process.env[key];
else process.env[key] = value;
}
}
}
function processStartTime(pid) {
try {
const rawStat = fs.readFileSync(`/proc/${pid}/stat`, "utf8");
const commandEnd = rawStat.lastIndexOf(")");
if (commandEnd < 0) return null;
return rawStat.slice(commandEnd + 2).trim().split(/\s+/)[19] ?? null;
} catch (error) {
if (error.code === "ENOENT") return null;
throw error;
}
}
function hasLegitimateOrphanAdoption(pid) {
const authority = orphanReaperAdoption.readProcess(pid);
return authority != null && orphanReaperAdoption.hasExpectedOrphanAdoption(authority);
}
function unixListenerInodes(socketPath) {
const inodes = new Set();
for (const line of fs.readFileSync("/proc/net/unix", "utf8").split("\n")) {
const match = line.match(
/^\S+:\s+\S+\s+\S+\s+\S+\s+(\S+)\s+(\S+)\s+(\d+)(?:\s+(.*))?$/,
);
if (
match != null &&
match[1] === "0001" &&
match[2] === "01" &&
match[4] === socketPath
) {
inodes.add(match[3]);
}
}
return [...inodes];
}
async function waitForCondition(predicate, description) {
const deadline = Date.now() + 5000;
while (Date.now() < deadline) {
if (predicate()) return;
await new Promise((resolve) => setTimeout(resolve, 25));
}
throw new Error(`timed out waiting for ${description}`);
}
async function spawnOrphanAuthority(socketPath, alias = false) {
const listenerScript = [
'const net=require("node:net");',
'const socketPath=process.argv.at(-1).replace("unix://","");',
"const server=net.createServer();",
'const target=process.env.SOCKET_ALIAS==="1"?`${socketPath}.target`:socketPath;',
'server.listen(target,()=>{if(target!==socketPath){const fs=require("node:fs");fs.chmodSync(target,0o600);fs.symlinkSync(target,socketPath)}});',
'process.on("SIGTERM",()=>server.close(()=>process.exit(0)));',
].join("");
const wrapperScript = [
'const {spawn}=require("node:child_process");',
"const child=spawn(process.execPath,",
'[ "-e",process.env.LISTENER_SCRIPT,"app-server","--listen",process.env.LISTEN_URL],',
'{stdio:"ignore",env:process.env});',
'process.on("SIGTERM",()=>{',
' try{child.kill("SIGTERM")}catch{}',
" child.once('exit',()=>process.exit(0));",
" setTimeout(()=>process.exit(0),1000).unref();",
"});",
"setInterval(()=>{},1000);",
].join("");
const bootstrapScript = [
'const {spawn}=require("node:child_process");',
"const child=spawn(process.execPath,",
'[ "-e",process.env.WRAPPER_SCRIPT,"app-server","--listen",process.env.LISTEN_URL],',
'{detached:true,stdio:"ignore",env:process.env});',
"process.stdout.write(`${child.pid}\\n`);",
"child.unref();",
].join("");
const result = spawnSync(process.execPath, ["-e", bootstrapScript], {
encoding: "utf8",
env: {
...process.env,
SOCKET_ALIAS: alias ? "1" : "0",
LISTENER_SCRIPT: listenerScript,
LISTEN_URL: `unix://${socketPath}`,
WRAPPER_SCRIPT: wrapperScript,
},
});
assert.equal(result.status, 0, result.stderr);
const pid = Number(result.stdout.trim());
assert.equal(Number.isSafeInteger(pid), true);
const startTime = processStartTime(pid);
assert.notEqual(startTime, null);
try {
await waitForCondition(
() => hasLegitimateOrphanAdoption(pid) && fs.existsSync(socketPath),
"detached authority to be adopted by PID 1 or the systemd user manager",
);
} catch (error) {
stopOrphanAuthority({ pid, startTime });
throw error;
}
return { pid, startTime };
}
function stopOrphanAuthority(orphan) {
if (orphan == null || processStartTime(orphan.pid) !== orphan.startTime) return;
try {
process.kill(orphan.pid, "SIGTERM");
} catch (error) {
if (error.code !== "ESRCH") throw error;
}
}
// Mirrors the rspack/SWC-minified 26.1027 main-process chunk: double-quoted
// strings, literal-first comparisons, `(0,ns.fn)(...)` calls, and handshake
// constants inlined into the SSH method.
function syntheticBundle() {
return [
'class gC{options;kind="websocket";logger=(0,i.i)("AppServerTransportSshWebsocket");proxyStreams=new Set;hasConnected=!1;supportsReconnect(){return!0}',
'async connectToRemoteAppServer(e,t){return this.runWithSshStartupGate(async()=>{let t={current:null},h=(0,n.hd)(),r=new w.kn("ws://codex-app-server/rpc",{perMessageDeflate:!1,headers:h,createConnection:()=>',
"(t.current=this.createSshProxyStream(),t.current)}),o={current:null},a=e=>{o.current=o.current??e};r.on(\"error\",a);",
'let s=64;r.once("upgrade",e=>{let t=Number(e.headers["frame-limit"]);Number.isSafeInteger(t)&&t>0&&(s=t)});let c=new n.Codec(r,null!=h);r.once("close",()=>{t.current?.destroy()});',
"try{if(await opened(r),null!=o.current)throw o.current}catch(e){throw t.current?.destroy(),r.terminate(),e}",
'let i=new n.On(r,void 0,s,c);return r.off("error",a),this.logger.info("app_server_connection.compression_negotiated",{safe:{compression:c.compression}}),(0,n.Dn)(r,{onPongTimeout:()=>{i.terminationReason="pong_timeout",r.terminate()}}),this.hasConnected=!0,i})}}',
'let v5=(0,i.i)("WindowContext");function b5(e){let t=_C(e.hostConfig);if(t)return v5.info("[ssh-websocket-v0] selected app-server transport"),new gC(t);',
'if("remote-control"===e.transportKind)return new Remote(e);',
'if((0,n.no)(e.hostConfig))return new hoe({hostConfig:e.hostConfig,repoRoot:e.repoRoot,resourcesPath:e.resourcesPath,defaultOriginator:e.defaultOriginator});',
'let r=x5(e.hostConfig);if(r){e.desktopAuthAppServerClient;let t=vbe(e.hostConfig,r);return new n.Tn({hostConfig:e.hostConfig,websocketUrl:r,getWebsocketProtocols:void 0,...null==t?{}:{socksProxyUrl:t}})}',
'return new n.Cn({hostConfig:e.hostConfig,repoRoot:e.repoRoot,resourcesPath:e.resourcesPath,defaultOriginator:e.defaultOriginator,getConfigOverrides:async()=>[...await Ope(e)]})}function afterFactory(){}',
].join("");
}
test("shared-app-server-socket stays disabled until explicitly enabled", () => {
withFeatureConfig([], (featuresRoot) => {
assert.deepEqual(loadLinuxFeaturePatchDescriptors({ featuresRoot }), []);
});
withFeatureConfig(["shared-app-server-socket"], (featuresRoot) => {
assert.deepEqual(
loadLinuxFeaturePatchDescriptors({ featuresRoot }).map((entry) => entry.id),
["feature:shared-app-server-socket:main-process-shared-app-server-socket"],
);
});
});
test("feature stages its socket hooks, orphan reaper, and attached CLI", () => {
withFeatureConfig(["shared-app-server-socket"], (featuresRoot) => {
const appDir = fs.mkdtempSync(path.join(os.tmpdir(), "shared-app-server-socket-app-"));
try {
const plan = stageEnabledLinuxFeatureInstall(appDir, { featuresRoot });
assert.deepEqual(
plan.runtimeHooks.map((hook) => [hook.key, path.basename(hook.target), hook.mode.toString(8)]),
[
["launcher", "shared-app-server-socket-socket-env.sh", "755"],
["afterExit", "shared-app-server-socket-socket-cleanup.sh", "755"],
],
);
assert.deepEqual(
plan.resources.map((resource) => [
resource.target,
resource.mode.toString(8),
]),
[
[".codex-linux/features/shared-app-server-socket/socket-path.js", "644"],
[
".codex-linux/features/shared-app-server-socket/orphan-reaper.js",
"644",
],
[
".codex-linux/features/shared-app-server-socket/attached-cli.sh",
"755",
],
],
);
const target = ".codex-linux/features/shared-app-server-socket/attached-cli.sh";
const staged = path.join(appDir, target);
assert.equal(fs.lstatSync(staged).isFile(), true);
assert.equal(fs.statSync(staged).mode & 0o777, 0o755);
} finally {
fs.rmSync(appDir, { recursive: true, force: true });
}
});
});
test("attached CLI metadata is locale stable in sourced and direct modes", () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "shared-app-server-attached-cli-locale-"));
try {
const runtimeRoot = path.join(root, "runtime");
const recordDir = path.join(runtimeRoot, "codex-desktop", "app-server-bridge");
const binDir = path.join(root, "bin");
const statWrapper = path.join(binDir, "stat");
const realStat = spawnSync("bash", ["-c", "command -v stat"], { encoding: "utf8" });
assert.equal(realStat.status, 0, realStat.stderr);
fs.mkdirSync(recordDir, { recursive: true, mode: 0o700 });
fs.chmodSync(recordDir, 0o700);
writeAttachedCliFixtureFile(
statWrapper,
[
"#!/usr/bin/env bash",
'metadata=$("$ATTACHED_TEST_REAL_STAT" "$@") || exit $?',
"if [[ ${LANGUAGE-} == de && ${LC_ALL-} != C ]]; then",
" metadata=${metadata/#directory/Verzeichnis}",
"fi",
"printf '%s\\n' \"$metadata\"",
"",
].join("\n"),
0o755,
);
const environment = {
...process.env,
ATTACHED_TEST_REAL_STAT: realStat.stdout.trim(),
CODEX_LINUX_APP_ID: "codex-desktop",
LANG: "C",
LANGUAGE: "de",
PATH: `${binDir}:${process.env.PATH}`,
XDG_RUNTIME_DIR: runtimeRoot,
};
delete environment.LC_ALL;
const sourced = spawnSync(
"bash",
[
"-c",
'source "$1"; attached_cli_main "$2" /proc exec',
"attached-cli-locale-test",
attachedCli,
recordDir,
],
{ encoding: "utf8", env: environment },
);
assert.equal(sourced.status, 1, sourced.stderr);
assert.equal(sourced.stdout, "");
assert.equal(sourced.stderr, "codex-desktop: Desktop shared app server is not available\n");
const direct = spawnSync("bash", [attachedCli, "exec"], {
encoding: "utf8",
env: environment,
});
assert.equal(direct.status, 1, direct.stderr);
assert.equal(direct.stdout, "");
assert.equal(
direct.stderr,
"codex-desktop: Desktop shared app server is not available\n",
);
} finally {
fs.rmSync(root, { recursive: true, force: true });
}
});
test("attached CLI verifier accepts real Linux listeners and accepted connections", async (t) => {