Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(update): Agent 经宿主确认后用内置更新器更新 Cindy,并可开关空闲自动更新
Dashcae0244cac88
diff --git a/apps/desktop/src/main/__tests__/updateService.test.ts b/apps/desktop/src/main/__tests__/updateService.test.tsindex fedaaa0b23..1aeb1a24f3 100644--- a/apps/desktop/src/main/__tests__/updateService.test.ts+++ b/apps/desktop/src/main/__tests__/updateService.test.ts@@ -410,6 +410,99 @@ describe('agent-facing managed app update check', () => {expect(spawnProcess).not.toHaveBeenCalled();});+ describe('confirmed Agent install', () => {+ beforeEach(() => {+ // Keep the idle auto-relaunch out of the way; the Agent path relaunches explicitly.+ readAutoUpdateSettings.mockReturnValue({ autoRelaunchOnIdle: false });+ fetchManifest.mockResolvedValue(updateManifest());+ });++ it('stages through checkForUpdate and relaunches with the built-in updater', async () => {+ download.mockImplementation(async ({ targetPath }: { targetPath: string }) => {+ fs.mkdirSync(path.dirname(targetPath), { recursive: true });+ fs.writeFileSync(targetPath, 'update');+ return { path: targetPath, size: 123 };+ });+ const exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);+ const service = await freshUpdateService('darwin');+ const order: string[] = [];+ const beforeRelaunch = vi.fn(async () => {+ order.push(`before:${download.mock.calls.length}:${spawnProcess.mock.calls.length}`);+ return true;+ });+ try {+ await expect(service.applyConfirmedAppUpdateForAgent({ beforeRelaunch }))+ .resolves.toEqual({ status: 'relaunching', targetVersion: '0.0.65' });+ expect(download).toHaveBeenCalledOnce();+ 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' });+ expect(download).toHaveBeenCalledOnce();+ expect(spawnProcess).toHaveBeenCalledOnce();+ } finally {+ service.stopUpdateService();+ exitSpy.mockRestore();+ }+ });++ it('joins concurrent requests onto one download and keeps the patch when relaunch is skipped', async () => {+ let finishDownload!: () => void;+ download.mockImplementation(({ targetPath }: { targetPath: string }) => new Promise((resolve) => {+ finishDownload = () => {+ fs.mkdirSync(path.dirname(targetPath), { recursive: true });+ fs.writeFileSync(targetPath, 'update');+ resolve({ path: targetPath, size: 123 });+ };+ }));+ const service = await freshUpdateService('darwin');+ try {+ const beforeRelaunch = vi.fn(async () => false);+ const first = service.applyConfirmedAppUpdateForAgent({ beforeRelaunch });+ const second = service.applyConfirmedAppUpdateForAgent({ beforeRelaunch });+ await vi.waitFor(() => { expect(download).toHaveBeenCalledOnce(); });+ finishDownload();+ await expect(first).resolves.toMatchObject({ status: 'failed', errorCode: 'relaunch_cancelled' });+ await expect(second).resolves.toMatchObject({ status: 'failed', errorCode: 'relaunch_cancelled' });+ expect(download).toHaveBeenCalledOnce();+ expect(spawnProcess).not.toHaveBeenCalled();+ expect(await service.checkAppUpdateForAgent()).toMatchObject({ status: 'ready', targetVersion: '0.0.65' });+ } finally {+ service.stopUpdateService();+ }+ });++ it('does not relaunch when the download fails or the build is unsupported', async () => {+ download.mockRejectedValue(new Error('network'));+ const service = await freshUpdateService('darwin');+ const beforeRelaunch = vi.fn(async () => true);+ try {+ await expect(service.applyConfirmedAppUpdateForAgent({ beforeRelaunch }))+ .resolves.toMatchObject({ status: 'failed', errorCode: 'download_failed' });+ isDev.mockReturnValue(true);+ download.mockClear();+ await expect(service.applyConfirmedAppUpdateForAgent({ beforeRelaunch }))+ .resolves.toMatchObject({ status: 'failed', errorCode: 'unsupported' });+ expect(download).not.toHaveBeenCalled();+ expect(beforeRelaunch).not.toHaveBeenCalled();+ expect(spawnProcess).not.toHaveBeenCalled();+ } finally {+ service.stopUpdateService();+ }+ });++ it('reads and writes the existing idle auto-install switch', async () => {+ const { writeAutoRelaunchOnIdle } = await import('../auto-update-settings-store');+ const service = await freshUpdateService('darwin');+ expect(service.readAutoRelaunchOnIdleForAgent()).toBe(false);+ readAutoUpdateSettings.mockReturnValue({ autoRelaunchOnIdle: true });+ expect(service.setAutoRelaunchOnIdleForAgent(true)).toBe(true);+ expect(writeAutoRelaunchOnIdle).toHaveBeenCalledWith(true);+ service.stopUpdateService();+ });+ });+it('does not advertise an invalid or asset-free manifest as an installable update', async () => {const service = await freshUpdateService('darwin');fetchManifest.mockResolvedValueOnce(updateManifest('not-semver'));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.tsnew file mode 100644index 0000000000..e2bb919b19--- /dev/null+++ b/apps/desktop/src/main/agent-app-update/__tests__/agentAppUpdateService.test.ts@@ -0,0 +1,361 @@+import { describe, expect, it, vi } from 'vitest';+import type { InteractionDecision } from '@cindy/maker-core';++import {+ createAgentAppUpdateService,+ type AgentAppUpdateDeps,+ type AgentAppUpdateMarker,+} from '../agentAppUpdateService.js';+import { AGENT_APP_AUTO_UPDATE_TOOL_NAME, AGENT_APP_UPDATE_TOOL_NAME } from '../constants.js';++const caller = { sessionId: 'task-1', sessionInstanceId: 'instance-1' };++function allow(): InteractionDecision {+ return { kind: 'permission', behavior: 'allow' };+}++function deny(reason?: string): InteractionDecision {+ return { kind: 'permission', behavior: 'deny', ...(reason ? { reason } : {}) };+}++function setup(overrides: Partial<AgentAppUpdateDeps> = {}) {+ let marker: AgentAppUpdateMarker | null = null;+ let autoUpdate = false;+ const deps: AgentAppUpdateDeps = {+ appVersion: () => '0.1.86',+ platform: 'darwin',+ pid: 100,+ now: () => 1_000,+ check: vi.fn(async () => ({+ status: 'available',+ currentVersion: '0.1.86',+ targetVersion: '0.1.90',+ })),+ apply: vi.fn(async ({ beforeRelaunch }) => {+ await beforeRelaunch();+ return { status: 'relaunching' as const, targetVersion: '0.1.90' };+ }),+ readAutoUpdate: () => autoUpdate,+ writeAutoUpdate: vi.fn((enabled: boolean) => {+ autoUpdate = enabled;+ return autoUpdate;+ }),+ resolveCaller: vi.fn(() => 'owner' as const),+ countOtherRunningTasks: vi.fn(() => 2),+ requestHostPermission: vi.fn(async () => allow()),+ waitForCallerTurnToEnd: vi.fn(async () => undefined),+ marker: {+ write: vi.fn((value: AgentAppUpdateMarker) => {+ marker = value;+ }),+ read: () => marker,+ clear: vi.fn(() => {+ marker = null;+ }),+ },+ notify: vi.fn(async () => undefined),+ compareVersions: (candidate, current) =>+ candidate === current ? 'same' : (candidate ?? '') > current ? 'newer' : 'older',+ translate: (key) => key,+ ...overrides,+ };+ return {+ deps,+ service: createAgentAppUpdateService(deps),+ getMarker: () => marker,+ setMarker: (value: AgentAppUpdateMarker | null) => {+ marker = value;+ },+ };+}++async function flush() {+ for (let i = 0; i < 5; i += 1) await Promise.resolve();+}++describe('Agent app update install', () => {+ it('does not download or restart until the owner approves the Host card', async () => {+ let resolveCard!: (decision: InteractionDecision) => void;+ const { deps, service } = setup({+ requestHostPermission: vi.fn(+ () =>+ new Promise<InteractionDecision>((resolve) => {+ resolveCard = resolve;+ }),+ ),+ });+ const pending = service.install(caller);+ await flush();+ expect(deps.requestHostPermission).toHaveBeenCalledOnce();+ expect(deps.apply).not.toHaveBeenCalled();+ expect(deps.marker.write).not.toHaveBeenCalled();++ const [sessionId, instanceId, card] = vi.mocked(deps.requestHostPermission).mock.calls[0]!;+ expect([sessionId, instanceId]).toEqual(['task-1', 'instance-1']);+ expect(card).toMatchObject({+ kind: 'permission',+ toolName: AGENT_APP_UPDATE_TOOL_NAME,+ title: 'update.agentInstall.title',+ input: { from: '0.1.86', to: '0.1.90' },+ metadata: { hostOwnedConfirmation: 'app_update' },+ });+ expect(card.suggestions).toBeUndefined();+ expect(card.description?.split('\n')).toEqual([+ 'update.agentInstall.versions',+ 'update.agentInstall.otherTasks',+ 'update.agentInstall.thisTask',+ 'update.agentInstall.remote',+ ]);++ resolveCard(allow());+ await expect(pending).resolves.toMatchObject({+ status: 'started',+ currentVersion: '0.1.86',+ targetVersion: '0.1.90',+ });+ await flush();+ expect(deps.apply).toHaveBeenCalledOnce();+ expect(deps.waitForCallerTurnToEnd).toHaveBeenCalledWith(caller);+ expect(deps.marker.write).toHaveBeenCalledWith(+ expect.objectContaining({+ sessionId: 'task-1',+ fromVersion: '0.1.86',+ targetVersion: '0.1.90',+ pid: 100,+ }),+ );+ });++ it.each([+ ['deny', deny('user_denied'), { status: 'declined' }],+ ['timeout', deny('interaction_timeout'), { status: 'confirmation_timeout' }],+ ['abort', deny('session_aborted'), { status: 'declined' }],+ [+ 'undelivered',+ deny('no_interaction_route'),+ { ok: false, errorCode: 'CONFIRMATION_UNAVAILABLE' },+ ],+ ])('does nothing when the card is answered with %s', async (_label, decision, expected) => {+ 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();+ // The flow is released: a later request raises a fresh card.+ await service.install(caller);+ expect(deps.requestHostPermission).toHaveBeenCalledTimes(2);+ });++ it('refuses non-owner turns before any card or download', async () => {+ const { deps, service } = setup({ resolveCaller: vi.fn(() => 'not-owner' as const) });+ await expect(service.install(caller)).resolves.toMatchObject({+ ok: false,+ errorCode: 'OWNER_TURN_REQUIRED',+ });+ expect(deps.check).not.toHaveBeenCalled();+ expect(deps.requestHostPermission).not.toHaveBeenCalled();+ expect(deps.apply).not.toHaveBeenCalled();+ });++ it('re-checks the caller after approval and stops if the task went away', async () => {+ const resolveCaller = vi.fn().mockReturnValueOnce('owner').mockReturnValueOnce('unavailable');+ const { deps, service } = setup({ resolveCaller });+ await expect(service.install(caller)).resolves.toMatchObject({+ ok: false,+ errorCode: 'CALLER_UNAVAILABLE',+ });+ expect(deps.apply).not.toHaveBeenCalled();+ });++ it('returns unsupported reasons without a card', async () => {+ const { deps, service } = setup({+ check: vi.fn(async () => ({+ status: 'unsupported',+ currentVersion: '0.0.0',+ reason: '此构建不支持应用内更新。',+ })),+ });+ await expect(service.install(caller)).resolves.toMatchObject({+ status: 'unsupported',+ reason: '此构建不支持应用内更新。',+ });+ expect(deps.requestHostPermission).not.toHaveBeenCalled();+ });++ it('keeps one install request: repeats neither raise another card nor download again', async () => {+ let resolveCard!: (decision: InteractionDecision) => void;+ let finishApply!: () => void;+ const { deps, service } = setup({+ requestHostPermission: vi.fn(+ () =>+ new Promise<InteractionDecision>((resolve) => {+ resolveCard = resolve;+ }),+ ),+ apply: vi.fn(+ () =>+ new Promise<{ status: 'relaunching' }>((resolve) => {+ finishApply = () => resolve({ status: 'relaunching' });+ }),+ ),+ });+ const first = service.install(caller);+ await flush();+ await expect(service.install(caller)).resolves.toMatchObject({+ status: 'confirmation_pending',+ });+ resolveCard(allow());+ await first;+ await expect(service.install(caller)).resolves.toMatchObject({+ status: 'in_progress',+ targetVersion: '0.1.90',+ });+ expect(deps.requestHostPermission).toHaveBeenCalledOnce();+ expect(deps.apply).toHaveBeenCalledOnce();+ finishApply();+ });++ it('writes an immediate failure back to the task when no restart happened', async () => {+ const { deps, service, getMarker } = setup({+ apply: vi.fn(async () => ({+ status: 'failed' as const,+ reason: '下载更新失败,请稍后重试。',+ errorCode: 'download_failed',+ })),+ });+ await service.install(caller);+ await flush();+ expect(getMarker()).toBeNull();+ expect(deps.notify).toHaveBeenCalledWith(+ 'task-1',+ expect.stringMatching(/^agent-app-update:/),+ 'update.agentInstall.failed 下载更新失败,请稍后重试。 update.agentInstall.retryHint',+ );+ // Released after the failure.+ await service.install(caller);+ expect(deps.requestHostPermission).toHaveBeenCalledTimes(2);+ });++ it('mentions the Linux password prompt only on Linux', async () => {+ const { deps, service } = setup({ platform: 'linux', countOtherRunningTasks: vi.fn(() => 0) });+ await service.install(caller);+ const card = vi.mocked(deps.requestHostPermission).mock.calls[0]![2];+ expect(card.description).toContain('update.agentInstall.noOtherTasks');+ expect(card.description).toContain('update.agentInstall.linuxAuth');+ });+});++describe('Agent app update result after restart', () => {+ const marker = (overrides: Partial<AgentAppUpdateMarker> = {}): AgentAppUpdateMarker => ({+ requestId: 'req-1',+ sessionId: 'task-1',+ fromVersion: '0.1.86',+ targetVersion: '0.1.90',+ requestedAt: 900,+ pid: 99,+ ...overrides,+ });++ it('reports the new version once and clears the marker', async () => {+ const { deps, service, setMarker, getMarker } = setup({+ appVersion: () => '0.1.90',+ translate: (key) =>+ key === 'update.agentInstall.succeeded' ? 'updated to {{version}} from {{from}}' : key,+ });+ setMarker(marker());+ await service.deliverPendingResult();+ await service.deliverPendingResult();+ expect(deps.notify).toHaveBeenCalledOnce();+ expect(deps.notify).toHaveBeenCalledWith(+ 'task-1',+ 'agent-app-update:req-1',+ 'updated to 0.1.90 from 0.1.86',+ );+ expect(getMarker()).toBeNull();+ });++ it('reports a failed install when the version did not change', async () => {+ const { deps, service, setMarker } = setup();+ setMarker(marker());+ await service.deliverPendingResult();+ expect(deps.notify).toHaveBeenCalledWith(+ 'task-1',+ 'agent-app-update:req-1',+ 'update.agentInstall.failed update.agentInstall.retryHint',+ );+ });++ it('ignores a marker written by this same process (no restart yet)', async () => {+ const { deps, service, setMarker, getMarker } = setup();+ setMarker(marker({ pid: 100 }));+ await service.deliverPendingResult();+ expect(deps.notify).not.toHaveBeenCalled();+ expect(getMarker()).not.toBeNull();+ });++ it('drops stale markers silently', async () => {+ const { deps, service, setMarker, getMarker } = setup({+ now: () => 900 + 8 * 24 * 60 * 60 * 1000,+ });+ setMarker(marker());+ await service.deliverPendingResult();+ expect(deps.notify).not.toHaveBeenCalled();+ expect(getMarker()).toBeNull();+ });+});++describe('Agent auto update switch and hint', () => {+ it('writes the existing setting only after the owner approves', async () => {+ const { deps, service } = setup();+ await expect(service.setAutoUpdate(caller, true)).resolves.toMatchObject({+ status: 'updated',+ autoUpdateEnabled: true,+ });+ expect(vi.mocked(deps.requestHostPermission).mock.calls[0]![2]).toMatchObject({+ toolName: AGENT_APP_AUTO_UPDATE_TOOL_NAME,+ input: { enabled: true },+ title: 'update.agentAutoUpdate.enableTitle',+ });+ expect(deps.writeAutoUpdate).toHaveBeenCalledWith(true);+ // Already enabled: no card, no write.+ await expect(service.setAutoUpdate(caller, true)).resolves.toMatchObject({+ status: 'unchanged',+ });+ expect(deps.requestHostPermission).toHaveBeenCalledOnce();+ });++ it('leaves the setting alone when declined or requested by a non-owner turn', async () => {+ const declined = setup({ requestHostPermission: vi.fn(async () => deny()) });+ await expect(declined.service.setAutoUpdate(caller, true)).resolves.toMatchObject({+ status: 'declined',+ });+ expect(declined.deps.writeAutoUpdate).not.toHaveBeenCalled();++ const guest = setup({ resolveCaller: vi.fn(() => 'not-owner' as const) });+ await expect(guest.service.setAutoUpdate(caller, true)).resolves.toMatchObject({+ errorCode: 'OWNER_TURN_REQUIRED',+ });+ expect(guest.deps.requestHostPermission).not.toHaveBeenCalled();+ });++ it('hints auto update once per task while it is off and an update exists', async () => {+ const { service } = setup();+ await expect(service.check(caller)).resolves.toMatchObject({+ autoUpdateEnabled: false,+ autoUpdateHint: true,+ });+ expect(await service.check(caller)).not.toHaveProperty('autoUpdateHint');+ await expect(service.check({ ...caller, sessionId: 'task-2' })).resolves.toMatchObject({+ autoUpdateHint: true,+ });+ });++ it('does not hint without an installable update or when already enabled', async () => {+ const noUpdate = setup({+ check: vi.fn(async () => ({ status: 'no_installable_update', currentVersion: '0.1.90' })),+ });+ expect(await noUpdate.service.check(caller)).not.toHaveProperty('autoUpdateHint');+ const enabled = setup({ readAutoUpdate: () => true });+ await expect(enabled.service.check(caller)).resolves.toMatchObject({ autoUpdateEnabled: true });+ expect(await enabled.service.check(caller)).not.toHaveProperty('autoUpdateHint');+ });+});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.tsnew file mode 100644index 0000000000..8249749e64--- /dev/null+++ b/apps/desktop/src/main/agent-app-update/__tests__/callerAuthority.test.ts@@ -0,0 +1,74 @@+import { describe, expect, it, vi } from 'vitest';++import { isAppUpdateOwnerTurn, type AppUpdateCallerFacts } from '../callerAuthority.js';++function facts(overrides: Partial<AppUpdateCallerFacts> = {}): AppUpdateCallerFacts {+ return {+ turnRunning: true,+ turnOrigin: null,+ route: null,+ ownerAuthoredInput: () => true,+ ...overrides,+ };+}++describe('isAppUpdateOwnerTurn', () => {+ it('accepts an owner-typed Desktop or same-account phone turn', () => {+ expect(isAppUpdateOwnerTurn(facts())).toBe(true);+ });++ it('refuses when no turn is running', () => {+ expect(isAppUpdateOwnerTurn(facts({ turnRunning: false }))).toBe(false);+ });++ it.each([+ { kind: 'scheduler' as const, scheduleId: 's', scheduleName: 'n' },+ { kind: 'goal' as const, goalSessionId: 'task' },+ ])('refuses automated turns ($kind)', (origin) => {+ const ownerAuthoredInput = vi.fn(() => true);+ expect(isAppUpdateOwnerTurn(facts({ turnOrigin: origin, ownerAuthoredInput }))).toBe(false);+ expect(ownerAuthoredInput).not.toHaveBeenCalled();+ });++ it('refuses inputs the coordinator cannot attribute to the owner (other task, guest, resume)', () => {+ expect(isAppUpdateOwnerTurn(facts({ ownerAuthoredInput: () => false }))).toBe(false);+ });++ it('uses the channel owner check for IM and official-bot turns', () => {+ const imRoute = (requesterAuthority?: 'owner' | 'guest' | 'unknown') => ({+ origin: { kind: 'im' as const, channel: 'telegram' as const },+ requesterAuthority,+ });+ const ownerAuthoredInput = vi.fn(() => true);+ expect(isAppUpdateOwnerTurn(facts({ route: imRoute('owner'), ownerAuthoredInput }))).toBe(true);+ expect(isAppUpdateOwnerTurn(facts({ route: imRoute('unknown'), ownerAuthoredInput }))).toBe(+ false,+ );+ expect(isAppUpdateOwnerTurn(facts({ route: imRoute('guest'), ownerAuthoredInput }))).toBe(+ false,+ );+ expect(isAppUpdateOwnerTurn(facts({ route: imRoute(undefined), ownerAuthoredInput }))).toBe(+ false,+ );+ expect(+ isAppUpdateOwnerTurn(+ facts({+ route: { origin: { kind: 'hook', source: 'telegram' }, requesterAuthority: 'owner' },+ }),+ ),+ ).toBe(true);+ // A channel route never falls back to Desktop input evidence.+ expect(ownerAuthoredInput).not.toHaveBeenCalled();+ });++ it('refuses scheduler routes and IM turns without a route', () => {+ expect(+ isAppUpdateOwnerTurn(+ facts({ route: { origin: { kind: 'scheduler' }, requesterAuthority: 'owner' } }),+ ),+ ).toBe(false);+ expect(isAppUpdateOwnerTurn(facts({ turnOrigin: { kind: 'user', surface: 'im' } }))).toBe(+ false,+ );+ });+});diff --git a/apps/desktop/src/main/agent-app-update/agentAppUpdateService.ts b/apps/desktop/src/main/agent-app-update/agentAppUpdateService.tsnew file mode 100644index 0000000000..a0fdeb3048--- /dev/null+++ b/apps/desktop/src/main/agent-app-update/agentAppUpdateService.ts@@ -0,0 +1,364 @@+/**+ * Agent-initiated Cindy updates (install / idle auto-install switch).+ *+ * The Agent never installs anything itself. Each request becomes a Host-owned+ * permission card on the calling task (Desktop, same-account phone and IM card+ * share one decision through the interaction router; Full Access cannot skip it+ * because it never passes the Agent's own approval callback). Only after the+ * owner approves does the built-in updater run, via the same check → download →+ * relaunch state machine as Settings → About.+ *+ * Restarting ends this process, so the outcome is recorded in an owner-scoped+ * marker and written back to the calling task on the next start.+ */+import { randomUUID } from 'node:crypto';++import type { InteractionDecision, InteractionRequest } from '@cindy/maker-core';++import {+ AGENT_APP_AUTO_UPDATE_TOOL_NAME,+ AGENT_APP_UPDATE_HOST_CONFIRMATION,+ AGENT_APP_UPDATE_TOOL_NAME,+} from './constants.js';++export interface AgentAppUpdateCaller {+ sessionId: string;+ sessionInstanceId: string;+}++export interface AgentAppUpdateCheck {+ status: string;+ currentVersion: string;+ targetVersion?: string;+ reason?: string;+}++export type AgentAppUpdateApplyResult =+ | { status: 'relaunching'; targetVersion?: string }+ | { status: 'failed'; reason: string; errorCode?: string };++export interface AgentAppUpdateMarker {+ requestId: string;+ sessionId: string;+ fromVersion: string;+ targetVersion?: string;+ requestedAt: number;+ /** Process that wrote the marker; a same-process read is not a restart. */+ pid: number;+}++type PermissionRequest = Extract<InteractionRequest, { kind: 'permission' }>;++export interface AgentAppUpdateDeps {+ appVersion(): string;+ platform: NodeJS.Platform;+ pid: number;+ now(): number;+ check(): Promise<AgentAppUpdateCheck>;+ apply(options: { beforeRelaunch: () => Promise<boolean> }): Promise<AgentAppUpdateApplyResult>;+ readAutoUpdate(): boolean;+ writeAutoUpdate(enabled: boolean): boolean;+ /** 'owner' only for a live local turn the account owner started (see callerAuthority.ts). */+ resolveCaller(caller: AgentAppUpdateCaller): 'owner' | 'not-owner' | 'unavailable';+ countOtherRunningTasks(callerSessionId: string): number;+ /** Host permission card on the calling task; null when that task is gone. */+ requestHostPermission(+ sessionId: string,+ sessionInstanceId: string,+ request: PermissionRequest,+ signal: AbortSignal,+ ): Promise<InteractionDecision | null>;+ /** Let the calling turn finish its reply before the restart (bounded by the host). */+ waitForCallerTurnToEnd(caller: AgentAppUpdateCaller): Promise<void>;+ marker: {+ write(marker: AgentAppUpdateMarker): void;+ read(): AgentAppUpdateMarker | null;+ clear(): void;+ };+ /** Persist a visible host notice in the task (idempotent per clientId). */+ notify(sessionId: string, clientId: string, text: string): Promise<void>;+ compareVersions(candidate: string | undefined, current: string): string;+ translate(key: string): string;+ logger?: { info?(msg: string, meta?: unknown): void; warn?(msg: string, meta?: unknown): void };+}++type ToolResult = Record<string, unknown>;++/** Card answers that never reached the user; reporting them as a refusal would mislead. */+const UNDELIVERED_REASONS = new Set([+ 'no_interaction_route',+ 'interaction_handler_failed',+ 'duplicate_request_id',+]);+const MARKER_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;+const UPDATABLE_STATUSES = new Set(['available', 'ready', 'downloading']);+const HINT_SESSION_LIMIT = 500;++function interpolate(template: string, args: Record<string, string | number>): string {+ return template.replace(/\{\{\s*(\w+)\s*\}\}/g, (match, name: string) =>+ Object.prototype.hasOwnProperty.call(args, name) ? String(args[name]) : match,+ );+}++function ownerTurnRequired(): ToolResult {+ return {+ ok: false,+ errorCode: 'OWNER_TURN_REQUIRED',+ message:+ '只有 Cindy 主人本人在本机、手机远程或私聊中发起的请求才能更新 Cindy;自动化、其他任务、群成员或共享任务成员的消息不能触发。',+ };+}++function callerUnavailable(): ToolResult {+ return { ok: false, errorCode: 'CALLER_UNAVAILABLE', message: '当前任务实例已结束或不再有效。' };+}++export function createAgentAppUpdateService(deps: AgentAppUpdateDeps) {+ const text = (key: string, args: Record<string, string | number> = {}) =>+ interpolate(deps.translate(key), args);+ /** One install request at a time: a pending card or a started install blocks repeats. */+ let flow: { kind: 'confirming' | 'installing'; targetVersion?: string } | null = null;+ let autoUpdateConfirming = false;+ const hintedSessions = new Set<string>();++ const decide = async (+ caller: AgentAppUpdateCaller,+ request: PermissionRequest,+ ): Promise<'allow' | 'deny' | 'timeout' | 'undelivered' | 'unavailable'> => {+ const decision = await deps.requestHostPermission(+ caller.sessionId,+ caller.sessionInstanceId,+ request,+ new AbortController().signal,+ );+ if (!decision || decision.kind !== 'permission') return 'unavailable';+ if (decision.behavior === 'allow') return 'allow';+ if (decision.reason && UNDELIVERED_REASONS.has(decision.reason)) return 'undelivered';+ if (decision.reason && /timeout/.test(decision.reason)) return 'timeout';+ return 'deny';+ };++ const declined = (outcome: 'deny' | 'timeout' | 'undelivered' | 'unavailable'): ToolResult => {+ if (outcome === 'unavailable') return callerUnavailable();+ if (outcome === 'undelivered') {+ return {+ ok: false,+ errorCode: 'CONFIRMATION_UNAVAILABLE',+ message: '确认卡没有送达用户,未做任何更改。',+ };+ }+ return {+ status: outcome === 'timeout' ? 'confirmation_timeout' : 'declined',+ message: '用户没有确认,未做任何更改。',+ };+ };++ const buildInstallCard = (+ caller: AgentAppUpdateCaller,+ from: string,+ to: string,+ ): PermissionRequest => {+ const others = deps.countOtherRunningTasks(caller.sessionId);+ const lines = [+ text('update.agentInstall.versions', { from, to }),+ others > 0+ ? text('update.agentInstall.otherTasks', { count: others })+ : text('update.agentInstall.noOtherTasks'),+ text('update.agentInstall.thisTask'),+ text('update.agentInstall.remote'),+ ...(deps.platform === 'linux' ? [text('update.agentInstall.linuxAuth')] : []),+ ];+ return {+ kind: 'permission',+ requestId: randomUUID(),+ toolName: AGENT_APP_UPDATE_TOOL_NAME,+ title: text('update.agentInstall.title', { version: to }),+ description: lines.join('\n'),+ input: { from, to },+ metadata: { hostOwnedConfirmation: AGENT_APP_UPDATE_HOST_CONFIRMATION },+ };+ };++ const reportFailure = async (sessionId: string, requestId: string, reason: string) => {+ const message = [+ text('update.agentInstall.failed', { version: deps.appVersion() }),+ reason,+ text('update.agentInstall.retryHint'),+ ]+ .filter(Boolean)+ .join(' ');+ try {+ await deps.notify(sessionId, `agent-app-update:${requestId}`, message);+ } catch (error) {+ deps.logger?.warn?.('agent app update failure notice failed', { error: String(error) });+ }+ };++ const runInstall = async (caller: AgentAppUpdateCaller, marker: AgentAppUpdateMarker) => {+ try {+ const result = await deps.apply({+ beforeRelaunch: async () => {+ await deps.waitForCallerTurnToEnd(caller);+ return true;+ },+ });+ // A relaunch ends this process; the next start reports from the marker.+ if (result.status === 'relaunching') return;+ deps.marker.clear();+ await reportFailure(caller.sessionId, marker.requestId, result.reason);+ } catch (error) {+ deps.marker.clear();+ await reportFailure(+ caller.sessionId,+ marker.requestId,+ String(error instanceof Error ? error.message : error),+ );+ } finally {+ flow = null;+ }+ };++ return {+ async check(+ caller: AgentAppUpdateCaller,+ ): Promise<AgentAppUpdateCheck & { autoUpdateEnabled: boolean; autoUpdateHint?: true }> {+ const result = await deps.check();+ const autoUpdateEnabled = deps.readAutoUpdate();+ // Suggest the switch at most once per task, and only when it would matter.+ const hint =+ !autoUpdateEnabled &&+ UPDATABLE_STATUSES.has(result.status) &&+ !hintedSessions.has(caller.sessionId);+ if (hint) {+ if (hintedSessions.size >= HINT_SESSION_LIMIT) hintedSessions.clear();+ hintedSessions.add(caller.sessionId);+ }+ return { ...result, autoUpdateEnabled, ...(hint ? { autoUpdateHint: true as const } : {}) };+ },++ async install(caller: AgentAppUpdateCaller): Promise<ToolResult> {+ if (flow) {+ return flow.kind === 'confirming'+ ? {+ status: 'confirmation_pending',+ message: '已有一张更新确认卡在等待用户处理,不要重复发起。',+ }+ : {+ status: 'in_progress',+ targetVersion: flow.targetVersion,+ message: '更新已在进行中,完成后 Cindy 会自动重启。',+ };+ }+ const authority = deps.resolveCaller(caller);+ if (authority === 'unavailable') return callerUnavailable();+ if (authority !== 'owner') return ownerTurnRequired();+ flow = { kind: 'confirming' };+ let started = false;+ try {+ const check = await deps.check();+ if (!UPDATABLE_STATUSES.has(check.status)) return { ...check };+ const from = check.currentVersion;+ // A first background download has no staged version yet.+ const to = check.targetVersion ?? text('update.agentInstall.latestVersion');+ flow.targetVersion = check.targetVersion;+ const outcome = await decide(caller, buildInstallCard(caller, from, to));+ if (outcome !== 'allow') return declined(outcome);+ // The user may have stopped or replaced the task while the card was open.+ const current = deps.resolveCaller(caller);+ if (current === 'unavailable') return callerUnavailable();+ if (current !== 'owner') return ownerTurnRequired();+ const marker: AgentAppUpdateMarker = {+ requestId: randomUUID(),+ sessionId: caller.sessionId,+ fromVersion: from,+ ...(check.targetVersion ? { targetVersion: check.targetVersion } : {}),+ requestedAt: deps.now(),+ pid: deps.pid,+ };+ deps.marker.write(marker);+ flow = { kind: 'installing', targetVersion: check.targetVersion };+ started = true;+ void runInstall(caller, marker);+ return {+ status: 'started',+ currentVersion: from,+ targetVersion: check.targetVersion,+ message:+ 'Cindy 正在通过内置更新器下载并安装更新,本轮回复结束后会自动重启;重启后结果会写回本任务。请简短告知用户,不要再执行其他操作。',+ };+ } finally {+ if (!started) flow = null;+ }+ },++ async setAutoUpdate(caller: AgentAppUpdateCaller, enabled: boolean): Promise<ToolResult> {+ const authority = deps.resolveCaller(caller);+ if (authority === 'unavailable') return callerUnavailable();+ if (authority !== 'owner') return ownerTurnRequired();+ if (deps.readAutoUpdate() === enabled)+ return { status: 'unchanged', autoUpdateEnabled: enabled };+ if (autoUpdateConfirming) {+ return {+ status: 'confirmation_pending',+ message: '已有一张自动更新确认卡在等待用户处理。',+ };+ }+ autoUpdateConfirming = true;+ try {+ const outcome = await decide(caller, {+ kind: 'permission',+ requestId: randomUUID(),+ toolName: AGENT_APP_AUTO_UPDATE_TOOL_NAME,+ title: text(+ enabled ? 'update.agentAutoUpdate.enableTitle' : 'update.agentAutoUpdate.disableTitle',+ ),+ description: [+ text(+ enabled+ ? 'update.agentAutoUpdate.enableDescription'+ : 'update.agentAutoUpdate.disableDescription',+ ),+ text('update.agentAutoUpdate.settingsHint'),+ ].join('\n'),+ input: { enabled },+ metadata: { hostOwnedConfirmation: AGENT_APP_UPDATE_HOST_CONFIRMATION },+ });+ if (outcome !== 'allow') return declined(outcome);+ const current = deps.resolveCaller(caller);+ if (current === 'unavailable') return callerUnavailable();+ if (current !== 'owner') return ownerTurnRequired();+ return { status: 'updated', autoUpdateEnabled: deps.writeAutoUpdate(enabled) };+ } finally {+ autoUpdateConfirming = false;+ }+ },++ /** Write the outcome of a pre-restart install back to its task. Safe to call repeatedly. */+ async deliverPendingResult(): Promise<void> {+ const marker = deps.marker.read();+ if (!marker || marker.pid === deps.pid) return;+ if (deps.now() - marker.requestedAt > MARKER_MAX_AGE_MS) {+ deps.marker.clear();+ return;+ }+ const version = deps.appVersion();+ const updated = deps.compareVersions(version, marker.fromVersion) === 'newer';+ const message = updated+ ? text('update.agentInstall.succeeded', { version, from: marker.fromVersion })+ : [+ text('update.agentInstall.failed', { version }),+ text('update.agentInstall.retryHint'),+ ].join(' ');+ try {+ await deps.notify(marker.sessionId, `agent-app-update:${marker.requestId}`, message);+ } catch (error) {+ // A deleted task or a different account cannot receive it; do not retry forever.+ deps.logger?.warn?.('agent app update result notice failed', { error: String(error) });+ }+ deps.marker.clear();+ deps.logger?.info?.('agent app update result delivered', { updated });+ },+ };+}++export type AgentAppUpdateService = ReturnType<typeof createAgentAppUpdateService>;diff --git a/apps/desktop/src/main/agent-app-update/callerAuthority.ts b/apps/desktop/src/main/agent-app-update/callerAuthority.tsnew file mode 100644index 0000000000..ffe024bd5e--- /dev/null+++ b/apps/desktop/src/main/agent-app-update/callerAuthority.ts@@ -0,0 +1,42 @@+import type { SendOrigin } from '@cindy/maker-core';++import type { InteractionRoute } from '../maker-ipc/interactionRouter.js';++export interface AppUpdateCallerFacts {+ /** The calling task is executing the turn that issued this tool call. */+ 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. */+ route: Pick<InteractionRoute, 'origin' | 'requesterAuthority'> | null;+ /** Coordinator evidence that the active Desktop/phone input was typed by the owner. */+ ownerAuthoredInput: () => boolean;+}++/**+ * Only a turn the account owner started may raise an app-update card. Positive+ * evidence is required from exactly one source; anything automated, delegated or+ * 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`);+ * - 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).+ */+export function isAppUpdateOwnerTurn(facts: AppUpdateCallerFacts): boolean {+ if (!facts.turnRunning) return false;+ const origin = facts.turnOrigin;+ 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 !== 'desktop') return false;+ } else if (origin?.surface === 'im') {+ // An IM turn always owns a route; without one its sender is unproven.+ return false;+ }+ return facts.ownerAuthoredInput();+}diff --git a/apps/desktop/src/main/agent-app-update/constants.ts b/apps/desktop/src/main/agent-app-update/constants.tsnew file mode 100644index 0000000000..a62bbbe883--- /dev/null+++ b/apps/desktop/src/main/agent-app-update/constants.ts@@ -0,0 +1,16 @@+/**+ * Host confirmation cards raised by the Agent app-update tools. They reuse the+ * generic `permission` interaction, so Desktop, same-account phones and IM cards+ * render them without upgrades. Only the owner may answer them: shared-task+ * guests are refused by name at the device-link boundary.+ */+export const AGENT_APP_UPDATE_TOOL_NAME = 'cindy.app.update';+export const AGENT_APP_AUTO_UPDATE_TOOL_NAME = 'cindy.app.auto_update';++export const AGENT_APP_UPDATE_HOST_CONFIRMATION = 'app_update';++/** Owner-only Host cards; shared-task guests may not answer these. */+export const OWNER_ONLY_HOST_CONFIRMATION_TOOL_NAMES: ReadonlySet<string> = new Set([+ AGENT_APP_UPDATE_TOOL_NAME,+ AGENT_APP_AUTO_UPDATE_TOOL_NAME,+]);diff --git a/apps/desktop/src/main/agent-app-update/index.ts b/apps/desktop/src/main/agent-app-update/index.tsnew file mode 100644index 0000000000..6c014f4514--- /dev/null+++ b/apps/desktop/src/main/agent-app-update/index.ts@@ -0,0 +1,163 @@+/**+ * Desktop wiring for the Agent app-update tools. Session facts (caller authority,+ * running tasks, Host cards) come from Maker Host; updater work goes through the+ * existing updateService entry points only.+ */+import fs from 'node:fs';+import path from 'node:path';+import { app } from 'electron';++import type { XdtHelperMcpDeps } from '@cindy/mcps';++import { ownerScopedUserDataPath } from '../appSessionState.js';+import {+ captureDataOwnerBroadcastScope,+ isDataOwnerBroadcastScopeCurrent,+} from '../device-link/broadcast-tap.js';+import { t } from '../i18n.js';+import { createMessage } from '../localDb/ipc/messages.js';+import { createLogger } from '../logger.js';+import {+ applyConfirmedAppUpdateForAgent,+ checkAppUpdateForAgent,+ readAutoRelaunchOnIdleForAgent,+ setAutoRelaunchOnIdleForAgent,+} from '../updateService.js';+import { compareAppUpdateVersions } from '../updateVersionPolicy.js';+import { atomicWriteFileSync, readAtomicFileSync } from '../utils/atomicWriteFile.js';+import {+ createAgentAppUpdateService,+ type AgentAppUpdateDeps,+ type AgentAppUpdateMarker,+ type AgentAppUpdateService,+} from './agentAppUpdateService.js';++type AppUpdateCallbacks = NonNullable<XdtHelperMcpDeps['appUpdate']>;++const log = createLogger('agent-app-update');+const MARKER_FILE = 'agent-app-update.json';++export type AgentAppUpdateSessionHost = Pick<+ AgentAppUpdateDeps,+ 'resolveCaller' | 'countOtherRunningTasks' | 'requestHostPermission' | 'waitForCallerTurnToEnd'+>;++let sessionHost: AgentAppUpdateSessionHost | null = null;+let service: AgentAppUpdateService | null = null;++function markerPath(): string {+ return ownerScopedUserDataPath(MARKER_FILE);+}++function parseMarker(raw: string | null): AgentAppUpdateMarker | null {+ if (!raw) return 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,+ };+ } catch {+ return null;+ }+}++function requireSessionHost(): AgentAppUpdateSessionHost {+ if (!sessionHost) throw new Error('Agent app update host is not ready');+ return sessionHost;+}++function getService(): AgentAppUpdateService {+ service ??= createAgentAppUpdateService({+ appVersion: () => app.getVersion(),+ platform: process.platform,+ pid: process.pid,+ now: () => Date.now(),+ check: checkAppUpdateForAgent,+ apply: applyConfirmedAppUpdateForAgent,+ readAutoUpdate: readAutoRelaunchOnIdleForAgent,+ writeAutoUpdate: setAutoRelaunchOnIdleForAgent,+ resolveCaller: (caller) => sessionHost?.resolveCaller(caller) ?? 'unavailable',+ countOtherRunningTasks: (sessionId) => requireSessionHost().countOtherRunningTasks(sessionId),+ requestHostPermission: (...args) => requireSessionHost().requestHostPermission(...args),+ waitForCallerTurnToEnd: (caller) => requireSessionHost().waitForCallerTurnToEnd(caller),+ marker: {+ write: (marker) => {+ const file = markerPath();+ fs.mkdirSync(path.dirname(file), { recursive: true });+ atomicWriteFileSync(file, JSON.stringify(marker));+ },+ read: () => {+ try {+ return parseMarker(readAtomicFileSync(markerPath()));+ } catch (error) {+ log.warn('agent app update marker read failed', { error: String(error) });+ return null;+ }+ },+ clear: () => {+ const file = markerPath();+ 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) });+ }+ }+ },+ },+ notify: async (sessionId, clientId, text) => {+ const ownerScope = captureDataOwnerBroadcastScope();+ await createMessage(+ sessionId,+ { clientId, role: 'assistant', content: text },+ {+ broadcastOwnerScope: ownerScope,+ shouldBroadcast: () => isDataOwnerBroadcastScopeCurrent(ownerScope),+ },+ );+ },+ compareVersions: compareAppUpdateVersions,+ translate: (key) => t(key),+ logger: log,+ });+ return service;+}++/** Maker Host supplies live-session facts once its Maker exists. */+export function setAgentAppUpdateSessionHost(host: AgentAppUpdateSessionHost | null): void {+ sessionHost = host;+}++/** cindy_helper app_update callbacks. */+export function createAgentAppUpdateCallbacks(+ isCurrentSession: AppUpdateCallbacks['isCurrentSession'],+): AppUpdateCallbacks {+ return {+ isCurrentSession,+ check: (caller) => getService().check(caller),+ install: (caller) => getService().install(caller),+ setAutoUpdate: (caller, enabled) => getService().setAutoUpdate(caller, enabled),+ };+}++/** Called after the owner's database is ready; reports an install started before the last restart. */+export async function deliverPendingAgentAppUpdateResult(): Promise<void> {+ try {+ await getService().deliverPendingResult();+ } catch (error) {+ log.warn('agent app update result delivery failed', { error: String(error) });+ }+}diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 3e1bd9cc15..4295b05449 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -454,6 +454,7 @@ import {} from './localDb/index';import { createDbClient, createInprocDbClient } from './localDb/client/DbClient';import { createLifecycleDbClientManager } from './localDb/client/lifecycleDbClient';+import { deliverPendingAgentAppUpdateResult } from './agent-app-update/index';import {clearCurrentDbClient,getCurrentDbClientUserId,@@ -9052,6 +9053,8 @@ app.on('ready', async () => {void restoreBotRuntimeForCurrentOwner();void restoreOrcaRemoteWorkersForCurrentOwner();startReadyWorktreeMaintenance();+ // An Agent-approved update restarted the app: write its outcome back to the task.+ void deliverPendingAgentAppUpdateResult();if (dbClientTakeover.mode === 'unchanged') {// 副窗口会再次走 localDb.ensureReady;同 owner 的 lifecycle client 已由首个// onReady 完整启动,因此这里只保留 DB 连接交接,不重复执行账号级启动维护。diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskDispatch.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskDispatch.test.tsindex 69ab93924a..fcb0ea54f7 100644--- a/apps/desktop/src/main/device-link/__tests__/sharedTaskDispatch.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskDispatch.test.ts@@ -102,6 +102,14 @@ describe('sharedTask dispatch scope', () => {args: ['permission-1', { kind: 'permission', behavior: 'allow', permissionUpdates: [permissionSuggestion] }],})).not.toThrow();});+ it.each(['cindy.app.update', 'cindy.app.auto_update'])('keeps the owner-only %s card away from guests', (toolName) => {+ setSharedTaskInteractionReader(() => ({ sessionId: 'task', kind: 'permission', toolName }));+ for (const behavior of ['allow', 'deny']) {+ const args = ['app-update-1', { kind: 'permission', behavior }];+ expect(() => assertSharedTaskInvoke(capture(), { channel: 'maker:resolve-interaction', args })).toThrow('PERMISSION_DENIED');+ expect(() => assertSharedTaskInteractionResolveCurrent(capture(), args)).toThrow('PERMISSION_DENIED');+ }+ });it.each([{ command: 'different-command' }, {}, null])('rejects guest replacement input %j at admission and consumption', (updatedInput) => {setSharedTaskInteractionReader(() => ({ sessionId: 'task', kind: 'permission', toolName: 'Bash' }));const args = ['permission-1', { kind: 'permission', behavior: 'allow', updatedInput }];diff --git a/apps/desktop/src/main/device-link/sharedTaskDispatch.ts b/apps/desktop/src/main/device-link/sharedTaskDispatch.tsindex 8f8eba7c6e..59382be53a 100644--- a/apps/desktop/src/main/device-link/sharedTaskDispatch.ts+++ b/apps/desktop/src/main/device-link/sharedTaskDispatch.ts@@ -2,6 +2,7 @@ import { FILE_BROWSER_EVENT_CHANNEL, FILE_BROWSER_REMOTE_OP_CHANNEL, fsWatchTopiimport type { SharedTaskHost } from './sharedTaskHost.js';import * as subscriptions from './subscriptions.js';import { normalizeWorkingDirForStorage } from '../../shared/workingDir.js';+import { OWNER_ONLY_HOST_CONFIRMATION_TOOL_NAMES } from '../agent-app-update/constants.js';export type SharedTaskPeerCapture = NonNullable<ReturnType<SharedTaskHost['capturePeer']>>;export interface SharedTaskInteractionCapture {@@ -160,7 +161,8 @@ function assertSharedTaskPermissionUpdates(/** Shared-task guests may answer the generic Agent interaction cards. Host-only* confirmations (plugin setup, issue review, grants, and rename prompts) never- * enter this branch and remain protected by the normal origin gate. */+ * enter this branch and remain protected by the normal origin gate. Owner-only+ * Host cards that do use the generic channel (app update) are refused by name. */function assertSharedTaskInteractionResolve(capture: SharedTaskPeerCapture, args: unknown[], sessionId: string,phase: 'invoke' | 'result',@@ -168,6 +170,7 @@ function assertSharedTaskInteractionResolve(if (args.length !== 2 || typeof args[0] !== 'string' || !args[0]) deny();const interaction = phase === 'invoke' ? readInteractionSession?.(args[0]) : undefined;if (phase === 'invoke' && (!interaction || interaction.sessionId !== sessionId)) deny();+ if (interaction?.toolName && OWNER_ONLY_HOST_CONFIRMATION_TOOL_NAMES.has(interaction.toolName)) deny();const decision = record(args[1]);if (!decision || typeof decision.kind !== 'string' || !interactionDecisionKinds.has(decision.kind)) deny();// Guests approve the host-displayed input, never substitute executable input.diff --git a/apps/desktop/src/main/hook-control/session-runner.ts b/apps/desktop/src/main/hook-control/session-runner.tsindex 5508d32d94..3907afa6d5 100644--- a/apps/desktop/src/main/hook-control/session-runner.ts+++ b/apps/desktop/src/main/hook-control/session-runner.ts@@ -1318,6 +1318,9 @@ 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/im/shared/__tests__/channelToolPolicy.test.ts b/apps/desktop/src/main/im/shared/__tests__/channelToolPolicy.test.tsindex be838cbb8c..5922953391 100644--- a/apps/desktop/src/main/im/shared/__tests__/channelToolPolicy.test.ts+++ b/apps/desktop/src/main/im/shared/__tests__/channelToolPolicy.test.ts@@ -50,3 +50,12 @@ describe('channel policy for scheduler command execution', () => {}});});++describe('channel policy for Host app update cards', () => {+ it.each([+ ['cindy.app.update', { from: '0.1.86', to: '0.1.90' }],+ ['cindy.app.auto_update', { enabled: true }],+ ])('lets the owner answer the %s card instead of hard-denying it', (toolName, input) => {+ expect(checkChannelDestructiveToolCall(toolName, input)).toEqual({ destructive: false });+ });+});diff --git a/apps/desktop/src/main/im/shared/__tests__/stopCommandRouting.test.ts b/apps/desktop/src/main/im/shared/__tests__/stopCommandRouting.test.tsindex f32c8d085b..affc4aab3a 100644--- a/apps/desktop/src/main/im/shared/__tests__/stopCommandRouting.test.ts+++ b/apps/desktop/src/main/im/shared/__tests__/stopCommandRouting.test.ts@@ -194,6 +194,16 @@ describe('messageHandler !stop routing', () => {}});+ it.each([+ ['a private chat', {}, true],+ ['the owner in a group', { speaker: { id: 'owner', name: 'Owner', isOwner: true } }, true],+ ['a group member', { speaker: { id: 'guest', name: 'Guest', isOwner: false } }, false],+ ])('marks %s turns with the control-command owner check', async (_label, patch, owner) => {+ deliver(makeEvent({ text: '更新 Cindy', ...patch } as Partial<IMMessageEvent>));+ await vi.waitFor(() => expect(runAgentTurn).toHaveBeenCalledTimes(1));+ expect(runAgentTurn.mock.calls[0][0].requesterIsOwner).toBe(owner);+ });+it('still drops an empty event without a summon, quote or attachment', async () => {deliver(makeEvent({ text: '' }));await flushMicrotasks();diff --git a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.tsindex c4019da92c..3ec3d5cfd4 100644--- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts+++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts@@ -192,6 +192,7 @@ vi.mock('../fbotTitle', () => ({generateAndPersistFbotTitle: mocks.generateAndPersistFbotTitle,}));+import { getActiveInteractionRoute } from '../../../maker-ipc/interactionRouter';import { createTurnRunner, type ImRunAgentTurnArgs, type ImTurnRunner } from '../turnRunner';import {readGroupHistoryAccess,@@ -1048,6 +1049,31 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ()}});+ it.each([+ [true, 'owner'],+ [undefined, 'unknown'],+ ] as const)('stamps the channel owner check onto the interaction route (requesterIsOwner=%s)', async (requesterIsOwner, authority) => {+ const h = setupSession(async () => ({ accepted: true }));+ const localRunner = createTurnRunner(fakeAdapter, fakeRepo, fakeCards);+ try {+ await localRunner.runAgentTurn({+ botContextId: 'cli_test_bot',+ userId: 'ou_user',+ userMessageId: `msg-owner-${String(requesterIsOwner)}`,+ text: '更新 Cindy',+ attachments: [],+ ...(requesterIsOwner ? { requesterIsOwner } : {}),+ });+ expect(getActiveInteractionRoute(h.session as never)).toMatchObject({+ origin: { kind: 'im' },+ requesterAuthority: authority,+ });+ h.emit({ type: 'done', data: {} });+ } finally {+ await localRunner.disposeAllSessions();+ }+ });+it('hard-denies destructive actions nested inside a channel dispatch wrapper', async () => {const h = setupSession(async () => ({ accepted: true }));mocks.checkDestructiveToolCall.mockImplementation((toolName, input) =>diff --git a/apps/desktop/src/main/im/shared/messageHandler.ts b/apps/desktop/src/main/im/shared/messageHandler.tsindex 7afc9d1221..60f80ee71c 100644--- a/apps/desktop/src/main/im/shared/messageHandler.ts+++ b/apps/desktop/src/main/im/shared/messageHandler.ts@@ -408,6 +408,8 @@ export function createMessageHandler(userId: event.senderId,userMessageId: event.messageId,sourceDescription: describeInteractionSource(event),+ // Same owner predicate as control commands: DMs passed the channel's owner gate.+ requesterIsOwner: isCommandAuthorized(event),...(channelNoteSource ? { channelNoteSource } : {}),text: event.text,// 受保护群的触发消息照常起 turn, 但不进会话存档(渠道侧已挡住群历史池,diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.tsindex acb1002b51..70b9575582 100644--- a/apps/desktop/src/main/im/shared/turnRunner.ts+++ b/apps/desktop/src/main/im/shared/turnRunner.ts@@ -317,6 +317,8 @@ interface QueuedSend {/** Durable route side effects run only after provider acceptance, never on enqueue. */onRouteResolved?: (sessionId: string) => void | Promise<void>;turnPermissionPolicy?: TurnPermissionPolicy;+ /** Main-verified owner sender (see ImRunAgentTurnArgs.requesterIsOwner). */+ requesterIsOwner?: boolean;/** 触发消息来自受保护群 —— 正文与附件不进会话存档(见 ImRunAgentTurnArgs)。 */protectedContent?: boolean;groupHistoryAccess?: GroupHistoryAccessScope;@@ -455,6 +457,11 @@ export interface ImRunAgentTurnArgs {trackBackgroundTask?: (operation: () => Promise<void>) => void;/** Optional per-turn host policy (personal WeChat routes confirmations to Desktop). */turnPermissionPolicy?: TurnPermissionPolicy;+ /**+ * The triggering message passed the channel's owner check (DM owner gate or+ * group speaker.isOwner). Only this unlocks owner-only Host actions; omitted = not owner.+ */+ requesterIsOwner?: boolean;/*** 这一轮的触发消息来自「禁止保存内容」的群。*@@ -1107,6 +1114,7 @@ export function createTurnRunner(...(args.beforeProviderStart ? { beforeProviderStart: args.beforeProviderStart } : {}),...(args.onRouteResolved ? { onRouteResolved: args.onRouteResolved } : {}),...(args.turnPermissionPolicy ? { turnPermissionPolicy: args.turnPermissionPolicy } : {}),+ ...(args.requesterIsOwner === true ? { requesterIsOwner: true } : {}),...(args.onEarlyReject ? { onEarlyReject: args.onEarlyReject } : {}),...(args.protectedContent === true ? { protectedContent: true } : {}),...(args.groupHistoryAccess ? { groupHistoryAccess: args.groupHistoryAccess } : {}),@@ -1394,6 +1402,7 @@ export function createTurnRunner(turnId: item.turn.turnId,origin: effectiveTurnPolicy.origin,interactionSurface: 'desktop',+ requesterAuthority: item.requesterIsOwner === true ? 'owner' : 'unknown',...(effectiveTurnPolicy.confirmationTimeoutMs? {timeoutMs: effectiveTurnPolicy.confirmationTimeoutMs,@@ -1413,6 +1422,7 @@ export function createTurnRunner(origin: effectiveTurnPolicy?.origin ?? { kind: 'im', channel },interactionSurface: 'channel-card',sourceDescription: item.turn.sourceDescription,+ requesterAuthority: item.requesterIsOwner === true ? 'owner' : 'unknown',...(effectiveTurnPolicy?.confirmationTimeoutMs? { timeoutMs: effectiveTurnPolicy.confirmationTimeoutMs }: {}),diff --git a/apps/desktop/src/main/maker-host/host-system-prompt.md b/apps/desktop/src/main/maker-host/host-system-prompt.mdindex cc3337dc73..2217c83a46 100644--- a/apps/desktop/src/main/maker-host/host-system-prompt.md+++ b/apps/desktop/src/main/maker-host/host-system-prompt.md@@ -1,4 +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 cindy_helper check_app_update to read the current update channel's version information. If an installable update is available, direct the user to Cindy's built-in Check for Updates action to download and install it; do not download, install or restart the application yourself. 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 tool is unavailable, direct the user to the same built-in action; do not improvise an installer.+When asked to update the Cindy application hosting this task, call cindy_helper install_app_update (check_app_update only reads version information); Cindy asks the user to confirm, then installs with its built-in updater. If the tools report no installable update or that installation is unsupported, relay that reason and do not sideload a release; if they are unavailable, point the user to Check for Updates in Settings on the computer running Cindy. Unless the user explicitly asks for that method, do not update Cindy through shell commands by downloading or replacing the app or by killing or restarting it, and never register a persistent restart job (such as launchctl submit).diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.tsindex 1185703a40..fc38968218 100644--- a/apps/desktop/src/main/maker-host/index.ts+++ b/apps/desktop/src/main/maker-host/index.ts@@ -85,7 +85,9 @@ import { getWorkerLink, updateWorkerStatus } from '../localDb/orcaTeamStore.js';import { cleanupSessionTempAttachments } from '../maker-ipc/normalizeAttachments.js';import { resolveGhostFsSessionSnapshot } from '../maker-ipc/ghostFsSessionSnapshot.js';import { HOST_CONFIRM_TIMEOUT_MS } from '../maker-ipc/hostConfirmTiming.js';-import { requestHostInteraction } from '../maker-ipc/interactionRouter.js';+import { getActiveInteractionRoute, requestHostInteraction } from '../maker-ipc/interactionRouter.js';+import { setAgentAppUpdateSessionHost } from '../agent-app-update/index.js';+import { isAppUpdateOwnerTurn } from '../agent-app-update/callerAuthority.js';import { markKnownOrcaWorkerSession } from '../maker-ipc/orcaManualInterrupt.js';import { markOrcaMcpHydratedIfNeeded } from '../maker-ipc/orcaMcpHydrationCache.js';import { preparePersistedOrcaSessionStart } from '../maker-ipc/orcaSessionStartOptions.js';@@ -112,6 +114,7 @@ import { prepareBotWorkspaceRuntime } from '../maker-ipc/botWorkspaceRuntime.js'import type { MakerSessionCreateOpts } from '../maker-ipc/sessionRequest.js';import {dispatchInterAgentMessage,+ isActiveInputOwnerAuthored,isSessionInTurn,wireSessionToIpc,} from '../maker-ipc/register.js';@@ -394,6 +397,8 @@ type RemoteCcQuery = Awaited<>;let _maker: Maker | null = null;+/** Upper bound for letting the confirming turn finish its reply before an Agent-approved restart. */+const AGENT_APP_UPDATE_TURN_DRAIN_MS = 2 * 60 * 1000;/** Prepared Bot runtime records waiting for the matching Maker startup result. */const pendingBotRuntimeSnapshots = new Map<string, BotProfileRuntimeSnapshot>();// Maker copies start options for every runtime, including rebuilds of one task.@@ -976,7 +981,7 @@ export function getMaker(): Maker {return { ...result, permission: session.stablePermissionModeState,hostCapabilities: Object.fromEntries(Object.entries(session.capabilities).filter(([, value]) => value && typeof value === 'object' && 'supported' in value)),- hostCapabilitiesNote: '宿主支持的交互能力,不等于有同名 Agent 工具。Cindy 应用安装更新和重启须通过内置更新界面;check_app_update 仅检查更新。' };+ hostCapabilitiesNote: '宿主支持的交互能力,不等于有同名 Agent 工具。安装 Cindy 更新须调用 install_app_update,由宿主向用户确认后经内置更新器完成;check_app_update 仅检查更新。' };},botCapabilities: createDesktopBotCapabilityService(),createMediaDownloadContext: (sessionId: string, sessionInstanceId: string) => {@@ -1058,6 +1063,37 @@ export function getMaker(): Maker {requestHostInteraction(session, request, bounded));},};+ // Agent app update: live-session facts for owner-only confirmation cards.+ const liveLocalSession = (sessionId: string, sessionInstanceId: string) => {+ const session = _maker?.getSession(sessionId);+ return session && session.instanceId === sessionInstanceId && session.getStatus() === 'active'+ && !session.remoteHostId ? session : null;+ };+ setAgentAppUpdateSessionHost({+ resolveCaller: ({ sessionId, sessionInstanceId }) => {+ const session = liveLocalSession(sessionId, sessionInstanceId);+ if (!session || isAppSessionBoundaryPending()) return 'unavailable';+ return isAppUpdateOwnerTurn({+ turnRunning: session.isTurnRunning(),+ turnOrigin: session.getCurrentTurnOrigin(),+ route: getActiveInteractionRoute(session),+ ownerAuthoredInput: () => isActiveInputOwnerAuthored(sessionId),+ }) ? 'owner' : 'not-owner';+ },+ countOtherRunningTasks: (callerSessionId) => (_maker?.listActiveSessions() ?? [])+ .filter((session) => session.id !== callerSessionId+ && (isSessionInTurn(session.id) || session.isTurnRunning())).length,+ requestHostPermission: makerMemoryProviderDeps.requestHostPermission,+ // Let the confirming turn deliver its reply first; never block the restart longer than the bound.+ waitForCallerTurnToEnd: async ({ sessionId, sessionInstanceId }) => {+ const deadline = Date.now() + AGENT_APP_UPDATE_TURN_DRAIN_MS;+ while (Date.now() < deadline) {+ const session = liveLocalSession(sessionId, sessionInstanceId);+ if (!session || (!session.isTurnRunning() && !isSessionInTurn(sessionId))) return;+ await new Promise((resolve) => setTimeout(resolve, 500));+ }+ },+ });const orcaTeamStoreAdapter = createDesktopOrcaTeamStoreAdapter({getWorkerLink,updateWorkerStatus,diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.tsindex b26c794785..da65970336 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts@@ -1853,6 +1853,27 @@ describe('AgentInputCoordinator send transaction', () => {expect(h.coordinator.getAcceptedInputProvenance(sid)).toMatchObject({ clientId: 'human', authoredText: 'New direction', originKind: undefined });});+ it.each([+ ['owner-typed text', {}, true],+ ['another task', { origin: { kind: 'session' as const, senderSessionId: 'other', displayText: 'update' } }, false],+ ['automation', { origin: { kind: 'scheduler' as const, scheduleId: 's', scheduleName: 'n' } }, false],+ ['Orca Lead', { origin: { kind: 'orca' as const, senderLabel: 'Lead' } }, false],+ ['a plugin', { sourcePlugin: { pluginId: 'p', name: 'P' } }, false],+ ['a shared-task guest', { sharedTaskAuthor: { sharedTaskId: 't', sessionId: 'owner-authored-input', memberId: 'm', accountId: 'guest', displayName: 'G' } }, false],+ ['an automatic resume', { autoResume: true }, false],+ ['a synthetic UI trigger', { autoReviewUserText: '[UI_ACTION_TRIGGER] continue' }, false],+ ['a delegated continuation', { autoReviewUserText: { kind: 'delegated-continuation' as const } }, false],+ ])('decides whether %s counts as owner-authored for owner-only Host actions', async (_label, patch, expected) => {+ const h = createHarness(), sid = 'owner-authored-input';+ h.sendToAgent.mockImplementationOnce(async () => { h.setRunning(true); return sendSuccess(); });+ expect(h.coordinator.isActiveInputOwnerAuthored(sid)).toBe(false);+ h.coordinator.enqueue(sid, { ...makeItem('input', 'Update Cindy'), autoReviewUserText: 'Update Cindy', ...patch } as AgentInputQueuedMessage);+ await flush();+ expect(h.coordinator.isActiveInputOwnerAuthored(sid)).toBe(expected);+ h.setRunning(false); h.coordinator.onTurnEvent(sid, 'done');+ expect(h.coordinator.isActiveInputOwnerAuthored(sid)).toBe(false);+ });+it('keeps accepted plugin authority through pending and rejected human steering', async () => {const h = createHarness(), sid = 'accepted-plugin-authority';h.sendToAgent.mockImplementationOnce(async () => { h.setRunning(true); return sendSuccess(); });diff --git a/apps/desktop/src/main/maker-ipc/__tests__/interactionRouter.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/interactionRouter.test.tsindex 42d36ec33f..9717db874d 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/interactionRouter.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/interactionRouter.test.ts@@ -3,6 +3,7 @@ import type { InteractionDecision, InteractionRequest } from '@cindy/maker-core'import {beginInteractionRoute,+ getActiveInteractionRoute,requestHostInteraction,installDesktopInteractionHandler,installInteractionLifecycleObserver,@@ -60,6 +61,53 @@ describe('session interaction router', () => {} finally { lease.release(); }});+ it('exposes the live route and its owner evidence for owner-only Host actions', async () => {+ const host = makeSession();+ installDesktopInteractionHandler(host.session, vi.fn<InteractionHandler>((_request, shared) => shared!.result));+ expect(getActiveInteractionRoute(host.session)).toBeNull();+ const lease = beginInteractionRoute(host.session, {+ route: {+ sessionId: host.session.id, turnId: 'turn-owner', origin: { kind: 'im', channel: 'telegram' },+ interactionSurface: 'channel-card', requesterAuthority: 'owner',+ },+ handle: vi.fn(async (): Promise<InteractionDecision> => ({ kind: 'permission', behavior: 'deny' })),+ });+ expect(getActiveInteractionRoute(host.session)).toMatchObject({+ origin: { kind: 'im', channel: 'telegram' }, requesterAuthority: 'owner',+ });+ lease.release();+ expect(getActiveInteractionRoute(host.session)).toBeNull();+ });++ it('lets the phone/Desktop or the IM card answer an app update card; the first answer wins', async () => {+ const host = makeSession();+ let desktopShared: Parameters<InteractionHandler>[1];+ const desktop = vi.fn<InteractionHandler>((_request, shared) => {+ desktopShared = shared;+ return shared!.result;+ });+ const channel = vi.fn<InteractionHandler>((_request, shared) => shared!.result);+ installDesktopInteractionHandler(host.session, desktop);+ const lease = beginInteractionRoute(host.session, {+ route: {+ sessionId: host.session.id, turnId: 'turn-update', origin: { kind: 'im', channel: 'telegram' },+ interactionSurface: 'channel-card', requesterAuthority: 'owner',+ },+ handle: channel,+ });+ try {+ const request = { ...permission('app-update-1'), toolName: 'cindy.app.update', input: { from: '1', to: '2' } } as InteractionRequest;+ const pending = requestHostInteraction(host.session, request, new AbortController().signal);+ await vi.waitFor(() => { expect(channel).toHaveBeenCalledOnce(); });+ // Same-account phone answers through the Desktop pending entry; a late IM click cannot override it.+ desktopShared!.decide({ kind: 'permission', behavior: 'allow' });+ const [, channelShared] = channel.mock.calls[0]!;+ expect(channelShared!.decide({ kind: 'permission', behavior: 'deny' })).toBe(false);+ await expect(pending).resolves.toMatchObject({ behavior: 'allow' });+ expect(desktop).toHaveBeenCalledOnce();+ } finally { lease.release(); }+ });+it('cancels the ordinary pending card when a Host permission is aborted', async () => {const host = makeSession();const controller = new AbortController();diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.tsindex 537dc668fd..9cb55c22fc 100644--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts@@ -1296,6 +1296,23 @@ export class AgentInputCoordinator {retrySourceClientId: item.retrySourceClientId ?? item.supersedesUserClientId };}+ /**+ * Owner-only Host actions (app update) require the active input itself to be text+ * this account's user typed on Desktop or a same-account remote device. Automation,+ * other tasks, Orca, plugins, shared-task guests and automatic resumes never qualify.+ */+ isActiveInputOwnerAuthored(sessionId: string): boolean {+ const item = this.states.get(sessionId)?.activeTurn?.item;+ // A trusted Desktop receipt (`origin.kind === 'desktop'`) is still owner input.+ const originKind = (item?.origin as { kind?: unknown } | undefined)?.kind;+ if (!item || (originKind !== undefined && originKind !== 'desktop')) return false;+ if (item.sourcePlugin || item.sharedTaskAuthor || item.botTaskCoordination) return false;+ if (item.clientId.startsWith('plugin-task:') || item.originalSyntheticTrigger) return false;+ if (item.autoResume && !item.retrySourceClientId) return false;+ const text = item.autoReviewUserText;+ return typeof text === 'string' && !!text.trim() && !text.startsWith('[UI_ACTION_TRIGGER]');+ }+/** Inputs consumed by this native turn, excluding queued work and stale generations. */getActiveInputClientIds(sessionId: string, vendorGeneration?: number): string[] {const active = this.states.get(sessionId)?.activeTurn;diff --git a/apps/desktop/src/main/maker-ipc/interactionRouter.ts b/apps/desktop/src/main/maker-ipc/interactionRouter.tsindex 286067bcb8..f994166a8f 100644--- a/apps/desktop/src/main/maker-ipc/interactionRouter.ts+++ b/apps/desktop/src/main/maker-ipc/interactionRouter.ts@@ -27,6 +27,11 @@ export interface InteractionRoute {timeoutMs?: number;/** Main-owned source text, shared by Desktop and channel presentations. */sourceDescription?: string;+ /**+ * Main-verified sender of the turn's triggering message. Only 'owner' unlocks+ * owner-only Host actions; channels that cannot prove it leave it unset.+ */+ requesterAuthority?: 'owner' | 'guest' | 'unknown';onStateChange?(state: InteractionRouteState): void;}@@ -123,6 +128,10 @@ class SessionInteractionRouter {this.lifecycleObserver = observer;}+ getActiveRoute(): InteractionRoute | null {+ return this.activeRoute?.route ?? null;+ }+private notifyState(route: InteractionRoute | undefined, state: InteractionRouteState): void {callSafely(() => route?.onStateChange?.(state));}@@ -315,6 +324,11 @@ export function requestHostInteraction(return routerFor(session).dispatch(request, signal);}+/** Read-only view of the live non-Desktop route; null for ordinary Desktop turns. */+export function getActiveInteractionRoute(session: InteractionSession): InteractionRoute | null {+ return routers.get(session as object)?.getActiveRoute() ?? null;+}+export function installInteractionLifecycleObserver(session: InteractionSession,observer: InteractionLifecycleObserver | null,diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 4672e4de8f..01ec001cb2 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -4027,6 +4027,11 @@ export function getSessionInputProvenance(sessionId: string) {return { input, executing: !!input || !!getMakerIfReady()?.getSession(sessionId)?.isTurnRunning() };}+/** Owner-authored active input (see AgentInputCoordinator.isActiveInputOwnerAuthored). */+export function isActiveInputOwnerAuthored(sessionId: string): boolean {+ return agentInputCoordinatorHolder?.isActiveInputOwnerAuthored(sessionId) ?? false;+}+/*** 标题素材读取需要覆盖 `status:isRunning=false` 到 terminal event 的短窗口:* 逻辑 running 已结束,但最后一条 Assistant 还没有拿到 durable turn seal。diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.tsindex 776c9d90e9..aa1eaf5703 100644--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts@@ -44,7 +44,7 @@ import { feishuIm, wechatIm } from '../im';import { sendFeishuSessionNotification } from '../im/feishu/notificationOrigin';import { getSlackToolBridge } from '../hook-control/slackToolBridge.js';import { createLogger } from '../logger.js';-import { checkAppUpdateForAgent } from '../updateService.js';+import { createAgentAppUpdateCallbacks } from '../agent-app-update/index.js';import { getScheduler } from '../scheduler-host/index.js';import { stabilizeHookCommand } from '../scheduler-host/hook-script-generator.js';import { assertPreRunHookCommandSyntax } from '../scheduler-host/pre-run-hook.js';@@ -473,11 +473,9 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc// (LLM 调工具时) registerMakerIpc 早已执行完毕, holder 已 ready。xdtHelper: {runtimeCapabilities: deps.runtimeCapabilities,- appUpdate: {- isCurrentSession: (sessionId, sessionInstanceId) =>- deps.isCurrentLocalSessionInstance?.(sessionId, sessionInstanceId) === true,- check: checkAppUpdateForAgent,- },+ // Install / auto-update requests become owner-only Host cards (see agent-app-update/).+ appUpdate: createAgentAppUpdateCallbacks((sessionId, sessionInstanceId) =>+ deps.isCurrentLocalSessionInstance?.(sessionId, sessionInstanceId) === true),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 b3ad52e82a..09a168c7f1 100644--- a/apps/desktop/src/main/updateService.ts+++ b/apps/desktop/src/main/updateService.ts@@ -2095,6 +2095,14 @@ function agentUpdateApplyBlockReason(): string | null {return null;}+/** Build and installation blockers shared by every Agent-facing update entry. */+function agentUpdateUnsupportedReason(): string | null {+ if (!app.isPackaged || isDev() || isCindyPersonalRuntime() || isVersionlessAppVersion(app.getVersion())) {+ return '此构建不支持应用内更新。';+ }+ return agentUpdateApplyBlockReason();+}+export async function checkAppUpdateForAgent(): Promise<{status: string;currentVersion: string;@@ -2102,11 +2110,8 @@ export async function checkAppUpdateForAgent(): Promise<{reason?: string;}> {const currentVersion = app.getVersion();- if (!app.isPackaged || isDev() || isCindyPersonalRuntime() || isVersionlessAppVersion(currentVersion)) {- return { status: 'unsupported', currentVersion, reason: '此构建不支持应用内更新。' };- }- const platformBlock = agentUpdateApplyBlockReason();- if (platformBlock) return { status: 'unsupported', currentVersion, reason: platformBlock };+ const unsupported = agentUpdateUnsupportedReason();+ if (unsupported) return { status: 'unsupported', currentVersion, reason: unsupported };if (currentStatus === 'downloading' || currentStatus === 'superseding') {return { status: 'downloading', currentVersion, targetVersion: readyVersion };}@@ -2131,6 +2136,70 @@ export async function checkAppUpdateForAgent(): Promise<{};}+const AGENT_UPDATE_FAILURE_REASONS: Record<Exclude<CheckForUpdateResult, 'ready'>, string> = {+ manifest_failed: '无法读取当前渠道的更新信息。',+ download_failed: '下载更新失败,请稍后重试。',+ manual_download: '当前安装需要手动下载新版本。',+ idle: '当前渠道没有适用于这台设备的可安装更新。',+};++export type AgentConfirmedAppUpdateResult =+ | { status: 'relaunching'; targetVersion?: string }+ | { status: 'failed'; reason: string; errorCode?: string };++/**+ * Apply an update the user approved on the Host confirmation card. This is the+ * built-in Check for Updates → Restart path, not a parallel one:+ * `checkForUpdate()` stages the patch (its in-flight guard keeps a repeated or+ * concurrent request on the same download) and `executeRelaunch()` applies it+ * with every existing platform, Subagent and channel guard.+ *+ * `beforeRelaunch` runs after the patch is staged; returning false keeps the+ * patch staged and skips the restart.+ */+export async function applyConfirmedAppUpdateForAgent(options: {+ beforeRelaunch: () => Promise<boolean>;+}): Promise<AgentConfirmedAppUpdateResult> {+ const unsupported = agentUpdateUnsupportedReason();+ if (unsupported) return { status: 'failed', reason: unsupported, errorCode: 'unsupported' };+ if (isRelaunching || autoRelaunchInProgress) return { status: 'relaunching', targetVersion: readyVersion };+ if (currentStatus !== 'ready') {+ const result = await checkForUpdate();+ if (result !== 'ready') {+ return { status: 'failed', reason: AGENT_UPDATE_FAILURE_REASONS[result], errorCode: result };+ }+ }+ if (!await options.beforeRelaunch()) {+ return { status: 'failed', reason: '更新已下载,但本次没有重启。', errorCode: 'relaunch_cancelled' };+ }+ if (isRelaunching || autoRelaunchInProgress) return { status: 'relaunching', targetVersion: readyVersion };+ if (currentStatus !== 'ready' || !readyVersion) {+ return { status: 'failed', reason: '已下载的更新不再可用,请重新检查更新。', errorCode: 'not_ready' };+ }+ const targetVersion = readyVersion;+ // macOS / Linux exit inside this call once the updater is spawned; Windows+ // returns with `isRelaunching` still set and exits from its own callbacks.+ await executeRelaunch(resolvedRelaunchTheme);+ if (isRelaunching) return { status: 'relaunching', targetVersion };+ return {+ status: 'failed',+ reason: '更新器没有启动,Cindy 未重启。',+ errorCode: lastErrorCode ?? 'relaunch_not_started',+ };+}++/** Effective idle auto-install switch (Settings → About), shared with the Agent tools. */+export function readAutoRelaunchOnIdleForAgent(): boolean {+ return readAutoUpdateSettings().autoRelaunchOnIdle;+}++/** Same write as the Settings toggle IPC; only called after the user confirmed the Host card. */+export function setAutoRelaunchOnIdleForAgent(enabled: boolean): boolean {+ writeAutoRelaunchOnIdle(enabled);+ void evaluateAutoRelaunch('agent-settings-set');+ return readAutoUpdateSettings().autoRelaunchOnIdle;+}+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.diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 9fe3c8fb49..80f1f06688 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -8044,6 +8044,26 @@"message": "Moving {{appName}} to the Applications folder gives you a better experience, including automatic updates.","move": "Move (Recommended)","later": "Not Now"+ },+ "agentInstall": {+ "title": "Update {{appName}} to {{version}}?",+ "versions": "Update from {{from}} to {{to}}. After you confirm, {{appName}} downloads and installs it with the built-in updater, then restarts.",+ "otherTasks": "{{count}} other task(s) are running and will be interrupted by the restart. Afterwards, click Continue in each task to resume.",+ "noOtherTasks": "No other tasks are running.",+ "thisTask": "This task restarts with {{appName}} after the current reply finishes.",+ "remote": "Phones and other remote connections disconnect briefly during the restart. Reconnect to see the result in this task.",+ "linuxAuth": "Installing requires your system password on this computer.",+ "latestVersion": "the new version",+ "succeeded": "{{appName}} is updated to {{version}} (was {{from}}).",+ "failed": "The {{appName}} update did not finish. This computer is still on {{version}}.",+ "retryHint": "Ask me to try again later, or check for updates in Settings → About."+ },+ "agentAutoUpdate": {+ "enableTitle": "Install updates while idle?",+ "disableTitle": "Stop installing updates while idle?",+ "enableDescription": "When an update finishes downloading, {{appName}} restarts to install it once this computer has been idle for 10 minutes and no tasks are running.",+ "disableDescription": "Downloaded updates will wait until you restart manually.",+ "settingsHint": "You can change this anytime in Settings → About."}},"sidebar": {diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex f390d09b2a..b60024688f 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -8036,6 +8036,26 @@"message": "{{appName}} を「アプリケーション」フォルダに移動すると、自動更新を含むより良い体験が得られます。","move": "移動(推奨)","later": "あとで"+ },+ "agentInstall": {+ "title": "{{appName}} を {{version}} に更新しますか?",+ "versions": "{{from}} から {{to}} に更新します。確認後、{{appName}} は内蔵アップデーターでダウンロードとインストールを行い、自動的に再起動します。",+ "otherTasks": "ほかに {{count}} 件のタスクが実行中で、再起動により中断されます。再起動後、各タスクで「続行」を押すと再開できます。",+ "noOtherTasks": "ほかに実行中のタスクはありません。",+ "thisTask": "このタスクは現在の返信が終わった後、{{appName}} とともに再起動します。",+ "remote": "再起動中はスマートフォンなどのリモート接続が一時的に切断されます。再接続後、このタスクで結果を確認できます。",+ "linuxAuth": "インストールにはこのコンピューターでのシステムパスワード入力が必要です。",+ "latestVersion": "新しいバージョン",+ "succeeded": "{{appName}} を {{version}} に更新しました(以前は {{from}})。",+ "failed": "{{appName}} の更新は完了しませんでした。現在も {{version}} です。",+ "retryHint": "後でもう一度依頼するか、「設定 → 情報」で更新を確認してください。"+ },+ "agentAutoUpdate": {+ "enableTitle": "アイドル時に更新をインストールしますか?",+ "disableTitle": "アイドル時の更新インストールをオフにしますか?",+ "enableDescription": "更新のダウンロード完了後、このコンピューターが 10 分間操作されず実行中のタスクがない場合、{{appName}} は自動的に再起動してインストールします。",+ "disableDescription": "ダウンロード済みの更新は、手動で再起動するまでインストールされません。",+ "settingsHint": "「設定 → 情報」でいつでも変更できます。"}},"sidebar": {diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 251cc446e0..2131c93050 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -8036,6 +8036,26 @@"message": "{{appName}}를 응용 프로그램 폴더로 이동하면 자동 업데이트를 포함한 더 나은 경험을 사용할 수 있습니다.","move": "이동 (권장)","later": "나중에"+ },+ "agentInstall": {+ "title": "{{appName}}을(를) {{version}}(으)로 업데이트할까요?",+ "versions": "{{from}}에서 {{to}}(으)로 업데이트합니다. 확인하면 {{appName}}이(가) 내장 업데이터로 다운로드·설치한 뒤 자동으로 다시 시작합니다.",+ "otherTasks": "다른 작업 {{count}}개가 실행 중이며 다시 시작하면 중단됩니다. 다시 시작한 뒤 각 작업에서 \"계속\"을 눌러 재개할 수 있습니다.",+ "noOtherTasks": "실행 중인 다른 작업이 없습니다.",+ "thisTask": "이 작업은 현재 답변이 끝난 뒤 {{appName}}과(와) 함께 다시 시작됩니다.",+ "remote": "다시 시작하는 동안 휴대폰 등 원격 연결이 잠시 끊깁니다. 다시 연결되면 이 작업에서 결과를 확인할 수 있습니다.",+ "linuxAuth": "설치하려면 이 컴퓨터에서 시스템 비밀번호를 입력해야 합니다.",+ "latestVersion": "새 버전",+ "succeeded": "{{appName}}이(가) {{version}}(으)로 업데이트되었습니다(이전 버전 {{from}}).",+ "failed": "{{appName}} 업데이트가 완료되지 않았습니다. 현재 버전은 여전히 {{version}}입니다.",+ "retryHint": "나중에 다시 요청하거나 \"설정 → 정보\"에서 업데이트를 확인하세요."+ },+ "agentAutoUpdate": {+ "enableTitle": "유휴 상태일 때 업데이트를 설치할까요?",+ "disableTitle": "유휴 상태일 때 업데이트 설치를 끌까요?",+ "enableDescription": "업데이트 다운로드가 끝난 뒤 이 컴퓨터가 10분 동안 유휴 상태이고 실행 중인 작업이 없으면 {{appName}}이(가) 자동으로 다시 시작해 설치합니다.",+ "disableDescription": "다운로드된 업데이트는 직접 다시 시작할 때까지 설치되지 않습니다.",+ "settingsHint": "\"설정 → 정보\"에서 언제든지 변경할 수 있습니다."}},"sidebar": {diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 39f7dfed27..1fb473445c 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -8036,6 +8036,26 @@"message": "将 {{appName}} 移动到「应用程序」文件夹可获得更好的体验,包括自动更新。","move": "移动(推荐)","later": "暂不"+ },+ "agentInstall": {+ "title": "更新 {{appName}} 到 {{version}}?",+ "versions": "从 {{from}} 更新到 {{to}}。确认后 {{appName}} 会用内置更新器下载并安装,然后自动重启。",+ "otherTasks": "另有 {{count}} 个任务正在运行,重启会中断它们;重启后可在对应任务中点「继续」恢复。",+ "noOtherTasks": "目前没有其他正在运行的任务。",+ "thisTask": "本任务会在这轮回复结束后随 {{appName}} 重启。",+ "remote": "重启期间手机等远程连接会暂时断开,重连后可在本任务中查看更新结果。",+ "linuxAuth": "安装时需要在这台电脑上输入系统密码。",+ "latestVersion": "新版本",+ "succeeded": "{{appName}} 已更新到 {{version}}(原版本 {{from}})。",+ "failed": "{{appName}} 更新没有完成,当前仍是 {{version}}。",+ "retryHint": "可以稍后再让我更新,或在「设置 → 关于」中检查更新。"+ },+ "agentAutoUpdate": {+ "enableTitle": "开启空闲时自动安装更新?",+ "disableTitle": "关闭空闲时自动安装更新?",+ "enableDescription": "开启后,更新下载完成时,如果这台电脑已空闲 10 分钟且没有正在运行的任务,{{appName}} 会自动重启完成安装。",+ "disableDescription": "关闭后,更新下载完成时需要你手动重启才会安装。",+ "settingsHint": "也可以随时在「设置 → 关于」中修改。"}},"sidebar": {diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 757ca87030..03fedc65e1 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -8036,6 +8036,26 @@"message": "將 {{appName}} 移動到「應用程式」資料夾可獲得更好的體驗,包括自動更新。","move": "移動(推薦)","later": "暫不"+ },+ "agentInstall": {+ "title": "將 {{appName}} 更新到 {{version}}?",+ "versions": "從 {{from}} 更新到 {{to}}。確認後 {{appName}} 會用內建更新器下載並安裝,然後自動重新啟動。",+ "otherTasks": "另有 {{count}} 個任務正在執行,重新啟動會中斷它們;重新啟動後可在對應任務中點「繼續」恢復。",+ "noOtherTasks": "目前沒有其他正在執行的任務。",+ "thisTask": "本任務會在這輪回覆結束後隨 {{appName}} 重新啟動。",+ "remote": "重新啟動期間手機等遠端連線會暫時中斷,重新連線後可在本任務中查看更新結果。",+ "linuxAuth": "安裝時需要在這台電腦上輸入系統密碼。",+ "latestVersion": "新版本",+ "succeeded": "{{appName}} 已更新到 {{version}}(原版本 {{from}})。",+ "failed": "{{appName}} 更新沒有完成,目前仍是 {{version}}。",+ "retryHint": "可以稍後再讓我更新,或在「設定 → 關於」中檢查更新。"+ },+ "agentAutoUpdate": {+ "enableTitle": "開啟閒置時自動安裝更新?",+ "disableTitle": "關閉閒置時自動安裝更新?",+ "enableDescription": "開啟後,更新下載完成時,如果這台電腦已閒置 10 分鐘且沒有正在執行的任務,{{appName}} 會自動重新啟動完成安裝。",+ "disableDescription": "關閉後,更新下載完成時需要你手動重新啟動才會安裝。",+ "settingsHint": "也可以隨時在「設定 → 關於」中修改。"}},"sidebar": {diff --git a/docs/dev-rules/agent-capabilities.md b/docs/dev-rules/agent-capabilities.mdindex e37fbf5f1d..018644c494 100644--- a/docs/dev-rules/agent-capabilities.md+++ b/docs/dev-rules/agent-capabilities.md@@ -26,7 +26,7 @@读取内置 server 的真实 schema 与渐进目录。没有 `scope` 时保留原产品说明查询行为。-指定由引擎自己连接的 server(自定义 MCP 等)时,宿主经发起查询的 Session 读取引擎在本任务中的状态:Codex 用带本任务 `threadId` 的 `mcpServerStatus/list`(不拿共享 app-server 的进程级清单代替),Claude Code 用 `mcpServerStatus()`。有工具时返回服务端原始工具名与截短说明;否则返回 `ok: false` 和明确的 `engineState`——`not-mounted`(本任务引擎未挂载,常见于任务开始后才增改)、`no-tools`(已配置但未报告工具,Codex 无法区分启动失败与本无工具)、`failed`、`needs-auth`、`pending`、`disabled`;引擎没有该入口(Pi、SSH 远端 Claude、远程 Agent)报 `HARNESS_DISCOVERY_UNAVAILABLE`,读取失败或超时报 `HARNESS_DISCOVERY_FAILED`。不转发引擎的失败原文,避免带出连接地址。实现见 `apps/desktop/src/main/maker-host/agentCapabilityCatalog.ts` 与 `packages/maker-core/src/agents/{codex,claude-code}/mcp-server-tools.ts`。宿主交互能力不等于 Agent 已有可调用接口;例如应用安装更新、重启没有正式 Agent 接口,`check_app_update` 只查询当前更新渠道。+指定由引擎自己连接的 server(自定义 MCP 等)时,宿主经发起查询的 Session 读取引擎在本任务中的状态:Codex 用带本任务 `threadId` 的 `mcpServerStatus/list`(不拿共享 app-server 的进程级清单代替),Claude Code 用 `mcpServerStatus()`。有工具时返回服务端原始工具名与截短说明;否则返回 `ok: false` 和明确的 `engineState`——`not-mounted`(本任务引擎未挂载,常见于任务开始后才增改)、`no-tools`(已配置但未报告工具,Codex 无法区分启动失败与本无工具)、`failed`、`needs-auth`、`pending`、`disabled`;引擎没有该入口(Pi、SSH 远端 Claude、远程 Agent)报 `HARNESS_DISCOVERY_UNAVAILABLE`,读取失败或超时报 `HARNESS_DISCOVERY_FAILED`。不转发引擎的失败原文,避免带出连接地址。实现见 `apps/desktop/src/main/maker-host/agentCapabilityCatalog.ts` 与 `packages/maker-core/src/agents/{codex,claude-code}/mcp-server-tools.ts`。宿主交互能力不等于 Agent 已有可调用接口。应用更新例外地提供 `cindy_helper` 的 `install_app_update` / `set_app_auto_update`:每次都由宿主向主人弹确认卡,确认后才经内置更新器执行(见 [`../product-rules/agent-app-update.md`](../product-rules/agent-app-update.md));`check_app_update` 只查询当前更新渠道。## 伙伴默认配置diff --git a/docs/dev-rules/cindy-updater.md b/docs/dev-rules/cindy-updater.mdindex 77c077a92b..8176e2b3f6 100644--- a/docs/dev-rules/cindy-updater.md+++ b/docs/dev-rules/cindy-updater.md@@ -40,6 +40,12 @@ Tauri 实现)与 Electron 侧的更新服务(`apps/desktop/src/main/updateSe先读实际代码再决定实现;不要只凭文档或记忆猜测更新流程。+## Agent 入口++Agent 只能通过 `updateService.ts` 的 `applyConfirmedAppUpdateForAgent` 走同一条+check → download → relaunch 状态机,且必须先经宿主确认卡;不得给 Agent 新开下载、替换或重启+路径。产品规则见 [`../product-rules/agent-app-update.md`](../product-rules/agent-app-update.md)。+## Review 要点1. 改动是否触及更新器或更新服务?触及就必须先有 owner 确认,PR 说明写明。diff --git a/docs/product-rules/agent-app-update.md b/docs/product-rules/agent-app-update.mdnew file mode 100644index 0000000000..41043d4083--- /dev/null+++ b/docs/product-rules/agent-app-update.md@@ -0,0 +1,57 @@+# Agent 更新 Cindy++2026-10-10 Dash 裁决:用户说「更新 Cindy」时,Agent 可以在用户确认后通过内置更新器完成更新,+也可以帮用户开启/关闭空闲时自动安装更新。背景是 #5128 只留下了只读的 `check_app_update`,+Agent 只能反复引导用户去点「检查更新」;那次收紧的起因是 Agent 自己下载安装包替换应用并用+`launchctl submit` 注册重启脚本,导致 macOS 循环重启。++## 行为++- `cindy_helper` 的 `app_update` 类目:`check_app_update`(只读)、`install_app_update`、+ `set_app_auto_update`。后两者每次执行前都由宿主在调用任务上弹确认卡,**不看权限档**,+ 完全访问也跳不过:卡片由 Main 通过 `requestHostPermission` 发起,不经 Agent 自己的审批回调。+- 确认卡复用通用 `permission` 交互(`cindy.app.update` / `cindy.app.auto_update`),桌面、+ 同账号手机远控与 IM 渠道卡共用 interaction router 的同一决定,旧版手机无需升级。+ 安装卡写明从哪个版本到哪个版本、Cindy 会重启、另有几个任务正在运行会被中断(重启后在任务里点+ 「继续」恢复)、本任务在这轮回复后重启、远程连接会短暂断开;Linux 另提示需要输入系统密码。+- 确认后走「设置 → 关于」同一条更新状态机:`checkForUpdate()` 下载(单飞,重复调用不重复下载),+ 等调用任务这轮回复结束(最多 2 分钟)后 `executeRelaunch()` 重启。拒绝、超时或卡片未送达都不下载、+ 不重启。同一时刻只有一个安装请求;确认卡等待中或已开始安装时再次调用直接返回当前状态。+- 重启前在账号私有目录写一份标记;新版本启动、该账号数据库就绪后,把结果(新版本号或「仍是旧版本」)+ 作为一条普通助手消息写回发起任务,桌面和手机重连后都能看到。未重启就失败(下载失败、更新器没启动)+ 时立即写回失败原因。+- 自动更新开关写入既有 `auto-update-settings-store`(用户显式 override),与设置页同一开关。+ `check_app_update` 在有可安装更新且开关未开时返回一次 `autoUpdateHint`,同一任务内只提示一次。+- 不支持的构建与安装环境(开发版、个人版、版本无关包、未移入「应用程序」、Linux 非受管安装、+ Windows 缺运行库等)沿用 `agentUpdateApplyBlockReason`,明确返回原因。++## 谁能触发++只有主人本人发起的轮次能触发,没有正面证据一律拒绝(`OWNER_TURN_REQUIRED`):++- 桌面与同账号手机:输入协调器里当前轮次的输入必须是主人亲手输入的文字;自动化、其他任务+ (`send_to_session`)、Orca、插件、共享任务访客、自动续跑、合成指令都不算。+- 个人 IM:沿用控制命令的主人判据(私聊已过渠道 owner 门;群里看发言人 `isOwner`)。+- 官方 Hook:仅 Telegram 私聊(服务端按账号绑定路由);群与其他渠道不算。+- scheduler / goal 轮次一律拒绝。++共享任务访客即使看到卡片也不能回答:device-link 共享任务门禁按工具名拒绝这两类确认。+远程任务(SSH、远程 Agent)不暴露 `app_update` 类目,按既有边界只能更新任务所在的那台 Cindy。++## 手机++手机没有远程修改被控端设置的入口(updater 类 channel 属 device-link allowlist「永不放行」),+本功能不新增 channel,也不改手机端代码:手机上通过 Agent + 确认卡完成更新或切换自动更新。++## 提示词++host system prompt 只保留模型自己推不出、代码又拦不住的部分:++- 用户要更新时调用 `install_app_update`,由宿主向用户确认(工具藏在 `cindy_helper` 二级目录,不提示找不到)。+- 工具报无可装更新或不支持时转述原因、不旁装 Release;工具不可用(如远程任务)时引导用户到 Cindy 所在电脑的设置里检查更新。+ 不支持的安装环境里内置「检查更新」同样装不了,不能一律引导去点它。+- 除非用户明确指定这种方式,不用 shell 下载、替换、结束或重启 Cindy:完全访问下代码拦不住 shell,+ 而工具报不支持时模型仍可能退回自行安装;用户明确要求的源码构建、个人版替换、包管理器升级不在禁止之列。+- 任何情况下都不注册持久重启任务(如 `launchctl submit`):这是循环重启的直接原因,重启由内置更新器负责。++静态文本,前缀缓存只在升级时失效一次。diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex 48e38339cf..59e1174232 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -621,8 +621,8 @@ Todo 是伙伴维护的事务清单:既包含用户交办,也允许从已授- 群专线与主任务都能使用相同的通用工具;伙伴专属“修改自己的资料”、工作台、群历史等工具仍需要对应的业务对象和本机数据。后台任务的跟踪、回传、停止仍使用现有 Session 任务契约。- 不隐瞒能力缺口:未安装、未连接、全局停用或当前引擎/远端不支持时明确返回状态。目录读取失败- 必须报告,不能用空列表启动并宣称已全配。Cindy 安装更新与重启目前没有 Agent 可直接调用的正式接口,- `check_app_update` 只检查更新,安装仍由用户在内置更新界面操作。+ 必须报告,不能用空列表启动并宣称已全配。Cindy 安装更新只能经 `install_app_update`+ 由宿主向主人弹确认卡后执行(见 [`agent-app-update.md`](agent-app-update.md)),`check_app_update` 只检查更新。- 本改动不引入跨设备控制协议、新的 `control_session` 大工具或新的幂等数据库表。通用工具保留原名和发现路径。伙伴的身份、个人记忆和 Skill 学习与工具权限分开维护。diff --git a/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts b/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.tsindex 3dc1b312a9..c25baca418 100644--- a/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts+++ b/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts@@ -75,6 +75,49 @@ describe("cindy_helper MCP server", () => {await server.close();}});+ it('routes install and auto-update requests to the Host with the bound caller', async () => {+ let current = true;+ const caller = { sessionId: 'local-task', sessionInstanceId: 'instance-1' };+ const check = vi.fn(async () => ({ status: 'available', currentVersion: '0.1.86', targetVersion: '0.1.90' }));+ const install = vi.fn(async () => ({ status: 'started', targetVersion: '0.1.90' }));+ const setAutoUpdate = vi.fn(async (_caller: unknown, enabled: boolean) => enabled+ ? { status: 'updated', autoUpdateEnabled: true }+ : { ok: false, errorCode: 'OWNER_TURN_REQUIRED', message: 'owner only' });+ const server = createXdtHelperMcpServer({+ resolveSurface: async () => 'default',+ appUpdate: { isCurrentSession: () => current, check, install, setAutoUpdate },+ }, {+ agentKind: 'claude-code', workingDir: '/repo', sessionId: 'local-task',+ getSessionContext: () => ({ agentKind: 'claude-code', workingDir: '/repo', ...caller }),+ });+ const [ct, st] = InMemoryTransport.createLinkedPair();+ const client = new Client({ name: 'app-install-test', version: '0.0.0' });+ await Promise.all([server.connect(st), client.connect(ct)]);+ const call = async (name: string, args: Record<string, unknown> = {}) => 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', 'set_app_auto_update',+ ]);+ expect(await call('check_app_update')).toMatchObject({ ok: true, status: 'available' });+ expect(check).toHaveBeenCalledWith(caller);+ expect(await call('install_app_update')).toMatchObject({ ok: true, status: 'started', targetVersion: '0.1.90' });+ expect(install).toHaveBeenCalledWith(caller);+ expect(await call('set_app_auto_update', { enabled: true })).toMatchObject({ ok: true, autoUpdateEnabled: true });+ expect(await call('set_app_auto_update', { enabled: false })).toMatchObject({+ ok: false, errorCode: 'OWNER_TURN_REQUIRED', data: { hint: 'owner only' },+ });+ expect(setAutoUpdate).toHaveBeenNthCalledWith(1, caller, true);+ current = false;+ expect(await call('install_app_update')).toMatchObject({ ok: false, errorCode: 'STALE_SESSION' });+ expect(install).toHaveBeenCalledOnce();+ } finally {+ await client.close();+ await server.close();+ }+ });it('hides app updates from a remote Pi task while retaining its other helper categories', async () => {let remoteHostId: string | undefined;const check = vi.fn(async () => ({ status: 'ready', currentVersion: '0.1.86', targetVersion: '0.1.90' }));diff --git a/packages/lizi-mcps/src/xdt-helper/app_update.ts b/packages/lizi-mcps/src/xdt-helper/app_update.tsindex 0b350d60ae..f83599be37 100644--- a/packages/lizi-mcps/src/xdt-helper/app_update.ts+++ b/packages/lizi-mcps/src/xdt-helper/app_update.ts@@ -1,10 +1,30 @@+import { z } from 'zod';import { BRAND_NAME } from '@cindy/maker-shared/branding';import type { XdtHelperToolRegistry } from '../lizi_xdtHelperToolRegistry.js';import { errorPayload, okPayload } from './_payload.js';+/** The bound task instance that issued the call; Host checks it, never the model. */+export interface AppUpdateCaller {+ sessionId: string;+ sessionInstanceId: string;+}++type HostResult = Record<string, unknown>;+export interface AppUpdateCallbacks {isCurrentSession(sessionId: string, sessionInstanceId: string): boolean;- check(): Promise<{ status: string; currentVersion: string; targetVersion?: string; reason?: string }>;+ check(caller: AppUpdateCaller): Promise<{ status: string; currentVersion: string; targetVersion?: string; reason?: string }>;+ /** Host shows the owner a confirmation card, then runs the built-in updater. */+ install?(caller: AppUpdateCaller): Promise<HostResult>;+ /** Host confirmation card, then the Settings → About idle auto-install switch. */+ setAutoUpdate?(caller: AppUpdateCaller, enabled: boolean): Promise<HostResult>;+}++function hostPayload(result: HostResult) {+ if (result.ok === false && typeof result.errorCode === 'string') {+ return errorPayload(result.errorCode, typeof result.message === 'string' ? result.message : result.errorCode);+ }+ return okPayload(result);}export function registerAppUpdateTools(@@ -14,29 +34,69 @@ export function registerAppUpdateTools(callbacks: AppUpdateCallbacks;},): void {- const callerError = () => {+ const resolveCaller = (): { error: ReturnType<typeof errorPayload> } | { caller: AppUpdateCaller } => {const context = deps.getSessionContext();- if (!context.sessionId) return errorPayload('NO_SESSION_CONTEXT', '当前调用没有绑定 Cindy 任务。');- if (context.remoteHostId) return errorPayload('REMOTE_SESSION', '远程任务不能更新本机 Cindy;请在本机任务中操作。');+ if (!context.sessionId) return { error: errorPayload('NO_SESSION_CONTEXT', '当前调用没有绑定 Cindy 任务。') };+ if (context.remoteHostId) return { error: errorPayload('REMOTE_SESSION', '远程任务不能更新本机 Cindy;请在本机任务中操作。') };if (!context.sessionInstanceId || !deps.callbacks.isCurrentSession(context.sessionId, context.sessionInstanceId)) {- return errorPayload('STALE_SESSION', '当前任务实例已结束或不再有效,不能更新 Cindy。');+ return { error: errorPayload('STALE_SESSION', '当前任务实例已结束或不再有效,不能更新 Cindy。') };}- return null;+ return { caller: { sessionId: context.sessionId, sessionInstanceId: context.sessionInstanceId } };};registry.register({name: 'check_app_update',category: 'app_update',- description: `仅读取当前渠道更新版本信息,检查当前运行的 ${BRAND_NAME} 是否有可通过应用内更新器安装的新版本。本工具不会下载、安装或重启应用;如需安装,请用户使用内置「检查更新」界面。不要用 GitHub Release 文件替换正在运行的应用。`,+ description: `仅读取当前渠道更新版本信息,检查当前运行的 ${BRAND_NAME} 是否有可通过应用内更新器安装的新版本,不会下载、安装或重启应用。用户要更新时调用 install_app_update。结果含 autoUpdateHint=true 时,可顺带提醒一句可以开启空闲时自动安装更新(set_app_auto_update)。不要用 GitHub Release 文件替换正在运行的应用。`,inputShape: {},handler: async () => {- const error = callerError();- if (error) return error;+ const resolved = resolveCaller();+ if ('error' in resolved) return resolved.error;try {- return okPayload(await deps.callbacks.check());+ return okPayload(await deps.callbacks.check(resolved.caller));} catch (cause) {return errorPayload('UPDATE_CHECK_FAILED', String(cause));}},});++ const install = deps.callbacks.install;+ if (install) {+ registry.register({+ name: 'install_app_update',+ category: 'app_update',+ description: `用户要求更新 ${BRAND_NAME} 时调用。宿主会向用户弹出确认卡(目标版本、会重启、会中断哪些任务),用户确认后才由内置更新器下载、安装并重启;拒绝或超时则不做任何更改。确认由宿主完成,不要先用文字向用户确认。不要用 shell 下载、替换应用或创建重启任务。`,+ inputShape: {},+ handler: async () => {+ const resolved = resolveCaller();+ if ('error' in resolved) return resolved.error;+ try {+ return hostPayload(await install(resolved.caller));+ } catch (cause) {+ return errorPayload('UPDATE_INSTALL_FAILED', String(cause));+ }+ },+ });+ }++ const setAutoUpdate = deps.callbacks.setAutoUpdate;+ if (setAutoUpdate) {+ registry.register({+ name: 'set_app_auto_update',+ category: 'app_update',+ description: `用户要求开启或关闭 ${BRAND_NAME}「空闲时自动安装更新」时调用。宿主会向用户弹出确认卡,确认后写入「设置 → 关于」中的同一开关。`,+ inputShape: {+ enabled: z.boolean().describe('true = 开启空闲时自动安装更新;false = 关闭'),+ },+ handler: async ({ enabled }) => {+ const resolved = resolveCaller();+ if ('error' in resolved) return resolved.error;+ try {+ return hostPayload(await setAutoUpdate(resolved.caller, enabled));+ } catch (cause) {+ return errorPayload('AUTO_UPDATE_SETTING_FAILED', String(cause));+ }+ },+ });+ }}diff --git a/packages/maker-core/src/session.origin.test.ts b/packages/maker-core/src/session.origin.test.tsindex 36332d388d..a9159ca7b5 100644--- a/packages/maker-core/src/session.origin.test.ts+++ b/packages/maker-core/src/session.origin.test.ts@@ -318,6 +318,18 @@ describe('Session per-turn origin 打标', () => {releaseLease();});+ it('exposes the dispatched turn origin to Host authority checks and clears it at terminal', async () => {+ const { handle, emit } = createControllableHandle();+ const session = makeSession(handle);+ expect(session.getCurrentTurnOrigin()).toBeNull();+ await session.send('go', { origin: SCHED_ORIGIN });+ expect(session.getCurrentTurnOrigin()).toEqual(SCHED_ORIGIN);+ await emit({ type: 'done', data: {} });+ expect(session.getCurrentTurnOrigin()).toBeNull();+ await session.send('typed');+ expect(session.getCurrentTurnOrigin()).toBeNull();+ });+it.each([SCHED_ORIGIN, { kind: 'user', surface: 'im' } as const])('带 origin 的 send → 本轮每个事件都带同一 turnOrigin;done 后清空 (%j)', async (origin) => {const { handle, emit } = createControllableHandle();const session = makeSession(handle);diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.tsindex 751fc848d7..1e170e6c8d 100644--- a/packages/maker-core/src/session.ts+++ b/packages/maker-core/src/session.ts@@ -2106,6 +2106,11 @@ export class Session {return this.handle.getCurrentTurnId?.() ?? null;}+ /** Product origin of the dispatched turn; Host owner-only actions refuse automated turns. */+ getCurrentTurnOrigin(): SendOrigin | null {+ return this.currentTurnOrigin;+ }+/*** dryRun: 问 SDK 这次 rewind 会动哪些文件。返回 RewindFilesResult 给 UI 显示 diff。* SDK 软拒绝 (老 session 无 checkpointing) 包成 {canRewind:false, error}, 业务可继续。