Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(update): keep failed writes from invalidating valid patches
guyong06f4ad62ae6f
diff --git a/apps/desktop/src/main/__tests__/manifestService.test.ts b/apps/desktop/src/main/__tests__/manifestService.test.tsnew file mode 100644index 0000000000..cd267ce258--- /dev/null+++ b/apps/desktop/src/main/__tests__/manifestService.test.ts@@ -0,0 +1,101 @@+import { EventEmitter } from 'node:events';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { TEST_CDN_BASE_URL } from '../../test/vitest/clientEndpointsFixture';++const netRequest = vi.hoisted(() => vi.fn());+const canaryRead = vi.hoisted(() => vi.fn(() => false));+const isBetaChannelEnabled = vi.hoisted(() => vi.fn(() => false));+const getClientEndpoint = vi.hoisted(() => vi.fn(() => TEST_CDN_BASE_URL));++vi.mock('electron', () => ({+ app: {+ isPackaged: true,+ getPath: vi.fn(() => '/tmp'),+ },+ net: { request: netRequest },+}));++vi.mock('../canaryFlagStore', () => ({+ read: canaryRead,+}));++vi.mock('../updateChannelStore', () => ({+ isBetaChannelEnabled,+}));++vi.mock('../clientEndpointsService', () => ({+ getClientEndpoint,+}));++vi.mock('../logger', () => ({+ createLogger: () => ({+ info: vi.fn(),+ warn: vi.fn(),+ error: vi.fn(),+ debug: vi.fn(),+ }),+}));++function mockManifestResponse(body: string, onEnd?: () => void): void {+ const request = new EventEmitter() as EventEmitter & {+ abort: ReturnType<typeof vi.fn>;+ end: ReturnType<typeof vi.fn>;+ };+ request.abort = vi.fn();+ request.end = vi.fn(() => {+ const response = new EventEmitter() as EventEmitter & { statusCode: number };+ response.statusCode = 200;+ request.emit('response', response);+ response.emit('data', Buffer.from(body));+ onEnd?.();+ response.emit('end');+ });+ netRequest.mockReturnValueOnce(request);+}++const RELEASE_MANIFEST = JSON.stringify({+ app: { version: '0.0.65' },+});++describe('manifestService cache channel identity', () => {+ beforeEach(() => {+ netRequest.mockReset();+ canaryRead.mockReset();+ canaryRead.mockReturnValue(false);+ isBetaChannelEnabled.mockReset();+ isBetaChannelEnabled.mockReturnValue(false);+ getClientEndpoint.mockReset();+ getClientEndpoint.mockReturnValue(TEST_CDN_BASE_URL);+ });++ afterEach(async () => {+ const { clearCachedManifest } = await import('../manifestService');+ clearCachedManifest();+ });++ it('discards a cached release manifest after the shared channel switches to beta', async () => {+ mockManifestResponse(RELEASE_MANIFEST);+ const service = await import('../manifestService');++ await expect(service.fetchManifest()).resolves.toMatchObject({ app: { version: '0.0.65' } });+ expect(service.getCachedManifest()).toMatchObject({ app: { version: '0.0.65' } });++ isBetaChannelEnabled.mockReturnValue(true);++ expect(service.getCachedManifest()).toBeNull();+ expect(netRequest.mock.calls[0]?.[0]).toContain('manifest-');+ expect(String(netRequest.mock.calls[0]?.[0])).not.toContain('-beta.json');+ });++ it('does not cache a fetch that finishes after the shared channel changes', async () => {+ mockManifestResponse(RELEASE_MANIFEST, () => {+ isBetaChannelEnabled.mockReturnValue(true);+ });+ const service = await import('../manifestService');++ await expect(service.fetchManifest()).resolves.toBeNull();+ expect(service.getCachedManifest()).toBeNull();+ });+});diff --git a/apps/desktop/src/main/__tests__/updateService.test.ts b/apps/desktop/src/main/__tests__/updateService.test.tsindex 389dcda9cc..7927c081ad 100644--- a/apps/desktop/src/main/__tests__/updateService.test.ts+++ b/apps/desktop/src/main/__tests__/updateService.test.ts@@ -1000,6 +1000,35 @@ describe('startup update relaunch safety', () => {}});+ it('does not treat a failed settings write as an external channel change', async () => {+ const service = await bootWithStagedPatch({ enabled: true });+ let releaseProbe: ((busy: boolean) => void) | undefined;+ const probeStarted = new Promise<void>((resolveStarted) => {+ service.setUpdateAutoRelaunchBusyProbe(+ () =>+ new Promise<boolean>((resolveProbe) => {+ resolveStarted();+ releaseProbe = resolveProbe;+ }),+ );+ });+ writeEnableBeta.mockRejectedValueOnce(new Error('lock timeout'));+ try {+ await probeStarted;+ const setHandler = ipcHandlers.get('update-channel-settings-set');+ expect(setHandler).toBeTypeOf('function');+ await expect(setHandler?.({ sender: { id: 1 } }, { enableBeta: true })).rejects.toThrow();+ expect(fs.existsSync(path.join(TEST_USER_DATA, 'updates', 'patch-info.json'))).toBe(true);+ releaseProbe?.(true);+ await vi.waitFor(() => {+ expect(service.getUpdateStatus()).toBe('ready');+ });+ expect(fs.existsSync(path.join(TEST_USER_DATA, 'updates', 'patch-info.json'))).toBe(true);+ } finally {+ service.stopUpdateService();+ }+ });+it('does not let a failed settings write overwrite a committed observed channel', async () => {const service = await bootWithStagedPatch({ enabled: false });let releaseFirstWrite: (() => void) | undefined;diff --git a/apps/desktop/src/main/manifestService.ts b/apps/desktop/src/main/manifestService.tsindex dd8ab88dd0..9d1892223a 100644--- a/apps/desktop/src/main/manifestService.ts+++ b/apps/desktop/src/main/manifestService.ts@@ -17,7 +17,7 @@import { app, net } from 'electron';import * as canaryFlagStore from './canaryFlagStore';-import { resolveUpdateChannel } from '@cindy/maker-shared/update-channel';+import { resolveUpdateChannel, type UpdateChannel } from '@cindy/maker-shared/update-channel';import { createLogger } from './logger';import { getClientEndpoint } from './clientEndpointsService';@@ -101,6 +101,8 @@ const REQUEST_TIMEOUT_MS = 30_000;// ── State ──────────────────────────────────────────────────────────────────let cached: Manifest | null = null;+/** 当前缓存对应的发布通道。读取时跟磁盘对账,共库另一实例切过渠道就丢掉。 */+let cachedChannel: UpdateChannel | null = null;/*** manifest 代际:切渠道(clearCachedManifest)时 +1。fetchManifest 发起时快照,* 响应完成写 cached 前核对——若期间切了渠道,这次 in-flight 的旧渠道响应直接作废,@@ -108,6 +110,10 @@ let cached: Manifest | null = null;*/let manifestEpoch = 0;+function currentUpdateChannel(): UpdateChannel {+ return resolveUpdateChannel(canaryFlagStore.read(), isBetaChannelEnabled());+}+// ── Helpers ────────────────────────────────────────────────────────────────// 惰性读取(见文件顶注):清单在 initClientEndpoints 之后才可读,模块级捕获会炸。@@ -158,10 +164,7 @@ export async function fetchManifest(if (isDev()) return null;if (signal?.aborted) return null;- const channel = resolveUpdateChannel(- canaryFlagStore.read(),- isBetaChannelEnabled(),- );+ const channel = currentUpdateChannel();const channelSuffix = channel === 'release' ? '' : `-${channel}`;// Cache-bust: append timestamp to prevent Chromium / CDN serving stale manifestconst url = `${getBaseUrl()}/manifest-${getPlatformKey()}${channelSuffix}.json?t=${Date.now()}`;@@ -205,12 +208,14 @@ export async function fetchManifest(const json = JSON.parse(body) as Manifest;// 响应回来前切了渠道:这是旧渠道的 manifest,不作废会污染 cached,// 让后续 agent prepare 装旧渠道资产。返回 null 让调用方下次按新渠道重取。- if (epochAtStart !== manifestEpoch) {+ // 共库另一实例改开关不会推进本进程 epoch,所以还要再对一次当前通道。+ if (epochAtStart !== manifestEpoch || currentUpdateChannel() !== channel) {log.info('manifest channel changed during fetch — discarding stale response');finish(null);return;}cached = json;+ cachedChannel = channel;log.info('Fetched OK: app.version=%s, hotfix=%s', json.app?.version, json.app?.hotfix?.file ?? 'none');finish(json);} catch (err) {@@ -236,8 +241,15 @@ export async function fetchManifest(/*** Return the in-memory cached manifest (may be null if never fetched or dev mode).+ * 读取时跟当前发布通道对账:共库另一实例切过渠道后,旧缓存不能再给 agent prepare 用。*/export function getCachedManifest(): Manifest | null {+ if (!cached) return null;+ if (cachedChannel !== currentUpdateChannel()) {+ log.info('cached manifest channel is stale — discarding');+ clearCachedManifest();+ return null;+ }return cached;}@@ -251,6 +263,7 @@ export function getCachedManifest(): Manifest | null {*/export function clearCachedManifest(): void {cached = null;+ cachedChannel = null;manifestEpoch += 1;}diff --git a/apps/desktop/src/main/updateService.ts b/apps/desktop/src/main/updateService.tsindex f5475fd778..23de567316 100644--- a/apps/desktop/src/main/updateService.ts+++ b/apps/desktop/src/main/updateService.ts@@ -1534,8 +1534,9 @@ export function initUpdateService(): void {const wasBeta = readUpdateChannelSettings().enableBeta;// 先拦住 apply 再等落盘:writeEnableBeta 可能卡住跨进程锁。// 真正写成之后再删 zip;写入失败则放开 hold,旧补丁还能用。+ // 写入前不要改 observedEnableBeta:失败路径会按磁盘对账,+ // 乐观改成目标值会把「磁盘没变」误判成别人已经切过渠道。if (wasBeta !== next) {- observedEnableBeta = next;holdStagedPatchForPendingChannelChange();}try {@@ -1559,7 +1560,6 @@ export function initUpdateService(): void {assertTrustedAppRendererEvent(event);const wasBeta = readUpdateChannelSettings().enableBeta;if (wasBeta) {- observedEnableBeta = false;holdStagedPatchForPendingChannelChange();}try {