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): 下载中报告实际下载的版本;未写回的结果不被新安装覆盖

Dash0b93b31b183f
diff --git a/apps/desktop/src/main/__tests__/updateService.test.ts b/apps/desktop/src/main/__tests__/updateService.test.ts
index 6507364762..04fbc6974f 100644
--- a/apps/desktop/src/main/__tests__/updateService.test.ts
+++ b/apps/desktop/src/main/__tests__/updateService.test.ts
@@ -495,7 +495,7 @@ describe('agent-facing managed app update check', () => {
}
});
- it('reports the version being downloaded instead of an unknown target', async () => {
+ it('reports the version actually being downloaded, not the latest manifest', async () => {
let finishDownload!: () => void;
download.mockImplementation(({ targetPath }: { targetPath: string }) => new Promise((resolve) => {
finishDownload = () => {
@@ -508,6 +508,8 @@ describe('agent-facing managed app update check', () => {
try {
const staging = service.checkForUpdate();
await vi.waitFor(() => { expect(download).toHaveBeenCalledOnce(); });
+ // The channel moves on mid-download; the in-flight download is still 0.0.65.
+ fetchManifest.mockResolvedValue(updateManifest('0.0.66'));
await expect(service.checkAppUpdateForAgent()).resolves.toMatchObject({
status: 'downloading', targetVersion: '0.0.65',
});
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 c5192ca74e..df2300edce 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
@@ -53,8 +53,8 @@ function setup(overrides: Partial<AgentAppUpdateDeps> = {}) {
marker = value;
}),
read: () => marker,
- clear: vi.fn(() => {
- marker = null;
+ clear: vi.fn((_owner, requestId: string) => {
+ if (marker?.requestId === requestId) marker = null;
}),
},
notify: vi.fn(async () => 'written' as const),
@@ -353,6 +353,51 @@ 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 56f21e78f2..2e77318c69 100644
--- a/apps/desktop/src/main/agent-app-update/agentAppUpdateService.ts
+++ b/apps/desktop/src/main/agent-app-update/agentAppUpdateService.ts
@@ -116,7 +116,8 @@ export interface AgentAppUpdateDeps {
marker: {
write(owner: AgentAppUpdateOwner, marker: AgentAppUpdateMarker): void;
read(owner: AgentAppUpdateOwner): AgentAppUpdateMarker | null;
- clear(owner: AgentAppUpdateOwner): void;
+ /** Removes the marker only if it still belongs to `requestId` (a newer install keeps its own). */
+ clear(owner: AgentAppUpdateOwner, requestId: string): void;
};
/**
* Persist a visible host notice in the owner's task (idempotent per clientId).
@@ -275,7 +276,7 @@ export function createAgentAppUpdateService(deps: AgentAppUpdateDeps) {
});
return;
}
- deps.marker.clear(owner);
+ deps.marker.clear(owner, marker.requestId);
deps.logger?.info?.('agent app update result delivered', {
failed: Boolean(marker.failure),
outcome,
@@ -303,6 +304,18 @@ export function createAgentAppUpdateService(deps: AgentAppUpdateDeps) {
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;
+ }
+ await deliver(owner, marker);
+ };
+
const runInstall = async (
caller: AgentAppUpdateCaller,
owner: AgentAppUpdateOwner,
@@ -371,6 +384,18 @@ 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: '上一次更新的结果还没写回任务,暂不发起新的更新;请稍后再试。',
+ };
+ }
+ }
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.
@@ -465,15 +490,7 @@ export function createAgentAppUpdateService(deps: AgentAppUpdateDeps) {
*/
async deliverPendingResult(): Promise<void> {
const owner = deps.captureOwner();
- if (!owner) return;
- 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);
- return;
- }
- await deliver(owner, marker);
+ if (owner) await deliverPending(owner);
},
};
}
diff --git a/apps/desktop/src/main/agent-app-update/index.ts b/apps/desktop/src/main/agent-app-update/index.ts
index 62b9c940c2..5adc3bf1d2 100644
--- a/apps/desktop/src/main/agent-app-update/index.ts
+++ b/apps/desktop/src/main/agent-app-update/index.ts
@@ -160,8 +160,16 @@ function getService(): AgentAppUpdateService {
return null;
}
},
- clear: (owner) => {
+ clear: (owner, requestId) => {
const file = markerPathOf(owner);
+ let current: AgentAppUpdateMarker | null = null;
+ 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 });
diff --git a/apps/desktop/src/main/updateService.ts b/apps/desktop/src/main/updateService.ts
index bc129ef759..a32be49f5d 100644
--- a/apps/desktop/src/main/updateService.ts
+++ b/apps/desktop/src/main/updateService.ts
@@ -174,6 +174,8 @@ const STARTUP_MANIFEST_TIMEOUT_MS = 8_000;
let currentStatus: UpdateStatus = 'idle';
let readyVersion: string | undefined;
+/** Version of the patch currently being downloaded (downloading / superseding only). */
+let downloadingVersion: string | undefined;
let readyFilePath: string | undefined;
/** 当前 staged 补丁对应的渠道代际。延迟清理用它区分「同路径上的新旧包」。 */
let readyChannelEpoch: number | undefined;
@@ -244,6 +246,7 @@ function broadcastChannelSettings(): void {
function setStatus(status: UpdateStatus, extra?: Partial<UpdateStatusPayload>): void {
currentStatus = status;
+ if (status !== 'downloading' && status !== 'superseding') downloadingVersion = undefined;
lastErrorCode = extra?.errorCode;
broadcastStatus({ status, ...extra });
if (status === 'ready' && !startupUpdateCheckInProgress && !extra?.errorCode) {
@@ -1221,6 +1224,7 @@ async function doCheckForUpdate(manifestOverride?: Manifest | null): Promise<Che
// wasReady 路径下,旧的 a.zip 必须保留到 b 通过 SHA 校验之后才能删,否则 b 下载失败
// 时用户连旧的 a 都装不上了。非 wasReady 路径保持原行为(下载前清理腾空间)。
+ downloadingVersion = latestVersion;
if (!wasReady) {
cleanOldFiles(fileName);
setStatus('downloading', { version: latestVersion, progress: 0 });
@@ -2135,14 +2139,8 @@ export async function checkAppUpdateForAgent(): Promise<{
if (unsupported) return { status: 'unsupported', currentVersion, reason: unsupported };
if (currentStatus === 'downloading' || currentStatus === 'superseding') {
// `readyVersion` is unset during a first download and still names the old
- // patch while superseding; read the version being downloaded from the
- // manifest (read-only) so a confirmation is always bound to a concrete version.
- const manifest = await fetchManifest();
- const downloading = manifest
- && compareAppUpdateVersions(manifest.app?.version, currentVersion) === 'newer'
- && resolveUpdateAsset(manifest)
- ? manifest.app.version : undefined;
- return { status: 'downloading', currentVersion, targetVersion: downloading };
+ // patch while superseding; report the version actually being downloaded.
+ return { status: 'downloading', currentVersion, targetVersion: downloadingVersion };
}
if (currentStatus === 'ready' && readyVersion) {
return { status: 'ready', currentVersion, targetVersion: readyVersion };
diff --git a/docs/product-rules/agent-app-update.md b/docs/product-rules/agent-app-update.md
index c776c9b295..7e4bb2edc9 100644
--- a/docs/product-rules/agent-app-update.md
+++ b/docs/product-rules/agent-app-update.md
@@ -16,14 +16,14 @@ Agent 只能反复引导用户去点「检查更新」;那次收紧的起因
「继续」恢复)、本任务在这轮回复后重启、远程连接会短暂断开;Linux 另提示需要输入系统密码。
- 确认后走「设置 → 关于」同一条更新状态机:`checkForUpdate()` 下载(单飞,重复调用不重复下载),
等调用任务这轮回复结束(最多 2 分钟)后 `executeRelaunch()` 重启;Windows / Linux 会等更新器真正启动
- (5 秒内成功即退出、失败即写回原因)再收尾。确认卡总是写明具体目标版本(后台首次下载中也读渠道版本;读不到就不弹卡),安装只认卡片上确认的版本:
+ (5 秒内成功即退出、失败即写回原因)再收尾。确认卡总是写明具体目标版本(后台正在下载时用实际下载的版本;读不到就不弹卡),安装只认卡片上确认的版本:
渠道期间换了新版本时不安装,提示重新发起。安装绑定确认时的账号:退出或切换账号会取消重启,
标记与结果消息只写回该账号,绝不写进后来的账号。拒绝、超时或卡片未送达都不下载、
不重启。同一时刻只有一个安装请求;确认卡等待中或已开始安装时再次调用直接返回当前状态。
- 重启前在账号私有目录写一份标记;新版本启动、该账号数据库就绪后,把结果(新版本号或「仍是旧版本」)
作为一条普通助手消息写回发起任务,桌面和手机重连后都能看到。写入暂时失败时保留标记、下次就绪再写
(按 clientId 去重);任务已不存在才丢弃。未重启就失败时先把失败原因写进标记再写回任务,
- 写回失败或期间切换了账号同样保留,等该账号下次就绪时补写。
+ 写回失败或期间切换了账号同样保留,等该账号下次就绪时补写。上一次的结果还没写回时不发起新安装(先尝试补写,仍失败则提示稍后再试),清除标记只清自己这次请求的。
- 自动更新开关写入既有 `auto-update-settings-store`(用户显式 override),与设置页同一开关。
`check_app_update` 在有可安装更新且开关未开时返回一次 `autoUpdateHint`,同一任务内只提示一次。
- 不支持的构建与安装环境(开发版、个人版、版本无关包、未移入「应用程序」、Linux 非受管安装、