Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi-kernel): Windows 上 Pi 内核发布 rename 有界重试,并记录安装失败阶段(#5204) (#5206)
Chris Zhangc7a469d06507
diff --git a/apps/desktop/src/main/agent-binaries/__tests__/pi-self-update.test.ts b/apps/desktop/src/main/agent-binaries/__tests__/pi-self-update.test.tsindex 8a27099355..0d7f7d3433 100644--- a/apps/desktop/src/main/agent-binaries/__tests__/pi-self-update.test.ts+++ b/apps/desktop/src/main/agent-binaries/__tests__/pi-self-update.test.ts@@ -5,7 +5,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';import { promises as fs } from 'node:fs';import os from 'node:os';import path from 'node:path';-import { installPiBinaryUpdate, parsePiRelease, piBinaryUpdateFailureStage, type PiBinaryUpdateDeps } from '../pi-self-update.js';+import { installPiBinaryUpdate, parsePiRelease, piBinaryUpdateFailureStage, renameWithTransientRetry, type PiBinaryUpdateDeps } from '../pi-self-update.js';const electronFetch = vi.hoisted(() => vi.fn());vi.mock('electron', () => ({ net: { fetch: electronFetch } }));@@ -88,6 +88,40 @@ describe('Pi standalone core update', () => {expect(deps.probe).toHaveBeenCalledTimes(3);await expect(fs.stat(path.dirname(extractionRoot))).rejects.toMatchObject({ code: 'ENOENT' });});+ it('retries a publish rename briefly blocked by Windows security software (#5204)', async () => {+ const { root, current, deps } = await fixture('win32');+ const rename = fs.rename.bind(fs);+ const spy = vi.spyOn(fs, 'rename').mockRejectedValueOnce(Object.assign(new Error('EPERM: operation not permitted, rename'), { code: 'EPERM' }))+ .mockImplementation(rename);+ const result = await installPiBinaryUpdate(root, current, false, deps, 'win32', 'arm64');+ expect(result.version).toBe('0.85.1');+ expect(spy).toHaveBeenCalledTimes(2);+ expect(await fs.readFile(path.join(path.dirname(result.binaryPath), '.verified'), 'utf8')).toBe('a'.repeat(64));+ expect(await fs.readFile(current, 'utf8')).toBe('old-running-runtime');+ });+ it('fails a permanently denied publish at the publish stage without retrying off Windows', async () => {+ const { root, current, deps } = await fixture();+ const spy = vi.spyOn(fs, 'rename').mockRejectedValue(Object.assign(new Error('EPERM'), { code: 'EPERM' }));+ const error = await installPiBinaryUpdate(root, current, false, deps, 'darwin', 'arm64').catch(error => error);+ expect(error).toMatchObject({ code: 'EPERM' });+ expect(piBinaryUpdateFailureStage(error)).toBe('publish');+ expect(spy).toHaveBeenCalledTimes(1);+ expect(await fs.readdir(root)).toEqual(['0.84.4']);+ expect(await fs.readFile(current, 'utf8')).toBe('old-running-runtime');+ });+ it('bounds Windows rename retries to transient codes and the install signal', async () => {+ const signal = new AbortController().signal;+ const eperm = vi.spyOn(fs, 'rename').mockRejectedValue(Object.assign(new Error('EPERM'), { code: 'EPERM' }));+ await expect(renameWithTransientRetry('a', 'b', { platform: 'win32', signal, delaysMs: [1, 1, 1] })).rejects.toMatchObject({ code: 'EPERM' });+ expect(eperm).toHaveBeenCalledTimes(4);+ eperm.mockReset().mockRejectedValue(Object.assign(new Error('ENOSPC'), { code: 'ENOSPC' }));+ await expect(renameWithTransientRetry('a', 'b', { platform: 'win32', signal, delaysMs: [1, 1, 1] })).rejects.toMatchObject({ code: 'ENOSPC' });+ expect(eperm).toHaveBeenCalledTimes(1);+ eperm.mockReset().mockRejectedValue(Object.assign(new Error('EBUSY'), { code: 'EBUSY' }));+ const aborted = new AbortController(); aborted.abort();+ await expect(renameWithTransientRetry('a', 'b', { platform: 'win32', signal: aborted.signal, delaysMs: [60_000] })).rejects.toMatchObject({ name: 'AbortError' });+ expect(eperm).toHaveBeenCalledTimes(1);+ });it('leaves the old installation usable when version verification fails', async () => {const { root, current, deps } = await fixture();deps.probe = vi.fn(async () => '0.84.4');diff --git a/apps/desktop/src/main/agent-binaries/pi-self-update.ts b/apps/desktop/src/main/agent-binaries/pi-self-update.tsindex 16a9314412..0c436b644c 100644--- a/apps/desktop/src/main/agent-binaries/pi-self-update.ts+++ b/apps/desktop/src/main/agent-binaries/pi-self-update.ts@@ -3,9 +3,13 @@ import type { PiBinaryUpdateFailureStage } from '@cindy/maker-core';import { promises as fs } from 'node:fs';import path from 'node:path';import { randomUUID } from 'node:crypto';+import { setTimeout as delay } from 'node:timers/promises';import { download } from '../downloader/index.js';import { extractMakeToolArchive } from '../cindy-make/toolArchive.js';import { isBinaryVersionNotOlder, probeBinaryVersion } from './binary-version-probe.js';+import { createLogger } from '../logger.js';++const log = createLogger('pi-self-update');const failureStages = new WeakMap<object, PiBinaryUpdateFailureStage>();export function piBinaryUpdateFailureStage(error: unknown): PiBinaryUpdateFailureStage | undefined {@@ -79,6 +83,38 @@ export async function installPiBinaryUpdate(export type PiBinaryRelease = ReturnType<typeof parsePiRelease>;+/** Windows security software can briefly hold handles on a freshly extracted and+ * just-executed pi.exe, so the publish rename fails with a transient code (#5204). */+const TRANSIENT_RENAME_CODES = new Set(['EPERM', 'EBUSY', 'EACCES']);+/** Bounded (~9.75s) and still inside the install AbortSignal; aligned with #5026. */+export const PI_PUBLISH_RENAME_RETRY_DELAYS_MS: readonly number[] = [250, 500, 1000, 2000, 3000, 3000];++export async function renameWithTransientRetry(+ from: string, to: string, options: { platform: string; signal: AbortSignal; delaysMs?: readonly number[] },+): Promise<void> {+ // Elsewhere EPERM/EACCES are real permission failures; retrying only delays the error.+ const delays = options.platform === 'win32' ? options.delaysMs ?? PI_PUBLISH_RENAME_RETRY_DELAYS_MS : [];+ for (let attempt = 0; ; attempt += 1) {+ try {+ await fs.rename(from, to);+ if (attempt > 0) log.info('Pi publish rename succeeded after transient retry', { attempts: attempt + 1 });+ return;+ } catch (error) {+ const code = (error as NodeJS.ErrnoException).code;+ if (attempt >= delays.length || !code || !TRANSIENT_RENAME_CODES.has(code)) throw error;+ log.warn('Pi publish rename hit transient error; retrying', { code, attempt: attempt + 1, delayMs: delays[attempt] });+ await delay(delays[attempt], undefined, { signal: options.signal });+ }+ }+}++function logCleanupFailure(target: 'staging' | 'unpublished-destination') {+ // Target label and code only: the path carries the user's profile directory.+ return (error: unknown): void => log.warn('Pi install cleanup failed; leftover directory', {+ target, code: (error as NodeJS.ErrnoException)?.code ?? 'unknown',+ });+}+/** Both Cindy release and upstream installs publish immutable, version-named directories. */export async function installPiBinaryRelease(root: string, release: PiBinaryRelease,@@ -112,7 +148,7 @@ export async function installPiBinaryRelease(if (await deps.probe(binary, signal) !== release.version) throw new Error('Downloaded Pi version verification failed');failureStage = 'publish';onPhase?.('activate');- await fs.rename(distribution, destination);+ await renameWithTransientRetry(distribution, destination, { platform, signal });const finalBinary = path.join(destination, release.executable);failureStage = 'version-verification';onPhase?.('verify');@@ -124,8 +160,8 @@ export async function installPiBinaryRelease(published = true;return { binaryPath: finalBinary, version: release.version };} finally {- await fs.rm(stage, { recursive: true, force: true }).catch(() => undefined);- if (!published) await fs.rm(destination, { recursive: true, force: true }).catch(() => undefined);+ await fs.rm(stage, { recursive: true, force: true }).catch(logCleanupFailure('staging'));+ if (!published) await fs.rm(destination, { recursive: true, force: true }).catch(logCleanupFailure('unpublished-destination'));}} catch (error) {const failure = error instanceof Error ? error : new Error('Pi installation failed');diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pi-kernel.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pi-kernel.test.tsindex ad0de96b5a..058d999de0 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/pi-kernel.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/pi-kernel.test.ts@@ -1,6 +1,9 @@import { beforeEach, describe, expect, it, vi } from 'vitest';import { createPiKernelIpc } from '../pi-kernel.js';import { PiKernelError } from '../../agent-binaries/pi-kernel-manager.js';+import { piBinaryUpdateError } from '../../agent-binaries/pi-self-update.js';+const logError = vi.hoisted(() => vi.fn());+vi.mock('../../logger.js', () => ({ createLogger: () => ({ trace: vi.fn(), debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: logError, fatal: vi.fn() }) }));vi.mock('../../agent-binaries/index.js', () => ({ getPiKernelManager: vi.fn() }));vi.mock('../../manifestService.js', () => ({ getBaseUrl: vi.fn(), getPlatformKey: vi.fn() }));const manager = { state: vi.fn(), check: vi.fn(), install: vi.fn() };@@ -28,4 +31,17 @@ describe('Pi version IPC boundary', () => {manager.install.mockRejectedValueOnce(new Error('/Users/private/secret'));await expect(handlers.install({}, { source: 'upstream', version: '0.87.1' })).rejects.toMatchObject({ code: 'INTERNAL', message: '[INTERNAL] Pi kernel installation failed' });});+ it('logs the failure stage and errno locally without the path-bearing message (#5204)', async () => {+ manager.install.mockRejectedValueOnce(piBinaryUpdateError(Object.assign(new Error("EPERM: rename 'C:\\Users\\me\\x'"), { code: 'EPERM' }), 'publish'));+ await expect(handlers.install({}, { source: 'upstream', version: '0.87.1' })).rejects.toMatchObject({ code: 'INTERNAL', message: '[INTERNAL] Pi kernel installation failed' });+ expect(logError).toHaveBeenCalledWith('Pi kernel installation failed', { source: 'upstream', stage: 'publish', code: 'EPERM' });+ expect(JSON.stringify(logError.mock.calls)).not.toContain('Users');+ logError.mockClear();+ manager.install.mockRejectedValueOnce(new PiKernelError('busy'));+ await expect(handlers.install({}, { source: 'upstream', version: '0.87.1' })).rejects.toMatchObject({ code: 'INTERNAL' });+ expect(logError).not.toHaveBeenCalled();+ manager.state.mockRejectedValueOnce(new Error('state unavailable'));+ await expect(handlers.install({}, { source: 'upstream', version: '0.87.1' })).rejects.toMatchObject({ code: 'INTERNAL' });+ expect(logError).not.toHaveBeenCalled();+ });});diff --git a/apps/desktop/src/main/maker-ipc/pi-kernel.ts b/apps/desktop/src/main/maker-ipc/pi-kernel.tsindex 1f4ba0ba97..318877e5d8 100644--- a/apps/desktop/src/main/maker-ipc/pi-kernel.ts+++ b/apps/desktop/src/main/maker-ipc/pi-kernel.ts@@ -2,10 +2,14 @@ import { ipcMain, type IpcMainInvokeEvent } from 'electron';import type { PiKernelManager } from '../agent-binaries/pi-kernel-manager.js';import { PiKernelError } from '../agent-binaries/pi-kernel-manager.js';import { getPiKernelManager } from '../agent-binaries/index.js';+import { piBinaryUpdateFailureStage } from '../agent-binaries/pi-self-update.js';+import { createLogger } from '../logger.js';import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';import { throwIpcError } from '../utils/ipcValidate.js';import { MAKER_INVOKE } from './channels.js';+const log = createLogger('pi-kernel');+export function createPiKernelIpc<Event>(deps: {assertSender: (event: Event) => void;manager: () => Pick<PiKernelManager, 'state' | 'check' | 'install'>;@@ -26,7 +30,20 @@ export function createPiKernelIpc<Event>(deps: {throwIpcError('INVALID_PARAMS', 'Invalid Pi install target');}try {- await deps.manager().install({ source: body.source, version: body.version });+ try {+ await deps.manager().install({ source: body.source, version: body.version });+ } catch (error) {+ if (!(error instanceof PiKernelError)) {+ // The renderer only sees a generic failure; keep the stage and errno here+ // (never the message, which may carry local paths).+ log.error('Pi kernel installation failed', {+ source: body.source,+ stage: piBinaryUpdateFailureStage(error) ?? 'unknown',+ code: (error as NodeJS.ErrnoException)?.code ?? 'none',+ });+ }+ throw error;+ }return await deps.manager().state();} catch (error) {const code = error instanceof PiKernelError && error.reason === 'version-changed' ? 'PRECONDITION_FAILED' : 'INTERNAL';