Skip to content

Commit 17fb535

Browse files
committed
fix(raycast): guard registry microtask teardown
1 parent 206eab8 commit 17fb535

5 files changed

Lines changed: 452 additions & 20 deletions

File tree

Lines changed: 361 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,361 @@
1+
#!/usr/bin/env node
2+
3+
import test from 'node:test';
4+
import assert from 'node:assert/strict';
5+
import path from 'node:path';
6+
import { fileURLToPath } from 'node:url';
7+
import { build } from 'esbuild';
8+
9+
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
10+
11+
function reactStubPlugin() {
12+
return {
13+
name: 'react-stub',
14+
setup(pluginBuild) {
15+
pluginBuild.onResolve({ filter: /^react$/ }, () => ({ path: 'react-stub', namespace: 'react-stub' }));
16+
pluginBuild.onResolve({ filter: /^react\/jsx-(dev-)?runtime$/ }, () => ({ path: 'react-jsx-runtime-stub', namespace: 'react-stub' }));
17+
pluginBuild.onLoad({ filter: /^react-stub$/, namespace: 'react-stub' }, () => ({
18+
loader: 'js',
19+
contents: `
20+
function runtime() {
21+
const current = globalThis.__SUPERCMD_REACT_RUNTIME__;
22+
if (!current) throw new Error('React hook runtime is not installed');
23+
return current;
24+
}
25+
26+
export const Fragment = Symbol.for('react.fragment');
27+
export function createContext(defaultValue) {
28+
const context = { _currentValue: defaultValue };
29+
context.Provider = function Provider(props) {
30+
context._currentValue = props.value;
31+
return props.children;
32+
};
33+
return context;
34+
}
35+
export function createElement(type, props, ...children) {
36+
return { $$typeof: Symbol.for('react.element'), type, props: { ...(props || {}), children } };
37+
}
38+
export function isValidElement(value) {
39+
return Boolean(value && value.$$typeof === Symbol.for('react.element'));
40+
}
41+
export function useCallback(callback, deps) {
42+
return runtime().useCallback(callback, deps);
43+
}
44+
export function useContext(context) {
45+
return runtime().useContext(context);
46+
}
47+
export function useEffect(effect, deps) {
48+
return runtime().useEffect(effect, deps);
49+
}
50+
export function useMemo(factory, deps) {
51+
return runtime().useMemo(factory, deps);
52+
}
53+
export function useRef(initialValue) {
54+
return runtime().useRef(initialValue);
55+
}
56+
export function useState(initialValue) {
57+
return runtime().useState(initialValue);
58+
}
59+
60+
const React = {
61+
Fragment,
62+
createContext,
63+
createElement,
64+
isValidElement,
65+
useCallback,
66+
useContext,
67+
useEffect,
68+
useMemo,
69+
useRef,
70+
useState,
71+
};
72+
export default React;
73+
`,
74+
}));
75+
pluginBuild.onLoad({ filter: /^react-jsx-runtime-stub$/, namespace: 'react-stub' }, () => ({
76+
loader: 'js',
77+
contents: `
78+
import { Fragment, createElement } from 'react';
79+
export { Fragment };
80+
export function jsx(type, props, key) {
81+
return createElement(type, { ...(props || {}), ...(key === undefined ? {} : { key }) });
82+
}
83+
export function jsxs(type, props, key) {
84+
return jsx(type, props, key);
85+
}
86+
export function jsxDEV(type, props, key) {
87+
return jsx(type, props, key);
88+
}
89+
`,
90+
}));
91+
},
92+
};
93+
}
94+
95+
function menuBarStubsPlugin() {
96+
return {
97+
name: 'menubar-stubs',
98+
setup(pluginBuild) {
99+
pluginBuild.onResolve({ filter: /^\.\/menubar-runtime-config$/ }, () => ({ path: 'menubar-runtime-config', namespace: 'menubar-stubs' }));
100+
pluginBuild.onResolve({ filter: /^\.\/menubar-runtime-payload-cache$/ }, () => ({ path: 'menubar-runtime-payload-cache', namespace: 'menubar-stubs' }));
101+
pluginBuild.onResolve({ filter: /^\.\/menubar-runtime-shared$/ }, () => ({ path: 'menubar-runtime-shared', namespace: 'menubar-stubs' }));
102+
103+
pluginBuild.onLoad({ filter: /^menubar-runtime-config$/, namespace: 'menubar-stubs' }, () => ({
104+
loader: 'js',
105+
contents: `
106+
export function getMenuBarRuntimeDeps() {
107+
return globalThis.__SUPERCMD_MENUBAR_DEPS__;
108+
}
109+
`,
110+
}));
111+
pluginBuild.onLoad({ filter: /^menubar-runtime-payload-cache$/, namespace: 'menubar-stubs' }, () => ({
112+
loader: 'js',
113+
contents: `
114+
export function createMenuBarVisiblePayloadHashCache() {
115+
return {};
116+
}
117+
export function shouldSendMenuBarVisiblePayload() {
118+
return true;
119+
}
120+
`,
121+
}));
122+
pluginBuild.onLoad({ filter: /^menubar-runtime-shared$/, namespace: 'menubar-stubs' }, () => ({
123+
loader: 'js',
124+
contents: `
125+
import { createContext } from 'react';
126+
export const MBRegistryContext = createContext(null);
127+
export function initMenuBarClickListener() {}
128+
export function removeMenuBarActions() {}
129+
export function resetMenuBarOrderCounters() {}
130+
export function setMenuBarActions() {}
131+
export async function toMenuBarIconPayloadAsync() {
132+
return undefined;
133+
}
134+
`,
135+
}));
136+
},
137+
};
138+
}
139+
140+
async function importBundledModule(relativePath, plugins = []) {
141+
const result = await build({
142+
entryPoints: [path.join(root, relativePath)],
143+
bundle: true,
144+
write: false,
145+
platform: 'node',
146+
format: 'esm',
147+
jsx: 'transform',
148+
tsconfigRaw: {
149+
compilerOptions: {
150+
jsx: 'react',
151+
},
152+
},
153+
plugins: [reactStubPlugin(), ...plugins],
154+
});
155+
return import(`data:text/javascript;base64,${Buffer.from(result.outputFiles[0].text).toString('base64')}`);
156+
}
157+
158+
function depsChanged(previous, next) {
159+
if (!previous || !next || previous.length !== next.length) return true;
160+
return next.some((value, index) => !Object.is(value, previous[index]));
161+
}
162+
163+
function createHookRuntime(label) {
164+
const hooks = [];
165+
const counters = {
166+
label,
167+
setStateCalls: 0,
168+
postUnmountSetStateCalls: 0,
169+
};
170+
let hookIndex = 0;
171+
let mounted = true;
172+
173+
const runtime = {
174+
counters,
175+
render(callback) {
176+
mounted = true;
177+
hookIndex = 0;
178+
return callback();
179+
},
180+
unmount() {
181+
mounted = false;
182+
for (let index = hooks.length - 1; index >= 0; index -= 1) {
183+
const cleanup = hooks[index]?.cleanup;
184+
if (typeof cleanup === 'function') {
185+
cleanup();
186+
hooks[index].cleanup = undefined;
187+
}
188+
}
189+
},
190+
useCallback(callback, deps) {
191+
return runtime.useMemo(() => callback, deps);
192+
},
193+
useContext(context) {
194+
return context?._currentValue;
195+
},
196+
useEffect(effect, deps) {
197+
const index = hookIndex;
198+
hookIndex += 1;
199+
const existing = hooks[index];
200+
if (existing && !depsChanged(existing.deps, deps)) return;
201+
if (typeof existing?.cleanup === 'function') existing.cleanup();
202+
const cleanup = effect();
203+
hooks[index] = { deps, cleanup };
204+
},
205+
useMemo(factory, deps) {
206+
const index = hookIndex;
207+
hookIndex += 1;
208+
const existing = hooks[index];
209+
if (existing && !depsChanged(existing.deps, deps)) return existing.value;
210+
const value = factory();
211+
hooks[index] = { deps, value };
212+
return value;
213+
},
214+
useRef(initialValue) {
215+
const index = hookIndex;
216+
hookIndex += 1;
217+
if (!hooks[index]) hooks[index] = { current: initialValue };
218+
return hooks[index];
219+
},
220+
useState(initialValue) {
221+
const index = hookIndex;
222+
hookIndex += 1;
223+
if (!hooks[index]) {
224+
const state = { value: typeof initialValue === 'function' ? initialValue() : initialValue };
225+
const setState = (nextValue) => {
226+
counters.setStateCalls += 1;
227+
if (!mounted) counters.postUnmountSetStateCalls += 1;
228+
state.value = typeof nextValue === 'function' ? nextValue(state.value) : nextValue;
229+
};
230+
hooks[index] = { state, setState };
231+
}
232+
return [hooks[index].state.value, hooks[index].setState];
233+
},
234+
};
235+
236+
return runtime;
237+
}
238+
239+
function createLegacyRegistryScheduler(label) {
240+
const counters = {
241+
label,
242+
setStateCalls: 0,
243+
postUnmountSetStateCalls: 0,
244+
pendingCallbacks: 0,
245+
};
246+
let mounted = true;
247+
let pending = false;
248+
249+
return {
250+
counters,
251+
schedule() {
252+
if (pending) return;
253+
pending = true;
254+
counters.pendingCallbacks += 1;
255+
queueMicrotask(() => {
256+
pending = false;
257+
counters.setStateCalls += 1;
258+
if (!mounted) counters.postUnmountSetStateCalls += 1;
259+
});
260+
},
261+
unmount() {
262+
mounted = false;
263+
},
264+
};
265+
}
266+
267+
async function flushMicrotasks() {
268+
await Promise.resolve();
269+
await Promise.resolve();
270+
}
271+
272+
function installRuntime(runtime) {
273+
globalThis.__SUPERCMD_REACT_RUNTIME__ = runtime;
274+
}
275+
276+
test('legacy registry microtask scheduler calls setState after unmount', async () => {
277+
const legacySurfaces = ['actions', 'list', 'grid', 'menubar'].map(createLegacyRegistryScheduler);
278+
279+
for (const surface of legacySurfaces) {
280+
surface.schedule();
281+
surface.unmount();
282+
}
283+
await flushMicrotasks();
284+
285+
const metrics = Object.fromEntries(legacySurfaces.map((surface) => [surface.counters.label, surface.counters]));
286+
for (const surface of legacySurfaces) {
287+
assert.equal(surface.counters.pendingCallbacks, 1, `${surface.counters.label} should have queued one callback`);
288+
assert.equal(surface.counters.postUnmountSetStateCalls, 1, `${surface.counters.label} legacy callback should set state after unmount`);
289+
}
290+
291+
console.log(JSON.stringify({ mode: 'registry-microtask-legacy-reproduction', metrics }, null, 2));
292+
});
293+
294+
test('registry microtasks scheduled before unmount are suppressed by runtime hooks', async () => {
295+
const [actionModule, listModule, gridModule, menuBarModule] = await Promise.all([
296+
importBundledModule('src/renderer/src/raycast-api/action-runtime-registry.tsx'),
297+
importBundledModule('src/renderer/src/raycast-api/list-runtime-hooks.ts'),
298+
importBundledModule('src/renderer/src/raycast-api/grid-runtime-hooks.ts'),
299+
importBundledModule('src/renderer/src/raycast-api/menubar-runtime-parent.tsx', [menuBarStubsPlugin()]),
300+
]);
301+
302+
const actionRuntime = createHookRuntime('actions');
303+
installRuntime(actionRuntime);
304+
const actionRegistryRuntime = actionModule.createActionRegistryRuntime({
305+
snapshotExtensionContext: () => ({}),
306+
withExtensionContext: (_ctx, callback) => callback(),
307+
ExtensionInfoReactContext: { _currentValue: { extId: 'ext/cmd', assetsPath: '', commandMode: 'view' } },
308+
getFormValues: () => ({}),
309+
Clipboard: { copy: () => {} },
310+
trash: () => {},
311+
getGlobalNavigation: () => ({ push: () => {} }),
312+
});
313+
const actionHook = actionRuntime.render(() => actionRegistryRuntime.useCollectedActions());
314+
actionHook.registryAPI.register('action-1', { title: 'Action', execute: () => {}, order: 1 });
315+
actionRuntime.unmount();
316+
actionHook.registryAPI.register('action-after-unmount', { title: 'Late', execute: () => {}, order: 2 });
317+
318+
const listRuntime = createHookRuntime('list');
319+
installRuntime(listRuntime);
320+
const listHook = listRuntime.render(() => listModule.useListRegistry());
321+
listHook.registryAPI.set('list-1', { props: { id: 'list-1', title: 'List' }, order: 1 });
322+
listRuntime.unmount();
323+
listHook.registryAPI.set('list-after-unmount', { props: { id: 'late', title: 'Late' }, order: 2 });
324+
325+
const gridRuntime = createHookRuntime('grid');
326+
installRuntime(gridRuntime);
327+
const gridHook = gridRuntime.render(() => gridModule.useGridRegistry());
328+
gridHook.registryAPI.set('grid-1', { props: { id: 'grid-1', title: 'Grid' }, order: 1 });
329+
gridRuntime.unmount();
330+
gridHook.registryAPI.set('grid-after-unmount', { props: { id: 'late', title: 'Late' }, order: 2 });
331+
332+
const menuBarRuntime = createHookRuntime('menubar');
333+
globalThis.window = { electron: { removeMenuBar: () => {}, updateMenuBar: () => {} } };
334+
globalThis.__SUPERCMD_MENUBAR_DEPS__ = {
335+
ExtensionInfoReactContext: { _currentValue: { extId: 'ext/cmd', assetsPath: '', commandMode: 'menu-bar' } },
336+
getExtensionContext: () => ({ extensionName: 'ext', commandName: 'cmd', assetsPath: '', commandMode: 'menu-bar' }),
337+
setExtensionContext: () => {},
338+
isEmojiOrSymbol: () => false,
339+
};
340+
installRuntime(menuBarRuntime);
341+
const menuTree = menuBarRuntime.render(() => menuBarModule.MenuBarExtraComponent({ children: null, title: 'Menu' }));
342+
const menuRegistryAPI = menuTree.props.value;
343+
menuRegistryAPI.register({ id: 'menu-1', type: 'item', title: 'Menu', order: 1 });
344+
menuBarRuntime.unmount();
345+
menuRegistryAPI.register({ id: 'menu-after-unmount', type: 'item', title: 'Late', order: 2 });
346+
347+
await flushMicrotasks();
348+
349+
const metrics = {
350+
actions: actionRuntime.counters,
351+
list: listRuntime.counters,
352+
grid: gridRuntime.counters,
353+
menubar: menuBarRuntime.counters,
354+
};
355+
for (const [label, counters] of Object.entries(metrics)) {
356+
assert.equal(counters.setStateCalls, 0, `${label} should suppress queued post-unmount updates`);
357+
assert.equal(counters.postUnmountSetStateCalls, 0, `${label} should not call state after unmount`);
358+
}
359+
360+
console.log(JSON.stringify({ mode: 'registry-microtask-lifecycle-fixed', metrics }, null, 2));
361+
});

0 commit comments

Comments
 (0)