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。

fix(desktop): 修复分享供应商「本任务总是允许」在并发与 Worker 重建后失效

fmfsaisaic78b6a7807a0
diff --git a/apps/desktop/src/main/remote-agent/__tests__/roundtrip.test.ts b/apps/desktop/src/main/remote-agent/__tests__/roundtrip.test.ts
index 3aa6bd756b..d472c7de2b 100644
--- a/apps/desktop/src/main/remote-agent/__tests__/roundtrip.test.ts
+++ b/apps/desktop/src/main/remote-agent/__tests__/roundtrip.test.ts
@@ -21,6 +21,7 @@ import { MAIN_OWNED_SEND_CONTEXT } from '@cindy/maker-core';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { RemoteAgentPoller } from '../controller/poller';
+import { credentialGrantFor } from '../executor/credentialGrants';
import { startRemoteAgentSession, type StartRemoteAgentDeps } from '../controller/startRemote';
import { createRemoteAgentHost, type HostedStartInput } from '../host/runHost';
import { PROVIDER_SHARE_CREDENTIAL_SESSION_APPROVAL } from '../../../shared/providerShareCredentialConsent';
@@ -258,6 +259,73 @@ describe('remote agent round trip', () => {
host.dispose();
}
});
+ it('restores a task-level credential grant when the agent is rebuilt with the same share and permission mode', async () => {
+ const env = path.join(project, '.env');
+ fs.writeFileSync(env, 'TOKEN=one');
+ const host = createRemoteAgentHost({
+ isAgentAvailable: () => true,
+ startHosted: async (input) => fakeHostedAgent(input, [env]),
+ isControllerAuthorized: () => true,
+ captureOwner: () => 'owner',
+ isOwnerCurrent: () => true,
+ runsRoot: hostRoot,
+ });
+ const sessionId = `grant-${randomUUID()}`;
+ const full = { sessionId, workingDir: project, model: 'm', permissionMode: 'bypassPermissions' as const };
+ const depsFor = (deviceId: string) => ({
+ ...makeDeps(host),
+ credentialConsent: { description: 'Only this task.', grant: credentialGrantFor(sessionId, deviceId) },
+ });
+ let localConfirmations = 0;
+ // 打开一次 Agent、跑一轮、关闭(相当于 Orca Worker 一轮结束后被回收)。
+ const openRunClose = async (
+ opts: typeof full | (Omit<typeof full, 'permissionMode'> & { permissionMode: 'default' }),
+ deviceId = 'share:a',
+ between?: (handle: AgentSessionHandle) => Promise<void>,
+ ) => {
+ const handle = await startRemoteAgentSession('pi', opts, depsFor(deviceId));
+ try {
+ handle.setInteractionResolver(async (request) => {
+ if (request.requestId !== 'forged') localConfirmations += 1;
+ return { kind: 'permission', behavior: 'allow', permissionUpdates: [PROVIDER_SHARE_CREDENTIAL_SESSION_APPROVAL] };
+ });
+ const reader = (async () => {
+ for await (const event of handle.events()) if (event.type === 'done') return;
+ })();
+ await handle.send({ type: 'user', content: 'read credentials' });
+ await reader;
+ await between?.(handle);
+ } finally {
+ await handle.close({ reason: 'navigation' });
+ }
+ };
+ try {
+ await openRunClose(full);
+ expect(localConfirmations).toBe(1);
+ // 同一任务、同一分享、权限档未变:重建后不再确认。
+ await openRunClose(full);
+ expect(localConfirmations).toBe(1);
+ // 另一个分享不沿用。
+ await openRunClose(full, 'share:b');
+ expect(localConfirmations).toBe(2);
+ // 回收期间权限档变了:作废,换回原权限档也要重新确认。
+ await openRunClose({ ...full, permissionMode: 'default' });
+ expect(localConfirmations).toBe(3);
+ await openRunClose(full);
+ expect(localConfirmations).toBe(4);
+ // 运行中切换权限档:作废,重建后也不恢复。
+ await openRunClose(full, 'share:a', async (handle) => {
+ await handle.setPermissionMode?.('default');
+ await handle.setPermissionMode?.('bypassPermissions');
+ });
+ expect(localConfirmations).toBe(4);
+ await openRunClose(full);
+ expect(localConfirmations).toBe(5);
+ } finally {
+ host.dispose();
+ }
+ });
+
it('runs a turn on the other computer while files, commands and confirmations stay here', async () => {
const host = createHost();
const handle = await startRemoteAgentSession('pi', {
diff --git a/apps/desktop/src/main/remote-agent/controller/service.ts b/apps/desktop/src/main/remote-agent/controller/service.ts
index 24ff36a8c0..ab0a72f701 100644
--- a/apps/desktop/src/main/remote-agent/controller/service.ts
+++ b/apps/desktop/src/main/remote-agent/controller/service.ts
@@ -24,6 +24,7 @@ import type {
} from '@cindy/maker-core';
import { resolveMemoryScopeKey } from '@cindy/maker-core';
+import { credentialGrantFor } from '../executor/credentialGrants';
import type { ExecutorCaptureHooks } from '../executor/executor';
import type { PdfTextExtractor } from '../executor/files';
import type { GuardedFetch } from '../executor/webFetch';
@@ -83,7 +84,7 @@ const SHARED_PROVIDER_CREDENTIAL_NOTICE =
"This task uses a shared provider, so what the agent reads passes through the sharer's computer or another computer they arrange. "
+ 'This may involve credentials, so it needs your confirmation. '
+ 'Always allow for this session skips further shared-provider credential confirmations in this task. '
- + 'Reopening the task or changing its permission mode requires confirmation again.';
+ + 'Changing its permission mode or quitting Cindy requires confirmation again.';
function mcpTargets(extra: PiExtraSpawnConfig | null): Map<string, LocalMcpTarget> {
const targets = new Map<string, LocalMcpTarget>();
@@ -192,7 +193,12 @@ export function createDeviceAgentStarter(deps: DeviceAgentServiceDeps) {
: {}),
...(webFetch ? { webFetch } : {}),
...(shared
- ? { credentialConsent: { description: deps.sharedProviderCredentialNotice?.() ?? SHARED_PROVIDER_CREDENTIAL_NOTICE } }
+ ? {
+ credentialConsent: {
+ description: deps.sharedProviderCredentialNotice?.() ?? SHARED_PROVIDER_CREDENTIAL_NOTICE,
+ ...(sessionId ? { grant: credentialGrantFor(sessionId, input.deviceId) } : {}),
+ },
+ }
: {}),
prepareMcp: async ({ kind, opts: startOpts, vendorOptions }): Promise<PreparedRemoteMcp> => {
const extra = await deps.prepareMcpBridge(deps.mcpProviders(), deps.logger, {
diff --git a/apps/desktop/src/main/remote-agent/controller/startRemote.ts b/apps/desktop/src/main/remote-agent/controller/startRemote.ts
index c7bfed7517..bd3b7f0eca 100644
--- a/apps/desktop/src/main/remote-agent/controller/startRemote.ts
+++ b/apps/desktop/src/main/remote-agent/controller/startRemote.ts
@@ -19,6 +19,7 @@ import {
import type { AgentEvent, AgentSessionHandle, StartSessionOptions } from '@cindy/maker-core';
import { PROVIDER_SHARE_CREDENTIAL_SESSION_APPROVAL } from '../../../shared/providerShareCredentialConsent';
+import type { CredentialGrantRecord } from '../executor/credentialGrants';
import { RemoteExecutor, type ExecutorCaptureHooks } from '../executor/executor';
import type { PdfTextExtractor } from '../executor/files';
import { ExecutorGate, executorGateModeFor, type ExecutorAction } from '../executor/gate';
@@ -91,9 +92,10 @@ export interface StartRemoteAgentDeps {
/**
* 供应商分享的受邀者任务(docs/product-rules/provider-sharing.md §9 第 7 条):读写凭证类文件、执行读取
* 凭证的命令不论权限档都要本机用户确认,没有批准时在本机弹确认卡;`description` 是卡上的说明。
- * 同账号任务不提供。
+ * 同账号任务不提供。`grant` 是这个任务在这个分享上的「本任务总是允许」记录,Agent 实例被系统回收
+ * 重建后据此恢复;缺省时授权只在本次启动的执行器内有效。
*/
- credentialConsent?: { description: string };
+ credentialConsent?: { description: string; grant?: CredentialGrantRecord };
/** 改写来自对方的事件(如工具名)。 */
mapEvent?: (kind: RemoteAgentKind) => ((event: AgentEvent) => AgentEvent) | undefined;
/** 本机 Codex 程序(给对方的 Codex 提供 exec-server 执行环境);缺省时不提供。 */
@@ -223,6 +225,8 @@ export async function startRemoteAgentSession(
const gate = new ExecutorGate(workspace, executorGateModeFor(opts.permissionMode, opts.planMode === true), Date.now, {
confirmCredentials: credentialConsent !== undefined,
});
+ // 同一任务、同一分享、权限档未变时恢复之前的「本任务总是允许」(Orca Worker 等会在两轮之间被回收重建)。
+ if (credentialConsent?.grant?.restore(gate.getMode())) gate.allowCredentialsForSession();
let controller: RemoteAgentHandleController | null = null;
const executor = new RemoteExecutor({
workspace,
@@ -236,6 +240,7 @@ export async function startRemoteAgentSession(
? {
confirm: async (action: ExecutorAction) =>
controller?.confirm(credentialConfirmation(action, credentialConsent.description)) ?? false,
+ ...(credentialConsent.grant ? { credentialGrant: credentialConsent.grant } : {}),
}
: {}),
});
diff --git a/apps/desktop/src/main/remote-agent/credentials.ts b/apps/desktop/src/main/remote-agent/credentials.ts
index 95dd6bb825..87155a21c2 100644
--- a/apps/desktop/src/main/remote-agent/credentials.ts
+++ b/apps/desktop/src/main/remote-agent/credentials.ts
@@ -3,7 +3,7 @@
*
* 受邀者任务的对话与 Agent 读到的文件内容会经过分享者的电脑。凭证类文件(密钥、.env、云与工具的
* 登录凭证)不论权限档,都要受邀者在本机确认后才发出:启动时不随项目说明同步,任务中读取时弹确认卡,
- * 可明确允许当前任务后续的凭证操作;关闭、重新打开任务或切换权限档后恢复确认
+ * 可明确允许当前任务后续的凭证操作;切换权限档或退出应用后恢复确认
* (docs/product-rules/provider-sharing.md §9 第 7 条)。
*
* 规则沿用本机任务的凭证规则(isSensitiveCredentialPath),只有一处不同:Claude Code / Codex 配置目录里
diff --git a/apps/desktop/src/main/remote-agent/executor/__tests__/executor.test.ts b/apps/desktop/src/main/remote-agent/executor/__tests__/executor.test.ts
index 70e700c448..e4b1b1b671 100644
--- a/apps/desktop/src/main/remote-agent/executor/__tests__/executor.test.ts
+++ b/apps/desktop/src/main/remote-agent/executor/__tests__/executor.test.ts
@@ -5,7 +5,7 @@ import path from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { handleExecMcpRequest } from '../ccMcp';
-import { RemoteExecutor, type ExecutorConfirmation } from '../executor';
+import { RemoteExecutor, type ExecutorConfirmation, type RemoteExecutorOptions } from '../executor';
import { EXECUTOR_APPROVAL_TTL_MS, ExecutorGate, executorGateModeFor, type ExecutorAction } from '../gate';
import type { PdfTextExtractor } from '../files';
import { findWindowsGitBash, truncateOutput } from '../shell';
@@ -581,6 +581,7 @@ describe('shared provider credentials', () => {
function sharedExecutor(
mode: ReturnType<typeof executorGateModeFor>,
confirm?: (action: ExecutorAction) => Promise<ExecutorConfirmation>,
+ credentialGrant?: RemoteExecutorOptions['credentialGrant'],
) {
const workspace = new ExecutorWorkspace({ workingDir: project });
const gate = new ExecutorGate(workspace, mode, Date.now, { confirmCredentials: true });
@@ -590,10 +591,42 @@ describe('shared provider credentials', () => {
rgPath: RG,
tempDir: path.join(root, 'tmp'),
...(confirm ? { confirm } : {}),
+ ...(credentialGrant ? { credentialGrant } : {}),
});
return { executor, gate, workspace };
}
+ it('records only an explicit task-level grant and clears it when the permission mode changes', async () => {
+ const env: ExecutorAction = { kind: 'exec', command: 'cat .env', cwd: project };
+ for (const answer of [true, false, 'session'] as const) {
+ const credentialGrant = { remember: vi.fn(), forget: vi.fn() };
+ const { executor } = sharedExecutor('normal', async () => answer, credentialGrant);
+ try {
+ expect(await executor.confirm(env)).toBe(answer !== false);
+ if (answer === 'session') expect(credentialGrant.remember).toHaveBeenCalledWith('normal');
+ else expect(credentialGrant.remember).not.toHaveBeenCalled();
+ executor.setGateMode('full');
+ expect(credentialGrant.forget).toHaveBeenCalledTimes(1);
+ } finally {
+ await executor.close();
+ }
+ }
+ // 卡片回答前请求被取消:不记录。
+ let answer!: (result: ExecutorConfirmation) => void;
+ const credentialGrant = { remember: vi.fn(), forget: vi.fn() };
+ const { executor } = sharedExecutor('full', () => new Promise((resolve) => { answer = resolve; }), credentialGrant);
+ const abort = new AbortController();
+ try {
+ const pending = executor.confirm(env, abort.signal);
+ abort.abort();
+ answer('session');
+ expect(await pending).toBe(false);
+ expect(credentialGrant.remember).not.toHaveBeenCalled();
+ } finally {
+ await executor.close();
+ }
+ });
+
it('holds credential reads, writes and commands even with full access, and nothing else', () => {
const { gate, workspace } = sharedExecutor('full');
const secret = path.join(os.homedir(), '.ssh', 'id_rsa');
@@ -685,6 +718,162 @@ describe('shared provider credentials', () => {
}
});
+ it('asks once for concurrent credential operations when the user allows the session', async () => {
+ const answers: Array<(result: ExecutorConfirmation) => void> = [];
+ const confirm = vi.fn(() => new Promise<ExecutorConfirmation>((resolve) => { answers.push(resolve); }));
+ const { executor } = sharedExecutor('full', confirm);
+ const first: ExecutorAction = { kind: 'exec', command: 'cat .env', cwd: project };
+ const second: ExecutorAction = { kind: 'exec', command: 'cat .env.production', cwd: project };
+ const pending = [executor.confirm(first), executor.confirm(second)];
+ try {
+ expect(confirm).toHaveBeenCalledTimes(1);
+ answers[0]('session');
+ expect(await Promise.all(pending)).toEqual([true, true]);
+ expect(executor.check(first).ok).toBe(true);
+ expect(executor.check(second).ok).toBe(true);
+ expect(confirm).toHaveBeenCalledTimes(1);
+ } finally {
+ await executor.close();
+ for (const answer of answers) answer(false);
+ await Promise.all(pending);
+ }
+ });
+
+ it.each([true, false, 'failed'] as const)('keeps concurrent requests independent after the first answer is %s', async (answer) => {
+ let resolve!: (result: ExecutorConfirmation) => void;
+ let reject!: (error: Error) => void;
+ const confirm = vi.fn<(action: ExecutorAction) => Promise<ExecutorConfirmation>>()
+ .mockImplementationOnce(() => new Promise<ExecutorConfirmation>((done, fail) => { resolve = done; reject = fail; }))
+ .mockResolvedValue(false);
+ const { executor } = sharedExecutor('full', confirm);
+ const first: ExecutorAction = { kind: 'exec', command: 'cat .env', cwd: project };
+ const second: ExecutorAction = { kind: 'exec', command: 'cat .env.production', cwd: project };
+ const pending = [executor.confirm(first), executor.confirm(second)];
+ try {
+ expect(confirm).toHaveBeenCalledTimes(1);
+ if (answer === 'failed') reject(new Error('confirmation failed'));
+ else resolve(answer);
+ expect(await Promise.all(pending)).toEqual([answer === true, false]);
+ expect(confirm).toHaveBeenCalledTimes(2);
+ expect(confirm).toHaveBeenNthCalledWith(2, second);
+ expect(executor.check(first).ok).toBe(answer === true);
+ expect(executor.check(first).ok).toBe(false);
+ expect(executor.check(second).ok).toBe(false);
+ } finally {
+ await executor.close();
+ resolve(false);
+ await Promise.all(pending);
+ }
+ });
+
+ it.each(['cancel', 'close', 'permission-change'] as const)('does not show or grant a queued confirmation after %s', async (end) => {
+ let answer!: (result: ExecutorConfirmation) => void;
+ const confirm = vi.fn(() => new Promise<ExecutorConfirmation>((resolve) => { answer = resolve; }));
+ const { executor, gate } = sharedExecutor('full', confirm);
+ const first: ExecutorAction = { kind: 'exec', command: 'cat .env', cwd: project };
+ const second: ExecutorAction = { kind: 'exec', command: 'cat .env.production', cwd: project };
+ const abort = new AbortController();
+ const pending = [executor.confirm(first), executor.confirm(second, abort.signal)];
+ try {
+ expect(confirm).toHaveBeenCalledTimes(1);
+ if (end === 'cancel') abort.abort();
+ else if (end === 'close') await executor.close();
+ else {
+ executor.setGateMode('normal');
+ executor.setGateMode('full');
+ }
+ answer('session');
+ expect(await Promise.all(pending)).toEqual([end === 'cancel', false]);
+ expect(confirm).toHaveBeenCalledTimes(1);
+ expect(gate.needsCredentialConsent(first)).toBe(end !== 'cancel');
+ } finally {
+ await executor.close();
+ answer(false);
+ await Promise.all(pending);
+ }
+ });
+
+ it('lets a cancelled queued request leave at once while later requests still wait for the open card', async () => {
+ const answers: Array<(result: ExecutorConfirmation) => void> = [];
+ const confirm = vi.fn(() => new Promise<ExecutorConfirmation>((resolve) => { answers.push(resolve); }));
+ const { executor } = sharedExecutor('full', confirm);
+ const first: ExecutorAction = { kind: 'exec', command: 'cat .env', cwd: project };
+ const second: ExecutorAction = { kind: 'exec', command: 'cat .env.production', cwd: project };
+ const third: ExecutorAction = { kind: 'exec', command: 'cat .env.local', cwd: project };
+ const abort = new AbortController();
+ const pending = [executor.confirm(first), executor.confirm(second, abort.signal), executor.confirm(third)];
+ try {
+ abort.abort();
+ // 第一张卡还没回答,排队中被取消的请求不必等它。
+ expect(await pending[1]).toBe(false);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(confirm).toHaveBeenCalledTimes(1);
+ answers[0](true);
+ expect(await pending[0]).toBe(true);
+ await vi.waitFor(() => expect(confirm).toHaveBeenCalledTimes(2));
+ expect(confirm).toHaveBeenNthCalledWith(2, third);
+ answers[1](true);
+ expect(await pending[2]).toBe(true);
+ } finally {
+ await executor.close();
+ for (const answer of answers) answer(false);
+ await Promise.all(pending);
+ }
+ });
+
+ it('stops an open card from blocking later requests once its request is cancelled', async () => {
+ const answers: Array<(result: ExecutorConfirmation) => void> = [];
+ const confirm = vi.fn(() => new Promise<ExecutorConfirmation>((resolve) => { answers.push(resolve); }));
+ const { executor, gate } = sharedExecutor('full', confirm);
+ const first: ExecutorAction = { kind: 'exec', command: 'cat .env', cwd: project };
+ const second: ExecutorAction = { kind: 'exec', command: 'cat .env.production', cwd: project };
+ const abort = new AbortController();
+ const pending = [executor.confirm(first, abort.signal), executor.confirm(second)];
+ try {
+ expect(confirm).toHaveBeenCalledTimes(1);
+ abort.abort();
+ await vi.waitFor(() => expect(confirm).toHaveBeenCalledTimes(2));
+ expect(confirm).toHaveBeenNthCalledWith(2, second);
+ // 已取消请求的卡片之后再回答,不建立任务授权。
+ answers[0]('session');
+ expect(await pending[0]).toBe(false);
+ expect(gate.needsCredentialConsent(second)).toBe(true);
+ answers[1](true);
+ expect(await pending[1]).toBe(true);
+ } finally {
+ await executor.close();
+ for (const answer of answers) answer(false);
+ await Promise.all(pending);
+ }
+ });
+
+ it('keeps ordinary permission limits and other tasks independent of a queued session grant', async () => {
+ let answer!: (result: ExecutorConfirmation) => void;
+ const confirm = vi.fn(() => new Promise<ExecutorConfirmation>((resolve) => { answer = resolve; }));
+ const { executor } = sharedExecutor('plan', confirm);
+ const otherConfirm = vi.fn(async (): Promise<ExecutorConfirmation> => false);
+ const other = sharedExecutor('full', otherConfirm).executor;
+ const first: ExecutorAction = { kind: 'read', path: path.join(project, '.env') };
+ const second: ExecutorAction = { kind: 'write', path: path.join(project, '.env.production') };
+ const pending = [executor.confirm(first), executor.confirm(second)];
+ try {
+ // 一个 Worker 等待确认,不阻塞另一任务,也不把任务授权扩展过去。
+ expect(await other.confirm(first)).toBe(false);
+ expect(otherConfirm).toHaveBeenCalledTimes(1);
+ answer('session');
+ expect(await Promise.all(pending)).toEqual([true, true]);
+ expect(confirm).toHaveBeenCalledTimes(1);
+ expect(executor.check(first).ok).toBe(true);
+ expect(executor.check(second).ok).toBe(false);
+ expect(other.check(first).ok).toBe(false);
+ } finally {
+ await executor.close();
+ await other.close();
+ answer(false);
+ await Promise.all(pending);
+ }
+ });
+
it('keeps allow-once commands one-time and revokes the session grant when the permission mode is set', async () => {
const command: ExecutorAction = { kind: 'exec', command: 'cat .env', cwd: project };
const confirm = vi.fn(async () => true);
diff --git a/apps/desktop/src/main/remote-agent/executor/credentialGrants.ts b/apps/desktop/src/main/remote-agent/executor/credentialGrants.ts
new file mode 100644
index 0000000000..9c0c0ba6aa
--- /dev/null
+++ b/apps/desktop/src/main/remote-agent/executor/credentialGrants.ts
@@ -0,0 +1,39 @@
+/**
+ * 供应商分享受邀者任务的「本任务总是允许」,按任务记在本机主进程内存里
+ * (docs/product-rules/provider-sharing.md §9 第 7 条)。
+ *
+ * 执行器随 Agent 实例关闭,而 Agent 实例会被系统回收后重建(如 Orca Worker 一轮结束后释放进程)。
+ * 只记在执行器里时,这类重建会让用户每轮都要重新确认。这里按「任务 + 分享」记住授权时的权限档:
+ * 重建时权限档一致才恢复,不一致即作废;权限档变化时由执行器删除。不落盘,退出应用即失效。
+ */
+import type { ExecutorGateMode } from './gate';
+
+export interface CredentialGrantRecord {
+ /** 新执行器启动时调用:之前在同一权限档下授权过就返回 true;权限档不一致时作废记录。 */
+ restore(mode: ExecutorGateMode): boolean;
+ /** 本机用户选择了「本任务总是允许」。 */
+ remember(mode: ExecutorGateMode): void;
+ /** 权限档变化:授权失效。 */
+ forget(): void;
+}
+
+const grants = new Map<string, ExecutorGateMode>();
+
+/** 某个任务在某个分享(Agent 所在的 `share:` 设备)上的授权记录。 */
+export function credentialGrantFor(sessionId: string, deviceId: string): CredentialGrantRecord {
+ const key = JSON.stringify([sessionId, deviceId]);
+ return {
+ restore(mode) {
+ const granted = grants.get(key);
+ if (granted === mode) return true;
+ grants.delete(key);
+ return false;
+ },
+ remember(mode) {
+ grants.set(key, mode);
+ },
+ forget() {
+ grants.delete(key);
+ },
+ };
+}
diff --git a/apps/desktop/src/main/remote-agent/executor/executor.ts b/apps/desktop/src/main/remote-agent/executor/executor.ts
index 6d0fcece34..67870406fa 100644
--- a/apps/desktop/src/main/remote-agent/executor/executor.ts
+++ b/apps/desktop/src/main/remote-agent/executor/executor.ts
@@ -32,6 +32,7 @@ import {
type RipgrepRunner,
type ToolResult,
} from './files';
+import type { CredentialGrantRecord } from './credentialGrants';
import type { ExecutorAction, ExecutorGate, ExecutorGateDecision, ExecutorGateMode } from './gate';
import { piGrep, type PiGrepInput } from './search';
import { resolveExecutorShell, runOnce, ShellSession } from './shell';
@@ -46,7 +47,7 @@ export interface ExecutorCaptureHooks {
noteOpaqueWrite(): void;
}
-/** `session` 仅免除当前执行器的分享凭证确认,普通权限上限仍由 gate 判断。 */
+/** `session` 免除当前任务后续的分享凭证确认,普通权限上限仍由 gate 判断。 */
export type ExecutorConfirmation = boolean | 'session';
export interface RemoteExecutorOptions {
@@ -65,6 +66,8 @@ export interface RemoteExecutorOptions {
* 默认只放行这一个操作;用户明确选择会话级允许后免除后续的分享凭证确认。缺省时直接拒绝。
*/
confirm?(action: ExecutorAction): Promise<ExecutorConfirmation>;
+ /** 「本任务总是允许」的任务级记录:Agent 实例被系统回收重建后据此恢复;缺省时只在本执行器内有效。 */
+ credentialGrant?: Pick<CredentialGrantRecord, 'remember' | 'forget'>;
}
export class ExecutorRequestError extends Error {
@@ -117,6 +120,7 @@ export class RemoteExecutor {
private readonly writeHooks: FileWriteHooks;
private closed = false;
private permissionGeneration = 0;
+ private credentialConfirmationTail?: Promise<void>;
constructor(private readonly opts: RemoteExecutorOptions) {
this.workspace = opts.workspace;
@@ -138,6 +142,7 @@ export class RemoteExecutor {
setGateMode(mode: ExecutorGateMode): void {
this.permissionGeneration += 1;
this.gate.setMode(mode);
+ this.opts.credentialGrant?.forget();
}
/** 本机用户在确认卡上允许了一个操作。 */
@@ -156,18 +161,46 @@ export class RemoteExecutor {
* 放行。不是凭证类、没有确认通道或任务已结束时返回 false。
*/
async confirm(action: ExecutorAction, signal?: AbortSignal): Promise<boolean> {
- if (this.closed || !this.opts.confirm || !this.gate.needsCredentialConsent(action)) return false;
+ if (this.closed || signal?.aborted || !this.opts.confirm || !this.gate.needsCredentialConsent(action)) return false;
const permissionGeneration = this.permissionGeneration;
- const allowed = await this.opts.confirm(action).catch(() => false);
- // 等确认期间任务结束、请求被取消或权限已切换:不接受旧确认。
- if ((allowed !== true && allowed !== 'session') || this.closed || signal?.aborted
- || permissionGeneration !== this.permissionGeneration) return false;
- if (allowed === 'session') {
- this.gate.allowCredentialsForSession();
- if (this.gate.getMode() === 'full') return true;
+ // 同一任务可能并行调用工具。只排队确认,不排队执行;前一张卡建立任务授权后,
+ // 后续请求重新检查,避免已经弹出的多张卡仍逐一等待用户回答。
+ // 排队位置要等前一个位置放行、且自己的卡处理完才放行。
+ const previous = this.credentialConfirmationTail;
+ let settle!: () => void;
+ const settled = new Promise<void>((resolve) => { settle = resolve; });
+ const slot = previous ? previous.then(() => settled) : settled;
+ this.credentialConfirmationTail = slot;
+ // 自己的请求取消后立即让出:还在排队就不再等(后面的请求仍等前一张卡);
+ // 卡已弹出就不再挡住后面的请求,这张卡之后的回答会被丢弃。
+ let onAbort: (() => void) | undefined;
+ const aborted = new Promise<void>((resolve) => {
+ onAbort = () => { settle(); resolve(); };
+ signal?.addEventListener('abort', onAbort, { once: true });
+ });
+ try {
+ if (previous) await Promise.race([previous, aborted]);
+ if (this.closed || signal?.aborted || permissionGeneration !== this.permissionGeneration) return false;
+ // 调用方仍会重新检查普通权限上限;这里只免除已授权的分享凭证确认。
+ if (!this.gate.needsCredentialConsent(action)) return true;
+ const allowed = await this.opts.confirm(action).catch(() => false);
+ // 等确认期间任务结束、请求被取消或权限已切换:不接受旧确认。
+ if ((allowed !== true && allowed !== 'session') || this.closed || signal?.aborted
+ || permissionGeneration !== this.permissionGeneration) return false;
+ if (allowed === 'session') {
+ this.gate.allowCredentialsForSession();
+ this.opts.credentialGrant?.remember(this.gate.getMode());
+ if (this.gate.getMode() === 'full') return true;
+ }
+ this.gate.recordApproval(action);
+ return true;
+ } finally {
+ if (onAbort) signal?.removeEventListener('abort', onAbort);
+ settle();
+ void slot.then(() => {
+ if (this.credentialConfirmationTail === slot) this.credentialConfirmationTail = undefined;
+ });
}
- this.gate.recordApproval(action);
- return true;
}
/** 检查上限;凭证类操作没有批准时先在本机问一次。 */
diff --git a/apps/desktop/src/main/remote-agent/executor/gate.ts b/apps/desktop/src/main/remote-agent/executor/gate.ts
index 2ebb32c4b2..377f4146e0 100644
--- a/apps/desktop/src/main/remote-agent/executor/gate.ts
+++ b/apps/desktop/src/main/remote-agent/executor/gate.ts
@@ -117,7 +117,10 @@ export class ExecutorGate {
this.mode = mode;
}
- /** 本机用户在凭证确认卡上选择了「本任务总是允许」。授权随执行器关闭或权限档变化失效。 */
+ /**
+ * 本机用户在凭证确认卡上选择了「本任务总是允许」,或新执行器按任务级记录恢复了这项授权
+ * (credentialGrants.ts)。权限档变化即失效。
+ */
allowCredentialsForSession(): void {
if (this.options.confirmCredentials) this.credentialsAllowedForSession = true;
}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 5cea137c0f..524b92191f 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -10186,7 +10186,7 @@
"saveEdit": "Save Text"
},
"sharedProviderCredential": {
- "description": "This task uses a shared provider, so what the Agent reads passes through the sharer’s computer or another computer they arrange. This step may involve credentials (such as keys or .env) and needs your confirmation. “Always allow for this session” skips further shared-provider credential confirmations in this task. Reopening the task or changing its permission mode requires confirmation again."
+ "description": "This task uses a shared provider, so what the Agent reads passes through the sharer’s computer or another computer they arrange. This step may involve credentials (such as keys or .env) and needs your confirmation. “Always allow for this session” skips further shared-provider credential confirmations in this task. Changing its permission mode or quitting Cindy requires confirmation again."
},
"mediaDownload": {
"title": "Download the generated media?",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 88598030d4..adcb964ae0 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -10149,7 +10149,7 @@
"saveEdit": "テキストを保存"
},
"sharedProviderCredential": {
- "description": "このタスクは共有されたプロバイダーを使うため、Agent が読み取った内容は共有元または共有元が手配したパソコンを経由します。この操作は認証情報(鍵や .env など)に関わる可能性があり、確認が必要です。「このセッションで常に許可」を選ぶと、このタスクで共有に伴う認証情報の確認を繰り返しません。タスクを開き直すか権限モードを変更すると、再度確認します。"
+ "description": "このタスクは共有されたプロバイダーを使うため、Agent が読み取った内容は共有元または共有元が手配したパソコンを経由します。この操作は認証情報(鍵や .env など)に関わる可能性があり、確認が必要です。「このセッションで常に許可」を選ぶと、このタスクで共有に伴う認証情報の確認を繰り返しません。権限モードを変更するか Cindy を終了すると、再度確認します。"
},
"mediaDownload": {
"title": "生成されたメディアをダウンロードしますか?",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 7559746485..43bd2e0cd7 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -10149,7 +10149,7 @@
"saveEdit": "텍스트 저장"
},
"sharedProviderCredential": {
- "description": "이 작업은 공유받은 제공자를 사용하므로 Agent가 읽은 내용은 공유한 사람의 컴퓨터 또는 그 사람이 지정한 컴퓨터를 거칩니다. 이 단계는 자격 증명(키, .env 등)과 관련될 수 있어 확인이 필요합니다. ‘이 세션에서 항상 허용’을 선택하면 이 작업에서 공유에 따른 자격 증명 확인을 반복하지 않습니다. 작업을 다시 열거나 권한 모드를 변경하면 다시 확인합니다."
+ "description": "이 작업은 공유받은 제공자를 사용하므로 Agent가 읽은 내용은 공유한 사람의 컴퓨터 또는 그 사람이 지정한 컴퓨터를 거칩니다. 이 단계는 자격 증명(키, .env 등)과 관련될 수 있어 확인이 필요합니다. ‘이 세션에서 항상 허용’을 선택하면 이 작업에서 공유에 따른 자격 증명 확인을 반복하지 않습니다. 권한 모드를 변경하거나 Cindy를 종료하면 다시 확인합니다."
},
"mediaDownload": {
"title": "생성된 미디어를 다운로드할까요?",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 18821bef71..a97d4a083d 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -10149,7 +10149,7 @@
"saveEdit": "保存文本"
},
"sharedProviderCredential": {
- "description": "这个任务用的是分享来的供应商,Agent 读到的内容会经过分享者或其安排的电脑。这一步可能涉及凭证(如密钥、.env),需要你确认后才继续。选择「本任务总是允许」后,本任务后续凭证操作不再额外确认;重新打开任务或切换权限档后需再次确认。"
+ "description": "这个任务用的是分享来的供应商,Agent 读到的内容会经过分享者或其安排的电脑。这一步可能涉及凭证(如密钥、.env),需要你确认后才继续。选择「本任务总是允许」后,本任务后续凭证操作不再额外确认;切换权限档或退出 Cindy 后需再次确认。"
},
"mediaDownload": {
"title": "允许下载生成的媒体?",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 0f524ff406..a3dc057d4b 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -10149,7 +10149,7 @@
"saveEdit": "儲存文字"
},
"sharedProviderCredential": {
- "description": "這個任務用的是分享來的供應商,Agent 讀到的內容會經過分享者或其安排的電腦。這一步可能涉及憑證(如金鑰、.env),需要你確認後才繼續。選擇「本任務總是允許」後,本任務後續憑證操作不再額外確認;重新開啟任務或切換權限模式後需再次確認。"
+ "description": "這個任務用的是分享來的供應商,Agent 讀到的內容會經過分享者或其安排的電腦。這一步可能涉及憑證(如金鑰、.env),需要你確認後才繼續。選擇「本任務總是允許」後,本任務後續憑證操作不再額外確認;切換權限模式或結束 Cindy 後需再次確認。"
},
"mediaDownload": {
"title": "允許下載產生的媒體?",
diff --git a/docs/product-rules/provider-sharing.md b/docs/product-rules/provider-sharing.md
index 2eccaee24b..ad39eadd68 100644
--- a/docs/product-rules/provider-sharing.md
+++ b/docs/product-rules/provider-sharing.md
@@ -281,13 +281,15 @@ Desktop「设置 → 模型供应商」的左栏(2026-10-08 用户裁决):
Skill、子代理、命令与说明文字不算)不随项目说明与个人配置在启动时同步,链接按真实目标判断;
- 任务中读写凭证类文件、执行读取或打出凭证的命令,不论权限档(含完全访问)都要受邀者在本机确认卡上
允许,默认只放行这一次。确认卡同时提供「本任务总是允许」(2026-10-12 用户确认):受邀者明确选择后,
- 当前任务运行期间不再额外确认凭证操作,Pi 的搜索结果也可包含凭证内容;只在本机执行器内存里记住,
- 关闭、重新打开任务或切换权限档后恢复确认,不扩展到其他任务或供应商分享。原权限档的其他限制仍然生效,
+ 当前任务不再额外确认凭证操作,Pi 的搜索结果也可包含凭证内容。授权按「任务 + 分享」只记在本机
+ 主进程内存里(2026-10-13 用户裁决):Agent 实例被系统回收后重建(如 Orca Worker 一轮结束后释放进程)
+ 时,权限档未变就沿用;切换权限档(含回收期间改了权限档)或退出应用后恢复确认,不扩展到其他任务或
+ 供应商分享。已知代价:归档后恢复的任务在本次应用运行期间沿用之前的授权。原权限档的其他限制仍然生效,
启动同步仍排除凭证文件。确认卡说明内容会经过分享者或其安排的电脑,以及这项授权的范围与失效时机。
确认卡与 Agent 的确认走同一通道,手机远控与 IM 也能处理;
- 命令只能按命令文本识别(脚本里读的、编码后再解开的认不出来),是防误发,不是防恶意。
同账号远程供应商不受影响:与本机一致,项目与个人配置里的符号链接一律跟随,不额外确认。
- 实现:`apps/desktop/src/main/remote-agent/{credentials.ts,executor/gate.ts,controller/projectFiles.ts}`。
+ 实现:`apps/desktop/src/main/remote-agent/{credentials.ts,executor/gate.ts,executor/credentialGrants.ts,controller/projectFiles.ts}`。
## 10. 与现有规则的关系