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。

refactor(update): 重启标记只在真正要重启时写,未重启的结果改为内存通知

Dashad2a51cad9bb
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 df2300edce..65385a54eb 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
@@ -293,11 +293,9 @@ describe('Agent app update install', () => {
await flush();
expect(restartAllowed).toBe(false);
expect(harness.deps.notify).not.toHaveBeenCalled();
- // The failure stays in the confirming account's marker until that account is back.
- expect(harness.deps.marker.write).toHaveBeenLastCalledWith(
- ownerA,
- expect.objectContaining({ failure: { errorCode: 'relaunch_cancelled' } }),
- );
+ // No restart happened, so no restart record is left on disk.
+ expect(harness.deps.marker.write).not.toHaveBeenCalled();
+ // The notice waits in memory until the confirming account is active again.
harness.switchOwner(ownerA);
await harness.service.deliverPendingResult();
expect(harness.deps.notify).toHaveBeenCalledOnce();
@@ -307,30 +305,93 @@ describe('Agent app update install', () => {
expect.stringMatching(/^agent-app-update:/),
expect.stringContaining('update.agentInstall.reasons.notRestarted'),
);
- expect(harness.getMarker()).toBeNull();
});
- it('keeps an in-process failure until its notice is persisted', async () => {
+ it('retries an in-process failure notice without blocking a new install', async () => {
const notify = vi
.fn<AgentAppUpdateDeps['notify']>()
.mockRejectedValueOnce(new Error('database busy'))
- .mockResolvedValueOnce('written');
- const harness = setup({
- notify,
- apply: vi.fn(async () => ({
- status: 'failed' as const,
- reason: 'x',
- errorCode: 'download_failed',
- })),
- });
+ .mockResolvedValue('written');
+ const apply = vi
+ .fn<AgentAppUpdateDeps['apply']>()
+ .mockResolvedValueOnce({ status: 'failed', reason: 'x', errorCode: 'download_failed' })
+ .mockResolvedValue({ status: 'relaunching' });
+ const harness = setup({ notify, apply });
await harness.service.install(caller);
await flush();
- expect(harness.getMarker()).toMatchObject({ failure: { errorCode: 'download_failed' } });
- // Same process: a recorded failure is deliverable without a restart.
- await harness.service.deliverPendingResult();
+ expect(notify).toHaveBeenCalledOnce();
+ expect(harness.getMarker()).toBeNull();
+ // The next install request first retries the pending notice, then proceeds.
+ await expect(harness.service.install(caller)).resolves.toMatchObject({ status: 'started' });
expect(notify).toHaveBeenCalledTimes(2);
expect(notify.mock.calls[0]![2]).toBe(notify.mock.calls[1]![2]);
+ expect(harness.deps.requestHostPermission).toHaveBeenCalledTimes(2);
+ });
+
+ it('writes the restart record only at the last gate, and clears it if the spawn then fails', async () => {
+ const harness = setup({
+ apply: vi.fn(async ({ beforeRelaunch, beforeSpawn }) => {
+ await beforeRelaunch();
+ expect(harness.getMarker()).toBeNull();
+ expect(beforeSpawn?.()).toBe(true);
+ expect(harness.getMarker()).toMatchObject({ sessionId: 'task-1', targetVersion: '0.1.90' });
+ return { status: 'failed' as const, reason: 'x', errorCode: 'updater_spawn_failed' };
+ }),
+ });
+ await harness.service.install(caller);
+ await flush();
expect(harness.getMarker()).toBeNull();
+ expect(vi.mocked(harness.deps.notify).mock.calls[0]![3]).toContain(
+ 'update.agentInstall.reasons.updaterNotStarted',
+ );
+ });
+
+ it('does not restart when the restart record cannot be written', async () => {
+ let allowed: boolean | undefined;
+ const harness = setup({
+ apply: vi.fn(async ({ beforeSpawn }) => {
+ allowed = beforeSpawn?.();
+ return allowed
+ ? { status: 'relaunching' as const }
+ : { status: 'failed' as const, reason: 'x', errorCode: 'relaunch_cancelled' };
+ }),
+ });
+ vi.mocked(harness.deps.marker.write).mockImplementation(() => {
+ throw new Error('disk full');
+ });
+ await harness.service.install(caller);
+ await flush();
+ expect(allowed).toBe(false);
+ expect(harness.deps.notify).toHaveBeenCalledOnce();
+ });
+
+ it('moves an undelivered earlier restart result to memory instead of overwriting it', async () => {
+ const harness = setup({
+ appVersion: () => '0.1.86',
+ apply: vi.fn(async ({ beforeSpawn }) => {
+ beforeSpawn?.();
+ return { status: 'relaunching' as const };
+ }),
+ });
+ harness.setMarker({
+ requestId: 'earlier',
+ sessionId: 'task-0',
+ fromVersion: '0.1.80',
+ targetVersion: '0.1.86',
+ requestedAt: 900,
+ pid: 99,
+ });
+ 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();
+ expect(harness.getMarker()).toMatchObject({ sessionId: 'task-1' });
+ // The earlier task still gets its result from memory.
+ await harness.service.deliverPendingResult();
+ expect(vi.mocked(harness.deps.notify).mock.calls.some((call) => call[1] === 'task-0')).toBe(
+ true,
+ );
});
it('refuses to start when no account is active at confirmation', async () => {
@@ -353,51 +414,6 @@ describe('Agent app update install', () => {
expect(deps.apply).not.toHaveBeenCalled();
});
- it('delivers a pending earlier result before starting, and never overwrites one it cannot deliver', async () => {
- const earlier = {
- requestId: 'earlier',
- sessionId: 'task-0',
- fromVersion: '0.1.80',
- targetVersion: '0.1.85',
- requestedAt: 900,
- pid: 100,
- failure: { errorCode: 'download_failed' },
- };
- const notify = vi
- .fn<AgentAppUpdateDeps['notify']>()
- .mockRejectedValueOnce(new Error('database busy'))
- .mockResolvedValue('written');
- const harness = setup({ notify });
- harness.setMarker(earlier);
- await expect(harness.service.install(caller)).resolves.toMatchObject({
- ok: false,
- errorCode: 'PREVIOUS_RESULT_PENDING',
- });
- expect(harness.deps.requestHostPermission).not.toHaveBeenCalled();
- expect(harness.getMarker()).toMatchObject({ requestId: 'earlier' });
- // Next attempt: the earlier result is written first, then the new install proceeds.
- await expect(harness.service.install(caller)).resolves.toMatchObject({ status: 'started' });
- expect(notify.mock.calls[1]![1]).toBe('task-0');
- expect(harness.deps.marker.write).toHaveBeenLastCalledWith(
- ownerA,
- expect.objectContaining({ sessionId: 'task-1' }),
- );
- });
-
- it('clears only the marker of the request it delivered', async () => {
- const harness = setup({
- apply: vi.fn(async () => ({
- status: 'failed' as const,
- reason: 'x',
- errorCode: 'not_ready',
- })),
- });
- await harness.service.install(caller);
- await flush();
- const written = vi.mocked(harness.deps.marker.write).mock.calls.at(-1)![1];
- expect(harness.deps.marker.clear).toHaveBeenCalledWith(ownerA, written.requestId);
- });
-
it('mentions the Linux password prompt only on Linux', async () => {
const { deps, service } = setup({ platform: 'linux', countOtherRunningTasks: vi.fn(() => 0) });
await service.install(caller);
diff --git a/apps/desktop/src/main/agent-app-update/agentAppUpdateService.ts b/apps/desktop/src/main/agent-app-update/agentAppUpdateService.ts
index 2e77318c69..d1e1a3f5a1 100644
--- a/apps/desktop/src/main/agent-app-update/agentAppUpdateService.ts
+++ b/apps/desktop/src/main/agent-app-update/agentAppUpdateService.ts
@@ -62,10 +62,8 @@ export interface AgentAppUpdateMarker {
fromVersion: string;
targetVersion?: string;
requestedAt: number;
- /** Process that wrote the marker; a same-process read is not a restart. */
+ /** Process that attempted the restart; a same-process read means it has not happened. */
pid: number;
- /** Set when the install ended without a restart; reportable from any process. */
- failure?: { errorCode?: string; stagedVersion?: string };
}
type PermissionRequest = Extract<InteractionRequest, { kind: 'permission' }>;
@@ -143,6 +141,14 @@ const UNDELIVERED_REASONS = new Set([
'duplicate_request_id',
]);
const MARKER_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
+const MAX_PENDING_NOTICES = 20;
+
+interface PendingNotice {
+ owner: AgentAppUpdateOwner;
+ sessionId: string;
+ clientId: string;
+ message: string;
+}
const UPDATABLE_STATUSES = new Set(['available', 'ready', 'downloading']);
const HINT_SESSION_LIMIT = 500;
@@ -231,44 +237,76 @@ export function createAgentAppUpdateService(deps: AgentAppUpdateDeps) {
};
};
- const resultMessage = (marker: AgentAppUpdateMarker): string => {
+ /** Outcome after a restart: compare the running version with the one before it. */
+ const restartMessage = (marker: AgentAppUpdateMarker): string => {
const version = deps.appVersion();
- if (!marker.failure && deps.compareVersions(version, marker.fromVersion) === 'newer') {
- return text('update.agentInstall.succeeded', { version, from: marker.fromVersion });
- }
- const reasonKey = marker.failure
- ? (FAILURE_REASON_KEYS[marker.failure.errorCode ?? ''] ?? 'generic')
- : null;
- return [
- text('update.agentInstall.failed', { version }),
- reasonKey
- ? text(`update.agentInstall.reasons.${reasonKey}`, {
- version: marker.failure?.stagedVersion ?? '',
- confirmed: marker.targetVersion ?? '',
- })
- : '',
+ return deps.compareVersions(version, marker.fromVersion) === 'newer'
+ ? text('update.agentInstall.succeeded', { version, from: marker.fromVersion })
+ : [
+ text('update.agentInstall.failed', { version }),
+ text('update.agentInstall.retryHint'),
+ ].join(' ');
+ };
+
+ const failureMessage = (
+ request: AgentAppUpdateMarker,
+ failure: { errorCode?: string; stagedVersion?: string },
+ ): string =>
+ [
+ text('update.agentInstall.failed', { version: deps.appVersion() }),
+ text(
+ `update.agentInstall.reasons.${FAILURE_REASON_KEYS[failure.errorCode ?? ''] ?? 'generic'}`,
+ {
+ version: failure.stagedVersion ?? '',
+ confirmed: request.targetVersion ?? '',
+ },
+ ),
text('update.agentInstall.retryHint'),
- ]
- .filter(Boolean)
- .join(' ');
+ ].join(' ');
+
+ /**
+ * Outcomes produced without a restart live only in memory: they are retried
+ * on every owner-ready delivery and on the next install request, and only
+ * while their own account is active. Nothing here blocks a new install.
+ */
+ const pendingNotices: PendingNotice[] = [];
+ const queueNotice = (notice: PendingNotice) => {
+ pendingNotices.push(notice);
+ if (pendingNotices.length > MAX_PENDING_NOTICES) pendingNotices.shift();
+ };
+ const flushNotices = async () => {
+ for (const notice of [...pendingNotices]) {
+ // Never write into whichever account replaced the one that confirmed.
+ if (!deps.isOwnerCurrent(notice.owner)) continue;
+ try {
+ await deps.notify(notice.owner, notice.sessionId, notice.clientId, notice.message);
+ } catch (error) {
+ deps.logger?.warn?.('agent app update notice failed; will retry', { error: String(error) });
+ continue;
+ }
+ pendingNotices.splice(pendingNotices.indexOf(notice), 1);
+ }
};
/**
- * The only path that writes a result and clears its marker. The marker is
- * removed only after the message is persisted or its task is gone; a
- * transient failure (or a different active account) keeps it for the next
- * owner-ready delivery.
+ * 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.
*/
- const deliver = async (owner: AgentAppUpdateOwner, marker: AgentAppUpdateMarker) => {
- // Never write into whichever account replaced the one that confirmed.
- if (!deps.isOwnerCurrent(owner)) return;
- let outcome: AgentAppUpdateNotifyOutcome;
+ 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 {
- outcome = await deps.notify(
+ await deps.notify(
owner,
marker.sessionId,
`agent-app-update:${marker.requestId}`,
- resultMessage(marker),
+ restartMessage(marker),
);
} catch (error) {
deps.logger?.warn?.('agent app update result notice failed; will retry', {
@@ -277,60 +315,48 @@ export function createAgentAppUpdateService(deps: AgentAppUpdateDeps) {
return;
}
deps.marker.clear(owner, marker.requestId);
- deps.logger?.info?.('agent app update result delivered', {
- failed: Boolean(marker.failure),
- outcome,
- });
};
- /** Persist the failure into the owner's marker first, then try to deliver it. */
- const recordFailure = async (
- owner: AgentAppUpdateOwner,
- marker: AgentAppUpdateMarker,
- failure: { errorCode?: string; stagedVersion?: string },
- ) => {
- const failed: AgentAppUpdateMarker = {
- ...marker,
- failure: {
- ...(failure.errorCode ? { errorCode: failure.errorCode } : {}),
- ...(failure.stagedVersion ? { stagedVersion: failure.stagedVersion } : {}),
- },
- };
+ /** 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, failed);
+ deps.marker.write(owner, request);
+ return true;
} catch (error) {
- deps.logger?.warn?.('agent app update failure marker write failed', { error: String(error) });
- }
- await deliver(owner, failed);
- };
-
- /** Deliver the owner's recorded result if it is reportable now. */
- const deliverPending = async (owner: AgentAppUpdateOwner) => {
- const marker = deps.marker.read(owner);
- // Without a recorded failure, a same-process marker means no restart yet.
- if (!marker || (!marker.failure && marker.pid === deps.pid)) return;
- if (deps.now() - marker.requestedAt > MARKER_MAX_AGE_MS) {
- deps.marker.clear(owner, marker.requestId);
- return;
+ // Without the record the outcome could not be reported after the restart.
+ deps.logger?.warn?.('agent app update marker write failed; not restarting', {
+ error: String(error),
+ });
+ return false;
}
- await deliver(owner, marker);
};
const runInstall = async (
caller: AgentAppUpdateCaller,
owner: AgentAppUpdateOwner,
- marker: AgentAppUpdateMarker,
+ request: AgentAppUpdateMarker,
) => {
+ let failure: { errorCode?: string; stagedVersion?: string };
try {
const result = await deps.apply({
- ...(marker.targetVersion ? { expectedVersion: marker.targetVersion } : {}),
+ expectedVersion: request.targetVersion,
beforeRelaunch: async () => {
await deps.waitForCallerTurnToEnd(caller);
// Logout or an account switch cancels the restart; the patch stays staged.
return deps.isOwnerCurrent(owner);
},
- // Re-checked again after the updater's Subagent reclaim, right before spawn.
- beforeSpawn: () => deps.isOwnerCurrent(owner),
+ beforeSpawn: () => recordRestart(owner, request),
});
// A relaunch ends this process; the next start reports from the marker.
if (result.status === 'relaunching') return;
@@ -338,13 +364,22 @@ export function createAgentAppUpdateService(deps: AgentAppUpdateDeps) {
errorCode: result.errorCode,
reason: result.reason,
});
- await recordFailure(owner, marker, result);
+ failure = result;
} catch (error) {
deps.logger?.warn?.('agent app update failed', { error: String(error) });
- await recordFailure(owner, marker, {});
+ failure = {};
} finally {
flow = null;
}
+ // A spawn that failed after the record was written did not restart anything.
+ deps.marker.clear(owner, request.requestId);
+ queueNotice({
+ owner,
+ sessionId: request.sessionId,
+ clientId: `agent-app-update:${request.requestId}`,
+ message: failureMessage(request, failure),
+ });
+ await flushNotices();
};
return {
@@ -384,18 +419,7 @@ export function createAgentAppUpdateService(deps: AgentAppUpdateDeps) {
flow = { kind: 'confirming' };
let started = false;
try {
- // A previous result not yet written back must not be overwritten by this install.
- const currentOwner = deps.captureOwner();
- if (currentOwner) {
- await deliverPending(currentOwner);
- if (deps.marker.read(currentOwner)) {
- return {
- ok: false,
- errorCode: 'PREVIOUS_RESULT_PENDING',
- message: '上一次更新的结果还没写回任务,暂不发起新的更新;请稍后再试。',
- };
- }
- }
+ await flushNotices();
const check = await deps.check();
if (!UPDATABLE_STATUSES.has(check.status)) return { ...check };
// Every confirmation names a concrete version; the updater installs only that one.
@@ -418,7 +442,7 @@ export function createAgentAppUpdateService(deps: AgentAppUpdateDeps) {
if (current !== 'owner') return ownerTurnRequired();
const owner = deps.captureOwner();
if (!owner) return callerUnavailable();
- const marker: AgentAppUpdateMarker = {
+ const request: AgentAppUpdateMarker = {
requestId: randomUUID(),
sessionId: caller.sessionId,
fromVersion: from,
@@ -426,10 +450,9 @@ export function createAgentAppUpdateService(deps: AgentAppUpdateDeps) {
requestedAt: deps.now(),
pid: deps.pid,
};
- deps.marker.write(owner, marker);
flow = { kind: 'installing', targetVersion: to };
started = true;
- void runInstall(caller, owner, marker);
+ void runInstall(caller, owner, request);
return {
status: 'started',
currentVersion: from,
@@ -490,7 +513,8 @@ export function createAgentAppUpdateService(deps: AgentAppUpdateDeps) {
*/
async deliverPendingResult(): Promise<void> {
const owner = deps.captureOwner();
- if (owner) await deliverPending(owner);
+ if (owner) await deliverRestartResult(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 5adc3bf1d2..e6cd0cb6d9 100644
--- a/apps/desktop/src/main/agent-app-update/index.ts
+++ b/apps/desktop/src/main/agent-app-update/index.ts
@@ -107,18 +107,6 @@ function parseMarker(raw: string | null): AgentAppUpdateMarker | null {
...(typeof value.targetVersion === 'string' ? { targetVersion: value.targetVersion } : {}),
requestedAt: value.requestedAt,
pid: value.pid,
- ...(value.failure && typeof value.failure === 'object'
- ? {
- failure: {
- ...(typeof value.failure.errorCode === 'string'
- ? { errorCode: value.failure.errorCode }
- : {}),
- ...(typeof value.failure.stagedVersion === 'string'
- ? { stagedVersion: value.failure.stagedVersion }
- : {}),
- },
- }
- : {}),
};
} catch {
return null;
diff --git a/docs/product-rules/agent-app-update.md b/docs/product-rules/agent-app-update.md
index ab39672d33..dd17fbc5ff 100644
--- a/docs/product-rules/agent-app-update.md
+++ b/docs/product-rules/agent-app-update.md
@@ -20,10 +20,14 @@ Agent 只能反复引导用户去点「检查更新」;那次收紧的起因
渠道期间换了新版本、或有更新的版本正在下载覆盖时(与内置横幅一致,不在 superseding 时重启)不安装,提示重新发起。安装绑定确认时的账号:退出或切换账号会取消重启,
标记与结果消息只写回该账号,绝不写进后来的账号。拒绝、超时或卡片未送达都不下载、
不重启。同一时刻只有一个安装请求;确认卡等待中或已开始安装时再次调用直接返回当前状态。
-- 重启前在账号私有目录写一份标记;新版本启动、该账号数据库就绪后,把结果(新版本号或「仍是旧版本」)
- 作为一条普通助手消息写回发起任务,桌面和手机重连后都能看到。写入暂时失败时保留标记、下次就绪再写
- (按 clientId 去重);任务已不存在才丢弃。未重启就失败时先把失败原因写进标记再写回任务,
- 写回失败或期间切换了账号同样保留,等该账号下次就绪时补写。上一次的结果还没写回时不发起新安装(先尝试补写,仍失败则提示稍后再试),清除标记只清自己这次请求的。
+- 结果写回分两种,互不阻塞:
+ - **真的要重启时**:更新器启动前的最后一道检查里,在账号私有目录写一份重启标记(写不进就不重启)。
+ 新版本启动、该账号数据库就绪后,把结果(新版本号或「仍是旧版本」)作为一条普通助手消息写回发起任务,
+ 桌面和手机重连后都能看到;写入暂时失败保留标记下次再写(按 clientId 去重),任务已不存在或超过
+ 7 天才丢弃。标记里还有上一次没写回的结果时,先转成下面的内存通知再写新标记,不静默覆盖。
+ - **没有重启时**(下载失败、版本变化、切换账号取消、更新器没启动等):不写磁盘,按错误码生成本地化原因
+ 放进内存待写回列表,立即写回;写不进或原账号不在时保留,在该账号下次就绪或下次发起更新时重试。
+ 这类通知不阻止发起新的更新;进程退出时未写回的会丢失(可接受,不为此新增持久化)。
- 自动更新开关写入既有 `auto-update-settings-store`(用户显式 override),与设置页同一开关。
`check_app_update` 在有可安装更新且开关未开时返回一次 `autoUpdateHint`,同一任务内只提示一次。
- 不支持的构建与安装环境(开发版、个人版、版本无关包、未移入「应用程序」、Linux 非受管安装、