Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(shared-task): 开放协作者决策并防止越权与撤权竞态 (#5245)
DavidShenXD9727ac7709cf
diff --git a/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts b/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.tsindex 03427340fa..198c39f6e6 100644--- a/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts+++ b/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts@@ -545,7 +545,7 @@ describe('sendToSession ordering', () => {);const directSendSwitchBlock = extractBetween(source,- 'pendingAgentSwitchApplyHolder = async (sessionId, signal, selection) =>',+ 'pendingAgentSwitchApplyHolder = async (','ipcMain.handle(MAKER_INVOKE.MARK_ORCA_ROLE',);diff --git a/apps/desktop/src/main/__tests__/permissionInteractionPause.test.ts b/apps/desktop/src/main/__tests__/permissionInteractionPause.test.tsindex 6a5bdafd1b..82d0f855a1 100644--- a/apps/desktop/src/main/__tests__/permissionInteractionPause.test.ts+++ b/apps/desktop/src/main/__tests__/permissionInteractionPause.test.ts@@ -2,6 +2,7 @@ import { readFileSync } from 'node:fs';import ts from 'typescript';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { InteractionDecision, InteractionRequest } from '@cindy/maker-core';+import { assertSharedTaskInteractionResolveCurrent, assertSharedTaskInvoke, setSharedTaskInteractionReader, type SharedTaskPeerCapture } from '../device-link/sharedTaskDispatch.js';// Execute the production listener and control adapter without booting Electron.const source = readFileSync(new URL('../maker-ipc/register.ts', import.meta.url), 'utf8');@@ -15,7 +16,16 @@ const names = new Set([const functions = ast.statements.filter((node) => ts.isFunctionDeclaration(node)&& node.name && names.has(node.name.text)).map(node => node.getText(ast).replace(/^export /, ''));let holdInputSource = '';+let resolveHandlerSource = '';+let interactionReaderSource = '';function visit(node: ts.Node): void {+ if (ts.isCallExpression(node) && node.expression.getText(ast) === 'setSharedTaskInteractionReader') {+ interactionReaderSource = node.arguments[0].getText(ast);+ }+ if (ts.isCallExpression(node) && node.expression.getText(ast) === 'ipcMain.handle'+ && node.arguments[0]?.getText(ast) === 'MAKER_INVOKE.RESOLVE_INTERACTION') {+ resolveHandlerSource = node.arguments[1].getText(ast);+ }if (ts.isPropertyAssignment(node) && node.name.getText(ast) === 'holdInput') {holdInputSource = node.initializer.getText(ast);}@@ -23,15 +33,19 @@ function visit(node: ts.Node): void {}visit(ast);if (!holdInputSource) throw new Error('Task holdInput adapter missing');+if (!resolveHandlerSource) throw new Error('Resolve interaction IPC handler missing');+if (!interactionReaderSource) throw new Error('Shared-task interaction reader missing');const compiled = ts.transpileModule(`${functions.join('\n')}+setSharedTaskInteractionReader(${interactionReaderSource});return { install: installDesktopInteractionListener, hold: ${holdInputSource},answer: resolvePendingInteraction, cleanup: cleanupPendingAgentInteractionsForSession,- take: takePendingInteractionsForSession };`, {+ take: takePendingInteractionsForSession, resolveFromIpc: ${resolveHandlerSource} };`, {compilerOptions: { target: ts.ScriptTarget.ES2022 },}).outputText;const MINUTE = 60_000;function harness() {+ let sharedTask: SharedTaskPeerCapture | undefined;const held = new Set<string>();const coordinator = {isExecutionPaused: (id: string) => held.has(id),@@ -42,6 +56,11 @@ function harness() {const entries = new Map();const dismiss = vi.fn();const deps = {+ getDeviceLinkInvokeContext: () => ({ sharedTask }),+ assertSharedTaskInteractionResolveCurrent,+ setSharedTaskInteractionReader,+ isPluginSetupInteractionDecision: () => false,+ assertResolveInteractionOrigin: vi.fn(), isPendingDesktopOnlyConfirmation: () => false,pendingInteractionResolvers: entries,agentInputCoordinatorHolder: coordinator, inputCoordinator: coordinator,PERMISSION_INTERACTION_TIMEOUT_MS: 10 * MINUTE,@@ -61,6 +80,7 @@ function harness() {answer: (id: string, decision: InteractionDecision) => boolean;cleanup: (id: string, reason: string) => void;take: (id: string) => Array<{ resolve: (decision: InteractionDecision) => void }>;+ resolveFromIpc: (event: unknown, id: string, decision: InteractionDecision) => Promise<{ accepted: boolean }>;};const request = (id = 'permission', sessionId = 'task', kind: InteractionRequest['kind'] = 'permission') => {runtime.install({ id: sessionId });@@ -69,11 +89,78 @@ function harness() {void promise.then(settled);return { promise, settled };};- return { ...runtime, request, entries, dismiss };+ return { ...runtime, request, entries, dismiss, setSharedTask: (peer?: SharedTaskPeerCapture) => { sharedTask = peer; } };}beforeEach(() => { vi.useFakeTimers(); vi.setSystemTime(0); });-afterEach(() => { vi.clearAllTimers(); vi.useRealTimers(); });+afterEach(() => { setSharedTaskInteractionReader(null); vi.clearAllTimers(); vi.useRealTimers(); });++it('does not consume the pending decision when membership is revoked after dispatch admission', async () => {+ const h = harness();+ const p = h.request();+ let authorized = true;+ const peer: SharedTaskPeerCapture = {+ author: { sharedTaskId: 'shared', sessionId: 'task', memberId: 'guest', accountId: 'guest', displayName: 'Guest' },+ isCurrent: () => authorized, authorize: () => authorized,+ };+ const decision = { kind: 'permission', behavior: 'allow' } as const;+ assertSharedTaskInvoke(peer, { channel: 'maker:resolve-interaction', args: ['permission', decision] });+ // Simulate revocation during async admission, without removing the request.+ await Promise.resolve();+ authorized = false;+ h.setSharedTask(peer);+ await expect(h.resolveFromIpc({}, 'permission', decision)).rejects.toThrow('PERMISSION_DENIED');+ expect(h.entries.has('permission')).toBe(true);+ expect(p.settled).not.toHaveBeenCalled();+ expect(h.dismiss).not.toHaveBeenCalled();+ h.setSharedTask(undefined);+ await expect(h.resolveFromIpc({}, 'permission', decision)).resolves.toEqual({ accepted: true });+ await expect(p.promise).resolves.toEqual(decision);+ expect(h.entries.has('permission')).toBe(false);+ expect(h.dismiss).toHaveBeenCalledTimes(1);+});++it.each(['permission', 'ask_user_question', 'plan_review'] as const)('rejects guest decisions after %s is handed to Feishu, including already-admitted requests', async (kind) => {+ const h = harness();+ const p = h.request(kind, 'task', kind);+ const peer: SharedTaskPeerCapture = {+ author: { sharedTaskId: 'shared', sessionId: 'task', memberId: 'guest', accountId: 'guest', displayName: 'Guest' },+ isCurrent: () => true, authorize: () => true,+ };+ const decision: InteractionDecision = kind === 'ask_user_question'+ ? { kind, answers: { choice: 'yes' } } : { kind, behavior: 'allow' };+ const payload = { channel: 'maker:resolve-interaction', args: [kind, decision] };+ assertSharedTaskInvoke(peer, payload);+ await Promise.resolve();+ const [taken] = h.take('task');+ expect(h.entries.get(kind).migrated).toBe(true);+ expect(() => assertSharedTaskInvoke(peer, payload)).toThrow('PERMISSION_DENIED');+ h.setSharedTask(peer);+ await expect(h.resolveFromIpc({}, kind, decision)).rejects.toThrow('PERMISSION_DENIED');+ expect(h.entries.has(kind)).toBe(true);+ expect(p.settled).not.toHaveBeenCalled();+ taken.resolve(decision);+ await expect(p.promise).resolves.toEqual(decision);+ expect(h.entries.has(kind)).toBe(false);+});++it('rejects a guest replacement tool input without consuming the pending request', async () => {+ const h = harness();+ const p = h.request();+ h.setSharedTask({+ author: { sharedTaskId: 'shared', sessionId: 'task', memberId: 'guest', accountId: 'guest', displayName: 'Guest' },+ isCurrent: () => true, authorize: () => true,+ });+ await expect(h.resolveFromIpc({}, 'permission', {+ kind: 'permission', behavior: 'allow', updatedInput: { command: 'different-command' },+ })).rejects.toThrow('PERMISSION_DENIED');+ expect(h.entries.has('permission')).toBe(true);+ expect(p.settled).not.toHaveBeenCalled();+ expect(h.dismiss).not.toHaveBeenCalled();+ const originalDecision = { kind: 'permission', behavior: 'allow' } as const;+ await expect(h.resolveFromIpc({}, 'permission', originalDecision)).resolves.toEqual({ accepted: true });+ await expect(p.promise).resolves.toEqual(originalDecision);+});describe('permission timeout follows the task pause lifecycle', () => {it('keeps the permission pending across its original deadline and resumes only the remaining budget', async () => {diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskDispatch.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskDispatch.test.tsindex 7d1562f7fb..f25118613a 100644--- a/apps/desktop/src/main/device-link/__tests__/sharedTaskDispatch.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskDispatch.test.ts@@ -1,6 +1,6 @@import { sharedTaskGuestPeer } from '@cindy/device-link';import { afterEach, describe, expect, it } from 'vitest';-import { assertSharedTaskInvoke, assertSharedTaskReferences, captureSharedTaskPush, setSharedTaskQueueReader, type SharedTaskPeerCapture } from '../sharedTaskDispatch.js';+import { assertSharedTaskInteractionResolveCurrent, assertSharedTaskInvoke, assertSharedTaskReferences, captureSharedTaskPush, setSharedTaskInteractionReader, setSharedTaskQueueReader, type SharedTaskInteractionCapture, type SharedTaskPeerCapture } from '../sharedTaskDispatch.js';function capture(): SharedTaskPeerCapture {return {@@ -9,7 +9,7 @@ function capture(): SharedTaskPeerCapture {authorize: (operation, item) => operation !== 'input.edit' && operation !== 'input.withdraw' || item?.authorAccountId === 'guest',};}-afterEach(() => setSharedTaskQueueReader(null));+afterEach(() => { setSharedTaskQueueReader(null); setSharedTaskInteractionReader(null); });describe('sharedTask dispatch scope', () => {it('reads subagent context only through the shared parent task', () => {for (const channel of ['local-db:subagent-runs:list', 'local-db:subagent-runs:detail', 'local-db:subagent-runs:transcript']) {@@ -45,6 +45,99 @@ describe('sharedTask dispatch scope', () => {expect(() => assertSharedTaskInvoke(capture(), { channel, args: ['other'] })).toThrow();}});+ it('allows guests to resolve generic Agent interaction cards for the shared task', () => {+ const permissionSuggestion = { type: 'addRules', behavior: 'allow', destination: 'session', rules: [{ toolName: 'Bash', ruleContent: 'git status' }] };+ const interactions: Record<string, SharedTaskInteractionCapture> = {+ 'permission-1': { sessionId: 'task', kind: 'permission', toolName: 'Bash', suggestions: [permissionSuggestion] },+ 'question-1': { sessionId: 'task', kind: 'ask_user_question' },+ 'plan-1': { sessionId: 'task', kind: 'plan_review' },+ };+ setSharedTaskInteractionReader((requestId) => interactions[requestId]);+ for (const [requestId, decision] of [+ ['permission-1', { kind: 'permission', behavior: 'allow' }],+ ['question-1', { kind: 'ask_user_question', answers: { choice: 'A' } }],+ ['plan-1', { kind: 'plan_review', behavior: 'deny', reason: 'change scope' }],+ ]) {+ expect(() => assertSharedTaskInvoke(capture(), {+ channel: 'maker:resolve-interaction', args: [requestId, decision],+ })).not.toThrow();+ }+ for (const decision of [+ { kind: 'plugin_setup', action: 'run_action' },+ { kind: 'issue_confirm', behavior: 'allow' },+ { kind: 'permission', behavior: 'maybe' },+ ]) {+ expect(() => assertSharedTaskInvoke(capture(), {+ channel: 'maker:resolve-interaction', args: ['permission-1', decision],+ })).toThrow('PERMISSION_DENIED');+ }+ expect(() => assertSharedTaskInvoke(capture(), {+ channel: 'maker:resolve-interaction', args: ['other-task', { kind: 'permission', behavior: 'allow' }],+ })).toThrow('PERMISSION_DENIED');+ expect(() => assertSharedTaskInvoke(capture(), {+ channel: 'maker:resolve-interaction',+ args: ['permission-1', { kind: 'permission', behavior: 'allow', permissionUpdates: [{ type: 'setMode', mode: 'bypassPermissions', destination: 'session' }] }],+ })).toThrow('PERMISSION_DENIED');+ expect(() => assertSharedTaskInvoke(capture(), {+ channel: 'maker:resolve-interaction',+ args: ['permission-1', { kind: 'permission', behavior: 'allow', permissionUpdates: [{ ...permissionSuggestion, rules: [{ toolName: 'Write' }] }] }],+ })).toThrow('PERMISSION_DENIED');+ expect(() => assertSharedTaskInvoke(capture(), {+ channel: 'maker:resolve-interaction',+ args: ['permission-1', { kind: 'permission', behavior: 'allow', permissionUpdates: [permissionSuggestion] }],+ })).not.toThrow();+ });+ it.each([{ command: 'different-command' }, {}, null])('rejects guest replacement input %j at admission and consumption', (updatedInput) => {+ setSharedTaskInteractionReader(() => ({ sessionId: 'task', kind: 'permission', toolName: 'Bash' }));+ const args = ['permission-1', { kind: 'permission', behavior: 'allow', updatedInput }];+ expect(() => assertSharedTaskInvoke(capture(), { channel: 'maker:resolve-interaction', args })).toThrow('PERMISSION_DENIED');+ expect(() => assertSharedTaskInteractionResolveCurrent(capture(), args)).toThrow('PERMISSION_DENIED');+ });+ it('accepts the host-provided Codex session approval, but rejects an unsolicited one', () => {+ const update = { type: 'codexSessionApproval', destination: 'session' };+ const request: SharedTaskInteractionCapture = { sessionId: 'task', kind: 'permission', toolName: 'Shell', suggestions: [update] };+ setSharedTaskInteractionReader(() => request);+ const args = ['permission-1', { kind: 'permission', behavior: 'allow', permissionUpdates: [update] }];+ expect(() => assertSharedTaskInvoke(capture(), { channel: 'maker:resolve-interaction', args })).not.toThrow();+ expect(() => assertSharedTaskInteractionResolveCurrent(capture(), args)).not.toThrow();+ request.suggestions = [];+ expect(() => assertSharedTaskInvoke(capture(), { channel: 'maker:resolve-interaction', args })).toThrow('PERMISSION_DENIED');+ expect(() => assertSharedTaskInteractionResolveCurrent(capture(), args)).toThrow('PERMISSION_DENIED');+ });+ it.each([+ { type: 'codexSessionApproval', destination: 'userSettings' },+ { type: 'codexSessionApproval', destination: 'session', mode: 'bypassPermissions' },+ { type: 'codexSessionApproval', destination: 'session', rules: [{ toolName: 'Write' }] },+ { type: 'setMode', destination: 'session', mode: 'bypassPermissions' },+ ])('rejects unsafe session approval shapes even when suggested: %j', (update) => {+ setSharedTaskInteractionReader(() => ({ sessionId: 'task', kind: 'permission', toolName: 'Shell', suggestions: [update] }));+ const args = ['permission-1', { kind: 'permission', behavior: 'allow', permissionUpdates: [update] }];+ expect(() => assertSharedTaskInvoke(capture(), { channel: 'maker:resolve-interaction', args })).toThrow('PERMISSION_DENIED');+ expect(() => assertSharedTaskInteractionResolveCurrent(capture(), args)).toThrow('PERMISSION_DENIED');+ });+ it('rejects a request that disappeared before consumption', () => {+ let active = true;+ setSharedTaskInteractionReader(() => active+ ? { sessionId: 'task', kind: 'permission', toolName: 'Bash' }+ : undefined);+ const args: unknown[] = ['request-1', { kind: 'permission', behavior: 'allow' }];+ expect(() => assertSharedTaskInvoke(capture(), { channel: 'maker:resolve-interaction', args })).not.toThrow();+ active = false;+ expect(() => assertSharedTaskInteractionResolveCurrent(capture(), args)).toThrow('PERMISSION_DENIED');+ });+ it.each(['permission', 'ask_user_question', 'plan_review'] as const)('rejects a revoked guest with a still-pending %s request', (kind) => {+ const pending = { sessionId: 'task', kind, toolName: 'Bash' };+ setSharedTaskInteractionReader(() => pending);+ let memberActive = true;+ const peer = { ...capture(), isCurrent: () => memberActive, authorize: () => memberActive };+ const decision = kind === 'ask_user_question'+ ? { kind, answers: { choice: 'A' } } : { kind, behavior: 'allow' };+ const args = ['request-1', decision];+ assertSharedTaskInvoke(peer, { channel: 'maker:resolve-interaction', args });+ memberActive = false;+ expect(() => assertSharedTaskInteractionResolveCurrent(peer, args)).toThrow('PERMISSION_DENIED');+ expect(() => assertSharedTaskInteractionResolveCurrent(capture(), args)).not.toThrow();+ });it('lets a guest read running command output only for the shared task, under history.read', () => {const channel = 'maker:background-task:output-tail';expect(() => assertSharedTaskInvoke(capture(), { channel, args: ['task', 'bash-1'] })).not.toThrow();diff --git a/apps/desktop/src/main/device-link/sharedTaskDispatch.ts b/apps/desktop/src/main/device-link/sharedTaskDispatch.tsindex 359a502c0b..75ea66ea01 100644--- a/apps/desktop/src/main/device-link/sharedTaskDispatch.ts+++ b/apps/desktop/src/main/device-link/sharedTaskDispatch.ts@@ -2,9 +2,17 @@ import { isSharedTaskPeer, parseSharedTaskPeer, isSharedTaskAttachment, type Invimport type { SharedTaskHost } from './sharedTaskHost.js';export type SharedTaskPeerCapture = NonNullable<ReturnType<SharedTaskHost['capturePeer']>>;+export interface SharedTaskInteractionCapture {+ sessionId: string;+ kind: 'permission' | 'ask_user_question' | 'plan_review';+ toolName?: string;+ suggestions?: unknown[];+}let host: SharedTaskHost | null = null;let readQueueItem: ((sessionId: string, clientId: string) => (SharedTaskQueueItem & { attachments?: unknown }) | undefined) | null = null;+let readInteractionSession: ((requestId: string) => SharedTaskInteractionCapture | undefined) | null = null;export function setSharedTaskQueueReader(value: typeof readQueueItem): void { readQueueItem = value; }+export function setSharedTaskInteractionReader(value: typeof readInteractionSession): void { readInteractionSession = value; }export function setSharedTaskDispatchHost(value: SharedTaskHost | null): void { host = value; }export function captureSharedTaskPeer(source: string): SharedTaskPeerCapture | null {return host?.capturePeer(source) ?? null;@@ -54,12 +62,78 @@ const sessionReads = new Set([]);const inputEdits = new Set(['maker:input:update-text', 'maker:input:update-content', 'maker:input:set-edit-lock']);const agentSettings = new Set(['maker:set-model', 'maker:set-effort', 'maker:set-fast-mode', 'maker:set-thinking-enabled', 'maker:switch-session-agent']);+const interactionDecisionKinds = new Set(['permission', 'ask_user_question', 'plan_review']);function record(value: unknown): Record<string, unknown> | null {return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : null;}function deny(): never { throw new Error('[PERMISSION_DENIED] SharedTask task access denied'); }+function sameJson(left: unknown, right: unknown): boolean {+ try { return JSON.stringify(left) === JSON.stringify(right); } catch { return false; }+}++function isSafeSessionPermissionUpdate(value: unknown, toolName: string): boolean {+ const update = record(value);+ if (!update || update.destination !== 'session') return false;+ if (update.type === 'codexSessionApproval') {+ return Object.keys(update).every((key) => key === 'type' || key === 'destination');+ }+ if (update.type !== 'addRules' || update.behavior !== 'allow' ||+ Object.keys(update).some((key) => !['type', 'behavior', 'destination', 'rules'].includes(key)) ||+ !Array.isArray(update.rules) || update.rules.length === 0) return false;+ return update.rules.every((rawRule) => {+ const rule = record(rawRule);+ return !!rule && typeof rule.toolName === 'string' && rule.toolName === toolName &&+ Object.keys(rule).every((key) => key === 'toolName' || key === 'ruleContent') &&+ (rule.ruleContent === undefined || typeof rule.ruleContent === 'string');+ });+}++function assertSharedTaskPermissionUpdates(+ decision: Record<string, unknown>, interaction: SharedTaskInteractionCapture,+): void {+ if (decision.permissionUpdates === undefined) return;+ if (interaction.kind !== 'permission' || !interaction.toolName ||+ !Array.isArray(decision.permissionUpdates) || decision.permissionUpdates.length === 0 ||+ !Array.isArray(interaction.suggestions)) deny();+ for (const update of decision.permissionUpdates) {+ if (!isSafeSessionPermissionUpdate(update, interaction.toolName) ||+ !interaction.suggestions.some((suggestion) => sameJson(update, suggestion))) deny();+ }+}++/** Shared-task guests may answer the generic Agent interaction cards. Host-only+ * confirmations (plugin setup, issue review, grants, and rename prompts) never+ * enter this branch and remain protected by the normal origin gate. */+function assertSharedTaskInteractionResolve(+ capture: SharedTaskPeerCapture, args: unknown[], sessionId: string,+ phase: 'invoke' | 'result',+): void {+ if (args.length !== 2 || typeof args[0] !== 'string' || !args[0]) deny();+ const interaction = phase === 'invoke' ? readInteractionSession?.(args[0]) : undefined;+ if (phase === 'invoke' && (!interaction || interaction.sessionId !== sessionId)) deny();+ const decision = record(args[1]);+ if (!decision || typeof decision.kind !== 'string' || !interactionDecisionKinds.has(decision.kind)) deny();+ // Guests approve the host-displayed input, never substitute executable input.+ if (decision.updatedInput !== undefined) deny();+ if (phase === 'invoke' && interaction?.kind !== decision.kind) deny();+ if (decision.kind === 'permission' || decision.kind === 'plan_review') {+ if (decision.behavior !== 'allow' && decision.behavior !== 'deny') deny();+ } else if (!record(decision.answers)) {+ deny();+ }+ if (phase === 'invoke' && interaction) assertSharedTaskPermissionUpdates(decision, interaction);+ if (!capture.authorize('approval.resolve')) deny();+}++/** Re-run the shared-task gate immediately before a pending decision is consumed. */+export function assertSharedTaskInteractionResolveCurrent(+ capture: SharedTaskPeerCapture, args: unknown[],+): void {+ assertSharedTaskInteractionResolve(capture, args, capture.author.sessionId, 'invoke');+}+/** Existing attachments can survive a text edit without being re-uploaded. The* set comes exclusively from this member's current host-owned pending row. */export function sharedTaskOwnedQueueReferences(capture: SharedTaskPeerCapture, clientId: unknown): ReadonlySet<string> {@@ -142,6 +216,10 @@ export function assertSharedTaskInvoke(if (!capture.authorize('events.subscribe')) deny();return;}+ if (channel === 'maker:resolve-interaction') {+ assertSharedTaskInteractionResolve(capture, args, sessionId, phase);+ return;+ }if (args[0] !== sessionId) deny();const operation = sessionReads.has(channel) ? 'history.read': ['maker:input:enqueue', 'maker:input:steer', 'maker:input:resume', 'maker:input:set-expanded'].includes(channel) ? 'input.send'diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botSkillRuntimeProjection.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botSkillRuntimeProjection.test.tsindex d662510371..e163feedbe 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/botSkillRuntimeProjection.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/botSkillRuntimeProjection.test.ts@@ -136,7 +136,10 @@ describe('complete personal Skills with bounded startup projection', () => {expect(opens.mock.calls.filter(([file]) => String(file).includes('catalog.jsonl'))).toHaveLength(0);expect((await fs.stat(path.join(mounts.pluginRoot, 'catalog.jsonl'))).mtimeMs).toBe(catalogTime);reads.mockRestore(); opens.mockRestore();- }, largeFixtureTimeout);+ // This includes a cold scan/open of all 2,048 real files. Under the full+ // Windows worker pool it can exceed the default 60s I/O allowance; this+ // is a completeness/cache test, not a wall-clock performance assertion.+ }, process.platform === 'win32' ? 120_000 : largeFixtureTimeout);it('keeps every Skill discoverable through the final query page', async () => {const firstPage = await listBotSkillsForSession({ callerSessionId: 'session', query: 'workflow' }, deps());diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 7fe274d299..247807a8b3 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -1098,7 +1098,7 @@ import {import { stampSharedTaskInput } from './sharedTaskInput.js';import { createSharedTaskContextUsageGuard } from './sharedTaskContextUsage.js';import { createSharedTaskSettingGuard } from './sharedTaskSetting.js';-import { setSharedTaskQueueReader } from '../device-link/sharedTaskDispatch.js';+import { assertSharedTaskInteractionResolveCurrent, setSharedTaskInteractionReader, setSharedTaskQueueReader } from '../device-link/sharedTaskDispatch.js';function captureSharedTaskSettingGuard(sessionId: string) {const context = getDeviceLinkInvokeContext();@@ -14789,6 +14789,16 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const item = inputCoordinator.getProjection(sessionId).pendingQueue.find((pending) => pending.clientId === clientId);return item ? { sessionId, authorAccountId: item.sharedTaskAuthor?.accountId ?? '', state: 'pending', attachments: item.files } : undefined;});+ setSharedTaskInteractionReader((requestId) => {+ const entry = pendingInteractionResolvers.get(requestId);+ const request = entry?.request;+ if (!entry || entry.migrated || !request || (request.kind !== 'permission' && request.kind !== 'ask_user_question' && request.kind !== 'plan_review')) return undefined;+ return {+ sessionId: entry.sessionId,+ kind: request.kind,+ ...(request.kind === 'permission' ? { toolName: request.toolName, suggestions: request.suggestions } : {}),+ };+ });getAgentIslandService()?.setCompletionDeferResolver((sessionId) =>inputCoordinator.hasPendingQueuedWork(sessionId),);@@ -16471,6 +16481,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// resolvable. Host-owned setup side effects and Desktop-only confirmations// may only originate from the trusted local Desktop.assertResolveInteractionOrigin(decision, isPendingDesktopOnlyConfirmation(requestId));+ const sharedTask = getDeviceLinkInvokeContext()?.sharedTask;+ if (sharedTask) {+ // The initial dispatch check may be separated from this handler by an+ // async DB admission. Recheck membership and pending-request ownership+ // immediately before resolving so a revoked guest cannot win the race.+ assertSharedTaskInteractionResolveCurrent(sharedTask, [requestId, decision]);+ }let pluginSetupResponseTarget: GhostSetupInteractionResponseTarget | undefined;if (isPluginSetupInteractionDecision(decision) && !isDeviceLinkInvoke()) {assertTrustedAppRendererEvent(event);diff --git a/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts b/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.tsindex ebca926098..110c78f872 100644--- a/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts+++ b/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts@@ -17,6 +17,10 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { readFileSync } from 'node:fs';import { resolve } from 'node:path';+import ts from 'typescript';+import { sharedTaskHostPeer } from '@cindy/device-link';+import { isRemoteSessionSticky } from '@/lib/makerTransport';+import { bindSharedTaskPushOwner, resetRemoteDataOwnerPushFence } from '@/lib/remoteDataOwnerPushFence';import type { Session } from '@/lib/ccAgent.types';import {@@ -206,6 +210,29 @@ function emptyProjection(sessionId: string) {}const flush = () => new Promise((r) => setTimeout(r, 0));++// Execute the hook's real edit callback with the real store and transport,+// without mounting unrelated hook effects or starting Electron.+function planEditor(sessionId: string) {+ const source = readFileSync(resolve(__dirname, '../hooks/useCCAgentChat.ts'), 'utf8');+ const ast = ts.createSourceFile('hook.ts', source, ts.ScriptTarget.ES2022, true);+ let callback = '';+ function visit(node: ts.Node): void {+ if (ts.isVariableDeclaration(node) && node.name.getText(ast) === 'updatePlanContent'+ && node.initializer && ts.isCallExpression(node.initializer)) {+ callback = node.initializer.arguments[0].getText(ast);+ }+ ts.forEachChild(node, visit);+ }+ visit(ast);+ if (!callback) throw new Error('Plan edit callback missing');+ const compiled = ts.transpileModule(`return (${callback});`, {+ compilerOptions: { target: ts.ScriptTarget.ES2022 },+ }).outputText;+ return new Function('sessionId', 'makerChatStore', 'isRemoteSessionSticky', 'planWriteTimerRef', 'log', compiled)(+ sessionId, makerChatStore, isRemoteSessionSticky, { current: null }, { error: vi.fn() },+ ) as (requestId: string, path: string, content: string) => void;+}const DEVICE_ID = 'dev-int-scn';let n = 0;const sid = () => `int-scn-${n++}`;@@ -230,6 +257,7 @@ beforeEach(() => {afterEach(() => {makerChatStore.__teardownGlobalListeners();+ resetRemoteDataOwnerPushFence();remoteProjectsStore.clear();delete (globalThis as { window?: unknown }).window;vi.clearAllMocks();@@ -314,6 +342,64 @@ describe('device-link 远程交互往返 — permission', () => {});describe('device-link 远程交互往返 — plan_review', () => {+ it('shared guest edits stay in memory and approval sends the edited plan to the host', async () => {+ const peer = sharedTaskHostPeer('plan-share', 'host');+ makerChatStore.__teardownGlobalListeners();+ host = makeFakeHost(peer);+ local = stubElectronApi(host);+ makerChatStore.initGlobalListeners();+ const s = sid();+ remoteProjectsStore.setDeviceSessions(peer, 'Host', [{ id: s } as Session]);+ bindSharedTaskPushOwner(peer, TEST_OWNER_STAMP.dataOwnerId);+ host.hostInteraction(s, { kind: 'plan_review', requestId: 'guest-plan', plan: 'Original', planFilePath: '/host/plan.md' });+ await flush();+ const write = vi.fn(async () => ({ success: true }));+ window.electronAPI.maker.writePlanFile = write;+ vi.useFakeTimers();+ try {+ const edit = planEditor(s);+ edit('guest-plan', '/host/plan.md', 'Edited');+ // A reconnect clears the mirror but must not turn a host path local.+ remoteProjectsStore.clear();+ edit('guest-plan', '/host/plan.md', 'Final draft');+ await vi.advanceTimersByTimeAsync(600);+ expect(write).not.toHaveBeenCalled();+ expect(makerChatStore.getSnapshot(s).pendingPlanReview?.plan).toBe('Final draft');+ } finally {+ vi.useRealTimers();+ }+ remoteProjectsStore.setDeviceSessions(peer, 'Host', [{ id: s } as Session]);+ makerChatStore.respondToPlanReview(s, 'guest-plan', true);+ await flush();+ expect(host.resolved).toEqual([{ requestId: 'guest-plan', decision: {+ kind: 'plan_review', behavior: 'allow', editedPlan: 'Final draft',+ } }]);+ expect(local.localResolveInteraction).not.toHaveBeenCalled();+ });++ it.each([false, true])('local autosave respects remote origin discovered during debounce: %s', async (becomesRemote) => {+ const s = sid();+ const write = vi.fn(async () => ({ success: true }));+ window.electronAPI.maker.writePlanFile = write;+ vi.useFakeTimers();+ try {+ const edit = planEditor(s);+ edit('local-plan', '/local/plan.md', 'First draft');+ edit('local-plan', '/local/plan.md', 'Final draft');+ if (becomesRemote) {+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Host', [{ id: s } as Session]);+ }+ await vi.advanceTimersByTimeAsync(600);+ if (becomesRemote) expect(write).not.toHaveBeenCalled();+ else {+ expect(write).toHaveBeenCalledTimes(1);+ expect(write).toHaveBeenCalledWith({ requestId: 'local-plan', planFilePath: '/local/plan.md', content: 'Final draft' });+ }+ } finally {+ vi.useRealTimers();+ }+ });+it('plan approve → behavior=allow + editedPlan(用户当前 plan)', async () => {const s = openRemoteSession();host.hostInteraction(diff --git a/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeTestCard.test.tsx b/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeTestCard.test.tsxindex c58b9806aa..0ec0785823 100644--- a/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeTestCard.test.tsx+++ b/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeTestCard.test.tsx@@ -611,6 +611,8 @@ describe('completion card in the input area', () => {await waitFor(() => expect(h.api).toHaveBeenCalledWith('session', 'completion', 'build'));});it('uses the single personal version from an old completion instead of switching to its historical build', async () => {+ let releaseVersions!: () => void;+ const versionsReady = new Promise<void>((resolve) => { releaseVersions = resolve; });h.merge = {id: 'source-update',status: 'conflict',@@ -626,11 +628,14 @@ describe('completion card in the input area', () => {});vi.stubGlobal('electronAPI', {cindyMakeTest: h.api,- getCindyVersions: vi.fn().mockResolvedValue({- currentId: 'original',- selectedId: 'original',- versions: [{ id: 'personal', kind: 'personal', available: true, compatible: true }],- switching: false,+ getCindyVersions: vi.fn(async () => {+ await versionsReady;+ return {+ currentId: 'original',+ selectedId: 'original',+ versions: [{ id: 'personal', kind: 'personal', available: true, compatible: true }],+ switching: false,+ };}),actCindyVersion: switchVersion,});@@ -645,9 +650,14 @@ describe('completion card in the input area', () => {}}/>,);- fireEvent.click(- await screen.findByRole('button', { name: 'cindyMake.versions.switchPersonal' }),- );+ const switchPersonal = await screen.findByRole('button', { name: 'cindyMake.versions.switchPersonal' });+ // The label is visible before the asynchronous version list enables it.+ expect((switchPersonal as HTMLButtonElement).disabled).toBe(true);+ fireEvent.click(switchPersonal);+ expect(switchVersion).not.toHaveBeenCalled();+ await act(async () => { releaseVersions(); });+ await waitFor(() => expect((switchPersonal as HTMLButtonElement).disabled).toBe(false));+ fireEvent.click(switchPersonal);await waitFor(() => expect(switchVersion).toHaveBeenCalledWith('switch', 'personal'));expect(h.api.mock.calls.some(([, , action]) => action === 'open-build')).toBe(false);});diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsxindex 031c9aa851..ce77d84b91 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx@@ -5352,13 +5352,12 @@ export function CCAgentSessionView({</div>}>- {isSharedTaskPeer(remoteDeviceId ?? '') ? (- (pendingPlanReview || pendingPermission || pendingAskUser || pendingPluginSetup || pendingIssueConfirm || pendingRenameSessionsConfirm || pendingGhostGrantConfirm) &&+ {isSharedTaskPeer(remoteDeviceId ?? '') &&+ !pendingPlanReview && !pendingPermission && !pendingAskUser &&+ (pendingPluginSetup || pendingIssueConfirm || pendingRenameSessionsConfirm || pendingGhostGrantConfirm || pendingRemoteDesktopConfirmation) ? (<div className="space-y-2 rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] p-4 text-[var(--text-primary)]"><p className="text-13 text-[var(--text-secondary)]">{t('sharedTask.waitingHost')}</p>- <pre className="max-h-64 overflow-auto whitespace-pre-wrap break-words text-13">{pendingPlanReview?.plan ?? (pendingPermission- ? [pendingPermission.title ?? pendingPermission.toolName, pendingPermission.description, JSON.stringify(pendingPermission.input, null, 2)].filter(Boolean).join('\n')- : JSON.stringify(pendingAskUser?.questions ?? pendingPluginSetup ?? pendingIssueConfirm ?? pendingRenameSessionsConfirm ?? pendingGhostGrantConfirm, null, 2))}</pre>+ <pre className="max-h-64 overflow-auto whitespace-pre-wrap break-words text-13">{JSON.stringify(pendingPluginSetup ?? pendingIssueConfirm ?? pendingRenameSessionsConfirm ?? pendingGhostGrantConfirm ?? pendingRemoteDesktopConfirmation, null, 2)}</pre></div>) : pendingPlanReview ? (<>diff --git a/apps/desktop/src/renderer/hooks/useCCAgentChat.ts b/apps/desktop/src/renderer/hooks/useCCAgentChat.tsindex 89a47f0d55..0e3441c862 100644--- a/apps/desktop/src/renderer/hooks/useCCAgentChat.ts+++ b/apps/desktop/src/renderer/hooks/useCCAgentChat.ts@@ -713,11 +713,15 @@ export function useCCAgentChat(// 2) Debounce the disk write — coalesce rapid keystrokes.if (planWriteTimerRef.current) clearTimeout(planWriteTimerRef.current);+ // Remote paths belong to the host. Keep the draft in memory and send it+ // back as editedPlan on approval; never autosave it on this client.+ if (isRemoteSessionSticky(sessionId)) return;// Skip the IPC entirely when there's no path (defensive — shouldn't// happen in practice; ExitPlanMode always carries planFilePath).if (!planFilePath) return;planWriteTimerRef.current = setTimeout(() => {planWriteTimerRef.current = null;+ if (isRemoteSessionSticky(sessionId)) return;window.electronAPI.maker.writePlanFile({ requestId, planFilePath, content }).then((result) => {diff --git a/apps/mobile/src/__tests__/InteractionPanelReceipt.test.tsx b/apps/mobile/src/__tests__/InteractionPanelReceipt.test.tsxindex 91309eb1f4..a874b6ff2b 100644--- a/apps/mobile/src/__tests__/InteractionPanelReceipt.test.tsx+++ b/apps/mobile/src/__tests__/InteractionPanelReceipt.test.tsx@@ -59,9 +59,9 @@ let root: Root;let host: HTMLDivElement;const requestId = 'codex:test:0';const onError = vi.fn();-function Harness({ companion = false }: { companion?: boolean }) {+function Harness({ companion = false, deviceId = 'd1' }: { companion?: boolean; deviceId?: string }) {const interactions = useSessionPendingInteractions('s1');- return <InteractionPanel companion={companion} deviceId="d1" sessionId="s1" interactions={interactions} onError={onError} />;+ return <InteractionPanel companion={companion} deviceId={deviceId} sessionId="s1" interactions={interactions} onError={onError} />;}beforeEach(() => {Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });@@ -88,6 +88,44 @@ async function type(id: string, value: string) {});}+it.each(['permission', 'ask_user_question', 'plan_review'])('lets a shared guest submit %s through its decision button', async (kind) => {+ remoteSessionStore.setPendingInteractions('s1', [{ request: {+ kind, requestId, toolName: 'Read', input: { path: '/tmp/test.txt' },+ questions: [{ question: 'Continue?', options: [{ label: 'Yes' }] }], plan: 'Read the file.',+ } }]);+ await act(async () => root.render(<Harness deviceId={sharedTaskHostPeer('shared', 'd1')} />));+ expect(host.querySelector('[data-testid="interaction.readOnlyCard"]')).toBeNull();+ resolveInteraction.mockResolvedValueOnce({ accepted: true });+ if (kind === 'ask_user_question') {+ await click('interaction.ask.option.1');+ await click('interaction.ask.submitButton');+ }+ else await click(kind === 'permission' ? 'interaction.permission.allowOnceButton' : 'interaction.plan.approveButton');+ expect(resolveInteraction).toHaveBeenCalledWith(requestId, expect.objectContaining(+ kind === 'ask_user_question' ? { kind, answers: { 'Continue?': 'Yes' } } : { kind, behavior: 'allow' },+ ));+});++it('submits the host-provided Codex session approval from the shared guest always-allow button', async () => {+ const suggestions = [{ type: 'codexSessionApproval', destination: 'session' }];+ remoteSessionStore.setPendingInteractions('s1', [{ request: {+ kind: 'permission', requestId, toolName: 'Shell', input: { command: 'git status' }, suggestions,+ } }]);+ await act(async () => root.render(<Harness deviceId={sharedTaskHostPeer('shared', 'd1')} />));+ resolveInteraction.mockResolvedValueOnce({ accepted: true });+ await click('interaction.permission.alwaysAllowButton');+ expect(resolveInteraction).toHaveBeenCalledExactlyOnceWith(requestId, {+ kind: 'permission', behavior: 'allow', permissionUpdates: suggestions,+ });+});++it.each(['plugin_setup', 'issue_confirm', 'ghost_grant_confirm', 'rename_sessions_confirm'])('keeps shared guest %s confirmation read-only', async (kind) => {+ remoteSessionStore.setPendingInteractions('s1', [{ request: { kind, requestId } }]);+ await act(async () => root.render(<Harness deviceId={sharedTaskHostPeer('shared', 'd1')} />));+ expect(host.querySelector('[data-testid="interaction.readOnlyCard"]')).not.toBeNull();+ expect(resolveInteraction).not.toHaveBeenCalled();+});+it('keeps multiple selections and the free answer when moving back, remounting, and retrying', async () => {remoteSessionStore.setPendingInteractions('s1', [{ request: {kind: 'ask_user_question', requestId, questions: [diff --git a/apps/mobile/src/__tests__/interactionModel.test.ts b/apps/mobile/src/__tests__/interactionModel.test.tsindex 292e91cad4..ecd06e3f19 100644--- a/apps/mobile/src/__tests__/interactionModel.test.ts+++ b/apps/mobile/src/__tests__/interactionModel.test.ts@@ -397,9 +397,10 @@ describe('interactionModel', () => {])).toBe(false);});- it('keeps shared-task guest pending interactions as a short desktop-style blocker', () => {+ it('keeps host-only shared-task confirmations as a short desktop-style blocker', () => {const interactionPanelSource = readFileSync(resolve(process.cwd(), 'src/session/InteractionPanel.tsx'), 'utf8');- const readOnlyStart = interactionPanelSource.indexOf('if (isSharedTaskPeer(deviceId)) {');+ const readOnlyStart = interactionPanelSource.indexOf("if (isSharedTaskPeer(deviceId) && !['permission', 'ask_user_question', 'plan_review'].includes(kind)) {");+ expect(readOnlyStart).toBeGreaterThan(-1);const readOnlyEnd = interactionPanelSource.indexOf('return (', interactionPanelSource.indexOf('}', readOnlyStart));const readOnlySource = interactionPanelSource.slice(readOnlyStart, readOnlyEnd);diff --git a/apps/mobile/src/session/InteractionPanel.tsx b/apps/mobile/src/session/InteractionPanel.tsxindex 97cc03f759..6916f16f6f 100644--- a/apps/mobile/src/session/InteractionPanel.tsx+++ b/apps/mobile/src/session/InteractionPanel.tsx@@ -251,7 +251,7 @@ function InteractionPanelContent({gap: touchLayout.cardGap,padding: touchLayout.cardPadding,};- if (isSharedTaskPeer(deviceId)) {+ if (isSharedTaskPeer(deviceId) && !['permission', 'ask_user_question', 'plan_review'].includes(kind)) {return (<View style={[styles.root, fillAvailableHeight && styles.rootFill, rootLayoutStyle]} testID="interaction.panel"><PendingTaskHeaderdiff --git a/apps/mobile/src/session/SharedTaskAdmissionDialog.tsx b/apps/mobile/src/session/SharedTaskAdmissionDialog.tsxindex ed9becc164..5c87ba8d94 100644--- a/apps/mobile/src/session/SharedTaskAdmissionDialog.tsx+++ b/apps/mobile/src/session/SharedTaskAdmissionDialog.tsx@@ -10,7 +10,9 @@ export function SharedTaskAdmissionDialog({ title, onClose, children }: {}) {const styles = useThemedStyles(makeStyles);return <Modal transparent visible animationType="fade" onRequestClose={onClose}>- <KeyboardAvoidingView style={styles.backdrop} behavior={Platform.OS === 'ios' ? 'padding' : 'height'}>+ {/* Android Modal already resizes for the IME. A second height adjustment+ creates a layout loop while the invitation input is focused. */}+ <KeyboardAvoidingView style={styles.backdrop} enabled={Platform.OS === 'ios'} behavior="padding"><View style={styles.card} accessibilityViewIsModal testID="sharedTask.admissionDialog"><ScrollView keyboardShouldPersistTaps="handled" contentContainerStyle={styles.content} bounces={false}><Text style={styles.title} accessibilityRole="header">{title}</Text>diff --git a/docs/product-rules/shared-task-mode.md b/docs/product-rules/shared-task-mode.mdindex 90c39a4789..ce26a3f923 100644--- a/docs/product-rules/shared-task-mode.md+++ b/docs/product-rules/shared-task-mode.md@@ -36,7 +36,7 @@- 任务由原桌面运行,模型费用沿用房主连接;同账号远控行为不变。- 访客可发消息、使用附件和语音输入、修改 Agent/模型/推理设置、停止 Agent。-- Agent 工具、shell、已有插件/MCP 沿用任务现有权限,Full Access 语义不变;已有需审批操作仍由房主处理。不添加访客专属沙箱、per-turn 权限或工具审批。邀请意味着房主信任访客使用该任务的 Agent 能力。+- Agent 工具、shell、已有插件/MCP 沿用任务现有权限,Full Access 语义不变;任务内 Agent 的 permission、ask_user_question、plan_review 交互由房主和协作者都可决策,其他房主管理确认仍由房主处理。不添加访客专属沙箱、per-turn 权限或工具审批。邀请意味着房主信任访客使用该任务的 Agent 能力。- 房主保留共享管理、归档/删除/导出/分支、权限模式、工作目录、插件/MCP 配置和后台/定时任务管理权限。- 访客通过客户端接口只能直接访问共享任务及其资源,不能调用全局凭证、其他任务或任意主机文件接口。Agent 原生工具不承诺工作目录硬隔离。- 消息按主机现有输入队列顺序处理,保留 clientId 幂等。访客仅编辑/撤回自己未处理消息,房主可处理全部未处理消息;直接更新内容,不显示“已编辑”。@@ -165,7 +165,7 @@- 房主与两个不同账号访客进入同一任务,访客加入无需审批,完整历史可读,多人发言进入同一 Agent。- 原同账号远控、正常任务权限、Full Access、串行队列和重复输入幂等不退化。-- 访客无法直接访问其他任务、伪造作者、改他人队列或响应房主审批。+- 访客无法直接访问其他任务、伪造作者、改他人队列或响应房主管理确认;任务内 Agent 的 permission、ask_user_question、plan_review 交互可由访客决策。- 退出/移除/停止共享/归档/登出立即阻断后续访问,旧邀请和迟到响应不复活权限。- 访客重启恢复、房主离线关闭、断线补发、附件上传下载、SSH 工作区、Desktop/Mobile 和旧版拒绝有相应验证。- 一个访客停止 ACK 时其他访客和房主控制端仍可工作。@@ -184,7 +184,7 @@启动参数、端点与端口以 [Desktop 开发规则](../dev-rules/desktop-development.md) 为准;包装脚本会停止当前 checkout 的旧开发实例,因此不要在同一个 checkout 连续执行两次来模拟双客户端。也可用 Desktop 房主加 Mobile 访客;手机端点必须是手机可达的测试服务地址。3. 房主打开已有任务,开启共享并复制邀请。访客从菜单加入,确认无需审批即可进入普通任务页,能够查看加入前的消息、工具结果和附件。4. 同时发送不同内容,确认两个客户端看到同一 Agent 输出及正确作者。Agent 忙时编辑或撤回自己的待发送消息;修改其他成员的待发送消息应失败。编辑带图片的消息,保留旧附件并增加新附件,确认发送后和重载后都可打开。-5. 分别验证切换 Agent、模型和推理设置、停止 Agent、普通权限与 Full Access。已有审批由房主处理,访客能查看请求并继续排队发消息。+5. 分别验证切换 Agent、模型和推理设置、停止 Agent、普通权限与 Full Access。任务内 Agent 弹出的 permission、ask_user_question、plan_review 交互由房主或访客选择后继续执行。6. 访客断网后重连,确认有效共享与历史恢复。房主断线后 60 秒内重连保留共享;持续离线超过宽限后共享关闭、旧邀请失效,上线后需重新开启。房主主动关闭或退出账号立即关闭共享。单个访客断线时,另一个访客及同账号远控继续工作。7. 验证移除、退出、停止共享、归档和登出。旧邀请不能恢复已退出或移除的身份,新邀请可以重新加入;未共享任务与主机全局设置不可经访客客户端访问。8. 验证本地工作区及 SSH 工作区的图片、音频、视频,检查 Light/Dark 和小屏。旧服务端或旧客户端应提示升级,不得退化成全设备控制。diff --git a/packages/device-link/src/__tests__/sharedTask.test.ts b/packages/device-link/src/__tests__/sharedTask.test.tsindex f4385afd86..1e1ddff625 100644--- a/packages/device-link/src/__tests__/sharedTask.test.ts+++ b/packages/device-link/src/__tests__/sharedTask.test.ts@@ -48,12 +48,12 @@ describe('sharedTask authorization', () => {}expect(isSharedTaskAttachment('file:///private/file.png', 'shared')).toBe(false);});- it.each(['history.read', 'attachment.read', 'attachment.upload', 'input.send', 'agent.configure', 'agent.stop'])(+ it.each(['history.read', 'attachment.read', 'attachment.upload', 'input.send', 'agent.configure', 'agent.stop', 'approval.resolve'])('lets an approved guest %s without treating them as the owner', (operation) => {expect(authorize(parse(snapshot()), guest, 'session-1', operation)).toMatchObject({ allowed: true, role: 'guest', memberId: 'member-a' });},);- it.each(['approval.resolve', 'permission.configure', 'workdir.configure', 'plugins.configure',+ it.each(['permission.configure', 'workdir.configure', 'plugins.configure','history.delete', 'session.archive', 'session.export', 'session.fork', 'background.create', 'schedule.create', 'sharedTask.manage'])('requires the owner for %s even when a guest can configure the model', (operation) => {expect(authorize(parse(snapshot()), guest, 'session-1', operation)).toEqual({ allowed: false, reason: 'owner-required' });diff --git a/packages/device-link/src/sharedTask.ts b/packages/device-link/src/sharedTask.tsindex 3546545c81..ba8248b1d8 100644--- a/packages/device-link/src/sharedTask.ts+++ b/packages/device-link/src/sharedTask.ts@@ -81,10 +81,10 @@ export type SharedTaskDecision =const sharedOperations: ReadonlySet<string> = new Set<SharedTaskOperation>(['history.read', 'events.subscribe', 'attachment.read', 'attachment.upload',- 'file.read', 'input.send', 'agent.stop', 'agent.configure',+ 'file.read', 'input.send', 'agent.stop', 'agent.configure', 'approval.resolve',]);const ownerOperations: ReadonlySet<string> = new Set<SharedTaskOperation>([- 'approval.resolve', 'permission.configure', 'workdir.configure', 'plugins.configure',+ 'permission.configure', 'workdir.configure', 'plugins.configure','history.delete', 'session.archive', 'session.export', 'session.fork','background.create', 'schedule.create', 'sharedTask.manage',]);