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): apply owner model selections on shared-task guest sends

DavidShenb52a00599921
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaRemoteModelWindowSelection.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaRemoteModelWindowSelection.test.ts
index 4d9c08fc14..9bba3581e2 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaRemoteModelWindowSelection.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaRemoteModelWindowSelection.test.ts
@@ -6,6 +6,8 @@ import { resolveVerifiedContextWindow } from '../../../shared/sessionContextWind
import { createContextOverflowRollover } from '../contextOverflowRollover';
import { applyPendingAgentSwitchIfIdle, createPendingAgentSwitchRegistry, projectPendingAgentSwitchIntent,
type MakerSessionAgentSwitchHandlerDeps, type PendingAgentSwitchIntent } from '../sessionAgentSwitchHandler';
+import { runDeviceLinkInvokeContext } from '../../device-link/invoke-context';
+import type { createSharedTaskPendingSelectionGuard } from '../sharedTaskSetting';
// Run the production remote-selection adapter, send boundary and window rollover
// together. Only device I/O, native processes and persistent writes are replaced.
@@ -40,10 +42,11 @@ function setup(agent: 'cc' | 'codex' | 'pi' = 'codex', role: string | null = 'wo
const rebuild = vi.fn();
const pending = createPendingAgentSwitchRegistry();
const log = { info: vi.fn(), warn: vi.fn(), debug: vi.fn() };
+ const drainPersistQueue = vi.fn(async () => {});
const rollover = createContextOverflowRollover({
getSessionRow: async () => ({ ...row, contextTokens: state.tokens, contextWindow: 1000000 }),
getLiveSession: () => live, rehydrateColdPiRuntimeForWindowVerification: async () => { live = runtime; },
- drainPersistQueue: async () => {}, closeSession: close, commitRebuild: rebuild,
+ drainPersistQueue, closeSession: close, commitRebuild: rebuild,
listMessages: async () => [{ role: 'user', content: 'history', clientId: 'u1', createdAt: 1 }],
findLatestRebuildMeta: async () => null, setPendingHandoff: vi.fn(),
replayUserMessage: async () => ({ accepted: true }),
@@ -76,10 +79,13 @@ function setup(agent: 'cc' | 'codex' | 'pi' = 'codex', role: string | null = 'wo
const assertRuntimeOwnerCurrent = vi.fn();
const selectSameAgentModel = compile(selectionAdapter, { throwIpcError,
applySessionRuntimeSelection: (sessionId: string, model: string, providerId: unknown,
- selection: { effort: string; fastMode: boolean; confirmedContextWindow?: number }, internalOptions: unknown) => applyRemote({
+ selection: { effort: string; fastMode: boolean; confirmedContextWindow?: number },
+ internalOptions: { pendingSelectionAccess?: ReturnType<typeof createSharedTaskPendingSelectionGuard> }) => applyRemote({
sessionId, model, providerId, atomicSelection: selection, internalOptions, runtimeStatus: row,
- confirmedContextWindow: selection.confirmedContextWindow, assertRuntimeOwnerCurrent,
- assertSharedTaskCurrent: { admit: vi.fn() }, supersededByOwnerBoundary: () => false,
+ confirmedContextWindow: selection.confirmedContextWindow,
+ assertRuntimeOwnerCurrent: () => { internalOptions.pendingSelectionAccess?.(); assertRuntimeOwnerCurrent(); },
+ assertSharedTaskCurrent: internalOptions.pendingSelectionAccess ?? { admit: vi.fn() },
+ supersededByOwnerBoundary: () => { internalOptions.pendingSelectionAccess?.(); return false; },
}),
});
const deps = { pendingSwitches: pending, getLiveSession: () => live, selectSameAgentModel, log } as unknown as MakerSessionAgentSwitchHandlerDeps;
@@ -91,7 +97,7 @@ function setup(agent: 'cc' | 'codex' | 'pi' = 'codex', role: string | null = 'wo
atomicSelection: { effort: 'high', fastMode: true }, internalOptions: { source: 'fallback' }, runtimeStatus: row,
assertRuntimeOwnerCurrent, assertSharedTaskCurrent: { admit: vi.fn() }, supersededByOwnerBoundary: () => false });
return { state, stage, fallback, accept, send: () => applyPendingAgentSwitchIfIdle(deps, 's1'),
- readProviders, pending, runtime, close, rebuild, persist, rollover, assertRuntimeOwnerCurrent };
+ readProviders, pending, runtime, close, rebuild, persist, rollover, drainPersistQueue, assertRuntimeOwnerCurrent };
}
describe('Orca remote-Agent window protection at send', () => {
@@ -210,6 +216,72 @@ describe('Orca remote-Agent window protection at send', () => {
});
});
+function guestContext() {
+ let current = true;
+ return {
+ context: { controllerDeviceId: 'guest-device', channel: 'maker:input:enqueue', sharedTask: {
+ author: { sharedTaskId: 'shared', sessionId: 's1', memberId: 'guest', accountId: 'guest', displayName: 'Guest' },
+ isCurrent: () => current,
+ authorize: (operation: string) => current && operation === 'input.send',
+ } },
+ revoke: () => { current = false; },
+ };
+}
+
+// #7825 review regression, unit: the production remote adapter must reject
+// revoked guest sends before setModel/close/persistence and retain the owner choice.
+// The local runtime preflight tests do not exercise either remote admission site.
+// Standalone: 12.29s (11.88s collecting the existing adapter/rollover dependency
+// graph, 149ms executing tests); no module resets, real I/O or timed waits added.
+describe('shared-task remote selection admission', () => {
+ it.each([
+ { role: null, rebuild: false },
+ { role: null, rebuild: true },
+ { role: 'worker', rebuild: false },
+ ])('rejects removal during remote model preflight (role=$role rebuild=$rebuild)', async ({ role, rebuild }) => {
+ const h = setup('codex', role);
+ const guest = guestContext();
+ await h.stage();
+ h.runtime.requiresModelSwitchRebuild.mockImplementationOnce(async () => {
+ guest.revoke();
+ return rebuild;
+ });
+ await expect(runDeviceLinkInvokeContext(guest.context, h.send)).rejects.toThrow('PERMISSION_DENIED');
+ expect(h.pending.get('s1')?.model).toBe('new');
+ expect(h.runtime.setModel).not.toHaveBeenCalled();
+ expect(h.close).not.toHaveBeenCalled();
+ expect(h.persist).not.toHaveBeenCalled();
+ await h.send();
+ expect(h.pending.get('s1')).toBeUndefined();
+ expect(h.persist).toHaveBeenCalledOnce();
+ });
+
+ it('retains a cold pending choice when membership is revoked during window verification', async () => {
+ const h = setup('codex', 'worker', true);
+ const guest = guestContext();
+ await h.stage();
+ h.drainPersistQueue.mockImplementationOnce(async () => { guest.revoke(); });
+ await expect(runDeviceLinkInvokeContext(guest.context, h.send)).rejects.toThrow('PERMISSION_DENIED');
+ expect(h.pending.get('s1')?.model).toBe('new');
+ expect(h.close).not.toHaveBeenCalled();
+ expect(h.rebuild).not.toHaveBeenCalled();
+ expect(h.persist).not.toHaveBeenCalled();
+ });
+
+ it('finishes an admitted window rebuild when membership is revoked during close', async () => {
+ const h = setup('cc', null);
+ const guest = guestContext();
+ await h.stage(200000);
+ h.state.tokens = 190000;
+ const close = h.close.getMockImplementation()!;
+ h.close.mockImplementationOnce(async () => { await close(); guest.revoke(); });
+ await runDeviceLinkInvokeContext(guest.context, h.send);
+ expect(h.rebuild).toHaveBeenCalledOnce();
+ expect(h.persist).toHaveBeenCalledWith('s1', expect.objectContaining({ model: 'new' }));
+ expect(h.pending.get('s1')).toBeUndefined();
+ });
+});
+
it('applies same-location fallback to the remote runtime and retains its execution location', async () => {
const h = setup('codex', null);
expect(await h.fallback()).toMatchObject({ deferred: false, superseded: false });
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts
index 95d8a0229f..991a8d0a4d 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts
@@ -16,8 +16,11 @@ import { createAgentHandoffPendingRegistry } from '../agentHandoff';
import { MAKER_INVOKE } from '../channels';
import { remoteAgentLinkError } from '../../remote-agent/controller/runClient';
import { IpcHarness } from './helpers/ipcHarness';
-import { runDeviceLinkInvokeContext } from '../../device-link/invoke-context';
+import { getDeviceLinkInvokeContext, runDeviceLinkInvokeContext } from '../../device-link/invoke-context';
import { applyScheduledModelSelection, type ScheduledModelSelection } from '../scheduledModelSelection';
+import { authorizeSharedTaskOperation } from '@cindy/device-link';
+import type { SharedTaskPeerCapture } from '../../device-link/sharedTaskDispatch';
+import { createSharedTaskSettingGuard } from '../sharedTaskSetting';
function makeRow(overrides: Partial<AgentSwitchSessionRow> = {}): AgentSwitchSessionRow {
return {
@@ -420,6 +423,83 @@ describe('same-engine selection at send', () => {
return { deps, pending, apply, calls, row: () => row };
}
+ // #7825, unit: exercise the production pending-apply entry with the real
+ // setting guard and permission policy. Existing cases test switching and
+ // guest denial separately; the missing input is an owner-staged choice whose
+ // first send runs inside a guest's async invoke context.
+ function sharedSelectionHarness(sessionId = 's1') {
+ const h = selectionHarness();
+ let current = true;
+ const capture: SharedTaskPeerCapture = {
+ author: { sharedTaskId: 'shared', sessionId, memberId: 'guest', accountId: 'guest', displayName: 'Guest' },
+ isCurrent: () => current,
+ authorize: (operation) => authorizeSharedTaskOperation({
+ sharedTaskId: 'shared', sessionId: 's1', ownerAccountId: 'owner', hostDeviceId: 'host',
+ status: 'active', revision: 1,
+ guests: current ? [{ memberId: 'guest', accountId: 'guest', version: 1, deviceIds: ['phone'] }] : [],
+ }, { accountId: 'guest', deviceId: 'phone' }, 's1', operation).allowed,
+ };
+ const context = { controllerDeviceId: 'phone', channel: 'maker:input:enqueue', sharedTask: capture,
+ sharedTaskSetting: { admitted: false } };
+ const preflight = vi.fn(async () => false);
+ const select = h.deps.selectSameAgentModel!;
+ h.deps.selectSameAgentModel = async (id, intent, applyNow, assertSelectionCurrent, beforeMutation, pendingSelectionAccess) => {
+ if (!applyNow) return select(id, intent, false);
+ const invoke = getDeviceLinkInvokeContext();
+ const guard = pendingSelectionAccess ?? createSharedTaskSettingGuard(invoke?.sharedTask, id, invoke?.sharedTaskSetting ?? { admitted: false });
+ assertSelectionCurrent?.();
+ guard();
+ await preflight();
+ await beforeMutation?.();
+ assertSelectionCurrent?.();
+ guard.admit();
+ return select(id, intent, true);
+ };
+ return { ...h, capture, context, preflight, revoke: () => { current = false; } };
+ }
+
+ it('applies the owner choice on the first guest send without granting the guest model access', async () => {
+ const h = sharedSelectionHarness();
+ await performSessionAgentSwitch(h.deps, { ...validParams, model: 'gpt-5.6-sol' });
+ await runDeviceLinkInvokeContext(h.context, async () => {
+ await applyPendingAgentSwitchIfIdle(h.deps, 's1');
+ expect(h.row().model).toBe('gpt-5.6-sol');
+ expect(h.pending.get('s1')).toBeUndefined();
+ // The next send still carries the guest author, and a subsequent settings
+ // request in the same invoke must not inherit the host transaction's admission.
+ expect(getDeviceLinkInvokeContext()).toBe(h.context);
+ expect(h.context.sharedTaskSetting.admitted).toBe(false);
+ const ipc = new IpcHarness();
+ registerMakerSessionAgentSwitchHandler(ipc, h.deps);
+ await expect(ipc.invoke(MAKER_INVOKE.SWITCH_SESSION_AGENT, 's1', 'codex', 'guest-model', null))
+ .rejects.toThrow('PERMISSION_DENIED');
+ expect(h.row().model).toBe('gpt-5.6-sol');
+ expect(h.pending.get('s1')).toBeUndefined();
+ });
+ expect(h.apply).toHaveBeenCalledOnce();
+ });
+
+ it.each(['revoked', 'other-task', 'during-preflight'] as const)(
+ 'keeps the owner choice pending when guest access fails (%s)', async (failure) => {
+ const h = sharedSelectionHarness(failure === 'other-task' ? 'other-task' : 's1');
+ await performSessionAgentSwitch(h.deps, { ...validParams, model: 'gpt-5.6-sol' });
+ if (failure === 'revoked') h.revoke();
+ if (failure === 'during-preflight') h.preflight.mockImplementationOnce(async () => {
+ h.revoke();
+ return false;
+ });
+ await expect(runDeviceLinkInvokeContext(h.context, () => applyPendingAgentSwitchIfIdle(h.deps, 's1')))
+ .rejects.toThrow('PERMISSION_DENIED');
+ expect(h.row().model).toBe('gpt-6-astra');
+ expect(h.apply).not.toHaveBeenCalled();
+ expect(h.pending.get('s1')?.model).toBe('gpt-5.6-sol');
+ // An invalid guest request must not discard the owner's pending choice.
+ await applyPendingAgentSwitchIfIdle(h.deps, 's1');
+ expect(h.row().model).toBe('gpt-5.6-sol');
+ expect(h.pending.get('s1')).toBeUndefined();
+ },
+ );
+
it('keeps the source thread untouched while selecting away and back, and applies only the final choice on send', async () => {
const h = selectionHarness();
for (const [model, providerId] of [['gpt-5.6-sol', 'xd'], ['gpt-6-astra', 'openai']]) {
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sharedTaskSetting.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sharedTaskSetting.test.ts
index 19cbb8588c..19a2439bb1 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/sharedTaskSetting.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sharedTaskSetting.test.ts
@@ -1,16 +1,19 @@
import { describe, expect, it, vi } from 'vitest';
import { authorizeSharedTaskOperation } from '@cindy/device-link';
-import { createSharedTaskSettingGuard } from '../sharedTaskSetting.js';
+import { createSharedTaskPendingSelectionGuard, createSharedTaskSettingGuard } from '../sharedTaskSetting.js';
import { applyRuntimeSetModelChange } from '../runtimeSetModel.js';
import { commitRuntimeAxisAfterPersistence } from '../runtimeSelectionAxes.js';
-function harness() {
+function harness(kind: 'setting' | 'pending' = 'setting') {
let current = true;
const transaction = { admitted: false };
- const guard = createSharedTaskSettingGuard({
+ const capture = {
author: { sharedTaskId: 'sharedTask', sessionId: 'task', memberId: 'guest', accountId: 'account', displayName: 'Guest' },
isCurrent: () => current, authorize: () => current,
- }, 'task', transaction);
+ };
+ const guard = kind === 'pending'
+ ? createSharedTaskPendingSelectionGuard(capture, 'task')
+ : createSharedTaskSettingGuard(capture, 'task', transaction);
return { guard, transaction, revoke() { current = false; } };
}
describe('sharedTask setting admission', () => {
@@ -39,8 +42,11 @@ describe('sharedTask setting admission', () => {
expect(closeSession).not.toHaveBeenCalled();
expect(session.model).toBe('host-model');
});
- it('rechecks membership after async model preflight, before any runtime change', async () => {
- const h = harness();
+ // #7825: the pending-choice fence must survive runtime preflight but must not
+ // prevent completion/rollback after mutation admission. These production
+ // runtime boundaries are distinct from the pending-apply/ALS tests.
+ it.each(['setting', 'pending'] as const)('rechecks %s membership after async model preflight, before any runtime change', async (kind) => {
+ const h = harness(kind);
const setModel = vi.fn();
const closeSession = vi.fn();
let resolve!: (value: boolean) => void;
@@ -56,8 +62,8 @@ describe('sharedTask setting admission', () => {
expect(setModel).not.toHaveBeenCalled();
expect(closeSession).not.toHaveBeenCalled();
});
- it('finishes persistence of an admitted native operation after removal', async () => {
- const h = harness();
+ it.each(['setting', 'pending'] as const)('finishes persistence of an admitted %s operation after removal', async (kind) => {
+ const h = harness(kind);
h.guard.admit();
h.revoke();
const commit = vi.fn();
@@ -66,8 +72,8 @@ describe('sharedTask setting admission', () => {
});
expect(commit).toHaveBeenCalledOnce();
});
- it('does not block recovery when persistence fails after an admitted operation', async () => {
- const h = harness();
+ it.each(['setting', 'pending'] as const)('does not block recovery when persistence fails after an admitted %s operation', async (kind) => {
+ const h = harness(kind);
h.guard.admit();
h.revoke();
const recover = vi.fn(async () => {});
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index b08e97688e..6d8b7f1168 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -11404,7 +11404,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
},
withCloseSuppressed: withRehydrateCloseSuppressed,
pendingSwitches: agentSwitchPending,
- selectSameAgentModel: async (sessionId, intent, applyNow, assertSelectionCurrent, beforeMutation) => {
+ selectSameAgentModel: async (sessionId, intent, applyNow, assertSelectionCurrent, beforeMutation, pendingSelectionAccess) => {
const result = await applySessionRuntimeSelection(sessionId, intent.model, intent.providerId, {
effort: (intent.effort ?? null) as SessionRuntimeProfile['effort'],
fastMode: intent.fastMode ?? false,
@@ -11414,7 +11414,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
...(intent.confirmedContextWindow ? { confirmedContextWindow: intent.confirmedContextWindow } : {}),
}, { source: 'user', sessionLockHeld: true, applyingUserSelectionOnSend: applyNow,
runtimeSource: intent.runtimeSource, configStaged: intent.configStaged === true,
- assertSelectionCurrent, beforeMutation });
+ assertSelectionCurrent, beforeMutation, pendingSelectionAccess });
if (result.contextWindowConfirmationRequired !== undefined) {
throwIpcError('PRECONDITION_FAILED', 'Model context window changed or was unknown; select the model again to confirm');
}
@@ -16606,6 +16606,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
type InternalRuntimeSelectionOptions = {
source: 'user' | SessionRuntimeMutationSource;
+ /** Host-owned pending choice triggered by a guest send; never supplied by IPC. */
+ pendingSelectionAccess?: ReturnType<typeof createSharedTaskSettingGuard>;
runtimeSource?: 'agent';
/** 系统配置对齐(IM 渠道默认跟随 / 伙伴模型对齐)登记: 落地时不打「脱离跟随」标记。 */
configStaged?: boolean;
@@ -22731,7 +22733,6 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (internalOptions.source !== 'user') return { deferred: false, superseded: true };
throwIpcError('PRECONDITION_FAILED', 'the agent is still working; change the model after this turn');
}
- assertSharedTaskCurrent.admit();
// 换到上下文更小的模型:与本机任务同一套保护——占用超过目标窗口的安全线时先把对话交接
// 成摘要、关掉当前会话,下一次发送按新模型重新开始。Orca 发送前重读目标窗口,
// 只有本机确认的具体窗口仍匹配时才允许重建,冷恢复也经过同一保护。
@@ -22763,7 +22764,6 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (orcaSelectionOnSend) {
if (supersededByOwnerBoundary()) return { deferred: false, superseded: true };
assertRuntimeOwnerCurrent();
- assertSharedTaskCurrent.admit();
}
rebuiltForWindow = prepared === 'rebuilt';
// Cold Pi verification can attach a runtime; use that handle for setModel.
@@ -22775,6 +22775,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const rebuild = await live.requiresModelSwitchRebuild?.(model, { providerId: targetProviderId }) ?? false;
if (internalOptions.beforeMutation) await internalOptions.beforeMutation();
assertRuntimeOwnerCurrent();
+ // Remote preflight may outlive guest membership. Admit only once the first
+ // mutation starts; a window rebuild admits earlier via assertCanCommit.
+ assertSharedTaskCurrent.admit();
if (rebuild) {
await withRehydrateCloseSuppressed(sessionId, () => maker.closeSession(sessionId, 'runtime-refresh'));
} else {
@@ -22785,6 +22788,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (atomicSelection) await live.setFastMode?.(targetFastMode);
}
}
+ // A cold runtime can reach persistence without setModel or a window rebuild.
+ assertRuntimeOwnerCurrent();
+ assertSharedTaskCurrent.admit();
setSessionProvider(sessionId, targetProviderId);
if (atomicSelection) {
setSessionEffort(sessionId, targetEffort);
@@ -22906,7 +22912,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
let atomicSelection = selection as
{ effort: SessionRuntimeProfile['effort']; fastMode: boolean | 'ultrafast'; thinking?: boolean } | undefined;
const runtimeOwnerEpoch = captureSessionRuntimeControlOwnerEpoch();
- const assertSharedTaskCurrent = captureSharedTaskSettingGuard(sessionId);
+ const assertSharedTaskCurrent = internalOptions.pendingSelectionAccess ?? captureSharedTaskSettingGuard(sessionId);
const assertRuntimeOwnerCurrent = (): void => {
assertSharedTaskCurrent();
internalOptions.assertSelectionCurrent?.();
diff --git a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts
index 6b0208bd68..2ea8296bd7 100644
--- a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts
+++ b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts
@@ -34,10 +34,10 @@
*/
import type { AgentKind } from '@cindy/maker-core';
-import { getDeviceLinkInvokeContext, isDeviceLinkInvoke } from '../device-link/invoke-context.js';
+import { getDeviceLinkInvokeContext, isDeviceLinkInvoke, runOutsideDeviceLinkInvokeContext } from '../device-link/invoke-context.js';
import { parseOrcaRemoteLead } from '../../shared/orcaRemoteWorker.js';
import { isProviderShareAgentDeviceId } from '../../shared/providerShare.js';
-import { createSharedTaskSettingGuard } from './sharedTaskSetting.js';
+import { createSharedTaskPendingSelectionGuard, createSharedTaskSettingGuard } from './sharedTaskSetting.js';
import { MAKER_INVOKE } from './channels.js';
import type { IpcHandlerRegistry } from './ipcHandlerRegistry.js';
@@ -219,6 +219,7 @@ export interface MakerSessionAgentSwitchHandlerDeps {
applyNow: boolean,
assertSelectionCurrent?: () => void,
beforeMutation?: () => Promise<void>,
+ pendingSelectionAccess?: ReturnType<typeof createSharedTaskPendingSelectionGuard>,
): Promise<{ deferred: boolean; superseded?: boolean }>;
/** 与 send / SET_MODEL 共用的 session 锁;生产注入,最小测试 harness 可省略。 */
withSessionLock?<T>(sessionId: string, task: () => Promise<T>): Promise<T>;
@@ -1515,7 +1516,18 @@ export function applyPendingAgentSwitchIfIdle(
try {
if (intent.sameAgentSelection) {
if (!deps.selectSameAgentModel) throw new Error('model selection apply is unavailable');
- const result = await deps.selectSameAgentModel(sessionId, intent, true);
+ const sharedTask = getDeviceLinkInvokeContext()?.sharedTask;
+ const access = sharedTask ? createSharedTaskPendingSelectionGuard(sharedTask, sessionId) : undefined;
+ access?.();
+ // #7825: the guest triggers a send, but the choice above came from the
+ // host registry. Apply only that choice under host authority; retain the
+ // captured send fence through preflight and admit before mutation. Keep
+ // this admission separate from the guest invoke's settings transaction.
+ const result = await (sharedTask
+ ? runOutsideDeviceLinkInvokeContext(() => deps.selectSameAgentModel!(
+ sessionId, intent, true, undefined, undefined, access,
+ ))
+ : deps.selectSameAgentModel(sessionId, intent, true));
if (result.deferred || result.superseded) {
throw new Error('model selection could not be applied before send');
}
diff --git a/apps/desktop/src/main/maker-ipc/sharedTaskSetting.ts b/apps/desktop/src/main/maker-ipc/sharedTaskSetting.ts
index 1ff86670c4..e287afedcf 100644
--- a/apps/desktop/src/main/maker-ipc/sharedTaskSetting.ts
+++ b/apps/desktop/src/main/maker-ipc/sharedTaskSetting.ts
@@ -6,10 +6,27 @@ export function createSharedTaskSettingGuard(
sharedTask: SharedTaskPeerCapture | undefined,
sessionId: string,
transaction: { admitted: boolean },
+) {
+ return createSharedTaskOperationGuard(sharedTask, sessionId, transaction, 'agent.configure');
+}
+
+/** Only for applying an existing host-owned choice, never a guest's setting payload. */
+export function createSharedTaskPendingSelectionGuard(
+ sharedTask: SharedTaskPeerCapture,
+ sessionId: string,
+) {
+ return createSharedTaskOperationGuard(sharedTask, sessionId, { admitted: false }, 'input.send');
+}
+
+function createSharedTaskOperationGuard(
+ sharedTask: SharedTaskPeerCapture | undefined,
+ sessionId: string,
+ transaction: { admitted: boolean },
+ operation: 'agent.configure' | 'input.send',
) {
const assertCurrent = () => {
if (!transaction.admitted && sharedTask && (sharedTask.author.sessionId !== sessionId ||
- !sharedTask.isCurrent() || !sharedTask.authorize('agent.configure'))) {
+ !sharedTask.isCurrent() || !sharedTask.authorize(operation))) {
throwIpcError('PERMISSION_DENIED', 'SharedTask task access denied');
}
};
diff --git a/docs/product-rules/shared-task-mode.md b/docs/product-rules/shared-task-mode.md
index 10dae8783c..97f0ee31c7 100644
--- a/docs/product-rules/shared-task-mode.md
+++ b/docs/product-rules/shared-task-mode.md
@@ -36,6 +36,7 @@
- 任务由原桌面运行,模型费用沿用房主连接;同账号远控行为不变。
- 访客可发消息、使用附件和语音输入、停止 Agent;Agent、模型和推理设置仅房主可修改(2026-10-10 用户裁决)。桌面与手机访客保留当前模型展示,但不可打开修改入口;房主端同时校验请求权限,旧版访客也不能绕过。
+- 房主登记的待生效模型选择可由访客的下一条消息触发生效(#7825):仅在应用主机登记的选择期间使用宿主身份,启动参数不取自访客;访客发送资格与任务归属在预检及变更准入时复核。变更已准入后允许完成提交或回滚,不能因撤权留下半次切换;后续消息仍保留访客来源,不能借该次准入修改模型。实现与回归见 `sessionAgentSwitchHandler.ts`、`sharedTaskSetting.ts` 及各自测试。
- Agent 工具、shell、已有插件/MCP 沿用任务现有权限,Full Access 语义不变;任务内 Agent 的 permission、ask_user_question、plan_review 交互由房主和协作者都可决策,其他房主管理确认仍由房主处理。不添加访客专属沙箱、per-turn 权限或工具审批。邀请意味着房主信任访客使用该任务的 Agent 能力。
- 房主保留共享管理、归档/删除/导出/分支、权限模式、工作目录、插件/MCP 配置和后台/定时任务管理权限。
- 访客通过客户端接口只能直接访问共享任务及其资源,不能调用全局凭证、其他任务或任意主机文件接口。Agent 原生工具不承诺工作目录硬隔离。