Repository navigation
Expand file tree
/
Copy pathtest.js
More file actions
362 lines (335 loc) · 19.8 KB
/
Copy pathtest.js
File metadata and controls
362 lines (335 loc) · 19.8 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
"use strict";
const { applyLinuxComputerUsePluginGatePatch } = require("./plugin-gate.js");
const assert = require("node:assert/strict");
const { execFileSync } = require("node:child_process");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const test = require("node:test");
const vm = require("node:vm");
const manifest = require("./feature.json");
const descriptors = require("./patch.js");
const {
createPatchReport,
enabledFeatureFailuresFromReport,
} = require("../../scripts/lib/patch-report.js");
const {
applyMainBundlePatchDescriptors,
} = require("../../scripts/patches/engine.js");
const {
applyLinuxComputerUseAvatarCursorBridgePatch,
applyLinuxComputerUseFeaturePatch,
applyLinuxComputerUseHostPlatformPatch,
matchesLinuxComputerUseHostPlatformContract,
} = require("../../scripts/patches/impl/computer-use.js");
test("computer-use-linux is opt-in and owns the current Linux descriptors", () => {
assert.equal(manifest.defaultEnabled, false);
assert.deepEqual(manifest.resources, [{
source: "host-service.mjs",
target: ".codex-linux/features/computer-use-linux/host-service.mjs",
mode: "0644",
}]);
assert.deepEqual(Object.keys(manifest.runtimeHooks), ["launcher", "afterExit"]);
assert.deepEqual(
descriptors.map(({ id }) => id),
[
"unified-runtime",
"avatar-cursor",
"ui-feature",
"plugin-gate",
"native-applications",
"ui-availability",
"host-platform",
"native-settings-visibility",
],
);
// rspack chunk names carry no meaning; webview owners are found by content.
for (const id of ["ui-availability", "host-platform", "native-settings-visibility"]) {
const descriptor = descriptors.find((candidate) => candidate.id === id);
assert.equal(descriptor.pattern, undefined, id);
assert.ok(descriptor.assetNeedles.length > 0, id);
}
const visibility = descriptors.find(({ id }) => id === "native-settings-visibility");
assert.equal(visibility.assetMatch, undefined);
assert.deepEqual(visibility.assetNeedles, ['"built by openai"', '"chatgpt official"']);
const hostPlatform = descriptors.find(({ id }) => id === "host-platform");
assert.equal(hostPlatform.assetMatch(hostPlatformFixture()), true);
assert.equal(hostPlatform.assetMatch("function unrelated(){return true}"), false);
});
function hostPlatformFixture(host = '"macOS"===S||"windows"===S', args = "areRequirementsPending:L,areRequiredFeaturesEnabled:M,enabled:T,isBrowserAndComputerUseAllowed:U,isAnyFeatureLoading:x,isComputerUseGateEnabled:b,") {
return 'function E(e){let{isLoading:A,platform:S}=(0,_.V)(),t={enabled:!0,featureName:"computer_use",hostId:e};' +
`return function({areRequirementsPending:e,isHostCompatiblePlatform:s}){return e?"loading":s?"available":"unsupported-platform"}({${args}isHostCompatiblePlatform:${host},isPlatformLoading:A,windowType:"electron"})}`;
}
test("computer-use-linux staging consumes release artifacts without invoking Cargo", () => {
const stage = fs.readFileSync(path.join(__dirname, "stage.sh"), "utf8");
assert.doesNotMatch(stage, /cargo\s+(?:build|install)/);
assert.match(stage, /target\/release\/codex-computer-use-linux/);
});
test("staging extends the hidden unified plugin and invalidates the browser-only cache", (t) => {
const workspace = fs.mkdtempSync(path.join(os.tmpdir(), "computer-use-linux-stage-"));
t.after(() => fs.rmSync(workspace, { recursive: true, force: true }));
const installDir = path.join(workspace, "app");
const target = path.join(installDir, "resources/plugins/openai-bundled/plugins/unified-computer-use");
const marketplacePath = path.join(target, "../../.agents/plugins/marketplace.json");
fs.mkdirSync(path.dirname(marketplacePath), { recursive: true });
const marketplace = JSON.stringify({ plugins: [{ name: "unified-computer-use" }, { name: "browser" }] });
fs.writeFileSync(marketplacePath, marketplace);
fs.mkdirSync(path.join(target, "scripts"), { recursive: true });
fs.mkdirSync(path.join(target, ".codex-plugin"));
fs.writeFileSync(path.join(target, ".codex-plugin/plugin.json"), JSON.stringify({ name: "unified-computer-use", version: "26.908.31748", mcpServers: "./.mcp.json" }));
fs.writeFileSync(path.join(target, ".mcp.json"), JSON.stringify({ mcpServers: { cua_repl: { command: "node", args: [], enabled: false } } }));
const backend = path.join(workspace, "backend");
fs.writeFileSync(backend, "#!/bin/sh\nexit 0\n", { mode: 0o755 });
const env = { ...process.env, SCRIPT_DIR: path.resolve(__dirname, "../.."), INSTALL_DIR: installDir,
CODEX_COMPUTER_USE_BINARY_SOURCE: backend, CODEX_COMPUTER_USE_COSMIC_BINARY_SOURCE: backend, CODEX_COMPUTER_USE_INDICATOR_BINARY_SOURCE: backend };
const stage = () => execFileSync("bash", [path.join(__dirname, "stage.sh")], { env, stdio: "pipe" });
const mcpPath = path.join(target, ".mcp.json");
const originalMcp = fs.readFileSync(mcpPath, "utf8");
const originalManifest = fs.readFileSync(path.join(target, ".codex-plugin/plugin.json"), "utf8");
for (const invalid of [
originalMcp.replace('"command":"node"', '"command":"changed"'),
originalMcp.replace('"args":[]', '"args":["changed"]'),
originalMcp.replace('"enabled":false', '"enabled":true'),
]) {
fs.writeFileSync(mcpPath, invalid);
assert.throws(stage, /unified.*contract/i);
assert.equal(fs.readFileSync(mcpPath, "utf8"), invalid);
assert.equal(fs.readFileSync(path.join(target, ".codex-plugin/plugin.json"), "utf8"), originalManifest);
assert.equal(fs.readFileSync(marketplacePath, "utf8"), marketplace);
assert.equal(fs.existsSync(path.join(target, "scripts/native-client.mjs")), false);
assert.equal(fs.existsSync(path.join(target, "scripts/native-service.mjs")), false);
}
fs.writeFileSync(mcpPath, originalMcp);
stage();
assert.ok(fs.existsSync(path.join(target, "bin/codex-computer-use-indicator")));
const version = JSON.parse(fs.readFileSync(path.join(target, ".codex-plugin/plugin.json"))).version;
assert.equal(version, "26.908.31748-linux-native.8");
assert.deepEqual(JSON.parse(fs.readFileSync(marketplacePath)).plugins.map(p => p.name), ["unified-computer-use", "browser", "computer-use"]);
const settingsManifest = JSON.parse(fs.readFileSync(path.join(target, "../computer-use/.codex-plugin/plugin.json")));
assert.equal(settingsManifest.mcpServers, undefined);
assert.equal(fs.existsSync(path.join(target, "../computer-use/.mcp.json")), false);
assert.equal(fs.existsSync(path.join(target, "../computer-use/bin/codex-computer-use-linux")), false);
assert.equal(fs.existsSync(path.join(target, "scripts/native-client.mjs")), true);
assert.equal(fs.existsSync(path.join(target, "scripts/native-service.mjs")), true);
assert.equal(fs.existsSync(path.join(target, "scripts/native-backend-service.mjs")), true);
assert.equal(fs.existsSync(path.join(target, "scripts/native-protocol.mjs")), true);
assert.equal(fs.readFileSync(path.join(target, "bin/codex-computer-use-linux"), "utf8"), fs.readFileSync(backend, "utf8"));
const legacyMcp = path.join(target, "../computer-use/.mcp.json");
fs.writeFileSync(legacyMcp, JSON.stringify({ mcpServers: { "computer-use": { command: "./bin/codex-computer-use-linux", args: ["mcp"] } } }));
stage();
assert.equal(fs.existsSync(legacyMcp), false);
assert.equal(JSON.parse(fs.readFileSync(path.join(target, ".codex-plugin/plugin.json"))).version, version);
const manifestPath = path.join(target, ".codex-plugin/plugin.json");
const previousManifest = JSON.parse(fs.readFileSync(manifestPath));
previousManifest.version = "26.901.41600-linux-native.1";
fs.writeFileSync(manifestPath, JSON.stringify(previousManifest));
stage();
assert.equal(JSON.parse(fs.readFileSync(manifestPath)).version, "26.901.41600-linux-native.8");
stage();
assert.equal(JSON.parse(fs.readFileSync(manifestPath)).version, "26.901.41600-linux-native.8");
fs.writeFileSync(mcpPath, "upstream drift");
assert.throws(stage, /unified.*contract/i);
});
test("current host-platform contract enables Linux without dropping requirement gates", () => {
const source = hostPlatformFixture();
const patched = applyLinuxComputerUseHostPlatformPatch(source);
assert.notEqual(patched, source);
assert.match(patched, /areRequirementsPending:L/);
assert.match(patched, /isBrowserAndComputerUseAllowed:U/);
assert.match(patched, /isHostCompatiblePlatform:"linux"===S\|\|"macOS"===S\|\|"windows"===S,/);
assert.equal(matchesLinuxComputerUseHostPlatformContract(patched), true);
assert.equal(applyLinuxComputerUseHostPlatformPatch(patched), patched);
const run = (code, platform) => new Function("_", "L", "M", "T", "U", "x", "b", `${code};return E()`)(
{ V: () => ({ isLoading: false, platform }) }, false, true, true, true, false, true,
);
assert.equal(run(patched, "linux"), "available");
assert.equal(run(source, "linux"), "unsupported-platform");
assert.equal(run(patched, "freebsd"), "unsupported-platform");
});
test("retired host-platform contracts are rejected byte-identically", () => {
for (const source of [
// Missing requirement and policy inputs.
hostPlatformFixture(undefined, "areRequiredFeaturesEnabled:M,enabled:T,isAnyFeatureLoading:x,isComputerUseGateEnabled:b,"),
// Pre-rspack helper call and template-literal shapes.
hostPlatformFixture("g(S)"),
hostPlatformFixture().replace('windowType:"electron"', "windowType:`electron`"),
// Not owned by the computer_use availability hook.
hostPlatformFixture().replace('featureName:"computer_use"', 'featureName:"browser_use"'),
]) {
assert.equal(matchesLinuxComputerUseHostPlatformContract(source), false, source);
assert.equal(applyLinuxComputerUseHostPlatformPatch(source), source);
}
});
test("malformed, duplicate, and mixed host-platform contracts are rejected byte-identically", () => {
const patched = applyLinuxComputerUseHostPlatformPatch(hostPlatformFixture());
for (const source of [
hostPlatformFixture('"linux"===S||"macOS"===S||"windows"===P'),
hostPlatformFixture('"linux"===S||"macOS"===S'),
patched + patched,
hostPlatformFixture() + patched,
]) {
assert.equal(matchesLinuxComputerUseHostPlatformContract(source), false, source);
assert.equal(applyLinuxComputerUseHostPlatformPatch(source), source);
}
});
const nativeRegistration = '{...n.nc.computerUse,autoInstallOptOutKey:(0,n.sc)(n.nc.computerUse.name),isAvailable:({features:e,platform:t})=>("darwin"===t||"win32"===t)&&e.computerUse}';
const registrationFixture = `var kd=[${nativeRegistration}];`;
function evaluateNativeRegistration(source) {
const n = {
nc: { computerUse: { name: "computer-use", installWhenMissing: true, installWhenMissingRequiresOptIn: true } },
sc: name => `auto-install-opt-out:${name}`,
};
return new Function("n", `${source};return kd`)(n);
}
test("current native registration enables Linux while preserving shared consent metadata", () => {
const source = applyLinuxComputerUsePluginGatePatch(registrationFixture);
const [native] = evaluateNativeRegistration(source);
assert.equal(evaluateNativeRegistration(source).length, 1);
for (const platform of ["linux", "darwin", "win32", "freebsd"]) {
for (const computerUse of [false, true]) {
const context = { platform, features: { computerUse } };
assert.equal(
native.isAvailable(context),
computerUse && ["linux", "darwin", "win32"].includes(platform),
);
}
}
assert.equal(native.installWhenMissingRequiresOptIn, true);
assert.equal(native.installWhenMissing, true);
assert.equal(native.autoInstallOptOutKey, "auto-install-opt-out:computer-use");
assert.equal(applyLinuxComputerUsePluginGatePatch(source), source);
});
test("native registration matching follows renamed aliases and preserves unrelated browser descriptors", () => {
const browser = "{...n.nc.browser,isAvailable:({features:e})=>e.computerUse||e.externalBrowserUse}";
const fixture = registrationFixture.replace("var kd=[", `var kd=[${browser},`).replaceAll("n.nc", "q.registry").replaceAll("n.sc", "q.optOut").replaceAll("features:e,platform:t", "features:flags,platform:os").replaceAll("===t", "===os").replaceAll("e.computerUse", "flags.computerUse");
const result = applyLinuxComputerUsePluginGatePatch(fixture);
assert.ok(result.includes('"linux"===os)&&flags.computerUse'));
assert.ok(result.includes(browser.replaceAll("n.nc", "q.registry").replaceAll("e.computerUse", "flags.computerUse")));
});
for (const [name, fixture] of [
["duplicate native registration", registrationFixture.replace(nativeRegistration, `${nativeRegistration},${nativeRegistration}`)],
["mixed patched and original registration", registrationFixture + applyLinuxComputerUsePluginGatePatch(registrationFixture)],
["wrong opt-out reference", registrationFixture.replace("(0,n.sc)(n.nc.computerUse.name)", "(0,n.sc)(n.nc.browser.name)")],
["unsupported gate", registrationFixture.replace('("darwin"===t||"win32"===t)&&e.computerUse', '"darwin"===t||e.computerUse')],
["retired direct opt-out call", registrationFixture.replace("(0,n.sc)(", "n.sc(")],
]) {
test(`native plugin patch rejects ${name}`, () => {
assert.notEqual(fixture, registrationFixture);
assert.throws(() => applyLinuxComputerUsePluginGatePatch(fixture), /Required Linux Computer Use plugin gate patch failed/);
});
}
test("chunks without the native plugin registration are left unchanged with a diagnostic", (t) => {
const warnings = [];
t.mock.method(console, "warn", message => warnings.push(message));
const chunk = "var kd=[];";
assert.equal(applyLinuxComputerUsePluginGatePatch(chunk), chunk);
assert.match(warnings.join("\n"), /Computer Use plugin registration/);
});
test("native plugin patch rejects partial Linux registrations", () => {
const patched = applyLinuxComputerUsePluginGatePatch(registrationFixture);
for (const bad of [
patched.replace('||"linux"===t', '||"freebsd"===t'),
patched.replace(")&&e.computerUse", ")||e.computerUse"),
patched.replace(".name),isAvailable", ".name),installWhenMissing:!0,isAvailable"),
]) {
assert.notEqual(bad, patched);
assert.throws(() => applyLinuxComputerUsePluginGatePatch(bad), /Required Linux Computer Use plugin gate patch failed/);
}
});
test("desktop feature gate enables Linux in the unique current Windows override", () => {
const current = 'function features(e,n,r){let i="win32"===r&&"1"===n.CODEX_ELECTRON_ENABLE_WINDOWS_COMPUTER_USE?{...e,computerUse:!0}:e,o=i;return o}';
const patched = applyLinuxComputerUseFeaturePatch(current);
assert.match(patched, /"linux"===r\?\{\.\.\.e,computerUse:!0\}:"win32"===r/);
assert.equal(applyLinuxComputerUseFeaturePatch(patched), patched);
assert.equal(new Function("e", "n", "r", `${patched};return features(e,n,r).computerUse`)(
{ computerUse: false }, {}, "linux",
), true);
});
test("desktop feature gate rejects missing, duplicate, and partial current contracts byte-identically", () => {
const current = 'function features(e,n,r){let i="win32"===r&&"1"===n.CODEX_ELECTRON_ENABLE_WINDOWS_COMPUTER_USE?{...e,computerUse:!0}:e,o=i;return o}';
const patched = applyLinuxComputerUseFeaturePatch(current);
assert.notEqual(patched, current);
for (const source of [
current + current,
patched + current,
current.replace("computerUse:!0", "computerUse:!1"),
current.replace("computerUse:!0}:e,", "computerUse:!0}:other,"),
patched.replace(/computerUse:!0\}:e,/, "computerUse:!0}:other,"),
]) {
assert.notEqual(source, current);
assert.equal(applyLinuxComputerUseFeaturePatch(source), source);
}
});
test("anchor-free desktop feature gate reports enabled-feature drift", () => {
const source = "function unrelated(){return!0}";
const descriptor = {
...descriptors.find(({ id }) => id === "ui-feature"),
featureId: "computer-use-linux",
sourceKind: "feature",
};
const report = createPatchReport();
report.enabledFeatures = ["computer-use-linux"];
const result = applyMainBundlePatchDescriptors(source, [descriptor], {}, report);
assert.equal(result.patchedSource, source);
assert.equal(result.warnings.length, 1);
assert.match(result.warnings[0], /Could not find Computer Use desktop feature gate/);
assert.equal(report.patches[0].status, "skipped-optional");
assert.notEqual(report.patches[0].status, "already-applied");
assert.equal(enabledFeatureFailuresFromReport(report).length, 1);
});
const cursorRegistration = 'class Overlay{constructor(e,t,r,n=!1){n||(!function(e,{addon:t,electronAppPath:r,platform:n=process.platform,resourcesPath:i=process.resourcesPath}={}){if("darwin"===n)try{(t??load({electronAppPath:r??app.getAppPath(),resourcesPath:i})).setRemoteHostedPIPContentComputerUseCursorLocationHandler(e)}catch{return!1}}(e=>{this.cursor=e}),!function(e,{addon:t,platform:n=process.platform}={}){if("darwin"===n)try{(t??load({})).setRemoteHostedPIPContentLayoutStateChangedHandler(e)}catch{return!1}}(e=>{this.layout=e}))}}globalThis.Overlay=Overlay;';
const cursorChunk = `exports.ids=[916],exports.modules={61071(e,t,r){"use strict";${cursorRegistration}}};`;
test("avatar cursor bridge adds a Linux branch to the inline registration", () => {
const patched = applyLinuxComputerUseAvatarCursorBridgePatch(cursorChunk);
assert.notEqual(patched, cursorChunk);
assert.ok(patched.startsWith("function codexLinuxComputerUseCursorComponent("));
assert.ok(patched.includes('{if("linux"===n)return codexLinuxRegisterComputerUseCursorHandler(e);if("darwin"===n)try{'));
assert.equal((patched.match(/"linux"===n/g) ?? []).length, 1, "only the cursor handler gains a Linux branch");
assert.doesNotThrow(() => new vm.Script(patched));
assert.equal(applyLinuxComputerUseAvatarCursorBridgePatch(patched), patched);
for (const platform of ["linux", "darwin"]) {
const loads = [];
const context = {
exports: {}, Buffer, process: { platform, env: {}, resourcesPath: "/resources" },
app: { getAppPath: () => "/app" },
load: options => {
loads.push(options);
return { setRemoteHostedPIPContentComputerUseCursorLocationHandler() {}, setRemoteHostedPIPContentLayoutStateChangedHandler() {} };
},
require: name => { throw Error(`unexpected ${name}`); },
};
context.globalThis = context;
vm.runInNewContext(patched, context);
// Evaluate the module factory the way the rspack runtime does.
Object.values(context.exports.modules)[0]({}, {}, () => {});
const overlay = vm.runInNewContext("new globalThis.Overlay()", context);
const bridge = vm.runInNewContext("codexLinuxRegisterComputerUseCursorHandler", context);
if (platform === "linux") {
// Without a private runtime directory the bridge keeps the handler but opens no socket.
assert.equal(typeof bridge.handler, "function");
bridge.handler({ isActive: true, x: 1, y: 2 });
assert.deepEqual({ ...overlay.cursor }, { isActive: true, x: 1, y: 2 });
assert.equal(bridge.server, undefined);
assert.equal(loads.length, 0, "Linux never loads the macOS addon");
} else {
assert.equal(bridge.handler, undefined);
assert.equal(loads.length, 2);
}
}
});
test("avatar cursor bridge skips anchor-free, changed, and partial chunks", (t) => {
const warnings = [];
t.mock.method(console, "warn", message => warnings.push(message));
const patched = applyLinuxComputerUseAvatarCursorBridgePatch(cursorChunk);
for (const source of [
'exports.ids=[87],exports.modules={1(e){e.exports=1}};',
cursorChunk.replace('if("darwin"===n)try{(t??load({electronAppPath', 'if("darwin"===n||"win32"===n)try{(t??load({electronAppPath'),
cursorChunk + cursorChunk,
patched.slice(patched.indexOf("exports.ids=")),
cursorChunk.replace("exports.ids=", "function codexLinuxRegisterComputerUseCursorHandler(){}exports.ids="),
]) {
assert.equal(applyLinuxComputerUseAvatarCursorBridgePatch(source), source);
}
assert.equal(warnings.length, 5);
assert.match(warnings[0], /Could not find the Computer Use cursor handler marker/);
});