Skip to content

Commit 89906f6

Browse files
committed
fix(codex): fingerprint computer-use plugin bytes
1 parent 5b87a1e commit 89906f6

4 files changed

Lines changed: 136 additions & 69 deletions

File tree

‎extensions/codex/src/app-server/desktop-generation-fingerprint.ts‎

Lines changed: 54 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ import {
88
type MacOSDesktopCodexAppPathCandidate,
99
} from "./desktop-app-paths.js";
1010

11+
const MAX_COMPUTER_USE_PLUGIN_TREE_ENTRIES = 4_096;
12+
1113
/** Fingerprints every desktop candidate that can own a managed fallback artifact. */
1214
export async function readMacOSDesktopGenerationFingerprint(
1315
candidates: readonly MacOSDesktopCodexAppPathCandidate[] = resolveMacOSDesktopCodexAppPathCandidates(
@@ -21,6 +23,8 @@ export async function readMacOSDesktopGenerationFingerprint(
2123
for (const artifactPath of resolveMacOSDesktopGenerationPaths(candidate)) {
2224
entries.push(`${artifactPath}\0${await statFingerprint(artifactPath)}`);
2325
}
26+
const pluginRoot = resolveComputerUsePluginRoot(candidate);
27+
entries.push(`${pluginRoot}\0${await directoryTreeFingerprint(pluginRoot)}`);
2428
}
2529
return createHash("sha256").update(entries.join("\0")).digest("hex");
2630
}
@@ -31,13 +35,6 @@ function resolveMacOSDesktopGenerationPaths(
3135
return [
3236
candidate.appBundlePath,
3337
path.join(candidate.bundledMarketplacePath, ".agents", "plugins", "marketplace.json"),
34-
path.join(
35-
candidate.bundledMarketplacePath,
36-
"plugins",
37-
"computer-use",
38-
".codex-plugin",
39-
"plugin.json",
40-
),
4138
...candidate.computerUseServiceAppPaths.flatMap((servicePath) => [
4239
servicePath,
4340
path.join(servicePath, "Contents", "Info.plist"),
@@ -54,7 +51,11 @@ function resolveMacOSDesktopGenerationPaths(
5451
];
5552
}
5653

57-
/** Stable directories whose immediate children cover every fingerprinted artifact. */
54+
function resolveComputerUsePluginRoot(candidate: MacOSDesktopCodexAppPathCandidate): string {
55+
return path.join(candidate.bundledMarketplacePath, "plugins", "computer-use");
56+
}
57+
58+
/** Stable roots that cover bundle replacement and recursive artifact updates. */
5859
export function resolveMacOSDesktopGenerationWatchPaths(
5960
candidates: readonly MacOSDesktopCodexAppPathCandidate[] = resolveMacOSDesktopCodexAppPathCandidates(
6061
"darwin",
@@ -63,26 +64,55 @@ export function resolveMacOSDesktopGenerationWatchPaths(
6364
const watched = new Set<string>(["/Applications"]);
6465
for (const candidate of candidates) {
6566
watched.add(candidate.appBundlePath);
66-
const directoryArtifacts = new Set([
67-
candidate.appBundlePath,
68-
...candidate.computerUseServiceAppPaths,
69-
]);
70-
for (const artifactPath of [
71-
candidate.appServerCommandPath,
72-
...resolveMacOSDesktopGenerationPaths(candidate),
73-
]) {
74-
let directory = directoryArtifacts.has(artifactPath)
75-
? artifactPath
76-
: path.dirname(artifactPath);
77-
while (directory.startsWith(`${candidate.appBundlePath}${path.sep}`)) {
78-
watched.add(directory);
79-
directory = path.dirname(directory);
80-
}
81-
}
8267
}
8368
return [...watched];
8469
}
8570

71+
async function directoryTreeFingerprint(root: string): Promise<string> {
72+
let rootStat: BigIntStats;
73+
try {
74+
rootStat = await fs.lstat(root, { bigint: true });
75+
} catch (error) {
76+
if (isNodeError(error, "ENOENT") || isNodeError(error, "ENOTDIR")) {
77+
return "missing";
78+
}
79+
throw error;
80+
}
81+
if (!rootStat.isDirectory()) {
82+
return statFingerprint(root);
83+
}
84+
85+
let entryCount = 0;
86+
const hash = createHash("sha256");
87+
hash.update("openclaw-codex-computer-use-plugin-tree-v1\0");
88+
const visit = async (directory: string, relativeDirectory: string, before: BigIntStats) => {
89+
hash.update(`directory\0${relativeDirectory}\0${statTuple(before)}\0`);
90+
const entries = (await fs.readdir(directory, { withFileTypes: true })).toSorted(
91+
(left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0),
92+
);
93+
for (const entry of entries) {
94+
entryCount += 1;
95+
if (entryCount > MAX_COMPUTER_USE_PLUGIN_TREE_ENTRIES) {
96+
throw new Error("Codex Computer Use plugin exceeds the bounded tree size");
97+
}
98+
const entryPath = path.join(directory, entry.name);
99+
const relativePath = path.join(relativeDirectory, entry.name);
100+
const entryStat = await fs.lstat(entryPath, { bigint: true });
101+
if (entryStat.isDirectory()) {
102+
await visit(entryPath, relativePath, entryStat);
103+
} else {
104+
hash.update(`entry\0${relativePath}\0${await statFingerprint(entryPath)}\0`);
105+
}
106+
}
107+
const after = await fs.lstat(directory, { bigint: true });
108+
if (!sameStat(before, after)) {
109+
throw new Error(`Codex desktop artifact changed while fingerprinting: ${directory}`);
110+
}
111+
};
112+
await visit(root, ".", rootStat);
113+
return hash.digest("hex");
114+
}
115+
86116
async function statFingerprint(filePath: string): Promise<string> {
87117
try {
88118
const entry = await fs.lstat(filePath, { bigint: true });

‎extensions/codex/src/app-server/desktop-generation-service.test.ts‎

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ class FakeWatcher extends EventEmitter {
1414

1515
type WatchRegistration = {
1616
watchedPath: string;
17+
recursive: boolean;
1718
listener: (eventType: string, filename: string | Buffer | null) => void;
1819
watcher: FakeWatcher;
1920
};
@@ -31,11 +32,11 @@ function createHarness(initialFingerprint: string) {
3132
{
3233
platform: "darwin",
3334
readFingerprint,
34-
resolveWatchPaths: () => ["/Applications", "/Applications/ChatGPT.app/Contents/Resources"],
35+
resolveWatchPaths: () => ["/Applications", "/Applications/ChatGPT.app"],
3536
pathExists: () => true,
36-
watchPath: (watchedPath, listener) => {
37+
watchPath: (watchedPath, options, listener) => {
3738
const watcher = new FakeWatcher();
38-
registrations.push({ watchedPath, listener, watcher });
39+
registrations.push({ watchedPath, recursive: options.recursive, listener, watcher });
3940
return watcher as FSWatcher;
4041
},
4142
},
@@ -90,6 +91,12 @@ describe("Codex desktop generation service", () => {
9091
} as never);
9192

9293
expect(harness.registrations).toHaveLength(2);
94+
expect(
95+
harness.registrations.map(({ watchedPath, recursive }) => [watchedPath, recursive]),
96+
).toEqual([
97+
["/Applications", false],
98+
["/Applications/ChatGPT.app", true],
99+
]);
93100
expect(harness.clearFailure).not.toHaveBeenCalled();
94101
await vi.advanceTimersByTimeAsync(1_000);
95102
await vi.waitFor(() => expect(harness.clearFailure).toHaveBeenCalledOnce());
@@ -153,9 +160,15 @@ describe("Codex desktop generation service", () => {
153160
const clearFailure = vi.fn();
154161
const reportFailure = vi.fn();
155162
const warn = vi.fn();
156-
const watchPath = vi.fn((): FSWatcher => {
157-
throw new Error("watch unavailable");
158-
});
163+
const watchPath = vi.fn(
164+
(
165+
_watchedPath: string,
166+
_options: { recursive: boolean },
167+
_listener: (eventType: string, filename: string | Buffer | null) => void,
168+
): FSWatcher => {
169+
throw new Error("watch unavailable");
170+
},
171+
);
159172
service = createCodexDesktopGenerationService(
160173
{ onGenerationChange },
161174
{

‎extensions/codex/src/app-server/desktop-generation.test.ts‎

Lines changed: 41 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -111,32 +111,49 @@ describe("Codex desktop generation owner", () => {
111111
});
112112
});
113113

114-
it("watches the stable parent chain for every fingerprinted artifact", () => {
114+
it("settles same-version Computer Use plugin content changes as a new generation", async () => {
115+
await withTempDir("openclaw-codex-generation-plugin-fingerprint-", async (root) => {
116+
const chatGpt = candidate(root, "ChatGPT.app");
117+
const pluginRoot = path.join(chatGpt.bundledMarketplacePath, "plugins", "computer-use");
118+
await Promise.all([
119+
writeCommand(chatGpt.appServerCommandPath, "chatgpt-x"),
120+
fs.mkdir(path.join(pluginRoot, ".codex-plugin"), { recursive: true }),
121+
]);
122+
await fs.writeFile(
123+
path.join(pluginRoot, ".codex-plugin", "plugin.json"),
124+
JSON.stringify({ name: "computer-use", version: "1.0.0" }),
125+
);
126+
await fs.writeFile(path.join(pluginRoot, ".mcp.json"), "plugin-content-x");
127+
const initialFingerprint = await readMacOSDesktopGenerationFingerprint([chatGpt]);
128+
129+
await fs.writeFile(path.join(pluginRoot, ".mcp.json"), "plugin-content-y");
130+
const updatedFingerprint = await readMacOSDesktopGenerationFingerprint([chatGpt]);
131+
expect(updatedFingerprint).not.toBe(initialFingerprint);
132+
133+
vi.useFakeTimers();
134+
let fingerprint = initialFingerprint;
135+
const owner = createCodexDesktopGenerationOwner({
136+
readFingerprint: async () => fingerprint,
137+
});
138+
const initial = owner.refresh();
139+
await vi.advanceTimersByTimeAsync(1_000);
140+
await expect(initial).resolves.toMatchObject({ epoch: 1 });
141+
142+
fingerprint = updatedFingerprint;
143+
owner.markDirty();
144+
const updated = owner.wait();
145+
await vi.advanceTimersByTimeAsync(1_000);
146+
147+
await expect(updated).resolves.toMatchObject({ epoch: 2 });
148+
});
149+
});
150+
151+
it("watches stable application roots for recursive artifact updates", () => {
115152
const fixture = candidate("/Applications", "ChatGPT.app");
116-
const servicePath = path.join(fixture.appBundlePath, "service", "Computer Use.app");
117-
const watchPaths = resolveMacOSDesktopGenerationWatchPaths([
118-
{ ...fixture, computerUseServiceAppPaths: [servicePath] },
153+
expect(resolveMacOSDesktopGenerationWatchPaths([fixture])).toEqual([
154+
"/Applications",
155+
fixture.appBundlePath,
119156
]);
120-
121-
expect(watchPaths).toEqual(
122-
expect.arrayContaining([
123-
"/Applications",
124-
fixture.appBundlePath,
125-
path.dirname(fixture.appServerCommandPath),
126-
path.join(fixture.bundledMarketplacePath, ".agents", "plugins"),
127-
path.join(fixture.bundledMarketplacePath, "plugins", "computer-use", ".codex-plugin"),
128-
servicePath,
129-
path.join(servicePath, "Contents"),
130-
path.join(
131-
servicePath,
132-
"Contents",
133-
"SharedSupport",
134-
"SkyComputerUseClient.app",
135-
"Contents",
136-
"MacOS",
137-
),
138-
]),
139-
);
140157
});
141158
});
142159

‎extensions/codex/src/app-server/desktop-generation.ts‎

Lines changed: 22 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ const DESKTOP_GENERATION_STATE = Symbol.for("openclaw.codexDesktopGenerationStat
2323
type GenerationOwner = ReturnType<typeof createCodexDesktopGenerationOwner>;
2424
type WatchFactory = (
2525
watchedPath: string,
26+
options: { recursive: boolean },
2627
listener: (eventType: string, filename: string | Buffer | null) => void,
2728
) => FSWatcher;
2829
type DesktopGenerationRuntime = {
@@ -74,7 +75,7 @@ export function createCodexDesktopGenerationService(
7475
readFingerprint: readMacOSDesktopGenerationFingerprint,
7576
resolveWatchPaths: resolveMacOSDesktopGenerationWatchPaths,
7677
pathExists: existsSync,
77-
watchPath: (watchedPath, listener) => watch(watchedPath, listener),
78+
watchPath: (watchedPath, options, listener) => watch(watchedPath, options, listener),
7879
},
7980
): OpenClawPluginService {
8081
return {
@@ -137,20 +138,26 @@ function armWatchers(current: DesktopGenerationState): boolean {
137138
continue;
138139
}
139140
try {
140-
const watcher = current.watchPath?.(watchedPath, (_eventType, filename) => {
141-
if (!isCurrentArm(current, owner, watchers, armEpoch)) {
142-
return;
143-
}
144-
if (
145-
watchedPath === APPLICATIONS_PATH &&
146-
filename &&
147-
!candidateNames.has(filename.toString().split(path.sep)[0] ?? "")
148-
) {
149-
return;
150-
}
151-
owner.markDirty();
152-
scheduleRearm(current, owner);
153-
});
141+
// Bundle roots need recursive invalidation: nested plugin bytes can change without
142+
// updating the app directory metadata that the settled fingerprint observes first.
143+
const watcher = current.watchPath?.(
144+
watchedPath,
145+
{ recursive: watchedPath !== APPLICATIONS_PATH },
146+
(_eventType, filename) => {
147+
if (!isCurrentArm(current, owner, watchers, armEpoch)) {
148+
return;
149+
}
150+
if (
151+
watchedPath === APPLICATIONS_PATH &&
152+
filename &&
153+
!candidateNames.has(filename.toString().split(path.sep)[0] ?? "")
154+
) {
155+
return;
156+
}
157+
owner.markDirty();
158+
scheduleRearm(current, owner);
159+
},
160+
);
154161
if (!watcher) {
155162
complete = false;
156163
reportWatcherFailure(current, owner, new Error(`Could not watch ${watchedPath}`));

0 commit comments

Comments
 (0)