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。

fix(desktop): 避免自动降级本地 PI runtime (#3594)

Chris Zhanga0ad8aa69868
diff --git a/apps/desktop/src/main/agent-binaries/__tests__/binary-version-probe.test.ts b/apps/desktop/src/main/agent-binaries/__tests__/binary-version-probe.test.ts
new file mode 100644
index 0000000000..39937e5cd2
--- /dev/null
+++ b/apps/desktop/src/main/agent-binaries/__tests__/binary-version-probe.test.ts
@@ -0,0 +1,40 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ isBinaryVersionNotOlder,
+ parseBinaryVersionOutput,
+ probeBinaryVersion,
+} from '../binary-version-probe.js';
+
+describe('binary version probe', () => {
+ it('normalizes bare, v-prefixed, and Pi-prefixed semantic versions', () => {
+ expect(parseBinaryVersionOutput('0.84.4\n', '')).toBe('0.84.4');
+ expect(parseBinaryVersionOutput('v0.84.4-beta.1\n', '')).toBe('0.84.4-beta.1');
+ expect(parseBinaryVersionOutput('pi 0.84.4\n', '')).toBe('0.84.4');
+ expect(parseBinaryVersionOutput('pi v0.84.4-beta.1\n', '')).toBe('0.84.4-beta.1');
+ });
+
+ it('uses SemVer precedence for prerelease arbitration', () => {
+ expect(isBinaryVersionNotOlder('0.84.5-beta.1', '0.84.4')).toBe(true);
+ expect(isBinaryVersionNotOlder('0.84.5-beta.1', '0.84.5')).toBe(false);
+ });
+
+ it('rejects unrelated or multiline-leading output', () => {
+ expect(parseBinaryVersionOutput('other 0.84.4\n', '')).toBeNull();
+ expect(parseBinaryVersionOutput('warning\n0.84.4\n', '')).toBeNull();
+ });
+
+ it('returns null instead of throwing when the executable cannot be spawned', async () => {
+ await expect(probeBinaryVersion('/definitely/missing/cindy-runtime')).resolves.toBeNull();
+ });
+
+ it('returns null when the host cancels the startup probe', async () => {
+ const controller = new AbortController();
+ controller.abort();
+ await expect(probeBinaryVersion(process.execPath, controller.signal)).resolves.toBeNull();
+ });
+
+ it('executes a cross-platform binary with a bounded --version probe', async () => {
+ await expect(probeBinaryVersion(process.execPath)).resolves.toMatch(/^\d+\.\d+\.\d+/);
+ });
+});
diff --git a/apps/desktop/src/main/agent-binaries/__tests__/factory-local-version.test.ts b/apps/desktop/src/main/agent-binaries/__tests__/factory-local-version.test.ts
new file mode 100644
index 0000000000..066a72e80a
--- /dev/null
+++ b/apps/desktop/src/main/agent-binaries/__tests__/factory-local-version.test.ts
@@ -0,0 +1,247 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import { gzipSync } from 'node:zlib';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { VendorAsset } from '../manifest.js';
+
+const FAKE_SHA = 'c'.repeat(64);
+const installRoots: string[] = [];
+
+const mocks = vi.hoisted(() => ({
+ asset: {
+ current: {
+ version: '0.84.3',
+ file: 'pi/0.84.3/darwin-arm64/pi.gz',
+ sha256: 'c'.repeat(64),
+ size: 3,
+ } as VendorAsset,
+ },
+ download: vi.fn(),
+}));
+
+vi.mock('../../downloader/index.js', () => ({
+ download: mocks.download,
+ DownloadError: class DownloadError extends Error {
+ code: string;
+ constructor(code: string, message: string) {
+ super(message);
+ this.code = code;
+ }
+ },
+}));
+
+vi.mock('../../manifestService.js', () => ({
+ fetchManifest: vi.fn(async () => ({ app: {} })),
+ getCachedManifest: vi.fn(() => ({ app: {} })),
+ getBaseUrl: () => 'https://cdn.test',
+ getPlatformKey: () => 'darwin-arm64',
+}));
+
+vi.mock('../manifest.js', () => ({
+ getVendorAsset: () => mocks.asset.current,
+ resolveVendorAssetUrl: (base: string, asset: VendorAsset) => `${base}/${asset.file}`,
+}));
+
+import { createBinaryProvisioner } from '../factory.js';
+
+interface DownloadOpts {
+ targetPath: string;
+}
+
+function uniqueInstallSubdir(): string {
+ return `factory-local-version-${Date.now()}-${Math.random().toString(36).slice(2)}`;
+}
+
+async function mountVerifiedBinary(
+ installSubdir: string,
+ directoryVersion: string,
+ binaryName: string,
+): Promise<string> {
+ const { app } = await import('electron');
+ const installRoot = path.join(app.getPath('userData'), installSubdir);
+ if (!installRoots.includes(installRoot)) installRoots.push(installRoot);
+ const versionDir = path.join(installRoot, directoryVersion);
+ fs.mkdirSync(versionDir, { recursive: true });
+ const binaryPath = path.join(versionDir, binaryName);
+ fs.writeFileSync(binaryPath, 'local binary');
+ fs.chmodSync(binaryPath, 0o755);
+ fs.writeFileSync(path.join(versionDir, '.verified'), '');
+ return binaryPath;
+}
+
+function makeProvisioner(
+ installSubdir: string,
+ binaryName: string,
+ localVersionResolver: (binaryPath: string) => Promise<string | null>,
+) {
+ return createBinaryProvisioner({
+ vendorKey: 'pi',
+ manifestField: 'pi',
+ installSubdir,
+ optionalAsset: true,
+ artifact: { kind: 'gz', binaryName },
+ localVersionResolver,
+ });
+}
+
+beforeEach(() => {
+ mocks.asset.current = {
+ version: '0.84.3',
+ file: 'pi/0.84.3/darwin-arm64/pi.gz',
+ sha256: FAKE_SHA,
+ size: 3,
+ };
+ mocks.download.mockReset();
+ mocks.download.mockImplementation(async (opts: DownloadOpts) => {
+ fs.mkdirSync(path.dirname(opts.targetPath), { recursive: true });
+ fs.writeFileSync(opts.targetPath, gzipSync(Buffer.from('cdn binary')));
+ return {
+ path: opts.targetPath,
+ size: 3,
+ sha256: FAKE_SHA,
+ fromCache: false,
+ durationMs: 1,
+ resumedFromBytes: 0,
+ };
+ });
+});
+
+afterEach(() => {
+ for (const root of installRoots.splice(0)) {
+ fs.rmSync(root, { recursive: true, force: true });
+ }
+});
+
+describe('local runtime version arbitration', () => {
+ it('preserves an in-place self-update newer than the manifest without download or cleanup', async () => {
+ const installSubdir = uniqueInstallSubdir();
+ const binaryName = 'pi';
+ const selfUpdated = await mountVerifiedBinary(installSubdir, '0.84.3', binaryName);
+ const older = await mountVerifiedBinary(installSubdir, '0.83.0', binaryName);
+ const versions = new Map([
+ [selfUpdated, '0.84.4'],
+ [older, '0.83.0'],
+ ]);
+ const resolveVersion = vi.fn(async (binaryPath: string) => versions.get(binaryPath) ?? null);
+ const provisioner = makeProvisioner(installSubdir, binaryName, resolveVersion);
+
+ await expect(provisioner.peekNeedsDownload()).resolves.toBe(false);
+ expect(resolveVersion).not.toHaveBeenCalled();
+ await expect(provisioner.prepare()).resolves.toEqual({
+ ready: true,
+ binaryPath: selfUpdated,
+ });
+ expect(mocks.download).not.toHaveBeenCalled();
+ expect(resolveVersion).toHaveBeenCalledTimes(2);
+ expect(fs.existsSync(path.dirname(older))).toBe(true);
+ await expect(provisioner.getState()).resolves.toMatchObject({
+ status: 'ready',
+ installedVersion: '0.84.4',
+ availableVersion: '0.84.3',
+ binaryPath: selfUpdated,
+ });
+ });
+
+ it.each([
+ ['the directory-latest candidate is invalid', null, '0.84.4'],
+ ['the older directory reports a higher version', '0.84.4', '0.84.5'],
+ ])(
+ 'selects the highest real version when %s',
+ async (_label, latestReported, olderDirectoryReported) => {
+ const installSubdir = uniqueInstallSubdir();
+ const binaryName = 'pi';
+ const olderDirectory = await mountVerifiedBinary(installSubdir, '0.84.3', binaryName);
+ const latestDirectory = await mountVerifiedBinary(installSubdir, '0.84.4', binaryName);
+ const versions = new Map([
+ [latestDirectory, latestReported],
+ [olderDirectory, olderDirectoryReported],
+ ]);
+ const resolveVersion = vi.fn(
+ async (binaryPath: string) => versions.get(binaryPath) ?? null,
+ );
+
+ const result = await makeProvisioner(
+ installSubdir,
+ binaryName,
+ resolveVersion,
+ ).prepare();
+
+ expect(result).toEqual({ ready: true, binaryPath: olderDirectory });
+ expect(resolveVersion).toHaveBeenCalledTimes(2);
+ expect(mocks.download).not.toHaveBeenCalled();
+ expect(fs.existsSync(path.dirname(olderDirectory))).toBe(true);
+ expect(fs.existsSync(path.dirname(latestDirectory))).toBe(true);
+ },
+ );
+
+ it('selects the highest real local version before an exact manifest-directory match', async () => {
+ const installSubdir = uniqueInstallSubdir();
+ const binaryName = 'pi';
+ const exact = await mountVerifiedBinary(installSubdir, '0.84.3', binaryName);
+ const newer = await mountVerifiedBinary(installSubdir, '0.84.4', binaryName);
+ const versions = new Map([
+ [exact, '0.84.3'],
+ [newer, '0.84.4'],
+ ]);
+
+ const result = await makeProvisioner(
+ installSubdir,
+ binaryName,
+ async (binaryPath) => versions.get(binaryPath) ?? null,
+ ).prepare();
+
+ expect(result).toEqual({ ready: true, binaryPath: newer });
+ expect(mocks.download).not.toHaveBeenCalled();
+ });
+
+ it('keeps an equal real version even when self-update left an older directory name', async () => {
+ mocks.asset.current.version = '0.84.4';
+ const installSubdir = uniqueInstallSubdir();
+ const binaryPath = await mountVerifiedBinary(installSubdir, '0.84.3', 'pi');
+
+ const result = await makeProvisioner(installSubdir, 'pi', async () => '0.84.4').prepare();
+
+ expect(result).toEqual({ ready: true, binaryPath });
+ expect(mocks.download).not.toHaveBeenCalled();
+ });
+
+ it('retains the existing CDN upgrade and cleanup flow when the local version is older', async () => {
+ mocks.asset.current = {
+ ...mocks.asset.current,
+ version: '0.84.5',
+ file: 'pi/0.84.5/darwin-arm64/pi.gz',
+ };
+ const installSubdir = uniqueInstallSubdir();
+ const oldBinary = await mountVerifiedBinary(installSubdir, '0.84.4', 'pi');
+
+ const result = await makeProvisioner(installSubdir, 'pi', async (binaryPath) =>
+ binaryPath === oldBinary ? '0.84.4' : null,
+ ).prepare();
+
+ expect(result.ready).toBe(true);
+ expect(path.basename(path.dirname(result.binaryPath))).toBe('0.84.5');
+ expect(mocks.download).toHaveBeenCalledTimes(1);
+ expect(fs.existsSync(path.dirname(oldBinary))).toBe(false);
+ });
+
+ it.each([
+ ['the probe fails', 'throw'],
+ ['the output is invalid', null],
+ ['the real version is older', '0.84.2'],
+ ])('repairs an exact-manifest directory when %s', async (_label, reported) => {
+ const installSubdir = uniqueInstallSubdir();
+ const exact = await mountVerifiedBinary(installSubdir, '0.84.3', 'pi');
+ const provisioner = makeProvisioner(installSubdir, 'pi', async () => {
+ if (reported === 'throw') throw new Error('probe failed');
+ return reported;
+ });
+
+ await expect(provisioner.peekNeedsDownload()).resolves.toBe(false);
+ await expect(provisioner.prepare()).resolves.toEqual({
+ ready: true,
+ binaryPath: exact,
+ });
+ expect(mocks.download).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/desktop/src/main/agent-binaries/binary-version-probe.ts b/apps/desktop/src/main/agent-binaries/binary-version-probe.ts
new file mode 100644
index 0000000000..c3b8276c18
--- /dev/null
+++ b/apps/desktop/src/main/agent-binaries/binary-version-probe.ts
@@ -0,0 +1,69 @@
+import { execFile } from 'node:child_process';
+import { createRequire } from 'node:module';
+
+interface SemverApi {
+ valid(version: string): string | null;
+ gte(left: string, right: string): boolean;
+}
+
+const semver = createRequire(import.meta.url)('semver') as SemverApi;
+const VERSION_PROBE_TIMEOUT_MS = 5_000;
+const VERSION_PROBE_MAX_BUFFER = 64 * 1024;
+
+/** Normalize a strict runtime semantic version using the installed semver implementation. */
+export function normalizeBinaryVersion(version: string): string | null {
+ return semver.valid(version.trim());
+}
+
+export function isBinaryVersionNotOlder(candidate: string, required: string): boolean {
+ return semver.gte(candidate, required);
+}
+
+/** Parse the supported Pi version forms from the first `--version` output line. */
+export function parseBinaryVersionOutput(stdout: string, stderr: string): string | null {
+ const output = (stdout || stderr).trim();
+ const firstLine = output.split(/\r?\n/, 1)[0]?.trim() ?? '';
+ const tokens = firstLine.split(/\s+/);
+ const versionToken = tokens.length === 1
+ ? tokens[0]
+ : tokens.length === 2 && tokens[0]?.toLowerCase() === 'pi'
+ ? tokens[1]
+ : undefined;
+ return versionToken
+ ? normalizeBinaryVersion(versionToken.replace(/^v(?=\d)/, ''))
+ : null;
+}
+
+/**
+ * Probe a managed executable without letting a broken/local self-update fail the
+ * surrounding CDN prepare. Invalid output, timeout, or spawn errors all return null.
+ */
+export function probeBinaryVersion(
+ binaryPath: string,
+ signal?: AbortSignal,
+): Promise<string | null> {
+ return new Promise((resolve) => {
+ try {
+ execFile(
+ binaryPath,
+ ['--version'],
+ {
+ encoding: 'utf8',
+ maxBuffer: VERSION_PROBE_MAX_BUFFER,
+ timeout: VERSION_PROBE_TIMEOUT_MS,
+ windowsHide: true,
+ signal,
+ },
+ (error, stdout, stderr) => {
+ if (error) {
+ resolve(null);
+ return;
+ }
+ resolve(parseBinaryVersionOutput(stdout, stderr));
+ },
+ );
+ } catch {
+ resolve(null);
+ }
+ });
+}
diff --git a/apps/desktop/src/main/agent-binaries/factory.ts b/apps/desktop/src/main/agent-binaries/factory.ts
index f3eaa90b33..b51fda51f4 100644
--- a/apps/desktop/src/main/agent-binaries/factory.ts
+++ b/apps/desktop/src/main/agent-binaries/factory.ts
@@ -26,6 +26,10 @@ import {
type BinaryProvisionerConfig,
type VendorRuntimeState,
} from './types.js';
+import {
+ isBinaryVersionNotOlder,
+ normalizeBinaryVersion,
+} from './binary-version-probe.js';
import { getVendorAsset, resolveVendorAssetUrl, type VendorAsset } from './manifest.js';
import { download, DownloadError, type ProgressEvent } from '../downloader/index.js';
import {
@@ -55,6 +59,39 @@ function getVerifiedMarker(installSubdir: string, version: string): string {
return path.join(getVersionDir(installSubdir, version), '.verified');
}
+interface VerifiedBinaryCandidate {
+ directoryVersion: string;
+ binaryPath: string;
+}
+
+/** List executable installs carrying the provisioner's completed-download marker. */
+function listVerifiedBinaries(
+ installSubdir: string,
+ binaryName: string,
+): VerifiedBinaryCandidate[] {
+ try {
+ const root = getInstallRoot(installSubdir);
+ return fs
+ .readdirSync(root, { withFileTypes: true })
+ .filter((entry) => entry.isDirectory())
+ .map((entry) => ({
+ directoryVersion: entry.name,
+ binaryPath: getFinalBinPath(installSubdir, entry.name, binaryName),
+ }))
+ .filter((candidate) => {
+ try {
+ fs.accessSync(getVerifiedMarker(installSubdir, candidate.directoryVersion));
+ fs.accessSync(candidate.binaryPath, fs.constants.X_OK);
+ return true;
+ } catch {
+ return false;
+ }
+ });
+ } catch {
+ return [];
+ }
+}
+
/**
* Find the latest locally installed and verified version.
* Scans the install root for directories containing a .verified marker file,
@@ -90,6 +127,44 @@ function findLatestVerifiedBinary(
return null;
}
+/**
+ * Choose the highest real local semver that is not older than the manifest.
+ * A resolver failure is deliberately ignored so this additive check can never
+ * turn the existing exact-manifest path into a startup failure.
+ */
+async function findPreferredLocalBinary(
+ installSubdir: string,
+ binaryName: string,
+ manifestVersion: string,
+ resolveVersion:
+ ((binaryPath: string, signal?: AbortSignal) => Promise<string | null>) | undefined,
+ signal?: AbortSignal,
+): Promise<{ version: string; binaryPath: string } | null> {
+ const requiredVersion = normalizeBinaryVersion(manifestVersion);
+ if (!resolveVersion || !requiredVersion) return null;
+
+ // Probe all completed installs concurrently so one broken candidate cannot hide
+ // a self-updated runtime or multiply the bounded probe delay.
+ const resolved = await Promise.all(
+ listVerifiedBinaries(installSubdir, binaryName).map(async (candidate) => {
+ try {
+ const reported = await resolveVersion(candidate.binaryPath, signal);
+ const version = reported ? normalizeBinaryVersion(reported) : null;
+ return version ? { version, binaryPath: candidate.binaryPath } : null;
+ } catch {
+ return null;
+ }
+ }),
+ );
+ return resolved.reduce<{ version: string; binaryPath: string } | null>((preferred, candidate) => {
+ if (!candidate || !isBinaryVersionNotOlder(candidate.version, requiredVersion))
+ return preferred;
+ return !preferred || isBinaryVersionNotOlder(candidate.version, preferred.version)
+ ? candidate
+ : preferred;
+ }, null);
+}
+
function isInstalled(installSubdir: string, version: string, binaryName: string): boolean {
try {
fs.accessSync(getFinalBinPath(installSubdir, version, binaryName), fs.constants.X_OK);
@@ -158,6 +233,35 @@ async function extractTarGzDir(srcTarGz: string, destDir: string, binaryName: st
export function createBinaryProvisioner(config: BinaryProvisionerConfig): BinaryProvisioner {
let state: VendorRuntimeState = { status: 'not_installed' };
+ const localVersionCache = new Map<string, { mtimeMs: number; size: number; version: string }>();
+
+ async function resolveLocalVersion(
+ binaryPath: string,
+ signal?: AbortSignal,
+ ): Promise<string | null> {
+ if (!config.localVersionResolver) return null;
+ let identity: { mtimeMs: number; size: number };
+ try {
+ const stat = fs.statSync(binaryPath);
+ identity = { mtimeMs: stat.mtimeMs, size: stat.size };
+ } catch {
+ return null;
+ }
+ const cached = localVersionCache.get(binaryPath);
+ if (cached && cached.mtimeMs === identity.mtimeMs && cached.size === identity.size) {
+ return cached.version;
+ }
+ let version: string | null = null;
+ try {
+ version = await config.localVersionResolver(binaryPath, signal);
+ } catch {
+ // Probe failures are handled as repair-needed by the manifest flow below.
+ }
+ if (version !== null) {
+ localVersionCache.set(binaryPath, { ...identity, version });
+ }
+ return version;
+ }
function emit(patch: Partial<VendorRuntimeState>, onProgress?: (p: VendorRuntimeState) => void): void {
state = { ...state, ...patch };
@@ -229,9 +333,30 @@ export function createBinaryProvisioner(config: BinaryProvisionerConfig): Binary
}
emit({ availableVersion: asset.version }, onProgress);
- // 3. 已安装命中
+ // 3. 本地真实版本不低于 manifest:保留用户自更新结果,禁止降级与旧版清理。
+ const preferredLocal = await findPreferredLocalBinary(
+ config.installSubdir,
+ binaryName,
+ asset.version,
+ config.localVersionResolver ? resolveLocalVersion : undefined,
+ opts?.signal,
+ );
+ if (preferredLocal) {
+ emit({
+ status: 'ready',
+ installedVersion: preferredLocal.version,
+ binaryPath: preferredLocal.binaryPath,
+ }, onProgress);
+ return { ready: true, binaryPath: preferredLocal.binaryPath };
+ }
+
+ // 3.1 未启用真实版本仲裁的 runtime 保持原有 manifest 精确命中流程。
+ // 启用仲裁时,探针失败/无效/较旧必须继续下载,以修复残留的 .verified 安装。
const finalBinPath = getFinalBinPath(config.installSubdir, asset.version, binaryName);
- if (isInstalled(config.installSubdir, asset.version, binaryName)) {
+ if (
+ !config.localVersionResolver &&
+ isInstalled(config.installSubdir, asset.version, binaryName)
+ ) {
emit({
status: 'ready',
installedVersion: asset.version,
diff --git a/apps/desktop/src/main/agent-binaries/index.ts b/apps/desktop/src/main/agent-binaries/index.ts
index 2767ab0ccc..a07292bf8f 100644
--- a/apps/desktop/src/main/agent-binaries/index.ts
+++ b/apps/desktop/src/main/agent-binaries/index.ts
@@ -31,6 +31,7 @@ import fs from 'node:fs';
import { app, BrowserWindow } from 'electron';
import { createBinaryProvisioner } from './factory.js';
+import { probeBinaryVersion } from './binary-version-probe.js';
import { findDevBinary } from './dev-fallback.js';
import {
findCachedLinuxRuntimeFallbackBinary,
@@ -173,6 +174,7 @@ interface AgentBinaryConfig {
vendorTag: VendorKey; // 'binary-download-progress' IPC payload 的 vendor 字段
artifactKind: 'gz' | 'tar-gz-dir'; // CDN 资产形态(单文件 gz / 整目录 tar.gz)
optionalAsset?: boolean; // true = manifest 缺字段不算"需要下载"(可选 vendor)
+ preserveLocalVersion?: boolean; // true = 本地真实版本 >= manifest 时保留,禁止降级
}
const CONFIG: Record<AgentBinaryKind, AgentBinaryConfig> = {
@@ -203,6 +205,7 @@ const CONFIG: Record<AgentBinaryKind, AgentBinaryConfig> = {
vendorTag: 'pi',
artifactKind: 'tar-gz-dir',
optionalAsset: true,
+ preserveLocalVersion: true,
},
};
@@ -220,6 +223,7 @@ function getBase(kind: AgentBinaryKind): BinaryProvisioner {
installSubdir: cfg.installSubdir,
artifact: { kind: cfg.artifactKind, binaryName: cfg.binaryName },
optionalAsset: cfg.optionalAsset,
+ localVersionResolver: cfg.preserveLocalVersion ? probeBinaryVersion : undefined,
});
baseProvisioners.set(kind, base);
}
diff --git a/apps/desktop/src/main/agent-binaries/types.ts b/apps/desktop/src/main/agent-binaries/types.ts
index bdd7704205..74d4886dd4 100644
--- a/apps/desktop/src/main/agent-binaries/types.ts
+++ b/apps/desktop/src/main/agent-binaries/types.ts
@@ -34,6 +34,12 @@ export interface BinaryProvisionerConfig {
* 走 prepare 的完整错误流程)。
*/
optionalAsset?: boolean;
+ /**
+ * 可选的本地真实版本探针。配置后,prepare/peek 会优先选择 `.verified` 安装中
+ * 实际 semver 不低于 manifest 的最高版本,避免宿主升级时把用户已自更新的
+ * runtime 降级。探针失败只表示候选不可用于仲裁,原 manifest 流程照常继续。
+ */
+ localVersionResolver?: (binaryPath: string, signal?: AbortSignal) => Promise<string | null>;
}
// ===== §5.2 VendorRuntimeState =====
diff --git a/apps/desktop/src/main/maker-host/__tests__/piBinaryDistribution.test.ts b/apps/desktop/src/main/maker-host/__tests__/piBinaryDistribution.test.ts
index 7c880bd385..8f76cc02c7 100644
--- a/apps/desktop/src/main/maker-host/__tests__/piBinaryDistribution.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/piBinaryDistribution.test.ts
@@ -43,6 +43,16 @@ describe('Pi binary distribution contract', () => {
expect(binaries).toContain('signal: opts.signal');
});
+ it('preserves a locally self-updated Pi when its real version is not below the manifest', () => {
+ const binaries = fs.readFileSync(
+ path.join(desktopRoot, 'src/main/agent-binaries/index.ts'),
+ 'utf8',
+ );
+
+ expect(binaries).toContain('preserveLocalVersion: true');
+ expect(binaries).toContain('localVersionResolver: cfg.preserveLocalVersion');
+ });
+
it('does not expose an old Pi cache through the binary-version IPC', () => {
const binaryVersion = fs.readFileSync(
path.join(desktopRoot, 'src/main/maker-ipc/binary-version.ts'),
diff --git a/docs/dev-rules/pi-harness.md b/docs/dev-rules/pi-harness.md
index 1d7eda1622..de1949cd19 100644
--- a/docs/dev-rules/pi-harness.md
+++ b/docs/dev-rules/pi-harness.md
@@ -187,7 +187,10 @@ Claude Code 仍用独立百分比。env:`CINDY_PI_API_KEY`、
最终启动 smoke 仍由对应发布 runner 执行。2026-08 起 pi 与 cc/codex 一样只走
CDN 运行时分发链(`agent-binaries` + splash prepare):CDN manifest 的可选 `pi`
字段指向整包 tar.gz(归档根即完整目录分发,SHA256 为 tar.gz 的),启动时按
- manifest 版本下载到 `userData/pi/<version>/` 并清旧版。正式安装包不内置 Pi;
+ manifest 版本下载到 `userData/pi/<version>/` 并清理更旧版本;prepare 会先对所有带
+ `.verified` 的本地候选执行有界 `--version` 探针,真实 semver 不低于 manifest 时直接
+ 保留该安装(包括原地自更新后目录名仍旧的情况),不下载也不清理。只有 manifest
+ 版本更高,或探针没有得到可用候选时,才沿用原 CDN 安装流程。正式安装包不内置 Pi;
manifest 缺字段或下载失败时**不阻塞启动**(splash 不进失败态),本次不注册 pi。
**不变量(刻意如此,别当 bug 改掉)**:`pi-host.resolvePiBinaryPath` 只读
`getReadyBinaryPath('pi')`——即本次启动 prepare 成功回填的路径,**不回落