Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

test(workspaces): unit tier 改用 threads 池,消掉打挂 launchservicesd 的进程 churn (#1018)

Dashe4b464a2efcc
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthFlow.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthFlow.test.ts
index 1a3a9e4ee8..e2a03f8808 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthFlow.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthFlow.test.ts
@@ -15,6 +15,7 @@ import {
startGhostOauthFlow,
type GhostOauthBrokerClient,
type GhostOauthClientConfig,
+ type GhostOauthFlowResult,
} from '../ghostOauthFlow.js';
const BASE_CONFIG: GhostOauthClientConfig = {
@@ -44,7 +45,7 @@ function browserRedirect(authorizeUrl: string, params: (u: URL) => Record<string
});
}
-/** 探一个当前空闲的 loopback 端口(探测与后续使用之间有极小竞态,可接受)。 */
+/** 探一个当前空闲的 loopback 端口。它只保证"探测那一刻"空闲,见 pinnedPortCase。 */
async function probeFreePort(): Promise<number> {
const probe = http.createServer();
const port = await new Promise<number>((resolve) => {
@@ -57,6 +58,40 @@ async function probeFreePort(): Promise<number> {
return port;
}
+/**
+ * 钉死端口(redirectPort)的用例统一走这里。probeFreePort 关掉探测 socket 之后,
+ * 端口在引擎真正 listen 之前可能被并发用例抢走 —— threads 池下同一进程里跑着
+ * 多个测试文件,这个窗口不再可以忽略。引擎把"钉死端口绑不上"精确报成
+ * LISTEN_FAILED,所以只在命中该错误时换端口重跑整段。
+ *
+ * 判据只看 body 返回的**第一单**:第一单 LISTEN_FAILED 说明这一轮连初始 bind 都
+ * 没抢到端口,换端口重来是对的。而后续单子的 LISTEN_FAILED 恰恰相反 —— 钉死端口
+ * 的交接/自愈(第二单顶掉第一单后立刻复用同一端口)本身就是被测行为,它报
+ * LISTEN_FAILED 就是回归,必须原样交给断言。若也一并重试,换个端口跑一次碰巧成功
+ * 就把回归掩盖掉了。所以 body 的第一个元素必须是"初始 bind 那一单"的结果。
+ */
+async function pinnedPortCase<T extends readonly unknown[]>(
+ body: (port: number) => Promise<T>,
+ attempts = 5,
+): Promise<T> {
+ let last!: T;
+ for (let attempt = 1; attempt <= attempts; attempt += 1) {
+ last = await body(await probeFreePort());
+ if (!isListenFailed(last[0])) return last;
+ }
+ return last;
+}
+
+/** 只认引擎明确报出的 LISTEN_FAILED;形状不符的值一律不算"端口被抢"。 */
+function isListenFailed(value: unknown): boolean {
+ return (
+ typeof value === 'object' &&
+ value !== null &&
+ (value as { ok?: unknown }).ok === false &&
+ (value as { error?: unknown }).error === 'LISTEN_FAILED'
+ );
+}
+
describe('startGhostOauthFlow', () => {
it('happy path:PKCE + state 校验 + code 换 token', async () => {
let capturedAuthorizeUrl = '';
@@ -306,25 +341,17 @@ describe('startGhostOauthFlow', () => {
});
it('redirectPort:回调钉死声明端口(Atlassian 精确匹配场景)', async () => {
- // 先探一个空闲端口再钉给引擎(端口探测与 listen 之间有极小竞态,可接受)。
- const probe = http.createServer();
- const freePort = await new Promise<number>((resolve) => {
- probe.listen(0, '127.0.0.1', () => {
- const addr = probe.address();
- resolve(typeof addr === 'object' && addr ? addr.port : 0);
- });
- });
- await new Promise((r) => probe.close(r));
-
- const result = await startGhostOauthFlow({
- config: { ...BASE_CONFIG, pkce: false, redirectPort: freePort },
- fetchImpl: vi.fn(async () => jsonResponse({ access_token: 'at-fixed' })) as unknown as typeof fetch,
- openExternal: (url) => {
- const u = new URL(url);
- expect(u.searchParams.get('redirect_uri')).toBe(`http://127.0.0.1:${freePort}/callback`);
- browserRedirect(url, (au) => ({ code: 'c-fixed', state: au.searchParams.get('state') ?? '' }));
- },
- });
+ const [result] = await pinnedPortCase(async (freePort) => [
+ await startGhostOauthFlow({
+ config: { ...BASE_CONFIG, pkce: false, redirectPort: freePort },
+ fetchImpl: vi.fn(async () => jsonResponse({ access_token: 'at-fixed' })) as unknown as typeof fetch,
+ openExternal: (url) => {
+ const u = new URL(url);
+ expect(u.searchParams.get('redirect_uri')).toBe(`http://127.0.0.1:${freePort}/callback`);
+ browserRedirect(url, (au) => ({ code: 'c-fixed', state: au.searchParams.get('state') ?? '' }));
+ },
+ }),
+ ]);
expect(result).toMatchObject({ ok: true });
});
@@ -352,54 +379,60 @@ describe('startGhostOauthFlow', () => {
});
it('钉死端口:第二单顶掉第一单后立刻复用同一端口(自家僵尸监听自愈,无需回收器)', async () => {
- const fixedPort = await probeFreePort();
- let secondDone: Promise<unknown> = Promise.resolve();
- const first = startGhostOauthFlow({
- config: { ...BASE_CONFIG, pkce: false, redirectPort: fixedPort },
- fetchImpl: vi.fn() as unknown as typeof fetch,
- openExternal: () => {
- // 第一单占着钉死端口等回调时,第二单同端口进场——必须等到第一单的
- // 监听真正关闭后成功 listen,而不是 LISTEN_FAILED。
- secondDone = startGhostOauthFlow({
- config: { ...BASE_CONFIG, pkce: false, redirectPort: fixedPort },
- fetchImpl: vi.fn(async () => jsonResponse({ access_token: 'at-heal' })) as unknown as typeof fetch,
- openExternal: (url2) => {
- browserRedirect(url2, (au) => ({ code: 'c-heal', state: au.searchParams.get('state') ?? '' }));
- },
- });
- },
+ const [firstResult, secondResult] = await pinnedPortCase(async (fixedPort) => {
+ let secondDone: Promise<unknown> = Promise.resolve();
+ const first = await startGhostOauthFlow({
+ config: { ...BASE_CONFIG, pkce: false, redirectPort: fixedPort },
+ fetchImpl: vi.fn() as unknown as typeof fetch,
+ openExternal: () => {
+ // 第一单占着钉死端口等回调时,第二单同端口进场——必须等到第一单的
+ // 监听真正关闭后成功 listen,而不是 LISTEN_FAILED。
+ secondDone = startGhostOauthFlow({
+ config: { ...BASE_CONFIG, pkce: false, redirectPort: fixedPort },
+ fetchImpl: vi.fn(async () => jsonResponse({ access_token: 'at-heal' })) as unknown as typeof fetch,
+ openExternal: (url2) => {
+ browserRedirect(url2, (au) => ({ code: 'c-heal', state: au.searchParams.get('state') ?? '' }));
+ },
+ });
+ },
+ });
+ return [first, await secondDone];
});
- await expect(first).resolves.toMatchObject({ ok: false, error: 'CANCELLED' });
- await expect(secondDone).resolves.toMatchObject({ ok: true });
+ expect(firstResult).toMatchObject({ ok: false, error: 'CANCELLED' });
+ expect(secondResult).toMatchObject({ ok: true });
});
it('钉死端口:第二单还在排队时第三单进场——前两单 CANCELLED,最后一单赢', async () => {
- const fixedPort = await probeFreePort();
- let secondDone: Promise<unknown> = Promise.resolve();
- let thirdDone: Promise<unknown> = Promise.resolve();
const neverOpen = vi.fn();
- const first = startGhostOauthFlow({
- config: { ...BASE_CONFIG, pkce: false, redirectPort: fixedPort },
- fetchImpl: vi.fn() as unknown as typeof fetch,
- openExternal: () => {
- // 第二单进场(排队等第一单收尾),紧接着第三单进场顶掉排队中的第二单。
- secondDone = startGhostOauthFlow({
+ const [firstResult, secondResult, thirdResult] = await pinnedPortCase(
+ async (fixedPort) => {
+ let secondDone: Promise<unknown> = Promise.resolve();
+ let thirdDone: Promise<unknown> = Promise.resolve();
+ const first = await startGhostOauthFlow({
config: { ...BASE_CONFIG, pkce: false, redirectPort: fixedPort },
fetchImpl: vi.fn() as unknown as typeof fetch,
- openExternal: neverOpen,
- });
- thirdDone = startGhostOauthFlow({
- config: { ...BASE_CONFIG, pkce: false, redirectPort: fixedPort },
- fetchImpl: vi.fn(async () => jsonResponse({ access_token: 'at-third' })) as unknown as typeof fetch,
- openExternal: (url3) => {
- browserRedirect(url3, (au) => ({ code: 'c-third', state: au.searchParams.get('state') ?? '' }));
+ openExternal: () => {
+ // 第二单进场(排队等第一单收尾),紧接着第三单进场顶掉排队中的第二单。
+ secondDone = startGhostOauthFlow({
+ config: { ...BASE_CONFIG, pkce: false, redirectPort: fixedPort },
+ fetchImpl: vi.fn() as unknown as typeof fetch,
+ openExternal: neverOpen,
+ });
+ thirdDone = startGhostOauthFlow({
+ config: { ...BASE_CONFIG, pkce: false, redirectPort: fixedPort },
+ fetchImpl: vi.fn(async () => jsonResponse({ access_token: 'at-third' })) as unknown as typeof fetch,
+ openExternal: (url3) => {
+ browserRedirect(url3, (au) => ({ code: 'c-third', state: au.searchParams.get('state') ?? '' }));
+ },
+ });
},
});
+ return [first, await secondDone, await thirdDone];
},
- });
- await expect(first).resolves.toMatchObject({ ok: false, error: 'CANCELLED' });
- await expect(secondDone).resolves.toMatchObject({ ok: false, error: 'CANCELLED' });
- await expect(thirdDone).resolves.toMatchObject({ ok: true });
+ );
+ expect(firstResult).toMatchObject({ ok: false, error: 'CANCELLED' });
+ expect(secondResult).toMatchObject({ ok: false, error: 'CANCELLED' });
+ expect(thirdResult).toMatchObject({ ok: true });
// 排队期即被顶掉的单不该拉起浏览器(不弹无主授权页)。
expect(neverOpen).not.toHaveBeenCalled();
});
@@ -560,38 +593,44 @@ describe('startGhostOauthFlow', () => {
});
it('publicRedirectUri:authorize URL 与 broker exchange 都用公网弹跳地址,本地监听仍在 loopback', async () => {
- const fixedPort = await probeFreePort();
const PUBLIC_URI = 'https://broker.example.com/jira/bounce';
- let capturedRedirectParam: string | null = null;
- const broker: GhostOauthBrokerClient = {
- exchange: vi.fn(async (slug: string, params: { code: string; redirectUri: string }) => {
- expect(slug).toBe('jira');
- expect(params.code).toBe('c-pub');
- // 双地址模型:code 交换带的 redirect_uri 必须与 authorize 时一致 = 公网弹跳地址。
- expect(params.redirectUri).toBe(PUBLIC_URI);
- return {
- ok: true as const,
- bundle: { accessToken: 'at-pub', refreshToken: 'rt-pub', expiresAt: Date.now() + 1000, grantedScope: null },
+ const [result, broker, capturedRedirectParam] = await pinnedPortCase(
+ async (
+ fixedPort,
+ ): Promise<[GhostOauthFlowResult, GhostOauthBrokerClient, string | null]> => {
+ let captured: string | null = null;
+ const brokerClient: GhostOauthBrokerClient = {
+ exchange: vi.fn(async (slug: string, params: { code: string; redirectUri: string }) => {
+ expect(slug).toBe('jira');
+ expect(params.code).toBe('c-pub');
+ // 双地址模型:code 交换带的 redirect_uri 必须与 authorize 时一致 = 公网弹跳地址。
+ expect(params.redirectUri).toBe(PUBLIC_URI);
+ return {
+ ok: true as const,
+ bundle: { accessToken: 'at-pub', refreshToken: 'rt-pub', expiresAt: Date.now() + 1000, grantedScope: null },
+ };
+ }),
+ refresh: vi.fn(),
};
- }),
- refresh: vi.fn(),
- };
- const result = await startGhostOauthFlow({
- config: { ...BASE_CONFIG, tokenBroker: 'jira', redirectPort: fixedPort, publicRedirectUri: PUBLIC_URI },
- fetchImpl: vi.fn() as unknown as typeof fetch,
- broker,
- openExternal: (url) => {
- capturedRedirectParam = new URL(url).searchParams.get('redirect_uri');
- // 假浏览器模拟弹跳路由的 302:公网地址打不通,直接回打本机 loopback
- // 缺省 /callback(未声明 callbackPath 时监听路径不变)。
- const cb = new URL(`http://127.0.0.1:${fixedPort}/callback`);
- cb.searchParams.set('code', 'c-pub');
- cb.searchParams.set('state', new URL(url).searchParams.get('state') ?? '');
- setImmediate(() => {
- void fetch(cb.toString()).catch(() => undefined);
+ const flowResult = await startGhostOauthFlow({
+ config: { ...BASE_CONFIG, tokenBroker: 'jira', redirectPort: fixedPort, publicRedirectUri: PUBLIC_URI },
+ fetchImpl: vi.fn() as unknown as typeof fetch,
+ broker: brokerClient,
+ openExternal: (url) => {
+ captured = new URL(url).searchParams.get('redirect_uri');
+ // 假浏览器模拟弹跳路由的 302:公网地址打不通,直接回打本机 loopback
+ // 缺省 /callback(未声明 callbackPath 时监听路径不变)。
+ const cb = new URL(`http://127.0.0.1:${fixedPort}/callback`);
+ cb.searchParams.set('code', 'c-pub');
+ cb.searchParams.set('state', new URL(url).searchParams.get('state') ?? '');
+ setImmediate(() => {
+ void fetch(cb.toString()).catch(() => undefined);
+ });
+ },
});
+ return [flowResult, brokerClient, captured];
},
- });
+ );
expect(result).toMatchObject({ ok: true });
if (result.ok) expect(result.bundle.accessToken).toBe('at-pub');
// 报给服务商的 redirect_uri 是公网弹跳地址,而不是 loopback。
@@ -600,64 +639,75 @@ describe('startGhostOauthFlow', () => {
});
it('callbackPath 非默认:声明路径收回调成功,缺省 /callback 404', async () => {
- const fixedPort = await probeFreePort();
- let defaultPathStatus = 0;
- const result = await startGhostOauthFlow({
- config: { ...BASE_CONFIG, pkce: false, redirectPort: fixedPort, callbackPath: '/slack-mcp/callback' },
- fetchImpl: vi.fn(async () => jsonResponse({ access_token: 'at-cbp' })) as unknown as typeof fetch,
- openExternal: (url) => {
- const u = new URL(url);
- // 单地址模型下 redirect_uri 直接带声明的 callbackPath。
- expect(u.searchParams.get('redirect_uri')).toBe(`http://127.0.0.1:${fixedPort}/slack-mcp/callback`);
- const state = u.searchParams.get('state') ?? '';
- setImmediate(() => {
- void (async () => {
- // 先打缺省 /callback:非声明路径 404,不结算本单。
- const res404 = await fetch(`http://127.0.0.1:${fixedPort}/callback?code=x&state=${state}`);
- defaultPathStatus = res404.status;
- await fetch(`http://127.0.0.1:${fixedPort}/slack-mcp/callback?code=c-cbp&state=${state}`);
- })().catch(() => undefined);
+ const [result, defaultPathStatus] = await pinnedPortCase(
+ async (fixedPort): Promise<[GhostOauthFlowResult, number]> => {
+ let status = 0;
+ const flow = await startGhostOauthFlow({
+ config: { ...BASE_CONFIG, pkce: false, redirectPort: fixedPort, callbackPath: '/slack-mcp/callback' },
+ fetchImpl: vi.fn(async () => jsonResponse({ access_token: 'at-cbp' })) as unknown as typeof fetch,
+ openExternal: (url) => {
+ const u = new URL(url);
+ // 单地址模型下 redirect_uri 直接带声明的 callbackPath。
+ expect(u.searchParams.get('redirect_uri')).toBe(`http://127.0.0.1:${fixedPort}/slack-mcp/callback`);
+ const state = u.searchParams.get('state') ?? '';
+ setImmediate(() => {
+ void (async () => {
+ // 先打缺省 /callback:非声明路径 404,不结算本单。
+ const res404 = await fetch(`http://127.0.0.1:${fixedPort}/callback?code=x&state=${state}`);
+ status = res404.status;
+ await fetch(`http://127.0.0.1:${fixedPort}/slack-mcp/callback?code=c-cbp&state=${state}`);
+ })().catch(() => undefined);
+ });
+ },
});
+ return [flow, status];
},
- });
+ );
expect(result).toMatchObject({ ok: true });
expect(defaultPathStatus).toBe(404);
});
it('跨源 code 投递(#810):声明域的 OPTIONS 预检拿到 CORS/PNA 头,GET 投递带头成功;非法来源拿不到头;无 Origin 的 302 回调不变', async () => {
- const fixedPort = await probeFreePort();
- let browserWork: Promise<{
+ type CorsProbes = {
preflightAllowed: Response;
preflightEvil: Response;
delivery: Response;
- }> | null = null;
- const result = await startGhostOauthFlow({
- config: { ...BASE_CONFIG, pkce: false, redirectPort: fixedPort },
- fetchImpl: vi.fn(async () => jsonResponse({ access_token: 'at-cors' })) as unknown as typeof fetch,
- openExternal: (url) => {
- const state = new URL(url).searchParams.get('state') ?? '';
- const cb = `http://127.0.0.1:${fixedPort}/callback`;
- browserWork = (async () => {
- // 声明域(authorizeUrl 的 origin)发预检:必须拿到 CORS + PNA 头。
- const preflightAllowed = await fetch(cb, {
- method: 'OPTIONS',
- headers: { origin: 'https://auth.example.com' },
- });
- // 任意其它网站发预检:204 但不带 CORS 头(浏览器会拦下后续请求)。
- const preflightEvil = await fetch(cb, {
- method: 'OPTIONS',
- headers: { origin: 'https://evil.example' },
- });
- // 声明域的页面 JS 跨源 GET 投递 code(xAI 新版流程形态)。
- const delivery = await fetch(`${cb}?code=c-cors&state=${state}`, {
- headers: { origin: 'https://auth.example.com' },
- });
- return { preflightAllowed, preflightEvil, delivery };
- })();
+ };
+ const [result, probes] = await pinnedPortCase(
+ async (fixedPort): Promise<[GhostOauthFlowResult, CorsProbes]> => {
+ let browserWork: Promise<CorsProbes> | null = null;
+ const flow = await startGhostOauthFlow({
+ config: { ...BASE_CONFIG, pkce: false, redirectPort: fixedPort },
+ fetchImpl: vi.fn(async () => jsonResponse({ access_token: 'at-cors' })) as unknown as typeof fetch,
+ openExternal: (url) => {
+ const state = new URL(url).searchParams.get('state') ?? '';
+ const cb = `http://127.0.0.1:${fixedPort}/callback`;
+ browserWork = (async () => {
+ // 声明域(authorizeUrl 的 origin)发预检:必须拿到 CORS + PNA 头。
+ const preflightAllowed = await fetch(cb, {
+ method: 'OPTIONS',
+ headers: { origin: 'https://auth.example.com' },
+ });
+ // 任意其它网站发预检:204 但不带 CORS 头(浏览器会拦下后续请求)。
+ const preflightEvil = await fetch(cb, {
+ method: 'OPTIONS',
+ headers: { origin: 'https://evil.example' },
+ });
+ // 声明域的页面 JS 跨源 GET 投递 code(xAI 新版流程形态)。
+ const delivery = await fetch(`${cb}?code=c-cors&state=${state}`, {
+ headers: { origin: 'https://auth.example.com' },
+ });
+ return { preflightAllowed, preflightEvil, delivery };
+ })();
+ },
+ });
+ // 初始 bind 就没抢到端口时 openExternal 不会被调用,browserWork 仍为 null;
+ // 这一轮的结果会被 pinnedPortCase 丢弃重跑,占位对象不会进入断言。
+ return [flow, (await browserWork) ?? ({} as CorsProbes)];
},
- });
+ );
expect(result).toMatchObject({ ok: true });
- const { preflightAllowed, preflightEvil, delivery } = await browserWork!;
+ const { preflightAllowed, preflightEvil, delivery } = probes;
expect(preflightAllowed!.status).toBe(204);
expect(preflightAllowed!.headers.get('access-control-allow-origin')).toBe(
@@ -675,39 +725,45 @@ describe('startGhostOauthFlow', () => {
});
it('consent 页与授权端点不同域:hosts 白名单命中的 https origin 也允许投递(#841 review)', async () => {
- const fixedPort = await probeFreePort();
- let preflightConsent: Response | null = null;
- let preflightOther: Response | null = null;
- const result = await startGhostOauthFlow({
- config: {
- ...BASE_CONFIG,
- pkce: false,
- redirectPort: fixedPort,
- // xAI 形态:authorizeUrl 在 auth 域,实际投递来自 hosts 白名单里的 accounts 域。
- corsDeliveryHosts: ['accounts.example.org', '*.wild.example.org'],
- },
- fetchImpl: vi.fn(async () => jsonResponse({ access_token: 'at-hosts' })) as unknown as typeof fetch,
- openExternal: (url) => {
- const state = new URL(url).searchParams.get('state') ?? '';
- const cb = `http://127.0.0.1:${fixedPort}/callback`;
- setImmediate(() => {
- void (async () => {
- preflightConsent = await fetch(cb, {
- method: 'OPTIONS',
- headers: { origin: 'https://accounts.example.org' },
- });
- // hosts 白名单没有的域拿不到 CORS 头;http 形态的白名单域同样不放行。
- preflightOther = await fetch(cb, {
- method: 'OPTIONS',
- headers: { origin: 'http://accounts.example.org' },
- });
- await fetch(`${cb}?code=c-hosts&state=${state}`, {
- headers: { origin: 'https://sub.wild.example.org' },
+ const [result, preflightConsent, preflightOther] = await pinnedPortCase(
+ async (
+ fixedPort,
+ ): Promise<[GhostOauthFlowResult, Response | null, Response | null]> => {
+ let consent: Response | null = null;
+ let other: Response | null = null;
+ const flow = await startGhostOauthFlow({
+ config: {
+ ...BASE_CONFIG,
+ pkce: false,
+ redirectPort: fixedPort,
+ // xAI 形态:authorizeUrl 在 auth 域,实际投递来自 hosts 白名单里的 accounts 域。
+ corsDeliveryHosts: ['accounts.example.org', '*.wild.example.org'],
+ },
+ fetchImpl: vi.fn(async () => jsonResponse({ access_token: 'at-hosts' })) as unknown as typeof fetch,
+ openExternal: (url) => {
+ const state = new URL(url).searchParams.get('state') ?? '';
+ const cb = `http://127.0.0.1:${fixedPort}/callback`;
+ setImmediate(() => {
+ void (async () => {
+ consent = await fetch(cb, {
+ method: 'OPTIONS',
+ headers: { origin: 'https://accounts.example.org' },
+ });
+ // hosts 白名单没有的域拿不到 CORS 头;http 形态的白名单域同样不放行。
+ other = await fetch(cb, {
+ method: 'OPTIONS',
+ headers: { origin: 'http://accounts.example.org' },
+ });
+ await fetch(`${cb}?code=c-hosts&state=${state}`, {
+ headers: { origin: 'https://sub.wild.example.org' },
+ });
+ })().catch(() => undefined);
});
- })().catch(() => undefined);
+ },
});
+ return [flow, consent, other];
},
- });
+ );
expect(result).toMatchObject({ ok: true });
expect(preflightConsent!.headers.get('access-control-allow-origin')).toBe(
'https://accounts.example.org',
@@ -717,26 +773,30 @@ describe('startGhostOauthFlow', () => {
});
it('跨源投递的 state 校验不放松:声明域带错 state 投递 → 400 带 CORS 头且不结算,正确投递仍成功', async () => {
- const fixedPort = await probeFreePort();
- let badDelivery: Response | null = null;
- const result = await startGhostOauthFlow({
- config: { ...BASE_CONFIG, pkce: false, redirectPort: fixedPort },
- fetchImpl: vi.fn(async () => jsonResponse({ access_token: 'x' })) as unknown as typeof fetch,
- openExternal: (url) => {
- const state = new URL(url).searchParams.get('state') ?? '';
- const cb = `http://127.0.0.1:${fixedPort}/callback`;
- setImmediate(() => {
- void (async () => {
- badDelivery = await fetch(`${cb}?code=c-bad&state=WRONG`, {
- headers: { origin: 'https://auth.example.com' },
- });
- await fetch(`${cb}?code=c-ok&state=${state}`, {
- headers: { origin: 'https://auth.example.com' },
+ const [result, badDelivery] = await pinnedPortCase(
+ async (fixedPort): Promise<[GhostOauthFlowResult, Response | null]> => {
+ let bad: Response | null = null;
+ const flow = await startGhostOauthFlow({
+ config: { ...BASE_CONFIG, pkce: false, redirectPort: fixedPort },
+ fetchImpl: vi.fn(async () => jsonResponse({ access_token: 'x' })) as unknown as typeof fetch,
+ openExternal: (url) => {
+ const state = new URL(url).searchParams.get('state') ?? '';
+ const cb = `http://127.0.0.1:${fixedPort}/callback`;
+ setImmediate(() => {
+ void (async () => {
+ bad = await fetch(`${cb}?code=c-bad&state=WRONG`, {
+ headers: { origin: 'https://auth.example.com' },
+ });
+ await fetch(`${cb}?code=c-ok&state=${state}`, {
+ headers: { origin: 'https://auth.example.com' },
+ });
+ })().catch(() => undefined);
});
- })().catch(() => undefined);
+ },
});
+ return [flow, bad];
},
- });
+ );
expect(result).toMatchObject({ ok: true });
expect(badDelivery!.status).toBe(400);
expect(badDelivery!.headers.get('access-control-allow-origin')).toBe('https://auth.example.com');
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/portReclaim.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/portReclaim.test.ts
index 9ca9018bcb..ceac4e8a89 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/portReclaim.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/portReclaim.test.ts
@@ -11,6 +11,15 @@ import { findPortOwnerPids, killPortOwner, reclaimLoopbackPort } from '../portRe
/** Windows / macOS 自带查询工具,结果必须精确;其它平台(Linux CI)可能缺 lsof。 */
const strictPlatform = process.platform === 'win32' || process.platform === 'darwin';
+/**
+ * 几条断言的前提是"这个端口号上没有别的 loopback 监听"。但端口号由 OS 从临时
+ * 端口段分配,探测用的 socket 一关,端口在断言之前完全可能被并发用例抢走 ——
+ * threads 池下同一进程里跑着多个测试文件,这个窗口不再可以忽略。被抢走时查出
+ * 候选是正确行为、不是回归,所以换端口重试;连着这么多个互不相同的端口都不干净,
+ * 才说明地址过滤真的坏了。
+ */
+const PORT_ATTEMPTS = 5;
+
async function listenLoopback(srv: http.Server): Promise<number> {
return new Promise<number>((resolve) => {
srv.listen(0, '127.0.0.1', () => {
@@ -37,10 +46,15 @@ describe('portReclaim', () => {
});
it('findPortOwnerPids:空闲端口返回空数组', async () => {
- const srv = http.createServer();
- const port = await listenLoopback(srv);
- await new Promise((r) => srv.close(r));
- await expect(findPortOwnerPids(port)).resolves.toEqual([]);
+ for (let attempt = 1; attempt <= PORT_ATTEMPTS; attempt += 1) {
+ const srv = http.createServer();
+ const port = await listenLoopback(srv);
+ await new Promise((r) => srv.close(r));
+ const pids = await findPortOwnerPids(port);
+ if (pids.length === 0) return;
+ // 端口被并发用例抢走了(见 PORT_ATTEMPTS 说明):换一个再试。
+ if (attempt === PORT_ATTEMPTS) expect(pids).toEqual([]);
+ }
});
it('findPortOwnerPids:只认挡路地址——绑非环回 IP 的监听不列为候选(不误杀)', async () => {
@@ -50,20 +64,24 @@ describe('portReclaim', () => {
.flat()
.find((i) => i && i.family === 'IPv4' && !i.internal)?.address;
if (!lanAddr) return;
- const srv = http.createServer();
- const port = await new Promise<number>((resolve, reject) => {
- srv.on('error', reject);
- srv.listen(0, lanAddr, () => {
- const addr = srv.address();
- resolve(typeof addr === 'object' && addr ? addr.port : 0);
- });
- }).catch(() => 0);
- if (port === 0) return; // 绑 LAN IP 失败(权限/网络形态),跳过
- try {
- // 该端口上只有一条绑 LAN IP 的监听:不会挡 127.0.0.1 bind,必须查不出候选。
- await expect(findPortOwnerPids(port)).resolves.toEqual([]);
- } finally {
- await new Promise((r) => srv.close(r));
+ for (let attempt = 1; attempt <= PORT_ATTEMPTS; attempt += 1) {
+ const srv = http.createServer();
+ const port = await new Promise<number>((resolve, reject) => {
+ srv.on('error', reject);
+ srv.listen(0, lanAddr, () => {
+ const addr = srv.address();
+ resolve(typeof addr === 'object' && addr ? addr.port : 0);
+ });
+ }).catch(() => 0);
+ if (port === 0) return; // 绑 LAN IP 失败(权限/网络形态),跳过
+ try {
+ // 该端口上只有一条绑 LAN IP 的监听:不会挡 127.0.0.1 bind,必须查不出候选。
+ const pids = await findPortOwnerPids(port);
+ if (pids.length === 0) return;
+ if (attempt === PORT_ATTEMPTS) expect(pids).toEqual([]);
+ } finally {
+ await new Promise((r) => srv.close(r));
+ }
}
});
@@ -76,17 +94,24 @@ describe('portReclaim', () => {
});
it('reclaimLoopbackPort:占用者是本进程时拒绝回收(护栏),端口空闲时放行重试', async () => {
- const srv = http.createServer();
- const port = await listenLoopback(srv);
- try {
- if (strictPlatform) {
- // 占用者 = 自己 → killPortOwner 护栏拒杀 → 回收失败。
- await expect(reclaimLoopbackPort(port)).resolves.toBe(false);
+ for (let attempt = 1; attempt <= PORT_ATTEMPTS; attempt += 1) {
+ const srv = http.createServer();
+ const port = await listenLoopback(srv);
+ try {
+ if (strictPlatform) {
+ // 占用者 = 自己 → killPortOwner 护栏拒杀 → 回收失败。
+ await expect(reclaimLoopbackPort(port)).resolves.toBe(false);
+ }
+ } finally {
+ await new Promise((r) => srv.close(r));
}
- } finally {
- await new Promise((r) => srv.close(r));
+ // 端口已空闲:查无占用者 → 返回 true 让调用方直接重试 listen。
+ // 只调一次并对这一次的结果下断言:reclaimLoopbackPort 依赖当次的端口归属,
+ // 重新调用会让断言看到另一个时刻的状态,既可能自己抖动、也会掩盖真正的失败态。
+ const reclaimed = await reclaimLoopbackPort(port);
+ if (reclaimed) return;
+ // 关掉后被并发用例抢走(见 PORT_ATTEMPTS 说明):整对场景换端口重来。
+ if (attempt === PORT_ATTEMPTS) expect(reclaimed).toBe(true);
}
- // 端口已空闲:查无占用者 → 返回 true 让调用方直接重试 listen。
- await expect(reclaimLoopbackPort(port)).resolves.toBe(true);
});
});
diff --git a/apps/desktop/src/main/maker-host/__tests__/claudeFastModeLog.test.ts b/apps/desktop/src/main/maker-host/__tests__/claudeFastModeLog.test.ts
index b6cb9da8e5..781489d8e9 100644
--- a/apps/desktop/src/main/maker-host/__tests__/claudeFastModeLog.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/claudeFastModeLog.test.ts
@@ -160,14 +160,16 @@ describe('createClaudeFastModeResponseObserver (结尾)', () => {
const sink = createClaudeFastModeResponseObserver(log)(ctx);
sink!.onData?.(gzipSync(Buffer.from(`${messageStartFrame('fast')}\n\n`)));
sink!.onEnd?.();
- // 解压是流式异步的(zlib 线程池回调):固定两个 tick 在测试并发高、事件循环
- // 忙时不够会 flaky,改为轮询等 debug 被调用(上限兜底防死等)。
- for (let i = 0; i < 200 && log.debug.mock.calls.length === 0; i += 1) {
- await new Promise((r) => setImmediate(r));
- }
- expect(log.debug).toHaveBeenCalledWith(
- 'claude fast mode applied (usage.speed observed)',
- expect.objectContaining({ contentEncoding: 'gzip', responseSpeed: 'fast', appliedFast: true }),
+ // 解压是流式异步的(zlib 回调走 libuv 线程池)。原先用 setImmediate 轮询:它只
+ // 推进 tick、几乎不消耗真实时间,200 个 tick 不到 1ms 就烧完。而 vitest 的
+ // threads 池下多个测试文件共享同一个进程、也就共享同一个默认 4 线程的 libuv
+ // 线程池,回调的墙钟延迟被拉长,tick 预算根本等不到(CI 实测 debug 被调用 0 次)。
+ // 改用 vi.waitFor 按墙钟等,并且等的就是断言本身成立。
+ await vi.waitFor(() =>
+ expect(log.debug).toHaveBeenCalledWith(
+ 'claude fast mode applied (usage.speed observed)',
+ expect.objectContaining({ contentEncoding: 'gzip', responseSpeed: 'fast', appliedFast: true }),
+ ),
);
});
});
diff --git a/apps/desktop/src/main/maker-host/__tests__/grokOauthCallbackListener.test.ts b/apps/desktop/src/main/maker-host/__tests__/grokOauthCallbackListener.test.ts
index 0c05be9a3a..0a68848334 100644
--- a/apps/desktop/src/main/maker-host/__tests__/grokOauthCallbackListener.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/grokOauthCallbackListener.test.ts
@@ -23,7 +23,11 @@ vi.mock('electron', () => ({
safeStorage: { isEncryptionAvailable: vi.fn(() => false) },
}));
-import { CallbackListener, xaiCallbackCorsHeaders } from '../grok-oauth-login.js';
+import {
+ CallbackListener,
+ XAI_CALLBACK_PORT_OCCUPIED_MESSAGE,
+ xaiCallbackCorsHeaders,
+} from '../grok-oauth-login.js';
const PORT = 56121;
const XAI_ORIGIN = 'https://accounts.x.ai';
@@ -88,12 +92,45 @@ describe('xaiCallbackCorsHeaders', () => {
});
});
+/**
+ * 绑 56121 时它可能短暂被别人占着,有两个来源:
+ * 1. 文件内部:close() 同步返回但端口是异步释放的,上一个用例「调过 close」
+ * 不等于端口已交还,下一个用例立刻重绑就撞上;
+ * 2. 文件外部:56121 落在临时端口段内(macOS 49152–65535 / Linux 32768–60999),
+ * 任何用 listen(0) 拿端口的并发用例都可能被内核分到它。desktop unit tier
+ * 一轮 1330 个文件、threads 池下还共享同一个进程,这不是理论风险 —— CI 上
+ * 两轮分别撞在不同用例的 beforeEach 上。而 xAI 只接受
+ * http://127.0.0.1:56121/callback,端口换不了。
+ *
+ * 两者是同一句话,所以只留一个判据:仅在引擎明确报出「端口被占用」时短暂重试,
+ * 其它启动失败原样抛出,不掩盖真正的问题。每次重试用全新实例,免得复用一个
+ * listen 失败过的 server。同族的客户端那一半由 send() 的 agent:false 处理。
+ *
+ * 判据必须与生产同源:start() 把底层错误包成新 Error、丢掉了 err.code,只剩文本可看,
+ * 而按端口号做子串匹配会连 EACCES / EADDRNOTAVAIL 一起收进来(它们的原文里同样带端口
+ * 号),把真正的启动故障当成「端口被占」白重试 100 次。所以整条比对生产导出的那句
+ * EADDRINUSE 专属提示。
+ */
+async function startFreshListener(): Promise<CallbackListener> {
+ for (let attempt = 1; ; attempt += 1) {
+ const candidate = new CallbackListener();
+ try {
+ await candidate.start();
+ return candidate;
+ } catch (err) {
+ candidate.close();
+ const occupied = err instanceof Error && err.message === XAI_CALLBACK_PORT_OCCUPIED_MESSAGE;
+ if (!occupied || attempt >= 100) throw err;
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ }
+ }
+}
+
describe('CallbackListener(xAI loopback 回调)', () => {
let listener: CallbackListener;
beforeEach(async () => {
- listener = new CallbackListener();
- await listener.start();
+ listener = await startFreshListener();
});
afterEach(() => {
@@ -323,8 +360,12 @@ describe('CallbackListener(xAI loopback 回调)', () => {
it('回调端口被占用时 start() 报可读错误', async () => {
const blocker = new CallbackListener();
- // beforeEach 已占 56121,新实例 start 应失败。
- await expect(blocker.start()).rejects.toThrow('56121');
+ // beforeEach 已占 56121,新实例 start 应失败。整条比对,不按端口号做子串匹配
+ // ——后者对任何带端口号的 listen 失败都成立(见 startFreshListener 说明)。
+ await expect(blocker.start()).rejects.toThrow(XAI_CALLBACK_PORT_OCCUPIED_MESSAGE);
blocker.close();
+ // 上面那条是同源比对,改文案不会让它失败;这句守住「用户看得见端口号」这个可读性
+ // 要求本身,顺带交叉校验测试里的 PORT 与生产的 REDIRECT_PORT 没有跑偏。
+ expect(XAI_CALLBACK_PORT_OCCUPIED_MESSAGE).toContain(String(PORT));
});
});
diff --git a/apps/desktop/src/main/maker-host/grok-oauth-login.ts b/apps/desktop/src/main/maker-host/grok-oauth-login.ts
index d41ead6d25..98601ef8b2 100644
--- a/apps/desktop/src/main/maker-host/grok-oauth-login.ts
+++ b/apps/desktop/src/main/maker-host/grok-oauth-login.ts
@@ -251,6 +251,15 @@ export function xaiCallbackCorsHeaders(origin: string | undefined): Record<strin
}
// ── 回调监听(固定端口 56121)────────────────────────────────────────────────────
+/**
+ * EADDRINUSE 专属的用户可读提示。单独导出是为了让「这次失败是不是端口被占」有一个
+ * 与生产同源的判据:start() 把底层错误包成新 Error、丢掉了 err.code,调用方只剩文本
+ * 可看;而 Node 其它 listen 失败的原文里同样带端口号(实测
+ * `listen EADDRNOTAVAIL: address not available 240.0.0.1:56121`),按端口号做子串匹配
+ * 会把 EACCES / EADDRNOTAVAIL 一起误判成端口被占。
+ */
+export const XAI_CALLBACK_PORT_OCCUPIED_MESSAGE = `xAI OAuth 回调端口 ${REDIRECT_PORT} 被占用(可能有其它 Grok 登录在跑),请关掉后重试`;
+
// 导出仅供单测(runGrokOAuthLogin 是唯一运行期使用方)。
export class CallbackListener {
private server: Server;
@@ -279,7 +288,7 @@ export class CallbackListener {
reject(
new Error(
err.code === 'EADDRINUSE'
- ? `xAI OAuth 回调端口 ${REDIRECT_PORT} 被占用(可能有其它 Grok 登录在跑),请关掉后重试`
+ ? XAI_CALLBACK_PORT_OCCUPIED_MESSAGE
: `OAuth callback server failed: ${err.message}`,
),
),
diff --git a/apps/desktop/vitest.config.ts b/apps/desktop/vitest.config.ts
index b7b5ffabaf..e25b016ca7 100644
--- a/apps/desktop/vitest.config.ts
+++ b/apps/desktop/vitest.config.ts
@@ -72,12 +72,17 @@ export default defineConfig({
// --localstorage-file 时方法全缺的残缺对象:node 环境下骗过
// `typeof localStorage !== 'undefined'` 探测,jsdom 环境下又因 key 已存在
// 顶掉 jsdom 注入的可用实现(vitest 填充全局时跳过已存在的 key)。统一在
- // worker 进程关掉该全局(flag 自 Node 22 起有效),恢复两种环境的原语义;
- // CI(Node 22,webstorage 默认关)上本为 no-op。配置放这里(而非 test 脚本
- // 注 NODE_OPTIONS)是因为根 test-workspaces runner 走 `exec vitest run`
- // 直调、不经 package.json 脚本,只有 config 层对所有入口一致生效。
+ // worker 里关掉该全局(flag 自 Node 22 起有效),恢复两种环境的原语义。
+ // 配置放这里(而非 test 脚本注 NODE_OPTIONS)是因为根 test-workspaces runner
+ // 走 `exec vitest run` 直调、不经 package.json 脚本,只有 config 层对所有
+ // 入口一致生效。
+ //
+ // 只给 forks 池配这个 execArgv,threads 池一律不配:给 worker thread 传自定义
+ // execArgv 会让 isolate 销毁时段错误(实测数据见 scripts/shared/node-webstorage.mjs),
+ // 所以哪怕有人手动 `--pool=threads` 也不该拿到这份配置。需要这个 flag 的 Node 上,
+ // 根 manifest 会用同一个 nodeWebstorageEnabled() 判据把 unit tier 留在 forks,
+ // 两者不会同时生效;不需要 flag 的 Node(本机与 CI 的 22)上压根没有 webstorage 全局。
poolOptions: {
- threads: { execArgv: ['--no-experimental-webstorage'] },
forks: { execArgv: ['--no-experimental-webstorage'] },
},
// Main-process code is pure Node — no DOM needed. Renderer tests (if/when
diff --git a/scripts/__tests__/test-workspaces.test.mjs b/scripts/__tests__/test-workspaces.test.mjs
index 2a2202d823..36592ca758 100644
--- a/scripts/__tests__/test-workspaces.test.mjs
+++ b/scripts/__tests__/test-workspaces.test.mjs
@@ -8,6 +8,7 @@ import { fileURLToPath } from "node:url";
import manifest, {
desktopUnitWorkerCount,
} from "../test-workspaces.config.mjs";
+import { nodeWebstorageEnabled } from "../shared/node-webstorage.mjs";
import {
acquireTestGateLock,
classifyTestGateLockProbeError,
@@ -151,7 +152,7 @@ test("orca workflow unit tier uses its own declared test runner", () => {
assert.deepEqual(orcaWorkspace.tiers.unit.command, {
type: "packageBin",
bin: "vitest",
- args: ["run", "--maxWorkers=1"],
+ args: ["run", "--pool=threads", "--maxWorkers=1"],
});
});
@@ -168,6 +169,7 @@ test("unit workspace concurrency reserves the full worker budget for heavy works
assert.equal(desktop.tiers.unit.execution, "exclusive");
assert.deepEqual(desktop.tiers.unit.command.args, [
"run",
+ `--pool=${nodeWebstorageEnabled() ? "forks" : "threads"}`,
`--maxWorkers=${desktopUnitWorkerCount()}`,
]);
assert.equal(desktopUnitWorkerCount(1), 1);
@@ -175,15 +177,60 @@ test("unit workspace concurrency reserves the full worker budget for heavy works
assert.equal(desktopUnitWorkerCount(32), 8);
assert.equal(desktopUnitWorkerCount(Number.NaN), 1);
assert.equal(mobile.tiers.unit.execution, "exclusive");
- assert.deepEqual(mobile.tiers.unit.command.args, ["run", "--maxWorkers=4"]);
+ assert.deepEqual(mobile.tiers.unit.command.args, [
+ "run",
+ "--pool=threads",
+ "--maxWorkers=4",
+ ]);
assert.equal(makerCore.tiers.unit.execution, undefined);
assert.deepEqual(makerCore.tiers.unit.command, {
type: "packageBin",
bin: "vitest",
- args: ["run", "--maxWorkers=1"],
+ args: ["run", "--pool=forks", "--maxWorkers=1"],
});
});
+test("unit tier pins an explicit vitest pool, forks only by documented exception", () => {
+ // The default forks pool recycles one child process per test file, which on
+ // 2026-07-30 sustained ~21 LaunchServices check-ins/second and took down
+ // macOS 27.0 beta's launchservicesd mid-gate (empty running-application
+ // registry -> no frontmost app -> dead keyboard, no menu bar, vanishing Dock
+ // tiles). A workspace added later must not silently inherit that churn, and
+ // opting back into forks must be a deliberate edit to this list.
+ // Desktop's entry is conditional: it only stays on forks on a Node whose
+ // webstorage globals force the execArgv that worker threads cannot take.
+ const forksByException = [
+ ...(nodeWebstorageEnabled() ? ["apps/desktop"] : []),
+ "packages/maker-core",
+ ];
+ const unpinned = [];
+ const onForks = [];
+ for (const workspace of manifest.workspaces) {
+ const tier = workspace.tiers?.unit;
+ if (!tier || (tier.status !== "required" && tier.status !== "manual"))
+ continue;
+ if (tier.command?.type !== "packageBin" || tier.command.bin !== "vitest")
+ continue;
+ const args = tier.command.args ?? [];
+ if (args.includes("--pool=forks")) onForks.push(workspace.cwd);
+ else if (!args.includes("--pool=threads")) unpinned.push(workspace.cwd);
+ }
+ assert.deepEqual(unpinned, []);
+ assert.deepEqual(onForks.sort(), [...forksByException].sort());
+});
+
+test("nodeWebstorageEnabled detects the globals that force the webstorage flag", () => {
+ assert.equal(nodeWebstorageEnabled({}), false);
+ assert.equal(nodeWebstorageEnabled({ localStorage: undefined }), false);
+ assert.equal(nodeWebstorageEnabled({ localStorage: {} }), true);
+ // Node 25's stub is an object whose methods are all missing; presence is what
+ // matters here, because that alone displaces jsdom's implementation.
+ assert.equal(
+ nodeWebstorageEnabled({ localStorage: Object.create(null) }),
+ true,
+ );
+});
+
test("normalizeRelPath makes path matching independent of host path separators", () => {
assert.equal(
normalizeRelPath("apps\\desktop\\src\\main\\foo.test.ts"),
diff --git a/scripts/shared/node-webstorage.mjs b/scripts/shared/node-webstorage.mjs
new file mode 100644
index 0000000000..5998286b7a
--- /dev/null
+++ b/scripts/shared/node-webstorage.mjs
@@ -0,0 +1,28 @@
+/**
+ * Node 25 installs the WebStorage globals by default, and with no
+ * `--localstorage-file` configured `globalThis.localStorage` is a stub whose
+ * methods are all missing: under the node environment it fools a
+ * `typeof localStorage !== 'undefined'` probe, and under jsdom the pre-existing
+ * key displaces jsdom's working implementation, because Vitest skips populating
+ * globals that already exist. `--no-experimental-webstorage` restores the
+ * original semantics; on Node 22 (local dev and CI) the global never exists, so
+ * the flag is a pure no-op there.
+ *
+ * The flag and the threads pool are mutually exclusive: passing custom execArgv
+ * to worker threads segfaults the isolate during teardown. Measured 2026-07-30:
+ * 2 of 10 full desktop unit runs crashed inside
+ * node::worker::WorkerThreadData::~WorkerThreadData -> final GC ->
+ * GlobalHandles::InvokeFirstPassWeakCallbacks, i.e. a native addon finalizer
+ * touching freed memory as the isolate went away; 8 further runs with the
+ * execArgv removed produced none. apps/desktop therefore hands the flag to the
+ * forks pool only, and never to threads.
+ *
+ * That leaves the pool choice, which is what this predicate decides (see
+ * UNIT_POOL_DEFAULT in scripts/test-workspaces.config.mjs): where the flag is
+ * genuinely needed, apps/desktop keeps today's behaviour and stays on forks so
+ * the flag still applies; where it is a no-op, the unit tier takes threads
+ * instead, which spawns no process per test file.
+ */
+export function nodeWebstorageEnabled(globalObject = globalThis) {
+ return typeof globalObject.localStorage !== 'undefined';
+}
diff --git a/scripts/test-workspaces.config.mjs b/scripts/test-workspaces.config.mjs
index aecd75ddcf..550e586191 100644
--- a/scripts/test-workspaces.config.mjs
+++ b/scripts/test-workspaces.config.mjs
@@ -1,10 +1,38 @@
import os from 'node:os';
+import { nodeWebstorageEnabled } from './shared/node-webstorage.mjs';
+
const vitestBin = (...args) => ({ type: 'packageBin', bin: 'vitest', args });
+// The unit tier pins the threads pool. Vitest's default `forks` pool keeps
+// `isolate` on and so recycles a child process per test file: this tier's ~1845
+// files cost ~1.9k process spawns per gate run, measured at 21 LaunchServices
+// check-ins/second on an 18-core macOS host. On 2026-07-30 that sustained churn
+// took down macOS 27.0 beta's launchservicesd, which came back with an empty
+// running-application registry — leaving the session with no frontmost app at
+// all: no menu bar, no keyboard input anywhere, Dock tiles vanishing on click,
+// and only a reboot to recover. Worker threads keep the same per-file isolation
+// at zero process cost (same 180 desktop files: 189 check-ins versus 1,
+// identical results, slightly faster).
+//
+// Not everything moves. The heavy manual tiers (db, migration, git-integration)
+// stay on the default pool: they bootstrap runtime assets and drive real
+// Git/SQLite subprocesses, and none sits on the PR gate path. A workspace also
+// opts out when its tests cannot survive a worker thread; both known blockers
+// are recorded at their call site below — desktop needs the webstorage flag on a
+// Node that installs those globals, and the flag cannot coexist with worker
+// threads (scripts/shared/node-webstorage.mjs), while maker-core fakes HOME,
+// which a worker cannot see because `process.env` there is a thread-local copy
+// while `os.homedir()` reads the real environment through libuv.
+//
+// Keep every opt-out listed in the pool regression test, and keep the list
+// short: at 1330 of this tier's 1845 files, desktop alone decides whether the
+// churn is a trickle or back to where it started.
+const UNIT_POOL_DEFAULT = 'threads';
// Workspace-level parallelism owns the global process budget. Keep ordinary
// Vitest workspaces at one worker each so outer concurrency cannot multiply
// every child process's default CPU-sized pool.
-const unitVitestCommand = (workers = 1) => vitestBin('run', `--maxWorkers=${workers}`);
+const unitVitestCommand = (workers = 1, pool = UNIT_POOL_DEFAULT) =>
+ vitestBin('run', `--pool=${pool}`, `--maxWorkers=${workers}`);
const noCollectableTestsReason = 'No collectable tests yet. Add tests and mark a tier required when this workspace gains testable logic.';
const desktopDbInclude = [
'src/main/localDb/**/__tests__/*.test.ts',
@@ -40,7 +68,7 @@ const noCollectableWorkspace = (name, cwd, reason = noCollectableTestsReason) =>
tiers: {},
});
-const requiredUnitWorkspace = (name, cwd, { workers = 1, execution } = {}) => ({
+const requiredUnitWorkspace = (name, cwd, { workers = 1, execution, pool } = {}) => ({
name,
cwd,
status: 'required',
@@ -48,7 +76,7 @@ const requiredUnitWorkspace = (name, cwd, { workers = 1, execution } = {}) => ({
unit: {
status: 'required',
...(execution ? { execution } : {}),
- command: unitVitestCommand(workers),
+ command: unitVitestCommand(workers, pool),
},
},
});
@@ -67,7 +95,16 @@ export default {
// found eight workers to be the best complexity/resource tradeoff.
// Lower-CPU hosts stay capped by their available parallelism.
// It runs exclusively so these workers never overlap outer workspaces.
- command: vitestBin('run', `--maxWorkers=${desktopUnitWorkerCount()}`),
+ // The pool follows the webstorage flag, because the flag cannot
+ // coexist with worker threads — see scripts/shared/node-webstorage.mjs
+ // for the crash it causes and the measurements. On Node 22, which is
+ // what local dev and CI run, the flag is a no-op, so this suite's 1330
+ // files take threads and stop spawning a process each. On a
+ // webstorage-enabled Node the flag wins and the suite stays on forks.
+ command: unitVitestCommand(
+ desktopUnitWorkerCount(),
+ nodeWebstorageEnabled() ? 'forks' : 'threads',
+ ),
exclude: [
'**/*.git-integration.test.ts',
'src/main/localDb/**',
@@ -153,7 +190,10 @@ export default {
requiredUnitWorkspace('@cindy/im', 'packages/lizi-im'),
requiredUnitWorkspace('@cindy/mcps', 'packages/lizi-mcps'),
requiredUnitWorkspace('@cindy/maker-cc-manager', 'packages/maker-cc-manager'),
- requiredUnitWorkspace('@cindy/maker-core', 'packages/maker-core'),
+ // Stays on forks: palette-scanner's tests stub HOME and the scanner resolves
+ // it through os.homedir(), which a worker thread cannot see (see
+ // UNIT_POOL_DEFAULT above).
+ requiredUnitWorkspace('@cindy/maker-core', 'packages/maker-core', { pool: 'forks' }),
requiredUnitWorkspace('@cindy/maker-remote-ssh', 'packages/maker-remote-ssh'),
requiredUnitWorkspace('@cindy/maker-scheduler', 'packages/maker-scheduler'),
requiredUnitWorkspace('@cindy/maker-shared', 'packages/maker-shared'),