Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(local-agent): 支持按应用创建可见任务并隔离接管
DavidShen10c135104012
diff --git a/apps/desktop/scripts/fixtures/local-agent/local-agent-fixture.tsx b/apps/desktop/scripts/fixtures/local-agent/local-agent-fixture.tsxindex d732a170e0..e9460d32b4 100644--- a/apps/desktop/scripts/fixtures/local-agent/local-agent-fixture.tsx+++ b/apps/desktop/scripts/fixtures/local-agent/local-agent-fixture.tsx@@ -14,6 +14,13 @@ mountPage({if (ctx.data.loadFailed) throw new Error('fixture connection read failed');return ctx.data.connections ?? [];},+ setCreateVisibleSessions: async (id: string, enabled: boolean) => {+ if (ctx.data.saveFailed) throw new Error('fixture setting write failed');+ const connection = ctx.data.connections?.find((entry: { id: string }) => entry.id === id);+ if (!connection) return false;+ connection.createVisibleSessions = enabled;+ return true;+ },revoke: async (id: string) => {if (id !== ctx.data.connections?.[0]?.id) throw new Error('wrong connection selected');if (ctx.data.revokeFailed) throw new Error('fixture revoke failed');diff --git a/apps/desktop/scripts/fixtures/local-agent/ui-page.mjs b/apps/desktop/scripts/fixtures/local-agent/ui-page.mjsindex 84617cb390..6a5c7efa84 100644--- a/apps/desktop/scripts/fixtures/local-agent/ui-page.mjs+++ b/apps/desktop/scripts/fixtures/local-agent/ui-page.mjs@@ -17,6 +17,8 @@ export default {'dev-failed': { about: 'API startup failure cannot supply a code', data: { developer: { state: 'failed' } } },'dev-stopped': { about: 'Stopped API cannot supply a code', data: { developer: { state: 'stopped' } } },default: { about: 'Revoke one application and retain the other row', data: { connections } },+ 'visible-enabled': { about: 'Toggle one application without changing another', data: { connections: [{ ...connections[0], createVisibleSessions: true }, connections[1]] } },+ 'save-failed': { about: 'A failed preference write retains the previous setting', data: { connections, saveFailed: true } },long: { about: 'Long unverified application names and IDs at phone width', viewport: { width: 390, height: 844 }, data: { connections: [{ id: 'grant-long', name: 'Independent application with a long name 独立本机应用程序', clientId: 'org.example.an.independent.application.with.a.long.identifier' }, connections[1],] } },@@ -61,6 +63,18 @@ export default {return;}await page.getByText(list[0].clientId, { exact: false }).waitFor();+ const toggles = page.getByRole('switch', { name: await ui.t('localAgent.createVisibleSessions'), exact: true });+ if (await toggles.nth(0).isChecked() !== Boolean(list[0].createVisibleSessions)) throw new Error('Wrong initial visibility');+ await toggles.nth(0).click();+ if (ui.data.saveFailed) {+ await page.getByText(await ui.t('localAgent.saveFailed'), { exact: true }).waitFor();+ if (await toggles.nth(0).isChecked()) throw new Error('Failed setting was shown as saved');+ } else {+ await page.waitForFunction(({ id, checked }) => document.getElementById(id)?.getAttribute('aria-checked') === String(checked), {+ id: `local-agent-visible-${list[0].id}`, checked: !Boolean(list[0].createVisibleSessions),+ });+ }+ if (await toggles.nth(1).isChecked()) throw new Error('Changed another application');await page.getByRole('button', { name: await ui.t('localAgent.revokeConnection', { app: list[0].name }), exact: true }).click();if (ui.data.cancel || ui.data.revokeFailed) await page.getByText(list[0].clientId, { exact: false }).waitFor();else await page.getByText(list[0].clientId, { exact: false }).waitFor({ state: 'detached' });diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex cfc0250f07..3fdca3cd43 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -423,7 +423,7 @@ import {} from './cindy-make/versionRuntimeIdentity.js';import { createStorageIpcHandlers } from './cindy-media/storageIpc';import { registerLocalAgentConfirmationIpc, cancelLocalAgentConfirmations } from './local-agent/confirmation.js';-import { disposeLocalAgentHost, localAgentConnections, localAgentDeveloperConnection, revokeLocalAgentConnections } from './local-agent/service.js';+import { disposeLocalAgentHost, localAgentConnections, localAgentDeveloperConnection, revokeLocalAgentConnections, setLocalAgentCreateVisibleSessions } from './local-agent/service.js';import { clearLocalEntries } from './device-link/remoteMediaCacheStore';import {collectDatabaseSizeWarningStatus,@@ -8624,6 +8624,10 @@ const registerIpcHandlers = () => {assertTrustedAppRendererEvent(event);return localAgentConnections(() => assertTrustedAppRendererEvent(event));});+ ipcMain.handle('local-agent:set-create-visible-sessions', (event, connectionId: unknown, enabled: unknown) => {+ assertTrustedAppRendererEvent(event);+ return setLocalAgentCreateVisibleSessions(connectionId, enabled, () => assertTrustedAppRendererEvent(event));+ });ipcMain.handle('local-agent:developer-connection', (event) => {assertTrustedAppRendererEvent(event);return localAgentDeveloperConnection(() => assertTrustedAppRendererEvent(event));diff --git a/apps/desktop/src/main/local-agent/__tests__/runtime.integration.test.ts b/apps/desktop/src/main/local-agent/__tests__/runtime.integration.test.tsindex 3fdc4f879b..d9c1cb5149 100644--- a/apps/desktop/src/main/local-agent/__tests__/runtime.integration.test.ts+++ b/apps/desktop/src/main/local-agent/__tests__/runtime.integration.test.ts@@ -8,6 +8,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';import fs from 'node:fs/promises';import os from 'node:os';import path from 'node:path';+vi.mock('../../logger.js', () => ({ createLogger: () => ({ warn: vi.fn() }) }));vi.mock('@cindy/maker-core', () => ({LOCAL_AGENT_CLIENT: Symbol('local-agent-client'),assertSendDispatched: (result: { accepted: boolean }) => {@@ -15,7 +16,12 @@ vi.mock('@cindy/maker-core', () => ({},}));import { openLocalAgentRuntime } from '../runtime.js';+import {+ installLocalAgentVisibleSessionHost,+ takeOverLocalAgentVisibleSession,+} from '../visibleSessions.js';import type { AgentEvent } from '@cindy/maker-core';+import { acquireSendToSessionLock } from '../../maker-ipc/sendToSessionLock.js';const cleanups: Array<() => Promise<unknown>> = [];afterEach(async () => {@@ -46,11 +52,17 @@ function handle(id: string) {}),};}-async function fixture() {+async function fixture(visible = false) {const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-local-runtime-'));cleanups.push(() => fs.rm(directory, { recursive: true, force: true }));const first = handle('first');const maker = { startLocalAgentSession: vi.fn(async () => first) };+ const host = {+ open: vi.fn(async (_options: any) => first),+ persistInput: vi.fn(async (..._args: any[]) => {}),+ close: vi.fn(async (_id: string, session: any) => session.close()),+ };+ installLocalAgentVisibleSessionHost(() => host as any);const events: unknown[] = [];const runtime = await openLocalAgentRuntime(maker as any,@@ -72,6 +84,7 @@ async function fixture() {},access: 'none',tools: [],+ ...(visible ? { visibleSession: { title: 'TapTap', clientId: 'com.taptap.pc' } } : {}),},{url: 'http://127.0.0.1:1/mcp/fixture',@@ -80,7 +93,7 @@ async function fixture() {},);cleanups.push(() => runtime.close());- return { runtime, maker, first, directory, events };+ return { runtime, maker, first, host, directory, events };}const image = { type: 'image', mimeType: 'image/png', data: Buffer.from('png').toString('base64') };async function inputFiles(directory: string) {@@ -91,6 +104,125 @@ async function inputFiles(directory: string) {const message = { parts: [{ type: 'text', text: 'hello' }], effort: 'high' };describe('local client runtime lifecycle', () => {+ // #7631 review P0: the existing visible-session tests only mock persistence.+ // A Cindy input must await close/handoff and fence all subsequent app input.+ // Minimal input: one live visible runtime followed by a host takeover (integration).+ it('fences the app before handing the visible task to Cindy', async () => {+ const f = await fixture(true);+ const entered = deferred(), finish = deferred();+ cleanups.push(async () => { finish.resolve(); });+ f.host.close.mockImplementationOnce(async () => {+ entered.resolve();+ await finish.promise;+ await f.first.close();+ });+ let ready = false;+ const takeover = takeOverLocalAgentVisibleSession(f.runtime.visibleSessionId!).then(() => {+ ready = true;+ });+ await entered.promise;+ expect(ready).toBe(false);+ await expect(f.runtime.call('send', message)).rejects.toThrow('已关闭');+ await expect(f.runtime.call('steer', message)).rejects.toThrow('已关闭');+ finish.resolve();+ await takeover;+ expect(ready).toBe(true);+ await takeOverLocalAgentVisibleSession(f.runtime.visibleSessionId!);+ expect(f.host.close).toHaveBeenCalledTimes(1);+ expect(f.first.send).not.toHaveBeenCalled();+ f.first.onEvent.mock.calls[0][0]({ type: 'text', data: { text: 'private Cindy output' } } as AgentEvent);+ expect(f.events).toEqual([]);+ });++ it('joins an API close queued behind the Cindy send lease without waiting on itself', async () => {+ const f = await fixture(true);+ const release = await acquireSendToSessionLock(f.runtime.visibleSessionId!);+ cleanups.push(async () => { release(); });+ const closing = f.runtime.close();+ try {+ await takeOverLocalAgentVisibleSession(f.runtime.visibleSessionId!, true);+ expect(f.first.close).toHaveBeenCalledOnce();+ } finally {+ release();+ }+ await closing;+ expect(f.host.close).toHaveBeenCalledOnce();+ });++ it('does not reopen an external engine waiting behind a Cindy takeover', async () => {+ const f = await fixture(true);+ const release = await acquireSendToSessionLock(f.runtime.visibleSessionId!);+ cleanups.push(async () => { release(); });+ await f.runtime.call('instructions', { instructions: 'new instructions' });+ const sending = f.runtime.call('send', message);+ const rejected = expect(sending).rejects.toThrow('已关闭');+ try {+ await vi.waitFor(() => expect(f.first.close).toHaveBeenCalledOnce());+ await takeOverLocalAgentVisibleSession(f.runtime.visibleSessionId!, true);+ } finally {+ release();+ }+ await rejected;+ expect(f.host.open).toHaveBeenCalledOnce();+ expect(f.first.send).not.toHaveBeenCalled();+ });++ it('blocks takeover on failed handoff and retries without reopening the app runtime', async () => {+ const f = await fixture(true);+ f.host.close.mockRejectedValueOnce(new Error('handoff unavailable'));+ await expect(takeOverLocalAgentVisibleSession(f.runtime.visibleSessionId!))+ .rejects.toThrow('handoff unavailable');+ await expect(f.runtime.call('send', message)).rejects.toThrow('已关闭');+ await takeOverLocalAgentVisibleSession(f.runtime.visibleSessionId!);+ expect(f.host.close).toHaveBeenCalledTimes(2);+ expect(f.host.open).toHaveBeenCalledTimes(1);+ });++ // #7631: publishing a task must retain the app tool boundary, save the+ // original input before dispatch, and close through the task handoff path.+ it('publishes opted-in sessions with durable input and the same app capability', async () => {+ const f = await fixture(true);+ expect(f.maker.startLocalAgentSession).not.toHaveBeenCalled();+ expect(f.runtime.visibleSessionId).toEqual(expect.any(String));+ expect(f.host.open.mock.calls[0][0]).toMatchObject({+ id: f.runtime.visibleSessionId,+ title: 'TapTap',+ workspaceKind: 'dialogue',+ makerMemoryEnabled: false,+ });+ f.first.send.mockImplementation(async (...args: any[]) => {+ await args[1].onAccepted();+ return { accepted: true };+ });+ await f.runtime.call('send', { parts: message.parts });+ await vi.waitFor(() => expect(f.host.persistInput).toHaveBeenCalledTimes(1));+ expect(f.host.persistInput.mock.calls[0][1]).toEqual({ type: 'user', content: message.parts });+ expect((f.first.send.mock.calls[0] as any)[0].content.at(-1).text).toContain(+ 'app_id: com.taptap.pc',+ );+ await f.runtime.close();+ expect(f.host.close).toHaveBeenCalledWith(f.runtime.visibleSessionId, f.first);+ });++ it('does not dispatch an opted-in input if its durable task record cannot be saved', async () => {+ const f = await fixture(true);+ f.host.persistInput.mockRejectedValueOnce(new Error('disk unavailable'));+ const dispatched = vi.fn();+ f.first.send.mockImplementation(async (...args: any[]) => {+ await args[1].onAccepted();+ dispatched();+ return { accepted: true };+ });+ await f.runtime.call('send', { parts: message.parts });+ await vi.waitFor(() =>+ expect(f.events).toContainEqual({+ type: 'turn_end',+ data: { status: 'failed', message: 'Cindy 未能完成本次发送。' },+ }),+ );+ expect(dispatched).not.toHaveBeenCalled();+ });+it('passes slash-prefixed app text as a literal instead of rejecting paths or running a native command', async () => {const f = await fixture();await f.runtime.call('send', { parts: [{ type: 'text', text: '/workspace/example' }] });@@ -194,7 +326,10 @@ describe('local client runtime lifecycle', () => {held = deferred(),second = handle('second'),third = handle('third');- cleanups.push(() => second.close(), () => third.close());+ cleanups.push(+ () => second.close(),+ () => third.close(),+ );f.maker.startLocalAgentSession.mockImplementationOnce(async () => {entered.resolve();diff --git a/apps/desktop/src/main/local-agent/__tests__/server.integration.test.ts b/apps/desktop/src/main/local-agent/__tests__/server.integration.test.tsindex 6eb2b55d3d..54e8764a70 100644--- a/apps/desktop/src/main/local-agent/__tests__/server.integration.test.ts+++ b/apps/desktop/src/main/local-agent/__tests__/server.integration.test.ts@@ -126,6 +126,58 @@ async function fixture(overrides: Partial<LocalAgentServerDeps> = {}) {}describe('local application authorization and lifecycle', () => {+ // #7631: only the owner setting may publish app sessions. RPC parameters+ // cannot enable it; the preference survives an API restart without allowing+ // the caller to select an existing Cindy task.+ it('defaults to private sessions and persists visibility independently for each authorized app', async () => {+ const f = await fixture();+ const first = await f.connect({ id: 'org.example.first', name: 'First' });+ const second = await f.connect({ id: 'org.example.second', name: 'Second' });+ const connection = f.server().connections()[0];+ await f.start(first, 'hidden', {+ visibleSession: { id: 'another-private-task' },+ createVisibleSessions: true,+ });+ expect(f.open.mock.calls[0][0].visibleSession).toBeUndefined();+ expect(await f.server().setCreateVisibleSessions(connection.id, true)).toBe(true);+ f.open.mockImplementation(async (input) => ({+ id: 'native-session',+ resumed: Boolean(input.resume),+ call: f.call,+ close: f.close,+ ...(input.visibleSession ? { visibleSessionId: 'visible-task' } : {}),+ }));+ const opened = await f.start(first, 'visible');+ expect(opened.result.cindySessionId).toBe('visible-task');+ expect(f.open.mock.calls.at(-1)![0].visibleSession).toEqual({+ title: 'First',+ clientId: 'org.example.first',+ });+ await f.start(second, 'hidden');+ expect(f.open.mock.calls.at(-1)![0].visibleSession).toBeUndefined();+ await f.restart();+ expect(+ f+ .server()+ .connections()+ .map((c) => Boolean(c.createVisibleSessions)),+ ).toEqual([true, false]);+ await f.start(first, 'resumed', { resume: opened.result.id });+ expect(f.open.mock.calls.at(-1)![0].visibleSession).not.toHaveProperty('id');+ grantWrites.fail = true;+ await expect(f.server().setCreateVisibleSessions(connection.id, false)).rejects.toThrow();+ expect(f.server().connections()[0].createVisibleSessions).toBe(true);+ await Promise.allSettled([+ f.server().setCreateVisibleSessions(connection.id, false),+ f.server().setCreateVisibleSessions(connection.id, true),+ ]);+ expect(f.server().connections()[0].createVisibleSessions).toBe(true);+ grantWrites.fail = false;+ expect(await f.server().setCreateVisibleSessions(connection.id, false)).toBe(true);+ await f.start(first, 'hidden-again');+ expect(f.open.mock.calls.at(-1)![0].visibleSession).toBeUndefined();+ });+it('bounds untrusted connection-code handshakes without following redirects or hanging on a reused port', async () => {let mode = 'redirect';let requests = 0;diff --git a/apps/desktop/src/main/local-agent/__tests__/service.test.ts b/apps/desktop/src/main/local-agent/__tests__/service.test.tsindex b09e5f7282..2dd77c2026 100644--- a/apps/desktop/src/main/local-agent/__tests__/service.test.ts+++ b/apps/desktop/src/main/local-agent/__tests__/service.test.ts@@ -17,6 +17,7 @@ const mock = vi.hoisted(() => ({handlers: new Map<string, (...args: any[]) => any>(),revoke: vi.fn(async (_id: string) => true),revokeAll: vi.fn(async () => {}),+ setVisible: vi.fn(async (_id: string, _enabled: boolean) => true),close: vi.fn(async () => {}),send: vi.fn(),trusted: true,@@ -93,6 +94,7 @@ vi.mock('../server.js', () => ({],revoke: mock.revoke,revokeAll: mock.revokeAll,+ setCreateVisibleSessions: mock.setVisible,close: mock.close,};},@@ -110,6 +112,7 @@ import {localAgentConnections,localAgentDeveloperConnection,revokeLocalAgentConnections,+ setLocalAgentCreateVisibleSessions,} from '../service.js';beforeEach(async () => {@@ -145,6 +148,18 @@ afterEach(async () => {});describe('generic local app Cindy authorization', () => {+ // #7631: a settings write is owner-scoped, validated and never granted by+ // an app RPC. Existing revocation tests do not exercise this new operation.+ it('changes only the requested connection and rejects malformed or stale-owner settings writes', async () => {+ expect(await setLocalAgentCreateVisibleSessions('grant-a', true)).toBe(true);+ expect(mock.setVisible).toHaveBeenCalledWith('grant-a', true);+ await expect(setLocalAgentCreateVisibleSessions('grant-a', 'true')).rejects.toThrow('[INVALID_PARAMS]');+ mock.setVisible.mockClear();+ const pending = setLocalAgentCreateVisibleSessions('grant-a', false);+ mock.generation++;+ expect(await pending).toBe(false);+ expect(mock.setVisible).not.toHaveBeenCalled();+ });// Regression: the old OS dialog owned cancellation. The shared Renderer round trip// must now retire the exact request, including queued prompts and late replies.it.each(['abort', 'close', 'destroyed', 'render-process-gone', 'navigation', 'in-page', 'timeout', 'owner'] as const)(diff --git a/apps/desktop/src/main/local-agent/runtime.ts b/apps/desktop/src/main/local-agent/runtime.tsindex 694f0d32c7..0ff71d6851 100644--- a/apps/desktop/src/main/local-agent/runtime.ts+++ b/apps/desktop/src/main/local-agent/runtime.ts@@ -13,6 +13,12 @@ import {type UserMessage,} from '@cindy/maker-core';import { LocalAgentError, type LocalAgentOpen, type LocalAgentRuntime } from './server.js';+import {+ localAgentVisibleSessionHost,+ registerLocalAgentVisibleRuntime,+} from './visibleSessions.js';+import { withSendToSessionLock } from '../maker-ipc/sendToSessionLock.js';+import { buildMessageSourceNote } from '@cindy/maker-shared/message-source';const object = (v: unknown): Record<string, unknown> =>v && typeof v === 'object' ? (v as Record<string, unknown>) : {};@@ -207,12 +213,35 @@ export async function openLocalAgentRuntime(let instructions = input.instructions;// The effort last applied by send.effort survives an instructions rebuild.let effort = input.effort;- const sessionId = `local-agent-${randomUUID()}`;- let handle: Session;+ const visibleHost = input.visibleSession+ ? localAgentVisibleSessionHost(maker as Maker)+ : undefined;+ if (input.visibleSession && !visibleHost)+ throw new LocalAgentError('SESSION_UNAVAILABLE', 'Cindy 任务入口尚未就绪。');+ const sessionId = visibleHost ? randomUUID() : `local-agent-${randomUUID()}`;+ const source = input.visibleSession+ ? { pluginId: `local-app:${input.visibleSession.clientId}`, name: input.visibleSession.title }+ : undefined;+ const wireMessage = (message: UserMessage): UserMessage => {+ if (!source) return message;+ const note = buildMessageSourceNote({ kind: 'plugin', ...source })!;+ return {+ ...message,+ content: [+ ...(typeof message.content === 'string'+ ? [{ type: 'text' as const, text: message.content }]+ : message.content),+ { type: 'text', text: note },+ ],+ };+ };+ // start assigns this under the send lock; close also handles failed startup.+ let handle!: Session;let closed = false,busy = false,preparing = false,resumed = false;+ let closing: Promise<void> | undefined;// Instructions are read when a Session starts; only that applied version is clean.let instructionsVersion = 0,appliedInstructions = 0;@@ -227,7 +256,34 @@ export async function openLocalAgentRuntime(await fs.mkdir(applicationDirectory, { recursive: true, mode: 0o700 });const temporary = await fs.mkdtemp(path.join(applicationDirectory, 'input-'));const projection = createEventProjection(bridge.emit, input.mcpName, localize);- const start = async (resume?: string, expected = epoch) => {+ const locked = <T>(task: () => Promise<T>) =>+ visibleHost ? withSendToSessionLock(sessionId, task) : task();+ let unregisterVisibleRuntime: (() => void) | undefined;+ const close = (sendLockHeld = false): Promise<void> => {+ // Fence app calls immediately, even while waiting for a Cindy send/route lock.+ closed = true;+ ++epoch;+ busy = false;+ const finish = () => {+ // Assign only after acquiring the lock. A normal close queued behind a+ // takeover must not make that takeover await its own lock release.+ if (closing) return closing;+ closing = (async () => {+ if (handle) {+ if (visibleHost) await visibleHost.close(sessionId, handle);+ else await handle.close({ reason: 'account-boundary' });+ }+ await fs.rm(temporary, { recursive: true, force: true }).catch(() => {});+ unregisterVisibleRuntime?.();+ })().catch((error) => {+ closing = undefined;+ throw error;+ });+ return closing;+ };+ return sendLockHeld ? finish() : locked(finish);+ };+ const startUnlocked = async (resume?: string, expected = epoch) => {assertCurrent(expected);const opts: StartSessionOptions = {sessionId,@@ -254,7 +310,16 @@ export async function openLocalAgentRuntime(},};resumed = Boolean(resume);- const next = await maker.startLocalAgentSession(input.model.engine, opts);+ const next = visibleHost+ ? await visibleHost.open({+ ...opts,+ id: sessionId,+ agentKind: input.model.engine,+ title: input.visibleSession!.title,+ workspaceKind: 'dialogue',+ })+ : await maker.startLocalAgentSession(input.model.engine, opts);+ handle = next;try {assertCurrent(expected);} catch (error) {@@ -268,7 +333,6 @@ export async function openLocalAgentRuntime('Cindy 原会话已不存在,请在调用应用中开始新的任务。未重放旧消息。',);}- handle = next;next.setInteractionListener(async (request) => {if (request.kind === 'permission') {const hostTool = input.tools.some((tool) =>@@ -315,9 +379,13 @@ export async function openLocalAgentRuntime(});return next;};+ const start = (resume?: string, expected = epoch) => locked(() => startUnlocked(resume, expected));+ if (visibleHost) unregisterVisibleRuntime = registerLocalAgentVisibleRuntime(sessionId, close);try {handle = await start(input.resume);} catch (error) {+ if (visibleHost && handle) await close();+ else unregisterVisibleRuntime?.();await fs.rm(temporary, { recursive: true, force: true });throw error;}@@ -387,6 +455,7 @@ export async function openLocalAgentRuntime(}};return {+ ...(visibleHost ? { visibleSessionId: sessionId } : {}),get id() {return handle.sdkSessionId;},@@ -427,7 +496,15 @@ export async function openLocalAgentRuntime(try {assertCurrent(current);if (!busy) throw new LocalAgentError('NOT_RUNNING', '当前没有正在运行的回答。');- await handle.steer(content);+ await handle.steer(wireMessage(content));+ if (visibleHost)+ await visibleHost.persistInput(+ sessionId,+ content,+ randomUUID(),+ () => assertCurrent(current),+ source!,+ );turnInputs.push(content);} catch (error) {await discard(content);@@ -464,7 +541,21 @@ export async function openLocalAgentRuntime(releaseInputs();turnInputs.push(sending);void (async () => {- const result = await handle.send(sending);+ const result = visibleHost+ ? await handle.send(wireMessage(sending), {+ onAccepted: (signal) =>+ visibleHost.persistInput(+ sessionId,+ sending,+ randomUUID(),+ () => {+ assertCurrent(current);+ signal?.throwIfAborted();+ },+ source!,+ ),+ })+ : await handle.send(sending);if (!result.accepted) await discard(sending);assertSendDispatched(result, 'local-agent/send');})().catch(() => {@@ -487,13 +578,6 @@ export async function openLocalAgentRuntime(throw error;}},- async close() {- closed = true;- ++epoch;- busy = false;- await handle.close({ reason: 'account-boundary' });- // The engine is confirmed closed; leftover input files must not report it as still running.- await fs.rm(temporary, { recursive: true, force: true }).catch(() => {});- },+ close: () => close(),};}diff --git a/apps/desktop/src/main/local-agent/server.ts b/apps/desktop/src/main/local-agent/server.tsindex 18b3e64002..938c64138b 100644--- a/apps/desktop/src/main/local-agent/server.ts+++ b/apps/desktop/src/main/local-agent/server.ts@@ -46,10 +46,13 @@ export interface LocalAgentOpen {access: 'none' | 'full';resume?: string;tools: Array<{ name: string; description: string; parameters: Record<string, unknown> }>;+ /** Host-owned preference; never accepted from the application's RPC parameters. */+ visibleSession?: { title: string; clientId: string };}export interface LocalAgentRuntime {id: string;resumed: boolean;+ visibleSessionId?: string;call(method: string, params: Record<string, unknown>): Promise<unknown>;close(): Promise<void>;}@@ -65,6 +68,7 @@ interface Grant {scope: string;client: LocalAgentClientIdentity;legacyRuntime: boolean;+ createVisibleSessions?: boolean;}interface Pair {id: string;@@ -202,6 +206,8 @@ export async function createLocalAgentServer(deps: LocalAgentServerDeps) {if (ids.has(id) || !/^[a-f0-9]{64}$/.test(digest)) throw new Error('grant');ids.add(id);const client = clientIdentity(saved.version === 1 ? g.name : g.client);+ if (g.createVisibleSessions !== undefined && typeof g.createVisibleSessions !== 'boolean')+ throw new Error('grant preference');return {id,name: client.name,@@ -209,6 +215,7 @@ export async function createLocalAgentServer(deps: LocalAgentServerDeps) {scope: text(g.scope),client,legacyRuntime: saved.version === 1 || g.legacyRuntime === true,+ ...(g.createVisibleSessions === true ? { createVisibleSessions: true } : {}),};});if (saved.bindings !== undefined) {@@ -219,7 +226,11 @@ export async function createLocalAgentServer(deps: LocalAgentServerDeps) {const b = record(value);return [text(id, 128),- { owner: text(b.owner), model: text(b.model), native: text(b.native, 4096) },+ {+ owner: text(b.owner),+ model: text(b.model),+ native: text(b.native, 4096),+ },];}),);@@ -230,6 +241,7 @@ export async function createLocalAgentServer(deps: LocalAgentServerDeps) {throw new LocalAgentError('GRANT_STORE_INVALID', '本机应用授权记录无法读取,原文件已保留。');}let persistence = Promise.resolve();+ let preferenceChanges = Promise.resolve();// A failed write must not let a revoked grant come back from disk after restart.let unsaved = false;const persist = () => {@@ -274,7 +286,10 @@ export async function createLocalAgentServer(deps: LocalAgentServerDeps) {const idle = Date.now() - CLIENT_IDLE_MS;for (const [key, state] of clients) if (state.seen <= idle) retire(key);if (clients.size >= MAX_CLIENTS || owned() >= MAX_GRANT_CLIENTS)- throw new LocalAgentError('CLIENT_LIMIT', '本机连接数量已满,请稍后重试或在 Cindy 中重新授权。');+ throw new LocalAgentError(+ 'CLIENT_LIMIT',+ '本机连接数量已满,请稍后重试或在 Cindy 中重新授权。',+ );};let base = '';let closing = false;@@ -515,6 +530,14 @@ export async function createLocalAgentServer(deps: LocalAgentServerDeps) {access,resume: binding?.native,tools,+ ...(grant.createVisibleSessions === true+ ? {+ visibleSession: {+ title: grant.name,+ clientId: grant.client.id,+ },+ }+ : {}),},{url: `${base}/mcp/${id}`,@@ -537,7 +560,11 @@ export async function createLocalAgentServer(deps: LocalAgentServerDeps) {run.resumeKey = binding && resumeKey ? resumeKey : token();const key = run.resumeKey,prior = bindings[key],- added = { owner: grant.id, model: model.id, native: run.runtime.id };+ added = {+ owner: grant.id,+ model: model.id,+ native: run.runtime.id,+ };bindings[key] = added;try {await persist();@@ -550,7 +577,12 @@ export async function createLocalAgentServer(deps: LocalAgentServerDeps) {throw error;}assertGrant(grant);- return { id: run.resumeKey, resumed: run.runtime.resumed, sessionId };+ return {+ id: run.resumeKey,+ resumed: run.runtime.resumed,+ sessionId,+ ...(run.runtime.visibleSessionId ? { cindySessionId: run.runtime.visibleSessionId } : {}),+ };} catch (error) {await closeRun(id, run);throw error;@@ -928,7 +960,37 @@ export async function createLocalAgentServer(deps: LocalAgentServerDeps) {connections: () =>grants.filter((g) => g.scope === deps.scope())- .map((g) => ({ id: g.id, name: g.name, clientId: g.client.id })),+ .map((g) => ({+ id: g.id,+ name: g.name,+ clientId: g.client.id,+ ...(g.createVisibleSessions === true ? { createVisibleSessions: true } : {}),+ })),+ setCreateVisibleSessions(connectionId: string, enabled: boolean) {+ const operation = preferenceChanges.then(async () => {+ const grant = grants.find((g) => g.id === connectionId && g.scope === deps.scope());+ if (!grant || closing) return false;+ const previous = grant.createVisibleSessions;+ if (enabled) grant.createVisibleSessions = true;+ else delete grant.createVisibleSessions;+ try {+ await persist();+ } catch (error) {+ if (grant.createVisibleSessions === (enabled ? true : undefined)) {+ if (previous === undefined) delete grant.createVisibleSessions;+ else grant.createVisibleSessions = previous;+ }+ throw error;+ }+ deps.changed?.();+ return grants.includes(grant) && grant.scope === deps.scope() && !closing;+ });+ preferenceChanges = operation.then(+ () => {},+ () => {},+ );+ return operation;+ },revoke,async revokeAll() {grants = [];@@ -954,7 +1016,12 @@ export async function createLocalAgentServer(deps: LocalAgentServerDeps) {await new Promise<void>((resolve) => server.close(() => resolve()));await persistence;// The last retry decides whether a revocation survives restart; never report it as closed.- const saved = unsaved ? await persist().then(() => true, () => false) : true;+ const saved = unsaved+ ? await persist().then(+ () => true,+ () => false,+ )+ : true;try {if (JSON.parse(await fs.readFile(discoveryFile, 'utf8')).instance === instanceId)await fs.rm(discoveryFile, { force: true });diff --git a/apps/desktop/src/main/local-agent/service.ts b/apps/desktop/src/main/local-agent/service.tsindex 2fb4b32129..5133604a0b 100644--- a/apps/desktop/src/main/local-agent/service.ts+++ b/apps/desktop/src/main/local-agent/service.ts@@ -137,15 +137,18 @@ export function installLocalAgentHost(maker: Maker): void {return localAgentModels(providers, maker.listAvailableAgents());},async approve(signal, client) {- const approved = await confirmLocalAgent({- title: t('localAgent.connectTitle'),- message: t('localAgent.connectMessage').replaceAll('{{app}}', () => client.name),- detail: `${t('localAgent.connectDetail')}\n\n${t('localAgent.clientIdentity')- .replaceAll('{{id}}', () => client.id)- .replaceAll('{{version}}', () => client.version ?? '—')}`,- confirmText: t('localAgent.allow'),- cancelText: t('localAgent.cancel'),- }, signal);+ const approved = await confirmLocalAgent(+ {+ title: t('localAgent.connectTitle'),+ message: t('localAgent.connectMessage').replaceAll('{{app}}', () => client.name),+ detail: `${t('localAgent.connectDetail')}\n\n${t('localAgent.clientIdentity')+ .replaceAll('{{id}}', () => client.id)+ .replaceAll('{{version}}', () => client.version ?? '—')}`,+ confirmText: t('localAgent.allow'),+ cancelText: t('localAgent.cancel'),+ },+ signal,+ );return approved && !signal.aborted && scopeNow() === scope;},open: (input, bridge) =>@@ -278,6 +281,34 @@ export async function revokeLocalAgentConnections(});}+export async function setLocalAgentCreateVisibleSessions(+ connectionId: unknown,+ enabled: unknown,+ assertCaller = () => {},+): Promise<boolean> {+ if (+ typeof connectionId !== 'string' ||+ !connectionId ||+ connectionId.length > 128 ||+ typeof enabled !== 'boolean'+ )+ throwIpcError('INVALID_PARAMS', t('localAgent.invalidConnection'));+ return settingsOperation(async () => {+ const owner = activeOwnerScopeKey();+ const pendingServer = current;+ const server = pendingServer ? await pendingServer : undefined;+ assertCaller();+ if (+ !server ||+ current !== pendingServer ||+ owner !== activeOwnerScopeKey() ||+ isAppSessionBoundaryPending()+ )+ return false;+ return server.setCreateVisibleSessions(connectionId, enabled);+ });+}+export async function disposeLocalAgentHost(): Promise<void> {cancelLocalAgentConfirmations();const previous = current;diff --git a/apps/desktop/src/main/local-agent/visibleSessions.ts b/apps/desktop/src/main/local-agent/visibleSessions.tsnew file mode 100644index 0000000000..a530b558e5--- /dev/null+++ b/apps/desktop/src/main/local-agent/visibleSessions.ts@@ -0,0 +1,57 @@+import type { CreateSessionOptions, Maker, Session, UserMessage } from '@cindy/maker-core';++/** The desktop's existing task pipeline owns visible records and event persistence. */+export interface LocalAgentVisibleSessionHost {+ open(options: CreateSessionOptions): Promise<Session>;+ persistInput(+ sessionId: string,+ message: UserMessage,+ clientId: string,+ assertCurrent: () => void,+ source: { pluginId: string; name: string },+ ): Promise<void>;+ close(sessionId: string, session: Session): Promise<void>;+}++// IPC registration outlives account changes and uses a dynamic Maker facade.+// Each runtime instead binds the concrete Maker and owner present at its open.+let createHost: ((maker: Maker) => LocalAgentVisibleSessionHost) | undefined;++// Ownership is attached to the external runtime, not its self-reported app id.+// Keep failed closes registered: a subsequent Cindy input must retry the handoff,+// never reuse a partially closed external Session or resume its native history.+const externalRuntimes = new Map<string, (sendLockHeld: boolean) => Promise<void>>();++export function hasLocalAgentVisibleRuntime(sessionId: string): boolean {+ return externalRuntimes.has(sessionId);+}++export function registerLocalAgentVisibleRuntime(+ sessionId: string,+ close: (sendLockHeld: boolean) => Promise<void>,+): () => void {+ externalRuntimes.set(sessionId, close);+ return () => {+ if (externalRuntimes.get(sessionId) === close) externalRuntimes.delete(sessionId);+ };+}++/** Called before Cindy input/control, including callers holding an explicit send lease. */+export async function takeOverLocalAgentVisibleSession(+ sessionId: string,+ sendLockHeld = false,+): Promise<void> {+ await externalRuntimes.get(sessionId)?.(sendLockHeld);+}++export function installLocalAgentVisibleSessionHost(+ factory: (maker: Maker) => LocalAgentVisibleSessionHost,+): void {+ createHost = factory;+}++export function localAgentVisibleSessionHost(+ maker: Maker,+): LocalAgentVisibleSessionHost | undefined {+ return createHost?.(maker);+}diff --git a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.tsindex ca947065dd..09fabe5f3c 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts@@ -65,6 +65,35 @@ function withUiLanguageNote(content: string): string {function withUiLanguageUserMessage(content: string): { type: 'user'; content: string } {return { type: 'user', content: withUiLanguageNote(content) };}++describe('local application task takeover', () => {+ // #7631 review P0. Runtime tests do not cover the ordinary send transaction.+ // Minimal regression (unit): a live external Session must be retired before+ // selecting the send target; failed handoff must never dispatch Cindy input.+ it.each([false, true])('does not reuse the external runtime (handoff fails=%s)', async (fails) => {+ const { deps, session } = createDeps();+ const replacement = createSession();+ let live: typeof session | undefined = session;+ deps.getSession = () => live;+ deps.bootstrapSession = vi.fn(async () => {+ live = replacement;+ return { session: replacement, didInjectOrcaInstructions: false, didInjectProjectContext: false };+ });+ deps.prepareExternalInput = async () => {+ if (fails) throw new Error('handoff unavailable');+ live = undefined;+ };+ const send = createMakerSendTransaction(deps).sendToAgentAccepted(+ 'session-1', 'private Cindy input', { id: 'session-1', agentKind: 'codex', workingDir: '/repo' },+ );+ if (fails) await expect(send).rejects.toThrow('handoff unavailable');+ else {+ await send;+ expect(replacement.send).toHaveBeenCalledOnce();+ }+ expect(session.send).not.toHaveBeenCalled();+ });+});describe('MCP App next-turn context', () => {it('keeps ordinary user intent when validating App context without a replacement intent', async () => {const assertCurrent = vi.fn(async () => {});diff --git a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts b/apps/desktop/src/main/maker-ipc/makerSendTransaction.tsindex 813dbd27ff..942b0195d7 100644--- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts+++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts@@ -527,6 +527,8 @@ export interface MakerSendTransactionDeps {* 随后本事务按空 session 走 lazy-create,避免 peek 之后对已关闭对象 send。*/prepareUnhealthySession?(sessionId: string): Promise<boolean | void>;+ /** Retire external ownership before selecting a runtime or applying a route. */+ prepareExternalInput?(sessionId: string): Promise<void>;/** Restore durable task status before route changes or native session resume. */restoreArchivedSessionForSend?(sessionId: string): Promise<void>;/**@@ -1138,6 +1140,7 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): MakesendOpts,): Promise<DesktopMakerSendResult> {if (typeof sessionId !== 'string') throwIpcError('INVALID_PARAMS', 'sessionId required');+ if (deps.prepareExternalInput) await deps.prepareExternalInput(sessionId);const dispatchProductTurn = deps.prepareProductTurn?.(sessionId);const requestedSendOpts = (sendOpts ?? {}) as MakerSendOptions;if (!requestedSendOpts.signal?.aborted) {diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 0f457440b3..fd681c2658 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -1111,6 +1111,7 @@ import {import { pendingHarnessRuntimeMutation, setSessionRuntimeHarness } from './sessionRuntimeHarnessSelection.js';import {COMPANION_SESSION_IDS_LIMIT,+ buildHandoffText,extractAgentIslandPromptText,extractPlainText,prependNoteToWireUserMessage,@@ -1119,6 +1120,12 @@ import {} from './agentHandoff.js';import { sanitizeSourceName } from '@cindy/maker-shared/message-source';import { registerSessionHandoffIpc } from './sessionHandoffIpc.js';+import {+ installLocalAgentVisibleSessionHost,+ hasLocalAgentVisibleRuntime,+ takeOverLocalAgentVisibleSession,+} from '../local-agent/visibleSessions.js';+import { ingestChatImageFromPath } from '../cindy-media/chatAttachments.js';import { UI_ACTION_TRIGGER_PREFIX } from '@cindy/maker-shared/synthetic-trigger';import {createContextOverflowRollover,@@ -8514,12 +8521,16 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const source = await readSessionSource(sessionId);assertCindyMakeSessionAvailable(source);await assertReviewSessionExternalInputAllowed(sessionId, async () => source);+ // This shared admission boundary precedes both direct and queued/steered+ // Cindy input. Merely opening/viewing the task does not transfer ownership.+ await takeOverLocalAgentVisibleSession(sessionId);}- async function assertReviewSettingsUnlocked(sessionId: string): Promise<void> {+ async function assertReviewSettingsUnlocked(sessionId: string, sendLockHeld = false): Promise<void> {if ((await readSessionSource(sessionId)) === 'review') {throwIpcError('UNSUPPORTED_CAPABILITY', 'Review task settings are fixed to the source task');}+ await takeOverLocalAgentVisibleSession(sessionId, sendLockHeld);}function orcaSessionStatus(sessionId: string): string {@@ -9252,6 +9263,128 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)return { session, didInjectOrcaInstructions, didInjectProjectContext };}+ installLocalAgentVisibleSessionHost((localMaker) => {+ const localAppOwner = activeOwnerScopeKey();+ const assertLocalAppOwner = () => {+ if (localAppOwner !== activeOwnerScopeKey())+ throwIpcError('PRECONDITION_FAILED', t('localAgent.authorizationRequired'));+ };+ return {+ open: (opts) =>+ withSendToSessionLock(opts.id!, async () => {+ assertLocalAppOwner();+ if (opts.id) {+ if (localMaker.getSession(opts.id))+ throwIpcError('PRECONDITION_FAILED', t('localAgent.busy'));+ const [row] = await getDbClient()+ .drizzle.select({ status: sessions.status, sdkSessionId: sessions.sdkSessionId })+ .from(sessions)+ .where(eq(sessions.id, opts.id))+ .limit(1);+ assertLocalAppOwner();+ if (+ row?.status === 'deleted' ||+ (opts.resumeSessionId &&+ row?.sdkSessionId &&+ row.sdkSessionId !== opts.resumeSessionId)+ )+ throwIpcError('PRECONDITION_FAILED', t('localAgent.executionUnavailable'));+ }+ // Keep the local application's existing tool capability and native storage.+ // The regular task pipeline supplies persistence and the desktop's live view.+ const session = await localMaker.createSession(opts);+ try {+ assertLocalAppOwner();+ if (opts.resumeSessionId && session.sdkSessionId !== opts.resumeSessionId)+ throwIpcError('PRECONDITION_FAILED', t('localAgent.executionUnavailable'));+ await persistSessionFields(session.id, {+ providerId: opts.providerId ?? null,+ permissionMode: 'ask',+ });+ assertLocalAppOwner();+ wireSessionToIpc(session);+ if (opts.resumeSessionId) agentHandoffPending.consume(session.id);+ broadcastSessionCreated(session.id);+ return session;+ } catch (error) {+ await session.close({ reason: 'account-boundary' });+ throw error;+ }+ }),+ persistInput: async (sessionId, message, clientId, assertCurrent, source) => {+ const assertValid = () => {+ assertLocalAppOwner();+ assertCurrent();+ };+ assertValid();+ const db = getDbClient().drizzle;+ const content =+ typeof message.content === 'string'+ ? message.content+ : await Promise.all(+ message.content.map(async (block) => {+ if (block.type !== 'image') return block;+ const image = await ingestChatImageFromPath({ sourcePath: block.path }, db);+ assertValid();+ return { ...block, path: image.url };+ }),+ );+ assertValid();+ await createDbMessage(+ sessionId,+ { clientId, role: 'user', content, agentMeta: { sourcePlugin: source } },+ {+ beforePublish: async () => assertValid(),+ },+ );+ },+ // The runtime owns the send lock for both API close and Cindy takeover.+ // Do not acquire it again: direct send callers may hold an explicit lease.+ close: async (sessionId, session) => {+ await session.close({ reason: 'account-boundary' });+ // Keep the external app's native history isolated. Subsequent Cindy input+ // starts a regular task with the existing durable transcript as context.+ if (localAppOwner !== activeOwnerScopeKey()) return;+ await drainPersistQueue();+ assertLocalAppOwner();+ const [row] = await getDbClient()+ .drizzle.select()+ .from(sessions)+ .where(eq(sessions.id, sessionId))+ .limit(1);+ assertLocalAppOwner();+ if (+ !row ||+ row.status === 'deleted' ||+ localMaker.getSession(sessionId) ||+ (row.sdkSessionId !== null && row.sdkSessionId !== session.sdkSessionId)+ )+ return;+ const history = await listMessagesForAgentHandoff(sessionId, 400);+ assertLocalAppOwner();+ const generation = agentHandoffPending.readGeneration(sessionId);+ const label = session.agentKind;+ const handoff = buildHandoffText(history, {+ fromLabel: label,+ toLabel: label,+ sessionId,+ reason: 'native-session-recovery',+ });+ await commitContextRebuild(sessionId, handoff, {+ reason: 'native-session-recovery',+ sourceUserClientId: null,+ sourceAgentKind: makerToDbAgentKind(session.agentKind),+ sourceModel: row.model ?? null,+ sourceProviderId: row.providerId ?? null,+ expectedClearedAt: row.clearedAt,+ });+ assertLocalAppOwner();+ agentHandoffPending.set(sessionId, handoff, generation);+ broadcastSessionPatched(sessionId, { sdkSessionId: null, contextTokens: 0 });+ },+ };+ });+async function recordBotCompactRuntimeLifecycle(input: {botId: string;sessionId: string;@@ -11643,6 +11776,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)else await scheduledModelScope.restore(sessionId);};pendingAgentSwitchApplyHolder = async (sessionId, signal, selection, beforeApply, scheduledModelOverride) => {+ await takeOverLocalAgentVisibleSession(sessionId);let stage = 'direct-send:acquire';let deferPendingApply = false;const release = await acquireSendToSessionLock(sessionId, undefined, () => stage);@@ -18103,6 +18237,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)sendToAgentAccepted: sendToAgentAcceptedUnlocked,prewarmSession: prewarmSessionRuntime,} = createMakerSendTransaction({+ prepareExternalInput: (sessionId) => takeOverLocalAgentVisibleSession(sessionId, true),restoreArchivedSessionForSend,prepareProductTurn: (sessionId) => {const dispatch = prepareUpstreamMergeTurn(sessionId);@@ -18432,6 +18567,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// 并在同一把会话发送锁里执行,真实发送不会与预热并发重复启动。const agentPrewarmer = createAgentPrewarmer({start: (sessionId, createOpts) => withSendToSessionLock(sessionId, async () => {+ if (hasLocalAgentVisibleRuntime(sessionId)) return false;if (maker.getSession(sessionId)) return false;if (agentSwitchPending.get(sessionId) || cindyMakeManager.isTaskPreparing(sessionId)) return false;// Queued work starts the runtime itself through the normal drain.@@ -22765,7 +22901,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// 后到的 SET_MODEL 才能写 route。否则切换 DB await 恢复后会用旧 provider// 覆盖用户刚选的新 route,形成 DB 与进程内路由分叉。const applyLocked = async () => {- await assertReviewSettingsUnlocked(sessionId);+ await assertReviewSettingsUnlocked(sessionId, true);if (supersededByOwnerBoundary()) {return { deferred: false, superseded: true };}diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 31412043b9..096ebd7ed1 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -1112,6 +1112,7 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('local-agent:confirmation:answer', requestId, confirmed),developerConnection: (): Promise<import('../shared/localAgent').LocalAgentDeveloperConnection | null> => ipcRenderer.invoke('local-agent:developer-connection'),connections: (): Promise<import('../shared/localAgent').LocalAgentConnection[]> => ipcRenderer.invoke('local-agent:connections'),+ setCreateVisibleSessions: (connectionId: string, enabled: boolean): Promise<boolean> => ipcRenderer.invoke('local-agent:set-create-visible-sessions', connectionId, enabled),revoke: (connectionId?: string): Promise<boolean> => ipcRenderer.invoke('local-agent:revoke', connectionId),onConnectionsChanged: (listener: () => void) => {const receive = () => listener();diff --git a/apps/desktop/src/renderer/components/chat/MessageSourceLabels.tsx b/apps/desktop/src/renderer/components/chat/MessageSourceLabels.tsxindex edee9c2fde..d7679b648a 100644--- a/apps/desktop/src/renderer/components/chat/MessageSourceLabels.tsx+++ b/apps/desktop/src/renderer/components/chat/MessageSourceLabels.tsx@@ -132,13 +132,16 @@ export function MessageSourcePluginBadge({const navigationMode = useSessionNavigationMode();const remote = Boolean(getStickySessionDeviceId(hostSessionId));const isApp = plugin.pluginId.startsWith('mcp-app:');- const interactive = navigationMode !== 'sidebar-embedded' && !remote && !isApp;+ const isLocalApp = plugin.pluginId.startsWith('local-app:');+ const interactive = navigationMode !== 'sidebar-embedded' && !remote && !isApp && !isLocalApp;return (<MessageSourceLabelShellkind="plugin"icon={<Puzzle size={11} strokeWidth={1.75} aria-hidden className="shrink-0" />}label={- isApp+ isLocalApp+ ? t('localAgent.messageSource', { name: plugin.name ?? plugin.pluginId.slice(10) })+ : isApp? t('mcpApps.messageSource', { name: plugin.name ?? plugin.pluginId.slice(8) }): plugin.name? t('chat.userMessage.pluginSentNamed', { name: plugin.name })diff --git a/apps/desktop/src/renderer/components/chat/__tests__/MessageSourceLabels.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/MessageSourceLabels.test.tsxindex 36a2988ffa..69ca892129 100644--- a/apps/desktop/src/renderer/components/chat/__tests__/MessageSourceLabels.test.tsx+++ b/apps/desktop/src/renderer/components/chat/__tests__/MessageSourceLabels.test.tsx@@ -122,6 +122,15 @@ describe('MessageSourceLabels device label', () => {});describe('MessageSourceLabels plugin and row', () => {+ // #7631: local app source IDs must not open an unrelated plugin page.+ it('identifies a local application and shows its app ID without plugin navigation', () => {+ render(<MessageSourceLabels sourcePlugin={{ pluginId: 'local-app:com.taptap.pc', name: 'TapTap' }} />);+ const label = screen.getByText('localAgent.messageSource:TapTap');+ expect(label.closest('[title]')?.getAttribute('title')).toBe('chat.userMessage.sourceIds.localApp:com.taptap.pc');+ expect(screen.queryByRole('button')).toBeNull();+ fireEvent.click(label);+ expect(mocks.navigate).not.toHaveBeenCalled();+ });it.each([['Reports', 'Reports'], [undefined, 'reports']])('identifies MCP Apps by server name or ID without opening plugin details (%s)',(name, expectedLabel) => {diff --git a/apps/desktop/src/renderer/components/settings/LocalAgentSection.tsx b/apps/desktop/src/renderer/components/settings/LocalAgentSection.tsxindex 3351a21bdc..83744812de 100644--- a/apps/desktop/src/renderer/components/settings/LocalAgentSection.tsx+++ b/apps/desktop/src/renderer/components/settings/LocalAgentSection.tsx@@ -1,6 +1,7 @@import { Fragment, useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { Button } from '@/components/ui/button';+import { Switch } from '@/components/ui/switch';import { toast } from '@/lib/toast';import { extractIpcError } from '@/utils/ipcError';import type {@@ -22,6 +23,7 @@ export function LocalAgentSection() {const [loading, setLoading] = useState(true);const [failed, setFailed] = useState(false);const [revoking, setRevoking] = useState<string>();+ const [saving, setSaving] = useState<string>();const [developer, setDeveloper] = useState<LocalAgentDeveloperConnection | null>(null);const [copying, setCopying] = useState(false);const copyingRef = useRef(false);@@ -97,10 +99,32 @@ export function LocalAgentSection() {setRevoking(undefined);}};+ const setVisibleSessions = async (id: string, enabled: boolean) => {+ if (busy.current) return;+ busy.current = true;+ setSaving(id);+ try {+ if (!(await window.electronAPI.localAgent.setCreateVisibleSessions(id, enabled)))+ throw new Error('Connection unavailable');+ setConnections((previous) =>+ previous.map((connection) =>+ connection.id === id ? { ...connection, createVisibleSessions: enabled } : connection,+ ),+ );+ } catch (error) {+ toast.error(extractIpcError(error)?.message ?? t('localAgent.saveFailed'));+ } finally {+ busy.current = false;+ setSaving(undefined);+ }+ };return (<div id="settings-search-target-local-agent" className="mt-6 flex flex-col gap-[14px]"><h2 className={SETTINGS_SECTION_TITLE_CLASS}>{t('localAgent.title')}</h2>- <div className={SETTINGS_CARD_CLASS} aria-busy={loading || Boolean(revoking)}>+ <div+ className={SETTINGS_CARD_CLASS}+ aria-busy={loading || Boolean(revoking) || Boolean(saving)}+ >{developer && (<><div className={SETTINGS_ROW_CLASS}>@@ -140,13 +164,36 @@ export function LocalAgentSection() {className="shrink-0"variant="secondary"size="sm"- disabled={Boolean(revoking)}+ disabled={Boolean(revoking) || Boolean(saving)}aria-label={t('localAgent.revokeConnection', { app: connection.name })}onClick={() => void revoke(connection.id)}>{t(revoking === connection.id ? 'localAgent.revoking' : 'localAgent.revoke')}</Button></div>+ <div className={SETTINGS_ROW_CLASS}>+ <div className="flex min-w-0 flex-col gap-1">+ <label+ htmlFor={`local-agent-visible-${connection.id}`}+ className={SETTINGS_ROW_LABEL_CLASS}+ >+ {t('localAgent.createVisibleSessions')}+ </label>+ <p+ id={`local-agent-visible-hint-${connection.id}`}+ className={SETTINGS_ROW_HINT_CLASS}+ >+ {t('localAgent.createVisibleSessionsHint')}+ </p>+ </div>+ <Switch+ id={`local-agent-visible-${connection.id}`}+ aria-describedby={`local-agent-visible-hint-${connection.id}`}+ checked={connection.createVisibleSessions === true}+ disabled={Boolean(revoking) || Boolean(saving)}+ onCheckedChange={(enabled) => void setVisibleSessions(connection.id, enabled)}+ />+ </div></Fragment>))) : (diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 39f8145e78..968cddf6ca 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -22,6 +22,10 @@}},"localAgent": {+ "createVisibleSessions": "Create visible sessions in Cindy",+ "createVisibleSessionsHint": "Applies to sessions this app opens from now on. Messages are saved in Cindy; existing sessions are kept when turned off.",+ "saveFailed": "Could not save this setting. Try again.",+ "messageSource": "Sent by local app “{{name}}”","title": "Local App Connections","empty": "No connected apps","description": "Authorized local apps can use Cindy models and agent capabilities. Cindy keeps supplier credentials.",@@ -12871,6 +12875,7 @@"pluginSent": "Sent by plugin","pluginViewDetail": "View plugin","sourceIds": {+ "localApp": "App ID: {{id}}","mcpApp": "$t(mcpApps.serverId)","session": "Session ID: {{id}}","teammate": "Teammate ID: {{id}}",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 5dcd384eed..7730e5c683 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -22,6 +22,10 @@}},"localAgent": {+ "createVisibleSessions": "Cindy に表示するセッションを作成",+ "createVisibleSessionsHint": "今後このアプリが開くセッションに適用します。メッセージは Cindy に保存され、オフにしても既存のセッションは残ります。",+ "saveFailed": "設定を保存できませんでした。もう一度お試しください。",+ "messageSource": "ローカルアプリ「{{name}}」から送信","title": "ローカルアプリの接続","empty": "接続済みのアプリはありません","description": "承認したローカルアプリが Cindy のモデルと実行機能を利用できます。認証情報は Cindy が管理します。",@@ -12826,6 +12830,7 @@"pluginSent": "プラグインから送信","pluginViewDetail": "プラグインを表示","sourceIds": {+ "localApp": "アプリ ID:{{id}}","mcpApp": "$t(mcpApps.serverId)","session": "セッション ID:{{id}}","teammate": "仲間 ID:{{id}}",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 616d6ca9f9..0557367901 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -22,6 +22,10 @@}},"localAgent": {+ "createVisibleSessions": "Cindy에 표시되는 세션 생성",+ "createVisibleSessionsHint": "앞으로 이 앱이 여는 세션에 적용됩니다. 메시지는 Cindy에 저장되며 꺼도 기존 세션은 유지됩니다.",+ "saveFailed": "설정을 저장하지 못했습니다. 다시 시도해 주세요.",+ "messageSource": "로컬 앱 “{{name}}”에서 전송","title": "로컬 앱 연결","empty": "연결된 앱 없음","description": "승인된 로컬 앱이 Cindy 모델과 실행 기능을 사용할 수 있습니다. 제공자 인증 정보는 Cindy가 관리합니다.",@@ -12826,6 +12830,7 @@"pluginSent": "플러그인에서 보냄","pluginViewDetail": "플러그인 보기","sourceIds": {+ "localApp": "앱 ID: {{id}}","mcpApp": "$t(mcpApps.serverId)","session": "세션 ID: {{id}}","teammate": "동료 ID: {{id}}",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 726109012d..1508c31db9 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -22,6 +22,10 @@}},"localAgent": {+ "createVisibleSessions": "在 Cindy 中创建可见任务",+ "createVisibleSessionsHint": "仅影响该应用之后打开的任务。消息会保存在 Cindy 中,关闭后已有任务仍保留。",+ "saveFailed": "保存设置失败,请重试。",+ "messageSource": "由本机应用「{{name}}」发送","title": "本机应用连接","empty": "尚未连接应用","description": "允许已授权的本机应用使用 Cindy 的模型与执行能力。供应商登录仍由 Cindy 管理。",@@ -12826,6 +12830,7 @@"pluginSent": "由插件发送","pluginViewDetail": "查看插件","sourceIds": {+ "localApp": "应用 ID:{{id}}","mcpApp": "$t(mcpApps.serverId)","session": "任务 ID:{{id}}","teammate": "伙伴 ID:{{id}}",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 06d05eeb29..5b6d9c4196 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -22,6 +22,10 @@}},"localAgent": {+ "createVisibleSessions": "在 Cindy 中建立可見任務",+ "createVisibleSessionsHint": "僅影響此應用程式之後開啟的任務。訊息會儲存在 Cindy 中,關閉後已有任務仍保留。",+ "saveFailed": "儲存設定失敗,請重試。",+ "messageSource": "由本機應用程式「{{name}}」傳送","title": "本機應用程式連線","empty": "尚未連接應用程式","description": "允許已授權的本機應用程式使用 Cindy 的模型與執行能力。供應商登入仍由 Cindy 管理。",@@ -12825,6 +12829,7 @@"pluginSent": "由插件傳送","pluginViewDetail": "檢視插件","sourceIds": {+ "localApp": "應用程式 ID:{{id}}","mcpApp": "$t(mcpApps.serverId)","session": "任務 ID:{{id}}","teammate": "夥伴 ID:{{id}}",diff --git a/apps/desktop/src/shared/localAgent.ts b/apps/desktop/src/shared/localAgent.tsindex c5cb4da707..113b5aa233 100644--- a/apps/desktop/src/shared/localAgent.ts+++ b/apps/desktop/src/shared/localAgent.ts@@ -3,12 +3,14 @@ export interface LocalAgentConnection {id: string;name: string;clientId?: string;+ createVisibleSessions?: boolean;}export interface LocalAgentSettingsApi {developerConnection(): Promise<LocalAgentDeveloperConnection | null>;connections(): Promise<LocalAgentConnection[]>;revoke(connectionId?: string): Promise<boolean>;+ setCreateVisibleSessions(connectionId: string, enabled: boolean): Promise<boolean>;onConnectionsChanged(listener: () => void): () => void;onConfirmation(listener: (request: LocalAgentConfirmation) => void): () => void;onConfirmationDismissed(listener: (requestId: string) => void): () => void;diff --git a/apps/mobile/src/__tests__/messageSourceLabels.test.ts b/apps/mobile/src/__tests__/messageSourceLabels.test.tsindex ff31bad352..0f3732dd7c 100644--- a/apps/mobile/src/__tests__/messageSourceLabels.test.ts+++ b/apps/mobile/src/__tests__/messageSourceLabels.test.ts@@ -17,6 +17,13 @@ beforeAll(async () => {await i18n.changeLanguage("zh-CN");});+// #7631: phone history must identify the same application as Desktop and the model note.+it('shows the local application name and app ID in visible task history', () => {+ const sourcePlugin = { pluginId: 'local-app:com.taptap.pc', name: 'TapTap' };+ expect(sourcePluginLabel(sourcePlugin)).toBe('由本机应用「TapTap」发送');+ expect(sourceIdText({ sourcePlugin })).toBe('应用 ID:com.taptap.pc');+});+const phone = {deviceId: "3f2a91c0-aaaa-bbbb",name: "快照名",diff --git a/apps/mobile/src/i18n/locales/en/message.json b/apps/mobile/src/i18n/locales/en/message.jsonindex 8e0814af36..626329d2dd 100644--- a/apps/mobile/src/i18n/locales/en/message.json+++ b/apps/mobile/src/i18n/locales/en/message.json@@ -9,6 +9,8 @@}},"renderer": {+ "sourceLocalApp": "Sent by local app “{{name}}”",+ "sourceLocalAppId": "App ID: {{id}}","failedSamplingAttempt": "This reply did not complete. Its content is for reference only.","moreActions": "More message actions","reply": "Reply",diff --git a/apps/mobile/src/i18n/locales/ja/message.json b/apps/mobile/src/i18n/locales/ja/message.jsonindex 7202a0189e..3eb4725d12 100644--- a/apps/mobile/src/i18n/locales/ja/message.json+++ b/apps/mobile/src/i18n/locales/ja/message.json@@ -9,6 +9,8 @@}},"renderer": {+ "sourceLocalApp": "ローカルアプリ「{{name}}」から送信",+ "sourceLocalAppId": "アプリ ID:{{id}}","failedSamplingAttempt": "この返信は完了しませんでした。内容は参考情報としてご覧ください。","moreActions": "その他のメッセージ操作","reply": "返信",diff --git a/apps/mobile/src/i18n/locales/ko/message.json b/apps/mobile/src/i18n/locales/ko/message.jsonindex bbdabeb804..404f892266 100644--- a/apps/mobile/src/i18n/locales/ko/message.json+++ b/apps/mobile/src/i18n/locales/ko/message.json@@ -9,6 +9,8 @@}},"renderer": {+ "sourceLocalApp": "로컬 앱 “{{name}}”에서 전송",+ "sourceLocalAppId": "앱 ID: {{id}}","failedSamplingAttempt": "완료되지 않은 답변입니다. 내용은 참고용으로만 확인해 주세요.","moreActions": "추가 메시지 작업","reply": "답장",diff --git a/apps/mobile/src/i18n/locales/zh-CN/message.json b/apps/mobile/src/i18n/locales/zh-CN/message.jsonindex 5dc16024ce..7f1aaa4819 100644--- a/apps/mobile/src/i18n/locales/zh-CN/message.json+++ b/apps/mobile/src/i18n/locales/zh-CN/message.json@@ -9,6 +9,8 @@}},"renderer": {+ "sourceLocalApp": "由本机应用「{{name}}」发送",+ "sourceLocalAppId": "应用 ID:{{id}}","failedSamplingAttempt": "此回复未完成,内容仅供参考。","moreActions": "更多消息操作","reply": "回复",diff --git a/apps/mobile/src/i18n/locales/zh-TW/message.json b/apps/mobile/src/i18n/locales/zh-TW/message.jsonindex b15feee2db..0d8e799178 100644--- a/apps/mobile/src/i18n/locales/zh-TW/message.json+++ b/apps/mobile/src/i18n/locales/zh-TW/message.json@@ -9,6 +9,8 @@}},"renderer": {+ "sourceLocalApp": "由本機應用程式「{{name}}」傳送",+ "sourceLocalAppId": "應用程式 ID:{{id}}","failedSamplingAttempt": "此回覆未完成,內容僅供參考。","moreActions": "更多訊息操作","reply": "回覆",diff --git a/apps/mobile/src/session/messageSourceLabels.ts b/apps/mobile/src/session/messageSourceLabels.tsindex 258b14feeb..a14c0a5b6c 100644--- a/apps/mobile/src/session/messageSourceLabels.ts+++ b/apps/mobile/src/session/messageSourceLabels.ts@@ -111,6 +111,9 @@ export function isSourceDeviceRemoved(}export function sourcePluginLabel(plugin: MessageSourcePlugin): string {+ if (plugin.pluginId.startsWith('local-app:')) {+ return i18n.t('message.renderer.sourceLocalApp', { name: plugin.name ?? plugin.pluginId.slice(10) });+ }if (plugin.pluginId.startsWith('mcp-app:')) {return i18n.t('mcpApps.messageSource', {name: plugin.name ?? plugin.pluginId.slice(8),@@ -163,6 +166,7 @@ export function orcaMessageTitle(const SOURCE_ID_I18N_KEYS: Record<MessageSourceIdKind, string> = {plugin: "message.renderer.sourcePluginId",mcpApp: "mcpApps.serverId",+ localApp: "message.renderer.sourceLocalAppId",teammate: "message.renderer.sourceTeammateId",session: "message.renderer.sourceSessionId",automation: "message.renderer.sourceAutomationId",diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex aa2ee8eaa8..9346ae634d 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -1,5 +1,15 @@# 跨端协议兼容+## 本机应用的可见任务(2026-10-28)++本机 Agent API v1 的 `session/open` 响应可选追加 `cindySessionId`。应用授权记录可选+保存 `createVisibleSessions: true`,缺省与旧授权均为关闭;旧客户端忽略新增响应字段,+不改变既有令牌、恢复句柄与工具策略。每次 open 创建新任务,调用方不能指定已有 Cindy 任务。+设置操作 `local-agent:set-create-visible-sessions` 只接受本机受信 Renderer,不进入+device-link 的 invoke 白名单。普通任务及消息沿用现有多端同步路径;本机应用来源使用+已有 `sourcePlugin` 元数据的 `local-app:` 前缀。旧查看端可能按插件显示来源,+不影响正文或执行授权;更新后显示本机应用。协议与验证入口见[本机 Agent API](../local-agent-api.md)。+## 群主与伙伴成员归属(2026-10-28)Chat Server 的 group 新建者和新任 owner 仅允许 human;非真人目标返回既有错误体中的diff --git a/docs/local-agent-api.md b/docs/local-agent-api.mdindex c59d387b3c..1d5d7a561c 100644--- a/docs/local-agent-api.md+++ b/docs/local-agent-api.md@@ -1,6 +1,6 @@# Cindy 本机 Agent API v1-这是供任意本机应用接入的 Agent 会话协议。Cindy 管理供应商、凭据、模型路由和 Claude Code / Codex / Pi 执行;客户端管理自己的界面、记录、上下文、工具实现及业务权限。HHH 是首个客户端,不是协议的应用类型或授权白名单。+这是供任意本机应用接入的 Agent 会话协议。Cindy 管理供应商、凭据、模型路由和 Claude Code / Codex / Pi 执行;客户端管理自己的界面、记录、上下文、工具实现及业务权限,用户也可按应用开启 Cindy 内的可见任务记录。HHH 是首个客户端,不是协议的应用类型或授权白名单。实现入口:[`main/local-agent/`](../apps/desktop/src/main/local-agent/)。协议扩展保持 v1,旧客户端可忽略新增能力字段;不要把兼容的本机 API 当成 OpenAI 或 Anthropic 模型 API,也不提供跨机访问。@@ -76,6 +76,16 @@ node scripts/examples/local-agent-client.mjs --connection-code "cindy-local:v1:<设置 → 远程连接 → 本机应用连接逐条显示应用和自报编号,每条可单独撤销。撤销同时失效令牌、恢复绑定、工具桥接与事件轮询,并关闭该授权的执行会话;其他授权保持可用。旧设置调用不带编号的“全部撤销”仍兼容。账号切换和退出会关闭本机 API;数据仍按 Cindy 的账号 owner 隔离。+### 在 Cindy 中创建可见任务++每个已连接应用有独立的「在 Cindy 中创建可见任务」开关,默认关闭;未设置的旧授权同样保持关闭。只有 Cindy 本机的受信设置界面能更改此偏好,应用不能通过 RPC 开启。该偏好仅影响之后的 `session/open`,不改变已打开的执行会话;关闭或撤销授权不会删除已有任务和消息。++开启后,每次 `session/open` 都创建新的普通可见任务,并沿用现有任务的消息持久化、实时事件与列表刷新。返回值可选追加 `cindySessionId`,是可用于 `cindy://session/<id>` 的任务编号,区别于应用自定的 `sessionId` 和不透明恢复句柄 `id`。传入 `resume` 仍按旧协议恢复本授权自己的原生执行,但不会查找、续接或改写之前的 Cindy 任务;之前的可见记录保留。应用不能指定 Cindy 任务编号,也不会取得由用户接管的运行时。++原问题、回复和工具活动保存在当前账号的任务历史中;图片先进入媒体总仓,临时输入回收后仍可查看。应用消息复用发送方元数据 `sourcePlugin` 的保留前缀 `local-app:<client-id>`,桌面、手机和交接文本均显示实际的本机应用来源,不提供插件详情跳转。来源名称仍是应用自报资料,不是认证依据。来源说明只追加到当次模型输入,不混入保存的正文,不增加 system 提示词。++可见任务仍沿用该应用原有的工具策略、授权隔离和独立原生历史,不装载私人记忆,也不使应用取得其他任务的访问权。仅查看任务不接管;用户在 Cindy 中发送、插话或修改运行设置前,宿主先拒绝该外部执行的新输入,关闭旧执行并完成持久上下文交接,再以普通 Cindy 任务继续。交接失败时阻止此次操作并保留重试,不回退到外部实例。外部执行正常关闭同样完成交接;应用的恢复句柄只保留接管前的原生历史,无法观察、控制或恢复接管后的 Cindy 运行时。此设置不提供未安装唤起、安装后重试或未登录期间的入站队列。+## 目录和会话操作| method | params | result / 语义 |@@ -120,7 +130,7 @@ node scripts/examples/local-agent-client.mjs --connection-code "cindy-local:v1:<## 执行、存储与兼容-`Maker.startLocalAgentSession` 复用三种引擎及既有内存 `Session`,由同一套发送、原生续段、终态归属、工具循环与关闭生命周期管理执行;不建立第二个 Agent 循环,也不写入 Cindy 的私人任务数据库或装载私人记忆。原生带 continuation claim 的 done 只是 SDK 段落边界,不能提前宣布客户端执行完成或接受下一轮发送。原生 cancelled 投影为 interrupted。+默认使用 `Maker.startLocalAgentSession` 复用三种引擎及既有内存 `Session`,由同一套发送、原生续段、终态归属、工具循环与关闭生命周期管理执行;不建立第二个 Agent 循环,也不写入 Cindy 的私人任务数据库或装载私人记忆。用户为应用开启可见任务后,改走既有 `Maker.createSession` 和 Desktop 消息记录管线,工具策略仍由原本机能力约束。原生带 continuation claim 的 done 只是 SDK 段落边界,不能提前宣布客户端执行完成或接受下一轮发送。原生 cancelled 投影为 interrupted。Claude client-only 关闭原生 tools/settings/skills;Pi 仅开启客户端网关;Codex 使用独立模型工具目录、app-server 与原生历史配置,保留所选模型的窗口配置。client-only 不合入 Cindy 的其他 MCP。Cindy 固定身份、回答呈现、host system prompt 及既有动态段装配保持原样;插件花名册仍由原回调按工作目录、启用状态和账号可见性产生,通讯录说明沿用各引擎现有可用性判断。花名册与提示词不是工具授权;连接未注册的私人 MCP 仍不可调用,也不因此取得私人任务、记忆或供应商凭据。静态指引可能提及本连接未开放的能力,调用方须按本连接实际登记的工具与公开事件处理,不能仅凭文字假定能力已获授权。Codex native 排除自动继承的私有 MCP 连接与 Apps 账号连接(包括原生插件自带的 MCP 服务,它们可能携带账号凭据),同时保留工作目录的原生技能、原生插件与执行能力,不复用 Review 的全量技能禁用策略。native 模式仍可读取工作目录和引擎原生配置;其文件访问受本机系统用户权限支配,API 隔离不是对同一系统用户下恶意程序的 OS 沙箱。diff --git a/docs/product-rules/message-source.md b/docs/product-rules/message-source.mdindex d14b93583f..6537257498 100644--- a/docs/product-rules/message-source.md+++ b/docs/product-rules/message-source.md@@ -15,6 +15,9 @@- 沿用既有字段:`origin`(scheduler / session / orca)、`imSource`、`hookSource`、`sharedTaskAuthor`;新增 `sourceDevice`、`sourcePlugin`;群内显式发给主人的私聊消息使用 `sourceGroup` 保存群名与 ID,桌面和手机的 assistant 消息均显示此来源。+- 本机应用的可见任务复用 `sourcePlugin` 的保留前缀 `local-app:<client-id>`,与既有+ `mcp-app:` 一样是应用来源的兼容投影;名称来自已授权连接,桌面与手机显示本机应用,+ 模型说明及交接使用 `app_id`,不链接到插件详情。它不改变应用授权或工具范围。- 新数据**不进** `origin`:多处 host 逻辑把任何 `origin.kind` 当作非人工派发。- 全部只用于归属展示,**不是**权限或信任判据;wire 传入的同名字段一律丢弃,由 host 重写。- 共享任务访客收到脱敏后的数据:任务来源去掉 id 与标题,自动化只保留「由自动化发送」,diff --git a/packages/maker-shared/src/__tests__/messageSource.test.ts b/packages/maker-shared/src/__tests__/messageSource.test.tsindex eb0f8f67bc..9165d9e3f8 100644--- a/packages/maker-shared/src/__tests__/messageSource.test.ts+++ b/packages/maker-shared/src/__tests__/messageSource.test.ts@@ -45,6 +45,13 @@ describe('promptSafeSourceName', () => {});describe('formatSourceRef', () => {+ // #7631: the task badge and model note identify a local app, never a plugin.+ it('keeps local application attribution and IDs consistent for display and handoff', () => {+ const sourcePlugin = { pluginId: 'local-app:com.taptap.pc', name: 'TapTap' };+ expect(messageSourceIdEntries({ sourcePlugin })).toEqual([{ kind: 'localApp', id: 'com.taptap.pc' }]);+ expect(buildMessageSourceNote(messageSourceSenderFromMeta({ sourcePlugin })))+ .toBe('[消息来源] 本条由本机应用「TapTap」(app_id: com.taptap.pc) 发送,不是用户本人输入。');+ });it('pairs every name with its id', () => {expect(formatSourceRef('发布检查', 'session_id', 's-1')).toBe('「发布检查」(session_id: s-1)');});diff --git a/packages/maker-shared/src/messageSource.ts b/packages/maker-shared/src/messageSource.tsindex 3ad47e3e97..0c96d7efeb 100644--- a/packages/maker-shared/src/messageSource.ts+++ b/packages/maker-shared/src/messageSource.ts@@ -218,7 +218,7 @@ export function isCrossDeviceSourceSessionId(sessionId: string | undefined): booreturn split > 0 && split < sessionId.length - 2;}-export type MessageSourceIdKind = 'plugin' | 'mcpApp' | 'teammate' | 'session' | 'automation' | 'member';+export type MessageSourceIdKind = 'plugin' | 'mcpApp' | 'localApp' | 'teammate' | 'session' | 'automation' | 'member';export interface MessageSourceIdEntry {kind: MessageSourceIdKind;@@ -233,6 +233,7 @@ export interface MessageSourceIdEntry {export function messageSourceIdEntries(meta: unknown): MessageSourceIdEntry[] {const sender = messageSourceSenderFromMeta(meta);if (sender?.kind === 'plugin') {+ if (sender.pluginId.startsWith('local-app:')) return [{ kind: 'localApp', id: sender.pluginId.slice(10) }];return sender.pluginId.startsWith('mcp-app:')? [{ kind: 'mcpApp', id: sender.pluginId.slice(8) }]: [{ kind: 'plugin', id: sender.pluginId }];@@ -274,6 +275,7 @@ export function describeMessageSourceSender(sender: MessageSourceSender): stringreturn ref ? `由任务${ref} 发送` : '由其他任务发送';}case 'plugin':+ if (sender.pluginId.startsWith('local-app:')) return `由本机应用${formatSourceRef(sender.name, 'app_id', sender.pluginId.slice(10))} 发送`;if (sender.pluginId.startsWith('mcp-app:')) return `由 MCP App${formatSourceRef(sender.name, 'mcp_server_id', sender.pluginId.slice(8))} 发送`;return `由插件${formatSourceRef(sender.name, 'plugin_id', sender.pluginId)} 发送`;case 'shared-member':