Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
refactor(update): 收缩范围——不认领已在进行的重启、去掉官方 Hook 主人路径;通知按账号 id 重试
Dash5ed981438210
diff --git a/apps/desktop/src/main/__tests__/updateService.test.ts b/apps/desktop/src/main/__tests__/updateService.test.tsindex 2400349a6c..89522cb08f 100644--- a/apps/desktop/src/main/__tests__/updateService.test.ts+++ b/apps/desktop/src/main/__tests__/updateService.test.ts@@ -437,9 +437,8 @@ 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.- const second = service.applyConfirmedAppUpdateForAgent({ beforeRelaunch });- await vi.advanceTimersByTimeAsync(21_000);- await expect(second).resolves.toMatchObject({ status: 'relaunching' });+ await expect(service.applyConfirmedAppUpdateForAgent({ beforeRelaunch }))+ .resolves.toMatchObject({ status: 'failed', errorCode: 'relaunch_in_progress' });expect(download).toHaveBeenCalledOnce();expect(spawnProcess).toHaveBeenCalledOnce();} finally {@@ -581,7 +580,7 @@ describe('agent-facing managed app update check', () => {}});- it('treats a relaunch already under way as this install only for the confirmed version', async () => {+ it('does not claim a relaunch that is already under way', async () => {// Idle auto-install is on and starts applying 0.0.65 as soon as it is staged.readAutoUpdateSettings.mockReturnValue({ autoRelaunchOnIdle: true });download.mockImplementation(async ({ targetPath }: { targetPath: string }) => {@@ -596,19 +595,10 @@ describe('agent-facing managed app update check', () => {await vi.waitFor(() => { expect(spawnProcess).toHaveBeenCalledOnce(); });const beforeRelaunch = vi.fn(async () => true);const beforeSpawn = vi.fn(() => true);- 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,- // 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,- })).resolves.toMatchObject({ status: 'failed', errorCode: 'relaunch_cancelled' });+ await expect(service.applyConfirmedAppUpdateForAgent({ expectedVersion: '0.0.65', beforeRelaunch, beforeSpawn }))+ .resolves.toMatchObject({ status: 'failed', errorCode: 'relaunch_in_progress' });expect(beforeRelaunch).not.toHaveBeenCalled();+ expect(beforeSpawn).not.toHaveBeenCalled();expect(spawnProcess).toHaveBeenCalledOnce();} finally {service.stopUpdateService();@@ -616,46 +606,6 @@ 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.tsindex 8e07b92818..802db28547 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@@ -297,12 +297,13 @@ describe('Agent app update install', () => {expect(harness.deps.notify).not.toHaveBeenCalled();// No restart happened, so no restart record is left on disk.expect(harness.deps.marker.add).not.toHaveBeenCalled();- // The notice waits in memory until the confirming account is active again.- harness.switchOwner(ownerA);+ // The notice waits in memory until the confirming account is active again+ // (a fresh sign-in: same account id, new scope object).+ harness.switchOwner({ ownerId: 'owner-a' });await harness.service.deliverPendingResult();expect(harness.deps.notify).toHaveBeenCalledOnce();expect(harness.deps.notify).toHaveBeenCalledWith(- ownerA,+ { ownerId: 'owner-a' },'task-1',expect.stringMatching(/^agent-app-update:/),expect.stringContaining('update.agentInstall.reasons.notRestarted'),diff --git a/apps/desktop/src/main/agent-app-update/__tests__/callerAuthority.test.ts b/apps/desktop/src/main/agent-app-update/__tests__/callerAuthority.test.tsindex 8249749e64..dc2ff10e29 100644--- a/apps/desktop/src/main/agent-app-update/__tests__/callerAuthority.test.ts+++ b/apps/desktop/src/main/agent-app-update/__tests__/callerAuthority.test.ts@@ -34,7 +34,7 @@ describe('isAppUpdateOwnerTurn', () => {expect(isAppUpdateOwnerTurn(facts({ ownerAuthoredInput: () => false }))).toBe(false);});- it('uses the channel owner check for IM and official-bot turns', () => {+ it('uses the channel owner check for personal IM turns', () => {const imRoute = (requesterAuthority?: 'owner' | 'guest' | 'unknown') => ({origin: { kind: 'im' as const, channel: 'telegram' as const },requesterAuthority,@@ -50,15 +50,26 @@ describe('isAppUpdateOwnerTurn', () => {expect(isAppUpdateOwnerTurn(facts({ route: imRoute(undefined), ownerAuthoredInput }))).toBe(false,);+ // A channel route never falls back to Desktop input evidence.+ expect(ownerAuthoredInput).not.toHaveBeenCalled();+ });++ it('refuses official-bot (hook) turns, which carry an automation origin', () => {expect(isAppUpdateOwnerTurn(facts({+ turnOrigin: {+ kind: 'scheduler',+ scheduleId: 'hook:conn',+ scheduleName: 'Hook · Telegram',+ },route: { origin: { kind: 'hook', source: 'telegram' }, requesterAuthority: 'owner' },}),),- ).toBe(true);- // A channel route never falls back to Desktop input evidence.- expect(ownerAuthoredInput).not.toHaveBeenCalled();+ ).toBe(false);+ expect(+ isAppUpdateOwnerTurn(facts({ route: { origin: { kind: 'hook', source: 'telegram' } } })),+ ).toBe(false);});it('refuses scheduler routes and IM turns without a route', () => {diff --git a/apps/desktop/src/main/agent-app-update/agentAppUpdateService.ts b/apps/desktop/src/main/agent-app-update/agentAppUpdateService.tsindex 1b1f7e8d4e..48a41db668 100644--- a/apps/desktop/src/main/agent-app-update/agentAppUpdateService.ts+++ b/apps/desktop/src/main/agent-app-update/agentAppUpdateService.ts@@ -50,6 +50,7 @@ const FAILURE_REASON_KEYS: Record<string, string> = {relaunch_cancelled: 'notRestarted',not_ready: 'notReady',relaunch_not_started: 'updaterNotStarted',+ relaunch_in_progress: 'relaunchInProgress',updater_spawn_failed: 'updaterNotStarted',unsupported: 'unsupported',linux_installation_unsupported: 'unsupported',@@ -145,7 +146,8 @@ const MAX_PENDING_NOTICES = 20;export const MAX_RESTART_RECORDS = 20;interface PendingNotice {- owner: AgentAppUpdateOwner;+ /** Account id, not a captured scope: a later sign-in of the same account still matches. */+ ownerId: string;sessionId: string;clientId: string;message: string;@@ -276,13 +278,13 @@ export function createAgentAppUpdateService(deps: AgentAppUpdateDeps) {if (pendingNotices.length > MAX_PENDING_NOTICES) pendingNotices.shift();};const flushNotices = async () => {+ const owner = deps.captureOwner();+ if (!owner) return;for (const notice of [...pendingNotices]) {- // A concurrent flush may already have delivered it.- if (!pendingNotices.includes(notice)) continue;- // Never write into whichever account replaced the one that confirmed.- if (!deps.isOwnerCurrent(notice.owner)) continue;+ // Never write into a different account; a concurrent flush may already have delivered it.+ if (notice.ownerId !== owner.ownerId || !pendingNotices.includes(notice)) continue;try {- await deps.notify(notice.owner, notice.sessionId, notice.clientId, notice.message);+ await deps.notify(owner, notice.sessionId, notice.clientId, notice.message);} catch (error) {deps.logger?.warn?.('agent app update notice failed; will retry', { error: String(error) });continue;@@ -371,7 +373,7 @@ export function createAgentAppUpdateService(deps: AgentAppUpdateDeps) {// A spawn that failed after the record was written did not restart anything.deps.marker.remove(owner, request.requestId);queueNotice({- owner,+ ownerId: owner.ownerId,sessionId: request.sessionId,clientId: `agent-app-update:${request.requestId}`,message: failureMessage(request, failure),diff --git a/apps/desktop/src/main/agent-app-update/callerAuthority.ts b/apps/desktop/src/main/agent-app-update/callerAuthority.tsindex ffe024bd5e..b2a7b07e14 100644--- a/apps/desktop/src/main/agent-app-update/callerAuthority.ts+++ b/apps/desktop/src/main/agent-app-update/callerAuthority.ts@@ -7,7 +7,7 @@ export interface AppUpdateCallerFacts {turnRunning: boolean;/** maker-core product origin of that turn (null for ordinary Desktop input). */turnOrigin: SendOrigin | null;- /** Live IM / hook route, if the turn came from a channel. */+ /** Live channel route, if the turn came from IM. */route: Pick<InteractionRoute, 'origin' | 'requesterAuthority'> | null;/** Coordinator evidence that the active Desktop/phone input was typed by the owner. */ownerAuthoredInput: () => boolean;@@ -19,8 +19,9 @@ export interface AppUpdateCallerFacts {* unproven is refused before the card exists:** - scheduler / goal turns (maker-core origin) — never;- * - IM / official-bot turns — the channel's owner check for the triggering- * message (`route.requesterAuthority`);+ * - personal IM turns — the channel's owner check for the triggering message+ * (`route.requesterAuthority`); official-bot (hook) turns run with an+ * automation origin and are refused like scheduler turns;* - Desktop / same-account phone turns — the coordinator's active input must be* owner-typed text (not another task, Orca, plugin, shared-task guest or resume).*/@@ -30,9 +31,7 @@ export function isAppUpdateOwnerTurn(facts: AppUpdateCallerFacts): boolean {if (origin && origin.kind !== 'user') return false;const route = facts.route;if (route) {- if (route.origin.kind === 'im' || route.origin.kind === 'hook') {- return route.requesterAuthority === 'owner';- }+ if (route.origin.kind === 'im') return route.requesterAuthority === 'owner';if (route.origin.kind !== 'desktop') return false;} else if (origin?.surface === 'im') {// An IM turn always owns a route; without one its sender is unproven.diff --git a/apps/desktop/src/main/hook-control/session-runner.ts b/apps/desktop/src/main/hook-control/session-runner.tsindex 3907afa6d5..5508d32d94 100644--- a/apps/desktop/src/main/hook-control/session-runner.ts+++ b/apps/desktop/src/main/hook-control/session-runner.ts@@ -1318,9 +1318,6 @@ export function createMakerHookSessionRunner(deps: {turnId: randomUUID(),origin: routeOrigin,interactionSurface: req.onInteraction ? 'channel-card' : 'headless',- // The official bot only proves the sender for Telegram private chats- // (server-bound to this account). Groups and other channels stay unknown.- requesterAuthority: req.source?.im === 'telegram' && req.laneKind === 'dm' ? 'owner' : 'unknown',sourceDescription: describeInteractionSource({channelName: req.source?.im ?? req.origin.connectionName,chatId: req.source?.channelName ?? req.title ?? req.source?.im ?? 'IM',diff --git a/apps/desktop/src/main/updateService.ts b/apps/desktop/src/main/updateService.tsindex 3af9135601..b63a61951a 100644--- a/apps/desktop/src/main/updateService.ts+++ b/apps/desktop/src/main/updateService.ts@@ -2165,8 +2165,6 @@ 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: '无法读取当前渠道的更新信息。',@@ -2235,19 +2233,16 @@ export async function applyConfirmedAppUpdateForAgent(options: {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, 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);+ // A relaunch already started elsewhere (Settings banner or idle auto-install)+ // is not this request's: report it instead of claiming its outcome.+ const relaunchInProgress: AgentConfirmedAppUpdateResult = {+ status: 'failed',+ reason: 'Cindy 已经在通过设置页或空闲自动安装重启更新,本次请求没有另外安装。',+ errorCode: 'relaunch_in_progress',};const unsupported = agentUpdateUnsupportedReason();if (unsupported) return { status: 'failed', reason: unsupported, errorCode: 'unsupported' };- if (isRelaunching || autoRelaunchInProgress) return await adoptRelaunchUnderWay();+ if (isRelaunching || autoRelaunchInProgress) return relaunchInProgress;if (currentStatus !== 'ready') {const result = await checkForUpdate();if (result !== 'ready') {@@ -2257,7 +2252,7 @@ export async function applyConfirmedAppUpdateForAgent(options: {const changedAfterDownload = versionChanged();if (changedAfterDownload) return changedAfterDownload;if (!await options.beforeRelaunch()) return relaunchCancelled;- if (isRelaunching || autoRelaunchInProgress) return await adoptRelaunchUnderWay();+ if (isRelaunching || autoRelaunchInProgress) return relaunchInProgress;// A background check may have superseded the staged patch during the wait.const changedBeforeRelaunch = versionChanged();if (changedBeforeRelaunch) return changedBeforeRelaunch;diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex d8d9e86251..d46b0b0eca 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -8066,7 +8066,8 @@"notReady": "The downloaded update is no longer available.","updaterNotStarted": "The updater did not start, so {{appName}} did not restart.","unsupported": "This installation does not support in-app updates.",- "generic": "Something went wrong during installation."+ "generic": "Something went wrong during installation.",+ "relaunchInProgress": "{{appName}} was already restarting to install an update from Settings or idle auto-install, so this request did not install separately."}},"agentAutoUpdate": {diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 16aabc73a5..1bdb28c733 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -8058,7 +8058,8 @@"notReady": "ダウンロード済みの更新は利用できなくなりました。","updaterNotStarted": "アップデーターが起動しなかったため、{{appName}} は再起動していません。","unsupported": "このインストール環境はアプリ内更新に対応していません。",- "generic": "インストール中にエラーが発生しました。"+ "generic": "インストール中にエラーが発生しました。",+ "relaunchInProgress": "{{appName}} は設定画面またはアイドル時の自動インストールで既に再起動中のため、このリクエストでは別途インストールしませんでした。"}},"agentAutoUpdate": {diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 075d59d79e..6df0647770 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -8058,7 +8058,8 @@"notReady": "다운로드한 업데이트를 더 이상 사용할 수 없습니다.","updaterNotStarted": "업데이터가 시작되지 않아 {{appName}}가 다시 시작되지 않았습니다.","unsupported": "이 설치 환경은 앱 내 업데이트를 지원하지 않습니다.",- "generic": "설치 중 오류가 발생했습니다."+ "generic": "설치 중 오류가 발생했습니다.",+ "relaunchInProgress": "{{appName}}이(가) 이미 설정 또는 유휴 시 자동 설치로 다시 시작해 업데이트 중이어서 이 요청으로는 따로 설치하지 않았습니다."}},"agentAutoUpdate": {diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 1060b2a221..90767f2773 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -8058,7 +8058,8 @@"notReady": "已下载的更新不再可用。","updaterNotStarted": "更新器没有启动,{{appName}} 未重启。","unsupported": "当前安装环境不支持应用内更新。",- "generic": "安装过程中出现错误。"+ "generic": "安装过程中出现错误。",+ "relaunchInProgress": "{{appName}} 已经在通过设置页或空闲自动安装重启更新,本次请求没有另外安装。"}},"agentAutoUpdate": {diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 784095eace..a876c8efa2 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -8058,7 +8058,8 @@"notReady": "已下載的更新不再可用。","updaterNotStarted": "更新器沒有啟動,{{appName}} 未重新啟動。","unsupported": "目前的安裝環境不支援應用程式內更新。",- "generic": "安裝過程中發生錯誤。"+ "generic": "安裝過程中發生錯誤。",+ "relaunchInProgress": "{{appName}} 已經在透過設定頁或閒置自動安裝重新啟動更新,這次請求沒有另外安裝。"}},"agentAutoUpdate": {diff --git a/docs/product-rules/agent-app-update.md b/docs/product-rules/agent-app-update.mdindex c80c48e11a..f2a4386422 100644--- a/docs/product-rules/agent-app-update.md+++ b/docs/product-rules/agent-app-update.md@@ -25,8 +25,7 @@ Agent 只能反复引导用户去点「检查更新」;那次收紧的起因新版本启动、该账号数据库就绪后,把结果(新版本号或「仍是旧版本」)作为一条普通助手消息写回发起任务,桌面和手机重连后都能看到;写入暂时失败保留标记下次再写(按 clientId 去重),任务已不存在或超过7 天才丢弃。标记文件按请求逐条保存重启记录,新记录追加而不覆盖,每条各自写回、各自清除。- 设置页或空闲自动安装已经在重启时,只有版本一致、通过同一道最后检查,并且等那次重启真正落定- (启动成功即退出,失败则当场写回原因)才算本次安装。+ 设置页或空闲自动安装已经在重启时,Agent 不认领那次重启,直接说明 Cindy 已在重启更新。- **没有重启时**(下载失败、版本变化、切换账号取消、更新器没启动等):不写磁盘,按错误码生成本地化原因放进内存待写回列表,立即写回;写不进或原账号不在时保留,在该账号下次就绪或下次发起更新时重试。这类通知不阻止发起新的更新;进程退出时未写回的会丢失(可接受,不为此新增持久化)。@@ -44,7 +43,7 @@ Agent 只能反复引导用户去点「检查更新」;那次收紧的起因- 个人 IM:沿用控制命令的主人判据(私聊已过渠道 owner 门;群里看发言人 `isOwner`)。- 个人微信:私聊联系人无法证明是主人(其权限策略本就记为 `requesterAuthority: unknown`),一律拒绝,主人可在桌面、手机或其他已验证主人的渠道发起。-- 官方 Hook:仅 Telegram 私聊(服务端按账号绑定路由);群与其他渠道不算。+- 官方 Hook:其轮次在 maker-core 里记为自动化来源,与 scheduler 一样拒绝;主人请用桌面、手机或个人 bot。- scheduler / goal 轮次一律拒绝。共享任务访客即使看到卡片也不能回答:device-link 共享任务门禁按工具名拒绝这两类确认。