Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

Merge origin/main into fix/local-agent-remote-providers

DavidShen9d2ea98544e2
diff --cc apps/desktop/src/main/local-agent/__tests__/runtime.integration.test.ts
index c7d22d54f0,a302ad3514..b68f717704
--- a/apps/desktop/src/main/local-agent/__tests__/runtime.integration.test.ts
+++ b/apps/desktop/src/main/local-agent/__tests__/runtime.integration.test.ts
@@@ -15,11 -16,12 +16,16 @@@ vi.mock('@cindy/maker-core', () => (
},
}));
import { openLocalAgentRuntime } from '../runtime.js';
+import { createLocalAgentGroupRouteResolver, type LocalAgentRouteResolver } from '../groupRoute.js';
+import { LOCAL_AGENT_ROUTE } from '../catalog.js';
+import { LOCAL_AGENT_CLIENT } from '@cindy/maker-core';
+import { createProviderGroupRemoteClient } from '../../provider-group/remoteClient.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 () => {
@@@ -50,11 -52,17 +56,17 @@@ function handle(id: string)
}),
};
}
- async function fixture(options: { route?: { deviceId: string; providerId: string }; resolveRoute?: LocalAgentRouteResolver; resume?: string; trackLoad?: Parameters<typeof openLocalAgentRuntime>[6] } = {}) {
-async function fixture(visible = false) {
++async function fixture(options: { visible?: boolean; route?: { deviceId: string; providerId: string }; resolveRoute?: LocalAgentRouteResolver; resume?: string; trackLoad?: Parameters<typeof openLocalAgentRuntime>[6] } = {}) {
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 maker = { startLocalAgentSession: vi.fn(async (..._args: any[]) => 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,
@@@ -77,19 -84,16 +89,20 @@@
},
access: 'none',
tools: [],
- ...(visible ? { visibleSession: { title: 'TapTap', clientId: 'com.taptap.pc' } } : {}),
+ resume: options.resume,
++ ...(options.visible ? { visibleSession: { title: 'TapTap', clientId: 'com.taptap.pc' } } : {}),
},
{
url: 'http://127.0.0.1:1/mcp/fixture',
token: 'invalid-fixture-token',
emit: (event) => events.push(event),
},
+ undefined,
+ options.resolveRoute,
+ options.trackLoad,
);
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) {
@@@ -100,131 -104,146 +113,280 @@@
const message = { parts: [{ type: 'text', text: 'hello' }], effort: 'high' };
describe('local client runtime lifecycle', () => {
+ it('registers resolved and resumed handles and reports a silent pending send before it settles', async () => {
+ const changed = vi.fn();
+ const trackLoad = vi.fn(() => changed);
+ const route = { providerId: 'member', groupAssigned: true,
+ groupBinding: { providerId: 'group', memberKey: 'device:self:member', groupDeviceId: 'owner' } };
+ const f = await fixture({ resolveRoute: async () => route, trackLoad });
+ expect(trackLoad).toHaveBeenCalledWith(expect.stringMatching(/^local-agent-/), route, f.first);
+ const pending = deferred();
+ f.first.send.mockImplementationOnce(async () => { await pending.promise; return { accepted: true }; });
+ await f.runtime.call('send', message);
+ expect(changed).toHaveBeenCalledTimes(1);
+ await f.runtime.call('interrupt', {});
+ expect(changed).toHaveBeenCalledTimes(2);
+ pending.resolve();
+ await Promise.resolve();
+ const reopened = await fixture({ resume: f.runtime.id, trackLoad });
+ expect(trackLoad).toHaveBeenLastCalledWith(expect.any(String), route, reopened.first);
+ await reopened.runtime.call('instructions', { instructions: 'new' });
+ await reopened.runtime.call('send', message);
+ expect(trackLoad).toHaveBeenCalledTimes(3);
+ });
+ // Review P1: the application bypassed ordinary task bootstrap and therefore
+ // never asked a same-account provider group to select its execution computer.
+ // Exercise the real runtime + group wire parser, including a native resume.
++ // Main's visible-task path must forward the same device route to createSession;
++ // otherwise enabling visibility silently executes a remote model locally.
+ it.each([
- ['device', 'b'.repeat(64), 'b'.repeat(64)],
- ['device', 'c'.repeat(64), undefined],
- ['local', null, 'a'.repeat(64)],
- ['share', 'share:fixture', 'share:fixture'],
- ] as const)('starts the selected %s group member and pins it across instruction rebuilds (%s)', async (kind, memberDevice, expectedDevice) => {
++ ['device', 'b'.repeat(64), 'b'.repeat(64), false],
++ ['device', 'c'.repeat(64), undefined, false],
++ ['local', null, 'a'.repeat(64), false],
++ ['share', 'share:fixture', 'share:fixture', false],
++ ['device', 'b'.repeat(64), 'b'.repeat(64), true],
++ ['device', 'c'.repeat(64), undefined, true],
++ ] as const)('starts the selected %s group member and pins it across instruction rebuilds (%s, %s, visible=%s)', async (kind, memberDevice, expectedDevice, visible) => {
+ const invoke = vi.fn(async () => ({ ok: true, result: {
+ kind: 'member', member: { kind, agentDeviceId: memberDevice, providerId: 'member-provider' }, label: 'B',
+ } }));
+ const resolver = createLocalAgentGroupRouteResolver({
+ remote: createProviderGroupRemoteClient(invoke), localDeviceId: () => 'c'.repeat(64), assertCurrent: () => {},
+ });
- const f = await fixture({ route: { deviceId: 'a'.repeat(64), providerId: 'group-provider' }, resolveRoute: resolver });
- const opts = f.maker.startLocalAgentSession.mock.calls[0][1];
++ const f = await fixture({ visible, route: { deviceId: 'a'.repeat(64), providerId: 'group-provider' }, resolveRoute: resolver });
++ const started = (fixture: typeof f, index: number) => visible
++ ? fixture.host.open.mock.calls[index][0]
++ : fixture.maker.startLocalAgentSession.mock.calls[index][1];
++ const opts = started(f, 0);
++ if (visible) expect(opts.agentDeviceId).toBe(expectedDevice);
+ // The group's local member always uses the group's provider id.
+ expect(opts.providerId).toBe(kind === 'local' ? 'group-provider' : 'member-provider');
+ expect(opts[LOCAL_AGENT_CLIENT]).toMatchObject({ groupAssigned: true, hostToolsOnly: true, mcpName: 'client' });
+ expect(opts[LOCAL_AGENT_CLIENT].agentDeviceId).toBe(expectedDevice);
+ expect(opts[LOCAL_AGENT_CLIENT].storageDirectory).toBe(path.join(f.directory, 'clients', 'grant-a', 'pi'));
+ expect(invoke).toHaveBeenCalledWith('a'.repeat(64), 'provider-group:remote', [expect.objectContaining({
+ action: 'pick', providerId: 'group-provider', agentKind: 'pi', model: 'model', exclude: [],
+ })]);
+ await f.runtime.call('instructions', { instructions: 'updated' });
+ await f.runtime.call('send', message);
+ expect(invoke).toHaveBeenCalledTimes(1);
- expect(f.maker.startLocalAgentSession.mock.calls[1][1]).toMatchObject({ providerId: opts.providerId, resumeSessionId: 'first' });
- expect(f.maker.startLocalAgentSession.mock.calls[1][1][LOCAL_AGENT_CLIENT]).toEqual(opts[LOCAL_AGENT_CLIENT]);
++ expect(started(f, 1)).toMatchObject({ providerId: opts.providerId, resumeSessionId: 'first' });
++ expect(started(f, 1)[LOCAL_AGENT_CLIENT]).toEqual(opts[LOCAL_AGENT_CLIENT]);
+ // Reopening via the server's persisted opaque binding must also stay on B,
+ // even after group strategy/load changes or the member leaves the group.
- const reopened = await fixture({ route: { deviceId: 'a'.repeat(64), providerId: 'group-provider' },
++ const reopened = await fixture({ visible, route: { deviceId: 'a'.repeat(64), providerId: 'group-provider' },
+ resolveRoute: resolver, resume: f.runtime.id });
+ expect(invoke).toHaveBeenCalledTimes(1);
- const restored = reopened.maker.startLocalAgentSession.mock.calls[0][1];
++ const restored = started(reopened, 0);
++ if (visible) expect(restored.agentDeviceId).toBe(expectedDevice);
+ expect(restored).toMatchObject({ providerId: opts.providerId, resumeSessionId: 'first' });
+ expect(restored[LOCAL_AGENT_CLIENT].agentDeviceId).toBe(expectedDevice);
+ expect(restored[LOCAL_AGENT_CLIENT].groupAssigned).toBe(true);
+ });
+
+ it.each(['none', 'legacy', 'unavailable', 'denied', 'owner-changed'] as const)('handles group selection %s without silently switching suppliers', async outcome => {
+ let current = true;
+ const invoke = vi.fn(async () => {
+ if (outcome === 'owner-changed') current = false;
+ if (outcome === 'legacy' || outcome === 'denied') return { ok: false, error: {
+ code: outcome === 'legacy' ? 'CHANNEL_NOT_ALLOWED' : 'ACCESS_REVOKED', message: 'private fixture details',
+ } };
+ return { ok: true, result: { kind: outcome === 'unavailable' ? 'unavailable' : 'none' } };
+ });
+ const resolveRoute = createLocalAgentGroupRouteResolver({
+ remote: createProviderGroupRemoteClient(invoke), localDeviceId: () => 'c'.repeat(64),
+ assertCurrent: () => { if (!current) throw new Error('owner changed'); },
+ });
+ const opening = fixture({ route: { deviceId: 'a'.repeat(64), providerId: 'group-provider' }, resolveRoute });
+ if (outcome === 'owner-changed') await expect(opening).rejects.toThrow('owner changed');
+ else if (outcome === 'unavailable' || outcome === 'denied') {
+ await expect(opening).rejects.toMatchObject({ code: 'REMOTE_AGENT_UNAVAILABLE',
+ message: '远程供应商暂不可用,请在 Cindy 中检查连接或更新远端版本。' });
+ } else {
+ const f = await opening;
+ const opts = f.maker.startLocalAgentSession.mock.calls[0][1];
+ expect(opts.providerId).toBe('group-provider');
+ expect(opts[LOCAL_AGENT_CLIENT].agentDeviceId).toBe('a'.repeat(64));
+ expect(opts[LOCAL_AGENT_CLIENT].groupAssigned).toBeUndefined();
+ }
+ });
+
+ it('leaves direct shared suppliers to the owner instead of using same-account group management', async () => {
+ const pick = vi.fn();
+ const f = await fixture({ route: { deviceId: 'share:fixture', providerId: 'shared-provider' },
+ resolveRoute: createLocalAgentGroupRouteResolver({ remote: { pick }, localDeviceId: () => null, assertCurrent: () => {} }) });
+ expect(pick).not.toHaveBeenCalled();
+ expect(f.maker.startLocalAgentSession.mock.calls[0][1][LOCAL_AGENT_CLIENT].agentDeviceId).toBe('share:fixture');
+ });
+
+ it('resumes pre-group bindings on their original source and rejects corrupt new bindings', async () => {
+ const resolveRoute = vi.fn();
+ const route = { deviceId: 'a'.repeat(64), providerId: 'group-provider' };
+ const f = await fixture({ route, resolveRoute, resume: 'old-native-thread' });
+ expect(resolveRoute).not.toHaveBeenCalled();
+ const opts = f.maker.startLocalAgentSession.mock.calls[0][1];
+ expect(opts.resumeSessionId).toBe('old-native-thread');
+ expect(opts[LOCAL_AGENT_CLIENT].agentDeviceId).toBe(route.deviceId);
+ await expect(fixture({ route, resolveRoute, resume: 'local-agent-group-v1:invalid' })).rejects.toMatchObject({ code: 'RESUME_UNAVAILABLE' });
+ });
+
+ // Remote application failures must remain actionable without leaking peer diagnostics.
+ it('preserves the old-peer error code when rebuilding an application session', async () => {
+ const f = await fixture();
+ f.maker.startLocalAgentSession.mockRejectedValueOnce(new Error('[REMOTE_AGENT_PEER_TOO_OLD] private peer details'));
+ await f.runtime.call('instructions', { instructions: 'updated' });
+ await expect(f.runtime.call('send', message)).rejects.toMatchObject({
+ code: 'REMOTE_AGENT_PEER_TOO_OLD',
+ message: '远程供应商暂不可用,请在 Cindy 中检查连接或更新远端版本。',
+ });
+ expect(f.first.send).not.toHaveBeenCalled();
+ });
+ it('does not auto-approve a shared supplier credential confirmation', async () => {
+ const f = await fixture();
+ const listener = f.first.setInteractionListener.mock.calls[0][0];
+ const answer = await listener({kind:'permission',toolName:'read',metadata:{hostOwnedConfirmation:'shared_provider_credential'}});
+ expect(answer).toEqual({kind:'permission',behavior:'deny',reason:'host_interaction_unavailable'});
+ });
+ // PR #7684: send persistence coverage did not exercise same-turn input.
+ // A failed image/database write must reject steer before provider delivery.
+ it('persists visible steer before delivery and never delivers a failed write', async () => {
- const f = await fixture(true);
++ const f = await fixture({ visible: true });
+ await f.runtime.call('send', { parts: message.parts });
+ const delivered = vi.fn();
+ f.first.steer.mockImplementation(async (...args: any[]) => {
+ await args[1]?.beforeProviderStart?.();
+ delivered();
+ });
+ f.host.persistInput.mockRejectedValueOnce(new Error('disk unavailable'));
+ await expect(f.runtime.call('steer', { parts: [image] })).rejects.toThrow('disk unavailable');
+ expect(delivered).not.toHaveBeenCalled();
+ expect(await inputFiles(f.directory)).toEqual([]);
+ f.host.persistInput.mockImplementationOnce(async () => {
+ expect(delivered).not.toHaveBeenCalled();
+ });
+ await f.runtime.call('steer', { parts: message.parts });
+ expect(delivered).toHaveBeenCalledOnce();
+ });
+
+ // #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 f = await fixture({ visible: 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 f = await fixture({ visible: 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 f = await fixture({ visible: 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);
++ const f = await fixture({ visible: 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);
++ const f = await fixture({ visible: 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);
++ const f = await fixture({ visible: 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' }] });
diff --cc apps/desktop/src/main/local-agent/runtime.ts
index 5ebcacc2d5,721d87ea7c..3e83df8008
--- a/apps/desktop/src/main/local-agent/runtime.ts
+++ b/apps/desktop/src/main/local-agent/runtime.ts
@@@ -13,9 -13,12 +13,15 @@@ import
type UserMessage,
} from '@cindy/maker-core';
import { LocalAgentError, type LocalAgentOpen, type LocalAgentRuntime } from './server.js';
+import { LOCAL_AGENT_ROUTE } from './catalog.js';
+import { localAgentResumeId, readLocalAgentResumeId, type LocalAgentExecutionRoute, type LocalAgentRouteResolver } from './groupRoute.js';
+import type { LocalAgentLoadTracker } from './load.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>) : {};
@@@ -215,9 -213,30 +221,31 @@@ export async function openLocalAgentRun
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 notifyLoad = () => {};
let closed = false,
busy = false,
preparing = false,
@@@ -236,31 -256,35 +265,58 @@@
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);
+ // Pin the actual execution location across instruction rebuilds/native resume.
+ // A thread id must never be resumed on a newly selected group member.
+ let selectedRoute: Promise<LocalAgentExecutionRoute> | undefined;
+ let executionRoute: LocalAgentExecutionRoute;
+ // Only stable public remote codes cross the API, never peer diagnostics.
+ const remoteFailure = (error: unknown): never => {
+ const code = error instanceof Error ? /^\[(REMOTE_AGENT_PEER_TOO_OLD|REMOTE_AGENT_SHARE_PAUSED|REMOTE_AGENT_SHARE_REMOVED|REMOTE_AGENT_PROVIDER_NOT_ALLOWED|REMOTE_AGENT_UNAVAILABLE)\]/.exec(error.message)?.[1] : undefined;
+ if (code) throw new LocalAgentError(code, localize(code, '远程供应商暂不可用,请在 Cindy 中检查连接或更新远端版本。'));
+ throw error;
+ };
- 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 initialRoute: LocalAgentExecutionRoute = {
+ providerId: input.model[LOCAL_AGENT_ROUTE]?.providerId ?? input.model.provider,
+ agentDeviceId: input.model[LOCAL_AGENT_ROUTE]?.deviceId,
+ };
+ const route = await (selectedRoute ??= resumeBinding.native
+ // A pre-group binding ran directly on its original source. Never assign
+ // a new location to an existing native thread, including legacy bindings.
+ ? Promise.resolve(resumeBinding.route ?? initialRoute)
+ : resolveRoute
+ ? resolveRoute({ ...initialRoute, sessionId, agentKind: input.model.engine, model: input.model.model })
+ : Promise.resolve(initialRoute)).catch(remoteFailure);
+ assertCurrent(expected);
+ executionRoute = route;
const opts: StartSessionOptions = {
sessionId,
workingDir: input.cwd,
@@@ -288,7 -310,16 +344,17 @@@
},
};
resumed = Boolean(resume);
- const next = await maker.startLocalAgentSession(input.model.engine, opts).catch(remoteFailure);
+ const next = visibleHost
+ ? await visibleHost.open({
+ ...opts,
++ agentDeviceId: route.agentDeviceId,
+ id: sessionId,
+ agentKind: input.model.engine,
+ title: input.visibleSession!.title,
+ workspaceKind: 'dialogue',
- })
- : await maker.startLocalAgentSession(input.model.engine, opts);
++ }).catch(remoteFailure)
++ : await maker.startLocalAgentSession(input.model.engine, opts).catch(remoteFailure);
+ handle = next;
try {
assertCurrent(expected);
} catch (error) {
@@@ -302,14 -333,8 +368,13 @@@
'Cindy 原会话已不存在,请在调用应用中开始新的任务。未重放旧消息。',
);
}
- handle = next;
+ notifyLoad = trackLoad?.(sessionId, route, next) ?? (() => {});
next.setInteractionListener(async (request) => {
if (request.kind === 'permission') {
+ if (request.metadata?.hostOwnedConfirmation === 'shared_provider_credential') {
+ projection.failAtEnd(localize('INTERACTION_UNAVAILABLE', '分享供应商的凭据访问需要本人确认,当前应用无法接收。'));
+ return { kind: 'permission', behavior: 'deny', reason: 'host_interaction_unavailable' };
+ }
const hostTool = input.tools.some((tool) =>
[`mcp__${input.mcpName}__${tool.name}`, `mcp:${input.mcpName}:${tool.name}`].includes(
request.toolName,
@@@ -354,9 -379,13 +419,13 @@@
});
return next;
};
+ const start = (resume?: string, expected = epoch) => locked(() => startUnlocked(resume, expected));
+ if (visibleHost) unregisterVisibleRuntime = registerLocalAgentVisibleRuntime(sessionId, close);
try {
- handle = await start(input.resume);
+ handle = await start(resumeBinding.native);
} catch (error) {
+ if (visibleHost && handle) await close();
+ else unregisterVisibleRuntime?.();
await fs.rm(temporary, { recursive: true, force: true });
throw error;
}
@@@ -426,8 -455,9 +495,9 @@@
}
};
return {
+ ...(visibleHost ? { visibleSessionId: sessionId } : {}),
get id() {
- return handle.sdkSessionId;
+ return localAgentResumeId(handle.sdkSessionId, executionRoute);
},
get resumed() {
return resumed;
@@@ -504,13 -542,21 +583,25 @@@
releaseInputs();
turnInputs.push(sending);
void (async () => {
- const result = await handle.send(wireMessage(sending), visibleHost ? {
- onAccepted: (signal) =>
- visibleHost.persistInput(
- sessionId,
- sending,
- randomUUID(),
- () => {
- assertCurrent(current);
- signal?.throwIfAborted();
- },
- source!,
- ),
- } : undefined);
- if (!result.accepted) await discard(sending);
- assertSendDispatched(result, 'local-agent/send');
+ try {
- const result = await handle.send(sending);
++ const result = await handle.send(wireMessage(sending), visibleHost ? {
++ onAccepted: (signal) =>
++ visibleHost.persistInput(
++ sessionId,
++ sending,
++ randomUUID(),
++ () => {
++ assertCurrent(current);
++ signal?.throwIfAborted();
++ },
++ source!,
++ ),
++ } : undefined);
+ if (!result.accepted) await discard(sending);
+ assertSendDispatched(result, 'local-agent/send');
+ } finally {
+ notifyLoad();
+ }
})().catch(() => {
if (closed || turn !== generation) return;
if (epoch === current) {
diff --cc apps/desktop/src/main/local-agent/service.ts
index db00d45e96,5133604a0b..fe2dfea922
--- a/apps/desktop/src/main/local-agent/service.ts
+++ b/apps/desktop/src/main/local-agent/service.ts
@@@ -135,40 -133,26 +135,43 @@@ export function installLocalAgentHost(m
allowSideEffects: false,
}).listProviders({
allowSideEffects: false,
- });
- return localAgentModels(providers, maker.listAvailableAgents());
+ }), remoteLocalAgentModels(() => scopeNow() === scope)]);
+ if (scopeNow() !== scope) throw new LocalAgentError('UNAUTHORIZED', 'Cindy 当前账号已更改,请重新连接。');
+ return [...localAgentModels(providers, maker.listAvailableAgents()), ...remoteModels]
+ .map((model, index) => ({ ...model, isDefault: index === 0 }));
},
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) =>
- openLocalAgentRuntime(maker, directory, input, bridge, localAgentMessage),
+ open: async (input, bridge) => {
+ // Load group orchestration only when an application actually opens a
+ // session; the HTTP discovery/startup path must stay lightweight.
+ const [{ getProviderGroupRemoteClient, getProviderGroupApplicationLoad }, { getSelfDeviceId }] = await Promise.all([
+ import('../provider-group/runtime.js'), import('../device-link/index.js'),
+ ]);
+ const assertCurrent = () => {
+ if (scopeNow() !== scope) throw new LocalAgentError('UNAUTHORIZED', 'Cindy 当前账号已更改,请重新连接。');
+ };
+ assertCurrent();
+ const load = getProviderGroupApplicationLoad();
+ return openLocalAgentRuntime(maker, directory, input, bridge, localAgentMessage, createLocalAgentGroupRouteResolver({
+ remote: getProviderGroupRemoteClient(),
+ localDeviceId: getSelfDeviceId,
+ assertCurrent,
+ }), load.track);
+ },
message: localAgentMessage,
warn: (code) => log.warn('local agent request failed', { code }),
changed: () => {
diff --cc apps/desktop/src/main/maker-ipc/register.ts
index 85d04e5f38,4999bd0808..b08e97688e
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@@ -11410,7 -11541,7 +11543,8 @@@ export function registerMakerIpc(maker
});
// 这台电脑上每个供应商正在运行一轮的任务数:组里「本机」这台显示它,同账号电脑读目录时也带上(§5)。
setProviderGroupLocalLoad(() => countProviderRunningTurns({
-- listTurnRunningSessions: () => maker.listActiveSessions().filter((s) => s.isTurnRunning()).map((s) => s.id),
++ // Visible app tasks also live in Maker; the application registry counts them once.
++ listTurnRunningSessions: () => maker.listActiveSessions().filter((s) => s.isTurnRunning() && !hasLocalAgentVisibleRuntime(s.id)).map((s) => s.id),
readSessionRoutes: readProviderLocalLoadRoutes,
resolveImplicitProvider: resolveProviderGroupImplicitProvider,
hostRunningProviders: remoteAgentHostRunningProviders,
diff --cc docs/dev-rules/protocol-compatibility.md
index 6e9bd81609,c375707316..c2e3bdab3d
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@@ -1,19 -1,15 +1,29 @@@
# 跨端协议兼容
+## 本机应用使用远程供应商
+
+`remote-agent` caps 增量增加可选 `localApplication: true`。协商成功后,open 的
+`options.localApplication` 携带 MCP 名、`hostToolsOnly` 和授权存储键的 SHA-256 摘要;
+不携带调用方的 MCP URL、令牌或存储路径。接收方严格验证字段,并从自己的受控存储根
+按控制端/中转身份派生应用目录,再构造到反向隧道的工具入口。
+
+控制端及供应商组中转均要求实际执行端声明该能力;旧端不支持时拒绝启动,不丢弃隔离
+声明继续执行。新端收到无该字段的旧请求保持原行为。应用的客户端工具经既有 MCP 通道
+返回原调用方;`client-only` 禁止原生文件/命令反向请求。无需服务端或 Mobile 变更,
+不扩大 IPC allowlist、设备权限或分享范围,不新增重放策略;一次来源失败不重启其他连接。
+回归见 `local-agent/__tests__/remoteCatalog.test.ts`、`remote-agent/__tests__/roundtrip.test.ts`
+与 `groupRelay.test.ts`,公开应用合同见 [本机 Agent API](../local-agent-api.md)。
+
+ ## 本机应用的可见任务(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;非真人目标返回既有错误体中的