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。

feat(desktop): 在关于页提供 Harness 更新入口 (#4928)

Lizi71e2a5b059d3
diff --git a/apps/desktop/src/main/__tests__/updateService.test.ts b/apps/desktop/src/main/__tests__/updateService.test.ts
index 838f4d377a..5b7dc5c705 100644
--- a/apps/desktop/src/main/__tests__/updateService.test.ts
+++ b/apps/desktop/src/main/__tests__/updateService.test.ts
@@ -336,6 +336,37 @@ describe('binary version checks after an applied update', () => {
});
});
+ it('schedules a one-time refresh of only the confirmed harness before a graceful relaunch', async () => {
+ const service = await freshUpdateService('darwin');
+ const { consumeStartupBinaryUpdateMarker } = await import('../agent-binaries/startup-update');
+ service.initUpdateService();
+ try {
+ const relaunch = ipcHandlers.get('update-harness-relaunch');
+ expect(relaunch).toBeTypeOf('function');
+ expect(relaunch?.({ sender: { id: 1 } }, 'codex')).toEqual({ accepted: true });
+ expect(appRelaunch).toHaveBeenCalledWith({ args: process.argv.slice(1) });
+ expect(appQuit).toHaveBeenCalled();
+ expect(consumeStartupBinaryUpdateMarker(TEST_USER_DATA, appGetVersion())).toEqual(['codex']);
+ } finally {
+ service.stopUpdateService();
+ }
+ });
+
+ it.each([undefined, 'pi', 'gemini'])('rejects a harness relaunch for %s without restarting', async (kind) => {
+ const service = await freshUpdateService('darwin');
+ const { consumeStartupBinaryUpdateMarker } = await import('../agent-binaries/startup-update');
+ service.initUpdateService();
+ try {
+ const relaunch = ipcHandlers.get('update-harness-relaunch');
+ expect(() => relaunch?.({ sender: { id: 1 } }, kind)).toThrow();
+ expect(appRelaunch).not.toHaveBeenCalled();
+ expect(appQuit).not.toHaveBeenCalled();
+ expect(consumeStartupBinaryUpdateMarker(TEST_USER_DATA, appGetVersion())).toBe(false);
+ } finally {
+ service.stopUpdateService();
+ }
+ });
+
it('writes the target-version marker only when the update is actually applied', async () => {
const service = await freshUpdateService('darwin');
const { consumeStartupBinaryUpdateMarker } = await import('../agent-binaries/startup-update');
diff --git a/apps/desktop/src/main/agent-binaries/__tests__/startup-policy.test.ts b/apps/desktop/src/main/agent-binaries/__tests__/startup-policy.test.ts
index d6fab70867..2d18c28c6e 100644
--- a/apps/desktop/src/main/agent-binaries/__tests__/startup-policy.test.ts
+++ b/apps/desktop/src/main/agent-binaries/__tests__/startup-policy.test.ts
@@ -154,6 +154,16 @@ describe('shared startup policy through the real binary preparation chain', () =
expect(mocks.download).toHaveBeenCalledTimes(2);
});
+ it('limits a harness-scoped marker to the confirmed harness', async () => {
+ writeStartupBinaryUpdateMarker(mocks.userDataDir, '2.0.0', ['codex']);
+ installManaged('claude-code');
+ installManaged('codex');
+ await expect(binaries.peekNeedsDownload('claude-code')).resolves.toBe(false);
+ await expect(binaries.peekNeedsDownload('codex')).resolves.toBe(true);
+ await expect(binaries.prepare('claude-code', quiet)).resolves.toMatchObject({ ready: true });
+ expect(mocks.download).not.toHaveBeenCalled();
+ });
+
it.each([false, true])('Pi background recovery inherits checkForUpdates=%s without caller flags', async (allowUpdates) => {
if (allowUpdates) writeStartupBinaryUpdateMarker(mocks.userDataDir, '2.0.0');
const localPath = installManaged('pi');
diff --git a/apps/desktop/src/main/agent-binaries/__tests__/startup-update.test.ts b/apps/desktop/src/main/agent-binaries/__tests__/startup-update.test.ts
index 249633b64f..f026fdbe05 100644
--- a/apps/desktop/src/main/agent-binaries/__tests__/startup-update.test.ts
+++ b/apps/desktop/src/main/agent-binaries/__tests__/startup-update.test.ts
@@ -44,6 +44,21 @@ describe('one-time startup binary update marker', () => {
expect(fs.existsSync(markerPath)).toBe(false);
});
+ it('keeps a harness-scoped marker limited to the confirmed harness', () => {
+ writeStartupBinaryUpdateMarker(userDataDir, '2.0.0', ['codex']);
+ expect(consumeStartupBinaryUpdateMarker(userDataDir, '2.0.0')).toEqual(['codex']);
+ expect(fs.existsSync(markerPath)).toBe(false);
+ });
+
+ it.each(['{"version":"2.0.0","kinds":[]}', '{"version":"2.0.0","kinds":"codex"}', '{"version":"2.0.0","kinds":["gemini"]}'])(
+ 'does not widen an unreadable scoped marker %s into a full refresh',
+ (contents) => {
+ fs.writeFileSync(markerPath, contents);
+ expect(consumeStartupBinaryUpdateMarker(userDataDir, '2.0.0')).toBe(false);
+ expect(fs.existsSync(markerPath)).toBe(false);
+ },
+ );
+
it('cleans up a cancelled apply and tolerates repeated cleanup', () => {
const cancel = writeStartupBinaryUpdateMarker(userDataDir, '2.0.0');
expect(cancel).toBeTypeOf('function');
diff --git a/apps/desktop/src/main/agent-binaries/index.ts b/apps/desktop/src/main/agent-binaries/index.ts
index 1fb01dfbbc..73d7446e0c 100644
--- a/apps/desktop/src/main/agent-binaries/index.ts
+++ b/apps/desktop/src/main/agent-binaries/index.ts
@@ -48,14 +48,15 @@ import {
} from '../manifestService.js';
import { ProgressNormalizer } from '../updateProgressNormalizer.js';
import { createLogger } from '../logger.js';
-import { consumeStartupBinaryUpdateMarker } from './startup-update.js';
+import { consumeStartupBinaryUpdateMarker, type StartupBinaryUpdateScope } from './startup-update.js';
-let startupCheckForUpdates: boolean | undefined;
+let startupUpdateScope: StartupBinaryUpdateScope | undefined;
-function resolveUpdateCheck(checkForUpdates?: boolean): boolean {
- startupCheckForUpdates ??= app.isPackaged
+function resolveUpdateCheck(kind: AgentBinaryKind, checkForUpdates?: boolean): boolean {
+ startupUpdateScope ??= app.isPackaged
&& consumeStartupBinaryUpdateMarker(app.getPath('userData'), app.getVersion());
- return checkForUpdates ?? startupCheckForUpdates;
+ if (checkForUpdates !== undefined) return checkForUpdates;
+ return startupUpdateScope === true || (Array.isArray(startupUpdateScope) && startupUpdateScope.includes(kind));
}
/**
@@ -390,7 +391,7 @@ export async function prepare(
return { ready: false, error: `${kind} dev binary not found for ${getPlatformKey()}`, downloaded: false };
}
- opts = { ...opts, checkForUpdates: resolveUpdateCheck(opts.checkForUpdates) };
+ opts = { ...opts, checkForUpdates: resolveUpdateCheck(kind, opts.checkForUpdates) };
// ── packaged Linux: CDN manifest 段优先,失败静默回落 runtime fallback ─────
// 2026-08 起 Linux 与 mac/win 同链:scripts 侧发版把 claude/codex 资产上传
@@ -672,7 +673,7 @@ export async function peekNeedsDownload(
): Promise<boolean> {
// dev 模式永不下载 (findDevBinary 命中 / 缺失都不走 OSS)
if (!app.isPackaged) return false;
- opts = { ...opts, checkForUpdates: resolveUpdateCheck(opts.checkForUpdates) };
+ opts = { ...opts, checkForUpdates: resolveUpdateCheck(kind, opts.checkForUpdates) };
// Linux(cc/codex):manifest 有段 → 走通用 CDN peek(与 mac/win 同口径);
// 无段(旧 canary / 首发渠道)→ 只看私有 fallback 是否已就位(fs 快查)。
// peek 时 manifest 未缓存则做一次跨 vendor 的短超时探测(3s,single-flight +
diff --git a/apps/desktop/src/main/agent-binaries/manifest.ts b/apps/desktop/src/main/agent-binaries/manifest.ts
index 0f501249bc..e3d80a16e5 100644
--- a/apps/desktop/src/main/agent-binaries/manifest.ts
+++ b/apps/desktop/src/main/agent-binaries/manifest.ts
@@ -62,6 +62,17 @@ export function getVendorAsset(manifest: Manifest, manifestField: string): Vendo
};
}
+const ASSET_PLATFORM_IN_PATH = /\/(linux-x64|linux-arm64|darwin-arm64|darwin-x64|win32-x64|win32-arm64)\//;
+
+/**
+ * True when the asset is not pinned to a different platform.
+ * Older manifests omit the platform segment and stay installable.
+ */
+export function vendorAssetMatchesPlatform(asset: VendorAsset, platformKey: string): boolean {
+ const assetPlatform = asset.file.match(ASSET_PLATFORM_IN_PATH)?.[1];
+ return !assetPlatform || assetPlatform === platformKey;
+}
+
/**
* 拼接完整下载 URL。
* 等价于现有 `${getBaseUrl()}/${asset.file}` 写法。
diff --git a/apps/desktop/src/main/agent-binaries/startup-update.ts b/apps/desktop/src/main/agent-binaries/startup-update.ts
index 4a3217b00a..32808e4f55 100644
--- a/apps/desktop/src/main/agent-binaries/startup-update.ts
+++ b/apps/desktop/src/main/agent-binaries/startup-update.ts
@@ -2,16 +2,25 @@ import fs from 'node:fs';
import path from 'node:path';
import { randomUUID } from 'node:crypto';
import { createLogger } from '../logger';
+import type { AgentBinaryKind } from './index.js';
const log = createLogger('agent-binaries/startup-update');
const MARKER_FILE = 'agent-binary-update-once.json';
+const MARKER_KINDS: readonly AgentBinaryKind[] = ['claude-code', 'codex', 'pi'];
+
+/**
+ * Which managed binaries the next startup may refresh: `true` = all (app update),
+ * a list = only the harnesses the user confirmed, `false` = ordinary startup.
+ */
+export type StartupBinaryUpdateScope = boolean | readonly AgentBinaryKind[];
export function writeStartupBinaryUpdateMarker(
userDataDir: string,
version: string,
+ kinds?: readonly AgentBinaryKind[],
): (() => void) | undefined {
const markerPath = path.join(userDataDir, MARKER_FILE);
- const contents = JSON.stringify({ version, token: randomUUID() });
+ const contents = JSON.stringify(kinds ? { version, kinds, token: randomUUID() } : { version, token: randomUUID() });
try {
fs.mkdirSync(userDataDir, { recursive: true });
fs.writeFileSync(markerPath, contents, { mode: 0o600 });
@@ -30,13 +39,18 @@ export function writeStartupBinaryUpdateMarker(
};
}
-export function consumeStartupBinaryUpdateMarker(userDataDir: string, version: string): boolean {
+export function consumeStartupBinaryUpdateMarker(userDataDir: string, version: string): StartupBinaryUpdateScope {
const markerPath = path.join(userDataDir, MARKER_FILE);
try {
const contents = fs.readFileSync(markerPath, 'utf8');
fs.unlinkSync(markerPath);
const marker: unknown = JSON.parse(contents);
- return !!marker && typeof marker === 'object' && 'version' in marker && marker.version === version;
+ if (!marker || typeof marker !== 'object' || !('version' in marker) || marker.version !== version) return false;
+ if (!('kinds' in marker)) return true;
+ // A scoped marker that cannot be read back must not widen into a full refresh.
+ const { kinds } = marker;
+ if (!Array.isArray(kinds) || kinds.length === 0) return false;
+ return kinds.every((kind) => MARKER_KINDS.includes(kind)) ? (kinds as AgentBinaryKind[]) : false;
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
log.warn('Could not consume the startup binary update check');
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/binaryVersionIpc.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/binaryVersionIpc.test.ts
new file mode 100644
index 0000000000..6822a6e95a
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/binaryVersionIpc.test.ts
@@ -0,0 +1,229 @@
+/**
+ * `maker:agent:binary-version` — About 页的本地版本与线上更新判断。
+ *
+ * 普通调用不能等网络(离线时关于页要立刻显示本地版本);checkLatest 只在线上
+ * 版本严格更高时报告可更新,与启动安装「保留不旧于 manifest 的本地版本」同口径。
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const h = vi.hoisted(() => ({
+ handlers: new Map<string, (...args: unknown[]) => unknown>(),
+ fetchManifest: vi.fn(),
+ execFile: vi.fn(),
+ versions: new Map<string, string>(),
+ trust: vi.fn(),
+ isDeviceLink: vi.fn(() => false),
+}));
+
+vi.mock('electron', () => ({
+ ipcMain: {
+ handle: vi.fn((channel: string, handler: (...args: unknown[]) => unknown) => {
+ h.handlers.set(channel, handler);
+ }),
+ },
+}));
+vi.mock('node:child_process', () => ({ execFile: h.execFile }));
+vi.mock('../../logger.js', () => ({
+ createLogger: () => ({ warn: vi.fn(), error: vi.fn(), info: vi.fn(), debug: vi.fn() }),
+}));
+vi.mock('../pi-kernel.js', () => ({ registerPiKernelIpc: vi.fn() }));
+vi.mock('../../security/trustedAppRenderer.js', () => ({
+ assertTrustedAppRendererEvent: (event: unknown) => h.trust(event),
+}));
+vi.mock('../../device-link/invoke-context.js', () => ({
+ isDeviceLinkInvoke: () => h.isDeviceLink(),
+}));
+vi.mock('../../manifestService.js', () => ({
+ fetchManifest: h.fetchManifest,
+ getPlatformKey: () => 'darwin-arm64',
+}));
+vi.mock('../../agent-binaries/index.js', () => ({
+ getReadyBinaryPath: (kind: string) => `/managed/${kind}`,
+ getCachedBinaryStatus: () => ({ binaryReady: false, binaryPath: null }),
+ isVettedAgentBinaryPath: () => true,
+}));
+
+const { registerMakerBinaryVersionIpc } = await import('../binary-version.js');
+const { MAKER_INVOKE } = await import('../channels.js');
+
+function installable(version: string, file = `runtime/${version}/pkg`) {
+ return { version, file, sha256: 'a'.repeat(64), size: 7 };
+}
+
+function invoke(kind: unknown, options?: unknown) {
+ const handler = h.handlers.get(MAKER_INVOKE.AGENT_BINARY_VERSION);
+ if (!handler) throw new Error('handler not registered');
+ return handler({}, kind, options) as Promise<{
+ version: string | null;
+ latestVersion: string | null;
+ updateAvailable: boolean;
+ }>;
+}
+
+describe('maker:agent:binary-version', () => {
+ beforeEach(() => {
+ h.handlers.clear();
+ h.fetchManifest.mockReset();
+ h.versions.clear();
+ h.trust.mockReset().mockImplementation(() => {});
+ h.isDeviceLink.mockReset().mockReturnValue(false);
+ h.execFile.mockReset().mockImplementation((
+ binaryPath: string,
+ _args: string[],
+ _options: unknown,
+ callback: (error: Error | null, stdout: string, stderr: string) => void,
+ ) => {
+ callback(null, h.versions.get(binaryPath) ?? '', '');
+ });
+ registerMakerBinaryVersionIpc();
+ });
+
+
+ it('rejects an untrusted renderer before probing or fetching the manifest', async () => {
+ h.trust.mockImplementation(() => {
+ throw new Error('PERMISSION_DENIED');
+ });
+ h.versions.set('/managed/codex', 'codex-cli 0.145.0');
+ h.fetchManifest.mockReturnValue(new Promise(() => {}));
+
+ await expect(invoke('codex', { checkLatest: true })).rejects.toThrow('PERMISSION_DENIED');
+ expect(h.execFile).not.toHaveBeenCalled();
+ expect(h.fetchManifest).not.toHaveBeenCalled();
+ });
+
+ it('still serves a device-link invoke that has no renderer sender', async () => {
+ h.isDeviceLink.mockReturnValue(true);
+ h.trust.mockImplementation(() => {
+ throw new Error('PERMISSION_DENIED');
+ });
+ h.versions.set('/managed/codex', 'codex-cli 0.145.0');
+
+ await expect(invoke('codex')).resolves.toMatchObject({ version: 'codex-cli 0.145.0' });
+ expect(h.trust).not.toHaveBeenCalled();
+ });
+
+ it('returns the local version without touching the network', async () => {
+ h.versions.set('/managed/claude-code', '2.1.258 (Claude Code)');
+ h.fetchManifest.mockReturnValue(new Promise(() => {}));
+
+ await expect(invoke('claude-code')).resolves.toMatchObject({
+ version: '2.1.258 (Claude Code)',
+ latestVersion: null,
+ updateAvailable: false,
+ });
+ expect(h.fetchManifest).not.toHaveBeenCalled();
+ });
+
+ it('reports an update only when the channel version is strictly newer', async () => {
+ h.versions.set('/managed/codex', 'codex-cli 0.145.0');
+ h.fetchManifest.mockResolvedValue({ codexPackage: installable('0.146.0') });
+ await expect(invoke('codex', { checkLatest: true })).resolves.toMatchObject({
+ latestVersion: '0.146.0',
+ updateAvailable: true,
+ });
+ });
+
+ it('does not offer an update from a legacy codex manifest field the installer cannot consume', async () => {
+ h.versions.set('/managed/codex', 'codex-cli 0.145.0');
+ h.fetchManifest.mockResolvedValue({ codex: { version: '0.146.0' } });
+ await expect(invoke('codex', { checkLatest: true })).resolves.toMatchObject({
+ latestVersion: null,
+ updateAvailable: false,
+ });
+ });
+
+ it.each(['0.145.0', '0.144.9'])('does not offer a no-op update when the channel has %s', async (latest) => {
+ h.versions.set('/managed/codex', 'codex-cli 0.145.0');
+ h.fetchManifest.mockResolvedValue({ codexPackage: installable(latest) });
+ await expect(invoke('codex', { checkLatest: true })).resolves.toMatchObject({
+ latestVersion: latest,
+ updateAvailable: false,
+ });
+ });
+
+ it('never offers the About update for Pi, which has its own kernel manager', async () => {
+ h.versions.set('/managed/pi', 'pi 0.84.4');
+ h.fetchManifest.mockResolvedValue({ pi: installable('0.90.0') });
+ await expect(invoke('pi', { checkLatest: true })).resolves.toMatchObject({ updateAvailable: false });
+ });
+
+ it('keeps the local version when the manifest is unreachable', async () => {
+ h.versions.set('/managed/claude-code', '2.1.258 (Claude Code)');
+ h.fetchManifest.mockRejectedValue(new Error('offline'));
+ await expect(invoke('claude-code', { checkLatest: true })).resolves.toMatchObject({
+ version: '2.1.258 (Claude Code)',
+ latestVersion: null,
+ updateAvailable: false,
+ });
+ });
+
+
+ it('re-probes on checkLatest instead of comparing a cached --version', async () => {
+ h.versions.set('/managed/codex', 'codex-cli 0.145.0');
+ h.fetchManifest.mockResolvedValue({ codexPackage: installable('0.146.0') });
+ await expect(invoke('codex', { checkLatest: true })).resolves.toMatchObject({
+ version: 'codex-cli 0.145.0',
+ updateAvailable: true,
+ });
+
+ h.versions.set('/managed/codex', 'codex-cli 0.146.0');
+ await expect(invoke('codex')).resolves.toMatchObject({ version: 'codex-cli 0.145.0' });
+ await expect(invoke('codex', { checkLatest: true })).resolves.toMatchObject({
+ version: 'codex-cli 0.146.0',
+ latestVersion: '0.146.0',
+ updateAvailable: false,
+ });
+ });
+
+ it('does not advertise an update the installer would reject', async () => {
+ h.versions.set('/managed/codex', 'codex-cli 0.145.0');
+ h.fetchManifest.mockResolvedValue({
+ codexPackage: { version: '0.146.0', file: 'runtime/0.146.0/pkg' },
+ });
+ await expect(invoke('codex', { checkLatest: true })).resolves.toMatchObject({
+ latestVersion: null,
+ updateAvailable: false,
+ });
+
+ h.fetchManifest.mockResolvedValue({
+ codexPackage: installable('0.146.0', 'codex/win32-x64/0.146.0/pkg'),
+ });
+ await expect(invoke('codex', { checkLatest: true })).resolves.toMatchObject({
+ latestVersion: null,
+ updateAvailable: false,
+ });
+ });
+
+
+ it('does not advertise an update whose sha256 the downloader would reject', async () => {
+ h.versions.set('/managed/codex', 'codex-cli 0.145.0');
+ for (const sha256 of ['', 'not-hex', 'abcd', 'g'.repeat(64), 'a'.repeat(63), 'a'.repeat(65)]) {
+ const asset = installable('0.146.0');
+ asset.sha256 = sha256;
+ h.fetchManifest.mockResolvedValue({ codexPackage: asset });
+ await expect(invoke('codex', { checkLatest: true })).resolves.toMatchObject({
+ latestVersion: null,
+ updateAvailable: false,
+ });
+ }
+ });
+
+
+ it('does not advertise an update whose size the downloader would reject', async () => {
+ h.versions.set('/managed/codex', 'codex-cli 0.145.0');
+ for (const size of [0, -1, Number.NaN, Number.POSITIVE_INFINITY]) {
+ const asset = installable('0.146.0');
+ asset.size = size;
+ h.fetchManifest.mockResolvedValue({ codexPackage: asset });
+ await expect(invoke('codex', { checkLatest: true })).resolves.toMatchObject({
+ latestVersion: null,
+ updateAvailable: false,
+ });
+ }
+ });
+
+ it('rejects malformed options', async () => {
+ await expect(invoke('codex', { checkLatest: 'yes' })).rejects.toThrow();
+ await expect(invoke('codex', 'checkLatest')).rejects.toThrow();
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/binary-version.ts b/apps/desktop/src/main/maker-ipc/binary-version.ts
index bec7ac8cb9..64f8f1983c 100644
--- a/apps/desktop/src/main/maker-ipc/binary-version.ts
+++ b/apps/desktop/src/main/maker-ipc/binary-version.ts
@@ -9,6 +9,7 @@
* Pi 是可选资产,只允许使用本次 prepare 成功的路径,失败时不能复用旧缓存。
* - Claude/Codex 按 binaryPath 缓存结果;Pi 现读,以反映受管/原生更新。
* - 5s 超时, 失败时返回 { error }。
+ * - checkLatest 时再比较当前通道 manifest;普通调用不等网络。
*/
import { registerPiKernelIpc } from './pi-kernel.js';
@@ -23,6 +24,15 @@ import {
type AgentBinaryKind,
} from '../agent-binaries/index.js';
import { throwIpcError } from '../utils/ipcValidate.js';
+import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';
+import { isDeviceLinkInvoke } from '../device-link/invoke-context.js';
+import {
+ isBinaryVersionNotOlder,
+ normalizeBinaryVersion,
+ parseBinaryVersionOutput,
+} from '../agent-binaries/binary-version-probe.js';
+import { getVendorAsset, vendorAssetMatchesPlatform } from '../agent-binaries/manifest.js';
+import { fetchManifest, getPlatformKey, type Manifest } from '../manifestService.js';
import { MAKER_INVOKE } from './channels.js';
@@ -32,11 +42,110 @@ export interface AgentBinaryVersionResult {
kind: AgentBinaryKind;
binaryPath: string | null;
version: string | null;
+ /** Latest version on the active update channel; only filled for `checkLatest`. */
+ latestVersion: string | null;
+ /** The channel version is strictly newer than the local one (Claude/Codex only). */
+ updateAvailable: boolean;
error?: string;
}
+interface AgentBinaryVersionOptions {
+ checkLatest?: boolean;
+}
+
const versionCache = new Map<string, string>();
+// About renders one request per managed agent. Share only the in-flight manifest
+// lookup so opening the page does not issue identical requests, while a later
+// About visit (or a channel switch) always gets a fresh online comparison.
+let latestManifestPromise: Promise<Manifest | null> | null = null;
+
+function getLatestManifest(): Promise<Manifest | null> {
+ if (latestManifestPromise) return latestManifestPromise;
+ const request = fetchManifest(8_000).catch(() => null);
+ latestManifestPromise = request;
+ void request.then(
+ () => {
+ if (latestManifestPromise === request) latestManifestPromise = null;
+ },
+ () => {
+ if (latestManifestPromise === request) latestManifestPromise = null;
+ },
+ );
+ return latestManifestPromise;
+}
+
+// Same fields as agent-binaries CONFIG. Only an asset the installer can
+// actually consume (complete metadata, this platform) may advertise an update.
+const MANIFEST_FIELD: Record<AgentBinaryKind, string> = {
+ 'claude-code': 'claudeCode',
+ codex: 'codexPackage',
+ pi: 'pi',
+};
+
+// downloader/index.ts rejects anything that is not exactly 64 hex chars.
+const DOWNLOAD_SHA256 = /^[0-9a-fA-F]{64}$/;
+
+function latestVersionFor(kind: AgentBinaryKind, manifest: Manifest | null): string | null {
+ if (!manifest) return null;
+ const asset = getVendorAsset(manifest, MANIFEST_FIELD[kind]);
+ if (!asset || !vendorAssetMatchesPlatform(asset, getPlatformKey())) return null;
+ // download() rejects a non-hex sha256; a non-positive expectedSize makes a
+ // normal Content-Length fail the transport check and keep the old runtime.
+ if (!DOWNLOAD_SHA256.test(asset.sha256)) return null;
+ if (!Number.isFinite(asset.size) || asset.size <= 0) return null;
+ return asset.version;
+}
+
+// Same ordering the startup installer uses to keep a local runtime that is not
+// older than the manifest, so the About action never offers a no-op relaunch.
+function isUpdateAvailable(kind: AgentBinaryKind, version: string | null, latestVersion: string | null): boolean {
+ if (kind === 'pi' || !version || !latestVersion) return false;
+ const current = parseBinaryVersionOutput(version, '');
+ const latest = normalizeBinaryVersion(latestVersion);
+ return !!current && !!latest && !isBinaryVersionNotOlder(current, latest);
+}
+
+function parseOptions(value: unknown): AgentBinaryVersionOptions {
+ if (value === undefined) return {};
+ if (!value || typeof value !== 'object') {
+ throwIpcError('INVALID_PARAMS', 'options must be an object');
+ }
+ const { checkLatest } = value as { checkLatest?: unknown };
+ if (checkLatest !== undefined && typeof checkLatest !== 'boolean') {
+ throwIpcError('INVALID_PARAMS', 'checkLatest must be a boolean');
+ }
+ return { checkLatest };
+}
+
+async function probeLocalVersion(
+ agentKind: AgentBinaryKind,
+ options?: { bypassCache?: boolean },
+): Promise<Omit<AgentBinaryVersionResult, 'latestVersion' | 'updateAvailable'>> {
+ const binaryPath = resolveBinaryPath(agentKind);
+ // 执行前复核路径确为受管二进制(CodeQL js/command-line-injection 防御纵深)
+ if (!binaryPath || !isVettedAgentBinaryPath(agentKind, binaryPath)) {
+ return { kind: agentKind, binaryPath: null, version: null, error: 'binary_not_ready' };
+ }
+
+ // Pi is always live. checkLatest also skips the process cache so an in-place
+ // self-update is compared against the manifest instead of a stale --version.
+ const cached = agentKind === 'pi' || options?.bypassCache ? undefined : versionCache.get(binaryPath);
+ if (cached) {
+ return { kind: agentKind, binaryPath, version: cached };
+ }
+
+ try {
+ const version = await spawnVersion(binaryPath);
+ if (agentKind !== 'pi') versionCache.set(binaryPath, version);
+ return { kind: agentKind, binaryPath, version };
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ log.warn(`${agentKind} --version failed: ${message}`);
+ return { kind: agentKind, binaryPath, version: null, error: message };
+ }
+}
+
function isAgentBinaryKind(value: unknown): value is AgentBinaryKind {
return value === 'claude-code' || value === 'codex' || value === 'pi';
}
@@ -78,31 +187,26 @@ export function registerMakerBinaryVersionIpc(): void {
ipcMain.handle(
MAKER_INVOKE.AGENT_BINARY_VERSION,
- async (_e, agentKind: unknown): Promise<AgentBinaryVersionResult> => {
+ async (event, agentKind: unknown, rawOptions: unknown): Promise<AgentBinaryVersionResult> => {
+ // Auxiliary preload windows must not spawn managed binaries or hit the
+ // update CDN. Device-link reuses this handler with a synthetic event after
+ // its own allowlist, so that path keeps the remote version read.
+ if (!isDeviceLinkInvoke()) assertTrustedAppRendererEvent(event);
if (!isAgentBinaryKind(agentKind)) {
throwIpcError('INVALID_PARAMS', 'agentKind required (claude-code | codex | pi)');
}
+ const { checkLatest } = parseOptions(rawOptions);
- const binaryPath = resolveBinaryPath(agentKind);
- // 执行前复核路径确为受管二进制(CodeQL js/command-line-injection 防御纵深)
- if (!binaryPath || !isVettedAgentBinaryPath(agentKind, binaryPath)) {
- return { kind: agentKind, binaryPath: null, version: null, error: 'binary_not_ready' };
- }
-
- const cached = agentKind === 'pi' ? undefined : versionCache.get(binaryPath);
- if (cached) {
- return { kind: agentKind, binaryPath, version: cached };
- }
-
- try {
- const version = await spawnVersion(binaryPath);
- if (agentKind !== 'pi') versionCache.set(binaryPath, version);
- return { kind: agentKind, binaryPath, version };
- } catch (err) {
- const message = err instanceof Error ? err.message : String(err);
- log.warn(`${agentKind} --version failed: ${message}`);
- return { kind: agentKind, binaryPath, version: null, error: message };
+ // The plain call never waits on the network, so About shows the local
+ // version immediately even offline; the online comparison is a second call.
+ if (!checkLatest) {
+ return { ...(await probeLocalVersion(agentKind)), latestVersion: null, updateAvailable: false };
}
+ // Start before probing so concurrent About rows join one in-flight lookup.
+ const onlineManifest = getLatestManifest();
+ const local = await probeLocalVersion(agentKind, { bypassCache: true });
+ const latestVersion = latestVersionFor(agentKind, await onlineManifest);
+ return { ...local, latestVersion, updateAvailable: isUpdateAvailable(agentKind, local.version, latestVersion) };
},
);
diff --git a/apps/desktop/src/main/updateService.ts b/apps/desktop/src/main/updateService.ts
index f2323270b8..fea8118e76 100644
--- a/apps/desktop/src/main/updateService.ts
+++ b/apps/desktop/src/main/updateService.ts
@@ -2243,6 +2243,25 @@ export function initUpdateService(): void {
app.quit();
});
+ // About → Agent version update: keep the same graceful app relaunch lifecycle,
+ // but ask the next startup to refresh managed harness binaries before they are
+ // exposed to Maker. The marker is consumed once by agent-binaries/prepare and
+ // is scoped to the harness the user confirmed; Pi has its own kernel manager.
+ ipcMain.handle('update-harness-relaunch', (event, kind: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ if (kind !== 'claude-code' && kind !== 'codex') {
+ throwIpcError('INVALID_PARAMS', 'kind required (claude-code | codex)');
+ }
+ const cancelMarker = writeStartupBinaryUpdateMarker(app.getPath('userData'), app.getVersion(), [kind]);
+ if (!cancelMarker) {
+ throwIpcError('INTERNAL', 'failed to schedule harness update');
+ }
+ log.info(`harness update relaunch requested: ${kind}`);
+ app.relaunch({ args: process.argv.slice(1) });
+ app.quit();
+ return { accepted: true };
+ });
+
ipcMain.on('update-set-relaunch-theme', (_event, theme: 'light' | 'dark') => {
if (theme === 'light' || theme === 'dark') {
resolvedRelaunchTheme = theme;
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 4c7256ba94..c523b22752 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -2615,6 +2615,9 @@ contextBridge.exposeInMainWorld('electronAPI', {
isCustomized?: boolean;
}> => ipcRenderer.invoke('update-channel-settings-reset'),
relaunchForChannelChange: (): Promise<void> => ipcRenderer.invoke('update-channel-relaunch'),
+ /** Restart once; the next startup refreshes only the confirmed managed harness first. */
+ relaunchForHarnessUpdate: (kind: 'claude-code' | 'codex'): Promise<{ accepted: true }> =>
+ ipcRenderer.invoke('update-harness-relaunch', kind),
probeBetaChannel: (): Promise<{ available: boolean }> =>
ipcRenderer.invoke('update-channel-probe-beta'),
setUpdateRelaunchTheme: (theme: 'light' | 'dark'): void => {
@@ -7326,12 +7329,15 @@ contextBridge.exposeInMainWorld('electronAPI', {
/** spawn 当前应用使用的 binary `--version`, 进程内缓存。About 面板用。 */
getBinaryVersion: (
agentKind: 'claude-code' | 'codex' | 'pi',
+ options?: { checkLatest?: boolean },
): Promise<{
kind: 'claude-code' | 'codex' | 'pi';
binaryPath: string | null;
version: string | null;
+ latestVersion: string | null;
+ updateAvailable: boolean;
error?: string;
- }> => ipcRenderer.invoke('maker:agent:binary-version', agentKind),
+ }> => ipcRenderer.invoke('maker:agent:binary-version', agentKind, options),
},
// ── Agent 今日累计 (取代老 electronAPI.codex.usage.* + electronAPI.onUsageTodaySpendChanged) ─
diff --git a/apps/desktop/src/renderer/components/settings/AboutSection.tsx b/apps/desktop/src/renderer/components/settings/AboutSection.tsx
index 05fd8f9572..4ed6b6544c 100644
--- a/apps/desktop/src/renderer/components/settings/AboutSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/AboutSection.tsx
@@ -3,19 +3,21 @@
*
* 版本号:
* - 应用版本号:仅国内版显示,值由 window.electronAPI.appDisplayVersion 同步注入
- * - Claude Code / Codex / Pi 版本号: spawn 当前应用使用的 binary `--version`
+ * - Claude Code / Codex 版本号: spawn 当前应用使用的 binary `--version`,再比较线上版本
+ * - Pi 版本号与内核更新由 PiKernelVersionRow 管理
*
* 卡片样式与 NotificationSection / FeishuBotSection 同级 (rounded-xl / Board border)。
*/
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { ExternalLink, FolderOpen, Upload } from 'lucide-react';
+import { Download, ExternalLink, FolderOpen, Upload } from 'lucide-react';
import { cn } from '@/lib/utils';
import { toast } from '@/lib/toast';
import { Switch } from '@/components/ui/switch';
import { Button } from '@/components/ui/button';
+import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
import { useExperimentalFlag } from '@/hooks/useExperimentalFeatures';
import { useAutoUpdateSettings } from '@/hooks/useAutoUpdateSettings';
import { useAnalyticsSettings } from '@/hooks/useAnalyticsSettings';
@@ -26,13 +28,17 @@ import { DefaultOverrideControls } from './DefaultOverrideControls';
import { CURRENT_CINDY_REGION } from '../../../shared/brandRegion';
import { LEGAL_LINKS } from '../../../shared/legalLinks';
+type UpdatableAgentKind = 'claude-code' | 'codex';
+
interface AgentVersionState {
loading: boolean;
version: string | null;
+ latestVersion: string | null;
+ updateAvailable: boolean;
error?: string;
}
-const INITIAL: AgentVersionState = { loading: true, version: null };
+const INITIAL: AgentVersionState = { loading: true, version: null, latestVersion: null, updateAvailable: false };
const DESKTOP_SOCIAL_LINKS = [
{
@@ -55,21 +61,33 @@ const DESKTOP_SOCIAL_LINKS = [
},
] as const;
-function useAgentBinaryVersion(kind: 'claude-code' | 'codex' | 'pi'): AgentVersionState {
+function useAgentBinaryVersion(kind: UpdatableAgentKind): AgentVersionState {
const [state, setState] = useState<AgentVersionState>(INITIAL);
useEffect(() => {
let cancelled = false;
- void window.electronAPI.maker.agent
- .getBinaryVersion(kind)
+ const { getBinaryVersion } = window.electronAPI.maker.agent;
+ // Local first so the version shows immediately even offline; the online
+ // comparison follows and only ever adds the update action.
+ void getBinaryVersion(kind)
.then((res) => {
if (cancelled) return;
- setState({ loading: false, version: res.version, error: res.error });
+ setState({ loading: false, version: res.version, latestVersion: null, updateAvailable: false, error: res.error });
+ return getBinaryVersion(kind, { checkLatest: true }).then((latest) => {
+ if (cancelled) return;
+ setState({
+ loading: false,
+ version: latest.version,
+ latestVersion: latest.latestVersion,
+ updateAvailable: latest.updateAvailable,
+ error: latest.error,
+ });
+ }, () => undefined);
})
.catch((err: unknown) => {
if (cancelled) return;
const message = err instanceof Error ? err.message : String(err);
- setState({ loading: false, version: null, error: message });
+ setState({ loading: false, version: null, latestVersion: null, updateAvailable: false, error: message });
});
return () => {
cancelled = true;
@@ -99,16 +117,16 @@ export function AgentVersionsRows() {
return (
<>
- <InfoRow
+ <AgentVersionRow
+ kind="claude-code"
label={t('settings.about.claudeCodeVersionLabel')}
- value={renderVersion(claudeCode, t)}
- dim={!claudeCode.version}
+ state={claudeCode}
/>
<Divider />
- <InfoRow
+ <AgentVersionRow
+ kind="codex"
label={t('settings.about.codexVersionLabel')}
- value={renderVersion(codex, t)}
- dim={!codex.version}
+ state={codex}
/>
<Divider />
<PiKernelVersionRow />
@@ -117,6 +135,96 @@ export function AgentVersionsRows() {
);
}
+function AgentVersionRow({
+ kind,
+ label,
+ state,
+}: {
+ kind: UpdatableAgentKind;
+ label: string;
+ state: AgentVersionState;
+}) {
+ const { t } = useTranslation();
+ const { confirm } = useConfirmDialog();
+ const currentVersion = state.version ? extractSemver(state.version) : null;
+ const latestVersion = state.latestVersion ? extractSemver(state.latestVersion) : null;
+ // Main decides with the installer's semver ordering: a newer local build never offers a no-op relaunch.
+ const updateAvailable = Boolean(state.updateAvailable && currentVersion && latestVersion);
+
+ const handleUpdate = async () => {
+ if (!currentVersion || !latestVersion) return;
+ const confirmed = await confirm({
+ title: t('settings.about.harnessUpdateTitle', { name: label }),
+ description: t('settings.about.harnessUpdateDescription', {
+ name: label,
+ currentVersion,
+ latestVersion,
+ }),
+ confirmText: t('settings.about.harnessUpdateConfirm', { name: label }),
+ cancelText: t('settings.about.harnessUpdateCancel'),
+ autoFocusConfirm: true,
+ });
+ if (!confirmed) return;
+
+ // Same gate as the app-update banner and the beta-channel restart: a logical
+ // turn, Claude background activity, or Ghost card action must not be killed
+ // by a generic confirmation. A failed probe means we cannot tell, so fail
+ // closed into the interruption warning instead of relaunching.
+ let hasInFlight = true;
+ try {
+ hasInFlight = await window.electronAPI.anyActivityBlockingRelaunch();
+ } catch {
+ hasInFlight = true;
+ }
+ if (hasInFlight) {
+ const interrupt = await confirm({
+ title: t('settings.about.harnessUpdateTitle', { name: label }),
+ description: t('settings.about.harnessUpdateBusyDescription', { name: label }),
+ confirmText: t('settings.about.harnessUpdateConfirm', { name: label }),
+ cancelText: t('settings.about.harnessUpdateCancel'),
+ });
+ if (!interrupt) return;
+ }
+
+ try {
+ await window.electronAPI.relaunchForHarnessUpdate(kind);
+ } catch {
+ toast.error(t('settings.about.harnessUpdateFailed'));
+ }
+ };
+
+ return (
+ <div className="flex items-center justify-between gap-3 px-[18px] py-4">
+ <span className="text-13 text-[var(--settings-section-sublabel)]">{label}</span>
+ <div className="flex min-w-0 items-center justify-end gap-2">
+ <span
+ className={cn(
+ 'truncate text-13 font-medium',
+ !state.version
+ ? 'text-[var(--settings-section-sublabel)] opacity-70'
+ : 'text-[var(--settings-section-title)]',
+ )}
+ >
+ {renderVersion(state, t)}
+ </span>
+ {updateAvailable && (
+ <Button
+ aria-label={t('settings.about.harnessUpdateButton', { name: label })}
+ className="gap-1 px-3 text-12"
+ onClick={() => void handleUpdate()}
+ size="md"
+ title={t('settings.about.harnessUpdateButton', { name: label })}
+ variant="secondary"
+ >
+ <Download aria-hidden size={12} strokeWidth={1.8} />
+ {t('settings.about.harnessUpdateButton', { name: label })}
+ </Button>
+ )}
+ </div>
+ </div>
+ );
+}
+
export function AboutSection() {
const { t } = useTranslation();
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/AboutSection.binaryVersions.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/AboutSection.binaryVersions.test.tsx
index 082975f75c..21a1c6e210 100644
--- a/apps/desktop/src/renderer/components/settings/__tests__/AboutSection.binaryVersions.test.tsx
+++ b/apps/desktop/src/renderer/components/settings/__tests__/AboutSection.binaryVersions.test.tsx
@@ -1,6 +1,6 @@
// @vitest-environment jsdom
-import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
vi.mock('react-i18next', () => ({
@@ -11,15 +11,38 @@ vi.mock('react-i18next', () => ({
}));
import { AgentVersionsRows } from '../AboutSection';
+import { ConfirmDialogProvider } from '@/components/ui/confirm-dialog-provider';
const getBinaryVersion = vi.fn();
const getState = vi.fn();
+const relaunchForHarnessUpdate = vi.fn();
+const anyActivityBlockingRelaunch = vi.fn();
+
+function versionResult(
+ kind: string,
+ options: { checkLatest?: boolean } | undefined,
+ online: { latestVersion: string; updateAvailable: boolean } | null,
+) {
+ const local = { kind, binaryPath: `/${kind}`, version: '1.0.0' };
+ if (!options?.checkLatest || !online) return { ...local, latestVersion: null, updateAvailable: false };
+ return { ...local, ...online };
+}
describe('AboutSection agent binary versions', () => {
+ const renderRows = () =>
+ render(
+ <ConfirmDialogProvider>
+ <AgentVersionsRows />
+ </ConfirmDialogProvider>,
+ );
+
beforeEach(() => {
vi.clearAllMocks();
getState.mockResolvedValue({ currentVersion: '0.84.4', restartRequired: false, official: { release: null }, upstream: { release: null }, operation: null });
+ anyActivityBlockingRelaunch.mockResolvedValue(false);
(window as unknown as { electronAPI: unknown }).electronAPI = {
+ relaunchForHarnessUpdate,
+ anyActivityBlockingRelaunch,
maker: {
piKernel: { getState },
agent: {
@@ -39,41 +62,134 @@ describe('AboutSection agent binary versions', () => {
Promise.resolve({
kind,
binaryPath: `/${kind}`,
- version:
- kind === 'claude-code'
- ? '2.1.258 (Claude Code)'
- : kind === 'codex'
- ? 'codex-cli 0.145.0'
- : 'pi 0.84.4',
+ version: kind === 'claude-code' ? '2.1.258 (Claude Code)' : 'codex-cli 0.145.0',
+ latestVersion: null,
+ updateAvailable: false,
}),
);
- render(<AgentVersionsRows />);
+ renderRows();
- await waitFor(() => expect(getBinaryVersion).toHaveBeenCalledTimes(2));
+ await waitFor(() => expect(getBinaryVersion).toHaveBeenCalledTimes(4));
expect(getBinaryVersion).toHaveBeenCalledWith('claude-code');
expect(getBinaryVersion).toHaveBeenCalledWith('codex');
+ expect(getBinaryVersion).toHaveBeenCalledWith('claude-code', { checkLatest: true });
+ expect(getBinaryVersion).toHaveBeenCalledWith('codex', { checkLatest: true });
expect(getState).toHaveBeenCalled();
await waitFor(() => {
expect(screen.getByText('settings.about.claudeCodeVersionLabel')).toBeTruthy();
expect(screen.getByText('settings.about.codexVersionLabel')).toBeTruthy();
expect(screen.getByText('settings.about.piVersionLabel')).toBeTruthy();
+ expect(screen.getByText('2.1.258')).toBeTruthy();
+ expect(screen.getByText('0.145.0')).toBeTruthy();
expect(screen.getByText('0.84.4')).toBeTruthy();
});
});
it('shows the existing not-ready state when Pi is unavailable', async () => {
getState.mockResolvedValue({ currentVersion: null, restartRequired: false, official: { release: null }, upstream: { release: null }, operation: null });
- getBinaryVersion.mockImplementation((kind: string) =>
+ getBinaryVersion.mockImplementation((kind: string, options?: { checkLatest?: boolean }) =>
+ Promise.resolve(versionResult(kind, options, null)),
+ );
+
+ renderRows();
+
+ await waitFor(() => expect(screen.getByText('settings.about.version.notReady')).toBeTruthy());
+ });
+
+ it('shows the local version without waiting for the online comparison', async () => {
+ getBinaryVersion.mockImplementation((kind: string, options?: { checkLatest?: boolean }) =>
+ options?.checkLatest ? new Promise(() => {}) : Promise.resolve(versionResult(kind, options, null)),
+ );
+
+ renderRows();
+
+ await waitFor(() => expect(screen.getAllByText('1.0.0')).toHaveLength(2));
+ expect(screen.queryByText('settings.about.version.loading')).toBeNull();
+ });
+
+ it('shows an update button only when Main reports a newer online version', async () => {
+ getBinaryVersion.mockImplementation((kind: string, options?: { checkLatest?: boolean }) =>
Promise.resolve(
- kind === 'pi'
- ? { kind, binaryPath: null, version: null, error: 'binary_not_ready' }
- : { kind, binaryPath: `/${kind}`, version: '1.0.0' },
+ versionResult(kind, options, kind === 'codex'
+ ? { latestVersion: '1.1.0', updateAvailable: true }
+ // A local build newer than the channel manifest differs but is not an update.
+ : { latestVersion: '0.9.0', updateAvailable: false }),
),
);
- render(<AgentVersionsRows />);
+ renderRows();
- await waitFor(() => expect(screen.getByText('settings.about.version.notReady')).toBeTruthy());
+ await waitFor(() => {
+ expect(screen.getByRole('button', { name: 'settings.about.harnessUpdateButton' })).toBeTruthy();
+ });
+ expect(screen.getAllByRole('button', { name: 'settings.about.harnessUpdateButton' })).toHaveLength(1);
+ });
+
+ it('requires confirmation and relaunches only for the confirmed harness', async () => {
+ getBinaryVersion.mockImplementation((kind: string, options?: { checkLatest?: boolean }) =>
+ Promise.resolve(
+ versionResult(kind, options, kind === 'codex' ? { latestVersion: '1.1.0', updateAvailable: true } : null),
+ ),
+ );
+ relaunchForHarnessUpdate.mockResolvedValue({ accepted: true });
+
+ renderRows();
+ await waitFor(() => {
+ expect(screen.getByRole('button', { name: 'settings.about.harnessUpdateButton' })).toBeTruthy();
+ });
+
+ fireEvent.click(screen.getByRole('button', { name: 'settings.about.harnessUpdateButton' }));
+ expect(relaunchForHarnessUpdate).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('button', { name: 'settings.about.harnessUpdateConfirm' }));
+ await waitFor(() => expect(relaunchForHarnessUpdate).toHaveBeenCalledExactlyOnceWith('codex'));
+ });
+
+ it('asks again before a harness restart would interrupt in-flight work', async () => {
+ getBinaryVersion.mockImplementation((kind: string, options?: { checkLatest?: boolean }) =>
+ Promise.resolve(
+ versionResult(kind, options, kind === 'codex' ? { latestVersion: '1.1.0', updateAvailable: true } : null),
+ ),
+ );
+ anyActivityBlockingRelaunch.mockResolvedValue(true);
+ relaunchForHarnessUpdate.mockResolvedValue({ accepted: true });
+
+ renderRows();
+ await waitFor(() => {
+ expect(screen.getByRole('button', { name: 'settings.about.harnessUpdateButton' })).toBeTruthy();
+ });
+
+ fireEvent.click(screen.getByRole('button', { name: 'settings.about.harnessUpdateButton' }));
+ fireEvent.click(screen.getByRole('button', { name: 'settings.about.harnessUpdateConfirm' }));
+ await waitFor(() => {
+ expect(screen.getByText('settings.about.harnessUpdateBusyDescription')).toBeTruthy();
+ });
+ expect(relaunchForHarnessUpdate).not.toHaveBeenCalled();
+
+ fireEvent.click(screen.getByRole('button', { name: 'settings.about.harnessUpdateConfirm' }));
+ await waitFor(() => expect(relaunchForHarnessUpdate).toHaveBeenCalledExactlyOnceWith('codex'));
+ });
+
+ it('does not relaunch when the busy probe fails and the interruption warning is declined', async () => {
+ getBinaryVersion.mockImplementation((kind: string, options?: { checkLatest?: boolean }) =>
+ Promise.resolve(
+ versionResult(kind, options, kind === 'codex' ? { latestVersion: '1.1.0', updateAvailable: true } : null),
+ ),
+ );
+ anyActivityBlockingRelaunch.mockRejectedValue(new Error('ipc channel closed'));
+
+ renderRows();
+ await waitFor(() => {
+ expect(screen.getByRole('button', { name: 'settings.about.harnessUpdateButton' })).toBeTruthy();
+ });
+
+ fireEvent.click(screen.getByRole('button', { name: 'settings.about.harnessUpdateButton' }));
+ fireEvent.click(screen.getByRole('button', { name: 'settings.about.harnessUpdateConfirm' }));
+ await waitFor(() => {
+ expect(screen.getByText('settings.about.harnessUpdateBusyDescription')).toBeTruthy();
+ });
+ fireEvent.click(screen.getByRole('button', { name: 'settings.about.harnessUpdateCancel' }));
+ await waitFor(() => expect(anyActivityBlockingRelaunch).toHaveBeenCalled());
+ expect(relaunchForHarnessUpdate).not.toHaveBeenCalled();
});
});
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 49fed552f1..08c1de0bd4 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -1087,6 +1087,13 @@
"claudeCodeVersionLabel": "Claude Code version",
"codexVersionLabel": "Codex version",
"piVersionLabel": "Pi version",
+ "harnessUpdateButton": "Update {{name}}",
+ "harnessUpdateTitle": "Update {{name}}",
+ "harnessUpdateDescription": "Cindy will restart and update {{name}} when it starts. Current version: {{currentVersion}}. Online version: {{latestVersion}}.",
+ "harnessUpdateConfirm": "Restart and Update {{name}}",
+ "harnessUpdateCancel": "Cancel",
+ "harnessUpdateBusyDescription": "Tasks are currently in progress and restarting will interrupt them. Restart and update anyway?",
+ "harnessUpdateFailed": "Could not schedule the Agent update. Please try again later.",
"logsDirLabel": "Logs directory",
"openLogsDir": "Open",
"openLogsDirTooltip": "Open the logs directory in the system file manager",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index f4fbecc7fa..25208b19f2 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -1087,6 +1087,13 @@
"claudeCodeVersionLabel": "Claude Code バージョン",
"codexVersionLabel": "Codex バージョン",
"piVersionLabel": "Pi バージョン",
+ "harnessUpdateButton": "{{name}}を更新",
+ "harnessUpdateTitle": "{{name}}を更新",
+ "harnessUpdateDescription": "Cindy を再起動すると、起動時に {{name}} を更新します。現在のバージョン: {{currentVersion}}。オンラインのバージョン: {{latestVersion}}。",
+ "harnessUpdateConfirm": "再起動して{{name}}を更新",
+ "harnessUpdateCancel": "キャンセル",
+ "harnessUpdateBusyDescription": "進行中のタスクがあります。再起動すると中断されます。それでも今すぐ再起動して更新しますか?",
+ "harnessUpdateFailed": "Agent の更新を準備できませんでした。しばらくしてからもう一度お試しください。",
"logsDirLabel": "ログディレクトリ",
"openLogsDir": "開く",
"openLogsDirTooltip": "システムのファイルマネージャーでログディレクトリを開く",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index db7da223dc..d860435a5b 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -1087,6 +1087,13 @@
"claudeCodeVersionLabel": "Claude Code 버전",
"codexVersionLabel": "Codex 버전",
"piVersionLabel": "Pi 버전",
+ "harnessUpdateButton": "{{name}} 업데이트",
+ "harnessUpdateTitle": "{{name}} 업데이트",
+ "harnessUpdateDescription": "Cindy가 다시 시작되며 시작할 때 {{name}}을(를) 업데이트합니다. 현재 버전: {{currentVersion}}. 온라인 버전: {{latestVersion}}.",
+ "harnessUpdateConfirm": "다시 시작하고 {{name}} 업데이트",
+ "harnessUpdateCancel": "취소",
+ "harnessUpdateBusyDescription": "진행 중인 작업이 있어 재시작하면 중단됩니다. 그래도 지금 다시 시작하고 업데이트할까요?",
+ "harnessUpdateFailed": "Agent 업데이트를 예약하지 못했습니다. 잠시 후 다시 시도해 주세요.",
"logsDirLabel": "로그 디렉터리",
"openLogsDir": "열기",
"openLogsDirTooltip": "시스템 파일 관리자에서 로그 디렉터리 열기",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 2ec17c81d3..303b1c9870 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -1087,6 +1087,13 @@
"claudeCodeVersionLabel": "Claude Code 版本号",
"codexVersionLabel": "Codex 版本号",
"piVersionLabel": "Pi 版本号",
+ "harnessUpdateButton": "更新 {{name}}",
+ "harnessUpdateTitle": "更新 {{name}}",
+ "harnessUpdateDescription": "将重启 Cindy,并在启动时更新 {{name}}。当前版本 {{currentVersion}},线上版本 {{latestVersion}}。",
+ "harnessUpdateConfirm": "重启并更新 {{name}}",
+ "harnessUpdateCancel": "取消",
+ "harnessUpdateBusyDescription": "当前有任务正在进行中,重启会打断它们。确定要立即重启并更新吗?",
+ "harnessUpdateFailed": "无法安排 Agent 更新,请稍后重试。",
"logsDirLabel": "日志目录",
"openLogsDir": "打开",
"openLogsDirTooltip": "在系统文件管理器中打开日志目录",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 003e64a56c..95742b8bfb 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -1087,6 +1087,13 @@
"claudeCodeVersionLabel": "Claude Code 版本號",
"codexVersionLabel": "Codex 版本號",
"piVersionLabel": "Pi 版本號",
+ "harnessUpdateButton": "更新 {{name}}",
+ "harnessUpdateTitle": "更新 {{name}}",
+ "harnessUpdateDescription": "Cindy 將重新啟動,並在啟動時更新 {{name}}。目前版本 {{currentVersion}},線上版本 {{latestVersion}}。",
+ "harnessUpdateConfirm": "重新啟動並更新 {{name}}",
+ "harnessUpdateCancel": "取消",
+ "harnessUpdateBusyDescription": "目前有任務進行中,重新啟動會中斷它們。確定要立即重新啟動並更新嗎?",
+ "harnessUpdateFailed": "無法安排 Agent 更新,請稍後再試。",
"logsDirLabel": "日誌目錄",
"openLogsDir": "開啟",
"openLogsDirTooltip": "在系統檔案管理器中開啟日誌目錄",
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 867841adf8..ce5ee6c73a 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -3817,6 +3817,8 @@ interface ElectronAPI {
}>;
/** 用户主动重启,让 beta 通道切换在下次冷启动前生效。 */
relaunchForChannelChange: () => Promise<void>;
+ /** 用户确认后重启,下一次启动只更新所确认的受管 Harness(Pi 由内核管理单独处理)。 */
+ relaunchForHarnessUpdate: (kind: 'claude-code' | 'codex') => Promise<{ accepted: true }>;
/** 打开 beta 前预检:探测 beta manifest 是否可达(HTTP 200)。 */
probeBetaChannel: () => Promise<{ available: boolean }>;
onUpdateChannelSettings: (
@@ -6585,10 +6587,17 @@ interface ElectronAPI {
identity?: string;
}>;
/** spawn 当前应用使用的 binary `--version`, 进程内缓存。About 面板用。 */
- getBinaryVersion: (agentKind: 'claude-code' | 'codex' | 'pi') => Promise<{
+ /** checkLatest 额外比较当前通道的线上版本;不传只读本地版本,离线也不等待。 */
+ getBinaryVersion: (
+ agentKind: 'claude-code' | 'codex' | 'pi',
+ options?: { checkLatest?: boolean },
+ ) => Promise<{
kind: 'claude-code' | 'codex' | 'pi';
binaryPath: string | null;
version: string | null;
+ latestVersion: string | null;
+ /** 线上版本严格高于本地版本时为 true(与启动安装的保留策略同口径)。 */
+ updateAvailable: boolean;
error?: string;
}>;
};