Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): route agent-requested app updates through managed updater
Cindye5597dcde868
diff --git a/apps/desktop/src/main/__tests__/updateService.test.ts b/apps/desktop/src/main/__tests__/updateService.test.tsindex 5b7dc5c705..d96cf59e84 100644--- a/apps/desktop/src/main/__tests__/updateService.test.ts+++ b/apps/desktop/src/main/__tests__/updateService.test.ts@@ -326,6 +326,50 @@ describe('installation version repair scope', () => {});});+describe('agent-triggered managed app update', () => {+ it('only schedules a single native relaunch for a downloaded newer version', async () => {+ readAutoUpdateSettings.mockReturnValue({ autoRelaunchOnIdle: false });+ fetchManifest.mockResolvedValue(updateManifest());+ 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('darwin');+ const exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);+ try {+ expect(service.installAppUpdateForAgent()).toMatchObject({ accepted: false });+ expect(await service.checkAppUpdateForAgent()).toMatchObject({+ status: 'ready', currentVersion: '0.0.64', targetVersion: '0.0.65',+ });+ expect(service.installAppUpdateForAgent()).toMatchObject({+ accepted: true, currentVersion: '0.0.64', targetVersion: '0.0.65',+ });+ expect(service.installAppUpdateForAgent()).toMatchObject({ accepted: false });+ expect(spawnProcess).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(5_000);+ await vi.waitFor(() => expect(spawnProcess).toHaveBeenCalledOnce());+ expect(JSON.stringify(spawnProcess.mock.calls)).toContain('/bin/bash');+ expect(JSON.stringify(spawnProcess.mock.calls)).not.toContain('launchctl');+ } finally {+ service.stopUpdateService();+ exitSpy.mockRestore();+ }+ });++ it('does not schedule an update from a development build or a current version', async () => {+ const service = await freshUpdateService('darwin');+ isDev.mockReturnValue(true);+ expect(await service.checkAppUpdateForAgent()).toMatchObject({ status: 'unsupported' });+ expect(service.installAppUpdateForAgent()).toMatchObject({ accepted: false });+ isDev.mockReturnValue(false);+ fetchManifest.mockResolvedValue(updateManifest('0.0.64'));+ expect(await service.checkAppUpdateForAgent()).toMatchObject({ status: 'no_installable_update' });+ expect(service.installAppUpdateForAgent()).toMatchObject({ accepted: false });+ expect(spawnProcess).not.toHaveBeenCalled();+ });+});+describe('binary version checks after an applied update', () => {beforeEach(() => {readAutoUpdateSettings.mockReturnValue({ autoRelaunchOnIdle: false });diff --git a/apps/desktop/src/main/maker-host/host-system-prompt.md b/apps/desktop/src/main/maker-host/host-system-prompt.mdindex 4dccd23f95..efdc65bec1 100644--- a/apps/desktop/src/main/maker-host/host-system-prompt.md+++ b/apps/desktop/src/main/maker-host/host-system-prompt.md@@ -1,2 +1,4 @@You are Cindy, an open-source AI assistant.Source: https://github.com/makecindy/cindy++When asked to update the Cindy application hosting this task, use the cindy_helper app_update tools to check and install the update. Never replace the running Cindy application through shell commands or create a persistent restart job (including launchctl submit). If a release exists but the current update channel has no installable update, say so; do not sideload it. If the managed tools are unavailable, direct the user to Cindy's built-in Check for Updates action; do not improvise an installer. Installing restarts Cindy and may end this task; an accepted request is not proof that the new version started successfully.diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.tsindex 426ef75424..a268abbf5e 100644--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts@@ -387,6 +387,12 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc// 启动早期跑, 那时 registerMakerIpc 还没执行, holder 是 null; 回调真正被调时// (LLM 调工具时) registerMakerIpc 早已执行完毕, holder 已 ready。xdtHelper: {+ appUpdate: {+ isCurrentSession: (sessionId, sessionInstanceId) =>+ deps.isCurrentLocalSessionInstance?.(sessionId, sessionInstanceId) === true,+ check: async () => (await import('../updateService')).checkAppUpdateForAgent(),+ install: async () => (await import('../updateService')).installAppUpdateForAgent(),+ },logger: createLogger('mcp/cindy_helper'),grokLogin: {start: async (context) => {diff --git a/apps/desktop/src/main/updateService.ts b/apps/desktop/src/main/updateService.tsindex fea8118e76..b868420e90 100644--- a/apps/desktop/src/main/updateService.ts+++ b/apps/desktop/src/main/updateService.ts@@ -210,6 +210,8 @@ let lastResumeAtMs: number | null = null;let startupUpdateCheckInProgress = false;let resolvedRelaunchTheme: 'light' | 'dark' = 'dark';let busyProbe: () => boolean | Promise<boolean> = () => false;+let agentRelaunchScheduled = false;+let agentRelaunchTimer: ReturnType<typeof setTimeout> | null = null;// ── Helpers ────────────────────────────────────────────────────────────────@@ -2071,6 +2073,59 @@ async function executeRelaunchUnguarded(theme: 'light' | 'dark'): Promise<void>// ── Public API ─────────────────────────────────────────────────────────────+export async function checkAppUpdateForAgent(): Promise<{+ status: string;+ currentVersion: string;+ targetVersion?: string;+ reason?: string;+}> {+ const currentVersion = app.getVersion();+ if (!app.isPackaged || isDev() || isCindyPersonalRuntime() || isVersionlessAppVersion(currentVersion)) {+ return { status: 'unsupported', currentVersion, reason: '此构建不支持应用内更新。' };+ }+ if (currentStatus === 'downloading' || currentStatus === 'superseding') {+ return { status: 'downloading', currentVersion, targetVersion: readyVersion };+ }+ const result = await checkForUpdate();+ if (currentStatus === 'ready' && readyVersion) {+ return { status: 'ready', currentVersion, targetVersion: readyVersion };+ }+ if (result === 'idle') return {+ status: 'no_installable_update', currentVersion,+ reason: '当前渠道没有适用于这台设备的可安装更新;也可能已是最新版本。',+ };+ return { status: result, currentVersion, reason: `应用内更新检查结果:${result}` };+}++export function installAppUpdateForAgent(): {+ accepted: boolean;+ currentVersion: string;+ targetVersion?: string;+ reason?: string;+} {+ const currentVersion = app.getVersion();+ if (!app.isPackaged || isDev() || isCindyPersonalRuntime() || isVersionlessAppVersion(currentVersion)) {+ return { accepted: false, currentVersion, reason: '此构建不支持应用内更新。' };+ }+ if (agentRelaunchScheduled || isRelaunching || autoRelaunchInProgress) {+ return { accepted: false, currentVersion, reason: '更新重启已在进行中。' };+ }+ if (currentStatus !== 'ready' || !readyVersion || !readyFilePath || !fs.existsSync(readyFilePath)+ || compareAppUpdateVersions(readyVersion, currentVersion) !== 'newer') {+ return { accepted: false, currentVersion, reason: '没有已下载且版本更新的应用内补丁;请先检查更新。' };+ }+ const targetVersion = readyVersion;+ agentRelaunchScheduled = true;+ // Let the MCP tool result reach the agent before the host exits. The existing+ // executor revalidates the staged patch and channel at the actual apply boundary.+ agentRelaunchTimer = setTimeout(() => {+ agentRelaunchTimer = null;+ agentRelaunchScheduled = false;+ void executeRelaunch(resolvedRelaunchTheme);+ }, 5_000);+ return { accepted: true, currentVersion, targetVersion };+}+export function initUpdateService(): void {// Observe the successful old-updater receipt before existing cleanup removes// it. Async and metadata-only; no effect on download/apply/rollback decisions.@@ -2508,6 +2563,11 @@ export async function enableUncustomizedBetaChannel(}export function stopUpdateService(): void {+ if (agentRelaunchTimer) {+ clearTimeout(agentRelaunchTimer);+ agentRelaunchTimer = null;+ agentRelaunchScheduled = false;+ }if (firstCheckTimer) {clearTimeout(firstCheckTimer);firstCheckTimer = null;diff --git a/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts b/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.tsindex f0c156eb0c..4362f9bca9 100644--- a/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts+++ b/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts@@ -18,6 +18,48 @@ function parsePayload(result: unknown): Record<string, unknown> {}describe("cindy_helper MCP server", () => {+ it('offers app updates only to a live local task and delegates installation once to the host', async () => {+ let context = {+ agentKind: 'codex' as const, workingDir: '/repo', sessionId: 'local-task',+ sessionInstanceId: 'instance-1', remoteHostId: undefined as string | undefined,+ };+ let current = true;+ const check = vi.fn(async () => ({ status: 'ready', currentVersion: '0.1.86', targetVersion: '0.1.90' }));+ const install = vi.fn(async () => ({ accepted: true, currentVersion: '0.1.86', targetVersion: '0.1.90' }));+ const server = createXdtHelperMcpServer({+ resolveSurface: async () => 'default',+ appUpdate: {+ isCurrentSession: (sessionId, instanceId) => current && sessionId === 'local-task' && instanceId === 'instance-1',+ check, install,+ },+ }, {+ ...context, getSessionContext: () => context,+ });+ const [ct, st] = InMemoryTransport.createLinkedPair();+ const client = new Client({ name: 'app-update-test', version: '0.0.0' });+ await Promise.all([server.connect(st), client.connect(ct)]);+ const call = async (name: string) => parsePayload(await client.callTool({+ name: 'call_tool', arguments: { name, args: {} },+ }));+ try {+ const tools = parsePayload(await client.callTool({ name: 'list_tools', arguments: { category: 'app_update' } }));+ expect((tools.tools as Array<{ name: string }>).map((tool) => tool.name)).toEqual([+ 'check_app_update', 'install_app_update',+ ]);+ expect(await call('check_app_update')).toMatchObject({ status: 'ready', targetVersion: '0.1.90' });+ expect(await call('install_app_update')).toMatchObject({ accepted: true, targetVersion: '0.1.90' });+ expect(check).toHaveBeenCalledOnce();+ expect(install).toHaveBeenCalledOnce();+ current = false;+ expect(await call('install_app_update')).toMatchObject({ ok: false, errorCode: 'STALE_SESSION' });+ context = { ...context, remoteHostId: 'remote-machine' };+ expect(await call('install_app_update')).toMatchObject({ ok: false, errorCode: 'CAPABILITY_NOT_AVAILABLE' });+ expect(install).toHaveBeenCalledOnce();+ } finally {+ await client.close();+ await server.close();+ }+ });it('lets a remote agent start only the scoped Grok device login and returns no credential', async () => {let current = true;const start = vi.fn(async () => ({diff --git a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.tsindex c12109c5df..fb77f24459 100644--- a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts+++ b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts@@ -42,6 +42,7 @@ import { registerMoveSessionTool, type MoveSessionCallback } from './xdt-helper/import { registerProjectManagementTools, type ProjectManagementCallbacks } from './xdt-helper/project_management.js';import {registerGetCapabilitiesTool,+ registerAppUpdateTools,registerGetCurrentSessionIdTool,registerSetCurrentSessionTitleTool,registerRenameSessionsTool,@@ -64,6 +65,7 @@ import {registerSkillhubTools,} from './xdt-helper/index.js';import type { SubmitGithubIssueDeps } from './xdt-helper/submit_github_issue.js';+import type { AppUpdateCallbacks } from './xdt-helper/app_update.js';import type { SkillhubAgentCallback } from './xdt-helper/skillhub.js';import type { SetCurrentSessionTitleDeps } from './xdt-helper/set_current_session_title.js';import type { RenameSessionsDeps } from './xdt-helper/rename_sessions.js';@@ -122,7 +124,7 @@ const CALL_TOOL_INPUT = {// list_tools 入口类目: cindy(自省) / control(会话控制面) / history(聊天历史) / feedback(官方反馈提交) / handoff(session 间 handoff)。// 协同 team 工具已拆到独立 cindy_orca server(插件开关 gate)。-const CATEGORY_ENUM = ['cindy', 'auth', 'control', 'history', 'feedback', 'handoff', 'skills', 'bots'] as const;+const CATEGORY_ENUM = ['cindy', 'auth', 'control', 'history', 'feedback', 'handoff', 'skills', 'app_update', 'bots'] as const;interface SessionTaskCallbacks {startSessionTask(params: {@@ -707,6 +709,7 @@ export type ControlDispatchOutcome =export interface XdtHelperMcpDeps {logger?: LiziMcpLogger;+ appUpdate?: AppUpdateCallbacks;grokLogin?: GrokLoginCallbacks;/** Host-owned runtime classification used to keep Bot tasks on a narrow surface. */resolveSurface?: (input: {@@ -831,6 +834,12 @@ export function createXdtHelperMcpServer(// 'cindy' 类: 自省 (无 host 依赖, 始终注册)。registerGetCapabilitiesTool(registry);+ if (deps.appUpdate) {+ registerAppUpdateTools(registry, {+ getSessionContext: () => resolveLiziMcpSessionContext(sessionCtx),+ callbacks: deps.appUpdate,+ });+ }if (deps.grokLogin)registerGrokLoginTools(registry, () => resolveLiziMcpSessionContext(sessionCtx), deps.grokLogin);registerGetCurrentSessionIdTool(registry, {diff --git a/packages/lizi-mcps/src/lizi_xdtHelperToolRegistry.ts b/packages/lizi-mcps/src/lizi_xdtHelperToolRegistry.tsindex 7d96b17587..c4be498799 100644--- a/packages/lizi-mcps/src/lizi_xdtHelperToolRegistry.ts+++ b/packages/lizi-mcps/src/lizi_xdtHelperToolRegistry.ts@@ -48,6 +48,7 @@ export type XdtHelperToolCategory =| 'feedback'| 'handoff'| 'skills'+ | 'app_update'| 'bots';export type XdtHelperToolContentBlock =diff --git a/packages/lizi-mcps/src/xdt-helper/app_update.ts b/packages/lizi-mcps/src/xdt-helper/app_update.tsnew file mode 100644index 0000000000..094ccd4c15--- /dev/null+++ b/packages/lizi-mcps/src/xdt-helper/app_update.ts@@ -0,0 +1,62 @@+import { BRAND_NAME } from '@cindy/maker-shared/branding';+import type { XdtHelperToolRegistry } from '../lizi_xdtHelperToolRegistry.js';+import { errorPayload, okPayload } from './_payload.js';++export interface AppUpdateCallbacks {+ isCurrentSession(sessionId: string, sessionInstanceId: string): boolean;+ check(): Promise<{ status: string; currentVersion: string; targetVersion?: string; reason?: string }>;+ install(): Promise<{ accepted: boolean; currentVersion: string; targetVersion?: string; reason?: string }>;+}++export function registerAppUpdateTools(+ registry: XdtHelperToolRegistry,+ deps: {+ getSessionContext: () => { sessionId?: string; sessionInstanceId?: string; remoteHostId?: string };+ callbacks: AppUpdateCallbacks;+ },+): void {+ const callerError = () => {+ const context = deps.getSessionContext();+ if (!context.sessionId) return errorPayload('NO_SESSION_CONTEXT', '当前调用没有绑定 Cindy 任务。');+ if (context.remoteHostId) return errorPayload('REMOTE_SESSION', '远程任务不能更新本机 Cindy;请在本机任务中操作。');+ if (!context.sessionInstanceId || !deps.callbacks.isCurrentSession(context.sessionId, context.sessionInstanceId)) {+ return errorPayload('STALE_SESSION', '当前任务实例已结束或不再有效,不能更新 Cindy。');+ }+ return null;+ };++ registry.register({+ name: 'check_app_update',+ category: 'app_update',+ description: `检查当前运行的 ${BRAND_NAME} 是否有可通过应用内更新器安装的新版本。不要用 GitHub Release 文件替换正在运行的应用。`,+ inputShape: {},+ handler: async () => {+ const error = callerError();+ if (error) return error;+ try {+ return okPayload(await deps.callbacks.check());+ } catch (cause) {+ return errorPayload('UPDATE_CHECK_FAILED', String(cause));+ }+ },+ });++ registry.register({+ name: 'install_app_update',+ category: 'app_update',+ description: `仅当用户明确要求安装/更新当前运行的 ${BRAND_NAME} 时使用。仅安装应用内更新器已下载的新版本;成功表示已安排重启,不代表新版本已启动。本工具会结束正在运行的 Cindy 和当前任务。不要另写重启脚本或使用 launchctl。`,+ inputShape: {},+ handler: async () => {+ const error = callerError();+ if (error) return error;+ try {+ const result = await deps.callbacks.install();+ return result.accepted+ ? okPayload(result)+ : errorPayload('UPDATE_NOT_READY', result.reason ?? '没有可安装的应用内更新;请先调用 check_app_update。', result);+ } catch (cause) {+ return errorPayload('UPDATE_INSTALL_FAILED', String(cause));+ }+ },+ });+}diff --git a/packages/lizi-mcps/src/xdt-helper/index.ts b/packages/lizi-mcps/src/xdt-helper/index.tsindex a0122d72f0..ec5485256d 100644--- a/packages/lizi-mcps/src/xdt-helper/index.ts+++ b/packages/lizi-mcps/src/xdt-helper/index.ts@@ -9,6 +9,7 @@*/export { registerGetCapabilitiesTool } from './get_capabilities.js';+export { registerAppUpdateTools, type AppUpdateCallbacks } from './app_update.js';export { registerGrokLoginTools, type GrokLoginCallbacks, type GrokLoginState } from './grok_login.js';export { registerSkillhubTools, type SkillhubAgentCallback, type SkillhubAgentRequest } from './skillhub.js';export {