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): 增加按需开发连接码
DavidShend6c33c0aa6c6
diff --git a/apps/desktop/scripts/fixtures/local-agent/local-agent-fixture.tsx b/apps/desktop/scripts/fixtures/local-agent/local-agent-fixture.tsxindex c6bbf7b3d2..d732a170e0 100644--- a/apps/desktop/scripts/fixtures/local-agent/local-agent-fixture.tsx+++ b/apps/desktop/scripts/fixtures/local-agent/local-agent-fixture.tsx@@ -1,9 +1,14 @@import { mountPage, subscription } from '../../ui-page/harness';import { LocalAgentSection } from '../../../src/renderer/components/settings/LocalAgentSection';+import { ToastContainer } from '../../../src/renderer/components/ui/toast/ToastContainer';mountPage({host: ctx => ({localAgent: {+ developerConnection: async () => {+ if (ctx.data.copyExpired && (window as any).__copyRequested) return { state: 'stopped' };+ return ctx.data.developer ?? null;+ },onConnectionsChanged: subscription('localAgentChanged'),connections: async () => {if (ctx.data.loadFailed) throw new Error('fixture connection read failed');@@ -16,5 +21,5 @@ mountPage({},},}),- render: () => <div className="mx-auto w-full max-w-3xl p-5"><LocalAgentSection /></div>,+ render: () => <><div className="mx-auto w-full max-w-3xl p-5"><LocalAgentSection /></div><ToastContainer /></>,});diff --git a/apps/desktop/scripts/fixtures/local-agent/ui-page.mjs b/apps/desktop/scripts/fixtures/local-agent/ui-page.mjsindex d121701fb6..84617cb390 100644--- a/apps/desktop/scripts/fixtures/local-agent/ui-page.mjs+++ b/apps/desktop/scripts/fixtures/local-agent/ui-page.mjs@@ -8,6 +8,14 @@ export default {real: 'LocalAgentSection, standard settings rows and themed Button',notCovered: 'Native consent, IPC authentication and actual grant revocation; these require isolated Desktop and protocol integration checks.',cases: {+ 'dev-ready': { about: 'Copy the current development endpoint', data: { developer: { state: 'ready', code: 'cindy-local:v1:12345:' + 'n'.repeat(43) } } },+ 'copy-failed': { about: 'Clipboard failure remains visible without claiming a copy', data: { copyFailed: true, developer: { state: 'ready', code: 'cindy-local:v1:12345:' + 'n'.repeat(43) } } },+ 'copy-expired': { about: 'Click refresh prevents copying a retired endpoint', data: { copyExpired: true, developer: { state: 'ready', code: 'cindy-local:v1:12345:' + 'n'.repeat(43) } } },+ 'dev-starting': { about: 'Starting API cannot supply a code', data: { developer: { state: 'starting' } } },+ 'dev-owner': { about: 'Owner unavailable cannot supply a code', data: { developer: { state: 'owner-unavailable' } } },+ 'dev-in-use': { about: 'Shared profile lease is owned by another process', viewport: { width: 390, height: 844 }, data: { developer: { state: 'host-in-use' } } },+ '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 } },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],@@ -20,6 +28,33 @@ export default {async check(page, ui) {const heading = page.getByRole('heading', { name: await ui.t('localAgent.title') });await heading.waitFor();+ const copy = page.getByRole('button', { name: await ui.t('localAgent.copyCode'), exact: true });+ if (ui.data.developer) {+ await copy.waitFor();+ if (ui.data.developer.state !== 'ready') {+ if (await copy.isEnabled()) throw new Error('Unavailable endpoint is copyable');+ await page.getByText(await ui.t(`localAgent.developerState.${ui.data.developer.state}`), { exact: true }).waitFor();+ } else {+ await page.evaluate((fail) => {+ window.__copyRequested = true;+ Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText: async (value) => {+ if (fail) throw new Error('clipboard denied');+ window.__copiedCode = value;+ } } });+ }, Boolean(ui.data.copyFailed));+ await copy.click();+ if (ui.data.copyExpired) {+ await page.getByText(await ui.t('localAgent.developerState.stopped'), { exact: true }).waitFor();+ if (await page.evaluate(() => Boolean(window.__copiedCode))) throw new Error('Copied expired endpoint');+ } else if (ui.data.copyFailed) {+ await page.getByText(await ui.t('localAgent.codeCopyFailed'), { exact: true }).waitFor();+ if (await page.evaluate(() => Boolean(window.__copiedCode))) throw new Error('Claimed failed copy');+ } else {+ await page.getByText(await ui.t('localAgent.codeCopied'), { exact: true }).waitFor();+ if (await page.evaluate(() => window.__copiedCode) !== ui.data.developer.code) throw new Error('Wrong connection code');+ }+ }+ } else if (await copy.count()) throw new Error('Installed build exposes development entry');const list = ui.data.connections ?? [];if (!list.length) {await page.getByText(await ui.t(ui.data.loadFailed ? 'localAgent.failed' : 'localAgent.empty'), { exact: true }).waitFor();diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 2c3a9292d0..a7c96b9b2f 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -417,7 +417,7 @@ import {isCindyPersonalRuntime,} from './cindy-make/versionRuntimeIdentity.js';import { createStorageIpcHandlers } from './cindy-media/storageIpc';-import { disposeLocalAgentHost, localAgentConnections, revokeLocalAgentConnections } from './local-agent/service.js';+import { disposeLocalAgentHost, localAgentConnections, localAgentDeveloperConnection, revokeLocalAgentConnections } from './local-agent/service.js';import { clearLocalEntries } from './device-link/remoteMediaCacheStore';import {collectDatabaseSizeWarningStatus,@@ -8558,6 +8558,10 @@ const registerIpcHandlers = () => {assertTrustedAppRendererEvent(event);return localAgentConnections(() => assertTrustedAppRendererEvent(event));});+ ipcMain.handle('local-agent:developer-connection', (event) => {+ assertTrustedAppRendererEvent(event);+ return localAgentDeveloperConnection(() => assertTrustedAppRendererEvent(event));+ });ipcMain.handle('local-agent:revoke', (event, connectionId?: unknown) => {assertTrustedAppRendererEvent(event);return revokeLocalAgentConnections(connectionId, () => assertTrustedAppRendererEvent(event));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 7646914001..117ccdb2bd 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@@ -2,7 +2,7 @@* 测试价值:createLocalAgentServer 的真实 loopback 授权、MCP、恢复与撤销协议。* 依据:本机接入必须独立授权、不重放副作用、不跨授权恢复;既有 device-link 测试不经过此接口。* 最小失败输入:无凭据 models、同 id 不同 payload、另一 grant 的 resume、超过批次大小的单事件。- * tier: integration(真实临时文件与 socket);单文件实测 136ms。+ * tier: integration(真实临时文件与 socket);单文件实测 1.43s(含 750ms 握手超时边界)。*/import { afterEach, describe, expect, it, vi } from 'vitest';import fs from 'node:fs/promises';@@ -11,10 +11,14 @@ import path from 'node:path';import { execFile } from 'node:child_process';import { promisify } from 'node:util';import { fileURLToPath } from 'node:url';-import { request } from 'node:http';+import { createServer, request } from 'node:http';import { once } from 'node:events';import { createLocalAgentServer, type LocalAgentServerDeps } from '../server.js';import type { LocalAgentModel } from '../catalog.js';+import { formatLocalAgentConnectionCode } from '../../../shared/localAgent.js';+const { LocalAgentClient, parseConnectionCode } = await import(+ new URL('../../../../../../scripts/examples/local-agent-client.mjs', import.meta.url).href+);const model: LocalAgentModel = {id: 'source-model-engine',@@ -110,6 +114,146 @@ async function fixture(overrides: Partial<LocalAgentServerDeps> = {}) {}describe('local application authorization and lifecycle', () => {+ it('bounds untrusted connection-code handshakes without following redirects or hanging on a reused port', async () => {+ let mode = 'redirect';+ let requests = 0;+ const endpoint = createServer((_request, response) => {+ requests++;+ if (mode === 'redirect') {+ response.writeHead(302, { Location: '/other' }).end();+ } else if (mode === 'oversize') {+ response.end('x'.repeat(32 * 1024 + 1));+ } else if (mode === 'malformed') {+ response.end('{');+ }+ // A stalled non-Cindy endpoint must hit the client's handshake timeout.+ });+ cleanups.push(async () => {+ endpoint.closeAllConnections();+ await new Promise<void>((resolve) => endpoint.close(() => resolve()));+ });+ endpoint.listen(0, '127.0.0.1');+ await once(endpoint, 'listening');+ const address = endpoint.address();+ if (!address || typeof address === 'string') throw new Error('Missing loopback port');+ const client = LocalAgentClient.fromConnectionCode(+ formatLocalAgentConnectionCode({ port: address.port, instance: 'n'.repeat(43) }),+ { id: 'org.example.handshake', name: 'Handshake test' },+ );+ for (const [next, code] of [+ ['redirect', 'CONNECTION_UNAVAILABLE'],+ ['oversize', 'TOO_LARGE'],+ ['malformed', 'CONNECTION_UNAVAILABLE'],+ ['stall', 'CONNECTION_UNAVAILABLE'],+ ]) {+ mode = next;+ await expect(client.connect()).rejects.toMatchObject({ code });+ }+ expect(requests).toBe(4);+ });+ // Connection codes replace public registration: test independent parsing against a real endpoint.+ it('accepts only bounded versioned loopback codes without creating a mapping or scanning profiles', async () => {+ const f = await fixture({ instanceInfo: { kind: 'development', region: 'cn' } });+ const code = formatLocalAgentConnectionCode(f.server().rpc);+ expect(parseConnectionCode(` \n${code}\t`)).toEqual(f.server().rpc);+ for (const port of [1, 65535])+ expect(+ parseConnectionCode(formatLocalAgentConnectionCode({ ...f.server().rpc, port })).port,+ ).toBe(port);+ for (const bad of [+ '',+ code.repeat(5),+ code.replace(':v1:', ':v01:'),+ code.replace(/:\d+:/, ':0:'),+ code.replace(/:\d+:/, ':65536:'),+ code.replace(/:\d+:/, ':0123:'),+ code + '?token=x',+ 'http://localhost/rpc',+ code.replace(':v1:', ':v1:\n'),+ code.slice(0, -1),+ ])+ expect(() => parseConnectionCode(bad)).toThrow();+ expect(() => parseConnectionCode(code.replace(':v1:', ':v2:'))).toThrow('Unsupported');+ expect((await f.rpc('capabilities')).result.instanceInfo).toEqual({+ kind: 'development',+ region: 'cn',+ });+ expect((await fs.readdir(f.directory)).sort()).toEqual(['discovery.json']);+ });+ it('verifies code identity without a token, keeps separate target grants, and rejects expired codes', async () => {+ const approveA = vi.fn(async () => true),+ approveB = vi.fn(async () => true);+ const a = await fixture({+ approve: approveA,+ instanceInfo: { kind: 'development', region: 'cn' },+ });+ const b = await fixture({+ approve: approveB,+ instanceInfo: { kind: 'development', region: 'global' },+ });+ const identity = { id: 'org.example.code', name: 'Code client' };+ const ca = LocalAgentClient.fromConnectionCode(+ formatLocalAgentConnectionCode(a.server().rpc),+ identity,+ );+ const cb = LocalAgentClient.fromConnectionCode(+ formatLocalAgentConnectionCode(b.server().rpc),+ identity,+ );+ const spy = vi.spyOn(globalThis, 'fetch');+ try {+ await ca.request('capabilities');+ expect(approveA).not.toHaveBeenCalled();+ await expect(ca.request('models')).rejects.toMatchObject({ code: 'UNAUTHORIZED' });+ await ca.connect();+ await cb.connect();+ await ca.request('models');+ const auth = spy.mock.calls.find(+ ([url, options]) =>+ String(url) === `${a.server().base}/rpc` && (options?.headers as any)?.Authorization,+ )?.[1]?.headers as any;+ expect((await b.rpc('models', {}, auth.Authorization.slice(7))).error.code).toBe(+ 'UNAUTHORIZED',+ );+ await ca.request('capabilities');+ for (const [, options] of spy.mock.calls)+ if (JSON.parse(String(options?.body)).method === 'capabilities')+ expect((options?.headers as any)?.Authorization).toBeUndefined();+ await ca.disconnect();+ expect((await cb.request('models')).models).toHaveLength(1);+ await cb.disconnect();+ const old = a.server().rpc;+ await a.restart();+ const reused = LocalAgentClient.fromConnectionCode(+ formatLocalAgentConnectionCode({ ...old, port: a.server().rpc.port }),+ identity,+ );+ await expect(reused.connect()).rejects.toMatchObject({ code: 'INSTANCE_CHANGED' });+ expect(approveA).toHaveBeenCalledTimes(1);+ } finally {+ spy.mockRestore();+ }+ });+ it('does not treat an installed or unknown old endpoint as development, preserving explicit legacy access', async () => {+ for (const instanceInfo of [undefined, { kind: 'installed' as const, region: 'cn' as const }]) {+ const approve = vi.fn(async () => true);+ const f = await fixture({ instanceInfo, approve });+ const client = LocalAgentClient.fromConnectionCode(+ formatLocalAgentConnectionCode(f.server().rpc),+ { id: 'test', name: 'Test' },+ );+ await expect(client.connect()).rejects.toMatchObject({+ code: instanceInfo ? 'INSTANCE_METADATA_MISMATCH' : 'INSTANCE_METADATA_UNSUPPORTED',+ });+ expect(approve).not.toHaveBeenCalled();+ const legacy = await LocalAgentClient.discover(f.server().discoveryFile, {+ id: 'legacy',+ name: 'Legacy',+ });+ await legacy.connect();+ await legacy.disconnect();+ }+ });// Revoking the token is immediate; unconfirmed native shutdown must be reported// and retained for cleanup, rather than claiming that an executor has stopped.it('reports an unconfirmed close and retries cleanup without restoring revoked authority', async () => {@@ -223,8 +367,9 @@ describe('local application authorization and lifecycle', () => {expect(await response).toBe(403);});- it('runs the standalone example in two unrelated Node processes using only discovery and public RPC', async () => {+ it('runs code and legacy discovery clients in unrelated Node processes with isolated tools', async () => {const f = await fixture({+ instanceInfo: { kind: 'development', region: 'cn' },open: async (input, bridge) => {let completion = Promise.resolve();return {@@ -270,8 +415,9 @@ describe('local application authorization and lifecycle', () => {process.execPath,[example,- '--discovery',- f.server().discoveryFile,+ ...(app === 'notes'+ ? ['--connection-code', formatLocalAgentConnectionCode(f.server().rpc)]+ : ['--discovery', f.server().discoveryFile]),'--cwd',f.directory,'--client-id',diff --git a/apps/desktop/src/main/local-agent/__tests__/service.test.ts b/apps/desktop/src/main/local-agent/__tests__/service.test.tsindex 277bcba6f5..6186d3ca3f 100644--- a/apps/desktop/src/main/local-agent/__tests__/service.test.ts+++ b/apps/desktop/src/main/local-agent/__tests__/service.test.ts@@ -18,9 +18,17 @@ const mock = vi.hoisted(() => ({send: vi.fn(),trusted: true,lockHeld: true,+ packaged: false,+ personal: false,+ region: 'cn',+ nonce: 0,+ startupGate: undefined as Promise<void> | undefined,}));vi.mock('electron', () => ({app: {+ get isPackaged() {+ return mock.packaged;+ },getVersion: () => 'test',getPath: () => 'unused',getPreferredSystemLanguages: () => ['zh-CN'],@@ -32,6 +40,14 @@ vi.mock('electron', () => ({},dialog: { showMessageBox: mock.dialog },}));+vi.mock('../../../shared/brandRegion.js', () => ({+ get CURRENT_CINDY_REGION() {+ return mock.region;+ },+}));+vi.mock('../../cindy-make/versionRuntimeIdentity.js', () => ({+ isCindyPersonalRuntime: () => mock.personal,+}));vi.mock('node:fs/promises', () => ({ default: { mkdir: async () => {} } }));vi.mock('../../device-link/crossProcessLock.js', () => ({withCrossProcessLock: async (@@ -55,11 +71,20 @@ vi.mock('../../maker-host/createDesktopProviderService.js', () => ({vi.mock('../../logger.js', () => ({ createLogger: () => ({ warn: vi.fn() }) }));vi.mock('../runtime.js', () => ({ openLocalAgentRuntime: vi.fn() }));vi.mock('../server.js', () => ({- LocalAgentError: class extends Error {},+ LocalAgentError: class extends Error {+ constructor(+ public code: string,+ message: string,+ ) {+ super(message);+ }+ },createLocalAgentServer: async (deps: any) => {mock.deps = deps;+ await mock.startupGate;if (mock.startupError) throw mock.startupError;return {+ rpc: { protocol: 1, port: 12345, instance: 'n'.repeat(42) + (++mock.nonce % 10) },connections: () => [{ id: 'grant-a', name: 'Notes', clientId: 'notes' },{ id: 'grant-b', name: 'Board', clientId: 'board' },@@ -74,6 +99,7 @@ import {disposeLocalAgentHost,installLocalAgentHost,localAgentConnections,+ localAgentDeveloperConnection,revokeLocalAgentConnections,} from '../service.js';@@ -83,10 +109,16 @@ beforeEach(async () => {mock.generation = 1;mock.trusted = true;mock.lockHeld = true;+ mock.packaged = false;+ mock.personal = false;+ mock.region = 'cn';+ mock.nonce = 0;+ mock.startupGate = undefined;mock.startupError = undefined;mock.dialog.mockResolvedValue({ response: 1 });installLocalAgentHost({} as any);await localAgentConnections();+ mock.send.mockClear();});afterEach(async () => {await disposeLocalAgentHost();@@ -180,9 +212,11 @@ describe('generic local app native authorization', () => {installLocalAgentHost({} as any);await expect(localAgentConnections()).rejects.toThrow('[PRECONDITION_FAILED]');expect(mock.deps).toBeUndefined();+ expect(await localAgentDeveloperConnection()).toEqual({ state: 'host-in-use' });});it('waits for the previous endpoint to close before replacing Maker on the same profile', async () => {const previous = mock.deps;+ const oldCode = await localAgentDeveloperConnection();let finish!: () => void;mock.close.mockImplementationOnce(() =>@@ -191,7 +225,9 @@ describe('generic local app native authorization', () => {}),);const stopping = disposeLocalAgentHost();+ expect(await localAgentDeveloperConnection()).toEqual({ state: 'stopped' });installLocalAgentHost({} as any);+ expect(await localAgentDeveloperConnection()).toEqual({ state: 'starting' });const connections = localAgentConnections();await vi.waitFor(() => expect(finish).toBeTypeOf('function'));expect(mock.deps).toBe(previous);@@ -199,5 +235,61 @@ describe('generic local app native authorization', () => {await stopping;await connections;expect(mock.deps).not.toBe(previous);+ expect(await localAgentDeveloperConnection()).not.toEqual(oldCode);+ });+ // Build identity, never the shared-profile path/version, controls the developer entry.+ it.each([+ [true, false, 'cn', 'installed'],+ [true, false, 'global', 'installed'],+ [false, false, 'cn', 'development'],+ [true, true, 'global', 'development'],+ [true, false, 'dev', 'development'],+ ])('projects build identity %s/%s/%s as %s', async (packaged, personal, region, kind) => {+ await disposeLocalAgentHost();+ Object.assign(mock, { packaged, personal, region });+ installLocalAgentHost({} as any);+ await localAgentConnections();+ expect(mock.deps.instanceInfo).toEqual({ kind, region });+ const value = await localAgentDeveloperConnection();+ if (kind === 'installed') expect(value).toBeNull();+ else+ expect(value).toEqual({+ state: 'ready',+ code: 'cindy-local:v1:12345:' + 'n'.repeat(42) + '2',+ });+ });+ it('never returns an old owner endpoint or raw startup error from the code query', async () => {+ mock.generation++;+ expect(await localAgentDeveloperConnection()).toEqual({ state: 'owner-unavailable' });+ await disposeLocalAgentHost();+ mock.owner = '';+ expect(await localAgentDeveloperConnection()).toEqual({ state: 'owner-unavailable' });+ mock.owner = 'owner-a';+ mock.startupError = new Error('PRIVATE PATH');+ installLocalAgentHost({} as any);+ await expect(localAgentConnections()).rejects.toThrow('[INTERNAL]');+ expect(await localAgentDeveloperConnection()).toEqual({ state: 'failed' });+ await expect(+ localAgentDeveloperConnection(() => {+ throw new Error('untrusted');+ }),+ ).rejects.toThrow('[INTERNAL]');+ });+ it('closes a late startup instead of publishing its code after the host was retired', async () => {+ await disposeLocalAgentHost();+ let release!: () => void;+ mock.startupGate = new Promise<void>((resolve) => {+ release = resolve;+ });+ mock.deps = undefined;+ installLocalAgentHost({} as any);+ const query = localAgentConnections().catch(() => undefined);+ await vi.waitFor(() => expect(mock.deps).toBeDefined());+ const stopping = disposeLocalAgentHost();+ release();+ await stopping;+ await query;+ expect(await localAgentDeveloperConnection()).toEqual({ state: 'stopped' });+ expect(mock.close).toHaveBeenCalled();});});diff --git a/apps/desktop/src/main/local-agent/server.ts b/apps/desktop/src/main/local-agent/server.tsindex 63a7bab7ac..53746315f5 100644--- a/apps/desktop/src/main/local-agent/server.ts+++ b/apps/desktop/src/main/local-agent/server.ts@@ -9,6 +9,7 @@ import fs from 'node:fs/promises';import path from 'node:path';import type { LocalAgentModel } from './catalog.js';import { atomicWriteFileSync, readAtomicFileSync } from '../utils/atomicWriteFile.js';+import type { LocalAgentInstanceInfo } from '../../shared/localAgent.js';const MAX_BODY = 16 * 1024 * 1024;const MAX_EVENTS = 8 * 1024 * 1024;@@ -92,6 +93,7 @@ export interface LocalAgentServerDeps {directory: string;discoveryDirectory?: string;version: string;+ instanceInfo?: Readonly<LocalAgentInstanceInfo>;scope(): string;models(): Promise<LocalAgentModel[]>;approve(signal: AbortSignal, client: LocalAgentClientIdentity): Promise<boolean>;@@ -698,7 +700,9 @@ export async function createLocalAgentServer(deps: LocalAgentServerDeps) {protocol: 1,version: deps.version,instance: instanceId,+ ...(deps.instanceInfo ? { instanceInfo: deps.instanceInfo } : {}),features: {+ ...(deps.instanceInfo ? { instanceMetadata: true } : {}),clientIdentity: true,isolatedSessions: true,individualRevocation: true,@@ -816,10 +820,9 @@ export async function createLocalAgentServer(deps: LocalAgentServerDeps) {const discoveryFile = path.join(discoveryDirectory, 'discovery.json');try {await fs.mkdir(discoveryDirectory, { recursive: true, mode: 0o700 });- await fs.writeFile(+ atomicWriteFileSync(discoveryFile,JSON.stringify({ protocol: 1, port: address.port, instance: instanceId }),- { mode: 0o600 },);} catch {closing = true;@@ -843,6 +846,7 @@ export async function createLocalAgentServer(deps: LocalAgentServerDeps) {}, 1000).unref();return {base,+ rpc: Object.freeze({ protocol: 1 as const, port: address.port, instance: instanceId }),discoveryFile,connections: () =>grantsdiff --git a/apps/desktop/src/main/local-agent/service.ts b/apps/desktop/src/main/local-agent/service.tsindex 26c929f066..86986755d6 100644--- a/apps/desktop/src/main/local-agent/service.ts+++ b/apps/desktop/src/main/local-agent/service.ts@@ -14,7 +14,14 @@ import { createLogger } from '../logger.js';import { t } from '../i18n.js';import { throwIpcError } from '../utils/ipcValidate.js';import { isIpcError } from '../../shared/ipc-errors.js';-import type { LocalAgentConnection } from '../../shared/localAgent.js';+import {+ formatLocalAgentConnectionCode,+ type LocalAgentConnection,+ type LocalAgentDeveloperConnection,+ type LocalAgentInstanceInfo,+} from '../../shared/localAgent.js';+import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';+import { isCindyPersonalRuntime } from '../cindy-make/versionRuntimeIdentity.js';import { isTrustedAppRendererWindow } from '../security/trustedAppRenderer.js';import { localAgentModels } from './catalog.js';import { createLocalAgentServer, LocalAgentError, type LocalAgentServerDeps } from './server.js';@@ -26,6 +33,25 @@ const log = createLogger('local-agent');let current: Promise<Awaited<ReturnType<typeof createLocalAgentServer>>> | undefined;let startupFailure: unknown;let teardown = Promise.resolve();+let readyServer: Awaited<ReturnType<typeof createLocalAgentServer>> | undefined;+let currentOwner: string | undefined;++function instanceInfo(): LocalAgentInstanceInfo {+ return {+ kind:+ !app.isPackaged || isCindyPersonalRuntime() || CURRENT_CINDY_REGION === 'dev'+ ? 'development'+ : 'installed',+ region: CURRENT_CINDY_REGION,+ };+}++function notifySettings(): void {+ for (const window of BrowserWindow.getAllWindows()) {+ if (isTrustedAppRendererWindow(window))+ window.webContents.send('local-agent:connections-changed');+ }+}/** A shared profile has one discovery endpoint and one grant writer. Reuse the* existing process lock so a passive/preview instance cannot resurrect revoked grants. */@@ -56,6 +82,7 @@ async function startWithProfileLease(deps: LocalAgentServerDeps) {if (!deps.scope()) throw new LocalAgentError('UNAUTHORIZED', '本机应用授权范围已更改。');const server = await createLocalAgentServer(deps);try {+ if (!deps.scope()) throw new LocalAgentError('UNAUTHORIZED', '本机应用授权范围已更改。');ready({...server,async close() {@@ -82,16 +109,20 @@ export function installLocalAgentHost(maker: Maker): void {const directory = ownerScopedUserDataPath('local-agent');const scopeNow = () => {const now = getActiveAppSession();- return now.dataOwnerId && !isAppSessionBoundaryPending() && activeOwnerScopeKey() === liveOwner+ return current === pending &&+ now.dataOwnerId &&+ !isAppSessionBoundaryPending() &&+ activeOwnerScopeKey() === liveOwner? createHash('sha256').update(`${now.mode}:${now.dataOwnerId}`).digest('hex'): '';};startupFailure = undefined;- const pending = teardown.then(() =>+ const pending: Promise<Awaited<ReturnType<typeof createLocalAgentServer>>> = teardown.then(() =>startWithProfileLease({directory,discoveryDirectory: path.join(app.getPath('userData'), 'local-agent'),version: app.getVersion(),+ instanceInfo: Object.freeze(instanceInfo()),scope: scopeNow,async models() {if (scopeNow() !== scope)@@ -134,18 +165,29 @@ export function installLocalAgentHost(maker: Maker): void {warn: (code) => log.warn('local agent request failed', { code }),changed: () => {if (scopeNow() !== scope) return;- for (const window of BrowserWindow.getAllWindows()) {- if (isTrustedAppRendererWindow(window))- window.webContents.send('local-agent:connections-changed');- }+ notifySettings();},}),);current = pending;+ currentOwner = liveOwner;+ readyServer = undefined;+ notifySettings();+ void pending.then(+ (server) => {+ if (current === pending && scopeNow() === scope) {+ readyServer = server;+ notifySettings();+ }+ },+ () => {},+ );void pending.catch((error) => {if (current === pending) {current = undefined;+ readyServer = undefined;startupFailure = error;+ notifySettings();}log.warn('local agent API startup failed', {code: error instanceof LocalAgentError ? error.code : 'LOCAL_AGENT_FAILED',@@ -153,6 +195,32 @@ export function installLocalAgentHost(maker: Maker): void {});}+/** Read only this process's held endpoint. Never borrow a shared profile's discovery file. */+export async function localAgentDeveloperConnection(+ assertCaller = () => {},+): Promise<LocalAgentDeveloperConnection | null> {+ return settingsOperation(async () => {+ assertCaller();+ if (instanceInfo().kind !== 'development') return null;+ if (+ !getActiveAppSession().dataOwnerId ||+ isAppSessionBoundaryPending() ||+ (currentOwner !== undefined && currentOwner !== activeOwnerScopeKey())+ )+ return { state: 'owner-unavailable' };+ if (startupFailure)+ return {+ state:+ startupFailure instanceof LocalAgentError && startupFailure.code === 'HOST_IN_USE'+ ? 'host-in-use'+ : 'failed',+ };+ if (!current) return { state: 'stopped' };+ if (!readyServer) return { state: 'starting' };+ return { state: 'ready', code: formatLocalAgentConnectionCode(readyServer.rpc) };+ });+}+async function settingsOperation<T>(action: () => Promise<T>): Promise<T> {try {return await action();@@ -227,7 +295,10 @@ export async function revokeLocalAgentConnections(export async function disposeLocalAgentHost(): Promise<void> {const previous = current;current = undefined;+ readyServer = undefined;+ currentOwner = undefined;startupFailure = undefined;+ notifySettings();const stopping = previous? previous.then((server) => server.close())diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 9044734e3c..00c6adc98b 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -1077,6 +1077,7 @@ const appearanceSettingsInfo = ipcRenderer.sendSync(contextBridge.exposeInMainWorld('electronAPI', {localAgent: {+ developerConnection: (): Promise<import('../shared/localAgent').LocalAgentDeveloperConnection | null> => ipcRenderer.invoke('local-agent:developer-connection'),connections: (): Promise<import('../shared/localAgent').LocalAgentConnection[]> => ipcRenderer.invoke('local-agent:connections'),revoke: (connectionId?: string): Promise<boolean> => ipcRenderer.invoke('local-agent:revoke', connectionId),onConnectionsChanged: (listener: () => void) => {diff --git a/apps/desktop/src/renderer/components/settings/LocalAgentSection.tsx b/apps/desktop/src/renderer/components/settings/LocalAgentSection.tsxindex 2ab46e29bc..3351a21bdc 100644--- a/apps/desktop/src/renderer/components/settings/LocalAgentSection.tsx+++ b/apps/desktop/src/renderer/components/settings/LocalAgentSection.tsx@@ -3,7 +3,10 @@ import { useTranslation } from 'react-i18next';import { Button } from '@/components/ui/button';import { toast } from '@/lib/toast';import { extractIpcError } from '@/utils/ipcError';-import type { LocalAgentConnection } from '../../../shared/localAgent';+import type {+ LocalAgentConnection,+ LocalAgentDeveloperConnection,+} from '../../../shared/localAgent';import {SETTINGS_CARD_CLASS,SETTINGS_ROW_CLASS,@@ -19,12 +22,26 @@ export function LocalAgentSection() {const [loading, setLoading] = useState(true);const [failed, setFailed] = useState(false);const [revoking, setRevoking] = useState<string>();+ const [developer, setDeveloper] = useState<LocalAgentDeveloperConnection | null>(null);+ const [copying, setCopying] = useState(false);+ const copyingRef = useRef(false);const busy = useRef(false);useEffect(() => {let alive = true,revision = 0;const refresh = () => {const request = ++revision;+ void window.electronAPI.localAgent+ .developerConnection()+ .then((value) => {+ if (alive && revision === request) setDeveloper(value);+ })+ .catch(() => {+ if (alive && revision === request) {+ setDeveloper((previous) => (previous ? { state: 'failed' } : null));+ setFailed(true);+ }+ });void window.electronAPI.localAgent.connections().then((value) => {@@ -47,6 +64,23 @@ export function LocalAgentSection() {unsubscribe();};}, []);+ const copyConnection = async () => {+ if (copyingRef.current) return;+ copyingRef.current = true;+ setCopying(true);+ try {+ const value = await window.electronAPI.localAgent.developerConnection();+ setDeveloper(value);+ if (!value || value.state !== 'ready') return;+ await navigator.clipboard.writeText(value.code);+ toast.success(t('localAgent.codeCopied'));+ } catch {+ toast.error(t('localAgent.codeCopyFailed'));+ } finally {+ copyingRef.current = false;+ setCopying(false);+ }+ };const revoke = async (id: string) => {if (busy.current) return;busy.current = true;@@ -67,6 +101,28 @@ export function LocalAgentSection() {<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)}>+ {developer && (+ <>+ <div className={SETTINGS_ROW_CLASS}>+ <div className="flex min-w-0 flex-col gap-1">+ <p className={SETTINGS_ROW_LABEL_CLASS}>{t('localAgent.developerConnection')}</p>+ <p role="status" className={SETTINGS_ROW_HINT_CLASS}>+ {t(`localAgent.developerState.${developer.state}`)}+ </p>+ </div>+ <Button+ variant="secondary"+ size="sm"+ className="shrink-0"+ disabled={developer.state !== 'ready' || copying}+ onClick={() => void copyConnection()}+ >+ {t('localAgent.copyCode')}+ </Button>+ </div>+ <div className={SETTINGS_ROW_DIVIDER_CLASS} />+ </>+ )}{connections.length ? (connections.map((connection, index) => (<Fragment key={connection.id}>@@ -97,12 +153,16 @@ export function LocalAgentSection() {<div className={SETTINGS_ROW_CLASS}><div className="flex min-w-0 flex-col gap-1"><p role={failed ? 'status' : undefined} className={SETTINGS_ROW_LABEL_CLASS}>- {t(loading ? 'localAgent.loading' : failed ? 'localAgent.failed' : 'localAgent.empty')}+ {t(+ loading+ ? 'localAgent.loading'+ : failed+ ? 'localAgent.failed'+ : 'localAgent.empty',+ )}</p>{!loading && !failed && (- <p className={SETTINGS_ROW_HINT_CLASS}>- {t('localAgent.description')}- </p>+ <p className={SETTINGS_ROW_HINT_CLASS}>{t('localAgent.description')}</p>)}</div></div>diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex ef56006074..2b0ab140ce 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -1,5 +1,5 @@{- "localAgent": {"title":"Local App Connections","empty":"No connected apps","description":"Authorized local apps can use Cindy models and agent capabilities. Cindy keeps supplier credentials.","revoke":"Revoke Connection","failed":"Could not read app connections.","connectTitle":"Connect a Local App","connectMessage":"Allow “{{app}}” to use Cindy?","connectDetail":"This app can list models and providers, create its own executions, and supply tools. Native execution can read and write files and run commands with your system user permissions; the working directory does not restrict access. Provider credentials stay in Cindy. Revoke individual connections in Settings → Remote Connections → Local App Connections.","cancel":"Cancel","allow":"Allow Connection","revokeMessage":"Revoke all local app connections?","revokeDetail":"All local app connections will stop working and their running tasks will stop. Apps can request a new connection when needed.","clientIdentity":"App-reported ID: {{id}}\nVersion: {{version}}\nThe requesting app supplies its name and ID; Cindy has not verified its publisher.","revokeOneMessage":"Revoke this connection for “{{app}}”?","revokeOneDetail":"Tasks running through this connection will stop. Other app connections will keep working. The app can request a new connection when needed.","revokeConnection":"Revoke connection for “{{app}}”","clientId":"App ID: {{id}}","operationFailed":"Could not confirm the local app operation. Check its current state before continuing.","invalidConnection":"The app connection ID is invalid.","revokeFailed":"Could not confirm the revocation. Check the current connection state.","loading":"Loading app connections…","revoking":"Revoking connection…","authorizationRequired":"This operation requires valid local app authorization.","pairExpired":"The connection request expired or was cancelled. Request a new connection from the app.","busy":"A local app execution is still running or the execution limit is reached. End unused executions first.","limitReached":"The local app connection limit is reached. Revoke unused connections in Settings.","invalidWorkspace":"The app must specify an existing absolute working directory on this computer.","sessionExists":"This execution ID is already in use by this app connection.","executionUnavailable":"The requested execution or tool call is unavailable. Messages and tool operations were not replayed.","selectionUnavailable":"The selected model, provider, or reasoning effort is unavailable. Select an available option in the app.","requestNotReplayed":"This request was not repeated. Check the original operation result in the app.","storageUnavailable":"Could not read or save local app connection data. Existing authorization records were retained.","stopUnconfirmed":"Further messages to this execution are blocked, but the process has not been confirmed stopped.","interactionUnavailable":"The engine requires an interaction that this app cannot receive.","interrupted":"This send was interrupted.","toolTimeout":"The app tool timed out. It was not automatically retried.","connectResult":"Return to the requesting app for the connection result. Authorization is decided in the Cindy confirmation window.","invalidRequest":"The app request is invalid or the operation is unsupported.","hostInUse":"Another Cindy instance manages local app connections for this profile. View the connections in that instance."},+ "localAgent": {"title":"Local App Connections","empty":"No connected apps","description":"Authorized local apps can use Cindy models and agent capabilities. Cindy keeps supplier credentials.","revoke":"Revoke Connection","failed":"Could not read app connections.","connectTitle":"Connect a Local App","connectMessage":"Allow “{{app}}” to use Cindy?","connectDetail":"This app can list models and providers, create its own executions, and supply tools. Native execution can read and write files and run commands with your system user permissions; the working directory does not restrict access. Provider credentials stay in Cindy. Revoke individual connections in Settings → Remote Connections → Local App Connections.","cancel":"Cancel","allow":"Allow Connection","revokeMessage":"Revoke all local app connections?","revokeDetail":"All local app connections will stop working and their running tasks will stop. Apps can request a new connection when needed.","clientIdentity":"App-reported ID: {{id}}\nVersion: {{version}}\nThe requesting app supplies its name and ID; Cindy has not verified its publisher.","revokeOneMessage":"Revoke this connection for “{{app}}”?","revokeOneDetail":"Tasks running through this connection will stop. Other app connections will keep working. The app can request a new connection when needed.","revokeConnection":"Revoke connection for “{{app}}”","clientId":"App ID: {{id}}","operationFailed":"Could not confirm the local app operation. Check its current state before continuing.","invalidConnection":"The app connection ID is invalid.","revokeFailed":"Could not confirm the revocation. Check the current connection state.","loading":"Loading app connections…","revoking":"Revoking connection…","authorizationRequired":"This operation requires valid local app authorization.","pairExpired":"The connection request expired or was cancelled. Request a new connection from the app.","busy":"A local app execution is still running or the execution limit is reached. End unused executions first.","limitReached":"The local app connection limit is reached. Revoke unused connections in Settings.","invalidWorkspace":"The app must specify an existing absolute working directory on this computer.","sessionExists":"This execution ID is already in use by this app connection.","executionUnavailable":"The requested execution or tool call is unavailable. Messages and tool operations were not replayed.","selectionUnavailable":"The selected model, provider, or reasoning effort is unavailable. Select an available option in the app.","requestNotReplayed":"This request was not repeated. Check the original operation result in the app.","storageUnavailable":"Could not read or save local app connection data. Existing authorization records were retained.","stopUnconfirmed":"Further messages to this execution are blocked, but the process has not been confirmed stopped.","interactionUnavailable":"The engine requires an interaction that this app cannot receive.","interrupted":"This send was interrupted.","toolTimeout":"The app tool timed out. It was not automatically retried.","connectResult":"Return to the requesting app for the connection result. Authorization is decided in the Cindy confirmation window.","invalidRequest":"The app request is invalid or the operation is unsupported.","hostInUse":"Another Cindy instance manages local app connections for this profile. View the connections in that instance.","developerConnection":"Development Connection","copyCode":"Copy Connection Code","codeCopied":"Connection code copied","codeCopyFailed":"Could not copy the connection code","developerState":{"ready":"For temporary connections from apps on this computer. Approval in this Cindy is still required. Copy a new code after restarting.","starting":"Preparing connection…","owner-unavailable":"Sign in or enter local mode first","host-in-use":"Another Cindy manages connections for this data folder","failed":"The local connection could not start","stopped":"The local connection has stopped"}},"mailReader": {"markReadFailed": "Could not sync read status. Check mailbox authorization and reopen this email.","title": "Mail",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 238b6372da..371be728f0 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -1,5 +1,5 @@{- "localAgent": {"title":"ローカルアプリの接続","empty":"接続済みのアプリはありません","description":"承認したローカルアプリが Cindy のモデルと実行機能を利用できます。認証情報は Cindy が管理します。","revoke":"接続を解除","failed":"アプリの接続を読み込めませんでした。","connectTitle":"ローカルアプリを接続","connectMessage":"「{{app}}」に Cindy の利用を許可しますか?","connectDetail":"このアプリはモデルとプロバイダーの一覧を取得し、独自の実行を作成してツールを提供できます。ネイティブ実行では、現在の OS ユーザーの権限でファイルを読み書きし、コマンドを実行できます。作業ディレクトリはアクセス範囲を制限しません。認証情報は Cindy が保持します。設定 → リモート接続 → ローカルアプリの接続で個別に解除できます。","cancel":"キャンセル","allow":"接続を許可","revokeMessage":"すべてのローカルアプリ接続を取り消しますか?","revokeDetail":"すべてのローカルアプリ接続が無効になり、実行中のタスクが停止します。必要に応じて再接続できます。","clientIdentity":"アプリが申告した ID:{{id}}\nバージョン:{{version}}\n名前と ID は申請元の申告であり、Cindy が発行元を確認したことを意味しません。","revokeOneMessage":"「{{app}}」のこの接続を取り消しますか?","revokeOneDetail":"この接続で実行中のタスクが停止します。他のアプリ接続には影響しません。必要に応じて再接続できます。","revokeConnection":"「{{app}}」の接続を取り消す","clientId":"アプリ ID:{{id}}","operationFailed":"ローカルアプリの操作結果を確認できませんでした。現在の状態を確認してから続けてください。","invalidConnection":"アプリ接続の ID が無効です。","revokeFailed":"接続の解除を確認できませんでした。現在の接続状態を確認してください。","loading":"アプリの接続を読み込み中…","revoking":"接続を解除中…","authorizationRequired":"この操作には有効なローカルアプリの承認が必要です。","pairExpired":"接続リクエストの有効期限が切れたか、キャンセルされました。アプリから接続を再申請してください。","busy":"ローカルアプリの実行が続いているか、実行数の上限に達しています。不要な実行を先に終了してください。","limitReached":"ローカルアプリの接続数が上限に達しています。設定で不要な接続を解除してください。","invalidWorkspace":"アプリは、このコンピューター上に存在する作業ディレクトリを絶対パスで指定する必要があります。","sessionExists":"このアプリ接続では、その実行 ID がすでに使われています。","executionUnavailable":"要求された実行またはツール呼び出しは利用できません。メッセージやツール操作は再実行されていません。","selectionUnavailable":"選択したモデル、プロバイダー、または推論強度は利用できません。アプリで利用可能な項目を選択してください。","requestNotReplayed":"このリクエストは再実行されていません。アプリで元の操作結果を確認してください。","storageUnavailable":"ローカルアプリの接続データを読み込めないか、保存できませんでした。既存の承認記録は保持されています。","stopUnconfirmed":"この実行への追加メッセージは停止しましたが、プロセスの終了はまだ確認できていません。","interactionUnavailable":"エンジンが必要とする操作を、このアプリでは受け取れません。","interrupted":"今回の送信は中断されました。","toolTimeout":"アプリのツールがタイムアウトしました。自動で再試行していません。","connectResult":"接続結果は申請元のアプリで確認してください。承認は Cindy の確認ウィンドウで決定します。","invalidRequest":"アプリのリクエストが無効か、この操作はサポートされていません。","hostInUse":"このプロファイルのローカルアプリ接続は、別の Cindy インスタンスが管理しています。そのインスタンスで接続を確認してください。"},+ "localAgent": {"title":"ローカルアプリの接続","empty":"接続済みのアプリはありません","description":"承認したローカルアプリが Cindy のモデルと実行機能を利用できます。認証情報は Cindy が管理します。","revoke":"接続を解除","failed":"アプリの接続を読み込めませんでした。","connectTitle":"ローカルアプリを接続","connectMessage":"「{{app}}」に Cindy の利用を許可しますか?","connectDetail":"このアプリはモデルとプロバイダーの一覧を取得し、独自の実行を作成してツールを提供できます。ネイティブ実行では、現在の OS ユーザーの権限でファイルを読み書きし、コマンドを実行できます。作業ディレクトリはアクセス範囲を制限しません。認証情報は Cindy が保持します。設定 → リモート接続 → ローカルアプリの接続で個別に解除できます。","cancel":"キャンセル","allow":"接続を許可","revokeMessage":"すべてのローカルアプリ接続を取り消しますか?","revokeDetail":"すべてのローカルアプリ接続が無効になり、実行中のタスクが停止します。必要に応じて再接続できます。","clientIdentity":"アプリが申告した ID:{{id}}\nバージョン:{{version}}\n名前と ID は申請元の申告であり、Cindy が発行元を確認したことを意味しません。","revokeOneMessage":"「{{app}}」のこの接続を取り消しますか?","revokeOneDetail":"この接続で実行中のタスクが停止します。他のアプリ接続には影響しません。必要に応じて再接続できます。","revokeConnection":"「{{app}}」の接続を取り消す","clientId":"アプリ ID:{{id}}","operationFailed":"ローカルアプリの操作結果を確認できませんでした。現在の状態を確認してから続けてください。","invalidConnection":"アプリ接続の ID が無効です。","revokeFailed":"接続の解除を確認できませんでした。現在の接続状態を確認してください。","loading":"アプリの接続を読み込み中…","revoking":"接続を解除中…","authorizationRequired":"この操作には有効なローカルアプリの承認が必要です。","pairExpired":"接続リクエストの有効期限が切れたか、キャンセルされました。アプリから接続を再申請してください。","busy":"ローカルアプリの実行が続いているか、実行数の上限に達しています。不要な実行を先に終了してください。","limitReached":"ローカルアプリの接続数が上限に達しています。設定で不要な接続を解除してください。","invalidWorkspace":"アプリは、このコンピューター上に存在する作業ディレクトリを絶対パスで指定する必要があります。","sessionExists":"このアプリ接続では、その実行 ID がすでに使われています。","executionUnavailable":"要求された実行またはツール呼び出しは利用できません。メッセージやツール操作は再実行されていません。","selectionUnavailable":"選択したモデル、プロバイダー、または推論強度は利用できません。アプリで利用可能な項目を選択してください。","requestNotReplayed":"このリクエストは再実行されていません。アプリで元の操作結果を確認してください。","storageUnavailable":"ローカルアプリの接続データを読み込めないか、保存できませんでした。既存の承認記録は保持されています。","stopUnconfirmed":"この実行への追加メッセージは停止しましたが、プロセスの終了はまだ確認できていません。","interactionUnavailable":"エンジンが必要とする操作を、このアプリでは受け取れません。","interrupted":"今回の送信は中断されました。","toolTimeout":"アプリのツールがタイムアウトしました。自動で再試行していません。","connectResult":"接続結果は申請元のアプリで確認してください。承認は Cindy の確認ウィンドウで決定します。","invalidRequest":"アプリのリクエストが無効か、この操作はサポートされていません。","hostInUse":"このプロファイルのローカルアプリ接続は、別の Cindy インスタンスが管理しています。そのインスタンスで接続を確認してください。","developerConnection":"開発用接続","copyCode":"接続コードをコピー","codeCopied":"接続コードをコピーしました","codeCopyFailed":"接続コードをコピーできませんでした","developerState":{"ready":"このパソコンのアプリから一時的に接続できます。この Cindy での許可が必要です。再起動後はコードをコピーし直してください。","starting":"接続を準備しています…","owner-unavailable":"先にログインするかローカルモードに入ってください","host-in-use":"このデータフォルダーの接続は別の Cindy が管理しています","failed":"ローカル接続を開始できませんでした","stopped":"ローカル接続は停止しています"}},"mailReader": {"markReadFailed": "既読状態を同期できませんでした。メールボックスの認証を確認して開き直してください。","title": "メール",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex f68c0f2009..85bc4bc2c6 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -1,5 +1,5 @@{- "localAgent": {"title":"로컬 앱 연결","empty":"연결된 앱 없음","description":"승인된 로컬 앱이 Cindy 모델과 실행 기능을 사용할 수 있습니다. 제공자 인증 정보는 Cindy가 관리합니다.","revoke":"연결 해제","failed":"앱 연결을 불러오지 못했습니다.","connectTitle":"로컬 앱 연결","connectMessage":"“{{app}}”의 Cindy 사용을 허용할까요?","connectDetail":"이 앱은 모델과 제공자 목록을 확인하고 자체 실행을 만들며 도구를 제공할 수 있습니다. 네이티브 실행은 현재 시스템 사용자 권한으로 파일을 읽고 쓰거나 명령을 실행할 수 있으며, 작업 디렉터리가 접근 범위를 제한하지 않습니다. 제공자 인증 정보는 Cindy가 보관합니다. 설정 → 원격 연결 → 로컬 앱 연결에서 개별 연결을 해제할 수 있습니다.","cancel":"취소","allow":"연결 허용","revokeMessage":"모든 로컬 앱 연결을 해제할까요?","revokeDetail":"모든 로컬 앱 연결이 무효화되고 실행 중인 작업이 중지됩니다. 필요하면 다시 연결할 수 있습니다.","clientIdentity":"앱이 제공한 ID: {{id}}\n버전: {{version}}\n이름과 ID는 요청 앱이 제공하며, Cindy가 게시자를 확인했다는 의미가 아닙니다.","revokeOneMessage":"“{{app}}”의 이 연결을 취소할까요?","revokeOneDetail":"이 연결에서 실행 중인 작업이 중지됩니다. 다른 앱 연결에는 영향을 주지 않습니다. 필요하면 다시 연결할 수 있습니다.","revokeConnection":"“{{app}}” 연결 취소","clientId":"앱 ID: {{id}}","operationFailed":"로컬 앱 작업 결과를 확인하지 못했습니다. 현재 상태를 확인한 후 계속하세요.","invalidConnection":"앱 연결 ID가 유효하지 않습니다.","revokeFailed":"연결 해제 결과를 확인하지 못했습니다. 현재 연결 상태를 확인하세요.","loading":"앱 연결을 불러오는 중…","revoking":"연결 해제 중…","authorizationRequired":"이 작업에는 유효한 로컬 앱 승인이 필요합니다.","pairExpired":"연결 요청이 만료되었거나 취소되었습니다. 앱에서 새 연결을 요청하세요.","busy":"로컬 앱 실행이 진행 중이거나 실행 한도에 도달했습니다. 사용하지 않는 실행을 먼저 종료하세요.","limitReached":"로컬 앱 연결 한도에 도달했습니다. 설정에서 사용하지 않는 연결을 해제하세요.","invalidWorkspace":"앱은 이 컴퓨터에 존재하는 작업 디렉터리의 절대 경로를 지정해야 합니다.","sessionExists":"이 앱 연결에서 해당 실행 ID를 이미 사용하고 있습니다.","executionUnavailable":"요청한 실행 또는 도구 호출을 사용할 수 없습니다. 메시지와 도구 작업은 다시 실행되지 않았습니다.","selectionUnavailable":"선택한 모델, 제공자 또는 추론 강도을 사용할 수 없습니다. 앱에서 사용 가능한 항목을 선택하세요.","requestNotReplayed":"이 요청은 다시 실행되지 않았습니다. 앱에서 원래 작업 결과를 확인하세요.","storageUnavailable":"로컬 앱 연결 데이터를 읽거나 저장하지 못했습니다. 기존 승인 기록은 유지되었습니다.","stopUnconfirmed":"이 실행에 추가 메시지를 보내는 것은 차단되었지만 프로세스가 중지되었는지는 확인되지 않았습니다.","interactionUnavailable":"엔진에 필요한 상호작용을 이 앱이 받을 수 없습니다.","interrupted":"이번 전송이 중단되었습니다.","toolTimeout":"앱 도구 호출 시간이 초과되었습니다. 자동으로 재시도하지 않았습니다.","connectResult":"연결 결과는 요청한 앱에서 확인하세요. 승인은 Cindy 확인 창에서 결정합니다.","invalidRequest":"앱 요청이 유효하지 않거나 지원하지 않는 작업입니다.","hostInUse":"이 프로필의 로컬 앱 연결은 다른 Cindy 인스턴스가 관리합니다. 해당 인스턴스에서 연결을 확인하세요."},+ "localAgent": {"title":"로컬 앱 연결","empty":"연결된 앱 없음","description":"승인된 로컬 앱이 Cindy 모델과 실행 기능을 사용할 수 있습니다. 제공자 인증 정보는 Cindy가 관리합니다.","revoke":"연결 해제","failed":"앱 연결을 불러오지 못했습니다.","connectTitle":"로컬 앱 연결","connectMessage":"“{{app}}”의 Cindy 사용을 허용할까요?","connectDetail":"이 앱은 모델과 제공자 목록을 확인하고 자체 실행을 만들며 도구를 제공할 수 있습니다. 네이티브 실행은 현재 시스템 사용자 권한으로 파일을 읽고 쓰거나 명령을 실행할 수 있으며, 작업 디렉터리가 접근 범위를 제한하지 않습니다. 제공자 인증 정보는 Cindy가 보관합니다. 설정 → 원격 연결 → 로컬 앱 연결에서 개별 연결을 해제할 수 있습니다.","cancel":"취소","allow":"연결 허용","revokeMessage":"모든 로컬 앱 연결을 해제할까요?","revokeDetail":"모든 로컬 앱 연결이 무효화되고 실행 중인 작업이 중지됩니다. 필요하면 다시 연결할 수 있습니다.","clientIdentity":"앱이 제공한 ID: {{id}}\n버전: {{version}}\n이름과 ID는 요청 앱이 제공하며, Cindy가 게시자를 확인했다는 의미가 아닙니다.","revokeOneMessage":"“{{app}}”의 이 연결을 취소할까요?","revokeOneDetail":"이 연결에서 실행 중인 작업이 중지됩니다. 다른 앱 연결에는 영향을 주지 않습니다. 필요하면 다시 연결할 수 있습니다.","revokeConnection":"“{{app}}” 연결 취소","clientId":"앱 ID: {{id}}","operationFailed":"로컬 앱 작업 결과를 확인하지 못했습니다. 현재 상태를 확인한 후 계속하세요.","invalidConnection":"앱 연결 ID가 유효하지 않습니다.","revokeFailed":"연결 해제 결과를 확인하지 못했습니다. 현재 연결 상태를 확인하세요.","loading":"앱 연결을 불러오는 중…","revoking":"연결 해제 중…","authorizationRequired":"이 작업에는 유효한 로컬 앱 승인이 필요합니다.","pairExpired":"연결 요청이 만료되었거나 취소되었습니다. 앱에서 새 연결을 요청하세요.","busy":"로컬 앱 실행이 진행 중이거나 실행 한도에 도달했습니다. 사용하지 않는 실행을 먼저 종료하세요.","limitReached":"로컬 앱 연결 한도에 도달했습니다. 설정에서 사용하지 않는 연결을 해제하세요.","invalidWorkspace":"앱은 이 컴퓨터에 존재하는 작업 디렉터리의 절대 경로를 지정해야 합니다.","sessionExists":"이 앱 연결에서 해당 실행 ID를 이미 사용하고 있습니다.","executionUnavailable":"요청한 실행 또는 도구 호출을 사용할 수 없습니다. 메시지와 도구 작업은 다시 실행되지 않았습니다.","selectionUnavailable":"선택한 모델, 제공자 또는 추론 강도을 사용할 수 없습니다. 앱에서 사용 가능한 항목을 선택하세요.","requestNotReplayed":"이 요청은 다시 실행되지 않았습니다. 앱에서 원래 작업 결과를 확인하세요.","storageUnavailable":"로컬 앱 연결 데이터를 읽거나 저장하지 못했습니다. 기존 승인 기록은 유지되었습니다.","stopUnconfirmed":"이 실행에 추가 메시지를 보내는 것은 차단되었지만 프로세스가 중지되었는지는 확인되지 않았습니다.","interactionUnavailable":"엔진에 필요한 상호작용을 이 앱이 받을 수 없습니다.","interrupted":"이번 전송이 중단되었습니다.","toolTimeout":"앱 도구 호출 시간이 초과되었습니다. 자동으로 재시도하지 않았습니다.","connectResult":"연결 결과는 요청한 앱에서 확인하세요. 승인은 Cindy 확인 창에서 결정합니다.","invalidRequest":"앱 요청이 유효하지 않거나 지원하지 않는 작업입니다.","hostInUse":"이 프로필의 로컬 앱 연결은 다른 Cindy 인스턴스가 관리합니다. 해당 인스턴스에서 연결을 확인하세요.","developerConnection":"개발용 연결","copyCode":"연결 코드 복사","codeCopied":"연결 코드를 복사했습니다","codeCopyFailed":"연결 코드를 복사하지 못했습니다","developerState":{"ready":"이 컴퓨터의 앱에서 임시로 연결합니다. 이 Cindy에서 승인이 필요합니다. 다시 시작하면 코드를 다시 복사하세요.","starting":"연결 준비 중…","owner-unavailable":"먼저 로그인하거나 로컬 모드로 들어가세요","host-in-use":"다른 Cindy가 이 데이터 폴더의 연결을 관리하고 있습니다","failed":"로컬 연결을 시작하지 못했습니다","stopped":"로컬 연결이 중지되었습니다"}},"mailReader": {"markReadFailed": "읽음 상태를 동기화하지 못했습니다. 메일함 인증을 확인하고 다시 여세요.","title": "메일",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 7264bb27ef..c255a6980d 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -1,5 +1,5 @@{- "localAgent": {"title":"本机应用连接","empty":"尚未连接应用","description":"允许已授权的本机应用使用 Cindy 的模型与执行能力。供应商登录仍由 Cindy 管理。","revoke":"撤销连接","failed":"无法读取应用连接。","connectTitle":"连接本机应用","connectMessage":"允许“{{app}}”使用 Cindy?","connectDetail":"此应用可以查看模型与供应商目录、创建自己的执行并提供工具。原生执行可以按当前系统用户的权限读写文件、运行命令;工作目录不限制访问范围。供应商凭证保留在 Cindy。可在设置 → 远程连接 → 本机应用连接中单独撤销连接。","cancel":"取消","allow":"允许连接","revokeMessage":"撤销所有本机应用连接?","revokeDetail":"所有本机应用的连接会失效,正在运行的接入任务会停止。需要使用时可重新申请连接。","clientIdentity":"应用自报编号:{{id}}\n版本:{{version}}\n名称和编号由申请方提供,不代表 Cindy 已验证其发布者。","revokeOneMessage":"撤销“{{app}}”的这条连接?","revokeOneDetail":"这条连接正在运行的任务会停止。其他应用连接不受影响。需要使用时可重新申请连接。","revokeConnection":"撤销“{{app}}”的连接","clientId":"应用编号:{{id}}","operationFailed":"无法确认本机应用操作的结果,请先查看当前状态。","invalidConnection":"应用连接编号无效。","revokeFailed":"无法确认撤销结果,请查看当前连接状态。","loading":"正在读取应用连接…","revoking":"正在撤销连接…","authorizationRequired":"此操作需要有效的本机应用授权。","pairExpired":"连接申请已过期或取消,请从应用重新申请连接。","busy":"本机应用仍有执行正在运行,或已达到执行上限,请先结束不用的执行。","limitReached":"已达到本机应用连接上限,请在设置中撤销不用的连接。","invalidWorkspace":"应用须指定此电脑上已存在的绝对工作目录。","sessionExists":"此应用连接已在使用该执行编号。","executionUnavailable":"所请求的执行或工具调用不可用,消息与工具操作未被重放。","selectionUnavailable":"所选模型、供应商或推理强度不可用,请在应用中重新选择。","requestNotReplayed":"此请求未被重复执行,请在应用中查看原操作结果。","storageUnavailable":"无法读取或保存本机应用连接数据,已保留现有授权记录。","stopUnconfirmed":"已阻止继续向此执行发送消息,但尚未确认进程已停止。","interactionUnavailable":"引擎需要此应用无法接收的交互操作。","interrupted":"本次发送已中断。","toolTimeout":"应用工具调用已超时,未自动重试。","connectResult":"请返回申请连接的应用查看结果,授权由 Cindy 确认窗口决定。","invalidRequest":"应用请求无效,或该操作不受支持。","hostInUse":"此配置的本机应用连接正由另一个 Cindy 实例管理,请在该实例中查看连接。"},+ "localAgent": {"title":"本机应用连接","empty":"尚未连接应用","description":"允许已授权的本机应用使用 Cindy 的模型与执行能力。供应商登录仍由 Cindy 管理。","revoke":"撤销连接","failed":"无法读取应用连接。","connectTitle":"连接本机应用","connectMessage":"允许“{{app}}”使用 Cindy?","connectDetail":"此应用可以查看模型与供应商目录、创建自己的执行并提供工具。原生执行可以按当前系统用户的权限读写文件、运行命令;工作目录不限制访问范围。供应商凭证保留在 Cindy。可在设置 → 远程连接 → 本机应用连接中单独撤销连接。","cancel":"取消","allow":"允许连接","revokeMessage":"撤销所有本机应用连接?","revokeDetail":"所有本机应用的连接会失效,正在运行的接入任务会停止。需要使用时可重新申请连接。","clientIdentity":"应用自报编号:{{id}}\n版本:{{version}}\n名称和编号由申请方提供,不代表 Cindy 已验证其发布者。","revokeOneMessage":"撤销“{{app}}”的这条连接?","revokeOneDetail":"这条连接正在运行的任务会停止。其他应用连接不受影响。需要使用时可重新申请连接。","revokeConnection":"撤销“{{app}}”的连接","clientId":"应用编号:{{id}}","operationFailed":"无法确认本机应用操作的结果,请先查看当前状态。","invalidConnection":"应用连接编号无效。","revokeFailed":"无法确认撤销结果,请查看当前连接状态。","loading":"正在读取应用连接…","revoking":"正在撤销连接…","authorizationRequired":"此操作需要有效的本机应用授权。","pairExpired":"连接申请已过期或取消,请从应用重新申请连接。","busy":"本机应用仍有执行正在运行,或已达到执行上限,请先结束不用的执行。","limitReached":"已达到本机应用连接上限,请在设置中撤销不用的连接。","invalidWorkspace":"应用须指定此电脑上已存在的绝对工作目录。","sessionExists":"此应用连接已在使用该执行编号。","executionUnavailable":"所请求的执行或工具调用不可用,消息与工具操作未被重放。","selectionUnavailable":"所选模型、供应商或推理强度不可用,请在应用中重新选择。","requestNotReplayed":"此请求未被重复执行,请在应用中查看原操作结果。","storageUnavailable":"无法读取或保存本机应用连接数据,已保留现有授权记录。","stopUnconfirmed":"已阻止继续向此执行发送消息,但尚未确认进程已停止。","interactionUnavailable":"引擎需要此应用无法接收的交互操作。","interrupted":"本次发送已中断。","toolTimeout":"应用工具调用已超时,未自动重试。","connectResult":"请返回申请连接的应用查看结果,授权由 Cindy 确认窗口决定。","invalidRequest":"应用请求无效,或该操作不受支持。","hostInUse":"此配置的本机应用连接正由另一个 Cindy 实例管理,请在该实例中查看连接。","developerConnection":"开发连接","copyCode":"复制连接码","codeCopied":"连接码已复制","codeCopyFailed":"未能复制连接码","developerState":{"ready":"供此电脑上的应用临时连接,仍需在此 Cindy 中授权。重启后需重新复制。","starting":"正在准备连接…","owner-unavailable":"请先登录或进入本地模式","host-in-use":"此数据目录的连接正由另一个 Cindy 管理","failed":"本机连接未能启动","stopped":"本机连接已停止"}},"mailReader": {"markReadFailed": "未能同步已读状态,请检查邮箱授权后重新打开。","title": "邮件",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 8a0cf78923..9295ea0251 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -1,5 +1,5 @@{- "localAgent": {"title":"本機應用程式連線","empty":"尚未連接應用程式","description":"允許已授權的本機應用程式使用 Cindy 的模型與執行能力。供應商登入仍由 Cindy 管理。","revoke":"撤銷連線","failed":"無法讀取應用程式連線。","connectTitle":"連接本機應用程式","connectMessage":"允許「{{app}}」使用 Cindy?","connectDetail":"此應用程式可以查看模型與供應商目錄、建立自己的執行並提供工具。原生執行可以依目前系統使用者的權限讀寫檔案、執行命令;工作目錄不限制存取範圍。供應商憑證保留在 Cindy。可在設定 → 遠端連線 → 本機應用程式連線中個別撤銷連線。","cancel":"取消","allow":"允許連接","revokeMessage":"撤銷所有本機應用程式連線?","revokeDetail":"所有本機應用程式連線將失效,正在執行的接入任務會停止。需要時可重新申請連線。","clientIdentity":"應用程式自報編號:{{id}}\n版本:{{version}}\n名稱與編號由申請方提供,不代表 Cindy 已驗證其發行者。","revokeOneMessage":"撤銷「{{app}}」的這條連線?","revokeOneDetail":"透過此連線執行的任務會停止。其他應用程式連線不受影響,需要時可重新申請連線。","revokeConnection":"撤銷「{{app}}」的連線","clientId":"應用程式編號:{{id}}","operationFailed":"無法確認本機應用程式操作的結果,請先查看目前狀態。","invalidConnection":"應用程式連線編號無效。","revokeFailed":"無法確認撤銷結果,請查看目前連線狀態。","loading":"正在讀取應用程式連線…","revoking":"正在撤銷連線…","authorizationRequired":"此操作需要有效的本機應用程式授權。","pairExpired":"連線申請已過期或取消,請從應用程式重新申請連線。","busy":"本機應用程式仍有執行正在運行,或已達執行上限,請先結束不用的執行。","limitReached":"已達本機應用程式連線上限,請在設定中撤銷不用的連線。","invalidWorkspace":"應用程式須指定此電腦上已存在的絕對工作目錄。","sessionExists":"此應用程式連線已在使用該執行編號。","executionUnavailable":"所請求的執行或工具呼叫無法使用,訊息與工具操作未被重播。","selectionUnavailable":"所選模型、供應商或推理強度無法使用,請在應用程式中重新選擇。","requestNotReplayed":"此請求未被重複執行,請在應用程式中查看原操作結果。","storageUnavailable":"無法讀取或儲存本機應用程式連線資料,已保留現有授權紀錄。","stopUnconfirmed":"已阻止繼續向此執行傳送訊息,但尚未確認程序已停止。","interactionUnavailable":"引擎需要此應用程式無法接收的互動操作。","interrupted":"本次傳送已中斷。","toolTimeout":"應用程式工具呼叫已逾時,未自動重試。","connectResult":"請返回申請連線的應用程式查看結果,授權由 Cindy 確認視窗決定。","invalidRequest":"應用程式請求無效,或該操作不受支援。","hostInUse":"此設定檔的本機應用程式連線正由另一個 Cindy 執行個體管理,請在該執行個體中查看連線。"},+ "localAgent": {"title":"本機應用程式連線","empty":"尚未連接應用程式","description":"允許已授權的本機應用程式使用 Cindy 的模型與執行能力。供應商登入仍由 Cindy 管理。","revoke":"撤銷連線","failed":"無法讀取應用程式連線。","connectTitle":"連接本機應用程式","connectMessage":"允許「{{app}}」使用 Cindy?","connectDetail":"此應用程式可以查看模型與供應商目錄、建立自己的執行並提供工具。原生執行可以依目前系統使用者的權限讀寫檔案、執行命令;工作目錄不限制存取範圍。供應商憑證保留在 Cindy。可在設定 → 遠端連線 → 本機應用程式連線中個別撤銷連線。","cancel":"取消","allow":"允許連接","revokeMessage":"撤銷所有本機應用程式連線?","revokeDetail":"所有本機應用程式連線將失效,正在執行的接入任務會停止。需要時可重新申請連線。","clientIdentity":"應用程式自報編號:{{id}}\n版本:{{version}}\n名稱與編號由申請方提供,不代表 Cindy 已驗證其發行者。","revokeOneMessage":"撤銷「{{app}}」的這條連線?","revokeOneDetail":"透過此連線執行的任務會停止。其他應用程式連線不受影響,需要時可重新申請連線。","revokeConnection":"撤銷「{{app}}」的連線","clientId":"應用程式編號:{{id}}","operationFailed":"無法確認本機應用程式操作的結果,請先查看目前狀態。","invalidConnection":"應用程式連線編號無效。","revokeFailed":"無法確認撤銷結果,請查看目前連線狀態。","loading":"正在讀取應用程式連線…","revoking":"正在撤銷連線…","authorizationRequired":"此操作需要有效的本機應用程式授權。","pairExpired":"連線申請已過期或取消,請從應用程式重新申請連線。","busy":"本機應用程式仍有執行正在運行,或已達執行上限,請先結束不用的執行。","limitReached":"已達本機應用程式連線上限,請在設定中撤銷不用的連線。","invalidWorkspace":"應用程式須指定此電腦上已存在的絕對工作目錄。","sessionExists":"此應用程式連線已在使用該執行編號。","executionUnavailable":"所請求的執行或工具呼叫無法使用,訊息與工具操作未被重播。","selectionUnavailable":"所選模型、供應商或推理強度無法使用,請在應用程式中重新選擇。","requestNotReplayed":"此請求未被重複執行,請在應用程式中查看原操作結果。","storageUnavailable":"無法讀取或儲存本機應用程式連線資料,已保留現有授權紀錄。","stopUnconfirmed":"已阻止繼續向此執行傳送訊息,但尚未確認程序已停止。","interactionUnavailable":"引擎需要此應用程式無法接收的互動操作。","interrupted":"本次傳送已中斷。","toolTimeout":"應用程式工具呼叫已逾時,未自動重試。","connectResult":"請返回申請連線的應用程式查看結果,授權由 Cindy 確認視窗決定。","invalidRequest":"應用程式請求無效,或該操作不受支援。","hostInUse":"此設定檔的本機應用程式連線正由另一個 Cindy 執行個體管理,請在該執行個體中查看連線。","developerConnection":"開發連線","copyCode":"複製連線碼","codeCopied":"連線碼已複製","codeCopyFailed":"無法複製連線碼","developerState":{"ready":"供此電腦上的應用程式暫時連線,仍需在此 Cindy 中授權。重新啟動後需重新複製。","starting":"正在準備連線…","owner-unavailable":"請先登入或進入本機模式","host-in-use":"此資料目錄的連線正由另一個 Cindy 管理","failed":"本機連線未能啟動","stopped":"本機連線已停止"}},"mailReader": {"markReadFailed": "未能同步已讀狀態,請檢查信箱授權後重新開啟。","title": "郵件",diff --git a/apps/desktop/src/shared/localAgent.ts b/apps/desktop/src/shared/localAgent.tsindex cfa81e67e1..fd277cb3a8 100644--- a/apps/desktop/src/shared/localAgent.ts+++ b/apps/desktop/src/shared/localAgent.ts@@ -6,7 +6,30 @@ export interface LocalAgentConnection {}export interface LocalAgentSettingsApi {+ developerConnection(): Promise<LocalAgentDeveloperConnection | null>;connections(): Promise<LocalAgentConnection[]>;revoke(connectionId?: string): Promise<boolean>;onConnectionsChanged(listener: () => void): () => void;}++/** Unauthenticated build self-description; never proof of a publisher or an app grant. */+export interface LocalAgentInstanceInfo {+ kind: 'installed' | 'development';+ region: 'global' | 'cn' | 'dev';+}++export type LocalAgentDeveloperConnection =+ | { state: 'ready'; code: string }+ | { state: 'starting' | 'owner-unavailable' | 'host-in-use' | 'failed' | 'stopped' };++/** A locator for this API generation, not a credential. No persistent mapping is needed. */+export function formatLocalAgentConnectionCode(rpc: { port: number; instance: string }): string {+ if (+ !Number.isInteger(rpc.port) ||+ rpc.port < 1 ||+ rpc.port > 65535 ||+ !/^[A-Za-z0-9_-]{43}$/.test(rpc.instance)+ )+ throw new Error('Invalid local endpoint');+ return `cindy-local:v1:${rpc.port}:${rpc.instance}`;+}diff --git a/docs/dev-rules/credentials-and-local-storage.md b/docs/dev-rules/credentials-and-local-storage.mdindex 52b294ab61..b3f62773d2 100644--- a/docs/dev-rules/credentials-and-local-storage.md+++ b/docs/dev-rules/credentials-and-local-storage.md@@ -198,7 +198,7 @@ refresh 与 relay 自救节流。在途 refresh 尚未返回时收到的恢复| ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || Cindy 管理的持久数据 | Desktop 使用 `app.getPath('userData')`,共享 package 由宿主注入等价根目录 || 浏览器用户配方 | `userData/browser-recipes/<site>/recipes/<id 的 SHA-256>.json`,每站多个流程,原子替换;兼容旧 `recipe.json`,新文件优先。只保存配方定义及 active/suspended 状态,不保存试跑的 inputs/页面返回值;禁止写入凭据,业务变动值用 inputs。试跑凭证与单轮修复预算只在 MCP 会话内存中,暂停状态跨重启保留。 |-| 本机应用 Agent 授权 | `owners/<owner-key>/local-agent/grants.json`,仅含令牌 SHA-256、自报应用资料、账号范围和按授权归属的原生恢复绑定,不存令牌明文、供应商凭据或消息。复用原子写入与恢复 helper;profile 根 `local-agent/host.lock` 复用跨进程锁,保证一个发现端点和写入者。临时输入与新授权的 Codex 运行历史在同一 owner 下的 `local-agent/clients/<grant-hash>/`;撤权同时关闭执行及工具入口,不允许跨授权恢复。协议与旧版兼容见 [本机应用接入](../local-agent-api.md) |+| 本机应用 Agent 授权 | `owners/<owner-key>/local-agent/grants.json`,仅含令牌 SHA-256、自报应用资料、账号范围和按授权归属的原生恢复绑定,不存令牌明文、供应商凭据或消息。复用原子写入与恢复 helper;profile 根 `local-agent/host.lock` 复用跨进程锁,保证一个发现端点和写入者。开发连接码从当前服务内存按需生成,不新增公共实例登记或短码映射文件。临时输入与新授权的 Codex 运行历史在同一 owner 下的 `local-agent/clients/<grant-hash>/`;撤权同时关闭执行及工具入口,不允许跨授权恢复。协议与旧版兼容见 [本机应用接入](../local-agent-api.md) || 预创建 worktree 的取消标记 | `userData/worktree-cancelled-creations/<sessionId 的 SHA-256>`,空文件原子排他创建;不含路径、草稿或关联密钥。保留以拒绝重启后迟到的创建请求,不按超时删除。只在核实未被任务认领后写入。同路径加 `.lock` 是可释放的跨进程操作锁,复用既有锁协议;同一 profile、同一任务的创建登记与取消回收串行,拿不到锁不得确认回收完成。异步创建完成后、登记前再次核对取消标记 || Mobile 已取消创建的草稿 | 复用账号隔离的 durable outbox;持久创建流程先保存草稿、原项目目录和附件,再登记 reservation 和发送远端 worktree 创建;创建回包前暂停发件箱投递。回收确认后,`creation.cancelled` 与原项目目录先持久写入,再忘记回收账本。重建使用新远端 ID,`storageSessionId` 保持原 AsyncStorage 键和附件目录,通过单次记录写入提交;写入失败时原草稿仍可读。编辑页恢复目录时重新探测资格,不沿用旧 worktree 的资格或分支偏好 || 可丢弃的临时数据 | `app.getPath('temp')` 或 `os.tmpdir()` 下的任务专属目录 |diff --git a/docs/local-agent-api.md b/docs/local-agent-api.mdindex 61c5229bec..99e204e6d1 100644--- a/docs/local-agent-api.md+++ b/docs/local-agent-api.md@@ -19,6 +19,28 @@ node scripts/examples/local-agent-client.mjs --discovery "<profile>/local-agent/示例令牌只在进程内存中,退出时关闭自己的会话并撤销自己的授权,不打印、保存或复用令牌。需要长期连接的产品自行通过 OS 凭据库保存此应用令牌;不得复制供应商登录。命令行参数不接收秘密。`--list-models` 不调用模型生成。+## 开发连接码(可选增量)++开发构建在 **设置 → 远程连接 → 本机应用连接 → 开发连接** 提供“复制连接码”。正式构建隐藏这一行。Main 只从本进程当前持有租约、owner 仍有效的 ready server 内存生成码,不读取其他实例的发现文件;启动中、未登录/未进入本地模式、`HOST_IN_USE`、启动失败或已停止均不能复制。复制时重新查询当前状态。++规范文本为 `cindy-local:v1:<port>:<instance>`:ASCII、总长60–64字符,`port` 为无前导零的十进制整数1..65535,`instance` 为已有API nonce(32字节随机值的43位无padding base64url)。原始输入最多256字符,只允许trim首尾空白,之后严格匹配上述格式;不接受内部空白、URL、host、path、query或额外字段。`v1` 对应RPC protocol=1;其他版本返回 `CONNECTION_CODE_UNSUPPORTED`,非法输入返回 `CONNECTION_CODE_INVALID`。++连接码是本机端点定位信息,不是grant/token,不包含账号、凭据、profile、源码目录、PID或稳定实例账本。没有短码服务、持久映射、公共实例目录、进程/端口扫描、TTL心跳或实例间通信。原API自己的 per-profile discovery、host.lock、owner-scoped grants和恢复记录继续保留;不是“整个API零文件”。++```sh+node scripts/examples/local-agent-client.mjs --connection-code "cindy-local:v1:<port>:<instance>" --list-models+```++独立Node示例保留 `--discovery` 旧入口,两个入口必须二选一。接码后只向 `http://127.0.0.1:<port>/rpc` 发无Bearer的 `capabilities`,携带码中nonce,拒绝重定向;握手超时750ms、响应上限32KiB。先核对protocol和instance,再核对 `features.instanceMetadata:true` 和 `instanceInfo:{kind,region}`;开发入口必须为 `kind:"development"`,region只能是global/cn/dev。缺元数据报 `INSTANCE_METADATA_UNSUPPORTED`,类型不符报 `INSTANCE_METADATA_MISMATCH`,端点代次不符报 `INSTANCE_CHANGED`,网络/超时/非法JSON不能验证时为 `CONNECTION_UNAVAILABLE`。只有握手通过后才按原 `connect/start` / 原生确认 / `connect/poll` 申请授权;拒绝、取消和超时保持原协议,不自动批准。++`instanceInfo` 是可选的两字段构建自述,版本继续使用capabilities顶层 `version`。只有实际packaged、非已验证个人构建且region非dev才是installed;unpackaged、CindyDev或个人构建均为development,不能按版本号或profile路径猜。region来自既有构建区域,默认global规则不变。元数据用于避免错连,不是对同OS用户恶意程序的发行认证。++日常正式连接继续读取调用方原先绑定的正式profile的 `local-agent/discovery.json`,然后无token核对nonce、`kind:"installed"`及预期region。共profile的开发实例若持有原host.lock,正式API仍会 `HOST_IN_USE`,该路径的discovery可能指向development;必须明确拒绝把它当正式版,不能自动改接另一实例。不同profile仍可独立连接;不新增锁接管、路由或实例协调。++旧v1端点缺身份元数据时,显式旧 `--discovery` 接入仍兼容、grants无需重建;但无法证明其正式身份,新的正式自动连接应显示legacy/unknown并提示经官方更新入口升级,不把缺字段默认当installed。没有本机API的旧安装版不可连接,不侧载或替换安装版。++每个客户端对象固定端点、nonce及自己的授权,能力查询永不带Bearer。重启/owner或API换代后码失效,重新从目标Cindy复制并握手;旧执行不迁移,消息、工具副作用和控制请求不自动重放。调用方负责临时开发覆盖及恢复正式配置,不转用其他目标token。此码仅用于同一电脑上的应用,不扩展SSH/device-link/Mobile协议。+## 发现、封装与能力目标 profile 根目录的 `local-agent/discovery.json`:diff --git a/i18n/GLOSSARY.md b/i18n/GLOSSARY.mdindex 9c26cd8f62..a37b6e7b9b 100644--- a/i18n/GLOSSARY.md+++ b/i18n/GLOSSARY.md@@ -259,6 +259,10 @@ Cindy Make 生成的本机定制应用成品。可与原版切换并沿用同一云端伙伴运行的那台电脑(docs/product-rules/cloud-companions.md §3):伙伴的 Agent、工作目录与连接只在这台电脑上,其他电脑与手机是查看和发消息的入口。手机与桌面同一叫法,伙伴设置行名、离线横幅与侧栏状态共用。英文行名用 Title Case(Main Computer),句中小写 main computer,故 checkCase 为 false。不要写成「主设备」「宿主机」或 home device(代码字段 homeDeviceId 不是界面用语)。先登记为 proposed,待桌面与手机实机走查后再定。+### Connection code++本机应用临时连接的端点定位文本,不是授权令牌;连接仍需目标 Cindy 原生确认。+### Content Update指不更换 TestFlight 或商店安装包、可通过 OTA 下发的 JS 与资源更新。当前先采用四语直译并登记为待讨论术语,避免与整包更新或测试版本更新混称。diff --git a/i18n/glossary.json b/i18n/glossary.jsonindex 2df10870fa..09dbd04053 100644--- a/i18n/glossary.json+++ b/i18n/glossary.json@@ -9,6 +9,7 @@{"id": "speech-speed", "status": "proposed", "en": "Speech speed", "translations": {"zh-CN": "语速", "zh-TW": "語速", "ja": "読み上げ速度", "ko": "읽기 속도"}, "checkCase": false, "note": "伙伴语音设置的合成语速;按伙伴保存,通话朗读、消息朗读和试听共用。区别于播放器倍速和语音输入停顿时间。"},{"id": "read-by-sentence", "status": "proposed", "en": "Read by sentence", "translations": {"zh-CN": "按句朗读", "zh-TW": "逐句朗讀", "ja": "文ごとに読み上げ", "ko": "문장별로 읽기"}, "checkCase": false, "note": "伙伴语音设置:默认在最终答复生成过程中按完整句子提前朗读;关闭后等待完整回复。需要回复后处理或无法识别最终答复阶段时延后。"},{"id": "voice-mode", "status": "proposed", "en": "Voice Mode", "translations": {"zh-CN": "语音模式", "zh-TW": "語音模式", "ja": "音声モード", "ko": "음성 모드"}, "checkCase": false, "note": "桌面伙伴一对一的连续语音交互方式;停顿发送、最终回复朗读和插话,沿用伙伴主任务。"},+ {"id":"connection-code","status":"proposed","en":"Connection code","translations":{"zh-CN":"连接码","zh-TW":"連線碼","ja":"接続コード","ko":"연결 코드"},"checkCase":false,"note":"本机应用临时连接的端点定位文本,不是授权令牌;连接仍需目标 Cindy 原生确认。"},{"id":"side-chat","status":"proposed","en":"Side chat","translations":{"zh-CN":"侧边追问","zh-TW":"側邊追問","ja":"サイドチャット","ko":"사이드 채팅"},"checkCase":false,"note":"在右侧独立提问,继承主任务已完成的上下文;追问不自动写回主任务。"},{"id": "detached-head", "status": "proposed", "en": "Detached HEAD", "translations": {"zh-CN": "分离 HEAD", "zh-TW": "分離 HEAD", "ja": "Detached HEAD", "ko": "Detached HEAD"}, "checkCase": false, "note": "沿用会话顶栏分支徽标现有译法"},{"id": "mivo-library", "status": "proposed", "en": "Mivo Library", "translations": {"zh-CN": "Mivo 作品库", "zh-TW": "Mivo 作品庫", "ja": "Mivo ライブラリ", "ko": "Mivo 라이브러리"}, "note": "#5929:引用目录系统项沿用 Mivo 品牌,仅本地化展示;通用 library 能力的品牌命名仍待维护者裁决。"},diff --git a/scripts/examples/local-agent-client.mjs b/scripts/examples/local-agent-client.mjsindex 61a76d71a2..7699cc9702 100644--- a/scripts/examples/local-agent-client.mjs+++ b/scripts/examples/local-agent-client.mjs@@ -11,9 +11,37 @@ export class LocalAgentApiError extends Error {constructor(code, message) { super(message); this.name = 'LocalAgentApiError'; this.code = code; }}+/** The code is an ephemeral loopback locator, never an application grant. */+export function parseConnectionCode(input) {+ if (typeof input !== 'string' || input.length > 256) throw new LocalAgentApiError('CONNECTION_CODE_INVALID', 'Invalid connection code.');+ const code = input.trim();+ if (/^cindy-local:v[0-9]+:/.test(code) && !code.startsWith('cindy-local:v1:'))+ throw new LocalAgentApiError('CONNECTION_CODE_UNSUPPORTED', 'Unsupported connection code version.');+ const match = /^cindy-local:v1:([1-9][0-9]{0,4}):([A-Za-z0-9_-]{43})$/.exec(code);+ if (!match || Number(match[1]) > 65535) throw new LocalAgentApiError('CONNECTION_CODE_INVALID', 'Invalid connection code.');+ return { protocol: 1, port: Number(match[1]), instance: match[2] };+}++async function readCapabilities(response) {+ const reader = response.body?.getReader();+ if (!reader) throw new LocalAgentApiError('INVALID_REPLY', 'Missing capabilities reply.');+ const chunks = [];+ let size = 0;+ try {+ for (;;) {+ const { value, done } = await reader.read();+ if (done) break;+ size += value.byteLength;+ if (size > 32 * 1024) throw new LocalAgentApiError('TOO_LARGE', 'Capabilities reply exceeds the limit.');+ chunks.push(Buffer.from(value));+ }+ return JSON.parse(Buffer.concat(chunks, size).toString('utf8'));+ } finally { await reader.cancel().catch(() => {}); }+}+/** Intentionally independent of Cindy/HHH packages; credentials live only in this process. */export class LocalAgentClient {- #base; #instance; #identity; #token; #prefix = randomUUID(); #sequence = 0;+ #base; #instance; #identity; #token; #development = false; #prefix = randomUUID(); #sequence = 0;constructor(discovery, identity) {if (discovery.protocol !== 1 || !Number.isInteger(discovery.port) || discovery.port < 1 || discovery.port > 65535|| typeof discovery.instance !== 'string' || !discovery.instance) {@@ -26,20 +54,37 @@ export class LocalAgentClient {static async discover(file, identity) {return new LocalAgentClient(JSON.parse(await fs.readFile(file, 'utf8')), identity);}+ static fromConnectionCode(code, identity) {+ const client = new LocalAgentClient(parseConnectionCode(code), identity);+ client.#development = true;+ return client;+ }async request(method, params = {}, { signal } = {}) {let response;try {response = await fetch(`${this.#base}/rpc`, {- method: 'POST', signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(30_000)]) : AbortSignal.timeout(30_000),- headers: { 'Content-Type': 'application/json', ...(this.#token ? { Authorization: `Bearer ${this.#token}` } : {}) },+ method: 'POST', redirect: 'error', signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(method === 'capabilities' ? 750 : 30_000)]) : AbortSignal.timeout(method === 'capabilities' ? 750 : 30_000),+ headers: { 'Content-Type': 'application/json', ...(this.#token && method !== 'capabilities' ? { Authorization: `Bearer ${this.#token}` } : {}) },body: JSON.stringify({ version: 1, instance: this.#instance, id: `${this.#prefix}:${++this.#sequence}`, method, params }),});- const reply = await response.json();+ const reply = method === 'capabilities' ? await readCapabilities(response) : await response.json();if (reply.error) throw new LocalAgentApiError(reply.error.code, reply.error.message);if (!response.ok || !Object.hasOwn(reply, 'result')) throw new LocalAgentApiError('INVALID_REPLY', 'Invalid API reply.');+ if (method === 'capabilities') {+ if (reply.result?.protocol !== 1 || reply.result.instance !== this.#instance)+ throw new LocalAgentApiError('INSTANCE_CHANGED', 'The endpoint changed. Copy a new connection code.');+ if (this.#development) {+ const info = reply.result.instanceInfo;+ if (reply.result.features?.instanceMetadata !== true || !info)+ throw new LocalAgentApiError('INSTANCE_METADATA_UNSUPPORTED', 'This endpoint cannot identify its build.');+ if (info.kind !== 'development' || !['global', 'cn', 'dev'].includes(info.region))+ throw new LocalAgentApiError('INSTANCE_METADATA_MISMATCH', 'This connection code is not for a development build.');+ }+ }return reply.result;} catch (error) {if (error instanceof LocalAgentApiError) throw error;+ if (method === 'capabilities') throw new LocalAgentApiError('CONNECTION_UNAVAILABLE', 'The selected endpoint could not be verified.');// Never automatically resubmit a possibly accepted send/tool/control request.throw new LocalAgentApiError('RESULT_UNKNOWN', `The ${method} reply was not received. The request may have been accepted; it was not resent.`);}@@ -75,18 +120,20 @@ export class LocalAgentClient {export async function main(argv = process.argv.slice(2)) {const { values } = parseArgs({ args: argv, options: {- help: { type: 'boolean' }, discovery: { type: 'string' }, model: { type: 'string' }, provider: { type: 'string' },+ help: { type: 'boolean' }, discovery: { type: 'string' }, 'connection-code': { type: 'string' }, model: { type: 'string' }, provider: { type: 'string' },engine: { type: 'string' }, cwd: { type: 'string' }, prompt: { type: 'string' }, 'list-models': { type: 'boolean' },'native-tools': { type: 'boolean' }, 'client-id': { type: 'string' }, 'client-name': { type: 'string' },} });if (values.help) {- console.log('Usage: node scripts/examples/local-agent-client.mjs --discovery <profile>/local-agent/discovery.json [--list-models] [--provider <id>] [--engine pi|codex|claude-code] [--model <opaque-id>] [--prompt <text>] [--cwd <folder>] [--native-tools] [--client-id <id>] [--client-name <name>]');+ console.log('Usage: node scripts/examples/local-agent-client.mjs (--discovery <profile>/local-agent/discovery.json | --connection-code <code>) [--list-models] [--provider <id>] [--engine pi|codex|claude-code] [--model <opaque-id>] [--prompt <text>] [--cwd <folder>] [--native-tools] [--client-id <id>] [--client-name <name>]');return;}- if (!values.discovery) throw new LocalAgentApiError('DISCOVERY_REQUIRED', 'Pass --discovery with the intended Cindy profile. No profiles are scanned.');- const client = await LocalAgentClient.discover(values.discovery, {+ if (Boolean(values.discovery) === Boolean(values['connection-code'])) throw new LocalAgentApiError('DISCOVERY_REQUIRED', 'Pass exactly one of --discovery or --connection-code. No profiles are scanned.');+ const identity = {id: values['client-id'] ?? 'org.example.cindy-client', name: values['client-name'] ?? 'Independent API example', version: '1.0',- });+ };+ const client = values['connection-code'] ? LocalAgentClient.fromConnectionCode(values['connection-code'], identity)+ : await LocalAgentClient.discover(values.discovery, identity);const controller = new AbortController();const stop = () => controller.abort();process.once('SIGINT', stop);