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: suppress repeated task consent and reject archived team starts

Dasha66b0b1bd624
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostIpcSenderTrust.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostIpcSenderTrust.test.ts
index 94da96f5d8..cf06946b60 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostIpcSenderTrust.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostIpcSenderTrust.test.ts
@@ -41,6 +41,13 @@ function handlerBlock(source: string, channel: string): string {
describe('高权限 ghost IPC 的来源闸(源码契约)', () => {
const source = fs.readFileSync(path.join(__dirname, '..', 'index.ts'), 'utf8');
+ it('keeps task permission retry behind the trusted Host sender gate', () => {
+ const block = handlerBlock(source, 'ghosts:request-task-approval');
+ expect(block.indexOf('assertTrustedAppRendererEvent(event)')).toBeLessThan(block.indexOf('requestPluginTaskApproval'));
+ expect(block).toContain('requireGhostAvailableForActiveSession(id)');
+ expect(block).toContain("purpose: 'task-capability'");
+ });
+
for (const channel of TRUSTED_SENDER_CHANNELS) {
it(`${channel} 断言 assertTrustedAppRendererEvent 且不吞 sender`, () => {
const block = handlerBlock(source, channel);
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/taskCapability.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/taskCapability.test.ts
index d2416fed07..660bdda81f 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/taskCapability.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/taskCapability.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it, vi } from 'vitest';
-import { ensurePluginTaskApproval, hasPluginTaskApproval } from '../taskCapability.js';
+import { ensurePluginTaskApproval, hasPluginTaskApproval, PluginTaskApprovalGate } from '../taskCapability.js';
import { handlePluginTaskRequest } from '../taskSlot.js';
import type { InstalledGhost } from '../../../shared/ghost.js';
@@ -21,6 +21,29 @@ const legacy = () =>
}) as InstalledGhost;
describe('explicit task capability approval', () => {
+ it.each(['denied', 'timeout', 'error'] as const)('suppresses serial automatic prompts after %s until Host retry', async outcome => {
+ const gate = new PluginTaskApprovalGate();
+ const attempt = vi.fn(async () => { if (outcome === 'error') throw new Error('no UI'); return false; });
+ await gate.request('p', 'owner:revision', false, attempt).catch(() => false);
+ for (let i = 0; i < 20; i++) expect(await gate.request('p', 'owner:revision', false, attempt)).toBe(false);
+ expect(attempt).toHaveBeenCalledOnce();
+ const retry = vi.fn(async () => true);
+ expect(await gate.request('p', 'owner:revision', true, retry)).toBe(true);
+ expect(retry).toHaveBeenCalledOnce();
+ });
+ it('does not bypass pending confirmation, and isolates owner/revision and plugin identities', async () => {
+ const gate = new PluginTaskApprovalGate();
+ let finish!: (value: boolean) => void;
+ const first = gate.request('p', 'owner:r1', false, () => new Promise(resolve => { finish = resolve; }));
+ const other = vi.fn(async () => false);
+ expect(await gate.request('p', 'owner:r1', true, other)).toBe(false);
+ expect(other).not.toHaveBeenCalled();
+ finish(false); await first;
+ await gate.request('q', 'owner:r1', false, other);
+ await gate.request('p', 'owner:r2', false, other);
+ await gate.request('p', 'new-owner:r2', false, other);
+ expect(other).toHaveBeenCalledTimes(3);
+ });
it('does not treat a preserved unknown declaration as consent', async () => {
const ghost = legacy();
const handler = vi.fn();
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 8708279b01..c1eca86542 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -2,7 +2,7 @@ import { getModelVisibilityOverride, waitForModelVisibilityMirror } from '../mak
import { projectGhostAgentModels } from './ghostAgentModels.js';
import { getDesktopProviderService } from '../maker-host/createDesktopProviderService.js';
import { handlePluginTaskRequest, type PluginTaskHandler } from './taskSlot.js';
-import { ensurePluginTaskApproval, hasPluginTaskApproval } from './taskCapability.js';
+import { ensurePluginTaskApproval, hasPluginTaskApproval, PluginTaskApprovalGate } from './taskCapability.js';
import { registerGhostCardRemoteProvider, persistGhostCardWithRemoteChange } from './cardRemoteResource.js';
import { openDeviceAuthorizationCard, openPluginAuthorizationCard } from '../plugin-oauth/deviceCard.js';
import { t as authorizationText } from '../i18n.js';
@@ -25,6 +25,26 @@ import { randomUUID } from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { isDeepStrictEqual } from 'node:util';
+import type { GhostInstallConsentFacts } from '../../shared/ghostInstallConsent.js';
+
+const taskApprovalGate = new PluginTaskApprovalGate();
+function requestPluginTaskApproval(id: string, isCurrent: () => boolean, confirm: (facts: GhostInstallConsentFacts) => Promise<boolean>, explicit = false): Promise<boolean> {
+ const ghost = findAvailableGhost(id);
+ if (!isCurrent()) return Promise.resolve(false);
+ if (hasPluginTaskApproval(ghost)) return Promise.resolve(true);
+ const owner = getActiveDataOwnerPushStamp();
+ const manager = getGhostManager();
+ const revision = ghostInstallApprovalToken(ghost?.approval);
+ const active = () => {
+ const current = getActiveDataOwnerPushStamp();
+ return isCurrent() && owner.dataOwnerId === current.dataOwnerId && owner.ownerGeneration === current.ownerGeneration &&
+ ghostInstallApprovalToken(findAvailableGhost(id)?.approval) === revision;
+ };
+ return taskApprovalGate.request(id, JSON.stringify([owner.dataOwnerId, owner.ownerGeneration, revision]), explicit, () => ensurePluginTaskApproval(id, {
+ getGhost: findAvailableGhost, isCurrent: active, confirm,
+ approve: (pluginId, expected, current) => manager.approveTaskCapability(pluginId, expected, current),
+ }));
+}
import { supportsCindyVersion } from '@cindy/plugin-protocol';
import { buildGhostRecommendationSnapshot } from './ghostRecommendationSnapshot.js';
@@ -7198,7 +7218,6 @@ export function registerGhostIpc(): void {
// 的 runner(maker-ipc)。
if (type === 'tasks-request') {
const owner = getActiveDataOwnerPushStamp();
- const manager = getGhostManager();
const isCurrent = () => {
const current = getActiveDataOwnerPushStamp();
return owner.dataOwnerId === current.dataOwnerId && owner.ownerGeneration === current.ownerGeneration &&
@@ -7207,14 +7226,10 @@ export function registerGhostIpc(): void {
return handlePluginTaskRequest(id, payload, {
getGhost: findAvailableGhost, handler: pluginTaskHandler,
isCurrent,
- ensureAuthorized: () => ensurePluginTaskApproval(id, {
- getGhost: findAvailableGhost, isCurrent,
- confirm: facts => {
+ ensureAuthorized: () => requestPluginTaskApproval(id, isCurrent, facts => {
const window = getDeepLinkMainWindow();
if (!window || !isTrustedAppRendererWindow(window)) return Promise.resolve(false);
return createWindowGhostInstallConsentPrompt(window.webContents)({ purpose: 'task-capability', initiator: 'user', origin: 'local-file', facts });
- },
- approve: (pluginId, revision, active) => manager.approveTaskCapability(pluginId, revision, active),
}),
});
}
@@ -8096,6 +8111,19 @@ export function registerGhostIpc(): void {
});
// 启用 / 停用(停用 = 面板休眠,布局位置保留;详见 GhostManager.setEnabled)。
+ ipcMain.handle('ghosts:request-task-approval', async (event, id: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ if (typeof id !== 'string' || !id.trim()) throwIpcError('INVALID_PARAMS', 'id must be a non-empty string');
+ requireGhostAvailableForActiveSession(id);
+ const isCurrent = () => {
+ try { assertTrustedAppRendererEvent(event); return !event.sender.isDestroyed(); } catch { return false; }
+ };
+ const granted = await requestPluginTaskApproval(id, isCurrent, facts =>
+ createWindowGhostInstallConsentPrompt(event.sender)({ purpose: 'task-capability', initiator: 'user', origin: 'local-file', facts }), true);
+ if (granted) broadcastGhostsChanged(getGhostManager().list());
+ return { granted };
+ });
+
ipcMain.handle('ghosts:set-enabled', async (event, id: unknown, enabled: unknown) => {
// 启用 Node 插件会获得本机进程能力;即使按钮在 Renderer 里,来源判定也
// 必须由 Main 按真实顶层 frame 完成,不能信任页面自报。
diff --git a/apps/desktop/src/main/cindy-brain/taskCapability.ts b/apps/desktop/src/main/cindy-brain/taskCapability.ts
index 7d8a2b15f1..44f1c26ef2 100644
--- a/apps/desktop/src/main/cindy-brain/taskCapability.ts
+++ b/apps/desktop/src/main/cindy-brain/taskCapability.ts
@@ -1,6 +1,25 @@
import { ghostPermissionItems, type InstalledGhost } from '../../shared/ghost.js';
import type { GhostInstallConsentFacts } from '../../shared/ghostInstallConsent.js';
+/** One automatic attempt per owner/install identity. Only Host UI may retry. */
+export class PluginTaskApprovalGate {
+ private readonly attempts = new Map<string, { identity: string; pending: boolean }>();
+
+ async request(id: string, identity: string, explicit: boolean, attempt: () => Promise<boolean>): Promise<boolean> {
+ const previous = this.attempts.get(id);
+ if (previous?.pending || (previous?.identity === identity && !explicit)) return false;
+ const state = { identity, pending: true };
+ this.attempts.set(id, state);
+ try {
+ const approved = await attempt();
+ if (approved && this.attempts.get(id) === state) this.attempts.delete(id);
+ return approved;
+ } finally {
+ state.pending = false;
+ }
+ }
+}
+
export function hasPluginTaskApproval(ghost: InstalledGhost | null | undefined): boolean {
return (
ghost?.enabled === true &&
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginStartTeamAdmission.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginStartTeamAdmission.test.ts
new file mode 100644
index 0000000000..cdf67d21ee
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginStartTeamAdmission.test.ts
@@ -0,0 +1,41 @@
+import { readFileSync } from 'node:fs';
+import { describe, expect, it, vi } from 'vitest';
+import ts from 'typescript';
+import { assertPluginTaskResult, PluginTaskError } from '../pluginTaskService.js';
+
+const source = readFileSync(new URL('../register.ts', import.meta.url), 'utf8');
+const branch = source.slice(source.indexOf(" case 'startTeam': {"), source.indexOf(" case 'setTeamPlan': {"));
+const js = ts.transpileModule(`return async function(pluginId, request) { switch(request.kind) { ${branch} } }`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
+
+function fixture(initial = 'active', afterConfirmation = initial) {
+ const epoch = {};
+ const task = { taskId: 'task', status: initial, revision: 1, permissionMode: 'auto' };
+ const service = { get: vi.fn(async () => ({ ...task })) };
+ const create = vi.fn(async () => ({ ok: true, teamId: 'team' }));
+ const start = vi.fn(async (_id: string, _mode: unknown, check: () => Promise<void>) => {
+ task.status = afterConfirmation;
+ await check();
+ return create();
+ });
+ const deps = { service, getCurrentDbClientSnapshot: () => epoch, PluginTaskError, assertPluginTaskResult, startOrcaTeamForCaller: start };
+ const run = new Function(...Object.keys(deps), js)(...Object.values(deps));
+ return { run: () => run('plugin', { kind: 'startTeam', taskId: 'task' }), start, create };
+}
+
+describe('plugin team active-task admission', () => {
+ it('rejects an already archived task before the start flow', async () => {
+ const f = fixture('archived');
+ await expect(f.run()).rejects.toMatchObject({ code: 'TASK_BUSY' });
+ expect(f.start).not.toHaveBeenCalled();
+ });
+ it('rejects archive during confirmation even without a revision change', async () => {
+ const f = fixture('active', 'archived');
+ await expect(f.run()).rejects.toMatchObject({ code: 'TASK_BUSY' });
+ expect(f.create).not.toHaveBeenCalled();
+ });
+ it('starts a still-active task', async () => {
+ const f = fixture();
+ await expect(f.run()).resolves.toEqual({ ok: true, teamId: 'team' });
+ expect(f.create).toHaveBeenCalledOnce();
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 9b8f453089..cae837838b 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -10338,10 +10338,15 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
case 'startTeam': {
const epoch = getCurrentDbClientSnapshot();
const task = await service.get(pluginId, request.taskId);
+ const assertActive = (status: string) => {
+ if (status !== 'active') throw new PluginTaskError('TASK_BUSY', 'Archived tasks cannot start a team');
+ };
+ assertActive(task.status);
if (task.permissionMode === 'plan' || task.permissionMode === 'bypassPermissions') throw new PluginTaskError('PERMISSION_DENIED', 'Coordinator requires an allowed execution permission');
const result = await startOrcaTeamForCaller(task.taskId, undefined, async () => {
if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');
const fresh = await service.get(pluginId, task.taskId);
+ assertActive(fresh.status);
if (fresh.revision !== task.revision) throw new PluginTaskError('STALE_REVISION', 'Task changed during confirmation');
});
if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 2fcaae8c3c..9fe7b2ca9f 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -1337,6 +1337,8 @@ contextBridge.exposeInMainWorld('electronAPI', {
ipcRenderer.invoke('ghosts:export', id),
setEnabled: (id: string, enabled: boolean): Promise<{ ok: true }> =>
ipcRenderer.invoke('ghosts:set-enabled', id, enabled),
+ requestTaskApproval: (id: string): Promise<{ granted: boolean }> =>
+ ipcRenderer.invoke('ghosts:request-task-approval', id),
/** 目录级禁用清单(插件页项目范围视图;sendSync 保证切换同帧渲染)。 */
workdirPrefsSync: (workdir: string): { disabled: string[] } =>
ipcRenderer.sendSync('ghosts:workdir-prefs', workdir),
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
index 116575861b..9f7c5b7962 100644
--- a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
@@ -123,6 +123,7 @@ export function GhostPluginDetailView({
const { scrolled, onScroll } = usePluginDetailScrolled();
const enableSwitchId = useId();
const [descriptionExpanded, setDescriptionExpanded] = useState(false);
+ const [taskApprovalPending, setTaskApprovalPending] = useState(false);
const [descriptionOverflows, setDescriptionOverflows] = useState(false);
const descriptionRef = useRef<HTMLParagraphElement>(null);
// 安装记录不完整时不可运行:enabled 直接门控为 false(说明现状 + 给恢复入口,不让它
@@ -494,6 +495,20 @@ export function GhostPluginDetailView({
{detail.tools.length > 0 ? <ToolsSection tools={detail.tools} /> : null}
{detail.permissions.length > 0 ? <PermissionSummary items={detail.permissions} /> : null}
+ {enabled && ghost?.manifest.agent?.tasks === true && ghost.taskCapabilityApproved !== true ? (
+ <Button variant="secondary" size="sm" className="mt-4" disabled={taskApprovalPending} onClick={async () => {
+ setTaskApprovalPending(true);
+ try {
+ await window.electronAPI.ghosts.requestTaskApproval(detail.id);
+ } catch {
+ toast.error(t('settings.ghosts.errors.generic'));
+ } finally {
+ setTaskApprovalPending(false);
+ }
+ }}>
+ {t('settings.ghosts.perm.agentTasksRequest')}
+ </Button>
+ ) : null}
<GhostLibrarySection ghostId={detail.id} enabled={ghost?.manifest.library === true} />
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
index 8e32defe59..bb21a6548a 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
@@ -6,6 +6,7 @@
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { InstalledGhost } from '../../../../shared/ghost';
const toastMocks = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));
@@ -179,6 +180,24 @@ afterEach(() => {
});
describe('Ghost plugin detail sections', () => {
+ it('lets the user retry task permission, disables duplicate clicks, and hides after approval', async () => {
+ vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} });
+ let finish!: (value: { granted: boolean }) => void;
+ const requestTaskApproval = vi.fn(() => new Promise<{ granted: boolean }>(resolve => { finish = resolve; }));
+ Object.assign(window.electronAPI, { ghosts: { requestTaskApproval } });
+ const ghost = { manifest: { agent: { tasks: true } }, enabled: true } as InstalledGhost;
+ const view = (approved = false) => <GhostPluginDetailView ghost={{ ...ghost, ...(approved ? { taskCapabilityApproved: true as const } : {}) }} detail={detail} panelStatus="Docked" onBack={vi.fn()} onToggle={vi.fn()} onUse={vi.fn()} onUpdate={vi.fn()} onUpdateFromFile={vi.fn()} onUninstall={vi.fn()} toggleDisabled={false} />;
+ const { rerender } = render(view());
+ const button = screen.getByRole('button', { name: 'settings.ghosts.perm.agentTasksRequest' }) as HTMLButtonElement;
+ fireEvent.click(button); fireEvent.click(button);
+ expect(requestTaskApproval).toHaveBeenCalledOnce();
+ expect(requestTaskApproval).toHaveBeenCalledWith(detail.id);
+ expect(button.disabled).toBe(true);
+ finish({ granted: false });
+ await waitFor(() => expect(button.disabled).toBe(false));
+ rerender(view(true));
+ expect(screen.queryByRole('button', { name: 'settings.ghosts.perm.agentTasksRequest' })).toBeNull();
+ });
it('uses the shared Cindy Switch for the plugin enabled control', () => {
vi.stubGlobal(
'ResizeObserver',
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index d3f9dd6f1b..3583ec8a2b 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -5366,6 +5366,7 @@
"agentUserActionDetail": "Each click permits one turn only, and only in the session that owns the card.",
"agentBackground": "Can automatically start new Agent turns in the background",
"agentBackgroundDetail": "Does not require a click each time, but can only use sessions you previously connected to this plugin. Model charges may apply.",
+ "agentTasksRequest": "Review task permission",
"agentTasks": "Can create and manage its own Cindy tasks",
"agentTasksDetail": "Can send messages, read results and stop its own executions. Tasks remain visible to you. Uses this plugin’s AI settings and may incur model charges; does not grant access to other tasks.",
"agentErrand": "Can hand tasks to the Cindy Agent and collect the result",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 8d9f2f15ae..1af036216c 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -5365,6 +5365,7 @@
"agentUserActionDetail": "1 回のクリックにつき 1 回だけ開始でき、そのカードが属するセッションでのみ使用できます。",
"agentBackground": "バックグラウンドで Agent の新しいターンを自動的に開始できます",
"agentBackgroundDetail": "毎回のクリックは不要ですが、以前このプラグインに関連付けたセッションでのみ使用できます。モデル料金が発生する場合があります。",
+ "agentTasksRequest": "セッション権限を確認",
"agentTasks": "このプラグインの Cindy セッションを作成・管理できます",
"agentTasksDetail": "メッセージの送信、結果の読み取り、自身の実行の停止ができます。セッションはユーザーに表示されます。プラグインの AI 設定を使用し、モデル料金が発生する場合があります。他のセッションへのアクセスは許可されません。",
"agentErrand": "Cindy Agent にタスクを任せて結果を受け取れます",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 2141521b87..cccd9b00f6 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -5365,6 +5365,7 @@
"agentUserActionDetail": "클릭 한 번마다 한 번만 시작할 수 있으며, 해당 카드가 속한 세션에서만 사용할 수 있습니다.",
"agentBackground": "백그라운드에서 Agent의 새 작업을 자동으로 시작할 수 있음",
"agentBackgroundDetail": "매번 클릭할 필요는 없지만, 이전에 이 플러그인과 연결한 세션에서만 사용할 수 있습니다. 모델 비용이 발생할 수 있습니다.",
+ "agentTasksRequest": "세션 권한 확인",
"agentTasks": "이 플러그인의 Cindy 세션을 만들고 관리할 수 있음",
"agentTasksDetail": "메시지를 보내고 결과를 읽으며 자신의 실행을 중지할 수 있습니다. 세션은 사용자에게 표시됩니다. 플러그인의 AI 설정을 사용하며 모델 비용이 발생할 수 있습니다. 다른 세션에 대한 접근 권한은 부여하지 않습니다.",
"agentErrand": "Cindy Agent에게 작업을 맡기고 결과를 받아올 수 있음",
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 7cb5edc67b..11b5b20d87 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -5365,6 +5365,7 @@
"agentUserActionDetail": "每次点击只允许启动一次,并且只能使用这张卡所属的任务。",
"agentBackground": "可在后台自动让 Agent 开始新一轮工作",
"agentBackgroundDetail": "不需要当次点击,但只能使用你曾为这个插件建立过关联的任务,可能产生模型费用。",
+ "agentTasksRequest": "确认任务权限",
"agentTasks": "可创建和管理本插件的 Cindy 任务",
"agentTasksDetail": "可发送消息、读取结果和停止本插件的执行,任务对你可见。沿用插件的 AI 配置,可能产生模型费用;不授予其他任务的访问权。",
"agentErrand": "可把任务交给 Cindy Agent 代办并取回结果",
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 84da98814a..c539b15f33 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -5365,6 +5365,7 @@
"agentUserActionDetail": "每次點選只允許啟動一次,並且只能使用這張卡所屬的任務。",
"agentBackground": "可在後臺自動讓 Agent 開始新一輪工作",
"agentBackgroundDetail": "不需要當次點選,但只能使用你曾為這個插件建立過關聯的任務,可能產生模型費用。",
+ "agentTasksRequest": "確認任務權限",
"agentTasks": "可建立和管理本插件的 Cindy 任務",
"agentTasksDetail": "可傳送訊息、讀取結果和停止本插件的執行,任務對你可見。沿用插件的 AI 配置,可能產生模型費用;不授予其他任務的存取權。",
"agentErrand": "可把任務交給 Cindy Agent 代辦並取回結果",
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 2f23532cc8..e644287a9c 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -1426,6 +1426,7 @@ interface ElectronAPI {
) => Promise<{ status: 'saved'; savedPath: string } | { status: 'canceled' }>;
/** 启用/停用(停用 = 面板休眠,布局位置保留)。 */
setEnabled: (id: string, enabled: boolean) => Promise<{ ok: true }>;
+ requestTaskApproval: (id: string) => Promise<{ granted: boolean }>;
/** 目录级禁用清单(插件页项目范围视图;sendSync 切换同帧渲染)。 */
workdirPrefsSync: (workdir: string) => { disabled: string[] };
/** 写/清一条目录级例外(disabled=false 即清除,回到跟随全局)。 */
diff --git a/docs/dev-rules/plugin-task-api-implementation.md b/docs/dev-rules/plugin-task-api-implementation.md
index 293ac3a1a3..c6d70800e9 100644
--- a/docs/dev-rules/plugin-task-api-implementation.md
+++ b/docs/dev-rules/plugin-task-api-implementation.md
@@ -38,12 +38,16 @@
## 首次修改授权
+插件新增的 tasks 能力首次使用时复用宿主权限确认。拒绝、超时或确认失败后,同一账号代际和安装修订在当前宿主进程内不再自动弹窗;插件重载或重复调用不能清除该状态。用户可在本机插件详情权限区点击“确认任务权限”重新进入原确认流程,点击不等于批准;在途确认不并发,账号、安装修订或发起窗口改变时旧结果无效。旧插件的既有功能、启用态、凭证与设置不变。此显式入口不向插件页面或 device-link 暴露;重启宿主后可重新首次询问。
+
逻辑页可调用 cindy.tasks.requestWriteAccess({taskId, mode?})。省略 mode 保留旧行为(acceptEdits,仅限未开始执行的任务);mode: auto 请求宿主原生确认,为空闲自有任务及插件后续任务启用 Auto。插件不能替用户确认,不能请求 Full access。拒绝不改状态;账号、配置、任务版本在确认期间改变则拒绝写入。Auto 插件主任务的 Worker 固定使用 Auto,不继承或改写全局 Worker 偏好;授权撤销后拒绝新建。独立目录不是沙箱。返回 granted 与更新后的 task/revision,插件应继续原批次。
### 主任务协调评测
`tasks.startTeam({taskId})` 为本插件拥有的普通任务启用 Orca Lead,复用现有协同入口及 Worker 权限确认。插件不能指定 Worker 权限绕过确认。确认返回后、实际启用前再次校验账号、插件授权、任务配置修订。`tasks.getTeam({taskId})` 只投影所属团队的 Worker 身份、实际模型配置、目录、队列和终态;不会将 Lead 一轮完成解释为整个团队完成。
+协同启动要求任务仍为 active;进入启动流程前和权限确认后的原生启动回调均重新检查,已归档任务不能借此创建或复用团队。不宣称与跨进程归档形成事务。
+
插件可读取自己任务在权限变化后的状态与执行停止,但新发送拒绝超出插件策略的 full access 任务。既有普通任务的所有权收据在成为 Lead 后继续有效;Worker 不是插件直接控制的普通任务。
评测客户端每批仅创建一个 Lead,答案目录逐份隔离,由 Lead 使用原生 Orca 调度。插件根据 Worker 成员、配置、目录、done 且无活动/队列的状态独立验收。该投影不是逐轮执行账本,不作为精确费用证据。重试先核对既有 Worker;未知归属不得重派或算零分。停止须确认 Lead 停止处理完成和团队不再活动。