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): 重启记录按请求追加不覆盖;采用已在进行的重启要等它落定

Dash06cf175a7d12
diff --git a/apps/desktop/src/main/__tests__/updateService.test.ts b/apps/desktop/src/main/__tests__/updateService.test.ts
index 6f161c06c1..2400349a6c 100644
--- a/apps/desktop/src/main/__tests__/updateService.test.ts
+++ b/apps/desktop/src/main/__tests__/updateService.test.ts
@@ -437,8 +437,9 @@ describe('agent-facing managed app update check', () => {
expect(order).toEqual(['before:1:0']);
expect(spawnProcess).toHaveBeenCalledOnce();
// A second request while relaunching neither downloads nor spawns again.
- await expect(service.applyConfirmedAppUpdateForAgent({ beforeRelaunch }))
- .resolves.toMatchObject({ status: 'relaunching' });
+ const second = service.applyConfirmedAppUpdateForAgent({ beforeRelaunch });
+ await vi.advanceTimersByTimeAsync(21_000);
+ await expect(second).resolves.toMatchObject({ status: 'relaunching' });
expect(download).toHaveBeenCalledOnce();
expect(spawnProcess).toHaveBeenCalledOnce();
} finally {
@@ -598,9 +599,11 @@ describe('agent-facing managed app update check', () => {
await expect(service.applyConfirmedAppUpdateForAgent({ expectedVersion: '0.0.66', beforeRelaunch, beforeSpawn }))
.resolves.toMatchObject({ status: 'failed', errorCode: 'version_changed', stagedVersion: '0.0.65' });
expect(beforeSpawn).not.toHaveBeenCalled();
- // Adopting it still passes the last gate, where the caller records its restart.
- await expect(service.applyConfirmedAppUpdateForAgent({ expectedVersion: '0.0.65', beforeRelaunch, beforeSpawn }))
- .resolves.toEqual({ status: 'relaunching', targetVersion: '0.0.65' });
+ // Adopting it still passes the last gate, where the caller records its restart,
+ // and waits for that relaunch to settle (here it stays under way: process.exit is mocked).
+ const adopted = service.applyConfirmedAppUpdateForAgent({ expectedVersion: '0.0.65', beforeRelaunch, beforeSpawn });
+ await vi.advanceTimersByTimeAsync(21_000);
+ await expect(adopted).resolves.toEqual({ status: 'relaunching', targetVersion: '0.0.65' });
expect(beforeSpawn).toHaveBeenCalledOnce();
await expect(service.applyConfirmedAppUpdateForAgent({
expectedVersion: '0.0.65', beforeRelaunch, beforeSpawn: () => false,
@@ -613,6 +616,46 @@ describe('agent-facing managed app update check', () => {
}
});
+ it('reports an adopted relaunch that fails afterwards instead of claiming it', async () => {
+ readAutoUpdateSettings.mockReturnValue({ autoRelaunchOnIdle: true });
+ download.mockImplementation(async ({ targetPath }: { targetPath: string }) => {
+ fs.mkdirSync(path.dirname(targetPath), { recursive: true });
+ fs.writeFileSync(targetPath, 'update');
+ return { path: targetPath, size: 123 };
+ });
+ const service = await freshUpdateService('win32');
+ const resourcesPath = path.join(TEST_ROOT, 'resources');
+ fs.mkdirSync(resourcesPath, { recursive: true });
+ fs.writeFileSync(path.join(resourcesPath, 'cindy-updater.exe'), 'updater');
+ const resourcesDescriptor = Object.getOwnPropertyDescriptor(process, 'resourcesPath');
+ Object.defineProperty(process, 'resourcesPath', { value: resourcesPath, configurable: true });
+ const tmpdirSpy = vi.spyOn(os, 'tmpdir').mockReturnValue(TEST_ROOT);
+ const exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);
+ const childListeners = new Map<string, (...args: unknown[]) => void>();
+ spawnProcess.mockImplementationOnce(() => ({
+ unref: vi.fn(),
+ on: vi.fn((event: string, listener: (...args: unknown[]) => void) => { childListeners.set(event, listener); }),
+ }));
+ try {
+ // Idle auto-install starts its own relaunch as soon as 0.0.65 is staged.
+ expect(await service.checkForUpdate()).toBe('ready');
+ await vi.waitFor(() => { expect(childListeners.has('error')).toBe(true); });
+ const adopted = service.applyConfirmedAppUpdateForAgent({
+ expectedVersion: '0.0.65', beforeRelaunch: async () => true, beforeSpawn: () => true,
+ });
+ childListeners.get('error')?.(Object.assign(new Error('spawn denied'), { code: 'EACCES' }));
+ await vi.advanceTimersByTimeAsync(200);
+ await expect(adopted).resolves.toMatchObject({ status: 'failed', errorCode: 'updater_spawn_failed' });
+ expect(exitSpy).not.toHaveBeenCalled();
+ } finally {
+ service.stopUpdateService();
+ tmpdirSpy.mockRestore();
+ exitSpy.mockRestore();
+ if (resourcesDescriptor) Object.defineProperty(process, 'resourcesPath', resourcesDescriptor);
+ else Reflect.deleteProperty(process, 'resourcesPath');
+ }
+ });
+
it('never restarts into the confirmed version while a newer one is superseding it', async () => {
let finishSecond: (() => void) | undefined;
download.mockImplementation(({ targetPath }: { targetPath: string }) => {
diff --git a/apps/desktop/src/main/agent-app-update/__tests__/agentAppUpdateService.test.ts b/apps/desktop/src/main/agent-app-update/__tests__/agentAppUpdateService.test.ts
index 6f9470cf82..8e07b92818 100644
--- a/apps/desktop/src/main/agent-app-update/__tests__/agentAppUpdateService.test.ts
+++ b/apps/desktop/src/main/agent-app-update/__tests__/agentAppUpdateService.test.ts
@@ -20,7 +20,7 @@ function deny(reason?: string): InteractionDecision {
}
function setup(overrides: Partial<AgentAppUpdateDeps> = {}) {
- let marker: AgentAppUpdateMarker | null = null;
+ let records: AgentAppUpdateMarker[] = [];
let autoUpdate = false;
let activeOwner: { ownerId: string } | null = ownerA;
const deps: AgentAppUpdateDeps = {
@@ -49,12 +49,12 @@ function setup(overrides: Partial<AgentAppUpdateDeps> = {}) {
captureOwner: vi.fn(() => activeOwner),
isOwnerCurrent: vi.fn((owner) => activeOwner?.ownerId === owner.ownerId),
marker: {
- write: vi.fn((_owner, value: AgentAppUpdateMarker) => {
- marker = value;
+ list: () => [...records],
+ add: vi.fn((_owner, record: AgentAppUpdateMarker) => {
+ records = [...records, record];
}),
- read: () => marker,
- clear: vi.fn((_owner, requestId: string) => {
- if (marker?.requestId === requestId) marker = null;
+ remove: vi.fn((_owner, requestId: string) => {
+ records = records.filter((record) => record.requestId !== requestId);
}),
},
notify: vi.fn(async () => 'written' as const),
@@ -66,9 +66,11 @@ function setup(overrides: Partial<AgentAppUpdateDeps> = {}) {
return {
deps,
service: createAgentAppUpdateService(deps),
- getMarker: () => marker,
+ /** Latest restart record, or null. */
+ getMarker: () => records.at(-1) ?? null,
+ getRecords: () => [...records],
setMarker: (value: AgentAppUpdateMarker | null) => {
- marker = value;
+ records = value ? [value] : [];
},
switchOwner: (owner: { ownerId: string } | null) => {
activeOwner = owner;
@@ -95,7 +97,7 @@ describe('Agent app update install', () => {
await flush();
expect(deps.requestHostPermission).toHaveBeenCalledOnce();
expect(deps.apply).not.toHaveBeenCalled();
- expect(deps.marker.write).not.toHaveBeenCalled();
+ expect(deps.marker.add).not.toHaveBeenCalled();
const [sessionId, instanceId, card] = vi.mocked(deps.requestHostPermission).mock.calls[0]!;
expect([sessionId, instanceId]).toEqual(['task-1', 'instance-1']);
@@ -126,7 +128,7 @@ describe('Agent app update install', () => {
expect(deps.apply).toHaveBeenCalledWith(expect.objectContaining({ expectedVersion: '0.1.90' }));
const { beforeSpawn } = vi.mocked(deps.apply).mock.calls[0]![0];
expect(beforeSpawn?.()).toBe(true);
- expect(deps.marker.write).toHaveBeenCalledWith(
+ expect(deps.marker.add).toHaveBeenCalledWith(
ownerA,
expect.objectContaining({
sessionId: 'task-1',
@@ -150,7 +152,7 @@ describe('Agent app update install', () => {
const { deps, service } = setup({ requestHostPermission: vi.fn(async () => decision) });
await expect(service.install(caller)).resolves.toMatchObject(expected);
expect(deps.apply).not.toHaveBeenCalled();
- expect(deps.marker.write).not.toHaveBeenCalled();
+ expect(deps.marker.add).not.toHaveBeenCalled();
// The flow is released: a later request raises a fresh card.
await service.install(caller);
expect(deps.requestHostPermission).toHaveBeenCalledTimes(2);
@@ -294,7 +296,7 @@ describe('Agent app update install', () => {
expect(restartAllowed).toBe(false);
expect(harness.deps.notify).not.toHaveBeenCalled();
// No restart happened, so no restart record is left on disk.
- expect(harness.deps.marker.write).not.toHaveBeenCalled();
+ expect(harness.deps.marker.add).not.toHaveBeenCalled();
// The notice waits in memory until the confirming account is active again.
harness.switchOwner(ownerA);
await harness.service.deliverPendingResult();
@@ -385,7 +387,7 @@ describe('Agent app update install', () => {
: { status: 'failed' as const, reason: 'x', errorCode: 'relaunch_cancelled' };
}),
});
- vi.mocked(harness.deps.marker.write).mockImplementation(() => {
+ vi.mocked(harness.deps.marker.add).mockImplementation(() => {
throw new Error('disk full');
});
await harness.service.install(caller);
@@ -394,7 +396,7 @@ describe('Agent app update install', () => {
expect(harness.deps.notify).toHaveBeenCalledOnce();
});
- it('moves an undelivered earlier restart result to memory instead of overwriting it', async () => {
+ it('keeps an undelivered earlier restart record next to a new one instead of overwriting it', async () => {
const harness = setup({
appVersion: () => '0.1.86',
apply: vi.fn(async ({ beforeSpawn }) => {
@@ -412,15 +414,26 @@ describe('Agent app update install', () => {
});
vi.mocked(harness.deps.notify).mockRejectedValueOnce(new Error('database busy'));
await harness.service.deliverPendingResult();
- expect(harness.getMarker()).toMatchObject({ requestId: 'earlier' });
await harness.service.install(caller);
await flush();
+ // Both survive on disk, so the earlier task's result outlives this restart too.
+ expect(harness.getRecords().map((record) => record.requestId)).toEqual([
+ 'earlier',
+ expect.any(String),
+ ]);
expect(harness.getMarker()).toMatchObject({ sessionId: 'task-1' });
- // The earlier task still gets its result from memory.
+ });
+
+ it('delivers every restart record of an earlier process independently', async () => {
+ const harness = setup({ appVersion: () => '0.1.90' });
+ const base = { fromVersion: '0.1.86', targetVersion: '0.1.90', requestedAt: 900, pid: 99 };
+ harness.setMarker({ ...base, requestId: 'a', sessionId: 'task-a' });
+ await harness.deps.marker.add(ownerA, { ...base, requestId: 'b', sessionId: 'task-b' });
+ vi.mocked(harness.deps.notify).mockRejectedValueOnce(new Error('database busy'));
await harness.service.deliverPendingResult();
- expect(vi.mocked(harness.deps.notify).mock.calls.some((call) => call[1] === 'task-0')).toBe(
- true,
- );
+ expect(harness.getRecords().map((record) => record.requestId)).toEqual(['a']);
+ await harness.service.deliverPendingResult();
+ expect(harness.getRecords()).toEqual([]);
});
it('refuses to start when no account is active at confirmation', async () => {
@@ -431,7 +444,7 @@ describe('Agent app update install', () => {
errorCode: 'CALLER_UNAVAILABLE',
});
expect(harness.deps.apply).not.toHaveBeenCalled();
- expect(harness.deps.marker.write).not.toHaveBeenCalled();
+ expect(harness.deps.marker.add).not.toHaveBeenCalled();
});
it('never raises a card without a concrete target version', async () => {
diff --git a/apps/desktop/src/main/agent-app-update/agentAppUpdateService.ts b/apps/desktop/src/main/agent-app-update/agentAppUpdateService.ts
index 1a6b96821c..1b1f7e8d4e 100644
--- a/apps/desktop/src/main/agent-app-update/agentAppUpdateService.ts
+++ b/apps/desktop/src/main/agent-app-update/agentAppUpdateService.ts
@@ -111,11 +111,11 @@ export interface AgentAppUpdateDeps {
captureOwner(): AgentAppUpdateOwner | null;
/** The captured account is still active and no account boundary is pending. */
isOwnerCurrent(owner: AgentAppUpdateOwner): boolean;
+ /** The owner's restart records: one per attempted restart whose result is not yet written back. */
marker: {
- write(owner: AgentAppUpdateOwner, marker: AgentAppUpdateMarker): void;
- read(owner: AgentAppUpdateOwner): AgentAppUpdateMarker | null;
- /** Removes the marker only if it still belongs to `requestId` (a newer install keeps its own). */
- clear(owner: AgentAppUpdateOwner, requestId: string): void;
+ list(owner: AgentAppUpdateOwner): AgentAppUpdateMarker[];
+ add(owner: AgentAppUpdateOwner, record: AgentAppUpdateMarker): void;
+ remove(owner: AgentAppUpdateOwner, requestId: string): void;
};
/**
* Persist a visible host notice in the owner's task (idempotent per clientId).
@@ -142,6 +142,7 @@ const UNDELIVERED_REASONS = new Set([
]);
const MARKER_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
const MAX_PENDING_NOTICES = 20;
+export const MAX_RESTART_RECORDS = 20;
interface PendingNotice {
owner: AgentAppUpdateOwner;
@@ -293,49 +294,41 @@ export function createAgentAppUpdateService(deps: AgentAppUpdateDeps) {
};
/**
- * The disk marker exists only for a restart that was about to happen: it is
- * written at the last gate before the updater spawns, and read back by the
- * next process. Cleared once its result is persisted or its task is gone.
+ * Restart records exist only for restarts that were about to happen: each is
+ * added at the last gate before the updater spawns and read back by a later
+ * process. Records never replace each other; each is removed on its own once
+ * its result is persisted, its task is gone, or it is stale.
*/
- const deliverRestartResult = async (owner: AgentAppUpdateOwner) => {
- const marker = deps.marker.read(owner);
- // Same process: the restart is still pending (or is being reported as failed).
- if (!marker || marker.pid === deps.pid) return;
- if (deps.now() - marker.requestedAt > MARKER_MAX_AGE_MS) {
- deps.marker.clear(owner, marker.requestId);
- return;
- }
- try {
- await deps.notify(
- owner,
- marker.sessionId,
- `agent-app-update:${marker.requestId}`,
- restartMessage(marker),
- );
- } catch (error) {
- deps.logger?.warn?.('agent app update result notice failed; will retry', {
- error: String(error),
- });
- return;
+ const deliverRestartResults = async (owner: AgentAppUpdateOwner) => {
+ for (const record of deps.marker.list(owner)) {
+ // Same process: that restart has not happened (yet).
+ if (record.pid === deps.pid) continue;
+ if (deps.now() - record.requestedAt > MARKER_MAX_AGE_MS) {
+ deps.marker.remove(owner, record.requestId);
+ continue;
+ }
+ try {
+ await deps.notify(
+ owner,
+ record.sessionId,
+ `agent-app-update:${record.requestId}`,
+ restartMessage(record),
+ );
+ } catch (error) {
+ deps.logger?.warn?.('agent app update result notice failed; will retry', {
+ error: String(error),
+ });
+ continue;
+ }
+ deps.marker.remove(owner, record.requestId);
}
- deps.marker.clear(owner, marker.requestId);
};
/** Last gate before the updater spawns (synchronous): owner check, then the restart record. */
const recordRestart = (owner: AgentAppUpdateOwner, request: AgentAppUpdateMarker): boolean => {
if (!deps.isOwnerCurrent(owner)) return false;
- const previous = deps.marker.read(owner);
- if (previous && previous.requestId !== request.requestId) {
- // An earlier restart's result not yet written back moves to memory, not overwritten silently.
- queueNotice({
- owner,
- sessionId: previous.sessionId,
- clientId: `agent-app-update:${previous.requestId}`,
- message: restartMessage(previous),
- });
- }
try {
- deps.marker.write(owner, request);
+ deps.marker.add(owner, request);
return true;
} catch (error) {
// Without the record the outcome could not be reported after the restart.
@@ -376,7 +369,7 @@ export function createAgentAppUpdateService(deps: AgentAppUpdateDeps) {
flow = null;
}
// A spawn that failed after the record was written did not restart anything.
- deps.marker.clear(owner, request.requestId);
+ deps.marker.remove(owner, request.requestId);
queueNotice({
owner,
sessionId: request.sessionId,
@@ -517,7 +510,7 @@ export function createAgentAppUpdateService(deps: AgentAppUpdateDeps) {
*/
async deliverPendingResult(): Promise<void> {
const owner = deps.captureOwner();
- if (owner) await deliverRestartResult(owner);
+ if (owner) await deliverRestartResults(owner);
await flushNotices();
},
};
diff --git a/apps/desktop/src/main/agent-app-update/index.ts b/apps/desktop/src/main/agent-app-update/index.ts
index e6cd0cb6d9..9984e238f2 100644
--- a/apps/desktop/src/main/agent-app-update/index.ts
+++ b/apps/desktop/src/main/agent-app-update/index.ts
@@ -40,6 +40,7 @@ import {
type AgentAppUpdateMarker,
type AgentAppUpdateOwner,
type AgentAppUpdateService,
+ MAX_RESTART_RECORDS,
} from './agentAppUpdateService.js';
/** Owner binding: broadcast scope for current-ness checks and the owner's own marker path. */
@@ -88,31 +89,59 @@ function assertOwnerCurrent(owner: AgentAppUpdateOwner): void {
throw new Error('The account that confirmed the update is no longer active');
}
-function parseMarker(raw: string | null): AgentAppUpdateMarker | null {
- if (!raw) return null;
+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 {
- const value = JSON.parse(raw) as Partial<AgentAppUpdateMarker>;
- if (
- typeof value.requestId !== 'string' ||
- typeof value.sessionId !== 'string' ||
- typeof value.fromVersion !== 'string' ||
- typeof value.requestedAt !== 'number' ||
- typeof value.pid !== 'number'
- )
- return null;
- return {
- requestId: value.requestId,
- sessionId: value.sessionId,
- fromVersion: value.fromVersion,
- ...(typeof value.targetVersion === 'string' ? { targetVersion: value.targetVersion } : {}),
- requestedAt: value.requestedAt,
- pid: value.pid,
- };
+ 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 {
- return null;
+ 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;
@@ -135,35 +164,22 @@ function getService(): AgentAppUpdateService {
captureOwner,
isOwnerCurrent,
marker: {
- write: (owner, marker) => {
+ list: (owner) => readRecords(markerPathOf(owner)),
+ add: (owner, record) => {
const file = markerPathOf(owner);
- fs.mkdirSync(path.dirname(file), { recursive: true });
- atomicWriteFileSync(file, JSON.stringify(marker));
+ // 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));
},
- read: (owner) => {
- try {
- return parseMarker(readAtomicFileSync(markerPathOf(owner)));
- } catch (error) {
- log.warn('agent app update marker read failed', { error: String(error) });
- return null;
- }
- },
- clear: (owner, requestId) => {
+ remove: (owner, requestId) => {
const file = markerPathOf(owner);
- let current: AgentAppUpdateMarker | null = null;
+ const records = readRecords(file);
+ const remaining = records.filter((record) => record.requestId !== requestId);
+ if (remaining.length === records.length) return;
try {
- current = parseMarker(readAtomicFileSync(file));
- } catch {
- current = null;
- }
- // A newer install's marker is not ours to remove.
- if (current && current.requestId !== requestId) return;
- for (const target of [file, `${file}.bak`]) {
- try {
- fs.rmSync(target, { force: true });
- } catch (error) {
- log.warn('agent app update marker cleanup failed', { error: String(error) });
- }
+ writeRecords(file, remaining);
+ } catch (error) {
+ log.warn('agent app update marker update failed', { error: String(error) });
}
},
},
diff --git a/apps/desktop/src/main/updateService.ts b/apps/desktop/src/main/updateService.ts
index 1f7673ad13..3af9135601 100644
--- a/apps/desktop/src/main/updateService.ts
+++ b/apps/desktop/src/main/updateService.ts
@@ -2165,6 +2165,8 @@ export async function checkAppUpdateForAgent(): Promise<{
/** Longer than the Windows / Linux updater spawn timeout (5 s). */
const AGENT_RELAUNCH_SETTLE_MS = 10_000;
+/** An adopted relaunch may still be in its Subagent reclaim (≈6 s) before that spawn window. */
+const AGENT_ADOPTED_RELAUNCH_SETTLE_MS = 20_000;
const AGENT_UPDATE_FAILURE_REASONS: Record<Exclude<CheckForUpdateResult, 'ready'>, string> = {
manifest_failed: '无法读取当前渠道的更新信息。',
@@ -2212,17 +2214,40 @@ export async function applyConfirmedAppUpdateForAgent(options: {
const relaunchCancelled: AgentConfirmedAppUpdateResult = {
status: 'failed', reason: '更新已下载,但本次没有重启。', errorCode: 'relaunch_cancelled',
};
+ /**
+ * Wait until a relaunch settles: success exits the process (Windows / Linux
+ * from their spawn callbacks), failure clears the flags in
+ * handleApplyFailure() or an early refusal. Whatever is still relaunching at
+ * the deadline is reported as relaunching.
+ */
+ const awaitRelaunchOutcome = async (
+ targetVersion: string | undefined,
+ timeoutMs: number,
+ ): Promise<AgentConfirmedAppUpdateResult> => {
+ const deadline = Date.now() + timeoutMs;
+ while ((isRelaunching || autoRelaunchInProgress) && Date.now() < deadline) {
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ }
+ if (isRelaunching || autoRelaunchInProgress) return { status: 'relaunching', targetVersion };
+ return {
+ status: 'failed',
+ reason: '更新器没有启动,Cindy 未重启。',
+ errorCode: lastErrorCode ?? 'relaunch_not_started',
+ };
+ };
// A relaunch already under way (Settings banner or idle auto-install) counts
- // as this install only for the confirmed version, and only after the same
- // last gate a spawn of our own would pass (the caller records its restart there).
- const adoptRelaunchUnderWay = (): AgentConfirmedAppUpdateResult =>
- versionChanged()
- ?? (options.beforeSpawn?.() === false
- ? relaunchCancelled
- : { status: 'relaunching', targetVersion: readyVersion });
+ // as this install only for the confirmed version, only after the same last
+ // gate a spawn of our own would pass (the caller records its restart there),
+ // and only once that relaunch has actually settled.
+ const adoptRelaunchUnderWay = async (): Promise<AgentConfirmedAppUpdateResult> => {
+ const changed = versionChanged();
+ if (changed) return changed;
+ if (options.beforeSpawn?.() === false) return relaunchCancelled;
+ return awaitRelaunchOutcome(readyVersion, AGENT_ADOPTED_RELAUNCH_SETTLE_MS);
+ };
const unsupported = agentUpdateUnsupportedReason();
if (unsupported) return { status: 'failed', reason: unsupported, errorCode: 'unsupported' };
- if (isRelaunching || autoRelaunchInProgress) return adoptRelaunchUnderWay();
+ if (isRelaunching || autoRelaunchInProgress) return await adoptRelaunchUnderWay();
if (currentStatus !== 'ready') {
const result = await checkForUpdate();
if (result !== 'ready') {
@@ -2232,7 +2257,7 @@ export async function applyConfirmedAppUpdateForAgent(options: {
const changedAfterDownload = versionChanged();
if (changedAfterDownload) return changedAfterDownload;
if (!await options.beforeRelaunch()) return relaunchCancelled;
- if (isRelaunching || autoRelaunchInProgress) return adoptRelaunchUnderWay();
+ if (isRelaunching || autoRelaunchInProgress) return await adoptRelaunchUnderWay();
// A background check may have superseded the staged patch during the wait.
const changedBeforeRelaunch = versionChanged();
if (changedBeforeRelaunch) return changedBeforeRelaunch;
@@ -2252,19 +2277,14 @@ export async function applyConfirmedAppUpdateForAgent(options: {
});
if (cancelledBeforeSpawn) return cancelledBeforeSpawn;
// macOS exits inside the call. Windows and Linux return with `isRelaunching`
- // still set and settle within their 5 s spawn timeout: success exits via
- // forceQuit(), failure clears the flag in handleApplyFailure(). Wait for that
- // outcome so a failed spawn is reported now rather than after a later restart.
- const settleDeadline = Date.now() + AGENT_RELAUNCH_SETTLE_MS;
- while (isRelaunching && process.platform !== 'darwin' && Date.now() < settleDeadline) {
- await new Promise((resolve) => setTimeout(resolve, 100));
- }
- if (isRelaunching) return { status: 'relaunching', targetVersion };
- return {
- status: 'failed',
- reason: '更新器没有启动,Cindy 未重启。',
- errorCode: lastErrorCode ?? 'relaunch_not_started',
- };
+ // still set and settle within their 5 s spawn timeout; wait for that outcome
+ // so a failed spawn is reported now rather than after a later restart.
+ if (process.platform === 'darwin') {
+ return isRelaunching
+ ? { status: 'relaunching', targetVersion }
+ : { status: 'failed', reason: '更新器没有启动,Cindy 未重启。', errorCode: lastErrorCode ?? 'relaunch_not_started' };
+ }
+ return awaitRelaunchOutcome(targetVersion, AGENT_RELAUNCH_SETTLE_MS);
}
/** Effective idle auto-install switch (Settings → About), shared with the Agent tools. */
diff --git a/docs/product-rules/agent-app-update.md b/docs/product-rules/agent-app-update.md
index dd17fbc5ff..c80c48e11a 100644
--- a/docs/product-rules/agent-app-update.md
+++ b/docs/product-rules/agent-app-update.md
@@ -24,7 +24,9 @@ Agent 只能反复引导用户去点「检查更新」;那次收紧的起因
- **真的要重启时**:更新器启动前的最后一道检查里,在账号私有目录写一份重启标记(写不进就不重启)。
新版本启动、该账号数据库就绪后,把结果(新版本号或「仍是旧版本」)作为一条普通助手消息写回发起任务,
桌面和手机重连后都能看到;写入暂时失败保留标记下次再写(按 clientId 去重),任务已不存在或超过
- 7 天才丢弃。标记里还有上一次没写回的结果时,先转成下面的内存通知再写新标记,不静默覆盖。
+ 7 天才丢弃。标记文件按请求逐条保存重启记录,新记录追加而不覆盖,每条各自写回、各自清除。
+ 设置页或空闲自动安装已经在重启时,只有版本一致、通过同一道最后检查,并且等那次重启真正落定
+ (启动成功即退出,失败则当场写回原因)才算本次安装。
- **没有重启时**(下载失败、版本变化、切换账号取消、更新器没启动等):不写磁盘,按错误码生成本地化原因
放进内存待写回列表,立即写回;写不进或原账号不在时保留,在该账号下次就绪或下次发起更新时重试。
这类通知不阻止发起新的更新;进程退出时未写回的会丢失(可接受,不为此新增持久化)。