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(update): 重启记录文件损坏时移到一边再写,不覆盖也不卡住

Dash3b1714cdd0c7
diff --git a/apps/desktop/src/main/agent-app-update/__tests__/restartRecords.test.ts b/apps/desktop/src/main/agent-app-update/__tests__/restartRecords.test.ts
new file mode 100644
index 0000000000..df5f5690fa
--- /dev/null
+++ b/apps/desktop/src/main/agent-app-update/__tests__/restartRecords.test.ts
@@ -0,0 +1,60 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('../../logger', () => ({
+ createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }),
+ maskPath: (value: string) => value,
+}));
+
+import { addRestartRecord, listRestartRecords, removeRestartRecord } from '../restartRecords.js';
+
+const record = (requestId: string) => ({
+ requestId,
+ sessionId: `task-${requestId}`,
+ fromVersion: '0.1.86',
+ targetVersion: '0.1.90',
+ requestedAt: 1,
+ pid: 1,
+});
+
+let dir: string;
+let file: string;
+
+beforeEach(() => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-app-update-records-'));
+ file = path.join(dir, 'agent-app-update.json');
+});
+
+afterEach(() => {
+ fs.rmSync(dir, { recursive: true, force: true });
+});
+
+describe('restart records file', () => {
+ it('appends records and removes them one by one', () => {
+ addRestartRecord(file, record('a'));
+ addRestartRecord(file, record('b'));
+ expect(listRestartRecords(file).map((entry) => entry.requestId)).toEqual(['a', 'b']);
+ removeRestartRecord(file, 'a');
+ expect(listRestartRecords(file).map((entry) => entry.requestId)).toEqual(['b']);
+ removeRestartRecord(file, 'b');
+ expect(fs.existsSync(file)).toBe(false);
+ });
+
+ it('moves a corrupt file aside before writing, never overwriting it', () => {
+ fs.writeFileSync(file, '{"records": [ broken');
+ addRestartRecord(file, record('new'));
+ expect(listRestartRecords(file).map((entry) => entry.requestId)).toEqual(['new']);
+ const aside = fs.readdirSync(dir).filter((name) => name.includes('.corrupt-'));
+ expect(aside).toHaveLength(1);
+ expect(fs.readFileSync(path.join(dir, aside[0]!), 'utf8')).toBe('{"records": [ broken');
+ });
+
+ it('leaves a corrupt file untouched when only reading or removing', () => {
+ fs.writeFileSync(file, 'not json');
+ expect(listRestartRecords(file)).toEqual([]);
+ removeRestartRecord(file, 'a');
+ expect(fs.readFileSync(file, 'utf8')).toBe('not json');
+ });
+});
diff --git a/apps/desktop/src/main/agent-app-update/index.ts b/apps/desktop/src/main/agent-app-update/index.ts
index 9984e238f2..5417fcd508 100644
--- a/apps/desktop/src/main/agent-app-update/index.ts
+++ b/apps/desktop/src/main/agent-app-update/index.ts
@@ -3,8 +3,6 @@
* running tasks, Host cards) come from Maker Host; updater work goes through the
* existing updateService entry points only.
*/
-import fs from 'node:fs';
-import path from 'node:path';
import { app } from 'electron';
import type { XdtHelperMcpDeps } from '@cindy/mcps';
@@ -33,15 +31,14 @@ import {
setAutoRelaunchOnIdleForAgent,
} from '../updateService.js';
import { compareAppUpdateVersions } from '../updateVersionPolicy.js';
-import { atomicWriteFileSync, readAtomicFileSync } from '../utils/atomicWriteFile.js';
import {
createAgentAppUpdateService,
type AgentAppUpdateDeps,
type AgentAppUpdateMarker,
type AgentAppUpdateOwner,
type AgentAppUpdateService,
- MAX_RESTART_RECORDS,
} from './agentAppUpdateService.js';
+import { addRestartRecord, listRestartRecords, removeRestartRecord } from './restartRecords.js';
/** Owner binding: broadcast scope for current-ness checks and the owner's own marker path. */
interface DesktopAgentAppUpdateOwner extends AgentAppUpdateOwner {
@@ -89,59 +86,6 @@ function assertOwnerCurrent(owner: AgentAppUpdateOwner): void {
throw new Error('The account that confirmed the update is no longer active');
}
-function parseRecord(value: unknown): AgentAppUpdateMarker | null {
- if (!value || typeof value !== 'object') return null;
- const record = value as Partial<AgentAppUpdateMarker>;
- if (
- typeof record.requestId !== 'string' ||
- typeof record.sessionId !== 'string' ||
- typeof record.fromVersion !== 'string' ||
- typeof record.requestedAt !== 'number' ||
- typeof record.pid !== 'number'
- )
- return null;
- return {
- requestId: record.requestId,
- sessionId: record.sessionId,
- fromVersion: record.fromVersion,
- ...(typeof record.targetVersion === 'string' ? { targetVersion: record.targetVersion } : {}),
- requestedAt: record.requestedAt,
- pid: record.pid,
- };
-}
-
-/** Restart records file: `{ records: [...] }`, one entry per attempted restart. */
-function readRecords(file: string, options?: { throwOnError?: boolean }): AgentAppUpdateMarker[] {
- let raw: string | null;
- try {
- raw = readAtomicFileSync(file);
- } catch (error) {
- // An unreadable (not merely missing) file may hold records; never overwrite it blindly.
- if (options?.throwOnError) throw error;
- log.warn('agent app update marker read failed', { error: String(error) });
- return [];
- }
- if (!raw) return [];
- try {
- const parsed = JSON.parse(raw) as { records?: unknown };
- return Array.isArray(parsed.records)
- ? parsed.records.map(parseRecord).filter((record): record is AgentAppUpdateMarker => !!record)
- : [];
- } catch {
- log.warn('agent app update marker is corrupt; ignoring it');
- return [];
- }
-}
-
-function writeRecords(file: string, records: AgentAppUpdateMarker[]): void {
- if (records.length === 0) {
- for (const target of [file, `${file}.bak`]) fs.rmSync(target, { force: true });
- return;
- }
- fs.mkdirSync(path.dirname(file), { recursive: true });
- atomicWriteFileSync(file, JSON.stringify({ records }));
-}
-
function requireSessionHost(): AgentAppUpdateSessionHost {
if (!sessionHost) throw new Error('Agent app update host is not ready');
return sessionHost;
@@ -164,24 +108,9 @@ function getService(): AgentAppUpdateService {
captureOwner,
isOwnerCurrent,
marker: {
- list: (owner) => readRecords(markerPathOf(owner)),
- add: (owner, record) => {
- const file = markerPathOf(owner);
- // A record that cannot be read back must not be silently replaced.
- const records = readRecords(file, { throwOnError: true });
- writeRecords(file, [...records, record].slice(-MAX_RESTART_RECORDS));
- },
- remove: (owner, requestId) => {
- const file = markerPathOf(owner);
- const records = readRecords(file);
- const remaining = records.filter((record) => record.requestId !== requestId);
- if (remaining.length === records.length) return;
- try {
- writeRecords(file, remaining);
- } catch (error) {
- log.warn('agent app update marker update failed', { error: String(error) });
- }
- },
+ list: (owner) => listRestartRecords(markerPathOf(owner)),
+ add: (owner, record) => addRestartRecord(markerPathOf(owner), record),
+ remove: (owner, requestId) => removeRestartRecord(markerPathOf(owner), requestId),
},
notify: async (owner, sessionId, clientId, text) => {
assertOwnerCurrent(owner);
diff --git a/apps/desktop/src/main/agent-app-update/restartRecords.ts b/apps/desktop/src/main/agent-app-update/restartRecords.ts
new file mode 100644
index 0000000000..c0e7cde91b
--- /dev/null
+++ b/apps/desktop/src/main/agent-app-update/restartRecords.ts
@@ -0,0 +1,97 @@
+/**
+ * Owner-scoped restart records for Agent-approved app updates: `{ records: [...] }`,
+ * one entry per attempted restart whose result is not yet written back. Entries
+ * are appended, never replaced, and removed one by one.
+ */
+import fs from 'node:fs';
+import path from 'node:path';
+
+import { createLogger, maskPath } from '../logger.js';
+import { atomicWriteFileSync, readAtomicFileSync } from '../utils/atomicWriteFile.js';
+import { MAX_RESTART_RECORDS, type AgentAppUpdateMarker } from './agentAppUpdateService.js';
+
+const log = createLogger('agent-app-update');
+
+function parseRecord(value: unknown): AgentAppUpdateMarker | null {
+ if (!value || typeof value !== 'object') return null;
+ const record = value as Partial<AgentAppUpdateMarker>;
+ if (
+ typeof record.requestId !== 'string' ||
+ typeof record.sessionId !== 'string' ||
+ typeof record.fromVersion !== 'string' ||
+ typeof record.requestedAt !== 'number' ||
+ typeof record.pid !== 'number'
+ )
+ return null;
+ return {
+ requestId: record.requestId,
+ sessionId: record.sessionId,
+ fromVersion: record.fromVersion,
+ ...(typeof record.targetVersion === 'string' ? { targetVersion: record.targetVersion } : {}),
+ requestedAt: record.requestedAt,
+ pid: record.pid,
+ };
+}
+
+function readRecords(file: string, mode: 'lenient' | 'before-write'): AgentAppUpdateMarker[] {
+ let raw: string | null;
+ try {
+ raw = readAtomicFileSync(file);
+ } catch (error) {
+ // An unreadable (not merely missing) file may hold records; never overwrite it blindly.
+ if (mode === 'before-write') throw error;
+ log.warn('agent app update marker read failed', { error: String(error) });
+ return [];
+ }
+ if (!raw) return [];
+ try {
+ const parsed = JSON.parse(raw) as { records?: unknown };
+ if (!Array.isArray(parsed.records)) throw new Error('records missing');
+ return parsed.records
+ .map(parseRecord)
+ .filter((record): record is AgentAppUpdateMarker => !!record);
+ } catch {
+ if (mode === 'before-write') {
+ // Unparseable content is moved aside rather than overwritten: nothing is
+ // destroyed, and a damaged file cannot block every later update either.
+ // A failed move throws, which cancels the restart.
+ const aside = `${file}.corrupt-${Date.now()}`;
+ fs.renameSync(file, aside);
+ log.warn('agent app update marker was corrupt; moved aside', { path: maskPath(aside) });
+ } else {
+ log.warn('agent app update marker is corrupt; ignoring it');
+ }
+ return [];
+ }
+}
+
+function writeRecords(file: string, records: AgentAppUpdateMarker[]): void {
+ if (records.length === 0) {
+ for (const target of [file, `${file}.bak`]) fs.rmSync(target, { force: true });
+ return;
+ }
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ atomicWriteFileSync(file, JSON.stringify({ records }));
+}
+
+export function listRestartRecords(file: string): AgentAppUpdateMarker[] {
+ return readRecords(file, 'lenient');
+}
+
+/** Throws when existing records cannot be preserved; the caller then does not restart. */
+export function addRestartRecord(file: string, record: AgentAppUpdateMarker): void {
+ const records = readRecords(file, 'before-write');
+ writeRecords(file, [...records, record].slice(-MAX_RESTART_RECORDS));
+}
+
+export function removeRestartRecord(file: string, requestId: string): void {
+ const records = readRecords(file, 'lenient');
+ const remaining = records.filter((record) => record.requestId !== requestId);
+ // Nothing of ours (or an unreadable file): leave it untouched.
+ if (remaining.length === records.length) return;
+ try {
+ writeRecords(file, remaining);
+ } catch (error) {
+ log.warn('agent app update marker update failed', { error: String(error) });
+ }
+}